Skip to main content

moq_audio/decode/
consumer.rs

1//! Subscribe to an encoded audio track and emit raw PCM.
2
3use std::collections::VecDeque;
4use std::task::Poll;
5
6use kio::clock::Instant;
7use moq_mux::container::Read as Encoded;
8use std::time::Duration;
9
10use bytes::Bytes;
11
12use super::backpressure::{self, Backpressure};
13use super::decoder::{Config, Decoder};
14use crate::jitter::{self, Target};
15use crate::resample::{Remix, Resampler};
16use crate::{Activity, Error, Format, Frame, Layout};
17pub use moq_mux::container::Delay;
18
19/// The most lost media concealed per gap; the rest is a [`Read::Gap`]. libopus CELT turns to
20/// noise past five lost packets (100 ms at 20 ms), still about -20 dB below the speech it
21/// replaces, and the audio after a longer concealment recovers twice as far from the original.
22/// SILK fades to near silence over the same span.
23const CONCEAL_MAX: Duration = Duration::from_millis(100);
24
25/// One item of a [`Consumer`] read, in delivery order: decoded PCM, or a break in it.
26///
27/// The decoded counterpart of [`moq_mux::container::Read`], and the same shape
28/// `moq_video::decode::Read` has, so a player handles loss and ends alike for
29/// every media type.
30#[derive(Clone, Debug)]
31#[non_exhaustive]
32pub enum Read {
33	/// Decoded PCM.
34	Frame(Frame),
35	/// Media after what was already read was lost: a group was skipped or never arrived,
36	/// or a packet's timestamp did not continue the previous one. What follows does not
37	/// continue what came before, and every sample decoded before the loss precedes it.
38	///
39	/// A codec that conceals loss (Opus) fills up to the first 100 ms of the
40	/// loss with [`Read::Frame`]s first, so the gap covers only the rest, and a shorter loss
41	/// reads as no gap at all. A loss across a declared [`Read::End`] is never concealed.
42	///
43	/// The span is an upper bound, and `timestamp` is in the scale of the frame that follows.
44	#[non_exhaustive]
45	Gap {
46		/// The furthest presentation point already read.
47		timestamp: moq_net::Timestamp,
48		/// How long until the next frame resumes.
49		duration: Duration,
50	},
51	/// The publisher stopped its encoder: it paused, switched source, or finished.
52	///
53	/// Frames that follow and start before `end` are the stopped encoder's remaining
54	/// media: its codec drain, trimmed at `end`, and the resampler's tail. The first frame
55	/// at or past `end` comes from a fresh encoder, since a timeline only moves forward.
56	#[non_exhaustive]
57	End {
58		/// Where the stopped encoder's media stops.
59		end: moq_net::Timestamp,
60	},
61}
62
63/// Where a consumer starts on a track that already holds groups.
64#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
65#[non_exhaustive]
66pub enum Start {
67	/// Decode every cached group.
68	#[default]
69	Oldest,
70	/// Start at the newest group, skipping whatever is already cached. Opening waits for
71	/// the track's live edge, or its end.
72	Latest,
73}
74
75/// The delay a subscription for `options` carries: theirs, with the playout delay `stated` as the
76/// min, where a live join starts. [`Start::Oldest`] states none, which reaches back as far as the
77/// max delay allows rather than join the live edge.
78fn subscribed(options: &Options, stated: Duration) -> Delay {
79	match options.start {
80		Start::Oldest => options.delay.with_min(None),
81		Start::Latest => options.delay.with_min(stated),
82	}
83}
84
85/// PCM output conversion requested from [`Consumer`].
86#[derive(Clone, Debug, Default)]
87#[non_exhaustive]
88pub struct Output {
89	/// How to pack samples in each emitted frame.
90	pub format: Format,
91	/// Output sample rate, or the codec rate when absent.
92	pub sample_rate: Option<u32>,
93	/// Output layout, or the codec layout when absent.
94	pub layout: Option<Layout>,
95}
96
97/// Subscription, decoder, and output policy for [`Consumer`].
98#[derive(Clone, Debug)]
99#[non_exhaustive]
100pub struct Options {
101	/// Low-level decoder configuration.
102	pub decoder: Config,
103	/// PCM output conversion.
104	pub output: Output,
105	/// How far behind the live edge playback runs.
106	///
107	/// [`Delay::min`] is the playout delay: the jitter buffer a player holds ahead of the
108	/// playhead, reported by [`Consumer::delay`], and where a cold join starts. With
109	/// [`estimate`](Self::estimate) it is a floor under the measured delay instead. A
110	/// [`Start::Latest`] subscription states whichever delay the player holds as its min,
111	/// following the estimate; a [`Start::Oldest`] one states none, reaching back to the oldest
112	/// group.
113	/// A `min` beyond the track's max age is refused. [`Delay::max`] is how far a group may fall
114	/// behind the live edge before the subscription skips it, and how long a missing group is
115	/// waited for; it adds no buffering.
116	pub delay: Delay,
117	/// Measure the playout delay from arrival timing, never below [`Delay::min`] (default:
118	/// `true`). `false` holds exactly `delay.min`.
119	pub estimate: bool,
120	/// Initial cached-group policy.
121	pub start: Start,
122	/// The subscription priority, ordering this track against the others on the session under
123	/// congestion: higher is sent first. Defaults to hang's `PRIORITY.audio`;
124	/// [`Consumer::set_priority`] moves it while running.
125	pub priority: i8,
126}
127
128impl Default for Options {
129	fn default() -> Self {
130		Self {
131			decoder: Config::default(),
132			output: Output::default(),
133			delay: Delay::default(),
134			estimate: true,
135			start: Start::default(),
136			priority: hang::catalog::PRIORITY.audio,
137		}
138	}
139}
140
141impl Options {
142	/// Build default real-time consumer options.
143	pub fn new() -> Self {
144		Self::default()
145	}
146}
147
148/// Subscribe to a moq-mux audio track and emit decoded PCM in the requested
149/// [`Output`].
150///
151/// The mirror of [`encode::Producer`](crate::encode::Producer): output format /
152/// sample rate / layout are fixed at construction, and
153/// [`read`](Self::read) returns [`Read`] events carrying decoded samples and track boundaries.
154pub struct Consumer {
155	decoder: Decoder,
156	track: moq_mux::container::Consumer<moq_mux::catalog::hang::Wire>,
157	/// The subscription's preferences, for a priority change, until the track ends: holding them
158	/// past that would keep the publisher's demand the container released.
159	control: Option<moq_net::track::Control>,
160	resampler: Option<Resampler>,
161	/// Converts the decoded layout to the output's, when they differ.
162	remix: Option<Remix>,
163	options: Options,
164	max_delay: std::time::Duration,
165	/// The track's max age, which clamps the max delay.
166	max_age: Option<std::time::Duration>,
167	/// Prime after a join or loss, never after a declared endpoint or at the track's
168	/// first packet, which the codec's own delay already primes.
169	warmup: Duration,
170	warmup_pending: bool,
171	/// Media decoded so far, up to the warmup. A gap keeps the codec's history, which primes
172	/// it as the browser's pre-roll does, so only what this falls short of is trimmed.
173	primed: Duration,
174	/// Whether a packet was read or lost yet, so the track's first packet can be told apart.
175	started: bool,
176	warmup_until: Option<moq_net::Timestamp>,
177	resolved_sample_rate: u32,
178	resolved_layout: Layout,
179	/// Where the next packet's timestamp should land: the last packet's timestamp
180	/// plus the media it covered, including the codec delay the decoder trimmed off
181	/// the front. A packet that misses it is a hole nobody declared.
182	next_start: Option<moq_net::Timestamp>,
183	/// Frames decoded and not yet handed back, so a gap's tail can be returned
184	/// ahead of the packet that exposed it.
185	ready: VecDeque<Read>,
186	/// Codec activity spans the resampler's buffered output still covers.
187	spans: VecDeque<ActivitySpan>,
188	/// Activity of the last span the output ran past, for the rounding samples the
189	/// filter leaves beyond the final input boundary.
190	trailing: Activity,
191	/// Timestamp of the first encoded packet in this decoder epoch, used to
192	/// interpret codec delay and a terminal marker.
193	epoch: Option<moq_net::Timestamp>,
194	/// Codec delay trimmed since the current decoder epoch began.
195	delay_trimmed: usize,
196	/// Codec-rate terminal frames emitted since `terminal_start`.
197	frames_decoded: usize,
198	/// Logical endpoint carried by an empty legacy frame before terminal packets.
199	end: Option<moq_net::Timestamp>,
200	/// The group `end` came from: it bounds only the terminal packets that follow it there.
201	end_group: u64,
202	/// Presentation time of the first decoded terminal frame.
203	terminal_start: Option<moq_net::Timestamp>,
204	/// The playout delay, fixed or estimated from arrivals.
205	target: Target,
206	/// The playout delay the subscription states as its [`Delay::min`] in place of
207	/// [`Options::delay`]'s.
208	stated: Duration,
209	/// Where arrival times are measured from.
210	origin: Instant,
211	/// Packets read and observed but not yet decoded, held by the [`Backpressure`] gate,
212	/// each with when it arrived, and how many of them are gaps or ends.
213	pending: VecDeque<(Encoded, kio::clock::Instant)>,
214	breaks: usize,
215	/// When the latest packet decoded arrived.
216	arrived: Option<kio::clock::Instant>,
217	/// The track ended, or failed with this error, behind whatever is pending.
218	ended: Option<Option<Error>>,
219	/// The gate, while its [`Backpressure`] handle lives.
220	gate: Option<kio::Consumer<backpressure::State>>,
221	/// The latest gap or end handed over: a playhead at or before it is from the timeline it ended.
222	boundary: Option<Duration>,
223	/// The duration of the latest decoded packet, which the next one is taken to match.
224	frame: Duration,
225	/// The group of the latest end read, until a later group or a loss arrives.
226	declared: Option<u64>,
227}
228
229struct ActivitySpan {
230	end: moq_net::Timestamp,
231	activity: Activity,
232}
233
234/// A target in `f64` milliseconds as a [`Duration`].
235fn from_millis(millis: f64) -> Duration {
236	Duration::from_secs_f64(millis / 1000.0)
237}
238
239impl Consumer {
240	/// Subscribe to `name` in `broadcast`, using the catalog entry to pick the
241	/// codec.
242	pub async fn new(
243		broadcast: &moq_net::broadcast::Consumer,
244		catalog: &hang::catalog::AudioConfig,
245		name: impl Into<String>,
246		options: Options,
247	) -> Result<Self, Error> {
248		// Only a codec, layout, or description the decoder refuses is a capability refusal.
249		// Codec faults and conditions learned from the subscription, such as retention,
250		// keep their original errors.
251		let setup = |err| match err {
252			Error::Unsupported(reason) => Error::UnsupportedConfig(reason),
253			err => err,
254		};
255		let decoder = Decoder::new(catalog, &options.decoder).map_err(setup)?;
256		let sample_rate = options.output.sample_rate.unwrap_or_else(|| decoder.sample_rate());
257		let layout = options.output.layout.unwrap_or_else(|| decoder.layout());
258		let remix = (decoder.layout() != layout)
259			.then(|| Remix::new(decoder.layout(), layout))
260			.transpose()
261			.map_err(setup)?;
262
263		if sample_rate == 0 {
264			return Err(Error::Unsupported("output sample rate must be > 0".into()));
265		}
266
267		let name = name.into();
268		let warmup = catalog.warmup.unwrap_or_default().min(moq_mux::container::DELAY_MAX);
269		let target = Target::new(options.delay.min.unwrap_or_default(), options.estimate, catalog.jitter);
270		// The subscription states the playout delay as its min from the start, the estimate's cold
271		// start included, so a live join reaches back by it (see `next`).
272		let stated = from_millis(target.millis());
273		let playout = moq_mux::container::Playout::new(subscribed(&options, stated), warmup);
274		let track = broadcast.track(hang::catalog::Reference::track(catalog, &name))?;
275		// The whole delay from the start, as the container keeps it: the transport enforces the
276		// max too, so a narrower one while joining would drop the groups queued behind a reader
277		// slow to take its first, and the publisher should never see a stated zero min first.
278		let mut subscriber = track
279			.subscribe(
280				playout.subscription(
281					moq_net::track::Subscription::default()
282						.with_ranges([moq_net::track::Range::ALL.with_priority(options.priority)]),
283				),
284			)
285			.await?;
286		// Latest skips cached history; a warmup is primed by trimming the newest group's
287		// start, like any other join. Move the local cursor, not Subscription::ranges: the
288		// latter is aggregated across subscribers and can ask the publisher to rewind for
289		// everyone. The live edge is known only once the feed is live, so wait for it rather
290		// than read the backlog of a warm copy still waiting on its source; the wait ends
291		// with the track.
292		if options.start == Start::Latest
293			&& let Some(live_edge) = subscriber.largest().await
294		{
295			subscriber = subscriber.with_range(live_edge.group..);
296		}
297		let control = subscriber.control();
298		let track = subscriber;
299		let max_age = track.info().max_age;
300		let max_delay = options
301			.delay
302			.max
303			.unwrap_or(Duration::MAX)
304			.min(max_age.unwrap_or(Duration::MAX));
305		// Holding longer than the publisher's max age would wait on groups that go stale
306		// before they play, so the caller asked for something impossible.
307		let delay = options.delay.min.unwrap_or_default();
308		if let Some(max_age) = max_age
309			&& delay > max_age
310		{
311			return Err(Error::Unsupported(format!(
312				"playout delay {delay:?} exceeds the track's max age of {max_age:?}"
313			)));
314		}
315		// The catalog says how the track is framed, and it is not always the legacy
316		// wire: `moq import fmp4` publishes CMAF. Reading a moof+mdat fragment as a
317		// varint timestamp plus a payload decodes to garbage rather than failing.
318		let container = moq_mux::catalog::hang::Wire::try_from(catalog)?;
319		// The start reaches the playout delay plus the warmup back, while the container skips at
320		// the max delay alone.
321		let track = playout.consumer(track, container);
322
323		Ok(Self {
324			target,
325			stated,
326			decoder,
327			track,
328			control: Some(control),
329			resampler: None,
330			remix,
331			options,
332			max_delay,
333			max_age,
334			warmup,
335			warmup_pending: !warmup.is_zero(),
336			primed: Duration::ZERO,
337			warmup_until: None,
338			started: false,
339			resolved_sample_rate: sample_rate,
340			resolved_layout: layout,
341			next_start: None,
342			ready: VecDeque::new(),
343			spans: VecDeque::new(),
344			trailing: Activity::Active,
345			epoch: None,
346			delay_trimmed: 0,
347			frames_decoded: 0,
348			end: None,
349			end_group: 0,
350			terminal_start: None,
351			origin: now(),
352			pending: VecDeque::new(),
353			breaks: 0,
354			arrived: None,
355			ended: None,
356			gate: None,
357			boundary: None,
358			frame: Duration::ZERO,
359			declared: None,
360		})
361	}
362
363	/// The decoder backend name in use, e.g. `"libopus"` or `"symphonia"`.
364	pub fn name(&self) -> &str {
365		self.decoder.name()
366	}
367
368	/// The options this consumer was built with.
369	pub fn options(&self) -> &Options {
370		&self.options
371	}
372
373	/// The effective skip budget after clamping to the track's max age, excluding decoder warmup.
374	pub fn max_delay(&self) -> std::time::Duration {
375		self.max_delay
376	}
377
378	/// Move [`Delay::max`] mid-stream, clamped to the track's max age like [`Options::delay`].
379	///
380	/// A player whose playout delay moves calls this to keep the subscription reaching as far
381	/// behind it, as `moq play` keeps it at the delay plus its time stretch.
382	///
383	/// A history subscription, [`Start::Oldest`] with no [`Delay::max`], reads every group in
384	/// order and ignores it: the transport delivers nothing past a missing group, so there is no
385	/// budget to skip at.
386	pub fn set_max_delay(&mut self, max: std::time::Duration) {
387		if self.options.start == Start::Oldest && self.options.delay.max.is_none() {
388			return;
389		}
390		self.options.delay = self.options.delay.with_max(max);
391		self.track.set_delay(self.stated());
392		self.max_delay = max.min(self.max_age.unwrap_or(std::time::Duration::MAX));
393	}
394
395	/// Move [`Options::priority`] mid-stream, updating the subscription in place rather than
396	/// resubscribing, so nothing already fetched is dropped or fetched again.
397	pub fn set_priority(&mut self, priority: i8) {
398		self.options.priority = priority;
399		let Some(control) = &self.control else {
400			return;
401		};
402		let mut subscription = control.subscription();
403		if subscription.ranges.iter().any(|range| range.priority != priority) {
404			for range in &mut subscription.ranges {
405				range.priority = priority;
406			}
407			// Closed only once the track ended, when there is nothing left to prioritize.
408			let _ = control.update(subscription);
409		}
410	}
411
412	/// The playout delay to hold ahead of the playhead right now: the fixed
413	/// [`Delay::min`], or with [`Options::estimate`] the estimate from every frame read so far.
414	///
415	/// The estimate measures when each packet landed in this node's cache
416	/// ([`moq_mux::container::Consumer::arrival`]), so neither a hole the container waits out nor
417	/// a late read holds the packets behind it as jitter.
418	pub fn delay(&self) -> Duration {
419		from_millis(self.target.millis())
420	}
421
422	// The delay the subscription carries; see [`subscribed`].
423	fn stated(&self) -> Delay {
424		subscribed(&self.options, self.stated)
425	}
426
427	/// Sample rate samples are actually delivered at, which is
428	/// [`Output::sample_rate`] resolved against the catalog.
429	pub fn sample_rate(&self) -> u32 {
430		self.resolved_sample_rate
431	}
432
433	/// Layout samples are actually delivered in.
434	pub fn layout(&self) -> Layout {
435		self.resolved_layout
436	}
437
438	/// Gate decoding behind the returned [`Backpressure`], replacing any earlier gate.
439	///
440	/// [`read`](Self::read) keeps reading packets as they arrive and holds them encoded
441	/// until the gate admits them. Dropping the handle decodes every packet as it arrives
442	/// again.
443	pub fn backpressure(&mut self) -> Backpressure {
444		let (backpressure, gate) = Backpressure::new();
445		self.gate = Some(gate);
446		backpressure
447	}
448
449	/// When the packet behind the latest decoded frame landed in this node's cache
450	/// ([`moq_mux::container::Consumer::arrival`]), which a hole or a gate holding it encoded
451	/// may have kept well before [`read`](Self::read) handed the frame over.
452	pub fn arrival(&self) -> Option<kio::clock::Instant> {
453		self.arrived
454	}
455
456	/// Read decoded PCM or a track boundary, or `None` when the track ends.
457	///
458	/// [`Frame::activity`] reports whether the packet these samples came from
459	/// coded audio. It describes where the frame begins, so a resampled
460	/// frame that straddles a change carries the activity its first sample came
461	/// from and the next frame carries the new one.
462	///
463	/// A timestamp that doesn't continue the previous packet is a hole in the
464	/// output, not a splice: nothing is carried across it, and the frames on either
465	/// side stay anchored to their own packet timeline, so the hole is there to
466	/// see. "Doesn't continue" allows for the quantization the stamps carry, which
467	/// on a millisecond-stamped ingest is most of a millisecond.
468	pub async fn read(&mut self) -> Result<Option<Read>, Error> {
469		loop {
470			if let Some(frame) = self.ready.pop_front() {
471				return Ok(Some(frame));
472			}
473
474			let (mux_frame, track_start) = match self.next().await? {
475				Some(Encoded::Frame { group, frame }) => {
476					let first = !std::mem::replace(&mut self.started, true);
477					// A later group after a declared end comes from a fresh encoder; the end's
478					// own group carries the stopped encoder's final packets, trimmed below.
479					if self.end.is_some() && group != self.end_group {
480						self.restart()?;
481						self.fresh_encoder();
482					}
483					// A group with nothing below it, which its publisher declares by skipping
484					// every start before it, is the track's first, and a group delivers from its
485					// frame 0 or not at all, so reading it first means decoding from the
486					// encoder's first packet. A finished group's end marker may come first; it
487					// carries no media.
488					(frame, first && self.track.is_skipped(0..group))
489				}
490				// Behind whatever the resampler held from before the loss.
491				Some(Encoded::Gap { timestamp, duration }) => {
492					self.started = true;
493					let resume = resume(timestamp, duration)?;
494					// Groups lost past a declared end were the fresh encoder's, so the packet
495					// after them still comes from it, and decodes as its first, unprimed: a wire
496					// before lite-07 names the run the publisher skipped across its silence a
497					// drop, so after every pause this gap is that silence, not lost media, and
498					// stays silent rather than concealed.
499					let fresh = self.end.is_some();
500					// Lost media continues the codec's history as far as it conceals, and only
501					// the rest is a hole.
502					let timestamp = match self.conceal(resume)? {
503						Some(end) if !discontinuous(end, resume)? => continue,
504						Some(end) => earlier(end.convert(resume.scale().ok_or(moq_net::TimeOverflow)?)?, resume),
505						None => timestamp,
506					};
507					self.boundary = Some(Duration::try_from(timestamp)?);
508					self.restart()?;
509					self.warmup_pending = !self.warmup.is_zero();
510					if fresh {
511						self.fresh_encoder();
512					}
513					self.ready.push_back(Read::Gap {
514						timestamp,
515						duration: resume.checked_sub(timestamp)?.try_into()?,
516					});
517					continue;
518				}
519				// The resampler keeps running: the stopped encoder's final packets follow in
520				// the marker's group and continue its media. What it still holds comes out
521				// after the end, starting before it, once a fresh encoder or the track's end
522				// drains it.
523				Some(Encoded::End { group, end }) => {
524					self.boundary = Some(Duration::try_from(end)?);
525					self.end = Some(end);
526					self.end_group = group;
527					self.frames_decoded = 0;
528					self.terminal_start = None;
529					self.ready.push_back(Read::End { end });
530					continue;
531				}
532				None => return Ok(self.flush()?.map(Read::Frame)),
533			};
534
535			let timestamp = mux_frame.timestamp;
536
537			// Undeclared holes are routine: a skipped stalled group, a packet the
538			// decoder refused, an ingest that resynced. Drop the timeline's state at
539			// the edge, before the packet after it goes anywhere near the decoder.
540			//
541			// Skipped once an end marker arrives, because from there the terminal
542			// phase reconstructs each batch's time from the marker rather than
543			// reading it off the packet, so there is nothing left to compare.
544			if self.end.is_none()
545				&& let Some(next) = self.next_start
546				&& discontinuous(next, timestamp)?
547			{
548				// A hole is lost media, concealed as far as the codec can.
549				let next = self.conceal(timestamp)?.unwrap_or(next);
550				if discontinuous(next, timestamp)? {
551					if let Some(frame) = self.gap()? {
552						self.ready.push_back(Read::Frame(frame));
553					}
554					// From where the timeline should have continued to where it did, which an
555					// overlap leaves empty.
556					let start = earlier(
557						next.convert(timestamp.scale().ok_or(moq_net::TimeOverflow)?)?,
558						timestamp,
559					);
560					self.ready.push_back(Read::Gap {
561						timestamp: start,
562						duration: timestamp.checked_sub(start)?.try_into()?,
563					});
564				}
565			}
566
567			self.decode(&mux_frame.payload, timestamp, track_start)?;
568		}
569	}
570
571	/// Conceal the packets lost between where the timeline should continue and `resume`, up to
572	/// [`CONCEAL_MAX`], returning where the concealed audio ends. `None` when nothing is
573	/// concealed: nothing decoded since the last break, a declared end is pending, or the codec
574	/// cannot conceal.
575	fn conceal(&mut self, resume: moq_net::Timestamp) -> Result<Option<moq_net::Timestamp>, Error> {
576		let Some(start) = self.next_start else {
577			return Ok(None);
578		};
579		if self.end.is_some() || self.frame.is_zero() || !self.decoder.conceals() {
580			return Ok(None);
581		}
582		// A millisecond-stamped resume may land up to a millisecond before the packet ending there.
583		let lost = Duration::try_from(resume)?
584			.saturating_sub(Duration::try_from(start)?)
585			.saturating_add(Duration::from_millis(1));
586		let packets = (lost.min(CONCEAL_MAX).as_nanos() / self.frame.as_nanos()) as usize;
587		if packets == 0 {
588			return Ok(None);
589		}
590		// Each concealed packet is placed by the samples before it, not by the previous one's
591		// stamp, which a coarse timescale would round down packet by packet.
592		let rate = self.decoder.sample_rate();
593		let samples = ((self.frame.as_nanos() * u128::from(rate) + 500_000_000) / 1_000_000_000) as usize;
594		for packet in 0..packets {
595			self.decode(&[], advance(start, packet * samples, rate)?, false)?;
596		}
597		let end = advance(start, packets * samples, rate)?;
598		self.next_start = Some(end);
599		Ok(Some(end))
600	}
601
602	/// Decode one packet, an empty one concealing a lost packet, and queue its output.
603	fn decode(&mut self, payload: &[u8], timestamp: moq_net::Timestamp, track_start: bool) -> Result<(), Error> {
604		let rate = self.decoder.sample_rate();
605		let epoch = *self.epoch.get_or_insert(timestamp);
606		let delay = self.decoder.delay_remaining();
607		self.decoder.decode(payload)?;
608		// Each packet is placed by its own samples, which a decoder that holds or splits
609		// its output would hand back somewhere else.
610		let contract = |name: &str| {
611			Error::Codec(format!(
612				"{name} did not ready exactly one output for one packet, and playback places exactly one"
613			))
614		};
615		let Some(decoded) = self.decoder.receive()? else {
616			return Err(contract(self.decoder.name()));
617		};
618		if self.decoder.receive()?.is_some() {
619			return Err(contract(self.decoder.name()));
620		}
621		// Anchored only once a packet decodes: a refused one primed nothing. The track's
622		// first packet has no history to warm up from: the codec's pre-skip, trimmed by
623		// the decoder, is all the priming its encoder declared.
624		if std::mem::take(&mut self.warmup_pending) && !track_start {
625			let warmup = self.warmup.saturating_sub(self.primed);
626			if !warmup.is_zero() {
627				let warmup =
628					moq_net::Timestamp::try_from(warmup)?.convert(timestamp.scale().ok_or(moq_net::TimeOverflow)?)?;
629				self.warmup_until = Some(timestamp.checked_add(warmup)?);
630			}
631		}
632		// Codec delay trimmed off the front is media this packet covered even
633		// though no samples came out, so it still moves the packet after it along.
634		let trimmed = delay - self.decoder.delay_remaining();
635		self.delay_trimmed += trimmed;
636		let activity = decoded.activity;
637		let mut decoded = decoded.samples;
638		// The packet's duration as the codec states it, never read off the
639		// timestamps: those carry every tune-in and hole along with the spacing.
640		let covered = decoded.len() / self.decoder.layout().channels() as usize + trimmed;
641		// Concealment is the same length as the packet before it, and primes nothing.
642		if covered > 0 && !payload.is_empty() {
643			self.target.set_frame(covered as f64 * 1000.0 / rate as f64);
644			self.frame = Duration::from_secs_f64(covered as f64 / rate as f64);
645			self.primed = self.primed.saturating_add(self.frame).min(self.warmup);
646		}
647		if let Some(end) = self.end {
648			let terminal_start = *self
649				.terminal_start
650				.get_or_insert(later(rewind(timestamp, self.delay_trimmed, rate)?, epoch));
651			let total = frames_between(terminal_start, end, rate)?;
652			let remaining = total.saturating_sub(self.frames_decoded);
653			decoded.truncate(remaining.saturating_mul(self.decoder.layout().channels() as usize));
654		}
655
656		let frames = decoded.len() / self.decoder.layout().channels() as usize;
657		let decoded_at = if let Some(terminal_start) = self.terminal_start {
658			advance(terminal_start, self.frames_decoded, rate)?
659		} else {
660			// The codec delay is padding before the epoch, not a hole after the
661			// first short frame. Keep later output contiguous by moving it back over
662			// everything trimmed since this decoder epoch began.
663			later(rewind(timestamp, self.delay_trimmed, rate)?, epoch)
664		};
665		if self.end.is_some() {
666			self.frames_decoded += frames;
667		}
668		// Packet continuity stays on the encoded timeline. `decoded_at` may be
669		// earlier because codec pre-skip is padding before the decoded epoch.
670		self.next_start = Some(advance(timestamp, frames + trimmed, rate)?);
671		if decoded.is_empty() {
672			return Ok(());
673		}
674
675		if self.resampler.is_none() && rate != self.resolved_sample_rate {
676			// A decoded frame pays for the channel count. Bound the input
677			// window in frames, and its duration at low rates, so neither
678			// side's allocation grows with a catalog's rate declaration.
679			let chunk_frames = (rate as usize / 50).clamp(1, 960);
680			self.resampler = Some(Resampler::new(
681				rate,
682				self.resolved_sample_rate,
683				self.decoder.layout().channels(),
684				chunk_frames,
685			)?);
686		}
687
688		let (pcm, timestamp) = match self.resampler.as_mut() {
689			// The resampler works in fixed chunks, so it holds back whatever didn't
690			// fill one. What comes out next starts with those held-back samples, which
691			// arrived before this packet did, so it is stamped where they arrived.
692			// Reading that off this packet instead would place the audio late by up to
693			// a chunk, sawtoothing A/V sync, and drag it the whole way whenever the
694			// source jumps forward without declaring a hole.
695			Some(r) => {
696				let held = if r.pending_frames() == 0 {
697					decoded_at
698				} else {
699					r.held_at().unwrap_or(decoded_at)
700				};
701				let timestamp = r.output_at(held)?;
702				let pcm = r.process(&decoded, decoded_at)?;
703				(pcm, timestamp)
704			}
705			None => (decoded, decoded_at),
706		};
707
708		let decoded_end = advance(decoded_at, frames, rate)?;
709
710		// The resampler hands back samples it was holding from earlier packets,
711		// so what comes out starts before the packet that filled its chunk. Track
712		// where each packet's activity ends so the output can be labelled by
713		// where it actually begins, not by the packet just submitted.
714		let resampled = self.resampler.is_some();
715		if resampled {
716			self.spans.push_back(ActivitySpan {
717				end: decoded_end,
718				activity,
719			});
720		}
721
722		// A packet shorter than the resampler's chunk leaves nothing to hand
723		// over yet. Read on rather than returning a frame with no samples, which
724		// a caller would otherwise see as audio arriving.
725		if pcm.is_empty() {
726			return Ok(());
727		}
728
729		let activity = if resampled {
730			self.activity_at(timestamp)
731		} else {
732			activity
733		};
734		// Queued rather than returned, so a tail drained at a gap earlier in this
735		// same iteration still comes out first. The next turn of the loop pops it.
736		if let Some(frame) = self.frame(pcm, timestamp, activity)? {
737			self.ready.push_back(Read::Frame(frame));
738		}
739		Ok(())
740	}
741
742	/// The next packet or boundary the gate admits, reading and observing every packet
743	/// that arrives meanwhile, or `None` once the track ends.
744	async fn next(&mut self) -> Result<Option<Encoded>, Error> {
745		loop {
746			// The subscription states the playout delay as its min, where a join starts; the
747			// container gives a missing group up by the max delay alone. Checked before every poll,
748			// since each arrival and each decoded frame can move it; the estimate moves in whole
749			// buckets, so each move is one update.
750			if self.stated != self.delay() {
751				self.stated = self.delay();
752				self.track.set_delay(self.stated());
753			}
754			// Read before judging the head, so any update after that wakes the wait.
755			let seen = self.gate.as_ref().map_or(0, |gate| gate.read().version);
756			let deadline = match self.pending.front() {
757				Some((Encoded::Frame { frame, .. }, arrived)) => {
758					match self.admit(Duration::try_from(frame.timestamp)?, *arrived) {
759						None => return Ok(self.pop()),
760						due => due,
761					}
762				}
763				Some(_) => return Ok(self.pop()),
764				None => match self.ended.as_mut() {
765					Some(failed) => return failed.take().map_or(Ok(None), Err),
766					None => None,
767				},
768			};
769
770			let gate = self.gate.as_ref().filter(|gate| !gate.is_closed());
771			let mut sleep = std::pin::pin!(deadline.map(kio::clock::sleep_until));
772			let track = &mut self.track;
773			let ended = self.ended.is_some();
774			let read = kio::wait(|waiter| {
775				if !ended && let Poll::Ready(read) = track.poll_read(waiter) {
776					return Poll::Ready(Some(read));
777				}
778				if let Some(gate) = gate
779					&& gate
780						.poll(waiter, |state| match state.version != seen {
781							true => Poll::Ready(()),
782							false => Poll::Pending,
783						})
784						.is_ready()
785				{
786					return Poll::Ready(None);
787				}
788				if let Some(sleep) = sleep.as_mut().as_pin_mut()
789					&& waiter.poll_future(sleep).is_ready()
790				{
791					return Poll::Ready(None);
792				}
793				Poll::Pending
794			})
795			.await;
796
797			match read {
798				// A scale-less track carries group keys, not times, so there is nothing to place.
799				Some(Ok(Some(Encoded::Frame { frame, .. }))) if frame.timestamp.scale().is_none() => {
800					self.ended = Some(Some(moq_net::Error::TimestampMismatch.into()));
801				}
802				Some(Ok(Some(read))) => {
803					// The estimator times arrivals, so it learns of a declared silence as the
804					// packets around it arrive rather than as they decode. The end's own group
805					// carries the stopped encoder's final packets, which end the speech before
806					// the silence, so only a later group, or a loss, says the silence it
807					// measures across was declared. A loss forgets the end, but the silence
808					// across it stays declared.
809					match &read {
810						Encoded::End { group, .. } => self.declared = Some(*group),
811						Encoded::Frame { group, .. } if self.declared.is_some_and(|end| end != *group) => {
812							self.declared = None;
813							self.target.end();
814						}
815						Encoded::Gap { .. } if self.declared.take().is_some() => self.target.end(),
816						_ => {}
817					}
818					// A backlog group the container dropped unread is never observed, so the
819					// estimator learns when it arrived instead: a join lasts until its skipped
820					// backlog has.
821					if let Some(backlog) = self.track.backlog() {
822						self.target.backlog(jitter::millis(backlog.duration_since(self.origin)));
823					}
824					// Every packet the container hands over is an arrival, including one the
825					// decoder will refuse, so it is observed before anything can fail.
826					// When the packet landed, not when it was read: a hole the container waits out
827					// holds the packets behind it, which arrived on time. The estimator and the
828					// gate's hold both count from it.
829					let landed = self.track.arrival().unwrap_or_else(now);
830					match &read {
831						Encoded::Frame { frame, .. } => {
832							if let Some(scale) = frame.timestamp.scale() {
833								let arrival = jitter::millis(landed.duration_since(self.origin));
834								let media = frame.timestamp.value() as f64 * 1000.0 / scale.as_u64() as f64;
835								self.target.observe(arrival, media);
836							}
837						}
838						_ => self.breaks += 1,
839					}
840					self.pending.push_back((read, landed));
841				}
842				Some(Ok(None)) => self.ended = Some(None),
843				Some(Err(err)) => self.ended = Some(Some(err.into())),
844				None => {}
845			}
846			if self.ended.is_some() {
847				self.control = None;
848			}
849		}
850	}
851
852	/// Take the oldest pending packet or boundary.
853	fn pop(&mut self) -> Option<Encoded> {
854		let (read, arrived) = self.pending.pop_front()?;
855		match read {
856			Encoded::Frame { .. } => self.arrived = Some(arrived),
857			_ => self.breaks -= 1,
858		}
859		Some(read)
860	}
861
862	/// When the pending packet at `timestamp`, which arrived at `arrived`, may decode, or
863	/// `None` if it may now.
864	fn admit(&self, timestamp: Duration, arrived: kio::clock::Instant) -> Option<kio::clock::Instant> {
865		let gate = self.gate.as_ref().filter(|gate| !gate.is_closed())?;
866		let state = gate.read();
867		if state.hold.is_zero() || self.ended.is_some() {
868			return None;
869		}
870		// Media queued behind the packet covers the hold, or nothing more continues it.
871		let covered = self.breaks > 0
872			|| matches!(self.pending.back(), Some((Encoded::Frame { frame, .. }, _))
873				if Duration::try_from(frame.timestamp).is_ok_and(|end| end >= timestamp + state.hold));
874		if covered {
875			return None;
876		}
877
878		// A packet waits at most the hold, which bounds what the gate keeps by arrival time,
879		// whatever the timestamps say.
880		let mut due = arrived.checked_add(state.hold);
881		let boundary = self.boundary;
882		if let Some((playhead, at)) = state
883			.playhead
884			.filter(|(playhead, _)| boundary.is_none_or(|boundary| *playhead > boundary))
885		{
886			// Due once the playhead is within the floor of where this packet's output ends.
887			let end = timestamp + self.frame;
888			let reach = playhead + state.floor;
889			let played = match end.checked_sub(reach) {
890				Some(ahead) => at.checked_add(ahead),
891				// Before the clock's origin is long past, so it decodes now.
892				None => Some(at.checked_sub(reach - end)?),
893			};
894			due = due.into_iter().chain(played).min();
895		}
896		// Past the clock's range never comes, so decode now rather than hold it forever.
897		due.filter(|due| *due > kio::clock::Instant::now())
898	}
899
900	/// Start a new timeline after a gap or past a declared end. The decoder is not reset:
901	/// the next group already starts on a keyframe, and the history it keeps primes the
902	/// packets after the break, so a gap trims no more warmup than the decoder still lacks,
903	/// and no pre-skip, which only a fresh encoder starts with.
904	///
905	/// Samples the resampler still holds arrived before the break, so they are drained
906	/// as their own frame first rather than filtered together with what follows it.
907	fn restart(&mut self) -> Result<(), Error> {
908		if let Some(frame) = self.drain()? {
909			self.ready.push_back(Read::Frame(frame));
910		}
911		self.next_start = None;
912		self.spans.clear();
913		self.trailing = Activity::Active;
914		self.frames_decoded = 0;
915		self.end = None;
916		self.terminal_start = None;
917		self.epoch = None;
918		self.delay_trimmed = 0;
919		self.warmup_until = None;
920		Ok(())
921	}
922
923	/// Expect a fresh encoder's packets: its pre-skip is trimmed again, and the stopped
924	/// encoder's history primes none of its warmup. Its first packet needs no warmup either, so
925	/// one a join or a gap left pending is dropped.
926	fn fresh_encoder(&mut self) {
927		self.decoder.reapply_delay();
928		self.primed = Duration::ZERO;
929		self.warmup_pending = false;
930	}
931
932	/// Reset resampling state at a hole, returning whatever the resampler was still
933	/// holding from before it.
934	///
935	/// Those samples arrived before the hole and belong before it, so they come
936	/// out as their own frame rather than being filtered together with the audio
937	/// on the far side. The resampler starts over from there, which is what makes
938	/// the next packet's output stamp from the packet itself: nothing is buffered
939	/// to reach back over. The codec keeps its history, which primes the packets
940	/// after the hole as a pre-roll would.
941	fn gap(&mut self) -> Result<Option<Frame>, Error> {
942		let frame = self.drain()?;
943
944		self.next_start = None;
945		self.spans.clear();
946		self.trailing = Activity::Active;
947		self.epoch = None;
948		self.delay_trimmed = 0;
949		self.warmup_pending = !self.warmup.is_zero();
950		self.warmup_until = None;
951		Ok(frame)
952	}
953
954	/// Drain what the resampler holds while keeping it for what follows.
955	fn drain(&mut self) -> Result<Option<Frame>, Error> {
956		let Some(resampler) = self.resampler.as_mut() else {
957			return Ok(None);
958		};
959		let timestamp = resampler.held_at().map(|held| resampler.output_at(held)).transpose()?;
960		let pcm = resampler.drain()?;
961		self.tail(pcm, timestamp)
962	}
963
964	/// The tail the resampler is still holding when the track ends, once.
965	///
966	/// Without it the last partial chunk is dropped, which is up to a chunk of
967	/// audio missing from the end of every resampled track. Flushing consumes the
968	/// resampler, which is what makes calling this on every later poll return
969	/// `None` rather than more tails.
970	fn flush(&mut self) -> Result<Option<Frame>, Error> {
971		let Some(resampler) = self.resampler.take() else {
972			return Ok(None);
973		};
974
975		let timestamp = resampler.held_at().map(|held| resampler.output_at(held)).transpose()?;
976		self.tail(resampler.flush()?, timestamp)
977	}
978
979	/// Stamp and pack a tail the resampler handed back, if it handed back one.
980	///
981	/// `timestamp` includes the filter's retained fractional phase. `None` means
982	/// the resampler never ran, so there is nothing to place.
983	fn tail(&mut self, pcm: Vec<f32>, timestamp: Option<moq_net::Timestamp>) -> Result<Option<Frame>, Error> {
984		let Some(timestamp) = timestamp.filter(|_| !pcm.is_empty()) else {
985			return Ok(None);
986		};
987
988		let activity = self.activity_at(timestamp);
989		self.frame(pcm, timestamp, activity)
990	}
991
992	/// The codec activity covering `timestamp`, dropping the spans it has passed.
993	fn activity_at(&mut self, timestamp: moq_net::Timestamp) -> Activity {
994		while let Some(span) = self.spans.front().filter(|span| span.end <= timestamp) {
995			self.trailing = span.activity;
996			self.spans.pop_front();
997		}
998
999		self.spans.front().map_or(self.trailing, |span| span.activity)
1000	}
1001
1002	/// Remix and pack decoded PCM into an output frame.
1003	fn frame(
1004		&self,
1005		mut pcm: Vec<f32>,
1006		mut timestamp: moq_net::Timestamp,
1007		activity: Activity,
1008	) -> Result<Option<Frame>, Error> {
1009		// Warmup must prime the resampler too; trim only what reaches presentation.
1010		if let Some(until) = self.warmup_until
1011			&& timestamp < until
1012		{
1013			let channels = self.decoder.layout().channels() as usize;
1014			let frames = pcm.len() / channels;
1015			let duration = Duration::try_from(until.checked_sub(timestamp)?)?;
1016			let trim = (duration.as_nanos() * u128::from(self.resolved_sample_rate)).div_ceil(1_000_000_000);
1017			let trim = usize::try_from(trim).unwrap_or(usize::MAX).min(frames);
1018			pcm.drain(..trim * channels);
1019			timestamp = advance(timestamp, trim, self.resolved_sample_rate)?;
1020		}
1021		if pcm.is_empty() {
1022			return Ok(None);
1023		}
1024		let pcm = match &self.remix {
1025			Some(remix) => remix.process(&pcm),
1026			None => pcm,
1027		};
1028
1029		let bytes = self
1030			.options
1031			.output
1032			.format
1033			.from_interleaved_f32(&pcm, self.resolved_layout.channels())?;
1034		Ok(Some(Frame {
1035			timestamp,
1036			data: Bytes::from(bytes),
1037			activity,
1038		}))
1039	}
1040}
1041
1042/// The receiver's monotonic clock.
1043fn now() -> Instant {
1044	Instant::now()
1045}
1046
1047/// Whether `timestamp` fails to continue `expected`, leaving a hole (or an
1048/// overlap) rather than the next packet in line.
1049///
1050/// Exact contiguity cannot be the test. RTMP stamps in whole milliseconds while a
1051/// 1024-sample AAC frame at 44.1 kHz runs 23.22 ms, so on the most common ingest
1052/// path every packet lands beside where its predecessor ended.
1053///
1054/// The slack is the quantization the stamps carry, and nothing else. A frame
1055/// duration would be far too much: a single lost packet lands exactly one frame
1056/// off, and Opus packets run anywhere from 2.5 ms to 60 ms with no duration
1057/// declared in the catalog, so a half-frame rule read off a 20 ms neighbour would
1058/// splice straight across a lost 2.5 ms one.
1059///
1060/// So a packet is discontinuous when it misses `expected` by more than one unit of
1061/// the coarsest timescale on the path, plus one unit of the stamp's own scale for
1062/// the rounding in the arithmetic that produced `expected`. The coarsest timescale
1063/// is the stamp's own scale floored at [`Timescale::MILLI`](moq_net::Timescale::MILLI):
1064/// the legacy hang container re-stamps every frame in microseconds whatever the
1065/// source used, and a wire that cannot carry a timescale at all (moq-lite before
1066/// 05, IETF moq-transport) falls back to milliseconds, so a millisecond is the
1067/// finest quantization a packet can be assumed to have kept. That floor stays under
1068/// the shortest packet anything here can send, 2.5 ms of Opus, so it never
1069/// swallows a lost one.
1070fn discontinuous(expected: moq_net::Timestamp, timestamp: moq_net::Timestamp) -> Result<bool, Error> {
1071	let unscaled = moq_net::TimeOverflow;
1072	let scale = expected
1073		.scale()
1074		.ok_or(unscaled)?
1075		.max(timestamp.scale().ok_or(unscaled)?);
1076	let quantum = scale.min(moq_net::Timescale::MILLI);
1077	let tolerance = (scale.as_u64() as u128).div_ceil(quantum.as_u64() as u128) + 1;
1078	Ok(expected.as_scale(scale)?.abs_diff(timestamp.as_scale(scale)?) > tolerance)
1079}
1080
1081/// Where a gap from `timestamp` lasting `duration` resumes, in the timestamp's scale.
1082///
1083/// The span came from whole ticks of that scale, truncated to nanoseconds, so rounding it up
1084/// recovers them exactly for any scale no finer than a nanosecond.
1085fn resume(timestamp: moq_net::Timestamp, duration: Duration) -> Result<moq_net::Timestamp, Error> {
1086	let scale = timestamp.scale().ok_or(moq_net::TimeOverflow)?;
1087	let ticks = (duration.as_nanos() * scale.as_u64() as u128).div_ceil(1_000_000_000);
1088	let ticks = u64::try_from(ticks).map_err(|_| moq_net::TimeOverflow)?;
1089	Ok(timestamp.checked_add(moq_net::Timestamp::new(ticks, scale)?)?)
1090}
1091
1092/// The later of two timestamps on one timeline, `a` when they don't compare.
1093fn later(a: moq_net::Timestamp, b: moq_net::Timestamp) -> moq_net::Timestamp {
1094	if b > a { b } else { a }
1095}
1096
1097/// The earlier of two timestamps on one timeline, `a` when they don't compare.
1098fn earlier(a: moq_net::Timestamp, b: moq_net::Timestamp) -> moq_net::Timestamp {
1099	if b < a { b } else { a }
1100}
1101
1102/// `timestamp` moved forward by `frames` at `sample_rate`, in its own timescale.
1103fn advance(timestamp: moq_net::Timestamp, frames: usize, sample_rate: u32) -> Result<moq_net::Timestamp, Error> {
1104	if frames == 0 {
1105		return Ok(timestamp);
1106	}
1107
1108	let offset = moq_net::Timestamp::from_scale(frames as u64, sample_rate as u64)?
1109		.convert(timestamp.scale().ok_or(moq_net::TimeOverflow)?)?;
1110	Ok(timestamp.checked_add(offset)?)
1111}
1112
1113/// Codec-rate frames in the interval, rounding a microsecond marker to the nearest frame.
1114fn frames_between(start: moq_net::Timestamp, end: moq_net::Timestamp, sample_rate: u32) -> Result<usize, Error> {
1115	let duration = end.checked_sub(start)?;
1116	let frames =
1117		(std::time::Duration::try_from(duration)?.as_nanos() * sample_rate as u128 + 500_000_000) / 1_000_000_000;
1118	usize::try_from(frames).map_err(|_| Error::Unsupported("audio duration does not fit in memory".into()))
1119}
1120
1121/// `timestamp` moved back by `frames` at `sample_rate`, in its own timescale.
1122///
1123/// Saturates at zero rather than failing: a publisher whose first timestamps
1124/// don't advance is odd, but it isn't a reason to end the track.
1125fn rewind(timestamp: moq_net::Timestamp, frames: usize, sample_rate: u32) -> Result<moq_net::Timestamp, Error> {
1126	if frames == 0 {
1127		return Ok(timestamp);
1128	}
1129
1130	let scale = timestamp.scale().ok_or(moq_net::TimeOverflow)?;
1131	let offset = moq_net::Timestamp::from_scale(frames as u64, sample_rate as u64)?.convert(scale)?;
1132	Ok(timestamp
1133		.checked_sub(offset)
1134		.unwrap_or(moq_net::Timestamp::new(0, scale)?))
1135}
1136
1137#[cfg(test)]
1138mod tests {
1139	async fn next_frame(consumer: &mut Consumer) -> Result<Option<Frame>, Error> {
1140		loop {
1141			match consumer.read().await? {
1142				Some(Read::Frame(frame)) => return Ok(Some(frame)),
1143				Some(Read::Gap { .. } | Read::End { .. }) => {}
1144				None => return Ok(None),
1145			}
1146		}
1147	}
1148
1149	use moq_net::Timestamp;
1150
1151	use super::*;
1152	use crate::encode::{Config as EncodeConfig, Encoder, Input, Options as EncodeOptions, Producer};
1153	use crate::{Format, Layout};
1154
1155	/// A gap's span, truncated to nanoseconds, resumes on the exact tick it was measured to, for
1156	/// every scale from seconds to nanoseconds and spans that leave a fraction of a nanosecond.
1157	#[test]
1158	fn a_gap_resumes_on_its_exact_tick() {
1159		for scale in [1, 1_000, 44_100, 48_000, 90_000, 1_000_000_000] {
1160			let scale = moq_net::Timescale::new(scale).unwrap();
1161			let start = Timestamp::new(12_345, scale).unwrap();
1162			for ticks in [0, 1, 2, 3, 1_023, 1_024, 48_000, 90_001, 1 << 40] {
1163				let span = Duration::try_from(Timestamp::new(ticks, scale).unwrap()).unwrap();
1164				let expected = start.checked_add(Timestamp::new(ticks, scale).unwrap()).unwrap();
1165				assert_eq!(resume(start, span).unwrap(), expected, "{ticks} ticks at {scale:?}");
1166			}
1167		}
1168	}
1169
1170	/// The staleness budget of `subscription`'s one live join.
1171	fn live_max(subscription: &moq_net::track::Subscription) -> Option<Duration> {
1172		match subscription.ranges.as_slice() {
1173			[
1174				moq_net::track::Range {
1175					start: moq_net::track::Start::Live { max, .. },
1176					..
1177				},
1178			] => *max,
1179			ranges => panic!("expected one live join, got {ranges:?}"),
1180		}
1181	}
1182
1183	/// The first request already states the min and max delay, each plus the warmup: a latest
1184	/// start waits for the live edge with its subscription open, before the container could
1185	/// update it.
1186	#[kio::test]
1187	async fn the_first_subscription_states_the_min_delay() {
1188		let broadcast = moq_net::broadcast::Info::new().produce();
1189		let mut track = broadcast
1190			.create_track("audio", hang::container::track_info(hang::catalog::PRIORITY.audio))
1191			.unwrap();
1192		let mut catalog = hang::catalog::AudioConfig::new(hang::catalog::AudioCodec::Pcm, 48_000, 1);
1193		catalog.warmup = Some(Duration::from_millis(100));
1194		let delay = Delay {
1195			min: Some(Duration::from_millis(300)),
1196			max: Some(Duration::from_millis(500)),
1197		};
1198		let consume = broadcast.consume();
1199		let mut open = Box::pin(Consumer::new(
1200			&consume,
1201			&catalog,
1202			"audio",
1203			Options {
1204				start: Start::Latest,
1205				delay,
1206				..Default::default()
1207			},
1208		));
1209		// The open waits for the live edge with its subscription open, so the first aggregate
1210		// the publisher sees is the request itself.
1211		let first = tokio::select! {
1212			opened = &mut open => panic!("the open finished with no live edge (ok: {})", opened.is_ok()),
1213			first = track.subscription_changed() => first.unwrap(),
1214		};
1215		assert_eq!(
1216			first.map(|sub| sub.ranges),
1217			Some(vec![
1218				moq_net::track::Range::from(moq_net::track::Start::Live {
1219					min: Some(Duration::from_millis(400)),
1220					max: Some(Duration::from_millis(600)),
1221				})
1222				.with_priority(hang::catalog::PRIORITY.audio)
1223			])
1224		);
1225	}
1226
1227	/// The priority reaches the publisher's aggregate subscription at hang's audio default, and a
1228	/// change moves that subscription in place, keeping the moved delay with it.
1229	#[tokio::test(start_paused = true)]
1230	async fn priority_reaches_the_subscription_and_moves_in_place() {
1231		let broadcast = moq_net::broadcast::Info::new().produce();
1232		let track = broadcast
1233			.create_track("audio", hang::container::track_info(hang::catalog::PRIORITY.audio))
1234			.unwrap();
1235		let catalog = hang::catalog::AudioConfig::new(hang::catalog::AudioCodec::Pcm, 48_000, 1);
1236		let mut consumer = Consumer::new(&broadcast.consume(), &catalog, "audio", Options::new())
1237			.await
1238			.unwrap();
1239		assert_eq!(
1240			track.subscription().map(|sub| sub.ranges[0].priority),
1241			Some(hang::catalog::PRIORITY.audio)
1242		);
1243
1244		consumer.set_priority(-20);
1245		assert_eq!(consumer.options().priority, -20);
1246		assert_eq!(track.subscription().map(|sub| sub.ranges[0].priority), Some(-20));
1247
1248		// A later delay change rewrites the subscription without undoing the priority.
1249		consumer.set_max_delay(Duration::from_secs(2));
1250		let subscription = track.subscription().unwrap();
1251		assert_eq!(subscription.ranges[0].priority, -20);
1252		assert_eq!(live_max(&subscription), Some(Duration::from_secs(2)));
1253	}
1254
1255	/// A moved max delay reaches the subscription, plus the warmup, clamped to the max age.
1256	#[tokio::test(start_paused = true)]
1257	async fn a_moved_max_delay_reaches_the_subscription() {
1258		let broadcast = moq_net::broadcast::Info::new().produce();
1259		let track = broadcast
1260			.create_track(
1261				"audio",
1262				hang::container::track_info(hang::catalog::PRIORITY.audio).with_max_age(Duration::from_secs(5)),
1263			)
1264			.unwrap();
1265		let mut catalog = hang::catalog::AudioConfig::new(hang::catalog::AudioCodec::Pcm, 48_000, 1);
1266		catalog.warmup = Some(Duration::from_millis(100));
1267		let mut consumer = Consumer::new(
1268			&broadcast.consume(),
1269			&catalog,
1270			"audio",
1271			Options {
1272				delay: Delay {
1273					max: Some(Duration::from_millis(500)),
1274					..Delay::default()
1275				},
1276				..Options::new()
1277			},
1278		)
1279		.await
1280		.unwrap();
1281		assert_eq!(consumer.max_delay(), Duration::from_millis(500));
1282
1283		consumer.set_max_delay(Duration::from_secs(2));
1284		assert_eq!(consumer.max_delay(), Duration::from_secs(2));
1285		assert_eq!(
1286			live_max(&track.subscription().unwrap()),
1287			Some(Duration::from_millis(2_100))
1288		);
1289
1290		consumer.set_max_delay(Duration::from_secs(9));
1291		assert_eq!(consumer.max_delay(), Duration::from_secs(5));
1292	}
1293
1294	/// A history subscription reads every group in order, so a moved max delay leaves it, and the
1295	/// budget it reports, as they were.
1296	#[tokio::test(start_paused = true)]
1297	async fn a_history_subscription_ignores_a_moved_max_delay() {
1298		let broadcast = moq_net::broadcast::Info::new().produce();
1299		let track = broadcast
1300			.create_track("audio", hang::container::track_info(hang::catalog::PRIORITY.audio))
1301			.unwrap();
1302		let catalog = hang::catalog::AudioConfig::new(hang::catalog::AudioCodec::Pcm, 48_000, 1);
1303		let mut consumer = Consumer::new(
1304			&broadcast.consume(),
1305			&catalog,
1306			"audio",
1307			Options {
1308				start: Start::Oldest,
1309				delay: Delay {
1310					max: None,
1311					..Delay::default()
1312				},
1313				..Options::new()
1314			},
1315		)
1316		.await
1317		.unwrap();
1318		let before = track.subscription().unwrap();
1319		let budget = consumer.max_delay();
1320		consumer.set_max_delay(Duration::ZERO);
1321		assert_eq!(consumer.options().delay.max, None);
1322		assert_eq!(consumer.max_delay(), budget);
1323		assert_eq!(track.subscription().unwrap(), before);
1324	}
1325
1326	#[tokio::test(start_paused = true)]
1327	async fn conversion_waits_for_decoded_samples() {
1328		for (rate, channels) in [(44_100, 1), (4_000_000_000, 8), (48_000, u32::MAX)] {
1329			let broadcast = moq_net::broadcast::Info::new().produce();
1330			let _track = broadcast
1331				.create_track("audio", hang::container::track_info(hang::catalog::PRIORITY.audio))
1332				.unwrap();
1333			let catalog = hang::catalog::AudioConfig::new(hang::catalog::AudioCodec::Pcm, rate, channels);
1334			let consumer = Consumer::new(
1335				&broadcast.consume(),
1336				&catalog,
1337				"audio",
1338				Options {
1339					output: Output {
1340						sample_rate: Some(96_000),
1341						..Default::default()
1342					},
1343					..Default::default()
1344				},
1345			)
1346			.await
1347			.unwrap();
1348			assert!(consumer.resampler.is_none(), "catalog allocated the resampler");
1349		}
1350	}
1351
1352	#[tokio::test(start_paused = true)]
1353	async fn conversion_allocation_is_bounded_after_data_arrives() {
1354		use std::future::Future;
1355		use std::task::{Context, Poll};
1356
1357		let mut baseline = None;
1358		for rate in [96_000, 4_000_000_000] {
1359			let broadcast = moq_net::broadcast::Info::new().produce();
1360			let track = broadcast
1361				.create_track("audio", hang::container::track_info(hang::catalog::PRIORITY.audio))
1362				.unwrap();
1363			let catalog = hang::catalog::AudioConfig::new(hang::catalog::AudioCodec::Pcm, rate, 8);
1364			let mut producer = moq_mux::container::Producer::new(
1365				track,
1366				moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Audio),
1367			);
1368			let mut consumer = Consumer::new(
1369				&broadcast.consume(),
1370				&catalog,
1371				"audio",
1372				Options {
1373					output: Output {
1374						sample_rate: Some(48_000),
1375						..Default::default()
1376					},
1377					..Default::default()
1378				},
1379			)
1380			.await
1381			.unwrap();
1382			producer
1383				.write(moq_mux::container::Frame {
1384					timestamp: Timestamp::ZERO,
1385					decode: None,
1386					duration: None,
1387					payload: vec![0; 4].into(),
1388					keyframe: true,
1389				})
1390				.unwrap();
1391			assert!(matches!(consumer.read().await, Err(Error::Misaligned { .. })));
1392			assert!(consumer.resampler.is_none(), "a refused packet allocated the resampler");
1393			producer
1394				.write(moq_mux::container::Frame {
1395					timestamp: Timestamp::ZERO,
1396					decode: None,
1397					duration: None,
1398					payload: vec![0; 960 * 8 * 4].into(),
1399					keyframe: true,
1400				})
1401				.unwrap();
1402			let (read, stats) = crate::allocation::measure(|| {
1403				let mut read = std::pin::pin!(consumer.read());
1404				read.as_mut().poll(&mut Context::from_waker(std::task::Waker::noop()))
1405			});
1406			assert!(!matches!(read, Poll::Ready(Err(_))), "{read:?}");
1407			assert!(consumer.resampler.is_some());
1408			let baseline = *baseline.get_or_insert(stats.bytes);
1409			assert!(
1410				stats.bytes <= baseline,
1411				"{rate} Hz allocated {} bytes, baseline {baseline}",
1412				stats.bytes
1413			);
1414		}
1415	}
1416
1417	/// How the timeline breaks between `warmup_output`'s two runs of packets.
1418	#[derive(Clone, Copy, Debug)]
1419	enum Break {
1420		/// A declared end, so a fresh encoder follows.
1421		Declared,
1422		/// A lost group: a seek opens the next without declaring the starts before it skipped.
1423		Lost,
1424		/// A timestamp jump across contiguous groups.
1425		Undeclared,
1426		/// A declared end, then a seek past the starts after it, as a wire before lite-07 delivers
1427		/// the run a publisher skipped across a pause.
1428		DeclaredGap,
1429	}
1430
1431	/// Decodes `first` packets, then six more a second later, past a `cut` in the timeline. The
1432	/// first run starts a second in, joined mid-stream.
1433	async fn warmup_output(cut: Break, first: u64) -> (Vec<u128>, usize) {
1434		let broadcast = moq_net::broadcast::Info::new().produce();
1435		let track = broadcast
1436			.create_track("audio", hang::container::track_info(hang::catalog::PRIORITY.audio))
1437			.unwrap();
1438		let mut catalog = hang::catalog::AudioConfig::new(hang::catalog::AudioCodec::Pcm, 48_000, 1);
1439		catalog.warmup = Some(Duration::from_millis(80));
1440		let mut producer = moq_mux::container::Producer::new(
1441			track.clone(),
1442			moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Audio),
1443		);
1444		let payload = Bytes::from(vec![0; 960 * size_of::<f32>()]);
1445		// Joined during a pause: the reader's first group is the end marker of what came before.
1446		if first == 0 {
1447			create_packet(&track, Timestamp::from_micros(1_000_000).unwrap(), Bytes::new());
1448		}
1449		for epoch in 1..3 {
1450			// Created rather than appended, so nothing declares the starts below it skipped: the
1451			// run's first packet is joined mid-stream, and one after a cut follows lost groups.
1452			let mut created = epoch == 1 && first > 0;
1453			if epoch != 1 {
1454				match cut {
1455					Break::Declared => producer.discontinuity().unwrap(),
1456					Break::Lost => created = true,
1457					Break::Undeclared => {}
1458					Break::DeclaredGap => {
1459						producer.discontinuity().unwrap();
1460						created = true;
1461					}
1462				}
1463			}
1464			for packet in 0..if epoch == 1 { first } else { 6 } {
1465				let timestamp = Timestamp::from_micros(epoch * 1_000_000 + packet * 20_000).unwrap();
1466				if std::mem::take(&mut created) {
1467					create_packet(&track, timestamp, payload.clone());
1468					continue;
1469				}
1470				producer
1471					.write(moq_mux::container::Frame {
1472						timestamp,
1473						decode: None,
1474						duration: None,
1475						payload: payload.clone(),
1476						keyframe: true,
1477					})
1478					.unwrap();
1479				producer.cut(None).unwrap();
1480			}
1481		}
1482		let _finished = producer.finish().unwrap();
1483		let mut consumer = Consumer::new(
1484			&broadcast.consume(),
1485			&catalog,
1486			"audio",
1487			Options {
1488				delay: Delay {
1489					max: Some(Duration::from_secs(10)),
1490					..Delay::default()
1491				},
1492				..Options::new()
1493			},
1494		)
1495		.await
1496		.unwrap();
1497		let mut stamps = Vec::new();
1498		let mut frames = 0;
1499		while let Some(frame) = next_frame(&mut consumer).await.unwrap() {
1500			stamps.push(frame.timestamp.as_micros().unwrap());
1501			frames += frame.data.len() / size_of::<f32>();
1502		}
1503		(stamps, frames)
1504	}
1505
1506	/// Publish one Legacy audio packet as its own group, created rather than appended so the
1507	/// starts below it stay unproduced: a reader joins it mid-stream, or reads what lies between
1508	/// as lost. An empty `payload` is an end marker.
1509	fn create_packet(track: &moq_net::track::Producer, timestamp: Timestamp, payload: Bytes) {
1510		let mut buf = bytes::BytesMut::new();
1511		hang::container::Frame { timestamp, payload }.encode(&mut buf).unwrap();
1512		track
1513			.create_group(moq_net::frame::Frame::new(timestamp, buf.freeze()))
1514			.unwrap()
1515			.finish()
1516			.unwrap();
1517	}
1518
1519	/// [`create_packet`] of a 20 ms packet at `micros`, saying no group starts between it and the
1520	/// packet before it when `follows`, so only a packet that never arrives is a hole.
1521	fn create_spaced(track: &moq_net::track::Producer, micros: u64, follows: bool, payload: Bytes) {
1522		if follows {
1523			track.skip_groups(micros - 19_999..micros);
1524		}
1525		create_packet(track, Timestamp::from_micros(micros).unwrap(), payload);
1526	}
1527
1528	/// An origin, its driver spawned.
1529	fn origin() -> moq_net::origin::Producer {
1530		let config = moq_net::origin::Config::default();
1531		let (producer, driver) = moq_net::origin::Producer::new(config);
1532		tokio::spawn(moq_net::time::run(driver));
1533		producer
1534	}
1535
1536	/// A lite-07 session over memory carrying `from`'s broadcasts into `to`, open while held.
1537	async fn link(
1538		from: &moq_net::origin::Producer,
1539		to: &moq_net::origin::Producer,
1540	) -> (moq_net::Session, moq_net::Session) {
1541		use moq_net::transport::memory;
1542
1543		let version: moq_net::Version = "moq-lite-07-wip".parse().unwrap();
1544		let mut config = memory::Config::default();
1545		config.protocol = Some(version.alpn().to_string());
1546		let (client_transport, server_transport) = memory::pair(config);
1547		let client = moq_net::Client::new()
1548			.with_versions(version.into())
1549			.with_publisher(from.consume());
1550		let server = moq_net::Server::new()
1551			.with_versions(version.into())
1552			.with_subscriber(to.clone());
1553		tokio::join!(
1554			async {
1555				let (session, driver) = client
1556					.connect(moq_net::time::Instant::now(), client_transport)
1557					.await
1558					.unwrap();
1559				tokio::spawn(moq_net::time::run(driver));
1560				session
1561			},
1562			async {
1563				let (session, driver) = server
1564					.accept(moq_net::time::Instant::now(), server_transport)
1565					.await
1566					.unwrap();
1567				tokio::spawn(moq_net::time::run(driver));
1568				session
1569			}
1570		)
1571	}
1572
1573	/// A relay copy whose upstream subscription went idle keeps the groups it cached. A
1574	/// latest start waits for the copy to go live and joins at its live edge, rather than
1575	/// replaying that backlog.
1576	#[tokio::test(start_paused = true)]
1577	async fn latest_skips_a_warm_copys_backlog() {
1578		let publisher = origin();
1579		let broadcast = publisher
1580			.route("bcast", moq_net::origin::RouteOptions::hidden())
1581			.unwrap();
1582		let track = broadcast
1583			.broadcast()
1584			.create_track("audio", hang::container::track_info(hang::catalog::PRIORITY.audio))
1585			.unwrap();
1586		broadcast.announce().unwrap();
1587		let mut demand = track.demand();
1588		let mut producer = moq_mux::container::Producer::new(
1589			track,
1590			moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Audio),
1591		);
1592		let mut write = |packet: u64| {
1593			producer
1594				.write(moq_mux::container::Frame {
1595					timestamp: Timestamp::from_micros(packet * 20_000).unwrap(),
1596					decode: None,
1597					duration: None,
1598					payload: vec![0; 960 * size_of::<f32>()].into(),
1599					keyframe: true,
1600				})
1601				.unwrap();
1602			producer.cut(None).unwrap();
1603		};
1604		for packet in 0..4 {
1605			write(packet);
1606		}
1607
1608		let relay = origin();
1609		let _link = link(&publisher, &relay).await;
1610		let consumer = relay.consume();
1611		let remote = consumer
1612			.follow("bcast", None)
1613			.unwrap()
1614			.available()
1615			.await
1616			.unwrap()
1617			.unwrap();
1618
1619		// A first reader warms the relay's copy with every group.
1620		{
1621			let subscription = moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
1622				moq_net::track::Start::Live {
1623					min: Some(Duration::from_secs(10)),
1624					max: Some(Duration::from_secs(10)),
1625				},
1626			)]);
1627			let mut warm = remote.track("audio").unwrap().subscribe(subscription).await.unwrap();
1628			let mut groups = 0;
1629			while groups < 4 {
1630				warm.recv_group().await.unwrap().unwrap();
1631				groups += 1;
1632			}
1633		}
1634		// The relay cancels the unread upstream subscription; its copy keeps the groups.
1635		while demand.wanted_changed().await.unwrap() {}
1636		write(4);
1637
1638		let catalog = hang::catalog::AudioConfig::new(hang::catalog::AudioCodec::Pcm, 48_000, 1);
1639		let mut consumer = Consumer::new(
1640			&remote,
1641			&catalog,
1642			"audio",
1643			Options {
1644				start: Start::Latest,
1645				delay: Delay {
1646					max: Some(Duration::from_secs(10)),
1647					..Delay::default()
1648				},
1649				..Options::new()
1650			},
1651		)
1652		.await
1653		.unwrap();
1654		let frame = next_frame(&mut consumer).await.unwrap().unwrap();
1655		assert_eq!(frame.timestamp.as_micros().unwrap(), 80_000, "the backlog was replayed");
1656	}
1657
1658	/// A latest join with a warmup loses no group the publisher bursts before its first
1659	/// frame decodes. A join that put only the warmup on the wire, widening it once the
1660	/// first packet was read, let the publisher skip every group of such a burst a warmup
1661	/// behind its newest, a gap no later update recovers.
1662	#[tokio::test(start_paused = true)]
1663	async fn latest_loses_no_group_the_publisher_bursts_before_its_first_frame() {
1664		let publisher = origin();
1665		let broadcast = publisher
1666			.route("bcast", moq_net::origin::RouteOptions::hidden())
1667			.unwrap();
1668		let track = broadcast
1669			.broadcast()
1670			.create_track("audio", hang::container::track_info(hang::catalog::PRIORITY.audio))
1671			.unwrap();
1672		broadcast.announce().unwrap();
1673		let mut producer = moq_mux::container::Producer::new(
1674			track.clone(),
1675			moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Audio),
1676		);
1677		// One 20 ms packet per group, a second in.
1678		let at = |packet: u64| Timestamp::from_micros(1_000_000 + packet * 20_000).unwrap();
1679		let payload = Bytes::from(vec![0; 960 * size_of::<f32>()]);
1680		// Joined mid-stream: created rather than appended, so it isn't the track's first packet,
1681		// which needs no warmup.
1682		create_packet(&track, at(0), payload.clone());
1683		let mut write = |packet: u64| {
1684			producer
1685				.write(moq_mux::container::Frame {
1686					timestamp: at(packet),
1687					decode: None,
1688					duration: None,
1689					payload: payload.clone(),
1690					keyframe: true,
1691				})
1692				.unwrap();
1693			producer.cut(None).unwrap();
1694		};
1695
1696		let subscriber = origin();
1697		let _link = link(&publisher, &subscriber).await;
1698		let consumer = subscriber.consume();
1699		let remote = consumer
1700			.follow("bcast", None)
1701			.unwrap()
1702			.available()
1703			.await
1704			.unwrap()
1705			.unwrap();
1706
1707		let mut catalog = hang::catalog::AudioConfig::new(hang::catalog::AudioCodec::Pcm, 48_000, 1);
1708		catalog.warmup = Some(Duration::from_millis(80));
1709		let mut consumer = Consumer::new(
1710			&remote,
1711			&catalog,
1712			"audio",
1713			Options {
1714				start: Start::Latest,
1715				delay: Delay {
1716					max: Some(Duration::from_secs(1)),
1717					..Delay::default()
1718				},
1719				..Options::new()
1720			},
1721		)
1722		.await
1723		.unwrap();
1724
1725		// Written in one pass, before the publisher's session runs again.
1726		for packet in 1..=20 {
1727			write(packet);
1728		}
1729		let _finished = producer.finish().unwrap();
1730
1731		let mut stamps = Vec::new();
1732		while let Some(read) = consumer.read().await.unwrap() {
1733			match read {
1734				Read::Frame(frame) => stamps.push(frame.timestamp.as_micros().unwrap()),
1735				Read::Gap { timestamp, duration } => panic!("a gap of {duration:?} after {timestamp:?}"),
1736				Read::End { .. } => {}
1737			}
1738		}
1739		let expected: Vec<u128> = (4..=20).map(|packet| 1_000_000 + packet * 20_000).collect();
1740		assert_eq!(stamps, expected, "the burst reached the decoder whole");
1741	}
1742
1743	#[tokio::test(start_paused = true)]
1744	async fn the_join_trim_stops_at_the_warmup_ceiling() {
1745		let broadcast = moq_net::broadcast::Info::new().produce();
1746		let track = broadcast
1747			.create_track("audio", hang::container::track_info(hang::catalog::PRIORITY.audio))
1748			.unwrap();
1749		let mut catalog = hang::catalog::AudioConfig::new(hang::catalog::AudioCodec::Pcm, 48_000, 1);
1750		catalog.warmup = Some(Duration::from_secs(3600));
1751		let mut producer = moq_mux::container::Producer::new(
1752			track.clone(),
1753			moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Audio),
1754		);
1755		let ceiling = moq_mux::container::DELAY_MAX.as_micros() as u64;
1756		let payload = Bytes::from(vec![0; 960 * size_of::<f32>()]);
1757		// Joined mid-stream, a second in, then contiguous, so no gap re-arms the warmup.
1758		create_packet(&track, Timestamp::from_micros(1_000_000).unwrap(), payload.clone());
1759		for micros in (20_000..=ceiling).step_by(20_000) {
1760			producer
1761				.write(moq_mux::container::Frame {
1762					timestamp: Timestamp::from_micros(1_000_000 + micros).unwrap(),
1763					decode: None,
1764					duration: None,
1765					payload: payload.clone(),
1766					keyframe: true,
1767				})
1768				.unwrap();
1769			producer.cut(None).unwrap();
1770		}
1771		let _finished = producer.finish().unwrap();
1772		let options = Options {
1773			delay: Delay {
1774				max: Some(moq_mux::container::DELAY_MAX),
1775				..Delay::default()
1776			},
1777			..Options::new()
1778		};
1779		let mut consumer = Consumer::new(&broadcast.consume(), &catalog, "audio", options)
1780			.await
1781			.unwrap();
1782		let mut stamps = Vec::new();
1783		while let Some(frame) = next_frame(&mut consumer).await.unwrap() {
1784			stamps.push(frame.timestamp.as_micros().unwrap());
1785		}
1786		assert_eq!(
1787			stamps,
1788			[1_000_000 + ceiling as u128],
1789			"an hour of warmup trims only up to the ceiling"
1790		);
1791	}
1792
1793	#[tokio::test(start_paused = true)]
1794	async fn warmup_trims_the_join_without_trimming_groups_or_declared_returns() {
1795		let (stamps, frames) = warmup_output(Break::Declared, 6).await;
1796		assert_eq!(
1797			stamps,
1798			[
1799				1_080_000, 1_100_000, 2_000_000, 2_020_000, 2_040_000, 2_060_000, 2_080_000, 2_100_000
1800			]
1801		);
1802		assert_eq!(frames, 8 * 960);
1803	}
1804
1805	/// A join during a pause reaches a fresh encoder's first packet, which needs no warmup, past a
1806	/// gap or not.
1807	#[tokio::test(start_paused = true)]
1808	async fn a_join_during_a_pause_trims_no_warmup() {
1809		for cut in [Break::Declared, Break::DeclaredGap] {
1810			let (stamps, frames) = warmup_output(cut, 0).await;
1811			assert_eq!(
1812				stamps,
1813				[2_000_000, 2_020_000, 2_040_000, 2_060_000, 2_080_000, 2_100_000],
1814				"{cut:?}"
1815			);
1816			assert_eq!(frames, 6 * 960, "{cut:?}");
1817		}
1818	}
1819
1820	/// The codec's history primes it across a gap, so only the warmup it falls short of is trimmed.
1821	#[tokio::test(start_paused = true)]
1822	async fn a_gap_trims_the_warmup_the_history_leaves() {
1823		for cut in [Break::Lost, Break::Undeclared] {
1824			let (stamps, frames) = warmup_output(cut, 2).await;
1825			assert_eq!(stamps, [2_040_000, 2_060_000, 2_080_000, 2_100_000], "{cut:?}");
1826			assert_eq!(frames, 4 * 960, "{cut:?}");
1827			// A primed decoder trims nothing after the gap.
1828			let (stamps, _) = warmup_output(cut, 6).await;
1829			assert_eq!(
1830				stamps[2..],
1831				[2_000_000, 2_020_000, 2_040_000, 2_060_000, 2_080_000, 2_100_000],
1832				"{cut:?}"
1833			);
1834		}
1835	}
1836
1837	/// A latest join skips the cached backlog and primes the decoder on the live edge's own
1838	/// group, as any other join does, while asking the publisher for its whole budget: the
1839	/// transport enforces it too, so a narrower one would drop the groups queued behind a
1840	/// reader slow to take its first.
1841	#[tokio::test(start_paused = true)]
1842	async fn warmup_latest_joins_at_the_live_edge_with_its_whole_budget() {
1843		let broadcast = moq_net::broadcast::Info::new().produce();
1844		let track = broadcast
1845			.create_track("audio", hang::container::track_info(hang::catalog::PRIORITY.audio))
1846			.unwrap();
1847		let mut producer = moq_mux::container::Producer::new(
1848			track.clone(),
1849			moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Audio),
1850		);
1851		for (start, packets) in [(0, 5), (1_000_000, 6)] {
1852			for packet in 0..packets {
1853				producer
1854					.write(moq_mux::container::Frame {
1855						timestamp: Timestamp::from_micros(start + packet * 20_000).unwrap(),
1856						decode: None,
1857						duration: None,
1858						payload: vec![0; 960 * size_of::<f32>()].into(),
1859						keyframe: packet == 0,
1860					})
1861					.unwrap();
1862			}
1863			producer.cut(None).unwrap();
1864		}
1865		let _finished = producer.finish().unwrap();
1866
1867		let mut catalog = hang::catalog::AudioConfig::new(hang::catalog::AudioCodec::Pcm, 48_000, 1);
1868		catalog.warmup = Some(Duration::from_millis(80));
1869		let mut consumer = Consumer::new(
1870			&broadcast.consume(),
1871			&catalog,
1872			"audio",
1873			Options {
1874				start: Start::Latest,
1875				delay: Delay {
1876					max: Some(Duration::from_secs(10)),
1877					..Delay::default()
1878				},
1879				..Options::new()
1880			},
1881		)
1882		.await
1883		.unwrap();
1884		assert_eq!(
1885			live_max(&track.subscription().unwrap()),
1886			Some(Duration::from_millis(10_080))
1887		);
1888
1889		let mut stamps = Vec::new();
1890		while let Some(frame) = next_frame(&mut consumer).await.unwrap() {
1891			stamps.push(frame.timestamp.as_micros().unwrap());
1892		}
1893		assert_eq!(stamps, [1_080_000, 1_100_000]);
1894	}
1895
1896	#[tokio::test(start_paused = true)]
1897	async fn warmup_primes_the_resampler_before_presenting_samples() {
1898		let broadcast = moq_net::broadcast::Info::new().produce();
1899		let track = broadcast
1900			.create_track("audio", hang::container::track_info(hang::catalog::PRIORITY.audio))
1901			.unwrap();
1902		let mut catalog = hang::catalog::AudioConfig::new(hang::catalog::AudioCodec::Pcm, 48_000, 1);
1903		catalog.warmup = Some(Duration::from_millis(80));
1904		// Joined mid-stream: the track's first packet needs no warmup.
1905		create_packet(
1906			&track,
1907			Timestamp::from_micros(1_000_000).unwrap(),
1908			[0, 0, 0x80, 0x3e].repeat(7680).into(),
1909		);
1910		let _finished = track.finish().unwrap();
1911		let mut consumer = Consumer::new(
1912			&broadcast.consume(),
1913			&catalog,
1914			"audio",
1915			Options {
1916				delay: Delay {
1917					max: Some(Duration::from_secs(1)),
1918					..Delay::default()
1919				},
1920				output: Output {
1921					sample_rate: Some(44_100),
1922					..Output::default()
1923				},
1924				..Options::new()
1925			},
1926		)
1927		.await
1928		.unwrap();
1929		let frame = next_frame(&mut consumer).await.unwrap().unwrap();
1930		assert!(frame.timestamp.as_micros().unwrap() >= 1_080_000);
1931		let first = f32::from_le_bytes(frame.data[..4].try_into().unwrap());
1932		assert!(
1933			(first - 0.25).abs() < 0.0001,
1934			"the resampler must be converged too: {first}"
1935		);
1936	}
1937
1938	/// Decodes a finished track of `packets` 20 ms Opus packets in one group, from the track's
1939	/// start or `joined` mid-stream a second in, keeping the encoder's declared warmup, and
1940	/// returns the first frame's stamp and the frames decoded.
1941	async fn opus_track_output(joined: bool, packets: u64) -> (Option<u128>, usize) {
1942		let mut encoder = Encoder::new(&EncodeConfig::new(48_000, Layout::Mono)).unwrap();
1943		let catalog = encoder.catalog();
1944		assert_eq!(catalog.warmup, Some(Duration::from_millis(80)));
1945
1946		let broadcast = moq_net::broadcast::Info::new().produce();
1947		let track = broadcast
1948			.create_track("audio", hang::container::track_info(hang::catalog::PRIORITY.audio))
1949			.unwrap();
1950		let pcm = vec![0.25f32; encoder.frame_size()];
1951		let base = if joined { 48_000 } else { 0 };
1952		let mut group: Option<moq_net::group::Producer> = None;
1953		for packet in 0..packets {
1954			let frame = hang::container::Frame {
1955				timestamp: Timestamp::from_scale(base + packet * encoder.frame_size() as u64, 48_000).unwrap(),
1956				payload: crate::single(encoder.encode_all(&pcm).unwrap()).payload,
1957			};
1958			match group.as_mut() {
1959				Some(group) => frame.write_to(group).unwrap(),
1960				None => {
1961					let mut buf = bytes::BytesMut::new();
1962					frame.encode(&mut buf).unwrap();
1963					// Appending declares nothing below it, the track's start; a join is created.
1964					group = Some(match joined {
1965						true => track
1966							.create_group(moq_net::frame::Frame::new(frame.timestamp, buf.freeze()))
1967							.unwrap(),
1968						false => track
1969							.append_group(moq_net::frame::Frame::new(frame.timestamp, buf.freeze()))
1970							.unwrap(),
1971					});
1972				}
1973			}
1974		}
1975		group.unwrap().finish().unwrap();
1976		let _finished = track.finish().unwrap();
1977
1978		let mut consumer = Consumer::new(
1979			&broadcast.consume(),
1980			&catalog,
1981			"audio",
1982			Options {
1983				delay: Delay {
1984					max: Some(Duration::from_secs(10)),
1985					..Delay::default()
1986				},
1987				..Options::new()
1988			},
1989		)
1990		.await
1991		.unwrap();
1992		let (mut first, mut frames) = (None, 0);
1993		while let Some(frame) = next_frame(&mut consumer).await.unwrap() {
1994			first.get_or_insert(frame.timestamp.as_micros().unwrap());
1995			frames += frame.data.len() / size_of::<f32>();
1996		}
1997		(first, frames)
1998	}
1999
2000	/// Decoding from the track's first packet drops only the codec's pre-skip: the encoder
2001	/// started there, so there is no history to warm up from. A track shorter than the
2002	/// warmup still decodes.
2003	#[tokio::test(start_paused = true)]
2004	async fn the_tracks_first_packet_keeps_all_but_pre_skip() {
2005		assert_eq!(opus_track_output(false, 2).await, (Some(0), 2 * 960 - 312));
2006	}
2007
2008	/// A join past the track's first group still drops its warmup after the pre-skip.
2009	#[tokio::test(start_paused = true)]
2010	async fn a_mid_stream_join_drops_its_warmup() {
2011		assert_eq!(
2012			opus_track_output(true, 6).await,
2013			(Some(1_080_000), 6 * 960 - 312 - 3_840)
2014		);
2015	}
2016
2017	/// How [`opus_loss`] loses its packets.
2018	#[derive(Clone, Copy, Debug)]
2019	enum Loss {
2020		/// Their groups never arrive.
2021		Groups,
2022		/// Their groups are skipped from the sequence, so only the stamps jump.
2023		Stamps,
2024		/// The publisher declares an end first, then its groups never arrive.
2025		Declared,
2026	}
2027
2028	/// What [`opus_loss`] reads: frames as (start, samples, RMS) and gaps as (start, duration), in µs.
2029	#[derive(Debug, PartialEq)]
2030	enum Event {
2031		Frame(u128, usize, f32),
2032		Gap(u128, u128),
2033		End(u128),
2034	}
2035
2036	/// Publishes 20 packets of a 20 ms Opus sine, each its own group, losing the `lost`
2037	/// packets, and reads the track from its first packet.
2038	async fn opus_loss(config: EncodeConfig, lost: std::ops::Range<u64>, loss: Loss) -> Vec<Event> {
2039		let mut encoder = Encoder::new(&config).unwrap();
2040		let catalog = encoder.catalog();
2041		let broadcast = moq_net::broadcast::Info::new().produce();
2042		let track = broadcast
2043			.create_track("audio", hang::container::track_info(hang::catalog::PRIORITY.audio))
2044			.unwrap();
2045		let mut producer = moq_mux::container::Producer::new(
2046			track.clone(),
2047			moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Audio),
2048		);
2049		let frames = encoder.frame_size() as u64;
2050		for packet in 0..20 {
2051			let pcm: Vec<f32> = (packet * frames..(packet + 1) * frames)
2052				.map(|i| (std::f32::consts::TAU * 440.0 * i as f32 / 48_000.0).sin() * 0.5)
2053				.collect();
2054			let payload = crate::single(encoder.encode_all(&pcm).unwrap()).payload;
2055			let timestamp = Timestamp::from_scale(packet * frames, 48_000).unwrap();
2056			// The end marker a unit before the live edge, as the producer's discontinuity places it.
2057			if matches!(loss, Loss::Declared) && packet == lost.start {
2058				let edge = timestamp.convert(hang::container::TIMESCALE).unwrap().value();
2059				create_packet(&track, Timestamp::from_micros(edge - 1).unwrap(), Bytes::new());
2060			}
2061			if lost.contains(&packet) {
2062				continue;
2063			}
2064			// Created rather than appended, so nothing declares the lost starts skipped.
2065			if !matches!(loss, Loss::Stamps) {
2066				create_packet(&track, timestamp, payload);
2067				continue;
2068			}
2069			producer
2070				.write(moq_mux::container::Frame {
2071					timestamp: Timestamp::from_scale(packet * frames, 48_000).unwrap(),
2072					decode: None,
2073					duration: None,
2074					payload,
2075					keyframe: true,
2076				})
2077				.unwrap();
2078			producer.cut(None).unwrap();
2079		}
2080		let _finished = producer.finish().unwrap();
2081
2082		let options = Options {
2083			delay: Delay {
2084				max: Some(Duration::from_secs(10)),
2085				..Delay::default()
2086			},
2087			..Options::new()
2088		};
2089		let mut consumer = Consumer::new(&broadcast.consume(), &catalog, "audio", options)
2090			.await
2091			.unwrap();
2092		let mut events = Vec::new();
2093		while let Some(read) = consumer.read().await.unwrap() {
2094			events.push(match read {
2095				Read::Frame(frame) => {
2096					let pcm: Vec<f32> = frame
2097						.data
2098						.as_chunks::<4>()
2099						.0
2100						.iter()
2101						.map(|b| f32::from_le_bytes(*b))
2102						.collect();
2103					let rms = (pcm.iter().map(|s| s * s).sum::<f32>() / pcm.len() as f32).sqrt();
2104					Event::Frame(frame.timestamp.as_micros().unwrap(), pcm.len(), rms)
2105				}
2106				Read::Gap { timestamp, duration } => Event::Gap(timestamp.as_micros().unwrap(), duration.as_micros()),
2107				Read::End { end } => Event::End(end.as_micros().unwrap()),
2108			});
2109		}
2110		events
2111	}
2112
2113	fn gaps(events: &[Event]) -> Vec<(u128, u128)> {
2114		events
2115			.iter()
2116			.filter_map(|event| match event {
2117				Event::Gap(at, duration) => Some((*at, *duration)),
2118				_ => None,
2119			})
2120			.collect()
2121	}
2122
2123	/// Each frame starts where the one before it ended, up to a microsecond of rounding.
2124	fn contiguous(events: &[Event]) -> bool {
2125		let frames: Vec<(u128, usize)> = events
2126			.iter()
2127			.filter_map(|event| match event {
2128				Event::Frame(at, len, _) => Some((*at, *len)),
2129				_ => None,
2130			})
2131			.collect();
2132		frames
2133			.windows(2)
2134			.all(|pair| (pair[0].0 + pair[0].1 as u128 * 1_000_000 / 48_000).abs_diff(pair[1].0) <= 1)
2135	}
2136
2137	/// The samples read in total, and how loud those starting in `range` (µs) are at their quietest.
2138	fn heard(events: &[Event], range: std::ops::Range<u128>) -> (usize, f32) {
2139		let mut total = 0;
2140		let mut quietest = f32::MAX;
2141		for event in events {
2142			if let Event::Frame(at, len, rms) = event {
2143				total += len;
2144				if range.contains(at) {
2145					quietest = quietest.min(*rms);
2146				}
2147			}
2148		}
2149		(total, quietest)
2150	}
2151
2152	/// CELT-coded Opus conceals a short loss whole: the audio carries on through it with no gap,
2153	/// by lost groups or by a hole in the stamps alike.
2154	#[tokio::test(start_paused = true)]
2155	async fn opus_conceals_a_short_loss() {
2156		for loss in [Loss::Groups, Loss::Stamps] {
2157			let events = opus_loss(EncodeConfig::new(48_000, Layout::Mono), 5..7, loss).await;
2158			assert_eq!(gaps(&events), [], "{loss:?}");
2159			assert!(contiguous(&events), "{loss:?}: {events:?}");
2160			let (total, quietest) = heard(&events, 93_000..133_000);
2161			assert_eq!(total, 20 * 960 - 312, "{loss:?}");
2162			// The sine runs at 0.35 RMS; silence would be zero.
2163			assert!(quietest > 0.1, "{loss:?}: concealed at {quietest}");
2164		}
2165	}
2166
2167	/// Short packets conceal on a sample-exact timeline: four lost 2.5 ms packets play as four.
2168	#[tokio::test(start_paused = true)]
2169	async fn opus_conceals_short_packets_back_to_back() {
2170		let config = EncodeConfig {
2171			frame_duration: Duration::from_micros(2_500),
2172			..EncodeConfig::new(48_000, Layout::Mono)
2173		};
2174		let events = opus_loss(config, 5..9, Loss::Groups).await;
2175		assert_eq!(gaps(&events), []);
2176		assert!(contiguous(&events), "{events:?}");
2177		let (total, _) = heard(&events, 0..0);
2178		assert_eq!(total, 20 * 120 - 312);
2179	}
2180
2181	/// A loss past [`CONCEAL_MAX`] conceals its first 100 ms and reads the rest as a gap.
2182	#[tokio::test(start_paused = true)]
2183	async fn opus_conceals_the_start_of_a_long_loss() {
2184		for loss in [Loss::Groups, Loss::Stamps] {
2185			let events = opus_loss(EncodeConfig::new(48_000, Layout::Mono), 5..15, loss).await;
2186			assert_eq!(gaps(&events), [(200_000, 100_000)], "{loss:?}");
2187			let (total, _) = heard(&events, 0..0);
2188			assert_eq!(total, 15 * 960 - 312, "{loss:?}");
2189		}
2190	}
2191
2192	/// Concealment primes nothing: past a long loss, the packet after it trims the warmup that
2193	/// the media decoded before the loss fell short of.
2194	#[tokio::test(start_paused = true)]
2195	async fn opus_concealment_primes_no_warmup() {
2196		let events = opus_loss(EncodeConfig::new(48_000, Layout::Mono), 2..12, Loss::Groups).await;
2197		assert_eq!(gaps(&events), [(140_000, 100_000)]);
2198		let (total, _) = heard(&events, 0..0);
2199		// Two packets less the pre-skip, five concealed, and eight less the 40 ms of the 80 ms warmup
2200		// the first two left.
2201		assert_eq!(total, 2 * 960 - 312 + 5 * 960 + 8 * 960 - 1_920);
2202	}
2203
2204	/// A declared end is silence, never concealed.
2205	#[tokio::test(start_paused = true)]
2206	async fn opus_never_conceals_across_a_declared_end() {
2207		let events = opus_loss(EncodeConfig::new(48_000, Layout::Mono), 5..7, Loss::Declared).await;
2208		assert!(events.iter().any(|event| matches!(event, Event::End(_))), "{events:?}");
2209		assert_eq!(gaps(&events), [(100_000, 40_000)]);
2210		let (total, quietest) = heard(&events, 90_000..140_000);
2211		assert_eq!(quietest, f32::MAX, "nothing plays in the declared silence");
2212		// The fresh encoder after the silence trims its own pre-skip.
2213		assert_eq!(total, 18 * 960 - 2 * 312);
2214	}
2215
2216	/// SILK and hybrid Opus conceal a short loss whole too, fading the audio rather than
2217	/// playing it at full scale.
2218	#[tokio::test(start_paused = true)]
2219	async fn opus_conceals_a_short_silk_and_hybrid_loss() {
2220		// 12 kbps codes SILK, 32 kbps hybrid, as `decoder::opus_conceals_silk_and_hybrid` checks.
2221		for bitrate in [12_000, 32_000] {
2222			let config = EncodeConfig {
2223				kind: Some(crate::encode::Kind::Voice),
2224				bitrate: Some(moq_net::bandwidth::Rate::from_bps(bitrate)),
2225				..EncodeConfig::new(48_000, Layout::Mono)
2226			};
2227			let events = opus_loss(config, 5..7, Loss::Groups).await;
2228			assert_eq!(gaps(&events), [], "{bitrate}");
2229			assert!(contiguous(&events), "{bitrate}: {events:?}");
2230			let (total, quietest) = heard(&events, 100_000..140_000);
2231			assert_eq!(total, 20 * 960 - 312, "{bitrate}");
2232			assert!(quietest > 0.02, "{bitrate}: concealed at {quietest}");
2233			// The sine runs at 0.35 RMS; saturated concealment reads about 1.0.
2234			let loudest = events
2235				.iter()
2236				.filter_map(|event| match event {
2237					Event::Frame(at, _, rms) if (100_000..140_000).contains(at) => Some(*rms),
2238					_ => None,
2239				})
2240				.fold(0f32, f32::max);
2241			assert!(loudest < 0.5, "{bitrate}: concealed at {loudest}");
2242		}
2243	}
2244
2245	/// A refused packet primed nothing, so the window starts at the first one that decodes.
2246	#[tokio::test(start_paused = true)]
2247	async fn warmup_starts_at_the_first_decoded_packet() {
2248		let broadcast = moq_net::broadcast::Info::new().produce();
2249		let track = broadcast
2250			.create_track("audio", hang::container::track_info(hang::catalog::PRIORITY.audio))
2251			.unwrap();
2252		let mut catalog = hang::catalog::AudioConfig::new(hang::catalog::AudioCodec::Pcm, 48_000, 1);
2253		catalog.warmup = Some(Duration::from_millis(80));
2254		let mut producer = moq_mux::container::Producer::new(
2255			track,
2256			moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Audio),
2257		);
2258		for packet in 0..7 {
2259			let payload = if packet == 0 {
2260				vec![0; 3]
2261			} else {
2262				vec![0; 960 * size_of::<f32>()]
2263			};
2264			producer
2265				.write(moq_mux::container::Frame {
2266					timestamp: Timestamp::from_micros(packet * 20_000).unwrap(),
2267					decode: None,
2268					duration: None,
2269					payload: payload.into(),
2270					keyframe: true,
2271				})
2272				.unwrap();
2273		}
2274		let _finished = producer.finish().unwrap();
2275		let mut consumer = Consumer::new(
2276			&broadcast.consume(),
2277			&catalog,
2278			"audio",
2279			Options {
2280				delay: Delay {
2281					max: Some(Duration::from_secs(10)),
2282					..Delay::default()
2283				},
2284				..Options::new()
2285			},
2286		)
2287		.await
2288		.unwrap();
2289		assert!(next_frame(&mut consumer).await.is_err());
2290		let mut stamps = Vec::new();
2291		while let Some(frame) = next_frame(&mut consumer).await.unwrap() {
2292			stamps.push(frame.timestamp.as_micros().unwrap());
2293		}
2294		assert_eq!(stamps, [100_000, 120_000]);
2295	}
2296
2297	/// What the resampler holds at a marker belongs before it: draining it after the next
2298	/// packet would splice it onto the resumed audio and stamp that late.
2299	#[tokio::test(start_paused = true)]
2300	async fn resampled_tail_stays_before_a_marker() {
2301		let broadcast = moq_net::broadcast::Info::new().produce();
2302		let track = broadcast
2303			.create_track("audio", hang::container::track_info(hang::catalog::PRIORITY.audio))
2304			.unwrap();
2305		let subscriber = broadcast.consume();
2306		let catalog = hang::catalog::AudioConfig::new(hang::catalog::AudioCodec::Pcm, 44_100, 1);
2307		let mut producer = moq_mux::container::Producer::new(
2308			track,
2309			moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Audio),
2310		);
2311		let mut consumer = Consumer::new(
2312			&subscriber,
2313			&catalog,
2314			"audio",
2315			Options {
2316				delay: Delay {
2317					max: Some(Duration::from_secs(10)),
2318					..Delay::default()
2319				},
2320				output: Output {
2321					sample_rate: Some(48_000),
2322					..Output::default()
2323				},
2324				..Options::new()
2325			},
2326		)
2327		.await
2328		.unwrap();
2329		for index in 0..2 {
2330			if index != 0 {
2331				producer.discontinuity().unwrap();
2332			}
2333			producer
2334				.write(moq_mux::container::Frame {
2335					timestamp: Timestamp::from_micros(index * 1_000_000).unwrap(),
2336					decode: None,
2337					duration: None,
2338					payload: vec![0u8; 1024 * size_of::<f32>()].into(),
2339					keyframe: true,
2340				})
2341				.unwrap();
2342		}
2343		let _finished = producer.finish().unwrap();
2344		let mut stamps = Vec::new();
2345		while let Some(frame) = next_frame(&mut consumer).await.unwrap() {
2346			stamps.push(frame.timestamp.as_micros().unwrap());
2347		}
2348		assert_eq!(stamps.len(), 4, "each span's body and tail: {stamps:?}");
2349		assert!(
2350			stamps[1] < 1_000_000,
2351			"the old tail stays before the marker: {stamps:?}"
2352		);
2353		assert_eq!(stamps[2], 1_000_000, "the resumed span starts on its source timestamp");
2354	}
2355
2356	#[kio::test]
2357	async fn remixes_mono_stream_to_stereo_output() {
2358		let mut broadcast = moq_net::broadcast::Info::new().produce();
2359		let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
2360		let subscriber = broadcast.consume();
2361		let input = Input {
2362			format: Format::F32,
2363			sample_rate: 48_000,
2364			layout: Layout::Mono,
2365		};
2366		let options = EncodeOptions {
2367			track: Some("audio".to_string()),
2368			config: EncodeConfig::new(48_000, Layout::Mono),
2369			..EncodeOptions::default()
2370		};
2371		let mut producer = Producer::new(&mut broadcast, catalog, input.clone(), &options).unwrap();
2372		let mut catalog = Encoder::new(&EncodeConfig::new(input.sample_rate, input.layout))
2373			.unwrap()
2374			.catalog();
2375		// Every packet counts here; the warmup tests cover trimming.
2376		catalog.warmup = None;
2377		let mut consumer = Consumer::new(
2378			&subscriber,
2379			&catalog,
2380			"audio",
2381			Options {
2382				output: Output {
2383					layout: Some(Layout::Stereo),
2384					..Output::default()
2385				},
2386				..Options::new()
2387			},
2388		)
2389		.await
2390		.unwrap();
2391
2392		let samples = vec![0.1f32; 960];
2393		let mut data = Vec::with_capacity(samples.len() * size_of::<f32>());
2394		for sample in samples {
2395			data.extend_from_slice(&sample.to_le_bytes());
2396		}
2397		producer.write(&Frame::new(Timestamp::ZERO, data.into())).unwrap();
2398
2399		let frame = next_frame(&mut consumer).await.unwrap().expect("decoded frame");
2400		let samples = Format::F32.as_interleaved_f32(&frame.data, 2).unwrap();
2401		assert_eq!(samples.len(), (960 - 312) * 2);
2402		for pair in samples.as_chunks::<2>().0.iter() {
2403			assert_eq!(pair[0], pair[1]);
2404		}
2405	}
2406
2407	/// An imported 44.1 kHz Opus stream decodes on the 48 kHz clock: the pre-skip
2408	/// is trimmed once as padding before the first packet, and every later frame
2409	/// is stamped where its samples fall.
2410	#[kio::test]
2411	async fn opus_timestamps_follow_the_48k_clock() {
2412		use crate::decode::decoder::tests::{opus_catalog, opus_packets};
2413
2414		let broadcast = moq_net::broadcast::Info::new().produce();
2415		let track = broadcast
2416			.create_track("audio", hang::container::track_info(hang::catalog::PRIORITY.audio))
2417			.unwrap();
2418		let subscriber = broadcast.consume();
2419
2420		let catalog = opus_catalog(moq_mux::codec::opus::Config::new(44_100, 1).with_pre_skip(312));
2421		let mut producer = moq_mux::container::Producer::new(
2422			track,
2423			moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Audio),
2424		);
2425		let mut consumer = Consumer::new(&subscriber, &catalog, "audio", Options::new())
2426			.await
2427			.unwrap();
2428		assert_eq!(consumer.sample_rate(), 48_000);
2429
2430		for (packet, payload) in opus_packets(3).into_iter().enumerate() {
2431			producer
2432				.write(moq_mux::container::Frame {
2433					timestamp: Timestamp::from_micros(packet as u64 * 20_000).unwrap(),
2434					decode: None,
2435					duration: None,
2436					payload,
2437					keyframe: packet == 0,
2438				})
2439				.unwrap();
2440		}
2441
2442		// 312 samples at 48 kHz is 6.5 ms.
2443		for (micros, frames) in [(0, 960 - 312), (13_500, 960), (33_500, 960)] {
2444			let frame = next_frame(&mut consumer).await.unwrap().expect("decoded frame");
2445			assert_eq!(frame.timestamp.as_micros().unwrap(), micros);
2446			assert_eq!(frame.data.len() / size_of::<f32>(), frames);
2447		}
2448	}
2449
2450	#[tokio::test]
2451	async fn an_undeclared_timestamp_hole_is_a_gap() {
2452		tokio::time::pause();
2453		let broadcast = moq_net::broadcast::Info::new().produce();
2454		let track = broadcast
2455			.create_track("audio", hang::container::track_info(hang::catalog::PRIORITY.audio))
2456			.unwrap();
2457		let mut producer = moq_mux::container::Producer::new(
2458			track,
2459			moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Audio),
2460		);
2461		let catalog = hang::catalog::AudioConfig::new(hang::catalog::AudioCodec::Pcm, 48_000, 1);
2462		let options = Options {
2463			delay: Delay {
2464				max: Some(Duration::from_secs(1)),
2465				..Delay::default()
2466			},
2467			..Options::new()
2468		};
2469		let mut consumer = Consumer::new(&broadcast.consume(), &catalog, "audio", options)
2470			.await
2471			.unwrap();
2472		// Contiguous groups, so the container sees no gap: only the stamps jump.
2473		for micros in [0, 20_000, 500_000] {
2474			producer
2475				.write(moq_mux::container::Frame {
2476					timestamp: Timestamp::from_micros(micros).unwrap(),
2477					decode: None,
2478					duration: Some(Timestamp::from_micros(20_000).unwrap()),
2479					keyframe: true,
2480					payload: (0..960).flat_map(|_| 0.25f32.to_le_bytes()).collect::<Vec<_>>().into(),
2481				})
2482				.unwrap();
2483		}
2484		let _finished = producer.finish().unwrap();
2485		let mut reads = Vec::new();
2486		while let Some(event) = consumer.read().await.unwrap() {
2487			reads.push(match event {
2488				Read::Frame(frame) => format!("frame {}", frame.timestamp.as_micros().unwrap()),
2489				Read::Gap { timestamp, duration } => {
2490					format!("gap {}+{}", timestamp.as_micros().unwrap(), duration.as_micros())
2491				}
2492				Read::End { end } => format!("end {}", end.as_micros().unwrap()),
2493			});
2494		}
2495		assert_eq!(reads, ["frame 0", "frame 20000", "gap 40000+460000", "frame 500000"]);
2496	}
2497
2498	/// What the resampler holds at a marker comes out after the end, starting before it,
2499	/// and ahead of the fresh encoder's first frame at or past it.
2500	#[tokio::test]
2501	async fn a_resampler_tail_after_an_end_starts_before_it() {
2502		tokio::time::pause();
2503		let broadcast = moq_net::broadcast::Info::new().produce();
2504		let track = broadcast
2505			.create_track("audio", hang::container::track_info(hang::catalog::PRIORITY.audio))
2506			.unwrap();
2507		let mut producer = moq_mux::container::Producer::new(
2508			track,
2509			moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Audio),
2510		);
2511		let catalog = hang::catalog::AudioConfig::new(hang::catalog::AudioCodec::Pcm, 44_100, 1);
2512		let mut consumer = Consumer::new(
2513			&broadcast.consume(),
2514			&catalog,
2515			"audio",
2516			Options {
2517				output: Output {
2518					sample_rate: Some(48_000),
2519					..Output::default()
2520				},
2521				delay: Delay {
2522					max: Some(Duration::from_secs(1)),
2523					..Delay::default()
2524				},
2525				..Options::new()
2526			},
2527		)
2528		.await
2529		.unwrap();
2530		for (micros, sample) in [(0, 0.25f32), (30_000, 0.5)] {
2531			producer
2532				.write(moq_mux::container::Frame {
2533					timestamp: Timestamp::from_micros(micros).unwrap(),
2534					decode: None,
2535					duration: Some(Timestamp::from_scale(1024, 44_100).unwrap()),
2536					keyframe: true,
2537					payload: (0..1024).flat_map(|_| sample.to_le_bytes()).collect::<Vec<_>>().into(),
2538				})
2539				.unwrap();
2540			if micros == 0 {
2541				producer.discontinuity().unwrap();
2542			}
2543		}
2544		let _finished = producer.finish().unwrap();
2545		let mut before = Vec::new();
2546		let mut ended = None;
2547		let mut after = Vec::new();
2548		while let Some(event) = consumer.read().await.unwrap() {
2549			match event {
2550				Read::Frame(frame) if ended.is_none() => before.push(frame.timestamp),
2551				Read::Frame(frame) => after.push(frame.timestamp),
2552				Read::End { end } => ended = Some(end),
2553				Read::Gap { .. } => panic!("nothing was lost"),
2554			}
2555		}
2556		let end = ended.expect("the marker reads as an end");
2557		assert!(
2558			before.iter().all(|timestamp| *timestamp < end),
2559			"{before:?} past {end:?}"
2560		);
2561		let tail = after.iter().take_while(|timestamp| **timestamp < end).count();
2562		assert_eq!(tail, 1, "the stopped encoder's resampler tail leads: {after:?}");
2563		assert!(after.len() > tail, "a later group opens a fresh decoded timeline");
2564		assert!(
2565			after[tail..].iter().all(|timestamp| *timestamp >= end),
2566			"{after:?} before {end:?}"
2567		);
2568	}
2569
2570	/// A packet whose sample count isn't a multiple of the resampler's chunk leaves
2571	/// samples buffered, and the next output starts with those. Stamping that
2572	/// output with the packet that completed the chunk puts it up to a chunk late,
2573	/// which is a sawtooth in A/V sync rather than a constant offset. Any codec
2574	/// whose frame is not a whole number of chunks reaches it: a 1024-sample frame
2575	/// at 44.1 kHz never fills the 882-frame chunk evenly.
2576	#[kio::test]
2577	async fn resampled_timestamps_follow_the_samples() {
2578		let broadcast = moq_net::broadcast::Info::new().produce();
2579		let track = broadcast
2580			.create_track("audio", hang::container::track_info(hang::catalog::PRIORITY.audio))
2581			.unwrap();
2582		let subscriber = broadcast.consume();
2583
2584		let catalog = hang::catalog::AudioConfig::new(hang::catalog::AudioCodec::Pcm, 44_100, 1);
2585		let mut producer = moq_mux::container::Producer::new(
2586			track,
2587			moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Audio),
2588		);
2589
2590		let mut consumer = Consumer::new(
2591			&subscriber,
2592			&catalog,
2593			"audio",
2594			Options {
2595				output: Output {
2596					sample_rate: Some(48_000),
2597					..Output::default()
2598				},
2599				delay: Delay {
2600					max: Some(std::time::Duration::from_secs(1)),
2601					..Delay::default()
2602				},
2603				..Options::new()
2604			},
2605		)
2606		.await
2607		.unwrap();
2608
2609		// Two 1024-sample packets, back to back at the codec's own rate.
2610		const FRAMES: u64 = 1024;
2611		let payload: Bytes = vec![0u8; FRAMES as usize * size_of::<f32>()].into();
2612		for packet in 0..2 {
2613			producer
2614				.write(moq_mux::container::Frame {
2615					timestamp: moq_net::Timestamp::from_scale(packet * FRAMES, 44_100).unwrap(),
2616					decode: None,
2617					duration: None,
2618					payload: payload.clone(),
2619					keyframe: true,
2620				})
2621				.unwrap();
2622		}
2623
2624		let first = next_frame(&mut consumer).await.unwrap().expect("decoded frame");
2625		assert_eq!(first.timestamp.as_micros().unwrap(), 0);
2626
2627		// Continuity, not a fixed number: the second frame starts where the first
2628		// one's samples end, whatever they came to. Within a few frames rather than
2629		// exactly, because the resampler emits whole frames and its count per chunk
2630		// wobbles around the nominal ratio; a real hole (the samples it held back, or
2631		// the startup silence it dropped) is twenty times this tolerance.
2632		let second = next_frame(&mut consumer).await.unwrap().expect("decoded frame");
2633		let first_frames = (first.data.len() / size_of::<f32>()) as u128;
2634		let ends_at = first_frames * 1_000_000 / 48_000;
2635		let gap = second.timestamp.as_micros().unwrap().abs_diff(ends_at);
2636		assert!(gap < 100, "expected the frames to meet, got a {gap} us gap");
2637	}
2638
2639	/// The resampler only converts whole chunks, so the last partial one has to be
2640	/// flushed at end of track or its audio is simply gone. A 1024-sample frame at
2641	/// 44.1 kHz guarantees a remainder, never filling the 882-frame chunk evenly.
2642	#[kio::test]
2643	async fn resampled_tail_survives_the_end_of_the_track() {
2644		let broadcast = moq_net::broadcast::Info::new().produce();
2645		let track = broadcast
2646			.create_track("audio", hang::container::track_info(hang::catalog::PRIORITY.audio))
2647			.unwrap();
2648		let subscriber = broadcast.consume();
2649
2650		let catalog = hang::catalog::AudioConfig::new(hang::catalog::AudioCodec::Pcm, 44_100, 1);
2651		let mut producer = moq_mux::container::Producer::new(
2652			track,
2653			moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Audio),
2654		);
2655
2656		let mut consumer = Consumer::new(
2657			&subscriber,
2658			&catalog,
2659			"audio",
2660			Options {
2661				output: Output {
2662					sample_rate: Some(48_000),
2663					..Output::default()
2664				},
2665				..Options::new()
2666			},
2667		)
2668		.await
2669		.unwrap();
2670
2671		// One 1024-frame packet: 882 fill a chunk, 142 are left holding.
2672		const FRAMES: usize = 1024;
2673		let payload: Bytes = vec![0u8; FRAMES * size_of::<f32>()].into();
2674		producer
2675			.write(moq_mux::container::Frame {
2676				timestamp: moq_net::Timestamp::ZERO,
2677				decode: None,
2678				duration: None,
2679				payload,
2680				keyframe: true,
2681			})
2682			.unwrap();
2683		let _finished = producer.finish().unwrap();
2684
2685		let first = next_frame(&mut consumer).await.unwrap().expect("decoded frame");
2686		let first_frames = first.data.len() / size_of::<f32>();
2687
2688		let tail = next_frame(&mut consumer).await.unwrap().expect("flushed tail");
2689		let tail_frames = tail.data.len() / size_of::<f32>();
2690
2691		// The 142 held-back frames at 44.1 kHz are ~155 at 48 kHz, plus the 69 the
2692		// sinc filter still owes: it runs centred, so the end of the track only
2693		// emerges once the flush has fed it silence to push it out.
2694		assert!((215..=230).contains(&tail_frames), "unexpected tail: {tail_frames}");
2695		// It picks up where the first frame's samples ended, within the same few
2696		// frames of whole-frame rounding as above.
2697		let ends_at = (first_frames as u128) * 1_000_000 / 48_000;
2698		let gap = tail.timestamp.as_micros().unwrap().abs_diff(ends_at);
2699		assert!(gap < 100, "expected the tail to meet the body, got a {gap} us gap");
2700
2701		// Together they cover the packet and no more: 1024 frames at 44.1 kHz is
2702		// ~1114 at 48 kHz. The filter's delay does not extend the stream, because
2703		// what the drain adds here is what the start dropped off the front.
2704		let total = first_frames + tail_frames;
2705		assert!((1105..=1120).contains(&total), "unexpected total: {total}");
2706		assert!(next_frame(&mut consumer).await.unwrap().is_none());
2707	}
2708
2709	#[kio::test]
2710	async fn resampling_keeps_the_activity_boundary_on_its_source() {
2711		let mut encoder = Encoder::new(&EncodeConfig {
2712			kind: Some(crate::encode::Kind::Voice),
2713			bitrate: Some(moq_net::bandwidth::Rate::from_bps(24_000)),
2714			frame_duration: std::time::Duration::from_millis(10),
2715			..EncodeConfig::new(48_000, Layout::Mono)
2716		})
2717		.unwrap();
2718		let catalog = hang::catalog::AudioConfig::new(hang::catalog::AudioCodec::Opus, 48_000, 1);
2719
2720		let broadcast = moq_net::broadcast::Info::new().produce();
2721		let track = broadcast
2722			.create_track("audio", hang::container::track_info(hang::catalog::PRIORITY.audio))
2723			.unwrap();
2724		let subscriber = broadcast.consume();
2725		let mut producer = moq_mux::container::Producer::new(
2726			track,
2727			moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Audio),
2728		);
2729		let mut consumer = Consumer::new(
2730			&subscriber,
2731			&catalog,
2732			"audio",
2733			Options {
2734				output: Output {
2735					sample_rate: Some(44_100),
2736					..Output::default()
2737				},
2738				delay: Delay {
2739					max: Some(std::time::Duration::from_secs(1)),
2740					..Delay::default()
2741				},
2742				..Options::new()
2743			},
2744		)
2745		.await
2746		.unwrap();
2747
2748		let active = vec![0.5; encoder.frame_size()];
2749		let silence = vec![0.0; encoder.frame_size()];
2750		let mut first_dtx = None;
2751		for index in 0..40u64 {
2752			let packet = crate::single(encoder.encode_all(if index == 0 { &active } else { &silence }).unwrap());
2753			let timestamp = Timestamp::from_scale(index * encoder.frame_size() as u64, 48_000).unwrap();
2754			if first_dtx.is_none() && packet.activity.is_dtx() {
2755				first_dtx = Some(timestamp);
2756			}
2757			producer
2758				.write(moq_mux::container::Frame {
2759					timestamp,
2760					decode: None,
2761					payload: packet.payload,
2762					keyframe: true,
2763					duration: None,
2764				})
2765				.unwrap();
2766			producer.cut(None).unwrap();
2767		}
2768		let _finished = producer.finish().unwrap();
2769
2770		let expected = first_dtx.expect("silence should enter Opus DTX");
2771		let mut actual = None;
2772		while let Some(frame) = next_frame(&mut consumer).await.unwrap() {
2773			// 10 ms packets do not fill the 20 ms chunk, so the resampler hands back
2774			// nothing every other packet. Those must not surface as frames: a frame
2775			// with no samples reads as audio arriving, and carries an activity
2776			// describing samples that are not there.
2777			assert!(!frame.data.is_empty(), "read returned a frame with no samples");
2778			if frame.activity.is_dtx() {
2779				actual = Some(frame.timestamp);
2780				break;
2781			}
2782		}
2783		let actual = actual.expect("consumer should report Opus DTX");
2784
2785		// Each frame carries the activity its first sample came from, so the label
2786		// can lag its source by up to the frame it lands in, but it must never lead
2787		// it: leading means samples that are still active got labelled DTX. That is
2788		// what labelling by the packet most recently submitted does, since the
2789		// resampler is handing back audio from before that packet. It puts the
2790		// boundary a chunk early instead of a fraction of a chunk late.
2791		let delay = actual.as_micros().unwrap() as i128 - expected.as_micros().unwrap() as i128;
2792		let chunk_us = 20_000i128;
2793		assert!(
2794			(0..chunk_us).contains(&delay),
2795			"DTX label landed {delay} us from its source, outside [0, {chunk_us})"
2796		);
2797	}
2798
2799	/// Publish PCM packets of `frames` samples each at the given stamps, and read
2800	/// back every decoded frame as `(microseconds, output frames)`.
2801	async fn pcm_gaps(rate: u32, out_rate: u32, frames: usize, stamps: &[Timestamp]) -> Vec<(u128, usize)> {
2802		let broadcast = moq_net::broadcast::Info::new().produce();
2803		let track = broadcast
2804			.create_track("audio", hang::container::track_info(hang::catalog::PRIORITY.audio))
2805			.unwrap();
2806		let subscriber = broadcast.consume();
2807
2808		let catalog = hang::catalog::AudioConfig::new(hang::catalog::AudioCodec::Pcm, rate, 1);
2809		let mut producer = moq_mux::container::Producer::new(
2810			track,
2811			moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Audio),
2812		);
2813		let mut consumer = Consumer::new(
2814			&subscriber,
2815			&catalog,
2816			"audio",
2817			// These tests publish a whole track up front and read it back afterwards,
2818			// so every packet but the last is already old by the time the consumer
2819			// looks. The default budget is zero, which sheds all of them.
2820			Options {
2821				output: Output {
2822					sample_rate: Some(out_rate),
2823					..Output::default()
2824				},
2825				delay: Delay {
2826					max: Some(std::time::Duration::from_secs(1)),
2827					..Delay::default()
2828				},
2829				..Options::new()
2830			},
2831		)
2832		.await
2833		.unwrap();
2834
2835		let payload: Bytes = vec![0u8; frames * size_of::<f32>()].into();
2836		for stamp in stamps {
2837			producer
2838				.write(moq_mux::container::Frame {
2839					timestamp: *stamp,
2840					decode: None,
2841					duration: None,
2842					payload: payload.clone(),
2843					keyframe: true,
2844				})
2845				.unwrap();
2846		}
2847		let _finished = producer.finish().unwrap();
2848
2849		let mut read = Vec::new();
2850		while let Some(frame) = next_frame(&mut consumer).await.unwrap() {
2851			read.push((
2852				frame.timestamp.as_micros().unwrap(),
2853				frame.data.len() / size_of::<f32>(),
2854			));
2855		}
2856		read
2857	}
2858
2859	/// Backpressure holds packets encoded while still reading and timing every one:
2860	/// stalled, a packet decodes once the media behind it covers the hold, with a
2861	/// playhead, once that is within the floor of where the packet ends, and either
2862	/// way once it has waited the hold, whatever its timestamp says.
2863	#[tokio::test(start_paused = true)]
2864	async fn backpressure_holds_packets_encoded_until_the_ring_has_room() {
2865		const PACKET: Duration = Duration::from_millis(20);
2866		let broadcast = moq_net::broadcast::Info::new().produce();
2867		let track = broadcast
2868			.create_track("audio", hang::container::track_info(hang::catalog::PRIORITY.audio))
2869			.unwrap();
2870		let catalog = hang::catalog::AudioConfig::new(hang::catalog::AudioCodec::Pcm, 48_000, 1);
2871		let mut producer = moq_mux::container::Producer::new(
2872			track,
2873			moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Audio),
2874		);
2875		let mut consumer = Consumer::new(
2876			&broadcast.consume(),
2877			&catalog,
2878			"audio",
2879			Options {
2880				delay: Delay {
2881					max: Some(Duration::from_secs(1)),
2882					..Delay::default()
2883				},
2884				..Options::new()
2885			},
2886		)
2887		.await
2888		.unwrap();
2889		let backpressure = consumer.backpressure();
2890		backpressure.set_latency(Duration::from_millis(100), Duration::from_secs(2));
2891
2892		let payload: Bytes = vec![0u8; 960 * size_of::<f32>()].into();
2893		let mut write = |index: u32| {
2894			producer
2895				.write(moq_mux::container::Frame {
2896					timestamp: Timestamp::try_from(PACKET * index).unwrap(),
2897					decode: None,
2898					duration: None,
2899					payload: payload.clone(),
2900					keyframe: true,
2901				})
2902				.unwrap();
2903		};
2904		let read = async |consumer: &mut Consumer, wait: Duration| {
2905			kio::clock::timeout(wait, next_frame(consumer))
2906				.await
2907				.ok()
2908				.map(|frame| Duration::try_from(frame.unwrap().unwrap().timestamp).unwrap())
2909		};
2910
2911		// Ten packets cover 180 ms behind the first, short of the hold.
2912		for index in 0..10 {
2913			write(index);
2914		}
2915		assert_eq!(read(&mut consumer, Duration::from_secs(1)).await, None);
2916		assert_eq!(consumer.pending.len(), 10, "every packet is read and held encoded");
2917		write(100);
2918		assert_eq!(read(&mut consumer, Duration::ZERO).await, Some(Duration::ZERO));
2919
2920		// The first packet ends sounding in half a second, so the next one, ending
2921		// 20 ms later, is within the 100 ms floor of the playhead 80 ms before that.
2922		let sounds = kio::clock::Instant::now()
2923			.checked_add(Duration::from_millis(500))
2924			.unwrap();
2925		backpressure.observe(Timestamp::try_from(PACKET).unwrap(), sounds);
2926		assert_eq!(read(&mut consumer, Duration::from_millis(419)).await, None);
2927		assert_eq!(read(&mut consumer, Duration::from_millis(1)).await, Some(PACKET));
2928
2929		// With the playhead far off, the next packet waits out the hold from its arrival.
2930		let far = kio::clock::Instant::now().checked_add(Duration::from_secs(10)).unwrap();
2931		backpressure.observe(Timestamp::try_from(PACKET * 2).unwrap(), far);
2932		assert_eq!(read(&mut consumer, Duration::from_millis(579)).await, None);
2933		assert_eq!(read(&mut consumer, Duration::from_millis(1)).await, Some(PACKET * 2));
2934
2935		// The track's end leaves nothing to wait for.
2936		let _finished = producer.finish().unwrap();
2937		let mut rest = 0;
2938		while next_frame(&mut consumer).await.unwrap().is_some() {
2939			rest += 1;
2940		}
2941		assert_eq!(rest, 8);
2942	}
2943
2944	/// A packet that doesn't continue the last one is a hole, not a splice: the
2945	/// resampler hands back what it was holding from before the gap as its own
2946	/// frame, and the audio after it is stamped from the packet that carried it
2947	/// rather than rewound over samples that no longer exist.
2948	#[tokio::test]
2949	async fn a_missing_packet_leaves_a_hole() {
2950		const FRAMES: usize = 1024;
2951		// Packets at sample 0 and sample 2048: the one at 1024 never arrived.
2952		let stamps = [
2953			Timestamp::from_scale(0, 44_100).unwrap(),
2954			Timestamp::from_scale(2 * FRAMES as u64, 44_100).unwrap(),
2955		];
2956		let read = pcm_gaps(44_100, 48_000, FRAMES, &stamps).await;
2957
2958		// The first packet's chunk, then the tail drained at the gap, then the
2959		// second packet's chunk. The flush at end of track adds the last tail.
2960		assert_eq!(read.len(), 4, "unexpected frames: {read:?}");
2961
2962		// Everything the first packet carried comes out before the hole: 1024 frames
2963		// at 44.1 kHz is ~1114 at 48 kHz, whole-frame rounding aside.
2964		let before: usize = read[..2].iter().map(|(_, frames)| frames).sum();
2965		assert!((1105..=1120).contains(&before), "unexpected pre-gap audio: {before}");
2966
2967		// The audio after the hole is stamped by its own packet. Rewinding over the
2968		// resampler's buffer instead would put it ~3 ms early, in the middle of the
2969		// hole, and splice the two sides together through the filter.
2970		assert_eq!(read[2].0, stamps[1].as_micros().unwrap());
2971
2972		// And the hole is the packet that never arrived: 1024 frames at 44.1 kHz.
2973		let ends_at = read[1].0 + (read[1].1 as u128) * 1_000_000 / 48_000;
2974		let hole = read[2].0 - ends_at;
2975		assert!((23_100..=23_350).contains(&hole), "unexpected hole: {hole} us");
2976	}
2977
2978	/// A packet can land a hair past where the last one ended without being a hole:
2979	/// the stamps are quantized, so `discontinuous` allows a millisecond of slack.
2980	/// The jump is still a jump, and the resampler is holding samples from before
2981	/// it. Deriving their stamp by counting back from the packet drags them forward
2982	/// by the whole jump; reading it off the packet they arrived with does not.
2983	#[tokio::test]
2984	async fn a_jump_inside_the_slack_leaves_the_held_samples_alone() {
2985		// 441 frames at 44.1 kHz is 10 ms, half of the 20 ms chunk, so the first
2986		// packet is held whole and the second is what completes the chunk.
2987		const FRAMES: usize = 441;
2988		// A millisecond past where the first packet ended, which is the slack the
2989		// legacy container's microsecond re-stamping is allowed.
2990		let stamps = [
2991			Timestamp::from_micros(0).unwrap(),
2992			Timestamp::from_micros(11_000).unwrap(),
2993		];
2994		let read = pcm_gaps(44_100, 48_000, FRAMES, &stamps).await;
2995
2996		// The chunk, then the flush at the end of the track: no hole was declared, so
2997		// nothing was drained in between.
2998		assert_eq!(read.len(), 2, "unexpected frames: {read:?}");
2999		// It starts with the first packet's samples, so it is stamped where that
3000		// packet was. Rewinding from the second one instead puts it a millisecond late.
3001		assert_eq!(read[0].0, 0, "held samples moved with the jump: {read:?}");
3002	}
3003
3004	#[tokio::test]
3005	async fn a_jump_after_a_full_chunk_uses_the_new_packet_timestamp() {
3006		let stamps = [
3007			Timestamp::from_micros(0).unwrap(),
3008			Timestamp::from_micros(21_000).unwrap(),
3009		];
3010		let read = pcm_gaps(44_100, 48_000, 882, &stamps).await;
3011		let mut r = crate::resample::Resampler::new(44_100, 48_000, 1, 882).unwrap();
3012		r.process(&[0.25; 882], stamps[0]).unwrap();
3013		let expected = r.output_at(stamps[1]).unwrap().as_micros().unwrap();
3014		assert_eq!(read[1].0, expected);
3015	}
3016
3017	/// Once an end marker arrives the gap check stops running, because from there
3018	/// each batch's time is reconstructed from the marker rather than read off the
3019	/// packet. A packet that jumps forward then still moves whatever the resampler
3020	/// is holding, and the activity that lands with it: those samples came from
3021	/// before the jump and are labelled by the packet they came from.
3022	#[kio::test]
3023	async fn a_terminal_jump_leaves_the_held_samples_alone() {
3024		let mut encoder = Encoder::new(&EncodeConfig {
3025			kind: Some(crate::encode::Kind::Voice),
3026			bitrate: Some(moq_net::bandwidth::Rate::from_bps(24_000)),
3027			..EncodeConfig::new(48_000, Layout::Mono)
3028		})
3029		.unwrap();
3030		let mut catalog = encoder.catalog();
3031		// Every packet counts here; the warmup tests cover trimming.
3032		catalog.warmup = None;
3033
3034		// One coded packet, then a withheld one to follow it. Taken from the same
3035		// encoder rather than published in between, so nothing fills the resampler's
3036		// chunk between the two.
3037		let active = crate::single(encoder.encode_all(&vec![0.5f32; encoder.frame_size()]).unwrap());
3038		assert!(active.activity.is_active());
3039		let silence = vec![0.0f32; encoder.frame_size()];
3040		let dtx = (0..200)
3041			.map(|_| crate::single(encoder.encode_all(&silence).unwrap()))
3042			.find(|packet| packet.activity.is_dtx())
3043			.expect("silence should enter Opus DTX");
3044
3045		let broadcast = moq_net::broadcast::Info::new().produce();
3046		let track = broadcast
3047			.create_track("audio", hang::container::track_info(hang::catalog::PRIORITY.audio))
3048			.unwrap();
3049		let subscriber = broadcast.consume();
3050		let mut producer = moq_mux::container::Producer::new(
3051			track,
3052			moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Audio),
3053		);
3054		let mut consumer = Consumer::new(
3055			&subscriber,
3056			&catalog,
3057			"audio",
3058			Options {
3059				output: Output {
3060					sample_rate: Some(44_100),
3061					..Output::default()
3062				},
3063				..Options::new()
3064			},
3065		)
3066		.await
3067		.unwrap();
3068
3069		// A 20 ms Opus packet decodes 960 frames, less the pre-skip on the first one,
3070		// so it doesn't fill the 960-frame chunk and is held whole.
3071		let write = |producer: &mut moq_mux::container::Producer<_>, frames: u64, payload: Bytes, keyframe: bool| {
3072			producer
3073				.write(moq_mux::container::Frame {
3074					timestamp: Timestamp::from_scale(frames, 48_000).unwrap(),
3075					decode: None,
3076					duration: None,
3077					payload,
3078					keyframe,
3079				})
3080				.unwrap();
3081		};
3082		write(&mut producer, 0, active.payload, true);
3083		// The end marker, then the terminal packet a second past where it belongs.
3084		// Same group: a new group at 1s would sit below the marker's live edge.
3085		write(&mut producer, 3 * 48_000, Bytes::new(), false);
3086		write(&mut producer, 48_000, dtx.payload, false);
3087		let _finished = producer.finish().unwrap();
3088
3089		let frame = next_frame(&mut consumer).await.unwrap().expect("decoded frame");
3090		// The output begins with the first packet's samples, so it is stamped and
3091		// labelled from that packet. Rewinding from the terminal one instead drops it
3092		// most of a second into the future, carrying the DTX label with it.
3093		assert_eq!(
3094			frame.timestamp.as_micros().unwrap(),
3095			0,
3096			"held samples moved with the jump"
3097		);
3098		assert!(
3099			frame.activity.is_active(),
3100			"held samples took the terminal packet's label"
3101		);
3102	}
3103
3104	/// Every packet on the RTMP path lands beside where the last one ended: FLV
3105	/// stamps in whole milliseconds and a 1024-sample AAC frame at 44.1 kHz runs
3106	/// 23.22 ms, so the stamps drift up to a millisecond either way. Reading that as
3107	/// a hole would reset the codec and the resampler on nearly every packet.
3108	///
3109	/// PCM stands in for AAC, which needs an encoder this crate doesn't have: the
3110	/// arithmetic that matters is the packet length and the millisecond stamps.
3111	#[tokio::test]
3112	async fn millisecond_stamps_are_not_a_gap() {
3113		const FRAMES: u64 = 1024;
3114		const PACKETS: u64 = 32;
3115
3116		// What an FLV ingest sends: each packet stamped in whole milliseconds.
3117		let stamps: Vec<_> = (0..PACKETS)
3118			.map(|packet| Timestamp::from_millis(packet * FRAMES * 1_000 / 44_100).unwrap())
3119			.collect();
3120		let read = pcm_gaps(44_100, 48_000, FRAMES as usize, &stamps).await;
3121
3122		// One frame per packet, since 1024 frames always fill at least one 882-frame
3123		// chunk, plus the flush at the end of the track. Reading a gap would drain
3124		// the resampler as well, adding a frame at every packet it fired on.
3125		assert_eq!(read.len(), stamps.len() + 1, "unexpected frames: {read:?}");
3126
3127		// And the output stays continuous across all of them, within the millisecond
3128		// the stamps themselves are quantized to.
3129		for pair in read.windows(2) {
3130			let ends_at = pair[0].0 + (pair[0].1 as u128) * 1_000_000 / 48_000;
3131			assert!(
3132				pair[1].0.abs_diff(ends_at) <= 1_100,
3133				"frames at {} and {} do not meet",
3134				pair[0].0,
3135				pair[1].0
3136			);
3137		}
3138	}
3139
3140	/// The tolerance can't come from a frame duration. Opus packets run from 2.5 ms
3141	/// to 60 ms with nothing in the catalog to say which, so a rule read off the
3142	/// 20 ms packet before it would splice straight across a lost 2.5 ms one.
3143	#[kio::test]
3144	async fn a_lost_opus_packet_shorter_than_its_neighbour_is_a_gap() {
3145		let input = Input {
3146			format: Format::F32,
3147			sample_rate: 48_000,
3148			layout: Layout::Mono,
3149		};
3150		let mut encoder = Encoder::new(&EncodeConfig::new(input.sample_rate, input.layout)).unwrap();
3151		let mut catalog = encoder.catalog();
3152		// Every packet counts here; the warmup tests cover trimming.
3153		catalog.warmup = None;
3154
3155		let broadcast = moq_net::broadcast::Info::new().produce();
3156		let track = broadcast
3157			.create_track("audio", hang::container::track_info(hang::catalog::PRIORITY.audio))
3158			.unwrap();
3159		let subscriber = broadcast.consume();
3160		let mut producer = moq_mux::container::Producer::new(
3161			track,
3162			moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Audio),
3163		);
3164		let mut consumer = Consumer::new(
3165			&subscriber,
3166			&catalog,
3167			"audio",
3168			Options {
3169				delay: Delay {
3170					max: Some(std::time::Duration::from_secs(1)),
3171					..Delay::default()
3172				},
3173				..Options::new()
3174			},
3175		)
3176		.await
3177		.unwrap();
3178
3179		// A 20 ms packet at 0, then the next one at 22.5 ms: the 2.5 ms packet
3180		// between them was lost.
3181		let pcm = vec![0.25f32; encoder.frame_size()];
3182		for timestamp in [
3183			Timestamp::from_micros(0).unwrap(),
3184			Timestamp::from_micros(22_500).unwrap(),
3185			Timestamp::from_micros(42_500).unwrap(),
3186		] {
3187			producer
3188				.write(moq_mux::container::Frame {
3189					timestamp,
3190					decode: None,
3191					duration: None,
3192					payload: crate::single(encoder.encode_all(&pcm).unwrap()).payload,
3193					keyframe: true,
3194				})
3195				.unwrap();
3196			producer.cut(None).unwrap();
3197		}
3198
3199		// The pre-skip is trimmed off the first packet, so it decodes short. That
3200		// shortfall is codec delay, not a hole: without counting it the packet after
3201		// every stream start would read as a gap.
3202		let first = next_frame(&mut consumer).await.unwrap().expect("decoded frame");
3203		let frames = first.data.len() / size_of::<f32>();
3204		assert!(frames < 960, "the pre-skip should be trimmed, got {frames} frames");
3205
3206		// The hole is real, but stream-level pre-skip does not start over. The audio is
3207		// stamped where the packet says rather than 2.5 ms early.
3208		let second = next_frame(&mut consumer).await.unwrap().expect("decoded frame");
3209		assert_eq!(second.timestamp.as_micros().unwrap(), 22_500);
3210		assert_eq!(second.data.len() / size_of::<f32>(), 960, "pre-skip was reapplied");
3211
3212		let third = next_frame(&mut consumer)
3213			.await
3214			.unwrap()
3215			.expect("decoded frame after gap");
3216		let second_frames = second.data.len() / size_of::<f32>();
3217		assert_eq!(
3218			third.timestamp,
3219			advance(second.timestamp, second_frames, 48_000).unwrap()
3220		);
3221	}
3222
3223	/// A lost group leaves the same encoder running, so its pre-skip, trimmed once at the
3224	/// stream's start, is not trimmed again off the media after the loss.
3225	#[tokio::test(start_paused = true)]
3226	async fn a_lost_group_does_not_trim_the_pre_skip_again() {
3227		assert_eq!(after_loss(false, None).await[0], (1_000_000, 960));
3228	}
3229
3230	/// Groups lost past a declared end were the fresh encoder's, so the packet after them
3231	/// still comes from it: its pre-skip is trimmed, leaving its media at the packet's stamp.
3232	#[tokio::test(start_paused = true)]
3233	async fn a_loss_after_a_declared_end_trims_the_fresh_encoders_pre_skip() {
3234		assert_eq!(after_loss(true, None).await[0], (1_000_000, 960 - 312));
3235	}
3236
3237	/// A gap after a declared end reaches the fresh encoder's first packet, which plays from its
3238	/// own stamp rather than a warmup later: before lite-07 the run skipped across every pause
3239	/// arrives as a drop, so priming there would clip the start of each utterance.
3240	#[tokio::test(start_paused = true)]
3241	async fn a_gap_after_a_declared_end_trims_no_warmup() {
3242		let warmup = Some(Duration::from_millis(10));
3243		assert_eq!(after_loss(true, warmup).await[0], (1_000_000, 960 - 312));
3244	}
3245
3246	/// Decodes two Opus packets, then, past lost groups and a declared end if `declared`, one
3247	/// more a second later, returning the stamp and length of each frame after the loss.
3248	async fn after_loss(declared: bool, warmup: Option<Duration>) -> Vec<(u128, usize)> {
3249		let input = Input {
3250			format: Format::F32,
3251			sample_rate: 48_000,
3252			layout: Layout::Mono,
3253		};
3254		let config = EncodeConfig::new(input.sample_rate, input.layout);
3255		let mut encoder = Encoder::new(&config).unwrap();
3256		let mut catalog = encoder.catalog();
3257		catalog.warmup = warmup;
3258
3259		let broadcast = moq_net::broadcast::Info::new().produce();
3260		let track = broadcast
3261			.create_track("audio", hang::container::track_info(hang::catalog::PRIORITY.audio))
3262			.unwrap();
3263		let mut producer = moq_mux::container::Producer::new(
3264			track.clone(),
3265			moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Audio),
3266		);
3267		let pcm = vec![0.25f32; encoder.frame_size()];
3268		for packet in 0..2 {
3269			producer
3270				.write(moq_mux::container::Frame {
3271					timestamp: Timestamp::from_micros(packet * 20_000).unwrap(),
3272					decode: None,
3273					duration: None,
3274					payload: crate::single(encoder.encode_all(&pcm).unwrap()).payload,
3275					keyframe: true,
3276				})
3277				.unwrap();
3278			producer.cut(None).unwrap();
3279		}
3280		if declared {
3281			producer.discontinuity().unwrap();
3282			encoder = Encoder::new(&config).unwrap();
3283		}
3284		// Created rather than appended, so nothing declares the starts before it skipped.
3285		let payload = crate::single(encoder.encode_all(&pcm).unwrap()).payload;
3286		create_packet(&track, Timestamp::from_micros(1_000_000).unwrap(), payload);
3287		let _finished = producer.finish().unwrap();
3288		let mut consumer = Consumer::new(
3289			&broadcast.consume(),
3290			&catalog,
3291			"audio",
3292			Options {
3293				delay: Delay {
3294					max: Some(Duration::from_secs(10)),
3295					..Delay::default()
3296				},
3297				..Options::new()
3298			},
3299		)
3300		.await
3301		.unwrap();
3302
3303		let mut lost = false;
3304		let mut after = Vec::new();
3305		while let Some(read) = consumer.read().await.unwrap() {
3306			match read {
3307				Read::Gap { .. } => lost = true,
3308				Read::Frame(frame) if lost => after.push((
3309					frame.timestamp.as_micros().unwrap(),
3310					frame.data.len() / size_of::<f32>(),
3311				)),
3312				Read::Frame(_) | Read::End { .. } => {}
3313			}
3314		}
3315		assert!(!after.is_empty(), "no frame after the loss");
3316		after
3317	}
3318
3319	/// Replay a corpus trace through the whole decode path, one PCM packet per group
3320	/// written at its recorded arrival and read straight back, and return the
3321	/// consumer's delay after each packet in milliseconds.
3322	///
3323	/// PCM rather than Opus only for speed: the frame term comes from the decoded
3324	/// sample count either way, and an unoptimized Opus codec takes minutes over
3325	/// the whole corpus. [`opus_states_its_own_frame_duration`] covers Opus. The
3326	/// lowest common rate keeps each packet small, since only its duration counts.
3327	/// With `hole`, the publisher leaves the starts between each end marker and what resumes
3328	/// undeclared, so whatever lay there may have been lost: a group after the marker that never
3329	/// arrived.
3330	async fn replay(case: &crate::jitter::tests::Case, hole: bool) -> Vec<f64> {
3331		use crate::jitter::tests::duration;
3332
3333		let rate = 8_000;
3334		let samples = (case.frame * rate as f64 / 1000.0) as usize;
3335		let mut catalog = hang::catalog::AudioConfig::new(hang::catalog::AudioCodec::Pcm, rate, 1);
3336		catalog.jitter = case.advertised.map(duration);
3337
3338		let broadcast = moq_net::broadcast::Info::new().produce();
3339		let track = broadcast
3340			.create_track("audio", hang::container::track_info(hang::catalog::PRIORITY.audio))
3341			.unwrap();
3342		let subscriber = broadcast.consume();
3343		let mut producer = moq_mux::container::Producer::new(
3344			track.clone(),
3345			moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Audio),
3346		);
3347
3348		let origin = Instant::now();
3349		let mut consumer = Consumer::new(
3350			&subscriber,
3351			&catalog,
3352			"audio",
3353			Options {
3354				delay: Delay {
3355					min: Some(case.delay.map_or(Duration::ZERO, duration)),
3356					..Delay::default()
3357				},
3358				estimate: case.delay.is_none(),
3359				..Options::new()
3360			},
3361		)
3362		.await
3363		.unwrap();
3364
3365		let payload: Bytes = vec![0u8; samples * size_of::<f32>()].into();
3366		let mut series = Vec::with_capacity(case.arrival.len());
3367		for (index, (&arrival, &media)) in case.arrival.iter().zip(&case.media).enumerate() {
3368			// The track's timescale is microseconds, so this is also the packet group's start.
3369			let micros = media as u64 * 1000;
3370			// The marker goes out as the utterance stops, so it is read during the silence
3371			// rather than alongside what resumes it.
3372			if case.ends.contains(&index) {
3373				producer.discontinuity().unwrap();
3374				match consumer.read().await.unwrap() {
3375					Some(Read::End { .. }) => {}
3376					other => panic!("packet {index} is preceded by {other:?}, not its end"),
3377				}
3378			}
3379			// On tokio's paused clock, which moq-net's landing times follow.
3380			tokio::time::advance(duration(arrival).saturating_sub(origin.elapsed())).await;
3381			let timestamp = Timestamp::from_micros(micros).unwrap();
3382			if hole && case.ends.contains(&index) {
3383				// Created rather than appended, so nothing declares the starts before it skipped.
3384				create_packet(&track, timestamp, payload.clone());
3385			} else {
3386				producer
3387					.write(moq_mux::container::Frame {
3388						timestamp,
3389						decode: None,
3390						duration: None,
3391						payload: payload.clone(),
3392						keyframe: true,
3393					})
3394					.unwrap();
3395				producer.cut(None).unwrap();
3396			}
3397
3398			next_frame(&mut consumer)
3399				.await
3400				.unwrap()
3401				.expect("one decoded frame per packet");
3402			series.push(crate::jitter::millis(consumer.delay()));
3403		}
3404		series
3405	}
3406
3407	/// The decode path measures what the corpus says it should: arrival when the
3408	/// container hands a packet over, media from its timestamp, and the frame term
3409	/// from what the codec decoded. `reorder` and `backlog` are left to the
3410	/// estimator's own test, since the container refuses a timestamp that runs
3411	/// backwards. `silence` publishes a discontinuity marker ahead of each frame its
3412	/// `ends` lists, so the consumer has to find the declared end on its own.
3413	#[tokio::test(start_paused = true)]
3414	async fn the_decode_path_conforms_to_the_corpus() {
3415		for name in [
3416			"advertised",
3417			"buildup",
3418			"fixed",
3419			"flush",
3420			"idle",
3421			"paced",
3422			"silence",
3423			"spike",
3424			"tunein",
3425		] {
3426			let case = crate::jitter::tests::case(name);
3427			let expected = case.series();
3428			for (index, actual) in replay(&case, false).await.into_iter().enumerate() {
3429				// A Duration is whole nanoseconds, so the round trip through one costs up
3430				// to a nanosecond on top of the corpus tolerance.
3431				assert!(
3432					(actual - expected[index]).abs() <= 1e-5,
3433					"{name}: packet {index} delays {actual} ms, expected {}",
3434					expected[index]
3435				);
3436			}
3437		}
3438	}
3439
3440	/// Paced packets for the first minute of `budget`'s trace: long enough to spend the
3441	/// prior and settle the target at its floor.
3442	const PACED: usize = 3000;
3443
3444	/// `@moq/watch`'s `playout.test.ts` "subscription budget" trace, `(arrival, media)` in ms
3445	/// per packet: a minute of 20 ms packets over a 50 ms path, then six seconds of them
3446	/// flushed six at a time.
3447	fn flushes() -> Vec<(u64, u64)> {
3448		let base = 20 * PACED as u64;
3449		(0..PACED as u64)
3450			.map(|i| (50 + 20 * i, 20 * i))
3451			.chain((0..300).map(|i| (base + 50 + 20 * (i / 6 * 6 + 5), base + 20 * i)))
3452			.collect()
3453	}
3454
3455	/// [`flushes`] through the whole decode path, one PCM packet per group. Every packet
3456	/// sharing an arrival lands before any is read, so the oldest of a flush trails the newest by
3457	/// 100 ms. After each arrival, `budget` turns the consumer's delay into its max delay.
3458	/// Returns the delay after each arrival in milliseconds, and how many packets were decoded
3459	/// rather than skipped.
3460	async fn budget(budget: impl Fn(Duration) -> Duration) -> (Vec<f64>, usize) {
3461		use moq_mux::container::Container as _;
3462
3463		let events = flushes();
3464		let catalog = hang::catalog::AudioConfig::new(hang::catalog::AudioCodec::Pcm, 8_000, 1);
3465		let broadcast = moq_net::broadcast::Info::new().produce();
3466		let track = broadcast
3467			.create_track("audio", hang::container::track_info(hang::catalog::PRIORITY.audio))
3468			.unwrap();
3469		let subscriber = broadcast.consume();
3470		let options = Options {
3471			delay: Delay {
3472				max: Some(budget(Duration::ZERO)),
3473				..Delay::default()
3474			},
3475			estimate: true,
3476			..Options::new()
3477		};
3478		let mut consumer = Consumer::new(&subscriber, &catalog, "audio", options).await.unwrap();
3479
3480		let container = moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Audio);
3481		let payload: Bytes = vec![0u8; 160 * size_of::<f32>()].into();
3482		let start = kio::clock::now();
3483		let mut series = Vec::new();
3484		let mut delivered = 0;
3485		let mut next = 0;
3486		while next < events.len() {
3487			let at = events[next].0;
3488			tokio::time::advance(Duration::from_millis(at).saturating_sub(start.elapsed())).await;
3489			let mut newest = 0;
3490			for (sequence, &(_, media)) in events.iter().enumerate().skip(next) {
3491				if events[sequence].0 != at {
3492					break;
3493				}
3494				let mut group = None;
3495				let frame = moq_mux::container::Frame {
3496					timestamp: Timestamp::from_micros(media * 1000).unwrap(),
3497					decode: None,
3498					duration: None,
3499					payload: payload.clone(),
3500					keyframe: true,
3501				};
3502				container
3503					.write(&mut moq_mux::container::Writer::new(&track, &mut group), &[frame])
3504					.unwrap();
3505				group.unwrap().finish().unwrap();
3506				newest = media;
3507				next = sequence + 1;
3508			}
3509			// Read through the newest packet, which the max delay never gives up; what it gives
3510			// up below that reads as a gap.
3511			loop {
3512				let frame = next_frame(&mut consumer).await.unwrap().expect("one frame per packet");
3513				delivered += 1;
3514				if frame.timestamp == Timestamp::from_micros(newest * 1000).unwrap() {
3515					break;
3516				}
3517			}
3518			series.push(crate::jitter::millis(consumer.delay()));
3519			consumer.set_max_delay(budget(consumer.delay()));
3520		}
3521		(series, delivered)
3522	}
3523
3524	/// The targets across the first twenty flushes, 2.4 s of them.
3525	fn onset(series: &[f64]) -> f64 {
3526		series[PACED..PACED + 20].iter().copied().fold(f64::MIN, f64::max)
3527	}
3528
3529	/// `moq play`'s subscription reaches the estimator's 2 s ceiling past its delay, never below
3530	/// the 2 s it opened with (`rs/moq-cli/src/play/media.rs`, here with audio's delay as the
3531	/// shared one), so a flush that starts after the target settled at its floor still lands
3532	/// whole and moves it, as the browser's does.
3533	#[tokio::test(start_paused = true)]
3534	async fn the_subscription_reaches_a_flush_that_starts_after_the_target_settled() {
3535		let reach = Duration::from_secs(2);
3536		let (series, delivered) = budget(|delay| (delay + reach).max(reach)).await;
3537		assert_eq!(series[PACED - 1], 40.0);
3538		assert_eq!(delivered, PACED + 300);
3539
3540		// Every packet observed: the estimator fed the same arrivals directly, after each one.
3541		let mut target = crate::jitter::Target::new(Duration::ZERO, true, None);
3542		target.set_frame(20.0);
3543		let mut direct = Vec::new();
3544		let events = flushes();
3545		for (index, &(at, media)) in events.iter().enumerate() {
3546			target.observe(at as f64, media as f64);
3547			if events.get(index + 1).is_none_or(|next| next.0 != at) {
3548				direct.push(target.millis());
3549			}
3550		}
3551		assert_eq!(series, direct);
3552		// Every flush lands whole, so its 100 ms reaches the 95th percentile within a few intervals.
3553		assert!(onset(&series) >= 120.0, "{:?}", &series[PACED..PACED + 20]);
3554	}
3555
3556	/// The counter-case: a max delay that only follows the delay gives up the oldest of each
3557	/// flush before the consumer observes it, so the estimate only ever sees what the delay it
3558	/// already holds allows.
3559	#[tokio::test(start_paused = true)]
3560	async fn a_budget_following_the_delay_drops_the_flush_it_should_measure() {
3561		let (series, delivered) = budget(|delay| delay).await;
3562		assert!(delivered < PACED + 300, "{delivered} delivered");
3563		assert!(onset(&series) < 120.0, "{:?}", &series[PACED..PACED + 20]);
3564	}
3565
3566	/// Write `events`, `(arrival, group, media)` in ms in arrival order, through the whole
3567	/// decode path, one PCM packet per group, reading each one `read` admits as it lands.
3568	/// The publisher answers that its feed starts at the first event's group, as a session's
3569	/// does. Returns the delay once they have all landed, and whether the container reported a
3570	/// backlog.
3571	async fn play(events: &[(u64, u64, u64)], read: impl Fn(u64) -> bool) -> (f64, bool) {
3572		let catalog = hang::catalog::AudioConfig::new(hang::catalog::AudioCodec::Pcm, 8_000, 1);
3573		let broadcast = moq_net::broadcast::Info::new().produce();
3574		let mut track = broadcast
3575			.create_track("audio", hang::container::track_info(hang::catalog::PRIORITY.audio))
3576			.unwrap();
3577		track.start_at(events[0].1).unwrap();
3578		let subscriber = broadcast.consume();
3579		// The estimate's 2 s ceiling past the delay, as `moq play` subscribes.
3580		let options = Options {
3581			delay: Delay {
3582				max: Some(Duration::from_secs(2)),
3583				..Delay::default()
3584			},
3585			estimate: true,
3586			..Options::new()
3587		};
3588		let mut consumer = Consumer::new(&subscriber, &catalog, "audio", options).await.unwrap();
3589
3590		let payload: Bytes = vec![0u8; 160 * size_of::<f32>()].into();
3591		let start = kio::clock::now();
3592		let first = events.iter().map(|&(_, _, media)| media).min();
3593		for &(at, sequence, media) in events {
3594			tokio::time::advance(Duration::from_millis(at).saturating_sub(start.elapsed())).await;
3595			create_spaced(&track, media * 1000, Some(media) != first, payload.clone());
3596			if read(sequence) {
3597				next_frame(&mut consumer).await.unwrap().expect("one frame per packet");
3598			}
3599		}
3600		(
3601			crate::jitter::millis(consumer.delay()),
3602			consumer.track.backlog().is_some(),
3603		)
3604	}
3605
3606	/// The live edge, group 200 onward, a packet every 20 ms over a 40 ms path, its arrivals
3607	/// moved by `delay`, which never lets one overtake another.
3608	fn live(delay: impl Fn(u64) -> u64) -> Vec<(u64, u64, u64)> {
3609		let mut last = 0;
3610		(0..300)
3611			.map(|k| {
3612				let at = delay(20 * k).max(last);
3613				last = at;
3614				(at, 200 + k, 100_000 + 20 * k)
3615			})
3616			.collect()
3617	}
3618
3619	/// A path that delivers every fifth packet 300 ms late from the start: each lands after
3620	/// the cursor passed it and is dropped unread, but was produced after the subscription
3621	/// began, so it is no backlog and holds no join open. The estimator measures the path
3622	/// from what it observes, as if the late packets never arrived.
3623	#[tokio::test(start_paused = true)]
3624	async fn late_groups_dropped_from_the_start_hold_no_join_open() {
3625		let late = |sequence: u64| sequence > 200 && sequence.is_multiple_of(5);
3626		let mut events: Vec<_> = live(|produced| produced + 40)
3627			.into_iter()
3628			.map(|(at, sequence, media)| (at + if late(sequence) { 300 } else { 0 }, sequence, media))
3629			.collect();
3630		events.sort_by_key(|&(at, sequence, _)| (at, sequence));
3631		let (dropped, backlog) = play(&events, |sequence| !late(sequence)).await;
3632		assert!(!backlog);
3633		let never: Vec<_> = events
3634			.iter()
3635			.copied()
3636			.filter(|&(_, sequence, _)| !late(sequence))
3637			.collect();
3638		let (lost, _) = play(&never, |_| true).await;
3639		assert_eq!(dropped, lost);
3640	}
3641
3642	/// A hole the container waits out up to the max delay holds the packets behind it, which
3643	/// landed on time: the estimate and [`Consumer::arrival`] use when they landed, not when
3644	/// they were read, so the wait reads as no jitter.
3645	#[tokio::test(start_paused = true)]
3646	async fn a_hole_waited_out_to_the_max_delay_leaves_the_estimate() {
3647		let publisher = origin();
3648		let route = publisher
3649			.route("bcast", moq_net::origin::RouteOptions::hidden())
3650			.unwrap();
3651		let track = route
3652			.broadcast()
3653			.create_track("audio", hang::container::track_info(hang::catalog::PRIORITY.audio))
3654			.unwrap();
3655		route.announce().unwrap();
3656		let payload: Bytes = vec![0u8; 160 * size_of::<f32>()].into();
3657		let write = |sequence: u64| create_spaced(&track, sequence * 20_000, sequence > 0, payload.clone());
3658
3659		// A received copy: its feed owes the missing group, so the reader waits for it.
3660		let relay = origin();
3661		let _link = link(&publisher, &relay).await;
3662		let remote = relay
3663			.consume()
3664			.follow("bcast", None)
3665			.unwrap()
3666			.available()
3667			.await
3668			.unwrap()
3669			.unwrap();
3670		let catalog = hang::catalog::AudioConfig::new(hang::catalog::AudioCodec::Pcm, 8_000, 1);
3671		let max = Duration::from_secs(2);
3672		let options = Options {
3673			delay: Delay {
3674				max: Some(max),
3675				..Delay::default()
3676			},
3677			estimate: true,
3678			..Options::new()
3679		};
3680		let mut consumer = Consumer::new(&remote, &catalog, "audio", options).await.unwrap();
3681
3682		write(0);
3683		next_frame(&mut consumer).await.unwrap().expect("the first packet");
3684		let estimate = consumer.delay();
3685
3686		// Packet 1 never arrives; the ones after it land on time, 20 ms apart.
3687		for sequence in 2..6 {
3688			tokio::time::advance(Duration::from_millis(if sequence == 2 { 40 } else { 20 })).await;
3689			write(sequence);
3690		}
3691		let since = kio::clock::now();
3692		assert!(matches!(consumer.read().await.unwrap(), Some(Read::Gap { .. })));
3693		assert!(
3694			since.elapsed() >= max / 2,
3695			"the hole was not waited: {:?}",
3696			since.elapsed()
3697		);
3698		for _ in 2..6 {
3699			next_frame(&mut consumer)
3700				.await
3701				.unwrap()
3702				.expect("a packet past the hole");
3703		}
3704		// They report when they landed too, which a gate's hold counts from.
3705		assert!(
3706			consumer.arrival().is_some_and(|arrived| arrived <= since),
3707			"a packet past the hole reports when it was read: {:?}, read from {since:?}",
3708			consumer.arrival()
3709		);
3710		// Steady arrivals after it, read as they land, close the interval that measured the wait.
3711		let resumed = 6 + (since.elapsed().as_millis() / 20) as u64;
3712		for sequence in resumed..resumed + 100 {
3713			write(sequence);
3714			next_frame(&mut consumer).await.unwrap().expect("a steady packet");
3715			tokio::time::advance(Duration::from_millis(20)).await;
3716		}
3717		assert!(
3718			consumer.delay() <= estimate,
3719			"the wait read as jitter: {:?} after, {estimate:?} before",
3720			consumer.delay()
3721		);
3722	}
3723
3724	/// A group lost between a declared end and what resumes leaves the end declared, as the
3725	/// browser's consumer does: the estimator measures the same as when nothing was lost.
3726	#[tokio::test(start_paused = true)]
3727	async fn a_declared_end_survives_a_lost_group() {
3728		let case = crate::jitter::tests::case("silence");
3729		assert!(!case.ends.is_empty());
3730		assert_eq!(replay(&case, true).await, replay(&case, false).await);
3731	}
3732
3733	/// The frame term is the packet's full duration, pre-skip included: Opus trims
3734	/// codec delay off the first packet, and reading the frame off what came out
3735	/// would shrink the term by exactly that much.
3736	#[kio::test]
3737	async fn opus_states_its_own_frame_duration() {
3738		let mut encoder = Encoder::new(&EncodeConfig::new(48_000, Layout::Mono)).unwrap();
3739		let mut catalog = encoder.catalog();
3740		// Every packet counts here; the warmup tests cover trimming.
3741		catalog.warmup = None;
3742
3743		let broadcast = moq_net::broadcast::Info::new().produce();
3744		let track = broadcast
3745			.create_track("audio", hang::container::track_info(hang::catalog::PRIORITY.audio))
3746			.unwrap();
3747		let subscriber = broadcast.consume();
3748		let mut producer = moq_mux::container::Producer::new(
3749			track,
3750			moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Audio),
3751		);
3752		let mut consumer = Consumer::new(&subscriber, &catalog, "audio", Options::new())
3753			.await
3754			.unwrap();
3755
3756		producer
3757			.write(moq_mux::container::Frame {
3758				timestamp: Timestamp::from_micros(0).unwrap(),
3759				decode: None,
3760				duration: None,
3761				payload: crate::single(encoder.encode_all(&vec![0.25f32; encoder.frame_size()]).unwrap()).payload,
3762				keyframe: true,
3763			})
3764			.unwrap();
3765		producer.cut(None).unwrap();
3766
3767		let frame = next_frame(&mut consumer).await.unwrap().expect("decoded frame");
3768		assert!(
3769			frame.data.len() / size_of::<f32>() < encoder.frame_size(),
3770			"pre-skip is trimmed"
3771		);
3772		// The cold-start prior reads 100 ms, plus one 20 ms packet.
3773		assert_eq!(consumer.delay(), std::time::Duration::from_millis(120));
3774	}
3775
3776	#[kio::test]
3777	async fn a_delay_beyond_max_age_is_refused() {
3778		let broadcast = moq_net::broadcast::Info::new().produce();
3779		let info = hang::container::track_info(hang::catalog::PRIORITY.audio)
3780			.with_max_age(std::time::Duration::from_millis(100));
3781		let _track = broadcast.create_track("audio", info).unwrap();
3782		let subscriber = broadcast.consume();
3783		let catalog = hang::catalog::AudioConfig::new(hang::catalog::AudioCodec::Pcm, 48_000, 1);
3784
3785		let options = |delay| Options {
3786			delay: Delay {
3787				min: Some(std::time::Duration::from_millis(delay)),
3788				..Delay::default()
3789			},
3790			estimate: false,
3791			..Options::new()
3792		};
3793		let err = Consumer::new(&subscriber, &catalog, "audio", options(101))
3794			.await
3795			.err()
3796			.expect("a delay the publisher cannot hold");
3797		assert!(matches!(err, Error::Unsupported(_)), "{err}");
3798
3799		let consumer = Consumer::new(&subscriber, &catalog, "audio", options(100))
3800			.await
3801			.unwrap();
3802		assert_eq!(consumer.delay(), std::time::Duration::from_millis(100));
3803	}
3804
3805	#[kio::test]
3806	async fn max_delay_is_clamped_to_publisher_max_age() {
3807		let broadcast = moq_net::broadcast::Info::new().produce();
3808		let info = hang::container::track_info(hang::catalog::PRIORITY.audio)
3809			.with_max_age(std::time::Duration::from_millis(100));
3810		let _track = broadcast.create_track("audio", info).unwrap();
3811		let subscriber = broadcast.consume();
3812		let catalog = hang::catalog::AudioConfig::new(hang::catalog::AudioCodec::Pcm, 48_000, 1);
3813
3814		let consumer = Consumer::new(
3815			&subscriber,
3816			&catalog,
3817			"audio",
3818			Options {
3819				delay: Delay {
3820					max: Some(std::time::Duration::from_millis(500)),
3821					..Delay::default()
3822				},
3823				..Options::new()
3824			},
3825		)
3826		.await
3827		.unwrap();
3828
3829		assert_eq!(consumer.max_delay(), std::time::Duration::from_millis(100));
3830	}
3831
3832	/// Opus pre-skip is padding before the decoded epoch, not missing media after
3833	/// the first short frame. The second frame must meet the first or playback
3834	/// fills the codec delay with silence and creates a startup glitch.
3835	#[kio::test]
3836	async fn opus_pre_skip_does_not_leave_a_timestamp_hole() {
3837		let input = Input {
3838			format: Format::F32,
3839			sample_rate: 48_000,
3840			layout: Layout::Mono,
3841		};
3842		let mut encoder = Encoder::new(&EncodeConfig::new(input.sample_rate, input.layout)).unwrap();
3843		let mut catalog = encoder.catalog();
3844		// Every packet counts here; the warmup tests cover trimming.
3845		catalog.warmup = None;
3846
3847		let broadcast = moq_net::broadcast::Info::new().produce();
3848		let track = broadcast
3849			.create_track("audio", hang::container::track_info(hang::catalog::PRIORITY.audio))
3850			.unwrap();
3851		let subscriber = broadcast.consume();
3852		let mut producer = moq_mux::container::Producer::new(
3853			track,
3854			moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Audio),
3855		);
3856		let mut consumer = Consumer::new(
3857			&subscriber,
3858			&catalog,
3859			"audio",
3860			Options {
3861				delay: Delay {
3862					max: Some(std::time::Duration::from_secs(1)),
3863					..Delay::default()
3864				},
3865				..Options::new()
3866			},
3867		)
3868		.await
3869		.unwrap();
3870
3871		let pcm = vec![0.25f32; encoder.frame_size()];
3872		for packet in 0..2 {
3873			producer
3874				.write(moq_mux::container::Frame {
3875					timestamp: Timestamp::from_scale(packet * encoder.frame_size() as u64, 48_000).unwrap(),
3876					decode: None,
3877					duration: None,
3878					payload: crate::single(encoder.encode_all(&pcm).unwrap()).payload,
3879					keyframe: true,
3880				})
3881				.unwrap();
3882			producer.cut(None).unwrap();
3883		}
3884
3885		let first = next_frame(&mut consumer).await.unwrap().expect("first decoded frame");
3886		let second = next_frame(&mut consumer).await.unwrap().expect("second decoded frame");
3887		let first_frames = first.data.len() / size_of::<f32>();
3888		let expected = advance(first.timestamp, first_frames, 48_000).unwrap();
3889		assert_eq!(second.timestamp, expected);
3890	}
3891
3892	#[kio::test]
3893	async fn a_playhead_event_reapplies_opus_pre_skip() {
3894		let input = Input {
3895			format: Format::F32,
3896			sample_rate: 48_000,
3897			layout: Layout::Mono,
3898		};
3899		let mut encoder = Encoder::new(&EncodeConfig::new(input.sample_rate, input.layout)).unwrap();
3900		let mut catalog = encoder.catalog();
3901		// Every packet counts here; the warmup tests cover trimming.
3902		catalog.warmup = None;
3903		let frame_size = encoder.frame_size();
3904
3905		let broadcast = moq_net::broadcast::Info::new().produce();
3906		let track = broadcast
3907			.create_track("audio", hang::container::track_info(hang::catalog::PRIORITY.audio))
3908			.unwrap();
3909		let subscriber = broadcast.consume();
3910		let mut producer = moq_mux::container::Producer::new(
3911			track,
3912			moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Audio),
3913		);
3914		let mut consumer = Consumer::new(
3915			&subscriber,
3916			&catalog,
3917			"audio",
3918			Options {
3919				delay: Delay {
3920					max: Some(std::time::Duration::from_secs(1)),
3921					..Delay::default()
3922				},
3923				..Options::new()
3924			},
3925		)
3926		.await
3927		.unwrap();
3928
3929		let pcm = vec![0.25f32; frame_size];
3930		let write = |producer: &mut moq_mux::container::Producer<_>, packet: u64, payload: bytes::Bytes| {
3931			producer
3932				.write(moq_mux::container::Frame {
3933					timestamp: Timestamp::from_scale(packet * frame_size as u64, 48_000).unwrap(),
3934					decode: None,
3935					duration: None,
3936					payload,
3937					keyframe: true,
3938				})
3939				.unwrap();
3940			producer.cut(None).unwrap();
3941		};
3942		write(
3943			&mut producer,
3944			0,
3945			crate::single(encoder.encode_all(&pcm).unwrap()).payload,
3946		);
3947		write(
3948			&mut producer,
3949			1,
3950			crate::single(encoder.encode_all(&pcm).unwrap()).payload,
3951		);
3952		producer.discontinuity().unwrap();
3953		write(
3954			&mut producer,
3955			2,
3956			crate::single(encoder.encode_all(&pcm).unwrap()).payload,
3957		);
3958		let _finished = producer.finish().unwrap();
3959
3960		let first = next_frame(&mut consumer).await.unwrap().expect("first decoded frame");
3961		let _second = next_frame(&mut consumer).await.unwrap().expect("second decoded frame");
3962		let resumed = next_frame(&mut consumer).await.unwrap().expect("resumed decoded frame");
3963		let first_frames = first.data.len() / size_of::<f32>();
3964		let resumed_frames = resumed.data.len() / size_of::<f32>();
3965		assert!(first_frames < frame_size, "the first epoch trims pre-skip");
3966		assert_eq!(
3967			resumed_frames, first_frames,
3968			"a playhead event reapplies pre-skip without flushing the decoder"
3969		);
3970	}
3971
3972	#[kio::test]
3973	async fn reads_the_container_the_catalog_declares() {
3974		let broadcast = moq_net::broadcast::Info::new().produce();
3975		let track = broadcast
3976			.create_track("audio", hang::container::track_info(hang::catalog::PRIORITY.audio))
3977			.unwrap();
3978		let observed = track.clone();
3979		let subscriber = broadcast.consume();
3980
3981		let mut catalog = hang::catalog::AudioConfig::new(hang::catalog::AudioCodec::Pcm, 48_000, 1);
3982		catalog.container = hang::catalog::Container::Loc;
3983
3984		let mut producer = moq_mux::container::Producer::new(
3985			track,
3986			moq_mux::catalog::hang::Wire::loc(moq_mux::container::Kind::Audio),
3987		);
3988		let max_delay = std::time::Duration::from_millis(250);
3989		let mut consumer = Consumer::new(
3990			&subscriber,
3991			&catalog,
3992			"audio",
3993			Options {
3994				delay: Delay {
3995					max: Some(max_delay),
3996					..Delay::default()
3997				},
3998				..Options::new()
3999			},
4000		)
4001		.await
4002		.unwrap();
4003		assert_eq!(live_max(&observed.subscription().unwrap()), Some(max_delay));
4004
4005		let samples = [0.25f32, -0.5, 0.75, -1.0];
4006		let payload: Vec<u8> = samples.iter().flat_map(|sample| sample.to_le_bytes()).collect();
4007		producer
4008			.write(moq_mux::container::Frame {
4009				timestamp: Timestamp::ZERO,
4010				decode: None,
4011				duration: None,
4012				payload: payload.into(),
4013				keyframe: true,
4014			})
4015			.unwrap();
4016
4017		let frame = next_frame(&mut consumer).await.unwrap().expect("decoded frame");
4018		assert_eq!(
4019			Format::F32.as_interleaved_f32(&frame.data, 1).unwrap().as_ref(),
4020			samples
4021		);
4022	}
4023
4024	/// The catalog picks the framing, not this crate. Hardcoding the legacy wire
4025	/// read a CMAF fragment as a varint timestamp plus a payload, which handed the
4026	/// codec garbage instead of failing, so anything published by `moq import
4027	/// fmp4` was undecodable.
4028	#[kio::test]
4029	async fn decodes_a_cmaf_framed_track() {
4030		let input = Input {
4031			format: Format::F32,
4032			sample_rate: 48_000,
4033			layout: Layout::Stereo,
4034		};
4035
4036		// One real Opus packet, so a mis-framed read can't accidentally decode.
4037		let mut encoder = Encoder::new(&EncodeConfig::new(input.sample_rate, input.layout)).unwrap();
4038		let mut catalog = encoder.catalog();
4039		// Every packet counts here; the warmup tests cover trimming.
4040		catalog.warmup = None;
4041		let pcm = vec![0.0f32; encoder.frame_size() * encoder.codec_channels() as usize];
4042		let packet = crate::single(encoder.encode_all(&pcm).unwrap());
4043
4044		// Re-describe the same rendition as CMAF and publish it that way.
4045		let muxer = moq_mux::container::fmp4::Muxer::audio(&catalog).unwrap();
4046		let init = muxer.init().unwrap().expect("an out-of-band codec has an init segment");
4047		catalog.container = hang::catalog::Container::Cmaf { init };
4048
4049		let broadcast = moq_net::broadcast::Info::new().produce();
4050		let subscriber = broadcast.consume();
4051		// A CMAF track counts in its init's ticks.
4052		let info = hang::container::track_info(hang::catalog::PRIORITY.audio).with_timescale(muxer.timescale());
4053		let track = broadcast.create_track("audio", info).unwrap();
4054		let container = moq_mux::catalog::hang::Wire::try_from(&catalog).unwrap();
4055		let mut producer = moq_mux::container::Producer::new(track, container);
4056
4057		let mut consumer = Consumer::new(&subscriber, &catalog, "audio", Options::new())
4058			.await
4059			.unwrap();
4060
4061		producer
4062			.write(moq_mux::container::Frame {
4063				timestamp: Timestamp::ZERO,
4064				decode: None,
4065				payload: packet.payload,
4066				keyframe: true,
4067				duration: None,
4068			})
4069			.unwrap();
4070		producer.cut(None).unwrap();
4071
4072		// The whole packet decodes: one 20 ms Opus frame at 48 kHz, less the pre-skip
4073		// trimmed off the first packet. Reading the fragment as legacy hands the codec
4074		// a slice of the moof instead, which still decodes, just to a shorter buffer.
4075		let frame = next_frame(&mut consumer).await.unwrap().expect("decoded frame");
4076		// `as_micros`, not `==`: the CMAF path carries the fmp4 timescale and
4077		// `Timestamp`'s equality is structural, so the scales would have to match too.
4078		assert_eq!(frame.timestamp.as_micros().unwrap(), 0);
4079		let samples = Format::F32.as_interleaved_f32(&frame.data, 2).unwrap();
4080		assert_eq!(samples.len(), (960 - 312) * 2);
4081	}
4082}