Skip to main content

moq_video/decode/
consumer.rs

1//! Subscribe to an encoded H.264, H.265, or AV1 track and emit decoded frames.
2
3use std::collections::VecDeque;
4use std::pin::Pin;
5use std::task::{Context, Poll};
6
7use hang::catalog::VideoConfig;
8use kio::clock::Instant;
9use moq_mux::container::Read as Encoded;
10
11use super::decoder::Config;
12use super::sink::Sink;
13use crate::Error;
14use crate::Frame;
15pub use moq_mux::container::Delay;
16
17/// One item of a [`Consumer`] read, in delivery order: a decoded picture, or a break
18/// between them.
19///
20/// The decoded counterpart of [`moq_mux::container::Read`], and the same shape
21/// `moq_audio::decode::Read` has, so a player handles loss and ends alike for
22/// every media type.
23#[non_exhaustive]
24pub enum Read {
25	/// A decoded picture.
26	Frame(Frame),
27	/// Media after what was already read was lost: a group was skipped or never arrived.
28	/// The decoder was drained first, so every picture from before the loss precedes it.
29	///
30	/// The span is an upper bound, and `timestamp` is in the scale of the media that follows.
31	#[non_exhaustive]
32	Gap {
33		/// The furthest presentation point already read.
34		timestamp: moq_net::Timestamp,
35		/// How long until the next picture resumes.
36		duration: std::time::Duration,
37	},
38	/// The publisher stopped its encoder: it paused, switched source, or finished.
39	///
40	/// The decoder was drained first, so the stopped encoder's last pictures precede it
41	/// rather than waiting for the next one. What follows comes from a fresh encoder.
42	#[non_exhaustive]
43	End {
44		/// Where the stopped encoder's media stops.
45		end: moq_net::Timestamp,
46	},
47}
48
49/// Where a consumer starts on a track that already holds groups.
50///
51/// A track keeps its groups for a while after they are read, so a decoder does
52/// not always open on an empty one: a player rebuilding its decoder subscribes
53/// while its predecessor still holds groups, and a rendition switched away from
54/// and back to stays warm on the origin for the track's idle linger (cached
55/// groups, not an upstream subscription). What to do with that
56/// backlog depends on the consumer, and the two answers are opposites, so it is
57/// asked rather than guessed.
58#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
59#[non_exhaustive]
60pub enum Start {
61	/// The oldest group the track still holds, decoding everything cached.
62	///
63	/// What a recorder, an export, or anything reading a complete track wants,
64	/// and the default because dropping media a caller has not asked to drop is
65	/// the worse mistake.
66	#[default]
67	Oldest,
68	/// The newest group, skipping whatever is already cached.
69	///
70	/// What a live player wants. Without it a rebuilt decoder walks the whole
71	/// backlog at decode speed before reaching live media, which a viewer sees
72	/// as playback jumping backwards and then sprinting to catch up. Opening
73	/// waits for the track's live edge, or its end.
74	Latest,
75}
76
77/// How a [`Consumer`] subscribes to its track, and the decoder it feeds.
78///
79/// The subscription half is what a bare [`Decoder`](super::Decoder) has no use
80/// for: where to start on a cached track, and how far to fall behind live
81/// before skipping. The decoder half is passed through as it is.
82///
83/// `#[non_exhaustive]`: build via [`Options::new`] (or `default()`) and set the
84/// fields, so future knobs don't break callers.
85#[derive(Clone, Debug)]
86#[non_exhaustive]
87pub struct Options {
88	/// The decoder: backend, output representation, scaling hint.
89	pub decoder: Config,
90	/// The subscription priority, ordering this track against the others on the session under
91	/// congestion: higher is sent first. Defaults to hang's `PRIORITY.video`;
92	/// [`Consumer::set_priority`] moves it while running.
93	pub priority: i8,
94	/// Where to start on a track that already holds groups.
95	pub start: Start,
96	/// How far behind the live edge playback runs. [`Delay::min`] is the
97	/// player's playout delay, where a [`Start::Latest`] join starts, and is not
98	/// stated for [`Start::Oldest`]; [`Delay::max`] is how far playback may drift
99	/// before a stalled group is skipped. The min defaults to unstated, which
100	/// [`Start::Latest`] joins as zero, and the max to zero: skip aggressively.
101	/// Set `min` to your playout delay and `max` at or past it for a softer skip.
102	/// The max is applied to the transport subscription, and both reach
103	/// [`moq_mux::container::Consumer`].
104	pub delay: Delay,
105}
106
107impl Default for Options {
108	fn default() -> Self {
109		Self {
110			decoder: Config::default(),
111			priority: hang::catalog::PRIORITY.video,
112			start: Start::default(),
113			delay: Delay::default(),
114		}
115	}
116}
117
118impl Options {
119	/// Defaults: a default [`Config`], hang's video priority, every cached group, real-time latency.
120	pub fn new() -> Self {
121		Self::default()
122	}
123}
124
125/// The delay a subscription for `options` states: a [`Start::Latest`] join holds the min, unstated
126/// as zero, and a [`Start::Oldest`] one states none.
127fn stated(options: &Options) -> Delay {
128	let mut delay = options.delay;
129	delay.min = match options.start {
130		Start::Oldest => None,
131		Start::Latest => delay.min.or(Some(std::time::Duration::ZERO)),
132	};
133	delay
134}
135
136/// Subscribe to a moq-mux video track and emit decoded frames.
137///
138/// The codec/backend are fixed at construction; [`read`](Self::read) returns
139/// [`Read`] events carrying pictures in the representation
140/// [`Config::output`](super::Config::output) asked for. The direct mirror of
141/// `moq_audio::decode::Consumer`.
142pub struct Consumer {
143	slot: Slot,
144	/// The subscription's preferences, reachable while a read holds the reader, until the track
145	/// ends: holding them past that would keep the publisher's demand the container released.
146	control: Option<moq_net::track::Control>,
147	name: String,
148	/// When the access unit behind the latest picture returned arrived.
149	arrival: Option<Instant>,
150	options: Options,
151	/// The publisher's max age, which bounds [`Consumer::max_delay`].
152	max_age: Option<std::time::Duration>,
153	/// A delay [`Consumer::set_max_delay`] moved while a read held the reader, shared with it so
154	/// the read applies it before it next waits on the track.
155	retune: kio::Lock<Option<Delay>>,
156}
157
158/// Access units a [`Reader`] remembers the arrival of while its decoder holds them.
159///
160/// An entry goes once the decoder returns its picture, or a picture fed after it
161/// at a later timestamp, so the queue holds only what the decoder has in flight:
162/// one entry without reordering, a few with B-frames. H.264 and H.265 hold at
163/// most 16 pictures, and this leaves room for a hardware pipeline beyond that.
164/// The cap bounds what a malformed stream strands, such as timestamps that run
165/// backwards within a group; the oldest go first.
166const ARRIVALS: usize = 32;
167
168/// The decoder, idle between reads or decoding.
169///
170/// A read in flight is kept across a cancelled [`Consumer::read`] and finished by
171/// the next one, since a cancelled [`Sink`] call poisons the sink.
172enum Slot {
173	Idle(Box<Reader>),
174	Busy(Step),
175}
176
177/// A [`Reader::read`] in flight, handing the reader back with its result.
178type Step = Pin<Box<dyn Future<Output = (Box<Reader>, Result<Option<Item>, Error>)> + Send>>;
179
180/// A read, with when the access unit behind a picture arrived.
181type Item = (Read, Option<Instant>);
182
183/// One subscription and the decoder it feeds.
184struct Reader {
185	/// A [`Sink`] rather than a bare `Decoder`: the read loop below is held
186	/// across `.await` by every caller (libmoq's spawned task, moq-transcode),
187	/// so the codec would otherwise migrate between executor workers and
188	/// unbalance the per-thread COM apartment the Windows backend opens.
189	decoder: Sink,
190	track: moq_mux::container::Consumer<moq_mux::catalog::hang::Wire>,
191	/// Pictures a single access unit or drain decoded to, and the boundary behind
192	/// them, that `read` hasn't returned yet. One AU yields one picture in the
193	/// low-delay path, but a backend may hand back more, so we buffer to keep
194	/// `read` one-item-per-call.
195	pending: VecDeque<Item>,
196	/// The presentation time, in microseconds, and arrival of each access unit
197	/// fed to the decoder that no picture has come back for, in decode order.
198	/// Keyed by timestamp, because a decoder may return pictures in presentation
199	/// or decode order. Microseconds, because a backend may hand a picture back
200	/// at another scale than its access unit's.
201	arrivals: VecDeque<(u128, Instant)>,
202	/// Whether the ended track's decoder has already been drained.
203	drained: bool,
204	/// Whether the container ended or failed, releasing its subscription. A codec error
205	/// leaves it reading, so a later read can still resume.
206	released: bool,
207	/// The first recovery group lacks the preceding GOP's references.
208	recover: bool,
209	leading_floor: Option<moq_net::Timestamp>,
210	/// A delay moved while this reader was held by a read, applied at the next poll of the track.
211	retune: kio::Lock<Option<Delay>>,
212}
213
214impl Consumer {
215	/// Subscribe to `name` in `broadcast`, decoding it per the catalog entry.
216	/// Errors if the rendition's codec is not supported by a native backend.
217	pub async fn new(
218		broadcast: &moq_net::broadcast::Consumer,
219		catalog: &VideoConfig,
220		name: impl Into<String>,
221		options: Options,
222	) -> Result<Self, Error> {
223		let (reader, control, max_age) = Reader::open(broadcast, catalog, &name.into(), &options).await?;
224		let retune = reader.retune.clone();
225		Ok(Self {
226			name: reader.decoder.name().to_owned(),
227			control: Some(control),
228			max_age,
229			slot: Slot::Idle(Box::new(reader)),
230			arrival: None,
231			options,
232			retune,
233		})
234	}
235
236	/// The decoder backend name in use, e.g. `"videotoolbox"` or `"openh264"`.
237	pub fn name(&self) -> &str {
238		&self.name
239	}
240
241	/// The options this consumer was built with, with any [`set_max_delay`](Self::set_max_delay)
242	/// applied.
243	pub fn options(&self) -> &Options {
244		&self.options
245	}
246
247	/// How far a group may fall behind the live edge before it is skipped: [`Delay::max`],
248	/// clamped to the track's max age.
249	pub fn max_delay(&self) -> std::time::Duration {
250		let max = self.options.delay.max.unwrap_or(std::time::Duration::MAX);
251		max.min(self.max_age.unwrap_or(std::time::Duration::MAX))
252	}
253
254	/// Move [`Delay::max`] mid-stream, updating the subscription in place.
255	///
256	/// A player whose playout delay moves calls this to keep the subscription reaching as far
257	/// behind it. A read cancelled mid-decode picks it up before it next waits on the track.
258	///
259	/// A history subscription, [`Start::Oldest`] with no [`Delay::max`], reads every group in
260	/// order and ignores it: the transport delivers nothing past a missing group, so there is no
261	/// budget to skip at.
262	pub fn set_max_delay(&mut self, max: std::time::Duration) {
263		if self.options.start == Start::Oldest && self.options.delay.max.is_none() {
264			return;
265		}
266		self.options.delay = self.options.delay.with_max(max);
267		let delay = stated(&self.options);
268		match &mut self.slot {
269			Slot::Idle(reader) => {
270				*self.retune.lock() = None;
271				reader.track.set_delay(delay);
272			}
273			Slot::Busy(_) => *self.retune.lock() = Some(delay),
274		}
275	}
276
277	/// Move the subscription priority mid-stream, updating the subscription in place
278	/// rather than resubscribing, so nothing already fetched is dropped or fetched again.
279	///
280	/// A read in flight is unaffected; an ended track ignores it.
281	pub fn set_priority(&mut self, priority: i8) {
282		let Some(control) = &self.control else {
283			return;
284		};
285		let mut subscription = control.subscription();
286		if subscription.ranges.iter().any(|range| range.priority != priority) {
287			for range in &mut subscription.ranges {
288				range.priority = priority;
289			}
290			// Closed only once the track ended, when there is nothing left to prioritize.
291			let _ = control.update(subscription);
292		}
293	}
294
295	/// When the access unit behind the latest picture [`read`](Self::read) returned
296	/// landed in this node's cache ([`moq_mux::container::Consumer::arrival`]).
297	///
298	/// Pair it with when the picture was read to tell network delay from decode
299	/// delay: it excludes the time the decoder held or reordered the picture.
300	/// A gap or an end leaves it unchanged, as `moq_audio::decode::Consumer::arrival`
301	/// does. `None` before the first picture, and for a picture that no access unit,
302	/// or more than one, matches by timestamp: one a backend returned at a timestamp
303	/// it was never handed, or a stream that repeats a timestamp while the decoder
304	/// holds both.
305	pub fn arrival(&self) -> Option<Instant> {
306		self.arrival
307	}
308
309	/// Read the next decoded picture or boundary, or `None` after the track ends and
310	/// the decoder's buffered tail has been drained.
311	///
312	/// Join and delivery-gap recovery trim leading pictures whose previous GOP is absent.
313	///
314	/// Cancel-safe: a decode in flight when the read is dropped is kept and
315	/// finished by the next read. A codec error fails the read.
316	pub async fn read(&mut self) -> Result<Option<Read>, Error> {
317		std::future::poll_fn(|cx| self.poll_read(cx)).await
318	}
319
320	fn poll_read(&mut self, cx: &mut Context<'_>) -> Poll<Result<Option<Read>, Error>> {
321		if matches!(self.slot, Slot::Idle(_)) {
322			// A pending placeholder holds the slot only while the reader moves into its step.
323			let Slot::Idle(mut reader) =
324				std::mem::replace(&mut self.slot, Slot::Busy(Box::pin(std::future::pending())))
325			else {
326				unreachable!("matched above");
327			};
328			self.slot = Slot::Busy(Box::pin(async move {
329				let result = reader.read().await;
330				(reader, result)
331			}));
332		}
333		let Slot::Busy(step) = &mut self.slot else {
334			unreachable!("started above");
335		};
336		let Poll::Ready((reader, result)) = step.as_mut().poll(cx) else {
337			return Poll::Pending;
338		};
339		if reader.released {
340			self.control = None;
341		}
342		let mut reader = reader;
343		// A delay moved while the read was decoding, which then returned without polling the track.
344		if let Some(delay) = self.retune.lock().take() {
345			reader.track.set_delay(delay);
346		}
347		// Left idle after an error, so the next read asks it again and gets the same answer.
348		self.slot = Slot::Idle(reader);
349		let Some((read, arrival)) = result? else {
350			return Poll::Ready(Ok(None));
351		};
352		// A gap or an end leaves the arrival unchanged.
353		if let Read::Frame(_) = read {
354			self.arrival = arrival;
355		}
356		Poll::Ready(Ok(Some(read)))
357	}
358}
359
360#[cfg(test)]
361impl Consumer {
362	/// The next picture, skipping gaps and ends.
363	async fn next_frame(&mut self) -> Result<Option<Frame>, Error> {
364		loop {
365			match self.read().await? {
366				Some(Read::Frame(frame)) => return Ok(Some(frame)),
367				Some(Read::Gap { .. } | Read::End { .. }) => {}
368				None => return Ok(None),
369			}
370		}
371	}
372
373	/// The decoder between reads.
374	fn reader(&mut self) -> &mut Reader {
375		let Slot::Idle(reader) = &mut self.slot else {
376			panic!("the decoder is not idle");
377		};
378		reader
379	}
380}
381
382impl Reader {
383	/// Subscribe per `options`, starting at the live edge when the caller asked for
384	/// [`Start::Latest`].
385	async fn open(
386		broadcast: &moq_net::broadcast::Consumer,
387		catalog: &VideoConfig,
388		name: &str,
389		options: &Options,
390	) -> Result<(Self, moq_net::track::Control, Option<std::time::Duration>), Error> {
391		let decoder = Sink::open(catalog, &options.decoder).await.map_err(|err| match err {
392			// Only a codec or description this build cannot decode is a refusal of the
393			// rendition. Backend and worker faults keep their own variants.
394			Error::UnsupportedCodec(reason) => Error::UnsupportedConfig(reason),
395			err => err,
396		})?;
397
398		// A decoder often opens on a track that is already cached: a replacement decoder
399		// subscribes while its predecessor still holds groups, and a rendition switched away from
400		// and back to stays warm on the origin for `moq_net::model::track::IDLE_LINGER` (cached
401		// groups, not an upstream subscription). A caller that asked for `Start::Latest` wants none
402		// of that backlog, which a cursor starting at the oldest group would replay at decode
403		// speed before reaching live media: on a thirty-second retention, half a minute of pictures
404		// raced through.
405		//
406		// A live join, the range a stated min delay places, starts that far behind each hop's live
407		// edge, never at what an ended feed left cached, so it names no stale group that would ask
408		// the publisher to rewind for everyone reading. A playout stating no minimum joins at the
409		// latest group. `Start::Oldest` states none, which reaches back as far as the max delay
410		// allows.
411		let playout = moq_mux::container::Playout::new(stated(options), std::time::Duration::ZERO);
412		let track = broadcast.track(hang::catalog::Reference::track(catalog, name))?;
413		// The whole delay from the first request, as the container keeps it, so the publisher
414		// never sees a stated zero min before the container's update.
415		let subscription = playout.subscription(
416			moq_net::track::Subscription::default()
417				.with_ranges([moq_net::track::Range::ALL.with_priority(options.priority)]),
418		);
419		let mut subscriber = track.subscribe(subscription).await?;
420		// The live edge is known only once the feed is live: a warm copy still waiting on its
421		// source reports nothing yet. Opening waits for it, or the track's end, as `Start::Latest`
422		// promises.
423		if options.start == Start::Latest {
424			subscriber.largest().await;
425		}
426		let control = subscriber.control();
427		let max_age = subscriber.info().max_age;
428		let track = subscriber;
429		// The catalog says how the track is framed, and it is not always the legacy
430		// wire: `moq import fmp4` publishes CMAF. Reading a moof+mdat fragment as a
431		// varint timestamp plus a payload decodes to garbage rather than failing.
432		let container = moq_mux::catalog::hang::Wire::try_from(catalog)?;
433		// On a cold network join the live edge's stream often lands first. The container starts
434		// at the group covering the live edge less the min delay, waiting for it.
435		let track = playout.consumer(track, container);
436
437		let reader = Self {
438			decoder,
439			track,
440			pending: VecDeque::new(),
441			arrivals: VecDeque::new(),
442			drained: false,
443			released: false,
444			recover: true,
445			leading_floor: None,
446			retune: kio::Lock::new(None),
447		};
448		Ok((reader, control, max_age))
449	}
450
451	/// The next item this decoder alone produces, with its access unit's arrival
452	/// for a picture; see [`Consumer::read`].
453	async fn read(&mut self) -> Result<Option<Item>, Error> {
454		loop {
455			if let Some(item) = self.pending.pop_front() {
456				return Ok(Some(item));
457			}
458			if self.drained {
459				return Ok(None);
460			}
461
462			let read = kio::wait(|waiter| {
463				if let Some(delay) = self.retune.lock().take() {
464					self.track.set_delay(delay);
465				}
466				self.track.poll_read(waiter)
467			})
468			.await;
469			self.released |= !matches!(read, Ok(Some(_)));
470			let mux_frame = match read? {
471				Some(Encoded::Frame { frame, .. }) => Some(frame),
472				// Drained so the pictures from before the boundary all come out ahead of it,
473				// rather than whenever the media after it pushes them through. The decoder
474				// stays usable and restarts on the next group's keyframe.
475				// The marker is consumed, so a failed drain still queues it and arms recovery
476				// before reporting, or the next read would never see it.
477				Some(Encoded::Gap { timestamp, duration }) => {
478					let drained = self.drain().await;
479					self.pending.push_back((Read::Gap { timestamp, duration }, None));
480					self.recover = true;
481					drained?;
482					continue;
483				}
484				// A fresh encoder has no preceding GOP to reference, so no recovery.
485				Some(Encoded::End { end, .. }) => {
486					let drained = self.drain().await;
487					self.pending.push_back((Read::End { end }, None));
488					drained?;
489					continue;
490				}
491				None => None,
492			};
493
494			let Some(mux_frame) = mux_frame else {
495				// The flag goes up only once the tail is in hand, so a read
496				// dropped before the drain ran retries it rather than reporting
497				// an end the stream has not reached. Flushing twice is safe: the
498				// second hands back nothing.
499				let drained = self.drain().await;
500				// Set before the error is returned, not after. A flush that
501				// failed once fails the same way every time, and the track has
502				// ended either way, so leaving the flag down turns one bad
503				// drain into a caller that reads, fails, and reads again with
504				// nothing in between to wait on. A caller that treats a codec
505				// error as one lost picture and carries on then spins.
506				self.drained = true;
507				drained?;
508				continue;
509			};
510
511			if mux_frame.keyframe {
512				self.leading_floor = self.recover.then_some(mux_frame.timestamp);
513				self.recover = false;
514			}
515			if self.leading_floor.is_some_and(|floor| mux_frame.timestamp < floor) {
516				continue;
517			}
518
519			let arrived = self.track.arrival();
520			// A frame with no time has no picture to match an arrival to.
521			let queued = arrived.zip(mux_frame.timestamp.as_micros().ok());
522			if let Some((arrived, micros)) = queued {
523				if self.arrivals.len() == ARRIVALS {
524					self.arrivals.pop_front();
525				}
526				self.arrivals.push_back((micros, arrived));
527			}
528			let decoded = self
529				.decoder
530				.decode(mux_frame.payload, mux_frame.timestamp, mux_frame.keyframe)
531				.await;
532			if decoded.is_err() && queued.is_some() {
533				// No picture will come back for a refused access unit, and left queued its
534				// arrival would be reported for a later one at the same timestamp.
535				self.arrivals.pop_back();
536			}
537			decoded?;
538			self.receive()?;
539		}
540	}
541
542	/// Queue every picture the decoder has ready, each with its access unit's arrival.
543	fn receive(&mut self) -> Result<(), Error> {
544		while let Some(picture) = self.decoder.receive()? {
545			// A frame with no time has no picture to match an arrival to.
546			let arrival = picture.timestamp.as_micros().ok().and_then(|at| {
547				// A timestamp queued twice is ambiguous: the picture may belong to either access
548				// unit, so it reports none rather than a guess.
549				let index = {
550					let mut matches = self
551						.arrivals
552						.iter()
553						.enumerate()
554						.filter(|(_, (timestamp, _))| *timestamp == at);
555					matches
556						.next()
557						.filter(|_| matches.next().is_none())
558						.map(|(index, _)| index)?
559				};
560				let (_, arrived) = self.arrivals.remove(index)?;
561				// An access unit fed before this one at an earlier time is a picture the
562				// decoder already returned or dropped, whichever order it returns them in.
563				let mut position = 0;
564				self.arrivals.retain(|(timestamp, _)| {
565					position += 1;
566					position > index || *timestamp > at
567				});
568				Some(arrived)
569			});
570			self.pending.push_back((Read::Frame(picture), arrival));
571		}
572		Ok(())
573	}
574
575	/// Queue every picture the decoder still holds. A flush that fails still
576	/// queues what it readied, so a later read hands those pictures over.
577	async fn drain(&mut self) -> Result<(), Error> {
578		let flushed = self.decoder.flush().await;
579		let received = self.receive();
580		// Whatever the flush did not return never comes back.
581		self.arrivals.clear();
582		flushed.and(received)
583	}
584}
585
586#[cfg(test)]
587mod tests {
588	#![cfg_attr(
589		not(feature = "openh264"),
590		allow(dead_code, unused_imports, reason = "only the `openh264` feature uses it")
591	)]
592
593	use bytes::Bytes;
594	use moq_net::Timestamp;
595
596	/// Build an origin producer, spawning its driver on the ambient runtime.
597	fn produce_origin() -> moq_net::origin::Producer {
598		let (producer, driver) = moq_net::origin::Producer::new(moq_net::origin::Config::default());
599		if tokio::runtime::Handle::try_current().is_ok() {
600			tokio::spawn(moq_net::time::run(driver));
601		} else {
602			// A sync test: nothing polls the driver, and dropping it would tear
603			// the origin down, so leak it and rely on the synchronous half.
604			std::mem::forget(driver);
605		}
606		producer
607	}
608	use super::*;
609	use crate::decode::Backend;
610	use crate::decode::backend::probe;
611	use crate::encode::{Backend as EncodeBackend, Config as EncodeConfig, Encoder, Publisher as EncodePublisher};
612	use moq_mux::container::Container as _;
613
614	#[tokio::test]
615	#[cfg(feature = "openh264")]
616	async fn reads_cmaf_container_declared_by_catalog() {
617		let mut source_broadcast = moq_net::broadcast::Info::new().produce();
618		let source_subscriber = source_broadcast.consume();
619		let source_catalog =
620			moq_mux::catalog::Producer::new(&mut source_broadcast, moq_mux::catalog::Config::default()).unwrap();
621		let config = EncodeConfig {
622			backend: EncodeBackend::Software,
623			..EncodeConfig::new(320, 240, crate::FrameRate::new(30, 1).unwrap())
624		};
625		let rendition = config.probe().await.unwrap();
626		let reserved = source_catalog.reserve().with_interval(config.effective_join());
627		let track = source_broadcast.unique_track(".avc3", reserved.track_info(hang::catalog::PRIORITY.video));
628		let mut producer = EncodePublisher::new(track, reserved, rendition).unwrap();
629		let mut encoder = Encoder::new(&config).unwrap();
630		let rgba = vec![0x80u8; 320 * 240 * 4];
631		for index in 0..2 {
632			encoder.cut().unwrap();
633			let surface = crate::Surface::rgba(&rgba, crate::Size::new(320, 240)).unwrap();
634			let frame = crate::Frame::new(moq_net::Timestamp::from_micros(index * 33_333).unwrap(), surface);
635			for encoded in encoder.encode_all(&frame).unwrap() {
636				producer.publish(&encoded).unwrap();
637			}
638		}
639
640		let origin = produce_origin();
641		let catalog = moq_mux::catalog::Consumer::<()>::new(&source_subscriber, moq_mux::catalog::CatalogFormat::Hang)
642			.await
643			.unwrap();
644		let source = moq_mux::Source::new(origin.consume(), source_subscriber.clone());
645		// Both frames are encoded before the export runs, so the exporter needs a budget
646		// wide enough to read them: its REAL_TIME default keeps only the live edge, and
647		// the second `next()` would then block forever waiting for a group that was
648		// skipped.
649		let mut export = moq_mux::container::fmp4::Export::new(source, catalog)
650			.with_delay(moq_mux::container::Delay::default().with_max(std::time::Duration::from_secs(30)));
651		let init = export.next().await.unwrap().expect("CMAF init");
652		let fragment = export.next().await.unwrap().expect("CMAF fragment");
653
654		let mut broadcast = moq_net::broadcast::Info::new().produce();
655		let subscriber = broadcast.consume();
656		let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
657		let mut import = moq_mux::container::fmp4::Import::new(broadcast, catalog.reserve()).with_cmaf(true);
658		import.decode(&init).unwrap();
659		import.decode(&fragment).unwrap();
660
661		let snapshot = catalog.snapshot();
662		let (name, config) = snapshot.video.renditions.iter().next().expect("video rendition");
663		assert!(matches!(config.container, hang::catalog::Container::Cmaf { .. }));
664		let mut consumer = Consumer::new(
665			&subscriber,
666			config,
667			name,
668			Options {
669				decoder: Config {
670					backend: Backend::Software,
671					..Config::new()
672				},
673				..Options::new()
674			},
675		)
676		.await
677		.unwrap();
678
679		let frame = consumer.next_frame().await.unwrap().expect("decoded frame");
680		assert_eq!(frame.size(), crate::Size::new(320, 240));
681	}
682
683	/// A decoder opened on a track that already holds groups starts at the
684	/// newest one, not at the oldest still cached.
685	///
686	/// A player rebuilding its decoder (a backend change, a rendition pin) opens
687	/// a second consumer while the first still holds the groups it has not
688	/// released. Starting those at sequence zero replays the whole retention at
689	/// decode speed before the picture reaches live media.
690	#[tokio::test]
691	async fn a_second_consumer_starts_at_the_live_edge() {
692		let broadcast = moq_net::broadcast::Info::new().produce();
693		let track = broadcast
694			.create_track("video", hang::container::track_info(hang::catalog::PRIORITY.video))
695			.unwrap();
696		// Kept so the aggregated subscription can be read back below.
697		let published = track.clone();
698		let subscriber = broadcast.consume();
699		let mut producer = moq_mux::container::Producer::new(
700			track,
701			moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Data),
702		);
703		// A keyframe opens a group, so this is three groups a second apart.
704		for index in 0..3u64 {
705			producer
706				.write(moq_mux::container::Frame {
707					timestamp: Timestamp::from_micros(index * 1_000_000).unwrap(),
708					decode: None,
709					duration: None,
710					payload: Bytes::from_static(b"access unit"),
711					keyframe: true,
712				})
713				.unwrap();
714		}
715		let _finished = producer.finish().unwrap();
716
717		let catalog = VideoConfig::new(hang::catalog::H264 {
718			inline: true,
719			profile: 0x42,
720			constraints: 0,
721			level: 30,
722		});
723		let mut consumer = Consumer::new(
724			&subscriber,
725			&catalog,
726			"video",
727			Options {
728				decoder: Config {
729					backend: Backend::Named(probe::BUFFERED_NAME.into()),
730					..Config::new()
731				},
732				start: Start::Latest,
733				// Wide enough to keep every group fresh: the age budget on its own
734				// delivers only the live edge, which would pass this test without
735				// `Start::Latest` doing anything.
736				delay: Delay {
737					max: Some(std::time::Duration::from_secs(10)),
738					..Delay::default()
739				},
740				..Options::new()
741			},
742		)
743		.await
744		.unwrap();
745
746		// The buffered probe stamps each picture with the access unit's own
747		// timestamp, so this says which group the read started from. It is the
748		// backend to use here rather than the plain probe, whose event log is
749		// process-wide and belongs to the thread-affinity test.
750		let frame = consumer.next_frame().await.unwrap().expect("a decoded frame");
751		assert_eq!(
752			frame.timestamp,
753			Timestamp::from_micros(2_000_000).unwrap(),
754			"a fresh consumer replayed the groups an earlier reader still holds",
755		);
756
757		// The skip names no cached group. The ranges are aggregated across every live
758		// subscriber and tell the publisher what to send, so a start at a cached group would
759		// rewind the track for everyone reading it. A rendition switched away from and back to
760		// is the case that bites, because its cached groups are stale by then and the publisher
761		// resends the broadcast from them. The live join starts from each hop's live edge.
762		assert_eq!(
763			published.subscription().map(|sub| sub.ranges),
764			Some(vec![
765				moq_net::track::Range::from(moq_net::track::Start::Live {
766					min: Some(std::time::Duration::ZERO),
767					max: Some(std::time::Duration::from_secs(10)),
768				})
769				.with_priority(hang::catalog::PRIORITY.video)
770			]),
771			"the publisher was asked to rewind the track",
772		);
773	}
774
775	/// The default reads everything the track holds.
776	///
777	/// `Start::Latest` is a player's policy and not the API's: a recorder, an
778	/// export, or a test decoding a track that was written before it subscribed
779	/// wants every group, and dropping media nobody asked to drop is the worse
780	/// of the two mistakes. This is the half that a live-edge default breaks,
781	/// so it is pinned beside the other one.
782	#[tokio::test]
783	async fn the_default_reads_every_cached_group() {
784		let broadcast = moq_net::broadcast::Info::new().produce();
785		let track = broadcast
786			.create_track("video", hang::container::track_info(hang::catalog::PRIORITY.video))
787			.unwrap();
788		let subscriber = broadcast.consume();
789		let mut producer = moq_mux::container::Producer::new(
790			track,
791			moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Data),
792		);
793		for index in 0..3u64 {
794			producer
795				.write(moq_mux::container::Frame {
796					timestamp: Timestamp::from_micros(index * 1_000_000).unwrap(),
797					decode: None,
798					duration: None,
799					payload: Bytes::from_static(b"access unit"),
800					keyframe: true,
801				})
802				.unwrap();
803		}
804		let _finished = producer.finish().unwrap();
805
806		let catalog = VideoConfig::new(hang::catalog::H264 {
807			inline: true,
808			profile: 0x42,
809			constraints: 0,
810			level: 30,
811		});
812		let mut consumer = Consumer::new(
813			&subscriber,
814			&catalog,
815			"video",
816			Options {
817				decoder: Config {
818					// The buffered probe rather than the plain one: the plain probe's
819					// event log is process-wide and belongs to the thread-affinity test.
820					backend: Backend::Named(probe::BUFFERED_NAME.into()),
821					..Config::new()
822				},
823				// A budget that keeps every group fresh, so the start policy is the
824				// only thing deciding what is read.
825				delay: Delay {
826					max: Some(std::time::Duration::from_secs(10)),
827					..Delay::default()
828				},
829				..Options::new()
830			},
831		)
832		.await
833		.unwrap();
834
835		let mut seen = Vec::new();
836		while let Some(frame) = consumer.next_frame().await.unwrap() {
837			seen.push(frame.timestamp);
838		}
839		assert_eq!(
840			seen,
841			vec![
842				Timestamp::from_micros(0).unwrap(),
843				Timestamp::from_micros(1_000_000).unwrap(),
844				Timestamp::from_micros(2_000_000).unwrap(),
845			],
846			"the default dropped groups the caller never asked to drop",
847		);
848	}
849
850	/// The priority reaches the publisher's aggregate subscription at hang's video default, and a
851	/// change while a read waits moves that subscription in place: the waiting read still gets
852	/// the next picture.
853	#[tokio::test]
854	async fn priority_reaches_the_subscription_and_moves_in_place() {
855		let broadcast = moq_net::broadcast::Info::new().produce();
856		let track = broadcast
857			.create_track("video", hang::container::track_info(hang::catalog::PRIORITY.video))
858			.unwrap();
859		let published = track.clone();
860		let subscriber = broadcast.consume();
861		let mut producer = moq_mux::container::Producer::new(
862			track,
863			moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Data),
864		);
865		let catalog = VideoConfig::new(hang::catalog::H264 {
866			inline: true,
867			profile: 0x42,
868			constraints: 0,
869			level: 30,
870		});
871		let options = Options {
872			decoder: Config {
873				backend: Backend::Named(probe::BUFFERED_NAME.into()),
874				..Config::new()
875			},
876			..Options::new()
877		};
878		let mut consumer = Consumer::new(&subscriber, &catalog, "video", options).await.unwrap();
879		assert_eq!(
880			published.subscription().map(|sub| sub.ranges[0].priority),
881			Some(hang::catalog::PRIORITY.video)
882		);
883
884		consumer.set_priority(10);
885		assert_eq!(published.subscription().map(|sub| sub.ranges[0].priority), Some(10));
886
887		// Park a read on the empty track, so the reader is held by the read in flight.
888		{
889			let read = consumer.read();
890			tokio::pin!(read);
891			assert!(futures::poll!(read.as_mut()).is_pending());
892		}
893		consumer.set_priority(-20);
894		assert_eq!(published.subscription().map(|sub| sub.ranges[0].priority), Some(-20));
895
896		producer
897			.write(moq_mux::container::Frame {
898				timestamp: Timestamp::from_micros(0).unwrap(),
899				decode: None,
900				duration: None,
901				payload: Bytes::from_static(b"access unit"),
902				keyframe: true,
903			})
904			.unwrap();
905		let _finished = producer.finish().unwrap();
906		let frame = consumer
907			.next_frame()
908			.await
909			.unwrap()
910			.expect("the waiting read's picture");
911		assert_eq!(frame.timestamp, Timestamp::from_micros(0).unwrap());
912	}
913
914	/// A moved max delay reaches the subscription, clamped to the max age, and one moved while a
915	/// cancelled read holds the reader reaches it on the next read, before that read waits.
916	#[tokio::test]
917	async fn a_moved_max_delay_reaches_the_subscription() {
918		let broadcast = moq_net::broadcast::Info::new().produce();
919		let track = broadcast
920			.create_track(
921				"video",
922				hang::container::track_info(hang::catalog::PRIORITY.video)
923					.with_max_age(std::time::Duration::from_secs(5)),
924			)
925			.unwrap();
926		let published = track.clone();
927		let mut producer = moq_mux::container::Producer::new(
928			track,
929			moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Data),
930		);
931		let catalog = VideoConfig::new(hang::catalog::H264 {
932			inline: true,
933			profile: 0x42,
934			constraints: 0,
935			level: 30,
936		});
937		let options = Options {
938			decoder: Config {
939				backend: Backend::Named(probe::BUFFERED_NAME.into()),
940				..Config::new()
941			},
942			delay: Delay {
943				max: Some(std::time::Duration::from_millis(500)),
944				..Delay::default()
945			},
946			..Options::new()
947		};
948		let mut consumer = Consumer::new(&broadcast.consume(), &catalog, "video", options)
949			.await
950			.unwrap();
951		let live_max = || match published.subscription().unwrap().ranges[..] {
952			[
953				moq_net::track::Range {
954					start: moq_net::track::Start::Live { max, .. },
955					..
956				},
957			] => max,
958			ref ranges => panic!("expected one live join, got {ranges:?}"),
959		};
960		assert_eq!(consumer.max_delay(), std::time::Duration::from_millis(500));
961
962		consumer.set_max_delay(std::time::Duration::from_secs(2));
963		assert_eq!(consumer.max_delay(), std::time::Duration::from_secs(2));
964		assert_eq!(consumer.options().delay.max, Some(std::time::Duration::from_secs(2)));
965		assert_eq!(live_max(), Some(std::time::Duration::from_secs(2)));
966
967		consumer.set_max_delay(std::time::Duration::from_secs(9));
968		assert_eq!(
969			consumer.max_delay(),
970			std::time::Duration::from_secs(5),
971			"past the max age"
972		);
973
974		// Park a read on the empty track, so the reader is held by the read in flight.
975		{
976			let read = consumer.read();
977			tokio::pin!(read);
978			assert!(futures::poll!(read.as_mut()).is_pending());
979		}
980		consumer.set_max_delay(std::time::Duration::from_secs(3));
981		{
982			let read = consumer.read();
983			tokio::pin!(read);
984			assert!(futures::poll!(read.as_mut()).is_pending());
985		}
986		assert_eq!(
987			live_max(),
988			Some(std::time::Duration::from_secs(3)),
989			"the next read retunes before it waits"
990		);
991
992		producer
993			.write(moq_mux::container::Frame {
994				timestamp: Timestamp::from_micros(0).unwrap(),
995				decode: None,
996				duration: None,
997				payload: Bytes::from_static(b"access unit"),
998				keyframe: true,
999			})
1000			.unwrap();
1001		let _finished = producer.finish().unwrap();
1002		consumer
1003			.next_frame()
1004			.await
1005			.unwrap()
1006			.expect("the waiting read's picture");
1007	}
1008
1009	/// A history subscription reads every group in order, so a moved max delay leaves it, and the
1010	/// budget it reports, as they were.
1011	#[tokio::test]
1012	async fn a_history_subscription_ignores_a_moved_max_delay() {
1013		let broadcast = moq_net::broadcast::Info::new().produce();
1014		let published = broadcast
1015			.create_track("video", hang::container::track_info(hang::catalog::PRIORITY.video))
1016			.unwrap();
1017		let catalog = VideoConfig::new(hang::catalog::H264 {
1018			inline: true,
1019			profile: 0x42,
1020			constraints: 0,
1021			level: 30,
1022		});
1023		let options = Options {
1024			decoder: Config {
1025				backend: Backend::Named(probe::BUFFERED_NAME.into()),
1026				..Config::new()
1027			},
1028			start: Start::Oldest,
1029			delay: Delay {
1030				max: None,
1031				..Delay::default()
1032			},
1033			..Options::new()
1034		};
1035		let mut consumer = Consumer::new(&broadcast.consume(), &catalog, "video", options)
1036			.await
1037			.unwrap();
1038		let before = published.subscription().unwrap();
1039		let budget = consumer.max_delay();
1040		consumer.set_max_delay(std::time::Duration::ZERO);
1041		assert_eq!(consumer.options().delay.max, None);
1042		assert_eq!(consumer.max_delay(), budget);
1043		assert_eq!(published.subscription().unwrap(), before);
1044	}
1045
1046	/// A read the container's error ends lets go of the subscription, so the handle kept for
1047	/// priority changes pins no demand on the publisher once nothing more is read.
1048	#[tokio::test]
1049	async fn an_ended_read_releases_the_subscription() {
1050		let broadcast = moq_net::broadcast::Info::new().produce();
1051		let track = broadcast
1052			.create_track("video", hang::container::track_info(hang::catalog::PRIORITY.video))
1053			.unwrap();
1054		let subscriber = broadcast.consume();
1055		let catalog = VideoConfig::new(hang::catalog::H264 {
1056			inline: true,
1057			profile: 0x42,
1058			constraints: 0,
1059			level: 30,
1060		});
1061		let options = Options {
1062			decoder: Config {
1063				backend: Backend::Named(probe::BUFFERED_NAME.into()),
1064				..Config::new()
1065			},
1066			..Options::new()
1067		};
1068		let mut consumer = Consumer::new(&subscriber, &catalog, "video", options).await.unwrap();
1069		assert!(track.subscription().is_some());
1070
1071		// A truncated varint where the legacy frame's timestamp belongs.
1072		let group = track
1073			.create_group(moq_net::frame::Frame::new(
1074				Timestamp::from_micros(0).unwrap(),
1075				Bytes::from_static(&[0xFF]),
1076			))
1077			.unwrap();
1078		let _group = group.finish().unwrap();
1079
1080		assert!(consumer.read().await.is_err(), "the malformed frame decoded");
1081		assert!(track.subscription().is_none(), "the ended consumer still subscribes");
1082	}
1083
1084	/// The age budget is the subscription's and not the decoder's: it reaches
1085	/// the publisher through the track subscription, while the decoder opens
1086	/// with exactly the config it was handed.
1087	///
1088	/// Driven by `pollster` rather than tokio: the probe's guard is a plain
1089	/// mutex, and holding one across an `.await` is what clippy rightly flags.
1090	#[test]
1091	fn max_delay_reaches_the_subscription_and_not_the_decoder() {
1092		let _probe = probe::native_exclusive();
1093		let broadcast = moq_net::broadcast::Info::new().produce();
1094		let track = broadcast
1095			.create_track("video", hang::container::track_info(hang::catalog::PRIORITY.video))
1096			.unwrap();
1097		let published = track.clone();
1098		let subscriber = broadcast.consume();
1099		let mut producer = moq_mux::container::Producer::new(
1100			track,
1101			moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Data),
1102		);
1103		producer
1104			.write(moq_mux::container::Frame {
1105				timestamp: Timestamp::from_micros(0).unwrap(),
1106				decode: None,
1107				duration: None,
1108				payload: Bytes::from_static(b"access unit"),
1109				keyframe: true,
1110			})
1111			.unwrap();
1112		let _finished = producer.finish().unwrap();
1113
1114		let catalog = VideoConfig::new(hang::catalog::H264 {
1115			inline: true,
1116			profile: 0x42,
1117			constraints: 0,
1118			level: 30,
1119		});
1120		let decoder = Config {
1121			backend: Backend::Named(probe::NATIVE_NAME.into()),
1122			output: crate::Output::Cpu,
1123			scale_hint: Some(crate::Size::new(160, 120)),
1124			..Default::default()
1125		};
1126		let max_delay = std::time::Duration::from_secs(10);
1127		let mut consumer = pollster::block_on(Consumer::new(
1128			&subscriber,
1129			&catalog,
1130			"video",
1131			Options {
1132				decoder: decoder.clone(),
1133				delay: Delay {
1134					max: Some(max_delay),
1135					..Delay::default()
1136				},
1137				..Options::new()
1138			},
1139		))
1140		.unwrap();
1141
1142		let subscription = published.subscription().expect("the consumer subscribed");
1143		let max = match subscription.ranges[..] {
1144			[
1145				moq_net::track::Range {
1146					start: moq_net::track::Start::Live { max, .. },
1147					..
1148				},
1149			] => max,
1150			ref ranges => panic!("expected one live join, got {ranges:?}"),
1151		};
1152		assert_eq!(max, Some(max_delay), "the age budget did not reach the publisher");
1153
1154		let opened = probe::native_opened().expect("the decoder opened");
1155		assert_eq!(opened.output, decoder.output);
1156		assert_eq!(opened.scale_hint, decoder.scale_hint);
1157
1158		let frame = pollster::block_on(consumer.next_frame())
1159			.unwrap()
1160			.expect("a decoded frame");
1161		assert!(
1162			matches!(frame.surface, crate::Surface::I420(_)),
1163			"CPU output was not enforced"
1164		);
1165	}
1166
1167	#[tokio::test]
1168	async fn leading_pictures_require_a_continuous_previous_group() {
1169		tokio::time::pause();
1170		let broadcast = moq_net::broadcast::Info::new().produce();
1171		let track = broadcast
1172			.create_track("video", hang::container::track_info(hang::catalog::PRIORITY.video))
1173			.unwrap();
1174		let catalog = VideoConfig::new(hang::catalog::H264 {
1175			inline: true,
1176			profile: 0x42,
1177			constraints: 0,
1178			level: 30,
1179		});
1180		let mut consumer = Consumer::new(
1181			&broadcast.consume(),
1182			&catalog,
1183			"video",
1184			Options {
1185				decoder: Config {
1186					backend: Backend::Named(probe::BUFFERED_NAME.into()),
1187					..Config::new()
1188				},
1189				delay: Delay {
1190					max: Some(std::time::Duration::from_secs(10)),
1191					..Delay::default()
1192				},
1193				..Options::new()
1194			},
1195		)
1196		.await
1197		.unwrap();
1198		let wire = moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Video);
1199		let write = |stamps: &[u64]| {
1200			let mut group = None;
1201			let frames: Vec<_> = stamps
1202				.iter()
1203				.enumerate()
1204				.map(|(index, stamp)| moq_mux::container::Frame {
1205					timestamp: Timestamp::from_micros(*stamp).unwrap(),
1206					decode: None,
1207					duration: None,
1208					payload: Bytes::from_static(b"access unit"),
1209					keyframe: index == 0,
1210				})
1211				.collect();
1212			wire.write(&mut moq_mux::container::Writer::new(&track, &mut group), &frames)
1213				.unwrap();
1214			group.unwrap().finish().unwrap();
1215		};
1216		write(&[1000, 800, 900, 1100]);
1217		write(&[2000, 1800, 1900, 2100]);
1218		let mut got = Vec::new();
1219		for _ in 0..5 {
1220			got.push(
1221				consumer
1222					.next_frame()
1223					.await
1224					.unwrap()
1225					.unwrap()
1226					.timestamp
1227					.as_micros()
1228					.unwrap(),
1229			);
1230		}
1231		assert_eq!(
1232			got,
1233			[1000, 1100, 2000, 1800, 1900],
1234			"join trims, continuous delivery keeps every leading picture"
1235		);
1236		consumer.reader().track.set_delay(Delay::default());
1237		write(&[3000]);
1238		write(&[4000, 3800, 3900, 4100]);
1239		let _track = track.finish().unwrap();
1240		got.clear();
1241		while let Some(frame) = consumer.next_frame().await.unwrap() {
1242			got.push(frame.timestamp.as_micros().unwrap());
1243		}
1244		assert_eq!(
1245			got,
1246			[2100, 4000, 4100],
1247			"a later latency skip must trim its recovery group too"
1248		);
1249	}
1250
1251	/// A track ends before a decoder that reorders pictures does. The consumer
1252	/// drains the backend once and returns its tail before reporting the end,
1253	/// each picture with the arrival of its own access unit rather than of the
1254	/// access unit that pushed it out.
1255	#[tokio::test(start_paused = true)]
1256	async fn track_end_drains_buffered_decoder() {
1257		let broadcast = moq_net::broadcast::Info::new().produce();
1258		let track = broadcast
1259			.create_track("video", hang::container::track_info(hang::catalog::PRIORITY.video))
1260			.unwrap();
1261		let subscriber = broadcast.consume();
1262		let mut producer = moq_mux::container::Producer::new(
1263			track,
1264			moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Data),
1265		);
1266		let mut written = Vec::new();
1267		for index in 0..2u64 {
1268			written.push(Instant::now());
1269			producer
1270				.write(moq_mux::container::Frame {
1271					timestamp: Timestamp::from_micros(index * 33_333).unwrap(),
1272					decode: None,
1273					duration: None,
1274					payload: Bytes::from_static(b"access unit"),
1275					keyframe: index == 0,
1276				})
1277				.unwrap();
1278			tokio::time::advance(std::time::Duration::from_millis(10)).await;
1279		}
1280		let _finished = producer.finish().unwrap();
1281
1282		let catalog = VideoConfig::new(hang::catalog::H264 {
1283			inline: true,
1284			profile: 0x42,
1285			constraints: 0,
1286			level: 30,
1287		});
1288		let mut consumer = Consumer::new(
1289			&subscriber,
1290			&catalog,
1291			"video",
1292			Options {
1293				decoder: Config {
1294					backend: Backend::Named(probe::BUFFERED_NAME.into()),
1295					..Config::new()
1296				},
1297				..Options::new()
1298			},
1299		)
1300		.await
1301		.unwrap();
1302
1303		assert_eq!(consumer.arrival(), None, "nothing read yet");
1304		let mut timestamps = Vec::new();
1305		let mut arrivals = Vec::new();
1306		while let Some(frame) = consumer.next_frame().await.unwrap() {
1307			timestamps.push(frame.timestamp.as_micros().unwrap());
1308			arrivals.push(consumer.arrival());
1309		}
1310		assert_eq!(timestamps, vec![0, 33_333]);
1311		assert_eq!(arrivals, written.into_iter().map(Some).collect::<Vec<_>>());
1312		assert!(
1313			consumer.next_frame().await.unwrap().is_none(),
1314			"the decoder was drained twice"
1315		);
1316	}
1317
1318	/// A decoder that reorders returns pictures in presentation order, so each one's
1319	/// arrival is looked up by its timestamp rather than taken in decode order.
1320	#[tokio::test(start_paused = true)]
1321	async fn arrival_follows_a_reordered_picture() {
1322		let (shown, landed) = decode_bframes(probe::REORDER_NAME).await;
1323		let expected: Vec<_> = [0, 1, 2, 3].map(|index| (index, Some(landed[&index]))).into();
1324		assert_eq!(shown, expected);
1325	}
1326
1327	/// A pipelined decoder that returns pictures in decode order, so a B-frame's access
1328	/// unit is fed before the P-frame ahead of it comes out, still maps each picture
1329	/// to its own access unit.
1330	#[tokio::test(start_paused = true)]
1331	async fn arrival_follows_a_picture_in_decode_order() {
1332		let (shown, landed) = decode_bframes(probe::BUFFERED_NAME).await;
1333		let expected: Vec<_> = [0, 3, 1, 2].map(|index| (index, Some(landed[&index]))).into();
1334		assert_eq!(shown, expected);
1335	}
1336
1337	/// Decode I0 P3 B1 B2 with the decoder named `decoder`, each access unit landing
1338	/// 10 ms after the last. Returns each picture shown, by frame index, with its
1339	/// reported arrival, and when each access unit landed.
1340	async fn decode_bframes(decoder: &str) -> (Vec<(u64, Option<Instant>)>, std::collections::BTreeMap<u64, Instant>) {
1341		let (broadcast, track) = live_track();
1342		let mut consumer = Consumer::new(
1343			&broadcast.consume(),
1344			&catalog(),
1345			"video",
1346			Options {
1347				decoder: Config {
1348					backend: Backend::Named(decoder.into()),
1349					..Config::new()
1350				},
1351				delay: Delay {
1352					max: Some(std::time::Duration::from_secs(10)),
1353					..Delay::default()
1354				},
1355				..Options::new()
1356			},
1357		)
1358		.await
1359		.unwrap();
1360
1361		let wire = moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Video);
1362		let mut group = None;
1363		let mut landed = std::collections::BTreeMap::new();
1364		for (index, frame) in [0u64, 3, 1, 2].into_iter().enumerate() {
1365			landed.insert(frame, Instant::now());
1366			wire.write(
1367				&mut moq_mux::container::Writer::new(&track, &mut group),
1368				&[moq_mux::container::Frame {
1369					timestamp: Timestamp::from_micros(frame * 33_333).unwrap(),
1370					decode: None,
1371					duration: None,
1372					payload: Bytes::from_static(b"access unit"),
1373					keyframe: index == 0,
1374				}],
1375			)
1376			.unwrap();
1377			tokio::time::advance(std::time::Duration::from_millis(10)).await;
1378		}
1379		group.unwrap().finish().unwrap();
1380		let _track = track.finish().unwrap();
1381
1382		let mut shown = Vec::new();
1383		while let Some(frame) = consumer.next_frame().await.unwrap() {
1384			let index = u64::try_from(frame.timestamp.as_micros().unwrap()).unwrap() / 33_333;
1385			shown.push((index, consumer.arrival()));
1386		}
1387		(shown, landed)
1388	}
1389
1390	/// A decoder holding more access units than the queue keeps drops the oldest
1391	/// arrivals, so their pictures report none rather than a guess.
1392	#[tokio::test(start_paused = true)]
1393	async fn arrivals_are_bounded() {
1394		const FRAMES: u64 = ARRIVALS as u64 + 8;
1395		let (broadcast, track) = live_track();
1396		let mut consumer = Consumer::new(
1397			&broadcast.consume(),
1398			&catalog(),
1399			"video",
1400			Options {
1401				decoder: Config {
1402					backend: Backend::Named(probe::HOLDING_NAME.into()),
1403					..Config::new()
1404				},
1405				delay: Delay {
1406					max: Some(std::time::Duration::from_secs(10)),
1407					..Delay::default()
1408				},
1409				..Options::new()
1410			},
1411		)
1412		.await
1413		.unwrap();
1414
1415		let wire = moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Video);
1416		let mut group = None;
1417		let frames: Vec<_> = (0..FRAMES)
1418			.map(|index| moq_mux::container::Frame {
1419				timestamp: Timestamp::from_micros(index * 33_333).unwrap(),
1420				decode: None,
1421				duration: None,
1422				payload: Bytes::from_static(b"access unit"),
1423				keyframe: index == 0,
1424			})
1425			.collect();
1426		wire.write(&mut moq_mux::container::Writer::new(&track, &mut group), &frames)
1427			.unwrap();
1428		group.unwrap().finish().unwrap();
1429		let _track = track.finish().unwrap();
1430
1431		let mut sourced = Vec::new();
1432		while consumer.next_frame().await.unwrap().is_some() {
1433			assert!(consumer.reader().arrivals.len() <= ARRIVALS);
1434			sourced.push(consumer.arrival().is_some());
1435		}
1436		let mut expected = vec![false; FRAMES as usize - ARRIVALS];
1437		expected.extend(vec![true; ARRIVALS]);
1438		assert_eq!(sourced, expected);
1439	}
1440
1441	/// A declared end drains the decoder, so the stopped encoder's last picture
1442	/// comes out ahead of the end while the publisher is still paused, rather
1443	/// than when the fresh encoder's first picture pushes it through.
1444	#[tokio::test]
1445	async fn an_end_drains_the_pictures_before_it() {
1446		let broadcast = moq_net::broadcast::Info::new().produce();
1447		let track = broadcast
1448			.create_track("video", hang::container::track_info(hang::catalog::PRIORITY.video))
1449			.unwrap();
1450		let subscriber = broadcast.consume();
1451		let mut producer = moq_mux::container::Producer::new(
1452			track,
1453			moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Video),
1454		);
1455		let picture = |micros: u64, payload: &'static [u8]| moq_mux::container::Frame {
1456			timestamp: Timestamp::from_micros(micros).unwrap(),
1457			decode: None,
1458			duration: Some(Timestamp::from_micros(33_333).unwrap()),
1459			payload: Bytes::from_static(payload),
1460			keyframe: true,
1461		};
1462		producer.write(picture(100_000, b"old access unit")).unwrap();
1463		producer.cut(None).unwrap();
1464		producer.discontinuity().unwrap();
1465
1466		let catalog = VideoConfig::new(hang::catalog::H264 {
1467			inline: true,
1468			profile: 0x42,
1469			constraints: 0,
1470			level: 30,
1471		});
1472		let mut consumer = Consumer::new(
1473			&subscriber,
1474			&catalog,
1475			"video",
1476			Options {
1477				decoder: Config {
1478					backend: Backend::Named(probe::BUFFERED_NAME.into()),
1479					..Config::new()
1480				},
1481				delay: Delay {
1482					max: Some(std::time::Duration::from_secs(10)),
1483					..Delay::default()
1484				},
1485				..Options::new()
1486			},
1487		)
1488		.await
1489		.unwrap();
1490
1491		let mut reads = Vec::new();
1492		let mut read = async |consumer: &mut Consumer| {
1493			reads.push(match consumer.read().await.unwrap() {
1494				Some(Read::Frame(frame)) => format!("frame {}", frame.timestamp.as_micros().unwrap()),
1495				Some(Read::Gap { timestamp, duration }) => {
1496					format!("gap {}+{}", timestamp.as_micros().unwrap(), duration.as_micros())
1497				}
1498				Some(Read::End { end }) => format!("end {}", end.as_micros().unwrap()),
1499				None => "none".to_string(),
1500			});
1501		};
1502		// Nothing follows the end yet.
1503		read(&mut consumer).await;
1504		read(&mut consumer).await;
1505
1506		producer.write(picture(200_000, b"new access unit")).unwrap();
1507		let _finished = producer.finish().unwrap();
1508		read(&mut consumer).await;
1509		read(&mut consumer).await;
1510		// The cut ended the group whole at the content's end, where the discontinuity marker starts.
1511		assert_eq!(reads, ["frame 100000", "end 133333", "frame 200000", "none"]);
1512	}
1513
1514	/// Every read until the track is done, as text: a codec error is one read too.
1515	async fn read_all(consumer: &mut Consumer) -> Vec<String> {
1516		let mut reads = Vec::new();
1517		loop {
1518			reads.push(match consumer.read().await {
1519				Ok(Some(Read::Frame(frame))) => format!("frame {}", frame.timestamp.as_micros().unwrap()),
1520				Ok(Some(Read::Gap { timestamp, .. })) => format!("gap {}", timestamp.as_micros().unwrap()),
1521				Ok(Some(Read::End { end })) => format!("end {}", end.as_micros().unwrap()),
1522				Ok(None) => return reads,
1523				Err(_) => "error".to_string(),
1524			});
1525		}
1526	}
1527
1528	/// A drain that fails at an end still delivers the pictures it readied ahead
1529	/// of the end, and the end itself, after reporting the error.
1530	#[tokio::test]
1531	async fn a_failed_drain_keeps_its_end() {
1532		let broadcast = moq_net::broadcast::Info::new().produce();
1533		let track = broadcast
1534			.create_track("video", hang::container::track_info(hang::catalog::PRIORITY.video))
1535			.unwrap();
1536		let subscriber = broadcast.consume();
1537		let mut producer = moq_mux::container::Producer::new(
1538			track,
1539			moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Video),
1540		);
1541		let picture = |micros: u64| moq_mux::container::Frame {
1542			timestamp: Timestamp::from_micros(micros).unwrap(),
1543			decode: None,
1544			duration: Some(Timestamp::from_micros(33_333).unwrap()),
1545			payload: Bytes::from_static(b"access unit"),
1546			keyframe: true,
1547		};
1548		producer.write(picture(100_000)).unwrap();
1549		producer.cut(None).unwrap();
1550		producer.discontinuity().unwrap();
1551		producer.write(picture(200_000)).unwrap();
1552		let _finished = producer.finish().unwrap();
1553
1554		let catalog = VideoConfig::new(hang::catalog::H264 {
1555			inline: true,
1556			profile: 0x42,
1557			constraints: 0,
1558			level: 30,
1559		});
1560		let mut consumer = Consumer::new(
1561			&subscriber,
1562			&catalog,
1563			"video",
1564			Options {
1565				decoder: Config {
1566					backend: Backend::Named(probe::FAILING_FLUSH_NAME.into()),
1567					..Config::new()
1568				},
1569				delay: Delay {
1570					max: Some(std::time::Duration::from_secs(10)),
1571					..Delay::default()
1572				},
1573				..Options::new()
1574			},
1575		)
1576		.await
1577		.unwrap();
1578
1579		assert_eq!(
1580			read_all(&mut consumer).await,
1581			["error", "frame 100000", "end 133333", "error", "frame 200000"]
1582		);
1583	}
1584
1585	/// A drain that fails at a gap still delivers the gap after the pictures it
1586	/// readied, and still trims the leading pictures of the recovery group.
1587	#[tokio::test(start_paused = true)]
1588	async fn a_failed_drain_keeps_its_gap_and_recovery() {
1589		let broadcast = moq_net::broadcast::Info::new().produce();
1590		let track = broadcast
1591			.create_track("video", hang::container::track_info(hang::catalog::PRIORITY.video))
1592			.unwrap();
1593		let catalog = VideoConfig::new(hang::catalog::H264 {
1594			inline: true,
1595			profile: 0x42,
1596			constraints: 0,
1597			level: 30,
1598		});
1599		let mut consumer = Consumer::new(
1600			&broadcast.consume(),
1601			&catalog,
1602			"video",
1603			Options {
1604				decoder: Config {
1605					backend: Backend::Named(probe::FAILING_FLUSH_NAME.into()),
1606					..Config::new()
1607				},
1608				delay: Delay {
1609					max: Some(std::time::Duration::from_secs(10)),
1610					..Delay::default()
1611				},
1612				..Options::new()
1613			},
1614		)
1615		.await
1616		.unwrap();
1617		let wire = moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Video);
1618		let write = |stamps: &[u64]| {
1619			let mut group = None;
1620			let frames: Vec<_> = stamps
1621				.iter()
1622				.enumerate()
1623				.map(|(index, stamp)| moq_mux::container::Frame {
1624					timestamp: Timestamp::from_micros(*stamp).unwrap(),
1625					decode: None,
1626					duration: None,
1627					payload: Bytes::from_static(b"access unit"),
1628					keyframe: index == 0,
1629				})
1630				.collect();
1631			wire.write(&mut moq_mux::container::Writer::new(&track, &mut group), &frames)
1632				.unwrap();
1633			group.unwrap().finish().unwrap();
1634		};
1635		write(&[1000, 1100]);
1636		let first = consumer.next_frame().await.unwrap().unwrap();
1637		assert_eq!(first.timestamp.as_micros().unwrap(), 1000);
1638
1639		consumer.reader().track.set_delay(Delay::default());
1640		write(&[2000]);
1641		write(&[3000, 2800, 2900, 3100]);
1642		assert!(consumer.read().await.is_err(), "the drain did not fail");
1643		// A codec error leaves the subscription reading, and its priority adjustable.
1644		consumer.set_priority(-20);
1645		assert_eq!(track.subscription().map(|sub| sub.ranges[0].priority), Some(-20));
1646		let _track = track.finish().unwrap();
1647		let reads = read_all(&mut consumer).await;
1648		assert_eq!(
1649			reads[..2],
1650			["frame 1100", "gap 1100"],
1651			"the drained picture, then its gap: {reads:?}"
1652		);
1653		assert_eq!(
1654			reads[2..],
1655			["frame 3000", "error", "frame 3100"],
1656			"recovery trims the leading pictures: {reads:?}"
1657		);
1658	}
1659
1660	/// A read dropped while a threaded flush is in flight loses nothing: the
1661	/// next read finishes that same flush rather than issuing another into a
1662	/// poisoned sink, and only then reports the end.
1663	#[cfg(not(apple))]
1664	#[tokio::test]
1665	async fn a_cancelled_read_resumes_the_flush_in_flight() {
1666		probe::prepare_blocking_flush();
1667		let broadcast = moq_net::broadcast::Info::new().produce();
1668		let track = broadcast
1669			.create_track("video", hang::container::track_info(hang::catalog::PRIORITY.video))
1670			.unwrap();
1671		let subscriber = broadcast.consume();
1672		let producer = moq_mux::container::Producer::new(
1673			track,
1674			moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Data),
1675		);
1676		let _finished = producer.finish().unwrap();
1677
1678		let catalog = VideoConfig::new(hang::catalog::H264 {
1679			inline: true,
1680			profile: 0x42,
1681			constraints: 0,
1682			level: 30,
1683		});
1684		let mut consumer = Consumer::new(
1685			&subscriber,
1686			&catalog,
1687			"video",
1688			Options {
1689				decoder: Config {
1690					backend: Backend::Named(probe::BLOCKING_FLUSH_NAME.into()),
1691					..Config::new()
1692				},
1693				..Options::new()
1694			},
1695		)
1696		.await
1697		.unwrap();
1698
1699		let mut read = Box::pin(consumer.next_frame());
1700		let entered = async {
1701			tokio::select! {
1702				_result = &mut read => panic!("flush returned before cancellation"),
1703				_ = probe::flush_entered() => {}
1704			}
1705		};
1706		if kio::clock::timeout(std::time::Duration::from_secs(1), entered)
1707			.await
1708			.is_err()
1709		{
1710			probe::release_flush();
1711			panic!("flush never reached the codec thread");
1712		}
1713		drop(read);
1714		probe::release_flush();
1715
1716		assert!(
1717			consumer.next_frame().await.unwrap().is_none(),
1718			"the cancelled read's flush was not resumed"
1719		);
1720		assert!(consumer.next_frame().await.unwrap().is_none());
1721	}
1722
1723	/// VAAPI returns its buffered tail before the consumer reports track end.
1724	#[cfg(all(target_os = "linux", feature = "vaapi", feature = "openh264"))]
1725	#[tokio::test]
1726	async fn the_track_ending_drains_the_decoder() {
1727		const FRAMES: u64 = 5;
1728		let config = EncodeConfig {
1729			backend: EncodeBackend::Software,
1730			..EncodeConfig::new(320, 240, crate::FrameRate::new(30, 1).unwrap())
1731		};
1732		let catalog = config.probe().await.expect("probe the software encoder");
1733
1734		let broadcast = moq_net::broadcast::Info::new().produce();
1735		let track = broadcast
1736			.create_track("video", hang::container::track_info(hang::catalog::PRIORITY.video))
1737			.unwrap();
1738		let subscriber = broadcast.consume();
1739		let mut producer = moq_mux::container::Producer::new(
1740			track,
1741			moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Data),
1742		);
1743
1744		let mut encoder = Encoder::new(&config).unwrap();
1745		let rgba = vec![0x80u8; 320 * 240 * 4];
1746		// When each access unit was written, bracketing when it landed.
1747		let mut written = Vec::new();
1748		for index in 0..FRAMES {
1749			if index == 0 {
1750				encoder.cut().unwrap();
1751			}
1752			let surface = crate::Surface::rgba(&rgba, crate::Size::new(320, 240)).unwrap();
1753			let frame = crate::Frame::new(moq_net::Timestamp::from_micros(index * 33_333).unwrap(), surface);
1754			for encoded in encoder.encode_all(&frame).unwrap() {
1755				let before = Instant::now();
1756				producer
1757					.write(moq_mux::container::Frame {
1758						timestamp: encoded.timestamp,
1759						decode: None,
1760						duration: None,
1761						payload: encoded.payload,
1762						keyframe: index == 0,
1763					})
1764					.unwrap();
1765				written.push((before, Instant::now()));
1766			}
1767		}
1768		let _finished = producer.finish().unwrap();
1769
1770		let decode = Options {
1771			decoder: Config {
1772				backend: Backend::Named("vaapi".into()),
1773				..Config::new()
1774			},
1775			..Options::new()
1776		};
1777		// The hardware gate: no libva, no render node, or no H.264 decode
1778		// entrypoint and the named backend refuses to open.
1779		let Ok(mut consumer) = Consumer::new(&subscriber, &catalog, "video", decode).await else {
1780			return;
1781		};
1782
1783		let mut timestamps = Vec::new();
1784		let mut arrivals = Vec::new();
1785		while let Some(frame) = consumer.next_frame().await.unwrap() {
1786			timestamps.push(frame.timestamp.as_micros().unwrap());
1787			arrivals.push(consumer.arrival().expect("the picture kept its arrival"));
1788		}
1789		let expected: Vec<u128> = (0..FRAMES as u128).map(|index| index * 33_333).collect();
1790		assert_eq!(timestamps, expected, "the track ended before the stream did");
1791		for (index, (arrived, (before, after))) in arrivals.iter().zip(&written).enumerate() {
1792			assert!(
1793				before <= arrived && arrived <= after,
1794				"picture {index} reports another access unit's arrival"
1795			);
1796		}
1797
1798		// The end stays the end: the drain runs once, so a caller that keeps
1799		// reading past it does not get the tail a second time.
1800		assert!(consumer.next_frame().await.unwrap().is_none());
1801	}
1802
1803	/// One frame per second.
1804	const SECOND: u64 = 1_000_000;
1805
1806	fn catalog() -> VideoConfig {
1807		VideoConfig::new(hang::catalog::H264 {
1808			inline: true,
1809			profile: 0x42,
1810			constraints: 0,
1811			level: 30,
1812		})
1813	}
1814
1815	fn live_track() -> (moq_net::broadcast::Producer, moq_net::track::Producer) {
1816		let broadcast = moq_net::broadcast::Info::new().produce();
1817		let track = broadcast
1818			.create_track("video", hang::container::track_info(hang::catalog::PRIORITY.video))
1819			.unwrap();
1820		(broadcast, track)
1821	}
1822
1823	/// The first request already states the min delay: a latest start waits for the live edge
1824	/// with its subscription open, before the container could update it.
1825	#[tokio::test]
1826	async fn the_first_subscription_states_the_min_delay() {
1827		let (broadcast, mut track) = live_track();
1828		let delay = Delay {
1829			min: Some(std::time::Duration::from_millis(300)),
1830			max: Some(std::time::Duration::from_millis(500)),
1831		};
1832		let consume = broadcast.consume();
1833		let catalog = catalog();
1834		let mut open = Box::pin(Consumer::new(
1835			&consume,
1836			&catalog,
1837			"video",
1838			Options {
1839				decoder: Config {
1840					backend: Backend::Named(probe::IMMEDIATE_NAME.into()),
1841					..Config::new()
1842				},
1843				start: Start::Latest,
1844				delay,
1845				..Options::new()
1846			},
1847		));
1848		// The open waits for the live edge with its subscription open, so the first aggregate
1849		// the publisher sees is the request itself.
1850		let first = tokio::select! {
1851			opened = &mut open => panic!("the open finished with no live edge (ok: {})", opened.is_ok()),
1852			first = track.subscription_changed() => first.unwrap(),
1853		};
1854		assert_eq!(
1855			first.map(|sub| sub.ranges),
1856			Some(vec![
1857				moq_net::track::Range::from(moq_net::track::Start::Live {
1858					min: Some(std::time::Duration::from_millis(300)),
1859					max: delay.max,
1860				})
1861				.with_priority(hang::catalog::PRIORITY.video)
1862			])
1863		);
1864	}
1865
1866	/// A device that cannot decode the stream refuses the rendition, so a caller
1867	/// can pick another one, the same as for a codec this build lacks.
1868	#[tokio::test]
1869	async fn a_device_refusal_is_an_unsupported_config() {
1870		let (broadcast, _track) = live_track();
1871		let result = Consumer::new(
1872			&broadcast.consume(),
1873			&catalog(),
1874			"video",
1875			Options {
1876				decoder: Config {
1877					backend: Backend::Named(probe::REFUSING_NAME.into()),
1878					..Config::new()
1879				},
1880				..Options::new()
1881			},
1882		)
1883		.await;
1884		match result {
1885			Err(Error::UnsupportedConfig(reason)) => assert!(reason.contains("cannot decode"), "{reason}"),
1886			Err(other) => panic!("expected UnsupportedConfig, got {other:?}"),
1887			Ok(_) => panic!("the consumer opened a decoder its device refused"),
1888		}
1889	}
1890
1891	/// A decoder that refuses an access unit never returns its picture, so a later
1892	/// access unit at the same timestamp reports its own arrival, not the refused one's.
1893	#[tokio::test(start_paused = true)]
1894	async fn a_refused_access_unit_does_not_lend_its_arrival() {
1895		let (broadcast, track) = live_track();
1896		let mut consumer = Consumer::new(
1897			&broadcast.consume(),
1898			&catalog(),
1899			"video",
1900			Options {
1901				decoder: Config {
1902					backend: Backend::Named(probe::IMMEDIATE_NAME.into()),
1903					..Config::new()
1904				},
1905				delay: Delay {
1906					max: Some(std::time::Duration::from_secs(10)),
1907					..Delay::default()
1908				},
1909				..Options::new()
1910			},
1911		)
1912		.await
1913		.unwrap();
1914
1915		let wire = moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Video);
1916		// A group's first frame is its keyframe, and a decoder that refused one drops the
1917		// deltas behind it, so each access unit opens a group of its own.
1918		let mut landed = Vec::new();
1919		for (sequence, payload) in [probe::CORRUPT, b"access unit".as_slice()].into_iter().enumerate() {
1920			landed.push(Instant::now());
1921			let mut group = None;
1922			wire.write(
1923				&mut moq_mux::container::Writer::new(&track, &mut group),
1924				&[moq_mux::container::Frame {
1925					decode: None,
1926					// Group starts strictly increase, so each access unit presents a second later.
1927					timestamp: Timestamp::from_micros(sequence as u64 * SECOND).unwrap(),
1928					duration: None,
1929					payload: Bytes::from_static(payload),
1930					keyframe: true,
1931				}],
1932			)
1933			.unwrap();
1934			group.unwrap().finish().unwrap();
1935			tokio::time::advance(std::time::Duration::from_millis(10)).await;
1936		}
1937		let _track = track.finish().unwrap();
1938
1939		let Err(err) = consumer.next_frame().await else {
1940			panic!("the refused access unit did not fail the read");
1941		};
1942		assert!(err.to_string().contains("corrupt"), "unexpected error: {err}");
1943		consumer
1944			.next_frame()
1945			.await
1946			.unwrap()
1947			.expect("the next access unit decodes");
1948		assert_eq!(consumer.arrival(), Some(landed[1]));
1949		assert_eq!(consumer.reader().arrivals.len(), 0, "nothing stays queued");
1950	}
1951
1952	/// A timestamp two access units share, both still held by the decoder, matches either
1953	/// of them, so the picture reports none rather than a guess.
1954	#[tokio::test(start_paused = true)]
1955	async fn a_repeated_timestamp_reports_no_arrival() {
1956		let (broadcast, track) = live_track();
1957		let mut consumer = Consumer::new(
1958			&broadcast.consume(),
1959			&catalog(),
1960			"video",
1961			Options {
1962				decoder: Config {
1963					backend: Backend::Named(probe::HOLDING_NAME.into()),
1964					..Config::new()
1965				},
1966				delay: Delay {
1967					max: Some(std::time::Duration::from_secs(10)),
1968					..Delay::default()
1969				},
1970				..Options::new()
1971			},
1972		)
1973		.await
1974		.unwrap();
1975
1976		let wire = moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Video);
1977		let mut group = None;
1978		for keyframe in [true, false] {
1979			wire.write(
1980				&mut moq_mux::container::Writer::new(&track, &mut group),
1981				&[moq_mux::container::Frame {
1982					timestamp: Timestamp::ZERO,
1983					decode: None,
1984					duration: None,
1985					payload: Bytes::from_static(b"access unit"),
1986					keyframe,
1987				}],
1988			)
1989			.unwrap();
1990			tokio::time::advance(std::time::Duration::from_millis(10)).await;
1991		}
1992		group.unwrap().finish().unwrap();
1993		let _track = track.finish().unwrap();
1994
1995		let mut shown = 0;
1996		while consumer.next_frame().await.unwrap().is_some() {
1997			assert_eq!(consumer.arrival(), None, "picture {shown} guessed an arrival");
1998			shown += 1;
1999		}
2000		assert!(shown > 0, "the decoder returned no picture");
2001	}
2002}