Skip to main content

moq_audio/encode/
producer.rs

1//! Encode raw PCM and publish it as a moq audio track.
2
3use std::collections::VecDeque;
4
5use bytes::Bytes;
6
7use moq_mux::catalog::hang::CatalogExt;
8use moq_mux::container::Frame as MuxFrame;
9use moq_net::Timestamp;
10
11use super::backlog::{Backlog, Raw, Stamp};
12use super::drift::{Drift, Steer};
13use super::encoded::Encoded;
14use super::encoder::{Config, Encoder, Input};
15use crate::resample::{Remix, Resampler};
16use crate::{Activity, Error, Frame};
17
18/// Encode and publication policy for [`Producer`].
19///
20/// `#[non_exhaustive]`: construct via [`Options::default`] and set fields, so
21/// new knobs can be added without breaking callers.
22#[derive(Clone, Debug)]
23#[non_exhaustive]
24pub struct Options {
25	/// Track name to publish under. `None` derives a unique one from the codec
26	/// (`0.opus`, then `1.opus`, ...), matching how the video side names its
27	/// track. Subscribers find it through the catalog either way.
28	pub track: Option<String>,
29	/// Codec input and encoded output config.
30	pub config: Config,
31	/// The connection's bandwidth, as an allocator over
32	/// [`Session::send_bandwidth`](moq_net::Session::send_bandwidth).
33	///
34	/// The audio track reserves its bitrate against it, so the video encoder sharing
35	/// the connection sizes itself against what's actually left rather than against
36	/// the whole uplink. Pass the same allocator to both.
37	///
38	/// Defaults to [`Allocator::unlimited`](moq_net::bandwidth::Allocator::unlimited),
39	/// which reserves nothing and leaves every sender at its configured rate.
40	///
41	/// Audio reserves but does not follow its share: Opus can retune live and PCM
42	/// can't at all, and at `hang`'s priorities audio outranks video, so it is only
43	/// ever squeezed on a link that can't carry audio alone.
44	pub bandwidth: moq_net::bandwidth::Allocator,
45	/// The time between join points: the minimum audio carried by each group. The
46	/// packet that reaches it closes the group, and the next packet opens a new one,
47	/// so a positive join shorter than a packet puts every packet in its own group.
48	///
49	/// Defaults to [`moq_mux::container::Join::DEFAULT`] (100 ms); [`Producer::new`] refuses zero.
50	/// Each group costs the relay a stream and its bookkeeping, so raising this trades per-group
51	/// overhead for coarser loss: a viewer that falls behind skips a whole group, and a lost packet
52	/// stalls the rest of its group until retransmitted. Packets still forward as
53	/// they are encoded rather than buffered until the group fills. A longer
54	/// [`Config::frame_duration`] (up to 60 ms for Opus) also packs more audio
55	/// per group, at the cost of encoder latency. An unfinished group remains open
56	/// across a pause or [`Producer::reanchor`] until the next write; use
57	/// [`Producer::discontinuity`] to close it when capture stops.
58	pub join: std::time::Duration,
59}
60
61impl Default for Options {
62	fn default() -> Self {
63		Self {
64			track: None,
65			config: Config::default(),
66			bandwidth: moq_net::bandwidth::Allocator::unlimited(),
67			join: moq_mux::container::Join::DEFAULT,
68		}
69	}
70}
71
72/// Encode raw PCM and publish it as a moq-mux audio track.
73///
74/// The input PCM layout is fixed at construction via [`Input`]; the codec
75/// config via [`Options`]. Subsequent [`write`](Self::write) calls just pass a
76/// [`Frame`]: payload bytes and a timestamp.
77///
78/// The catalog rendition is registered at construction (not on first write), so
79/// a subscriber that opens the catalog before any frames arrive still sees the
80/// track.
81pub struct Producer {
82	encoder: Encoder,
83	/// A publish that failed after the codec advanced past its packet, which ended the track with an
84	/// error: every later call reports the cause rather than stamping what follows.
85	failed: Option<Error>,
86	bitrate: moq_net::bandwidth::Rate,
87	input: Input,
88	/// Converts the input layout to the codec's, when they differ.
89	remix: Option<Remix>,
90	resampler: Option<Resampler>,
91	/// Steers the resampler onto the input's timestamps, for a capture whose device counts
92	/// samples on a clock of its own.
93	drift: Option<Drift>,
94	track: moq_mux::container::Producer<moq_mux::container::legacy::Wire, hang::catalog::AudioConfig>,
95	pending: Vec<f32>,
96	backlog: Backlog,
97	active: bool,
98	reset_pending: bool,
99	/// Codec samples a group carries before the packet reaching it closes the group.
100	group_samples: u64,
101	/// Codec samples in the open group.
102	grouped: u64,
103	/// Samples emitted since the current anchor (reset by [`reanchor`](Self::reanchor)).
104	frames_produced: u64,
105	/// Stamps of the frames the codec has been given but has not yet returned a packet for,
106	/// oldest first: it returns one packet per frame in order, however late.
107	in_flight: VecDeque<Stamp>,
108	/// Taken from the first frame after each (re)start. `None` until the first write so the
109	/// next frame re-anchors to its timestamp.
110	anchor: Option<Anchor>,
111	/// Where the latest stamped packet ends, in microseconds: the next anchor's floor, since
112	/// group starts strictly increase.
113	stamped: u64,
114	/// Where the newest published packet ends: the open group's end when encoding stops, since
115	/// frames stamped since may still wait in the backlog or the codec. `None` after priming,
116	/// which ends where it starts and which the muxer may write a unit past a marker.
117	published: Option<Timestamp>,
118	/// An encoder reset that still needs a marker group before its next packet.
119	pending_discontinuity: bool,
120	/// Whether no packet has been published since the last marker group, or the track began, so a
121	/// break needs no marker of its own.
122	decoder_boundary: bool,
123	/// How the encoder classified the packet it coded most recently: [`Activity::Dtx`] exactly while
124	/// a voice encode is silent.
125	activity: Activity,
126	/// Whether a voice encode declared the end of speech, and drops packets until it resumes.
127	silent: bool,
128}
129
130/// Where a timeline begins: emitted PTS = `at + frames_produced / codec_rate`.
131#[derive(Clone, Copy, Debug)]
132struct Anchor {
133	/// The first frame's timestamp in microseconds, raised to `floor`.
134	at: u64,
135	/// Where the packets stamped before this timeline end, in microseconds. Codec priming folded
136	/// below `at` stops here.
137	floor: u64,
138}
139
140struct Terminal {
141	packets: Vec<Encoded>,
142	end: Timestamp,
143	start: Timestamp,
144	frame_size: usize,
145	codec_rate: u32,
146}
147
148/// A published track whose PCM layout is not known yet.
149///
150/// The track exists in the broadcast immediately, so its name and subscriber
151/// state are available, while the catalog rendition waits for
152/// [`encode`](Self::encode) to supply the layout it describes. Unlike a catalog
153/// [`Reserved`](moq_mux::catalog::Reserved) this does not withhold the catalog:
154/// subscribers see the broadcast without this rendition until it resolves.
155struct Reserved {
156	track: moq_mux::container::Producer<moq_mux::container::legacy::Wire, hang::catalog::AudioConfig>,
157}
158
159impl Reserved {
160	/// Publish on the track `create` makes from the catalog's info.
161	fn new<E: CatalogExt>(
162		catalog: moq_mux::catalog::Producer<E>,
163		options: &Options,
164		create: impl FnOnce(moq_net::track::Info) -> Result<moq_net::track::Producer, Error>,
165	) -> Result<Self, Error> {
166		if options.join.is_zero() {
167			return Err(Error::Unsupported("a join of zero opens no group".to_owned()));
168		}
169		// The catalog's info carries the microsecond timescale audio hang frames stamp, so
170		// Lite05 subscribers know what scale to expect and the model layer accepts
171		// Frame::timestamp on append, plus whatever max age the catalog declared.
172		let track = create(catalog.track_info(hang::catalog::PRIORITY.audio))?;
173		// Held to end the track if the catalog refuses the rendition, so a subscriber already
174		// waiting on it learns that rather than reading a drop.
175		let held = track.clone();
176		let track = match catalog.audio(
177			track,
178			moq_mux::container::legacy::Wire(moq_mux::container::Kind::Audio),
179			None,
180		) {
181			Ok(track) => track,
182			Err(err) => {
183				let _ = held.abort(moq_net::Error::NotFound);
184				return Err(err.into());
185			}
186		};
187
188		Ok(Self { track })
189	}
190
191	/// Build the encoder for `input` and register the rendition describing it.
192	///
193	/// Separate from [`encode`](Self::encode), which cannot fail, so a layout the
194	/// codec rejects leaves the track intact to abort with that error. A `drift`
195	/// encode always resamples, so its ratio can follow the input's timestamps.
196	fn register(&mut self, input: Input, options: &Options, drift: Option<Drift>) -> Result<Registered, Error> {
197		let remix = (input.layout != options.config.layout)
198			.then(|| Remix::new(input.layout, options.config.layout))
199			.transpose()?;
200		let encoder = Encoder::new(&options.config)?;
201
202		let resampler = if drift.is_some() {
203			Some(Resampler::adjustable(
204				input.sample_rate,
205				encoder.codec_rate(),
206				encoder.codec_channels(),
207			)?)
208		} else if input.sample_rate == encoder.codec_rate() {
209			None
210		} else {
211			// Use microsecond precision so 2.5 ms frame_duration (supported by
212			// libopus) doesn't truncate to 2 ms.
213			let chunk_frames =
214				((input.sample_rate as u128 * encoder.config().frame_duration.as_micros()) / 1_000_000) as usize;
215			Some(Resampler::new(
216				input.sample_rate,
217				encoder.codec_rate(),
218				encoder.codec_channels(),
219				chunk_frames,
220			)?)
221		};
222
223		let mut catalog = encoder.catalog();
224		// A resampler holds input past the frame it completes, so its frames trail by more than their
225		// own duration: measure the delay rather than state the encoder's zero.
226		if resampler.is_some() {
227			catalog.delay = None;
228		}
229		self.track.set(catalog)?;
230
231		let group_samples = options.join.as_nanos() * u128::from(encoder.codec_rate());
232		let group_samples = u64::try_from(group_samples.div_ceil(1_000_000_000)).unwrap_or(u64::MAX);
233
234		Ok(Registered {
235			encoder,
236			input,
237			remix,
238			resampler,
239			drift,
240			group_samples,
241		})
242	}
243
244	/// Spend the reservation on a registered encoder, publishing through the track.
245	fn encode(self, registered: Registered) -> Producer {
246		let history = self.track.track().info().max_age.unwrap_or(hang::container::MAX_AGE);
247		let bitrate = registered.encoder.bitrate();
248		self.track.report_bitrate(bitrate);
249
250		Producer {
251			backlog: Backlog::new(
252				history,
253				registered.encoder.frame_size(),
254				registered.encoder.codec_rate(),
255			),
256			active: true,
257			reset_pending: false,
258			bitrate,
259			encoder: registered.encoder,
260			failed: None,
261			input: registered.input,
262			remix: registered.remix,
263			resampler: registered.resampler,
264			drift: registered.drift,
265			track: self.track,
266			pending: Vec::new(),
267			group_samples: registered.group_samples,
268			grouped: 0,
269			frames_produced: 0,
270			in_flight: VecDeque::new(),
271			anchor: None,
272			stamped: 0,
273			published: None,
274			pending_discontinuity: false,
275			decoder_boundary: true,
276			activity: Activity::Active,
277			silent: false,
278		}
279	}
280}
281
282/// Create the track [`Options::track`] names in `broadcast`, or a unique one after the codec.
283fn named<'a>(
284	broadcast: &'a moq_net::broadcast::Producer,
285	options: &'a Options,
286) -> impl FnOnce(moq_net::track::Info) -> Result<moq_net::track::Producer, Error> + 'a {
287	move |info| match &options.track {
288		Some(name) => Ok(broadcast
289			.create_track(name.clone(), info)
290			.ok_or_else(|| hang::Error::Duplicate(name.clone()))?),
291		// Mirrors the video side, which derives a unique name from the codec
292		// rather than making every caller invent one.
293		None => Ok(broadcast.unique_track(&format!(".{}", options.config.codec), info)),
294	}
295}
296
297/// Accept `request` with `info`, failing if that ended the track, as a renewal with another
298/// info does, so nothing registers a rendition for a track that will never carry frames.
299fn accepted(
300	request: moq_net::track::Request,
301	info: moq_net::track::Info,
302) -> Result<moq_net::track::Producer, moq_net::Error> {
303	let track = request.accept(info);
304	match track.poll_closed(&kio::Waiter::noop()) {
305		std::task::Poll::Ready(Err(err)) => Err(err),
306		_ => Ok(track),
307	}
308}
309
310/// A registered rendition, waiting for its [`Reserved`] to be spent on it.
311///
312/// Proof that [`Reserved::register`] succeeded, so [`Reserved::encode`] takes no
313/// fallible step and cannot strand the track it consumes.
314struct Registered {
315	encoder: Encoder,
316	input: Input,
317	remix: Option<Remix>,
318	resampler: Option<Resampler>,
319	drift: Option<Drift>,
320	group_samples: u64,
321}
322
323impl Producer {
324	/// Publish a track encoding `input` into `broadcast`, registering its
325	/// rendition in `catalog` immediately.
326	pub fn new<E: CatalogExt>(
327		broadcast: &mut moq_net::broadcast::Producer,
328		catalog: moq_mux::catalog::Producer<E>,
329		input: Input,
330		options: &Options,
331	) -> Result<Self, Error> {
332		Self::build(catalog, input, options, None, named(broadcast, options))
333	}
334
335	/// Publish a track encoding `input` on the track a subscriber's `request` asks for,
336	/// registering its rendition in `catalog` immediately, as [`new`](Self::new) does.
337	///
338	/// This is how an on-demand publisher serves a track asked for again after its last producer
339	/// dropped while read: serve it with the options it was first published with. Its readers
340	/// hold the track info they set, so options that change it end the track with
341	/// [`MalformedTrack`](moq_net::Error::MalformedTrack) and fail here. Nothing checks the rest: its
342	/// readers also decode with the codec settings they were first given, so keep those too. The
343	/// request names the track, so [`Options::track`] must be `None`. A config the codec refuses
344	/// rejects the request with [`NotFound`](moq_net::Error::NotFound), or ends the
345	/// accepted track with it.
346	pub fn requested<E: CatalogExt>(
347		request: moq_net::track::Request,
348		catalog: moq_mux::catalog::Producer<E>,
349		input: Input,
350		options: &Options,
351	) -> Result<Self, Error> {
352		let mut request = Some(request);
353		let built = match options.track {
354			Some(_) => Err(Error::Unsupported("a requested track is already named".to_owned())),
355			None => Self::build(catalog, input, options, None, |info| {
356				Ok(accepted(request.take().expect("accepted once"), info)?)
357			}),
358		};
359		// Not accepted: the subscribers waiting on it learn it won't be served. `NotFound`, not
360		// `Unsupported`, which moq-lite sends as a retryable `Internal`, so a relay would ask again.
361		if let (Err(_), Some(request)) = (&built, request) {
362			request.reject(moq_net::Error::NotFound);
363		}
364		built
365	}
366
367	/// [`new`](Self::new) for a capture device, whose samples keep its own clock: each frame's
368	/// timestamp is when its first sample was captured on the host's clock, and the encode
369	/// resamples by up to 2000 ppm to stay on it rather than drift from it by the sample count.
370	#[cfg(any(feature = "capture", test))]
371	pub(crate) fn capture<E: CatalogExt>(
372		broadcast: &mut moq_net::broadcast::Producer,
373		catalog: moq_mux::catalog::Producer<E>,
374		input: Input,
375		options: &Options,
376	) -> Result<Self, Error> {
377		Self::build(catalog, input, options, Some(Drift::new()), named(broadcast, options))
378	}
379
380	fn build<E: CatalogExt>(
381		catalog: moq_mux::catalog::Producer<E>,
382		input: Input,
383		options: &Options,
384		drift: Option<Drift>,
385		create: impl FnOnce(moq_net::track::Info) -> Result<moq_net::track::Producer, Error>,
386	) -> Result<Self, Error> {
387		let mut reserved = Reserved::new(catalog, options, create)?;
388		match reserved.register(input, options, drift) {
389			Ok(registered) => Ok(reserved.encode(registered)),
390			Err(err) => {
391				// A subscriber may already be waiting on the track; tell it the track won't be served.
392				reserved.track.abort(moq_net::Error::NotFound);
393				Err(err)
394			}
395		}
396	}
397
398	/// The cause of an earlier publish failure, which ended the track.
399	fn check(&self) -> Result<(), Error> {
400		self.failed.clone().map_or(Ok(()), Err)
401	}
402
403	/// End the track with an error past everything published, so subscribers stop waiting on it
404	/// while this producer is still held. Readers keep every packet published before it.
405	fn fail_track(&mut self) {
406		let _ = self.track.cut(None);
407		let _ = self.track.track().clone().fail(moq_net::StreamError::Internal.into());
408	}
409
410	/// The name of the published track, which is [`Options::track`] resolved.
411	pub fn track_name(&self) -> &str {
412		self.track.name()
413	}
414
415	/// A watch-only handle to the track's subscriber demand, created eagerly so
416	/// subscription state is observable before any frames arrive. Watch it via
417	/// [`wanted`](moq_net::track::Demand::wanted) / [`wanted_changed`](moq_net::track::Demand::wanted_changed).
418	pub fn demand(&self) -> moq_net::track::Demand {
419		self.track.track().demand()
420	}
421
422	#[cfg(any(feature = "capture", test))]
423	pub(crate) fn track(&self) -> &moq_net::track::Producer {
424		self.track.track()
425	}
426
427	/// Whether a [`Kind::Voice`](super::Kind::Voice) encode is sending its talker, or
428	/// withholding the silence it is in.
429	///
430	/// A local "am I talking" indicator without running a second voice detector
431	/// over the microphone. It reads [`Activity::Dtx`] from the end of speech the
432	/// track declared until speech resumes, and [`Activity::Active`] otherwise,
433	/// including for every other kind.
434	pub fn activity(&self) -> Activity {
435		self.activity
436	}
437
438	/// Current encoder target bitrate.
439	pub fn bitrate(&self) -> moq_net::bandwidth::Rate {
440		self.bitrate
441	}
442
443	/// Retune the live encoder to `bitrate`.
444	pub fn set_bitrate(&mut self, bitrate: moq_net::bandwidth::Rate) -> Result<(), Error> {
445		self.check()?;
446		let encoder = &mut self.encoder;
447		let previous = encoder.bitrate();
448		encoder.set_bitrate(bitrate)?;
449		// Advertise the configured target in place, so encoded-byte estimates cannot replace it.
450		if let Err(err) = self.track.set_bitrate(encoder.bitrate().as_bps()) {
451			// Keep the encoder on what the catalog still advertises. It accepted that rate before,
452			// so the publish error is the one to report.
453			let _ = encoder.set_bitrate(previous);
454			return Err(err.into());
455		}
456		self.bitrate = encoder.bitrate();
457		self.track.report_bitrate(self.bitrate);
458		Ok(())
459	}
460
461	/// Re-anchor the timeline to the next frame's timestamp, dropping any
462	/// partial input frame. Call this when resuming after an idle gap (e.g. a
463	/// released-then-reopened microphone) so the gap appears in the PTS and
464	/// audio stays aligned with a wall-clock video track, rather than the gap
465	/// being compressed out by the running sample count. If the codec had
466	/// started, a marker group is published before the next packet so
467	/// subscribers jump the playhead.
468	///
469	/// This is for a gap the caller learns of only once audio returns, such as
470	/// a device stall: until then subscribers see an undeclared stall. A stop
471	/// known as it happens, such as a mute, takes
472	/// [`discontinuity`](Self::discontinuity) instead, which needs no
473	/// `reanchor` after it.
474	pub fn reanchor(&mut self) {
475		if self.encoder.started() || !self.backlog.is_empty() {
476			self.pending_discontinuity = true;
477		}
478		self.reset_state();
479	}
480
481	fn reset_state(&mut self) {
482		self.anchor = None;
483		self.activity = Activity::Active;
484		self.frames_produced = 0;
485		self.pending.clear();
486		self.reset_pending = true;
487		if self.backlog.is_empty() {
488			self.encoder.reset();
489			self.in_flight.clear();
490		}
491		// The resampler holds samples of its own, plus filter state primed by them.
492		// Left alone, `finish` would flush that pre-reset audio onto the track
493		// (stamped at an anchor that no longer exists), and the next write would run
494		// the new audio through a filter still ringing with the old.
495		if let Some(resampler) = self.resampler.as_mut() {
496			resampler.reset();
497		}
498		if let Some(drift) = self.drift.as_mut() {
499			drift.restart();
500		}
501	}
502
503	/// Push one [`Frame`] of PCM in the layout declared by [`Input`]. Encodes and
504	/// publishes as many packets as the input contains; any partial trailing
505	/// frame is carried to the next call.
506	///
507	/// The first frame after construction (or [`reanchor`](Self::reanchor))
508	/// anchors the timeline: its timestamp becomes the anchor, and emitted PTS
509	/// then advances purely by the running sample count, so subsequent frames'
510	/// timestamps are ignored. A timeline only moves forward, so an anchor before
511	/// where the packets already stamped end is raised to there. An idle gap is
512	/// only reflected in the PTS if you call [`reanchor`](Self::reanchor) on
513	/// resume (which re-anchors from the next frame's wall-clock stamp); writing
514	/// straight across a gap without resetting compresses it out.
515	///
516	/// [`Frame::activity`] is ignored: the encoder classifies what it actually
517	/// produced, which [`activity`](Self::activity) reports.
518	pub fn write(&mut self, frame: &Frame) -> Result<(), Error> {
519		self.check()?;
520		let timestamp_us = (frame.timestamp.as_micros().ok())
521			.and_then(|micros| u64::try_from(micros).ok())
522			.ok_or_else(|| {
523				Error::Unsupported(format!(
524					"frame timestamp {:?} is unscaled or out of range",
525					frame.timestamp
526				))
527			})?;
528		if let Some(anchor) = self.anchor
529			&& !self.steer(anchor, frame)?
530		{
531			return Ok(());
532		}
533		let floor = self.stamped;
534		let anchor = *self.anchor.get_or_insert(Anchor {
535			at: timestamp_us.max(floor),
536			floor,
537		});
538
539		let input = &self.input;
540		let (format, channels) = (input.format, input.layout.channels());
541		let pcm = format.as_interleaved_f32(frame.data.as_ref(), channels)?;
542		let pcm = match &self.remix {
543			Some(remix) => remix.process(&pcm),
544			None => pcm.into_owned(),
545		};
546		let pcm: Vec<f32> = match self.resampler.as_mut() {
547			Some(r) => r.process(&pcm, frame.timestamp)?,
548			None => pcm,
549		};
550
551		self.pending.extend(pcm);
552
553		self.publish_full_frames(anchor)
554	}
555
556	/// Steer a capture's resampler so `frame`'s first sample is stamped when it was captured, or
557	/// re-anchor on it when the stamps jumped further than a ratio can follow. False for a frame
558	/// to drop, whose time the published audio already covers.
559	fn steer(&mut self, anchor: Anchor, frame: &Frame) -> Result<bool, Error> {
560		let (Some(drift), Some(resampler)) = (self.drift.as_mut(), self.resampler.as_mut()) else {
561			return Ok(true);
562		};
563		let channels = self.input.layout.channels() as usize;
564		let bytes = self.input.format.bytes_per_sample() * channels;
565		let frames = (frame.data.len() / bytes.max(1)) as u64;
566		let duration = std::time::Duration::from_micros(frames * 1_000_000 / u64::from(self.input.sample_rate));
567		let codec_rate = f64::from(self.encoder.codec_rate());
568		let offset = (resampler.position() * 1e6 / codec_rate).round() as u64;
569		let pts = Timestamp::from_micros(anchor.at.saturating_add(offset))?;
570		match drift.observe(frame.timestamp, pts, duration) {
571			Steer::Hold => {}
572			Steer::Ratio(relative) => resampler.adjust(relative)?,
573			Steer::Resync => self.reanchor(),
574			Steer::Drop => return Ok(false),
575		}
576		Ok(true)
577	}
578
579	/// Encode and publish every full frame in `pending`, keeping any partial
580	/// trailing frame for the next call.
581	///
582	/// Frames are read in place and the remainder moves to the front once, so a
583	/// large batch costs linear rather than quadratic copying.
584	fn publish_full_frames(&mut self, anchor: Anchor) -> Result<(), Error> {
585		let frame_samples = self.encoder.frame_size() * self.encoder.codec_channels() as usize;
586		// Taken so each frame can be borrowed while `self` encodes it; restored below on every path.
587		let mut pending = std::mem::take(&mut self.pending);
588		let mut consumed = 0;
589		let mut result = Ok(());
590		while result.is_ok() && pending.len() - consumed >= frame_samples {
591			let frame = &pending[consumed..consumed + frame_samples];
592			// A frame that fails is consumed too, so it is never encoded twice.
593			consumed += frame_samples;
594			result = self.publish_frame(anchor, frame);
595		}
596		pending.drain(..consumed);
597		self.pending = pending;
598		result
599	}
600
601	/// Stamp one codec frame, then encode it now or keep it in the backlog.
602	fn publish_frame(&mut self, anchor: Anchor, samples: &[f32]) -> Result<(), Error> {
603		let stamp = self.stamp(anchor)?;
604		let end = Self::timestamp(anchor, self.frames_produced, 0, self.encoder.codec_rate())?;
605		let reset = std::mem::take(&mut self.reset_pending);
606		let discontinuity = std::mem::take(&mut self.pending_discontinuity);
607		if self.active && self.backlog.is_empty() {
608			return self.encode_frame(samples, stamp, reset, discontinuity);
609		}
610		// Only a frame that waits needs its own copy.
611		self.backlog.push(Raw {
612			samples: samples.to_vec(),
613			stamp,
614			end,
615			reset,
616			discontinuity,
617		});
618		Ok(())
619	}
620
621	/// Stamp the next codec frame on `anchor`, and count it produced.
622	fn stamp(&mut self, anchor: Anchor) -> Result<Stamp, Error> {
623		let (delay, codec_rate) = (self.encoder.folded_delay(), self.encoder.codec_rate());
624		let start = Self::timestamp(anchor, self.frames_produced, delay, codec_rate)?;
625		self.frames_produced += self.encoder.frame_size() as u64;
626		let end = Self::timestamp(anchor, self.frames_produced, delay, codec_rate)?;
627		self.stamped = end.as_micros()? as u64;
628		Ok(Stamp { start, end })
629	}
630
631	fn encode_frame(&mut self, samples: &[f32], stamp: Stamp, reset: bool, discontinuity: bool) -> Result<(), Error> {
632		self.check()?;
633		// A break before anything was published, such as history expiring before the first
634		// subscriber, has nothing to separate.
635		if discontinuity && !self.decoder_boundary {
636			self.track.discontinuity()?;
637			self.decoder_boundary = true;
638		}
639		let encoder = &mut self.encoder;
640		if reset {
641			encoder.reset();
642			self.in_flight.clear();
643		}
644		encoder.encode(samples)?;
645		self.publish_ready(Some(stamp))
646	}
647
648	/// Publish every packet the codec has ready, each stamped with the frame it pairs with:
649	/// the oldest held stamp, then `submitted`, the frame just encoded, which is queued only
650	/// when the codec holds its packet, so a codec that holds nothing never fills the queue.
651	fn publish_ready(&mut self, mut submitted: Option<Stamp>) -> Result<(), Error> {
652		while let Some(packet) = self.encoder.receive()? {
653			let Some(stamp) = self.in_flight.pop_front().or_else(|| submitted.take()) else {
654				return Err(Error::Codec(format!(
655					"{} returned more packets than it was given frames",
656					self.encoder.name()
657				)));
658			};
659			// The codec and its timestamp queue already advanced past this packet, so no later
660			// write could stamp what follows: end the producer with the cause.
661			if let Err(err) = self.publish_gated(packet, stamp) {
662				self.fail_track();
663				self.failed = Some(err.clone());
664				return Err(err);
665			}
666		}
667		self.in_flight.extend(submitted);
668		Ok(())
669	}
670
671	/// Capture controls encoding independently of keeping its input open.
672	#[cfg(any(feature = "capture", test))]
673	pub(crate) fn set_active(&mut self, active: bool, now: Timestamp) -> Result<(), Error> {
674		self.backlog.expire(now);
675		// Replayed groups land as fresh arrivals, so only this cut keeps a rejoining live
676		// subscriber from receiving all the retained audio before the live edge.
677		if active && let Some(budget) = self.track.track().subscription().and_then(|sub| replay_budget(&sub)) {
678			self.backlog.expire_within(now, budget);
679		}
680		// Live input completes the partial frame within one codec frame, so only idle refreshes expire it.
681		if !active {
682			self.expire_partial(now)?;
683		}
684		if self.backlog.take_evicted() {
685			self.reset_pending = true;
686			self.pending_discontinuity = true;
687		}
688		// Nothing reads on, so the open group ends where its last packet does: a reader of it,
689		// such as a fetch, finishes while the audio is retained. The epoch continues, so the
690		// replay that follows opens the next group with no marker.
691		// A group ending in priming stays open for the packet that moves on, as `publish` leaves it.
692		if self.active
693			&& !active
694			&& !self.track.needs_keyframe()
695			&& let Some(end) = self.published
696		{
697			self.track.cut(Some(end))?;
698		}
699		self.active = active;
700		// One codec frame per turn lets capture keep draining while catching up.
701		if active && let Some(raw) = self.backlog.pop() {
702			self.track.history(raw.stamp.start);
703			self.encode_frame(&raw.samples, raw.stamp, raw.reset, raw.discontinuity)?;
704		}
705		Ok(())
706	}
707
708	/// The partial codec frame and the resampler's tail follow the retained frames, so once those
709	/// are gone they expire on the same window, rather than reaching the track stale when it finishes.
710	#[cfg(any(feature = "capture", test))]
711	fn expire_partial(&mut self, now: Timestamp) -> Result<(), Error> {
712		let Some(anchor) = self.anchor else { return Ok(()) };
713		if !self.backlog.is_empty() {
714			return Ok(());
715		}
716		let channels = self.encoder.codec_channels() as usize;
717		let frames = self.frames_produced + (self.pending.len() / channels) as u64;
718		let end = Self::timestamp(anchor, frames, 0, self.encoder.codec_rate())?;
719		if self.backlog.expired(end, now) {
720			self.reanchor();
721		}
722		Ok(())
723	}
724
725	#[cfg(any(feature = "capture", test))]
726	pub(crate) fn backlog_ready(&self) -> bool {
727		self.active && !self.backlog.is_empty()
728	}
729
730	#[cfg(any(feature = "capture", test))]
731	pub(crate) fn backlog_deadline(&self) -> Option<std::time::Duration> {
732		self.backlog.deadline()
733	}
734
735	/// Whether unencoded history is still retained.
736	#[cfg(feature = "capture")]
737	pub(crate) fn retains(&self) -> bool {
738		!self.backlog.is_empty()
739	}
740
741	/// PTS of the frame `frames` samples past the anchor, stamped `delay` samples
742	/// earlier to fold in codec priming the catalog can't signal.
743	///
744	/// Priming that would land before the anchor's floor, zero or where the previous
745	/// timeline's packets end, is stamped at the floor instead: it decodes to the
746	/// codec's warm-up rather than to input, so only its spacing is lost.
747	fn timestamp(anchor: Anchor, frames: u64, delay: usize, codec_rate: u32) -> Result<Timestamp, Error> {
748		let frames = i128::from(frames) - delay as i128;
749		let offset_us = (frames * 1_000_000).div_euclid(i128::from(codec_rate));
750		let micros = (i128::from(anchor.at) + offset_us).max(i128::from(anchor.floor));
751		let micros = u64::try_from(micros).map_err(|_| moq_net::TimeOverflow)?;
752		Ok(Timestamp::from_micros(micros)?)
753	}
754
755	/// Publish `encoded` unless a voice encode is silent, so a silent talker sends nothing.
756	///
757	/// libopus's discontinuous transmission decides what is silence: its first no-transmit packet
758	/// declares the end of speech where that packet starts, as a mute's
759	/// [`discontinuity`](Self::discontinuity) does, and the rest of the silence is dropped, its
760	/// keep-alives included. The packet speech resumes with opens a new group on the same timeline.
761	/// Only voice turns transmission off, so every other encode publishes everything.
762	fn publish_gated(&mut self, encoded: Encoded, stamp: Stamp) -> Result<(), Error> {
763		let silent = encoded.activity.is_dtx() || (self.silent && encoded.in_dtx);
764		self.activity = match silent {
765			true => Activity::Dtx,
766			false => encoded.activity,
767		};
768		if !silent {
769			self.silent = false;
770			self.publish(encoded, stamp)?;
771			self.decoder_boundary = false;
772			return Ok(());
773		}
774		if !std::mem::replace(&mut self.silent, true) && !self.decoder_boundary {
775			// Bound a group the join left open where speech ended, so the marker follows it.
776			if !self.track.needs_keyframe() {
777				self.track.cut(Some(stamp.start))?;
778			}
779			self.track.discontinuity()?;
780			self.decoder_boundary = true;
781		}
782		Ok(())
783	}
784
785	fn publish(&mut self, encoded: Encoded, stamp: Stamp) -> Result<(), Error> {
786		// Every packet decodes on its own, so a group may start at any of them: the first packet
787		// after a cut opens one. Codecs recover independently after a dropped group.
788		let keyframe = self.track.needs_keyframe();
789		if keyframe {
790			self.grouped = 0;
791		}
792		let mux_frame = MuxFrame {
793			timestamp: stamp.start,
794			decode: None,
795			payload: encoded.payload,
796			keyframe,
797			duration: None,
798		};
799		self.track.write(mux_frame)?;
800		self.published = (stamp.end > stamp.start).then_some(stamp.end);
801		self.grouped += self.encoder.frame_size() as u64;
802		// Cut as soon as the group is long enough rather than when the next packet arrives, so
803		// the relay sees it finish without waiting. The group ends whole where its last packet
804		// ends, which is where the next one starts, so a reader can tell the group starting there
805		// continues it. Priming stamped at the floor ends where it starts, as the packet after it
806		// does: group starts strictly increase, so the group stays open for the packet that moves on.
807		if self.grouped >= self.group_samples && stamp.end > stamp.start {
808			self.track.cut(Some(stamp.end))?;
809		}
810		Ok(())
811	}
812
813	/// Publish terminal packets after an empty frame that carries their logical endpoint.
814	fn publish_terminal(
815		track: &mut moq_mux::container::Producer<moq_mux::container::legacy::Wire, hang::catalog::AudioConfig>,
816		terminal: Terminal,
817	) -> Result<(), Error> {
818		track.write(MuxFrame {
819			timestamp: terminal.end,
820			decode: None,
821			payload: Bytes::new(),
822			keyframe: true,
823			duration: None,
824		})?;
825
826		// The group ends where the source does, unless the padding the codec needs to finish it
827		// starts past that: a group never ends below a frame of its own.
828		let mut end = terminal.end;
829		for (index, packet) in terminal.packets.into_iter().enumerate() {
830			let offset = Timestamp::from_scale((index * terminal.frame_size) as u64, terminal.codec_rate as u64)?
831				.convert(terminal.start.scale().ok_or(moq_net::TimeOverflow)?)?;
832
833			let timestamp = terminal.start.checked_add(offset)?;
834			track.write(MuxFrame {
835				timestamp,
836				decode: None,
837				payload: packet.payload,
838				keyframe: false,
839				duration: None,
840			})?;
841			if timestamp > end {
842				end = timestamp;
843			}
844		}
845
846		track.cut(Some(end))?;
847		Ok(())
848	}
849
850	/// Mark a break in the published timeline and reset codec state.
851	///
852	/// Call this when capture stops rather than merely gapping between packets: going idle,
853	/// switching source, or anything else that resumes on a new anchor. Buffered samples
854	/// are dropped, and the next frame sets a fresh anchor. See
855	/// [`Producer::discontinuity`](moq_mux::container::Producer::discontinuity).
856	///
857	/// Unlike [`reanchor`](Self::reanchor), the marker goes out now and closes the
858	/// open group, so subscribers hear the silence as declared from its start: the
859	/// decoder reports it as [`Read::End`](crate::decode::Read::End), and a player
860	/// fills it with comfort noise rather than counting a gap.
861	pub fn discontinuity(&mut self) -> Result<(), Error> {
862		// A marker already ends what was published, such as a voice encode's pause.
863		if !self.decoder_boundary {
864			self.track.discontinuity()?;
865		}
866		self.pending_discontinuity = false;
867		self.decoder_boundary = true;
868		self.reset_state();
869		Ok(())
870	}
871
872	/// Flush pending samples, resampler output, and codec lookahead, then finalize
873	/// the track.
874	///
875	/// Consumes the producer, releasing the codec and input scratch. The returned [`Finished`]
876	/// keeps the track and its catalog rendition published, and can still
877	/// [`abort`](Finished::abort) them. A finish that fails ends the track with an error instead.
878	pub fn finish(self) -> Result<Finished, Error> {
879		self.end(None)
880	}
881
882	/// [`finish`](Self::finish) the track with `err`, for a source that failed: subscribers keep
883	/// every packet published, then get `err` instead of the end of stream.
884	#[cfg(feature = "capture")]
885	pub(crate) fn fail(self, err: moq_net::Error) -> Result<Finished, Error> {
886		self.end(Some(err))
887	}
888
889	/// Publish everything still held, then end the track with `err` or cleanly.
890	fn end(mut self, err: Option<moq_net::Error>) -> Result<Finished, Error> {
891		if let Err(cause) = self.check().and_then(|()| self.drain()) {
892			// Every published packet stays readable, then subscribers get an error rather than an
893			// end that would claim the source was published whole: `err` when the source failed.
894			let _ = self
895				.track
896				.fail(err.unwrap_or_else(|| moq_net::StreamError::Internal.into()));
897			return Err(cause);
898		}
899		let track = match err {
900			None => self.track.finish()?,
901			Some(err) => self.track.fail(err)?,
902		};
903		Ok(Finished { track })
904	}
905
906	/// Publish everything the codec, resampler, and backlog still hold.
907	fn drain(&mut self) -> Result<(), Error> {
908		// Preserve the final retained history after capture ends, even without live demand.
909		self.active = true;
910		while let Some(raw) = self.backlog.pop() {
911			self.track.history(raw.stamp.start);
912			self.encode_frame(&raw.samples, raw.stamp, raw.reset, raw.discontinuity)?;
913		}
914		if self.reset_pending {
915			self.encoder.reset();
916			self.in_flight.clear();
917		}
918		// Whatever the resampler still holds belongs to this track: its last partial
919		// chunk, plus the audio its filter is running behind on. Dropping it here
920		// would publish a track that ends before its source did.
921		if let Some(resampler) = self.resampler.take() {
922			self.pending.extend(resampler.flush()?);
923		}
924
925		// The drained resampler tail can span multiple frames. Publish those first
926		// so only the final partial frame reaches the encoder's terminal drain.
927		// Nothing written since a reanchor: whatever is left continues where the stamps end.
928		let anchor = self.anchor.unwrap_or(Anchor {
929			at: self.stamped,
930			floor: self.stamped,
931		});
932		self.publish_full_frames(anchor)?;
933		// What the codec still holds came from full frames, so it goes out at their stamps, leaving
934		// the terminal drain's packets to start where the source's partial tail does.
935		self.encoder.flush()?;
936		self.publish_ready(None)?;
937		if !self.in_flight.is_empty() {
938			return Err(Error::Codec(format!(
939				"{} kept {} packet(s) past its flush",
940				self.encoder.name(),
941				self.in_flight.len()
942			)));
943		}
944		// A gap no full frame carried, such as history expiring right before capture ended,
945		// still separates the final partial frame from the epoch before it.
946		if std::mem::take(&mut self.pending_discontinuity) && !self.decoder_boundary && !self.pending.is_empty() {
947			self.track.discontinuity()?;
948			self.decoder_boundary = true;
949		}
950
951		let frame_size = self.encoder.frame_size();
952		let codec_rate = self.encoder.codec_rate();
953		let channels = self.encoder.codec_channels() as usize;
954		let source_frames = self.pending.len() / channels;
955		let delay = self.encoder.folded_delay();
956		let start = Self::timestamp(anchor, self.frames_produced, delay, codec_rate)?;
957		// The source ends where it ends: priming only moves the packets carrying it.
958		let end = Self::timestamp(anchor, self.frames_produced + source_frames as u64, 0, codec_rate)?;
959		let finish = self.encoder.drain(&self.pending)?;
960		let discard_padding = finish.discard_padding();
961		let packets = finish.into_packets();
962
963		// A voice encode that ends silent already declared the end of speech, so its tail is
964		// silence nobody needs.
965		if self.silent && packets.iter().all(|packet| packet.activity.is_dtx() || packet.in_dtx) {
966			return Ok(());
967		}
968		if discard_padding > 0 {
969			Self::publish_terminal(
970				&mut self.track,
971				Terminal {
972					packets,
973					end,
974					start,
975					frame_size,
976					codec_rate,
977				},
978			)?;
979		} else {
980			for packet in packets {
981				let stamp = self.stamp(anchor)?;
982				self.publish_gated(packet, stamp)?;
983			}
984		}
985		Ok(())
986	}
987
988	/// Abort the track with `err` instead of finishing it, so subscribers see the
989	/// real cause rather than [`moq_net::Error::Dropped`]. Pending samples are dropped.
990	pub fn abort(self, err: moq_net::Error) {
991		self.track.abort(err);
992	}
993}
994
995/// An audio track whose [`Producer`] [finished](Producer::finish) it: every packet is published,
996/// and it can still be watched or aborted, but not written to.
997///
998/// Dropping it releases the track like dropping a [`Producer`].
999///
1000/// ```compile_fail,E0599
1001/// # fn cannot_write(track: moq_audio::encode::Finished, frame: &moq_audio::Frame) {
1002/// track.write(frame).unwrap();
1003/// # }
1004/// ```
1005#[must_use = "dropping it releases the track and its catalog rendition"]
1006pub struct Finished {
1007	track: moq_mux::container::Finished<moq_mux::container::legacy::Wire, hang::catalog::AudioConfig>,
1008}
1009
1010impl Finished {
1011	/// The name of the published track, which is [`Options::track`] resolved.
1012	pub fn track_name(&self) -> &str {
1013		self.track.name()
1014	}
1015
1016	/// A watch-only handle to the track's subscriber demand; see [`Producer::demand`].
1017	pub fn demand(&self) -> moq_net::track::Demand {
1018		self.track.demand()
1019	}
1020
1021	/// Abort the track with `err`; see [`Producer::abort`]. Readers still draining get the end the
1022	/// track declared instead once every group below it finished: the clean end after
1023	/// [`Producer::finish`], or the capture's error when the source failed.
1024	pub fn abort(self, err: moq_net::Error) {
1025		self.track.abort(err);
1026	}
1027}
1028
1029/// How far back a subscription wants retained audio replayed. A live join
1030/// ([`Start::Live`](moq_net::track::Start::Live) with no end) starts its lag behind the live edge,
1031/// which a player states as its playout delay plus the codec's warmup, bounded by the join's own
1032/// max, so when every range is one the furthest of those bounds it. A join with no lag limit, as
1033/// every join before moq-lite-07 is, starts from the oldest group but drops anything older than its
1034/// max, so its max alone bounds it. Any other range is history, such as one from the oldest group
1035/// (as moq-transport carries every join), which wants everything kept, as does a join bounded by
1036/// neither: `None` leaves the retention.
1037#[cfg(any(feature = "capture", test))]
1038fn replay_budget(subscription: &moq_net::track::Subscription) -> Option<std::time::Duration> {
1039	let joins: Option<Vec<std::time::Duration>> = subscription
1040		.ranges
1041		.iter()
1042		.map(|range| match (range.start, range.end) {
1043			// Unbounded by both, it wants everything kept.
1044			(moq_net::track::Start::Live { min, max }, None) => min.into_iter().chain(max).min(),
1045			_ => None,
1046		})
1047		.collect();
1048	joins?.into_iter().max()
1049}
1050
1051#[cfg(test)]
1052mod tests {
1053	async fn decoded_frame(consumer: &mut crate::decode::Consumer) -> Result<Option<Frame>, Error> {
1054		loop {
1055			match consumer.read().await? {
1056				Some(crate::decode::Read::Frame(frame)) => return Ok(Some(frame)),
1057				Some(crate::decode::Read::Gap { .. } | crate::decode::Read::End { .. }) => {}
1058				None => return Ok(None),
1059			}
1060		}
1061	}
1062
1063	use std::task::Poll;
1064	use std::time::Duration;
1065
1066	use super::*;
1067	use crate::decode::{Consumer as AudioConsumer, Options as DecodeOptions};
1068	use crate::{Activity, Format, Layout};
1069
1070	/// The next published packet, passing over gaps and ends.
1071	async fn packet<F: moq_mux::container::Container>(reader: &mut moq_mux::container::Consumer<F>) -> Option<MuxFrame>
1072	where
1073		F::Error: std::fmt::Debug,
1074	{
1075		loop {
1076			if let moq_mux::container::Read::Frame { frame, .. } = reader.read().await.unwrap()? {
1077				return Some(frame);
1078			}
1079		}
1080	}
1081
1082	/// A track asked for again after its producer dropped while read is served by a producer on
1083	/// the request, published with the same options, and its reader reads on.
1084	#[tokio::test]
1085	async fn a_requested_producer_serves_a_renewal() {
1086		let input = Input::default();
1087		let options = Options {
1088			config: Config::from_input(super::super::Codec::Pcm, &input),
1089			..Options::default()
1090		};
1091		let mut broadcast = moq_net::broadcast::Info::new().produce();
1092		let mut requests = broadcast.requests();
1093		let consumer = broadcast.consume();
1094		let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
1095		let mut producer = Producer::new(&mut broadcast, catalog.clone(), input.clone(), &options).unwrap();
1096		let name = producer.track_name().to_owned();
1097		let track = consumer.track(&name).unwrap().subscribe(None).await.unwrap();
1098		let mut reader =
1099			moq_mux::container::Consumer::new(track, moq_mux::container::legacy::Wire(moq_mux::container::Kind::Audio));
1100		producer.write(&pcm_frame(&[0.5; 1920], 0)).unwrap();
1101		assert_eq!(
1102			packet(&mut reader).await.unwrap().timestamp,
1103			Timestamp::from_micros(0).unwrap()
1104		);
1105		drop(producer);
1106
1107		let request = requests.requested_track().await.unwrap();
1108		assert_eq!(request.name(), name);
1109		let mut next = Producer::requested(request, catalog.clone(), input, &options).unwrap();
1110		assert!(catalog.snapshot().audio.renditions.contains_key(&name));
1111		next.write(&pcm_frame(&[0.25; 1920], 20_000)).unwrap();
1112		assert_eq!(
1113			packet(&mut reader).await.unwrap().timestamp,
1114			Timestamp::from_micros(20_000).unwrap()
1115		);
1116	}
1117
1118	/// A renewal served with options that change its track info ends the track with
1119	/// `MalformedTrack`, so the producer fails rather than advertise a rendition nothing will carry.
1120	#[tokio::test]
1121	async fn a_requested_producer_refuses_a_renewal_it_would_change() {
1122		let input = Input::default();
1123		let options = Options {
1124			config: Config::from_input(super::super::Codec::Pcm, &input),
1125			..Options::default()
1126		};
1127		let mut broadcast = moq_net::broadcast::Info::new().produce();
1128		let mut requests = broadcast.requests();
1129		let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
1130		let track = broadcast
1131			.create_track("audio", catalog.track_info(hang::catalog::PRIORITY.audio - 1))
1132			.unwrap();
1133		let mut reader = broadcast
1134			.consume()
1135			.track("audio")
1136			.unwrap()
1137			.subscribe(None)
1138			.await
1139			.unwrap();
1140		drop(track);
1141
1142		let request = requests.requested_track().await.unwrap();
1143		let refused = Producer::requested(request, catalog.clone(), input, &options);
1144		assert!(matches!(refused, Err(Error::Net(moq_net::Error::MalformedTrack))));
1145		assert!(!catalog.snapshot().audio.renditions.contains_key("audio"));
1146		assert!(matches!(reader.recv_group().await, Err(moq_net::Error::MalformedTrack)));
1147	}
1148
1149	/// A rendition the catalog refuses after the request was accepted, here a name another
1150	/// producer claims, ends the track with `NotFound` rather than leaving it to drop.
1151	#[tokio::test]
1152	async fn a_requested_producer_ends_a_track_the_catalog_refuses() {
1153		let input = Input::default();
1154		let options = Options {
1155			config: Config::from_input(super::super::Codec::Pcm, &input),
1156			..Options::default()
1157		};
1158		let mut broadcast = moq_net::broadcast::Info::new().produce();
1159		let mut requests = broadcast.requests();
1160		let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
1161		let mut other = moq_net::broadcast::Info::new().produce();
1162		let claimed = Options {
1163			track: Some("audio".into()),
1164			..options.clone()
1165		};
1166		let _claim = Producer::new(&mut other, catalog.clone(), input.clone(), &claimed).unwrap();
1167
1168		let track = broadcast
1169			.create_track("audio", catalog.track_info(hang::catalog::PRIORITY.audio))
1170			.unwrap();
1171		let mut reader = broadcast
1172			.consume()
1173			.track("audio")
1174			.unwrap()
1175			.subscribe(None)
1176			.await
1177			.unwrap();
1178		drop(track);
1179
1180		let request = requests.requested_track().await.unwrap();
1181		assert!(Producer::requested(request, catalog, input, &options).is_err());
1182		assert!(matches!(reader.recv_group().await, Err(moq_net::Error::NotFound)));
1183	}
1184
1185	/// A request names its track, so a requested producer given a name of its own fails and
1186	/// rejects the request, ending the subscriber waiting on it.
1187	#[tokio::test]
1188	async fn a_requested_producer_refuses_another_name() {
1189		let mut broadcast = moq_net::broadcast::Info::new().produce();
1190		let mut requests = broadcast.requests();
1191		let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
1192		let pending = broadcast.consume().track("audio").unwrap().subscribe(None);
1193		let request = requests.requested_track().await.unwrap();
1194		let options = Options {
1195			track: Some("other".into()),
1196			..Options::default()
1197		};
1198		assert!(Producer::requested(request, catalog, Input::default(), &options).is_err());
1199		assert!(matches!(pending.await, Err(moq_net::Error::NotFound)));
1200	}
1201
1202	/// The catalog's stats follow the encoder's target from the first rendition on.
1203	#[tokio::test]
1204	async fn stats_follow_the_target_bitrate() {
1205		let mut broadcast = moq_net::broadcast::Info::new().produce();
1206		let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
1207		let options = Options {
1208			track: Some("audio".into()),
1209			..Options::default()
1210		};
1211		let mut producer = Producer::new(&mut broadcast, catalog.clone(), Input::default(), &options).unwrap();
1212		let reported = || catalog.stats().remove("audio").and_then(|stats| stats.bitrate);
1213		assert_eq!(reported(), Some(producer.bitrate().as_bps()));
1214
1215		let initial = producer.bitrate();
1216		producer
1217			.set_bitrate(moq_net::bandwidth::Rate::from_bps(initial.as_bps() / 2))
1218			.unwrap();
1219		assert_ne!(producer.bitrate(), initial);
1220		assert_eq!(reported(), Some(producer.bitrate().as_bps()));
1221	}
1222
1223	#[tokio::test]
1224	#[ignore = "measures real codec CPU; release benchmark, run by nightly"]
1225	async fn benchmark_raw_audio() {
1226		println!("tracks,retention_secs,always_on,idle_ms,catchup_ms");
1227		for tracks in [1, 8] {
1228			for seconds in [1, 30] {
1229				for active in [true, false] {
1230					let mut broadcast = moq_net::broadcast::Info::new().produce();
1231					let catalog = moq_mux::catalog::Producer::new(
1232						&mut broadcast,
1233						moq_mux::catalog::Config::default().with_max_age(Duration::from_secs(seconds)),
1234					)
1235					.unwrap();
1236					let mut producers: Vec<_> = (0..tracks)
1237						.map(|_| {
1238							Producer::new(&mut broadcast, catalog.clone(), Input::default(), &Options::default())
1239								.unwrap()
1240						})
1241						.collect();
1242					for producer in &mut producers {
1243						producer.set_active(active, Timestamp::ZERO).unwrap();
1244					}
1245					let pcm: Vec<_> = (0..1920).map(|index| (index as f32 * 0.1).sin() * 0.1).collect();
1246					let start = kio::clock::now();
1247					for index in 0..3000 {
1248						let frame = pcm_frame(&pcm, index * 20_000);
1249						for producer in &mut producers {
1250							producer.write(&frame).unwrap();
1251						}
1252					}
1253					let idle = start.elapsed();
1254					let start = kio::clock::now();
1255					for producer in &mut producers {
1256						loop {
1257							producer
1258								.set_active(true, Timestamp::from_micros(60_000_000).unwrap())
1259								.unwrap();
1260							if !producer.backlog_ready() {
1261								break;
1262							}
1263						}
1264					}
1265					let catchup = start.elapsed();
1266					println!(
1267						"{tracks},{seconds},{active},{:.3},{:.3}",
1268						idle.as_secs_f64() * 1e3,
1269						catchup.as_secs_f64() * 1e3
1270					);
1271					let _finished: Vec<_> = producers
1272						.into_iter()
1273						.map(|producer| producer.finish().unwrap())
1274						.collect();
1275				}
1276			}
1277		}
1278	}
1279
1280	#[tokio::test(start_paused = true)]
1281	async fn raw_history_keeps_codec_boundaries_capture_time_and_the_live_edge() {
1282		let input = Input::default();
1283		let options = Options {
1284			track: Some("audio".into()),
1285			config: Config::from_input(super::super::Codec::Pcm, &input),
1286			..Options::default()
1287		};
1288		let mut broadcast = moq_net::broadcast::Info::new().produce();
1289		let consumer = broadcast.consume();
1290		let catalog = moq_mux::catalog::Producer::new(
1291			&mut broadcast,
1292			moq_mux::catalog::Config::default().with_max_age(Duration::from_secs(1)),
1293		)
1294		.unwrap();
1295		let mut producer = Producer::new(&mut broadcast, catalog, input, &options).unwrap();
1296		let at = |index: u64| Timestamp::from_micros(1_000_000 + index * 20_000).unwrap();
1297		producer.set_active(false, at(0)).unwrap();
1298		for index in 0..150 {
1299			// Capture buffers need not coincide with a codec frame, even across a demand gap.
1300			producer
1301				.write(&pcm_frame(
1302					&vec![index as f32; 274],
1303					at(index).as_micros().unwrap() as u64,
1304				))
1305				.unwrap();
1306			producer
1307				.write(&pcm_frame(
1308					&vec![index as f32; 1646],
1309					at(index).as_micros().unwrap() as u64 + 2854,
1310				))
1311				.unwrap();
1312		}
1313		assert!(!producer.encoder.started(), "no codec work without demand");
1314		let track = consumer
1315			.track("audio")
1316			.unwrap()
1317			.subscribe(
1318				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
1319					moq_net::track::Start::Live {
1320						min: Some(Duration::from_secs(1)),
1321						max: Some(Duration::from_secs(1)),
1322					},
1323				)]),
1324			)
1325			.await
1326			.unwrap();
1327		let mut reader =
1328			moq_mux::container::Consumer::new(track, moq_mux::container::legacy::Wire(moq_mux::container::Kind::Audio));
1329		loop {
1330			producer.set_active(true, at(150)).unwrap();
1331			if !producer.backlog_ready() {
1332				break;
1333			}
1334		}
1335		// History expiring before anything was published leaves no epoch to end with a marker.
1336		let first = reader.read().await.unwrap().unwrap();
1337		assert!(
1338			matches!(&first, moq_mux::container::Read::Frame { frame, .. } if frame.timestamp == at(100)),
1339			"{first:?}"
1340		);
1341		for index in 101..150 {
1342			let frame = packet(&mut reader).await.unwrap();
1343			assert_eq!(frame.timestamp, at(index));
1344			assert_eq!(frame.payload.len(), 1920 * 4);
1345			assert_eq!(f32::from_le_bytes(frame.payload[..4].try_into().unwrap()), index as f32);
1346		}
1347		producer.set_active(false, at(150)).unwrap();
1348		producer
1349			.write(&pcm_frame(&vec![0.5; 1920], at(150).as_micros().unwrap() as u64))
1350			.unwrap();
1351		producer.set_active(true, at(151)).unwrap();
1352		assert_eq!(packet(&mut reader).await.unwrap().timestamp, at(150));
1353		producer
1354			.write(&pcm_frame(&vec![0.5; 1920], at(151).as_micros().unwrap() as u64))
1355			.unwrap();
1356		assert_eq!(packet(&mut reader).await.unwrap().timestamp, at(151));
1357		let _finished = producer.finish().unwrap();
1358	}
1359
1360	/// A group the join left open when encoding stops ends where its last packet does, so a reader
1361	/// of it, such as a fetch, finishes while the audio is retained rather than waiting for a
1362	/// subscriber to return. The replay that follows opens the next group with no marker.
1363	#[tokio::test(start_paused = true)]
1364	async fn stopping_ends_the_open_group() {
1365		let input = Input::default();
1366		let options = Options {
1367			track: Some("audio".into()),
1368			config: Config::from_input(super::super::Codec::Pcm, &input),
1369			join: Duration::from_millis(100),
1370			..Options::default()
1371		};
1372		let mut broadcast = moq_net::broadcast::Info::new().produce();
1373		let consumer = broadcast.consume();
1374		let catalog = moq_mux::catalog::Producer::new(
1375			&mut broadcast,
1376			moq_mux::catalog::Config::default().with_max_age(Duration::from_secs(30)),
1377		)
1378		.unwrap();
1379		let mut producer = Producer::new(&mut broadcast, catalog, input, &options).unwrap();
1380		let at = |index: u64| Timestamp::from_micros(1_000_000 + index * 20_000).unwrap();
1381		producer.set_active(true, at(0)).unwrap();
1382		producer
1383			.write(&pcm_frame(&vec![0.5; 1920], at(0).as_micros().unwrap() as u64))
1384			.unwrap();
1385		let open = producer.track().largest().expect("a group opened").group;
1386		producer.set_active(false, at(1)).unwrap();
1387		producer
1388			.write(&pcm_frame(&vec![0.5; 1920], at(1).as_micros().unwrap() as u64))
1389			.unwrap();
1390
1391		let mut group = consumer.track("audio").unwrap().fetch_group(open, None).await.unwrap();
1392		assert!(group.read_frame().await.unwrap().is_some());
1393		let end = now_or_never(group.read_frame()).expect("the open group ended");
1394		assert!(end.unwrap().is_none());
1395
1396		producer.set_active(true, at(2)).unwrap();
1397		assert_eq!(
1398			producer.track().largest().unwrap().group,
1399			at(1).as_micros().unwrap() as u64
1400		);
1401		let _finished = producer.finish().unwrap();
1402	}
1403
1404	/// Stopping partway through a replay ends the open group where its last published packet does,
1405	/// not where the newest retained frame does, so the next replayed frame opens the next group at
1406	/// its own timestamp.
1407	#[tokio::test(start_paused = true)]
1408	async fn stopping_mid_replay_ends_the_group_at_its_last_packet() {
1409		let input = Input::default();
1410		let options = Options {
1411			track: Some("audio".into()),
1412			config: Config::from_input(super::super::Codec::Pcm, &input),
1413			join: Duration::from_millis(100),
1414			..Options::default()
1415		};
1416		let mut broadcast = moq_net::broadcast::Info::new().produce();
1417		let catalog = moq_mux::catalog::Producer::new(
1418			&mut broadcast,
1419			moq_mux::catalog::Config::default().with_max_age(Duration::from_secs(30)),
1420		)
1421		.unwrap();
1422		let mut producer = Producer::new(&mut broadcast, catalog, input, &options).unwrap();
1423		let at = |index: u64| Timestamp::from_micros(1_000_000 + index * 20_000).unwrap();
1424		producer.set_active(false, at(0)).unwrap();
1425		for index in 0..3 {
1426			producer
1427				.write(&pcm_frame(&vec![0.5; 1920], at(index).as_micros().unwrap() as u64))
1428				.unwrap();
1429		}
1430		// Each turn replays one retained frame.
1431		producer.set_active(true, at(3)).unwrap();
1432		assert_eq!(
1433			producer.track().largest().unwrap().group,
1434			at(0).as_micros().unwrap() as u64
1435		);
1436		producer.set_active(false, at(3)).unwrap();
1437		producer.set_active(true, at(3)).unwrap();
1438		assert_eq!(
1439			producer.track().largest().unwrap().group,
1440			at(1).as_micros().unwrap() as u64
1441		);
1442		let _finished = producer.finish().unwrap();
1443	}
1444
1445	/// Replayed groups reach the track as fresh arrivals, so only the encoder can tell they are old:
1446	/// a live viewer rejoining after seconds idle would otherwise receive all of them first. A live
1447	/// join states how far back it plays as its lag, which bounds the replay however far its max
1448	/// reaches, and its max bounds the replay however far its lag reaches, as with a join a wire
1449	/// before lite-07 makes of its one max age.
1450	#[tokio::test(start_paused = true)]
1451	async fn demand_replays_only_the_history_its_live_join_wants() {
1452		let budget = Duration::from_millis(130);
1453		let long = Duration::from_secs(10);
1454		for (min, max) in [(budget, long), (long, budget)] {
1455			replays_from(
1456				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
1457					moq_net::track::Start::Live {
1458						min: Some(min),
1459						max: Some(max),
1460					},
1461				)]),
1462				143,
1463			)
1464			.await;
1465		}
1466	}
1467
1468	/// A join with no lag limit, as one before moq-lite-07 is, starts from the oldest group but drops
1469	/// anything older than its max, so its max alone bounds the replay.
1470	#[tokio::test(start_paused = true)]
1471	async fn a_join_with_no_lag_limit_replays_its_max() {
1472		replays_from(
1473			moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
1474				moq_net::track::Start::Live {
1475					min: None,
1476					max: Some(Duration::from_millis(130)),
1477				},
1478			)]),
1479			143,
1480		)
1481		.await;
1482	}
1483
1484	/// A join bounded by neither lag nor max drops nothing, so it replays the whole retention.
1485	#[tokio::test(start_paused = true)]
1486	async fn a_join_bounded_by_neither_replays_the_whole_retention() {
1487		replays_from(
1488			moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
1489				moq_net::track::Start::Live { min: None, max: None },
1490			)]),
1491			0,
1492		)
1493		.await;
1494	}
1495
1496	/// Replays 150 retained frames to `subscription` and checks the first one it reads is `first`.
1497	async fn replays_from(subscription: moq_net::track::Subscription, first: u64) {
1498		let input = Input::default();
1499		let options = Options {
1500			track: Some("audio".into()),
1501			config: Config::from_input(super::super::Codec::Pcm, &input),
1502			..Options::default()
1503		};
1504		let mut broadcast = moq_net::broadcast::Info::new().produce();
1505		let consumer = broadcast.consume();
1506		let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
1507		let mut producer = Producer::new(&mut broadcast, catalog, input, &options).unwrap();
1508		let at = |index: u64| Timestamp::from_micros(1_000_000 + index * 20_000).unwrap();
1509		producer.set_active(false, at(0)).unwrap();
1510		for index in 0..150 {
1511			producer
1512				.write(&pcm_frame(
1513					&vec![index as f32; 1920],
1514					at(index).as_micros().unwrap() as u64,
1515				))
1516				.unwrap();
1517		}
1518		let track = consumer.track("audio").unwrap().subscribe(subscription).await.unwrap();
1519		let mut reader =
1520			moq_mux::container::Consumer::new(track, moq_mux::container::legacy::Wire(moq_mux::container::Kind::Audio));
1521		// One replay turn, read at once as a network subscriber is served: the group it wrote is
1522		// the newest the track holds, so the subscriber's own budget cannot judge it stale.
1523		producer.set_active(true, at(150)).unwrap();
1524		// A 130 ms budget at frame 150 still wants the frames ending after it, 143 onward, and the
1525		// whole retention starts at 0.
1526		let Some(moq_mux::container::Read::Frame { frame, .. }) = reader.read().await.unwrap() else {
1527			panic!("expected a replayed frame");
1528		};
1529		assert_eq!(frame.timestamp, at(first));
1530		let _finished = producer.finish().unwrap();
1531	}
1532
1533	/// Replay catches up behind the live edge another track already reached; advertising that as
1534	/// delay would buffer playback by the replayed history for the rest of the broadcast.
1535	#[tokio::test(start_paused = true)]
1536	async fn replayed_history_raises_no_catalog_delay() {
1537		let mut broadcast = moq_net::broadcast::Info::new().produce();
1538		let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
1539		let options = |track: &str| Options {
1540			track: Some(track.into()),
1541			..Options::default()
1542		};
1543		let mut producer = Producer::new(&mut broadcast, catalog.clone(), Input::default(), &options("audio")).unwrap();
1544		let mut other = Producer::new(&mut broadcast, catalog, Input::default(), &options("other")).unwrap();
1545		let at = |index: u64| Timestamp::from_micros(1_000_000 + index * 20_000).unwrap();
1546		producer.set_active(false, at(0)).unwrap();
1547		for index in 0..50 {
1548			producer
1549				.write(&pcm_frame(&vec![0.1; 1920], at(index).as_micros().unwrap() as u64))
1550				.unwrap();
1551		}
1552		// Another track already reached the live edge.
1553		for index in 45..50 {
1554			other
1555				.write(&pcm_frame(&vec![0.1; 1920], at(index).as_micros().unwrap() as u64))
1556				.unwrap();
1557		}
1558		loop {
1559			producer.set_active(true, at(50)).unwrap();
1560			if !producer.backlog_ready() {
1561				break;
1562			}
1563		}
1564		for index in 50..55 {
1565			producer
1566				.write(&pcm_frame(&vec![0.1; 1920], at(index).as_micros().unwrap() as u64))
1567				.unwrap();
1568		}
1569		let producer = producer.finish().unwrap();
1570		let delay = producer.track.estimate().delay;
1571		assert!(
1572			delay.is_none_or(|delay| delay < Duration::from_millis(100)),
1573			"{delay:?}"
1574		);
1575		let _finished = other.finish().unwrap();
1576	}
1577
1578	/// History expiring right before capture ends still marks the gap before the final partial frame.
1579	#[tokio::test(start_paused = true)]
1580	async fn finish_marks_a_gap_no_full_frame_carried() {
1581		let input = Input::default();
1582		let options = Options {
1583			track: Some("audio".into()),
1584			config: Config::from_input(super::super::Codec::Pcm, &input),
1585			..Options::default()
1586		};
1587		let mut broadcast = moq_net::broadcast::Info::new().produce();
1588		let consumer = broadcast.consume();
1589		let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
1590		let mut producer = Producer::new(&mut broadcast, catalog, input, &options).unwrap();
1591		let track = consumer
1592			.track("audio")
1593			.unwrap()
1594			.subscribe(
1595				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
1596					moq_net::track::Start::Live {
1597						min: Some(Duration::from_secs(60)),
1598						max: Some(Duration::from_secs(60)),
1599					},
1600				)]),
1601			)
1602			.await
1603			.unwrap();
1604		let mut reader =
1605			moq_mux::container::Consumer::new(track, moq_mux::container::legacy::Wire(moq_mux::container::Kind::Audio));
1606		producer.write(&pcm_frame(&vec![0.1; 1920], 1_000_000)).unwrap();
1607		producer
1608			.set_active(false, Timestamp::from_micros(1_020_000).unwrap())
1609			.unwrap();
1610		producer.write(&pcm_frame(&vec![0.1; 1920], 1_020_000)).unwrap();
1611		// Half a codec frame stays pending, then the retention expires the backlog as capture stops.
1612		producer.write(&pcm_frame(&vec![0.1; 960], 1_040_000)).unwrap();
1613		// The full frames' retention ended at 31.04 s; the partial one's runs to 31.05 s.
1614		producer
1615			.set_active(false, Timestamp::from_micros(31_045_000).unwrap())
1616			.unwrap();
1617		let _finished = producer.finish().unwrap();
1618
1619		let first = reader.read().await.unwrap().unwrap();
1620		assert!(matches!(first, moq_mux::container::Read::Frame { .. }), "{first:?}");
1621		// The terminal packet carries its own end; the marker ends the epoch before the gap, ahead of it.
1622		let next = reader.read().await.unwrap().unwrap();
1623		assert!(
1624			matches!(next, moq_mux::container::Read::End { end, .. } if end.as_micros().unwrap() < 1_040_000),
1625			"the final partial frame joined the epoch before the gap: {next:?}"
1626		);
1627	}
1628
1629	#[kio::test]
1630	async fn the_partial_frame_expires_with_the_history_before_it() {
1631		let input = Input::default();
1632		let options = Options {
1633			track: Some("audio".into()),
1634			config: Config::from_input(super::super::Codec::Pcm, &input),
1635			..Options::default()
1636		};
1637		let mut broadcast = moq_net::broadcast::Info::new().produce();
1638		let consumer = broadcast.consume();
1639		let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
1640		let mut producer = Producer::new(&mut broadcast, catalog, input, &options).unwrap();
1641		let track = consumer
1642			.track("audio")
1643			.unwrap()
1644			.subscribe(
1645				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
1646					moq_net::track::Start::Live {
1647						min: Some(Duration::from_secs(60)),
1648						max: Some(Duration::from_secs(60)),
1649					},
1650				)]),
1651			)
1652			.await
1653			.unwrap();
1654		let mut reader =
1655			moq_mux::container::Consumer::new(track, moq_mux::container::legacy::Wire(moq_mux::container::Kind::Audio));
1656		producer.write(&pcm_frame(&vec![0.1; 1920], 1_000_000)).unwrap();
1657		producer
1658			.set_active(false, Timestamp::from_micros(1_020_000).unwrap())
1659			.unwrap();
1660		// A full retained frame, then half of one.
1661		producer.write(&pcm_frame(&vec![0.1; 2880], 1_020_000)).unwrap();
1662		// Past the partial frame's retention too, as when a failed source's history runs out.
1663		producer
1664			.set_active(false, Timestamp::from_micros(31_100_000).unwrap())
1665			.unwrap();
1666		let _finished = producer.finish().unwrap();
1667
1668		let first = reader.read().await.unwrap().unwrap();
1669		assert!(
1670			matches!(first, moq_mux::container::Read::Frame { ref frame, .. } if frame.timestamp.as_micros().unwrap() == 1_000_000),
1671			"{first:?}"
1672		);
1673		// Nothing retained reaches the track after it expired.
1674		loop {
1675			match reader.read().await.unwrap() {
1676				Some(moq_mux::container::Read::Frame { frame, .. }) => {
1677					panic!("expired audio at {:?} reached the track", frame.timestamp)
1678				}
1679				Some(_) => {}
1680				None => break,
1681			}
1682		}
1683	}
1684
1685	#[test]
1686	fn raw_history_expires_without_more_capture() {
1687		let mut broadcast = moq_net::broadcast::Info::new().produce();
1688		let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
1689		let mut producer = Producer::new(&mut broadcast, catalog, Input::default(), &Options::default()).unwrap();
1690		producer.set_active(false, Timestamp::ZERO).unwrap();
1691		producer.write(&pcm_frame(&vec![0.1; 1920], 0)).unwrap();
1692		assert_eq!(producer.backlog_deadline(), Some(Duration::from_millis(30_020)));
1693		producer
1694			.set_active(true, Timestamp::from_micros(30_020_000).unwrap())
1695			.unwrap();
1696		assert!(producer.backlog.is_empty());
1697		assert!(!producer.encoder.started());
1698		let _finished = producer.finish().unwrap();
1699	}
1700
1701	#[tokio::test]
1702	async fn demand_follows_subscribers_and_closes_with_the_producer() {
1703		let mut broadcast = moq_net::broadcast::Info::new().produce();
1704		let consumer = broadcast.consume();
1705		let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
1706		let options = Options {
1707			track: Some("audio".into()),
1708			..Options::default()
1709		};
1710		let producer = Producer::new(&mut broadcast, catalog, Input::default(), &options).unwrap();
1711		let mut demand = producer.demand();
1712
1713		assert_eq!(demand.name(), "audio");
1714		assert!(!demand.wanted());
1715		let subscriber = consumer.track("audio").unwrap().subscribe(None).await.unwrap();
1716		let wanted = async {
1717			while !demand.wanted_changed().await? {}
1718			moq_net::Result::Ok(())
1719		};
1720		kio::clock::timeout(Duration::from_secs(1), wanted)
1721			.await
1722			.expect("subscription demand")
1723			.unwrap();
1724		assert!(demand.wanted());
1725
1726		drop(subscriber);
1727		drop(consumer);
1728		let unwanted = async {
1729			while demand.wanted_changed().await? {}
1730			moq_net::Result::Ok(())
1731		};
1732		kio::clock::timeout(Duration::from_secs(1), unwanted)
1733			.await
1734			.expect("subscription released")
1735			.unwrap();
1736		assert!(!demand.wanted());
1737
1738		drop(producer.finish().unwrap());
1739		let closed = kio::clock::timeout(Duration::from_secs(1), demand.closed())
1740			.await
1741			.expect("producer closed");
1742		assert!(closed.is_ok(), "{closed:?}");
1743	}
1744
1745	/// A finished publication may live as long as its broadcast; the codec and input
1746	/// allocation count must stay flat as more tracks retire on it.
1747	#[tokio::test(start_paused = true)]
1748	async fn finished_publications_release_encoding_resources() {
1749		let backend = crate::encode::backend::stub::install();
1750		let mut broadcast = moq_net::broadcast::Info::new().produce();
1751		let consumer = broadcast.consume();
1752		let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
1753		let mut retired = Vec::new();
1754		for index in 0..16 {
1755			let input = Input {
1756				format: Format::F32,
1757				sample_rate: 44_100,
1758				layout: Layout::Stereo,
1759			};
1760			let options = Options {
1761				track: Some(format!("audio-{index}")),
1762				config: Config::from_input(crate::encode::Codec::Aac, &Input::new(48_000, Layout::Mono)),
1763				..Options::default()
1764			};
1765			let mut producer = Producer::new(&mut broadcast, catalog.clone(), input, &options).unwrap();
1766			assert_eq!(backend.resources(), 1);
1767			producer.write(&pcm_frame(&vec![0.1; 4096], 0)).unwrap();
1768			assert!(producer.pending.capacity() > 0);
1769			assert!(producer.remix.is_some());
1770			retired.push(producer.finish().unwrap());
1771			assert_eq!(backend.resources(), 0, "retired {index} codecs");
1772
1773			// Retention still owns both the published track and its catalog rendition.
1774			let mut reader = consumer
1775				.track(&format!("audio-{index}"))
1776				.unwrap()
1777				.subscribe(None)
1778				.await
1779				.unwrap();
1780			let mut frames = 0;
1781			while let Some(mut group) = reader.recv_group().await.unwrap() {
1782				while group.read_frame().await.unwrap().is_some() {
1783					frames += 1;
1784				}
1785			}
1786			assert!(frames > 0);
1787			assert_eq!(catalog.snapshot().audio.renditions.len(), index + 1);
1788		}
1789		assert_eq!(backend.resources(), 0);
1790		assert_eq!(retired.len(), 16);
1791	}
1792
1793	/// Terminal Opus lookahead samples survive both exact-frame and partial-frame input.
1794	#[kio::test]
1795	async fn finish_publishes_the_opus_lookahead_tail() {
1796		for (group_ms, frames) in [(1, 960), (1, 860), (100, 2_880), (100, 2_780)] {
1797			let input = Input {
1798				format: Format::F32,
1799				sample_rate: 48_000,
1800				layout: Layout::Mono,
1801			};
1802			let options = Options {
1803				track: Some("audio".to_string()),
1804				join: Duration::from_millis(group_ms),
1805				config: Config {
1806					layout: Layout::Mono,
1807					bitrate: Some(moq_net::bandwidth::Rate::from_bps(128_000)),
1808					..Config::default()
1809				},
1810				..Options::default()
1811			};
1812			let mut decoder_config = Encoder::new(&options.config).unwrap().catalog();
1813			// Every packet counts here; the consumer's warmup tests cover trimming.
1814			decoder_config.warmup = None;
1815
1816			let mut broadcast = moq_net::broadcast::Info::new().produce();
1817			let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
1818			let consumer = broadcast.consume();
1819			let mut producer = Producer::new(&mut broadcast, catalog, input, &options).unwrap();
1820			let mut audio = AudioConsumer::new(
1821				&consumer,
1822				&decoder_config,
1823				"audio",
1824				DecodeOptions {
1825					delay: crate::decode::Delay {
1826						max: Some(Duration::from_secs(1)),
1827						..Default::default()
1828					},
1829					..DecodeOptions::new()
1830				},
1831			)
1832			.await
1833			.unwrap();
1834
1835			let mut pcm = vec![0.0f32; frames];
1836			let impulse = pcm.len() - 100;
1837			pcm[impulse] = 1.0;
1838			let data: Vec<u8> = pcm.iter().flat_map(|sample| sample.to_le_bytes()).collect();
1839			producer.write(&Frame::new(Timestamp::ZERO, Bytes::from(data))).unwrap();
1840			let _finished = producer.finish().unwrap();
1841
1842			let mut decoded = Vec::new();
1843			while let Some(frame) = decoded_frame(&mut audio).await.unwrap() {
1844				let pcm = Format::F32.as_interleaved_f32(&frame.data, 1).unwrap();
1845				decoded.extend_from_slice(&pcm);
1846			}
1847			assert_eq!(decoded.len(), frames, "terminal padding extended the source");
1848			let peak = decoded.iter().fold(0.0f32, |peak, sample| peak.max(sample.abs()));
1849			assert!(peak > 0.1, "the {frames}-frame Opus tail lost the impulse: peak {peak}");
1850		}
1851	}
1852
1853	/// Batching cannot change what is published: every packet, timestamp, group boundary
1854	/// and the flushed tail match whether PCM arrives a frame at a time or in one burst,
1855	/// with or without resampling.
1856	#[kio::test]
1857	async fn batch_size_does_not_change_the_published_track() {
1858		for input_rate in [48_000u32, 44_100] {
1859			let input = Input::new(input_rate, Layout::Stereo);
1860			// Not a whole number of codec frames, so finish flushes a partial tail.
1861			let frames = input_rate as usize + 123;
1862			let samples: Vec<f32> = (0..frames * 2)
1863				.map(|index| (index as f32 * 0.01).sin() * 0.25)
1864				.collect();
1865			let mut reference = None;
1866			for batch in [1, 7, 959, 961, 1921, 4410, frames] {
1867				let mut broadcast = moq_net::broadcast::Info::new().produce();
1868				let catalog =
1869					moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
1870				let consumer = broadcast.consume();
1871				let mut options = Options {
1872					track: Some("audio".to_string()),
1873					config: Config::from_input(super::super::Codec::Pcm, &input),
1874					..Options::default()
1875				};
1876				options.config.sample_rate = 48_000;
1877				let mut producer = Producer::new(&mut broadcast, catalog, input.clone(), &options).unwrap();
1878				let track = consumer
1879					.track("audio")
1880					.unwrap()
1881					.subscribe(
1882						moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
1883							moq_net::track::Start::Live {
1884								min: Some(Duration::from_secs(60)),
1885								max: Some(Duration::from_secs(60)),
1886							},
1887						)]),
1888					)
1889					.await
1890					.unwrap();
1891				let mut reader = moq_mux::container::Consumer::new(
1892					track,
1893					moq_mux::container::legacy::Wire(moq_mux::container::Kind::Audio),
1894				);
1895
1896				for (index, chunk) in samples.chunks(batch * 2).enumerate() {
1897					let at = (index * batch) as u64 * 1_000_000 / input_rate as u64;
1898					producer.write(&pcm_frame(chunk, 1_000_000 + at)).unwrap();
1899				}
1900				let _finished = producer.finish().unwrap();
1901
1902				let mut published = Vec::new();
1903				while let Some(read) = reader.read().await.unwrap() {
1904					published.push(match read {
1905						moq_mux::container::Read::Frame { group, frame } => (
1906							format!("{group} {:?} {}", frame.timestamp, frame.keyframe),
1907							frame.payload,
1908						),
1909						other => (format!("{other:?}"), Bytes::new()),
1910					});
1911				}
1912				if input_rate == 48_000 {
1913					// PCM at the codec rate publishes exactly the input, its final frame zero-padded.
1914					let payload: Vec<u8> = published.iter().flat_map(|(_, payload)| payload.to_vec()).collect();
1915					let expected: Vec<u8> = samples.iter().flat_map(|sample| sample.to_le_bytes()).collect();
1916					assert_eq!(
1917						payload.len(),
1918						expected.len().next_multiple_of(1920 * 4),
1919						"batch={batch}"
1920					);
1921					assert_eq!(payload[..expected.len()], expected[..], "batch={batch}");
1922					assert!(payload[expected.len()..].iter().all(|&byte| byte == 0), "batch={batch}");
1923				}
1924				assert_eq!(
1925					&published,
1926					reference.get_or_insert_with(|| published.clone()),
1927					"{input_rate} Hz, batch={batch}"
1928				);
1929			}
1930		}
1931	}
1932
1933	/// A resampled publisher used to end its track early: `finish` flushed the
1934	/// encoder's own buffer but left the resampler holding its last partial chunk,
1935	/// plus the audio its filter runs behind on.
1936	#[kio::test]
1937	async fn finish_publishes_the_resampled_tail() {
1938		let input = Input {
1939			format: Format::F32,
1940			sample_rate: 44_100,
1941			layout: Layout::Mono,
1942		};
1943
1944		let mut broadcast = moq_net::broadcast::Info::new().produce();
1945		let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
1946		let consumer = broadcast.consume();
1947		let options = Options {
1948			track: Some("audio".to_string()),
1949			config: Config::new(48_000, Layout::Mono),
1950			..Options::default()
1951		};
1952		let mut producer = Producer::new(&mut broadcast, catalog, input.clone(), &options).unwrap();
1953
1954		// Subscribe before the track ends, or there is nothing left to subscribe to.
1955		let mut track = moq_mux::container::Consumer::new(
1956			consumer
1957				.track("audio")
1958				.unwrap()
1959				.subscribe(
1960					moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
1961						moq_net::track::Start::Live {
1962							min: Some(Duration::from_secs(1)),
1963							max: Some(Duration::from_secs(1)),
1964						},
1965					)]),
1966				)
1967				.await
1968				.unwrap(),
1969			moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Audio),
1970		);
1971
1972		// Chosen so the tail decides a whole packet: 8838 frames at 44.1 kHz is ~9620
1973		// at 48 kHz, just past ten 960-sample Opus frames. Losing the resampler's
1974		// remainder and its filter delay drops back under ten, costing a packet.
1975		let data: Vec<u8> = vec![0.25f32; 8_838].iter().flat_map(|s| s.to_le_bytes()).collect();
1976		producer
1977			.write(&Frame::new(moq_net::Timestamp::ZERO, data.into()))
1978			.unwrap();
1979		let _finished = producer.finish().unwrap();
1980
1981		let mut packets = 0;
1982		while packet(&mut track).await.is_some() {
1983			packets += 1;
1984		}
1985		assert_eq!(packets, 11);
1986	}
1987
1988	/// `reanchor` promises to drop buffered samples, and the resampler buffers
1989	/// samples of its own. Leaving those behind let `finish` flush pre-reset audio
1990	/// onto the track, stamped at an anchor that no longer exists.
1991	#[kio::test]
1992	async fn reanchor_drops_the_resampler_buffer_too() {
1993		let input = Input {
1994			format: Format::F32,
1995			sample_rate: 44_100,
1996			layout: Layout::Mono,
1997		};
1998
1999		let mut broadcast = moq_net::broadcast::Info::new().produce();
2000		let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
2001		let consumer = broadcast.consume();
2002		let options = Options {
2003			track: Some("audio".to_string()),
2004			..Options::default()
2005		};
2006		let mut producer = Producer::new(&mut broadcast, catalog, input.clone(), &options).unwrap();
2007
2008		let mut track = moq_mux::container::Consumer::new(
2009			consumer
2010				.track("audio")
2011				.unwrap()
2012				.subscribe(moq_net::track::Subscription::default())
2013				.await
2014				.unwrap(),
2015			moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Audio),
2016		);
2017
2018		// Too little to publish a packet, so it all sits in the resampler.
2019		let data: Vec<u8> = vec![0.25f32; 441].iter().flat_map(|s| s.to_le_bytes()).collect();
2020		producer
2021			.write(&Frame::new(moq_net::Timestamp::ZERO, data.into()))
2022			.unwrap();
2023
2024		producer.reanchor();
2025		let _finished = producer.finish().unwrap();
2026
2027		// The reset dropped everything, so the track ends without a packet.
2028		assert!(track.read().await.unwrap().is_none());
2029	}
2030
2031	/// Resetting after a full frame drops codec lookahead as well as producer buffers.
2032	#[kio::test]
2033	async fn reanchor_drops_the_encoder_lookahead() {
2034		let mut broadcast = moq_net::broadcast::Info::new().produce();
2035		let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
2036		let consumer = broadcast.consume();
2037		let options = Options {
2038			track: Some("audio".to_string()),
2039			..Options::default()
2040		};
2041		let mut producer = Producer::new(
2042			&mut broadcast,
2043			catalog,
2044			Input {
2045				layout: Layout::Mono,
2046				..Input::default()
2047			},
2048			&options,
2049		)
2050		.unwrap();
2051		let mut track = moq_mux::container::Consumer::new(
2052			consumer
2053				.track("audio")
2054				.unwrap()
2055				.subscribe(moq_net::track::Subscription::default())
2056				.await
2057				.unwrap(),
2058			moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Audio),
2059		);
2060
2061		producer.write(&full_frame(1_000_000)).unwrap();
2062		producer.reanchor();
2063		let _finished = producer.finish().unwrap();
2064
2065		assert!(packet(&mut track).await.is_some());
2066		assert!(packet(&mut track).await.is_none());
2067	}
2068
2069	/// A codec reset starts a new pre-skip interval at the receiver too.
2070	#[kio::test]
2071	async fn reanchor_restarts_the_decoder() {
2072		let input = Input {
2073			format: Format::F32,
2074			sample_rate: 48_000,
2075			layout: Layout::Mono,
2076		};
2077		let options = Options {
2078			track: Some("audio".to_string()),
2079			config: Config::new(48_000, Layout::Mono),
2080			..Options::default()
2081		};
2082		let mut decoder_config = Encoder::new(&options.config).unwrap().catalog();
2083		// Every packet counts here; the consumer's warmup tests cover trimming.
2084		decoder_config.warmup = None;
2085
2086		let mut broadcast = moq_net::broadcast::Info::new().produce();
2087		let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
2088		let subscriber = broadcast.consume();
2089		let mut producer = Producer::new(&mut broadcast, catalog, input, &options).unwrap();
2090		let mut audio = AudioConsumer::new(
2091			&subscriber,
2092			&decoder_config,
2093			"audio",
2094			DecodeOptions {
2095				delay: crate::decode::Delay {
2096					max: Some(Duration::from_millis(500)),
2097					..Default::default()
2098				},
2099				..DecodeOptions::new()
2100			},
2101		)
2102		.await
2103		.unwrap();
2104
2105		producer.write(&full_frame(0)).unwrap();
2106		let first = decoded_frame(&mut audio)
2107			.await
2108			.unwrap()
2109			.expect("first packet before the reanchor");
2110		assert_eq!(first.data.len() / size_of::<f32>(), 960 - 312);
2111
2112		producer.reanchor();
2113		producer.write(&full_frame(1_000_000)).unwrap();
2114		let _finished = producer.finish().unwrap();
2115
2116		let mut resumed_frames = 0;
2117		while let Some(frame) = decoded_frame(&mut audio).await.unwrap() {
2118			if frame.timestamp.as_micros().unwrap() >= 1_000_000 {
2119				resumed_frames += frame.data.len() / size_of::<f32>();
2120			}
2121		}
2122		assert!(resumed_frames > 0, "the reanchored audio still decodes");
2123	}
2124
2125	/// A 20 ms frame of a tone libopus codes as speech.
2126	fn tone() -> Vec<f32> {
2127		(0..960)
2128			.map(|sample| (sample as f32 * 440.0 * 2.0 * std::f32::consts::PI / 48_000.0).sin() * 0.5)
2129			.collect()
2130	}
2131
2132	/// One second of tone, two of silence, one of tone, and one of silence, in 20 ms frames.
2133	fn talk() -> Vec<Vec<f32>> {
2134		let (tone, silence) = (tone(), vec![0.0; 960]);
2135		[(50, &tone), (100, &silence), (50, &tone), (50, &silence)]
2136			.into_iter()
2137			.flat_map(|(count, frame)| std::iter::repeat_n(frame.clone(), count))
2138			.collect()
2139	}
2140
2141	fn micros(timestamp: Timestamp) -> u64 {
2142		timestamp.as_micros().unwrap() as u64
2143	}
2144
2145	fn mono(kind: Option<super::super::Kind>) -> Config {
2146		Config {
2147			kind,
2148			..Config::new(48_000, Layout::Mono)
2149		}
2150	}
2151
2152	/// What a mono 48 kHz producer of `kind` publishes for `frames`, 20 ms each from zero, then a
2153	/// 10 ms partial frame of silence before it finishes, with the activity it reported after
2154	/// each frame.
2155	async fn gated(
2156		kind: Option<super::super::Kind>,
2157		join: Duration,
2158		frames: &[Vec<f32>],
2159	) -> (Vec<moq_mux::container::Read>, Vec<Activity>) {
2160		let input = Input::new(48_000, Layout::Mono);
2161		let options = Options {
2162			track: Some("audio".to_string()),
2163			config: mono(kind),
2164			join,
2165			..Options::default()
2166		};
2167		let mut broadcast = moq_net::broadcast::Info::new().produce();
2168		let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
2169		let consumer = broadcast.consume();
2170		let mut producer = Producer::new(&mut broadcast, catalog, input, &options).unwrap();
2171		let track = consumer
2172			.track("audio")
2173			.unwrap()
2174			.subscribe(
2175				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
2176					moq_net::track::Start::Live {
2177						min: Some(Duration::from_secs(60)),
2178						max: Some(Duration::from_secs(60)),
2179					},
2180				)]),
2181			)
2182			.await
2183			.unwrap();
2184		let mut reader =
2185			moq_mux::container::Consumer::new(track, moq_mux::container::legacy::Wire(moq_mux::container::Kind::Audio));
2186
2187		let mut activity = Vec::new();
2188		for (index, frame) in frames.iter().enumerate() {
2189			producer.write(&pcm_frame(frame, index as u64 * 20_000)).unwrap();
2190			activity.push(producer.activity());
2191		}
2192		producer
2193			.write(&pcm_frame(&[0.0; 480], frames.len() as u64 * 20_000))
2194			.unwrap();
2195		let _finished = producer.finish().unwrap();
2196
2197		let mut read = Vec::new();
2198		while let Some(item) = reader.read().await.unwrap() {
2199			read.push(item);
2200		}
2201		(read, activity)
2202	}
2203
2204	/// A voice encode publishes push-to-talk's wire shape: libopus's hangover, an end where its
2205	/// discontinuous transmission starts, nothing for the rest of the silence, and resumed speech
2206	/// in a new group on the same timeline. Every join bounds the group speech ended in.
2207	#[tokio::test]
2208	async fn voice_sends_nothing_while_its_talker_is_silent() {
2209		use moq_mux::container::Read;
2210
2211		let frames = talk();
2212		// The bare encoder returns libopus's keep-alives, coded frames amid the no-transmit ones,
2213		// so the producer has some to drop.
2214		let mut encoder = Encoder::new(&mono(Some(super::super::Kind::Voice))).unwrap();
2215		let raw: Vec<Encoded> = frames
2216			.iter()
2217			.map(|frame| crate::single(encoder.encode_all(frame).unwrap()))
2218			.collect();
2219		let first_dtx = raw.iter().position(|packet| packet.activity.is_dtx()).unwrap();
2220		assert!(
2221			raw[first_dtx..150].iter().any(|packet| packet.activity.is_active()),
2222			"no keep-alive in two seconds of silence"
2223		);
2224		let paused = first_dtx as u64 * 20_000;
2225		let second_dtx = 150 + raw[150..].iter().position(|packet| packet.activity.is_dtx()).unwrap();
2226
2227		for join in [Duration::from_millis(20), Duration::from_millis(100)] {
2228			let (read, activity) = gated(Some(super::super::Kind::Voice), join, &frames).await;
2229			let ends: Vec<(usize, u64)> = (read.iter().enumerate())
2230				.filter_map(|(index, item)| match item {
2231					Read::End { end, .. } => Some((index, micros(*end))),
2232					_ => None,
2233				})
2234				.collect();
2235			assert_eq!(ends.len(), 2, "one end per pause: {read:?}");
2236
2237			// The end is where libopus stopped transmitting, after its hangover.
2238			let (first, end) = ends[0];
2239			assert!(
2240				(paused - 20_000..=paused).contains(&end),
2241				"end at {end} us, transmission stopped at {paused} us"
2242			);
2243			let frame = |index: usize| match &read[index] {
2244				Read::Frame { group, frame } => Some((*group, micros(frame.timestamp))),
2245				_ => None,
2246			};
2247			let (_, last) = frame(first - 1).expect("a frame before the end");
2248			assert_eq!(last, paused - 20_000, "the hangover is published whole");
2249
2250			// Speech resumes on the running timeline, in a group of its own.
2251			let (resumed, at) = frame(first + 1).expect("speech after the end");
2252			assert_eq!(at, 3_000_000);
2253			assert!(
2254				!read[..first]
2255					.iter()
2256					.any(|item| matches!(item, Read::Frame { group, .. } if *group == resumed))
2257			);
2258			assert_eq!(
2259				ends[1].0 - first - 1,
2260				second_dtx - 150,
2261				"the speech and the hangover after it"
2262			);
2263
2264			// Nothing follows the second end: the finish is silence too.
2265			assert_eq!(ends[1].0, read.len() - 1, "{:?}", &read[ends[1].0..]);
2266
2267			// The local indicator follows what the track carries.
2268			assert_eq!(activity[first_dtx - 1], Activity::Active);
2269			assert!(activity[first_dtx..150].iter().all(|activity| activity.is_dtx()));
2270			assert!(activity[150..200].iter().all(|activity| activity.is_active()));
2271		}
2272	}
2273
2274	/// Only voice suppresses silence: music, and audio of no known kind, publish every frame.
2275	#[tokio::test]
2276	async fn other_kinds_send_their_silence() {
2277		let frames = talk();
2278		for kind in [None, Some(super::super::Kind::Music)] {
2279			let (read, activity) = gated(kind, Duration::from_millis(20), &frames).await;
2280			let published: Vec<u64> = (read.iter())
2281				.filter_map(|item| match item {
2282					moq_mux::container::Read::Frame { frame, .. } => Some(micros(frame.timestamp)),
2283					_ => None,
2284				})
2285				.collect();
2286			let every: Vec<u64> = (0..frames.len() as u64).map(|index| index * 20_000).collect();
2287			assert_eq!(published[..frames.len()], every, "{kind:?}");
2288			// The only end is the finish's, which bounds the padded final frame.
2289			let ends = (read.iter())
2290				.filter(|item| matches!(item, moq_mux::container::Read::End { .. }))
2291				.count();
2292			assert_eq!(ends, 1, "{kind:?}");
2293			assert!(activity.iter().all(|activity| activity.is_active()), "{kind:?}");
2294		}
2295	}
2296
2297	/// A mute while the talker is silent ends nothing new: the pause already declared its end.
2298	#[kio::test]
2299	async fn a_mute_in_a_voice_pause_adds_no_end() {
2300		let options = Options {
2301			track: Some("audio".to_string()),
2302			config: mono(Some(super::super::Kind::Voice)),
2303			..Options::default()
2304		};
2305		let mut broadcast = moq_net::broadcast::Info::new().produce();
2306		let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
2307		let consumer = broadcast.consume();
2308		let mut producer = Producer::new(&mut broadcast, catalog, Input::new(48_000, Layout::Mono), &options).unwrap();
2309		let track = consumer
2310			.track("audio")
2311			.unwrap()
2312			.subscribe(
2313				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
2314					moq_net::track::Start::Live {
2315						min: Some(Duration::from_secs(60)),
2316						max: Some(Duration::from_secs(60)),
2317					},
2318				)]),
2319			)
2320			.await
2321			.unwrap();
2322		let mut reader =
2323			moq_mux::container::Consumer::new(track, moq_mux::container::legacy::Wire(moq_mux::container::Kind::Audio));
2324
2325		for (index, frame) in talk()[..150].iter().enumerate() {
2326			producer.write(&pcm_frame(frame, index as u64 * 20_000)).unwrap();
2327		}
2328		assert!(producer.activity().is_dtx());
2329		producer.discontinuity().unwrap();
2330		producer.write(&pcm_frame(&tone(), 3_000_000)).unwrap();
2331		drop(producer);
2332
2333		let mut ends = 0;
2334		while let Ok(Some(item)) = reader.read().await {
2335			match item {
2336				moq_mux::container::Read::End { .. } => ends += 1,
2337				moq_mux::container::Read::Frame { frame, .. } if ends > 0 => {
2338					assert_eq!(micros(frame.timestamp), 3_000_000);
2339				}
2340				_ => {}
2341			}
2342		}
2343		assert_eq!(ends, 1);
2344	}
2345
2346	/// A player hears a voice pause as declared silence and decodes the speech after it.
2347	#[kio::test]
2348	async fn a_voice_pause_decodes_as_an_end() {
2349		let options = Options {
2350			track: Some("audio".to_string()),
2351			config: mono(Some(super::super::Kind::Voice)),
2352			..Options::default()
2353		};
2354		let decoder_config = Encoder::new(&options.config).unwrap().catalog();
2355		let mut broadcast = moq_net::broadcast::Info::new().produce();
2356		let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
2357		let subscriber = broadcast.consume();
2358		let input = Input::new(48_000, Layout::Mono);
2359		let mut producer = Producer::new(&mut broadcast, catalog, input, &options).unwrap();
2360		// Everything is published before the first read, so the player keeps it all.
2361		let decode = DecodeOptions {
2362			delay: crate::decode::Delay::default().with_max(Duration::from_secs(60)),
2363			..DecodeOptions::new()
2364		};
2365		let mut consumer = AudioConsumer::new(&subscriber, &decoder_config, "audio", decode)
2366			.await
2367			.unwrap();
2368
2369		for (index, frame) in talk()[..200].iter().enumerate() {
2370			producer.write(&pcm_frame(frame, index as u64 * 20_000)).unwrap();
2371		}
2372		let _finished = producer.finish().unwrap();
2373
2374		// Decoded frame timestamps, split at each end: the pause's, then the finish's.
2375		let mut spans = vec![Vec::new()];
2376		while let Some(read) = consumer.read().await.unwrap() {
2377			match read {
2378				crate::decode::Read::Frame(frame) => spans.last_mut().unwrap().push(micros(frame.timestamp)),
2379				crate::decode::Read::End { .. } => spans.push(Vec::new()),
2380				crate::decode::Read::Gap { .. } => panic!("a declared pause read as loss"),
2381			}
2382		}
2383		assert_eq!(spans.len(), 3, "{spans:?}");
2384		assert!(spans[0].iter().all(|at| *at < 1_400_000), "{:?}", spans[0]);
2385		assert_eq!(spans[1].first(), Some(&3_000_000), "speech after the pause decodes");
2386		assert!(spans[1].iter().all(|at| *at < 4_000_000), "{:?}", spans[1]);
2387	}
2388
2389	// One 20 ms Opus frame at 48 kHz mono is exactly 960 f32 samples, so each
2390	// `write` of this drains precisely one packet (no resampler, no leftover).
2391	fn full_frame(timestamp_us: u64) -> Frame {
2392		pcm_frame(&vec![0.1; 960], timestamp_us)
2393	}
2394
2395	fn pcm_frame(samples: &[f32], timestamp_us: u64) -> Frame {
2396		let data: Vec<u8> = samples.iter().flat_map(|sample| sample.to_le_bytes()).collect();
2397		Frame::new(Timestamp::from_micros(timestamp_us).unwrap(), Bytes::from(data))
2398	}
2399
2400	/// Publish each frame and read back the resulting packet PTS (microseconds).
2401	/// If `reset_before` contains an index, `reanchor()` is called before that
2402	/// frame's `write`.
2403	async fn published_pts(frames: &[Frame], reset_before: Option<usize>) -> Vec<u128> {
2404		let mut broadcast = moq_net::broadcast::Info::new().produce();
2405		let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
2406		let consumer = broadcast.consume();
2407
2408		// Input rate == Opus codec rate, so there's no resampler and sample
2409		// counts stay exact, making the PTS assertions deterministic.
2410		let input = Input {
2411			format: Format::F32,
2412			sample_rate: 48_000,
2413			layout: Layout::Mono,
2414		};
2415		let options = Options {
2416			track: Some("audio".to_string()),
2417			..Options::default()
2418		};
2419		let mut producer = Producer::new(&mut broadcast, catalog, input, &options).unwrap();
2420
2421		let track = consumer.track("audio").unwrap().subscribe(None).await.unwrap();
2422		let mut reader =
2423			moq_mux::container::Consumer::new(track, moq_mux::container::legacy::Wire(moq_mux::container::Kind::Audio));
2424
2425		let mut pts = Vec::new();
2426		for (i, frame) in frames.iter().enumerate() {
2427			if reset_before == Some(i) {
2428				producer.reanchor();
2429			}
2430			producer.write(frame).unwrap();
2431			let read = packet(&mut reader).await.expect("a packet per full frame");
2432			pts.push(read.timestamp.as_micros().unwrap());
2433		}
2434		pts
2435	}
2436
2437	/// A join of zero would open a group per packet, so the producer refuses it
2438	/// before advertising a track that would never carry the requested layout.
2439	#[tokio::test]
2440	async fn a_zero_join_is_refused() {
2441		let mut broadcast = moq_net::broadcast::Info::new().produce();
2442		let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
2443		let options = Options {
2444			join: Duration::ZERO,
2445			..Options::default()
2446		};
2447		let Err(err) = Producer::new(&mut broadcast, catalog.clone(), Input::default(), &options) else {
2448			panic!("a zero join cannot open");
2449		};
2450		assert!(matches!(err, Error::Unsupported(_)), "unexpected error: {err:?}");
2451		assert!(catalog.snapshot().audio.renditions.is_empty());
2452	}
2453
2454	/// The packet that reaches the join closes its group, so a join that isn't a
2455	/// whole number of packets rounds up, and one shorter than a packet groups each.
2456	#[kio::test]
2457	async fn join_packs_packets_per_group() {
2458		for (group_ms, expected) in [(1, [1, 1]), (30, [2, 2]), (100, [5, 5])] {
2459			let mut broadcast = moq_net::broadcast::Info::new().produce();
2460			let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
2461			let consumer = broadcast.consume();
2462			let input = Input {
2463				format: Format::F32,
2464				sample_rate: 48_000,
2465				layout: Layout::Mono,
2466			};
2467			let options = Options {
2468				track: Some("audio".to_string()),
2469				join: Duration::from_millis(group_ms),
2470				..Options::default()
2471			};
2472			let mut producer = Producer::new(&mut broadcast, catalog, input, &options).unwrap();
2473			let mut track = consumer
2474				.track("audio")
2475				.unwrap()
2476				.subscribe(
2477					moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
2478						moq_net::track::Start::Live {
2479							min: Some(Duration::from_secs(1)),
2480							max: Some(Duration::from_secs(1)),
2481						},
2482					)]),
2483				)
2484				.await
2485				.unwrap();
2486
2487			for index in 0..10 {
2488				producer.write(&full_frame(index * 20_000)).unwrap();
2489			}
2490
2491			let mut sizes = Vec::new();
2492			for _ in expected {
2493				let mut group = track.recv_group().await.unwrap().expect("a group");
2494				let mut frames = 0;
2495				while group.read_frame().await.unwrap().is_some() {
2496					frames += 1;
2497				}
2498				sizes.push(frames);
2499			}
2500			assert_eq!(sizes, expected, "group duration {group_ms} ms");
2501		}
2502	}
2503
2504	#[tokio::test(start_paused = true)]
2505	async fn default_groups_carry_one_hundred_milliseconds() {
2506		for (frame_us, packets) in [(2_500, 40), (10_000, 10), (20_000, 5), (40_000, 3)] {
2507			let mut broadcast = moq_net::broadcast::Info::new().produce();
2508			let consumer = broadcast.consume();
2509			let catalog = moq_mux::catalog::Producer::new(&mut broadcast, Default::default()).unwrap();
2510			let input = Input {
2511				format: Format::F32,
2512				sample_rate: 48_000,
2513				layout: Layout::Mono,
2514			};
2515			let mut options = Options {
2516				track: Some("audio".into()),
2517				..Default::default()
2518			};
2519			options.config.layout = Layout::Mono;
2520			options.config.frame_duration = Duration::from_micros(frame_us);
2521			let mut producer = Producer::new(&mut broadcast, catalog, input, &options).unwrap();
2522			let mut track = consumer
2523				.track("audio")
2524				.unwrap()
2525				.subscribe(
2526					moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
2527						moq_net::track::Start::Live {
2528							min: Some(Duration::from_secs(1)),
2529							max: Some(Duration::from_secs(1)),
2530						},
2531					)]),
2532				)
2533				.await
2534				.unwrap();
2535			for index in 0..packets * 2 {
2536				producer
2537					.write(&pcm_frame(
2538						&vec![0.1; (frame_us * 48_000 / 1_000_000) as usize],
2539						1_000_000 + index * frame_us,
2540					))
2541					.unwrap();
2542			}
2543			for _ in 0..2 {
2544				let mut group = track.recv_group().await.unwrap().unwrap();
2545				let mut count = 0;
2546				while group.read_frame().await.unwrap().is_some() {
2547					count += 1;
2548				}
2549				assert_eq!(count, packets, "{frame_us} us packets");
2550			}
2551			let _finished = producer.finish().unwrap();
2552		}
2553	}
2554
2555	/// Timeline breaks close a partial group and reset the resumed group's packet count.
2556	#[kio::test]
2557	async fn join_restarts_after_a_timeline_break() {
2558		for deferred in [false, true] {
2559			let mut broadcast = moq_net::broadcast::Info::new().produce();
2560			let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
2561			let consumer = broadcast.consume();
2562			let input = Input {
2563				format: Format::F32,
2564				sample_rate: 48_000,
2565				layout: Layout::Mono,
2566			};
2567			let options = Options {
2568				track: Some("audio".to_string()),
2569				join: Duration::from_millis(100),
2570				..Options::default()
2571			};
2572			let mut producer = Producer::new(&mut broadcast, catalog, input, &options).unwrap();
2573			let mut track = consumer.track("audio").unwrap().subscribe(None).await.unwrap();
2574
2575			for index in 0..2 {
2576				producer.write(&full_frame(index * 20_000)).unwrap();
2577			}
2578			let mut partial = track.recv_group().await.unwrap().expect("partial group");
2579			for _ in 0..2 {
2580				assert!(
2581					partial.read_frame().await.unwrap().is_some(),
2582					"packets forward before the group fills"
2583				);
2584			}
2585			assert!(partial.poll_read_frame(&kio::Waiter::noop()).is_pending());
2586
2587			if deferred {
2588				producer.reanchor();
2589				assert!(partial.poll_read_frame(&kio::Waiter::noop()).is_pending());
2590			} else {
2591				producer.discontinuity().unwrap();
2592				assert!(partial.read_frame().await.unwrap().is_none());
2593			}
2594			for index in 0..5 {
2595				producer.write(&full_frame(1_000_000 + index * 20_000)).unwrap();
2596			}
2597			assert!(partial.read_frame().await.unwrap().is_none());
2598			let mut resumed = track.recv_group().await.unwrap().expect("resumed group");
2599			assert_eq!(
2600				resumed.start, 1_000_000,
2601				"the resumed group starts at its first packet, in the track's microseconds"
2602			);
2603			for _ in 0..5 {
2604				assert!(resumed.read_frame().await.unwrap().is_some());
2605			}
2606			assert!(resumed.read_frame().await.unwrap().is_none());
2607		}
2608	}
2609
2610	#[kio::test]
2611	async fn anchors_to_first_frame_timestamp() {
2612		// The first frame's timestamp becomes the anchor (regression guard: the
2613		// old code derived PTS purely from the sample count, always near 0).
2614		let pts = published_pts(&[full_frame(1_000_000)], None).await;
2615		assert_eq!(pts, vec![1_000_000]);
2616	}
2617
2618	/// AAC can't signal its encoder delay, so each packet is stamped that much
2619	/// earlier and the first input sample still decodes at the anchor.
2620	#[kio::test]
2621	async fn aac_folds_the_encoder_delay_into_timestamps() {
2622		async fn pts(anchor_us: u64) -> Vec<u128> {
2623			let mut broadcast = moq_net::broadcast::Info::new().produce();
2624			let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
2625			let consumer = broadcast.consume();
2626
2627			let input = Input::new(48_000, Layout::Mono);
2628			let options = Options {
2629				track: Some("audio".to_string()),
2630				config: Config::from_input(crate::encode::Codec::Aac, &input),
2631				..Options::default()
2632			};
2633			let stub = crate::encode::backend::stub::install();
2634			let mut producer = Producer::new(&mut broadcast, catalog, input, &options).unwrap();
2635			drop(stub);
2636
2637			let track = consumer
2638				.track("audio")
2639				.unwrap()
2640				.subscribe(
2641					moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
2642						moq_net::track::Start::Live {
2643							min: Some(Duration::from_secs(1)),
2644							max: Some(Duration::from_secs(1)),
2645						},
2646					)]),
2647				)
2648				.await
2649				.unwrap();
2650			let mut reader = moq_mux::container::Consumer::new(
2651				track,
2652				moq_mux::container::legacy::Wire(moq_mux::container::Kind::Audio),
2653			);
2654
2655			producer.write(&pcm_frame(&[0.1; 4 * 1024], anchor_us)).unwrap();
2656			let mut pts = Vec::new();
2657			for _ in 0..4 {
2658				pts.push(
2659					packet(&mut reader)
2660						.await
2661						.expect("a packet")
2662						.timestamp
2663						.as_micros()
2664						.unwrap(),
2665				);
2666			}
2667			pts
2668		}
2669
2670		// 2112 frames of delay at 48 kHz is 44 ms, rounded down per packet.
2671		assert_eq!(pts(1_000_000).await, vec![956_000, 977_333, 998_666, 1_020_000]);
2672		// Priming before a zero anchor stamps at zero; the input still starts on time.
2673		assert_eq!(pts(0).await, vec![0, 0, 0, 20_000]);
2674	}
2675
2676	/// Group starts strictly increase, so a reanchor never stamps below where the packets before
2677	/// it end: an AAC resume closer than its encoder delay stamps the priming there, and a resume
2678	/// that rewinds starts there.
2679	#[kio::test]
2680	async fn a_reanchor_resumes_no_earlier_than_the_packets_before_it_end() {
2681		async fn pts(resume_us: u64) -> Vec<u128> {
2682			let mut broadcast = moq_net::broadcast::Info::new().produce();
2683			let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
2684			let consumer = broadcast.consume();
2685
2686			let input = Input::new(48_000, Layout::Mono);
2687			let options = Options {
2688				track: Some("audio".to_string()),
2689				config: Config::from_input(crate::encode::Codec::Aac, &input),
2690				// A group per packet, so the break follows a group that ended whole.
2691				join: Duration::from_millis(20),
2692				..Options::default()
2693			};
2694			let stub = crate::encode::backend::stub::install();
2695			let mut producer = Producer::new(&mut broadcast, catalog, input, &options).unwrap();
2696			drop(stub);
2697
2698			let track = consumer
2699				.track("audio")
2700				.unwrap()
2701				.subscribe(
2702					moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
2703						moq_net::track::Start::Live {
2704							min: Some(Duration::from_secs(1)),
2705							max: Some(Duration::from_secs(1)),
2706						},
2707					)]),
2708				)
2709				.await
2710				.unwrap();
2711			let mut reader = moq_mux::container::Consumer::new(
2712				track,
2713				moq_mux::container::legacy::Wire(moq_mux::container::Kind::Audio),
2714			);
2715
2716			// Stamped 956_000 to 1_020_000, the last packet ending at 1_041_333.
2717			producer.write(&pcm_frame(&[0.1; 4 * 1024], 1_000_000)).unwrap();
2718			producer.reanchor();
2719			producer.write(&pcm_frame(&[0.1; 4 * 1024], resume_us)).unwrap();
2720			let mut pts = Vec::new();
2721			for _ in 0..8 {
2722				pts.push(
2723					packet(&mut reader)
2724						.await
2725						.expect("a packet")
2726						.timestamp
2727						.as_micros()
2728						.unwrap(),
2729				);
2730			}
2731			pts.split_off(4)
2732		}
2733
2734		// Priming would start at 1_006_000. The break's marker starts where the packets before it
2735		// end, so the group after it starts a microsecond later, and so does every packet stamped
2736		// with its first.
2737		assert_eq!(pts(1_050_000).await, vec![1_041_334, 1_041_334, 1_048_666, 1_070_000]);
2738		assert_eq!(pts(1_000_000).await, vec![1_041_334, 1_041_334, 1_041_334, 1_061_333]);
2739	}
2740
2741	/// Priming stamped where the packets before a reanchor end lands on the break's marker, so the
2742	/// muxer writes it a unit later. Stopping with only priming in the open group leaves that group
2743	/// open for the packet that moves on, as `publish` does, rather than cutting below its packets.
2744	#[tokio::test]
2745	async fn stopping_after_priming_on_a_marker_keeps_the_track() {
2746		let mut broadcast = moq_net::broadcast::Info::new().produce();
2747		let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
2748		let input = Input::new(48_000, Layout::Mono);
2749		let options = Options {
2750			track: Some("audio".to_string()),
2751			config: Config::from_input(crate::encode::Codec::Aac, &input),
2752			..Options::default()
2753		};
2754		let stub = crate::encode::backend::stub::install();
2755		let mut producer = Producer::new(&mut broadcast, catalog, input, &options).unwrap();
2756		drop(stub);
2757
2758		producer.write(&pcm_frame(&[0.1; 4 * 1024], 1_000_000)).unwrap();
2759		producer.reanchor();
2760		// The codec returns two priming packets, stamped at 1_041_333 and written at 1_041_334.
2761		producer.write(&pcm_frame(&[0.1; 2 * 1024], 1_000_000)).unwrap();
2762		producer
2763			.set_active(false, Timestamp::from_micros(1_100_000).unwrap())
2764			.unwrap();
2765		producer
2766			.set_active(true, Timestamp::from_micros(1_100_000).unwrap())
2767			.unwrap();
2768		producer.write(&pcm_frame(&[0.1; 3 * 1024], 1_021_333)).unwrap();
2769		let _finished = producer.finish().unwrap();
2770	}
2771
2772	/// A codec that holds frames returns their packets late, and each still goes out at the stamp
2773	/// of the frame it encoded, including the one only `finish` flushes out ahead of the drain.
2774	#[kio::test]
2775	async fn held_packets_keep_their_frames_stamps() {
2776		let mut broadcast = moq_net::broadcast::Info::new().produce();
2777		let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
2778		let consumer = broadcast.consume();
2779
2780		let input = Input::new(48_000, Layout::Mono);
2781		let options = Options {
2782			track: Some("audio".to_string()),
2783			config: Config::from_input(crate::encode::Codec::Aac, &input),
2784			..Options::default()
2785		};
2786		let stub = crate::encode::backend::stub::install();
2787		let mut producer = Producer::new(&mut broadcast, catalog, input, &options).unwrap();
2788		drop(stub);
2789
2790		let track = consumer
2791			.track("audio")
2792			.unwrap()
2793			.subscribe(
2794				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
2795					moq_net::track::Start::Live {
2796						min: Some(Duration::from_secs(1)),
2797						max: Some(Duration::from_secs(1)),
2798					},
2799				)]),
2800			)
2801			.await
2802			.unwrap();
2803		let mut reader =
2804			moq_mux::container::Consumer::new(track, moq_mux::container::legacy::Wire(moq_mux::container::Kind::Audio));
2805
2806		// The stub holds the third frame, so only `finish` releases it.
2807		producer.write(&pcm_frame(&[0.1; 3 * 1024], 1_000_000)).unwrap();
2808		let _finished = producer.finish().unwrap();
2809
2810		let mut published = Vec::new();
2811		while let Some(frame) = packet(&mut reader).await {
2812			let index = u64::from_be_bytes(frame.payload[..].try_into().unwrap());
2813			published.push((index, frame.timestamp.as_micros().unwrap()));
2814		}
2815		// Each frame is stamped 2112 frames of priming early, the drain's three silent ones too.
2816		assert_eq!(
2817			published,
2818			vec![
2819				(0, 956_000),
2820				(1, 977_333),
2821				(2, 998_666),
2822				(3, 1_020_000),
2823				(4, 1_041_333),
2824				(5, 1_062_666),
2825			]
2826		);
2827	}
2828
2829	/// The encoder needs no correction for the resampler's own delay: it anchors
2830	/// the anchor to the first input timestamp and advances by emitted samples,
2831	/// while `Resampler::process` drops its startup silence rather than passing it
2832	/// on, so the first sample published is the first sample written. Anything
2833	/// that let that delay through would shift every PTS on a resampled track,
2834	/// which no `reanchor` would ever correct.
2835	#[kio::test]
2836	async fn resampling_does_not_shift_the_first_pts() {
2837		let mut broadcast = moq_net::broadcast::Info::new().produce();
2838		let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
2839		let consumer = broadcast.consume();
2840
2841		// 44.1 kHz in, and Opus only runs at 48 kHz, so this one resamples.
2842		let input = Input {
2843			format: Format::F32,
2844			sample_rate: 44_100,
2845			layout: Layout::Mono,
2846		};
2847		let options = Options {
2848			track: Some("audio".to_string()),
2849			..Options::default()
2850		};
2851		let mut producer = Producer::new(&mut broadcast, catalog, input, &options).unwrap();
2852
2853		// A whole second goes out before the first read, so the default budget of zero
2854		// would shed all but the last packet and the first PTS read would be the tail's.
2855		let track = consumer
2856			.track("audio")
2857			.unwrap()
2858			.subscribe(
2859				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
2860					moq_net::track::Start::Live {
2861						min: Some(Duration::from_secs(1)),
2862						max: Some(Duration::from_secs(1)),
2863					},
2864				)]),
2865			)
2866			.await
2867			.unwrap();
2868		let mut reader =
2869			moq_mux::container::Consumer::new(track, moq_mux::container::legacy::Wire(moq_mux::container::Kind::Audio));
2870
2871		// A second of audio, so the filter's delay is nowhere near the whole write.
2872		producer.write(&pcm_frame(&vec![0.1; 44_100], 1_000_000)).unwrap();
2873
2874		let first = packet(&mut reader).await.expect("a packet");
2875		assert_eq!(first.timestamp.as_micros().unwrap(), 1_000_000);
2876	}
2877
2878	#[kio::test]
2879	async fn pts_advances_by_frame_duration_ignoring_later_timestamps() {
2880		// Second frame's own timestamp (way ahead) is ignored; PTS advances by
2881		// exactly one 20 ms frame from the anchor.
2882		let pts = published_pts(&[full_frame(1_000), full_frame(999_999)], None).await;
2883		assert_eq!(pts, vec![1_000, 1_000 + 20_000]);
2884	}
2885
2886	#[kio::test]
2887	async fn reanchor_lets_the_gap_land_in_pts() {
2888		// Frame at t=0, then reanchor + a frame at t=5s: the 5 s idle gap must
2889		// appear in the PTS (otherwise audio drifts behind a wall-clock video track).
2890		let pts = published_pts(&[full_frame(0), full_frame(5_000_000)], Some(1)).await;
2891		assert_eq!(pts, vec![0, 5_000_000]);
2892	}
2893
2894	/// `Options::track = None` derives a codec-suffixed name rather than making
2895	/// the caller invent one, mirroring the video side. Pins the exact name the
2896	/// docs promise, and that a second producer doesn't collide with the first.
2897	#[tokio::test]
2898	async fn default_options_derive_the_track_name() {
2899		let mut broadcast = moq_net::broadcast::Info::new().produce();
2900		let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
2901
2902		let first = Producer::new(&mut broadcast, catalog.clone(), Input::default(), &Options::default()).unwrap();
2903		assert_eq!(first.track_name(), "0.opus");
2904
2905		let second = Producer::new(&mut broadcast, catalog, Input::default(), &Options::default()).unwrap();
2906		assert_eq!(second.track_name(), "1.opus");
2907	}
2908
2909	#[tokio::test(start_paused = true)]
2910	async fn retuning_updates_the_published_bitrate_in_place() {
2911		let mut broadcast = moq_net::broadcast::Info::new().produce();
2912		let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
2913		let options = Options {
2914			track: Some("audio".into()),
2915			..Options::default()
2916		};
2917		let mut producer = Producer::new(&mut broadcast, catalog.clone(), Input::default(), &options).unwrap();
2918		let before = catalog.snapshot().audio.renditions["audio"].clone();
2919		let bitrate = moq_net::bandwidth::Rate::from_bps(64_000);
2920		producer.set_bitrate(bitrate).unwrap();
2921		let after = catalog.snapshot();
2922		assert_eq!(after.audio.renditions.len(), 1);
2923		let mut expected = before;
2924		expected.bitrate = Some(64_000);
2925		assert_eq!(after.audio.renditions["audio"], expected);
2926		assert_eq!(producer.track_name(), "audio");
2927		assert_eq!(producer.bitrate(), bitrate);
2928		// Encoded-byte detection must not replace the newly configured target.
2929		for timestamp in [0, 20_000, 40_000] {
2930			producer.write(&pcm_frame(&vec![0.1; 1920], timestamp)).unwrap();
2931		}
2932		assert_eq!(catalog.snapshot().audio.renditions["audio"].bitrate, Some(64_000));
2933	}
2934
2935	/// The rendition a producer publishes is the encoder's own catalog, so neither can drift.
2936	#[tokio::test]
2937	async fn publishes_the_encoder_catalog() {
2938		for codec in [crate::encode::Codec::Opus, crate::encode::Codec::Pcm] {
2939			let mut broadcast = moq_net::broadcast::Info::new().produce();
2940			let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
2941			let options = Options {
2942				track: Some("audio".into()),
2943				config: Config {
2944					codec,
2945					..Config::default()
2946				},
2947				..Options::default()
2948			};
2949			let _producer = Producer::new(&mut broadcast, catalog.clone(), Input::default(), &options).unwrap();
2950			let published = catalog.snapshot().audio.renditions.remove("audio").unwrap();
2951			assert_eq!(published, Encoder::new(&options.config).unwrap().catalog(), "{codec:?}");
2952		}
2953	}
2954
2955	/// A resampler holds input past the frame it completes, so a resampled rendition leaves its
2956	/// delay to measurement instead of stating the encoder's zero.
2957	#[tokio::test]
2958	async fn a_resampled_rendition_measures_its_delay() {
2959		for (rate, delay) in [(48_000, Some(Duration::ZERO)), (44_100, None)] {
2960			let mut broadcast = moq_net::broadcast::Info::new().produce();
2961			let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
2962			let options = Options {
2963				track: Some("audio".into()),
2964				..Options::default()
2965			};
2966			let input = Input::new(rate, crate::Layout::Stereo);
2967			let _producer = Producer::new(&mut broadcast, catalog.clone(), input, &options).unwrap();
2968			assert_eq!(catalog.snapshot().audio.renditions["audio"].delay, delay, "{rate} Hz");
2969		}
2970	}
2971
2972	/// Captured audio for [`capture_offsets`]: a device clock `ppm` fast of the host's, 10 ms
2973	/// buffers stamped late by up to `late_us`, and from `jump.0` seconds in, stamps moved by
2974	/// `jump.1` microseconds, as a host suspend (forward) or a burst of queued audio (backward).
2975	struct Capture {
2976		input_rate: u32,
2977		codec_rate: u32,
2978		ppm: f64,
2979		seconds: u64,
2980		late_us: u64,
2981		jump: Option<(u64, i64)>,
2982	}
2983
2984	/// How far each packet's PTS lands from the host instant its first sample was captured, in
2985	/// microseconds, by when that sample was captured, in seconds.
2986	///
2987	/// The input is a ramp of its own sample index, so each packet's first sample names the input
2988	/// sample it holds, whatever was resampled, slipped, or dropped. PCM keeps it exact.
2989	async fn capture_offsets(capture: Capture) -> Vec<(f64, f64)> {
2990		let input = Input {
2991			format: Format::F32,
2992			sample_rate: capture.input_rate,
2993			layout: Layout::Mono,
2994		};
2995		let mut config = Config::from_input(super::super::Codec::Pcm, &input);
2996		config.sample_rate = capture.codec_rate;
2997		let options = Options {
2998			track: Some("audio".into()),
2999			config,
3000			..Options::default()
3001		};
3002		let mut broadcast = moq_net::broadcast::Info::new().produce();
3003		let consumer = broadcast.consume();
3004		let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
3005		let mut producer = Producer::capture(&mut broadcast, catalog, input, &options).unwrap();
3006		let track = consumer.track("audio").unwrap().subscribe(None).await.unwrap();
3007		let mut reader =
3008			moq_mux::container::Consumer::new(track, moq_mux::container::legacy::Wire(moq_mux::container::Kind::Audio));
3009
3010		let device_rate = f64::from(capture.input_rate) * (1.0 + capture.ppm * 1e-6);
3011		let captured = |index: f64| {
3012			let at = 1.0 + index / device_rate;
3013			let jump = capture.jump.filter(|(from, _)| at - 1.0 >= *from as f64);
3014			at + jump.map_or(0.0, |(_, by)| by as f64 / 1e6)
3015		};
3016		let block = capture.input_rate as usize / 100;
3017		let total = capture.input_rate as usize * capture.seconds as usize;
3018		assert!(total < 1 << 24, "the ramp must stay exact in f32");
3019		// A fixed LCG, so the jitter is the same every run.
3020		let mut seed = 0x2545_f491_u64;
3021		let mut offsets = Vec::new();
3022		for start in (0..total).step_by(block) {
3023			seed = seed
3024				.wrapping_mul(6_364_136_223_846_793_005)
3025				.wrapping_add(1_442_695_040_888_963_407);
3026			let late = (seed >> 33) % capture.late_us.max(1);
3027			let at = (captured(start as f64) * 1e6) as u64 + late;
3028			let ramp: Vec<f32> = (start..start + block).map(|index| index as f32).collect();
3029			producer.write(&pcm_frame(&ramp, at)).unwrap();
3030			while let Some(Some(packet)) = now_or_never(packet(&mut reader)) {
3031				let first = captured(f64::from(f32::from_le_bytes(packet.payload[..4].try_into().unwrap())));
3032				offsets.push((first, packet.timestamp.as_micros().unwrap() as f64 - first * 1e6));
3033			}
3034			// One task poll per block: the simulator panics on a poll that reads ready too often.
3035			kio::clock::sim::yield_now().await;
3036		}
3037		offsets
3038	}
3039
3040	/// Poll `future` once, for a reader that must not wait on packets not yet written.
3041	fn now_or_never<F: std::future::Future>(future: F) -> Option<F::Output> {
3042		let mut future = std::pin::pin!(future);
3043		match future
3044			.as_mut()
3045			.poll(&mut std::task::Context::from_waker(std::task::Waker::noop()))
3046		{
3047			Poll::Ready(output) => Some(output),
3048			Poll::Pending => None,
3049		}
3050	}
3051
3052	/// The worst offset from `after` seconds on, against the first packet's, in milliseconds.
3053	fn drift(offsets: &[(f64, f64)], after: f64) -> f64 {
3054		let start = offsets[0].1;
3055		let offsets = offsets.iter().filter(|(at, _)| *at >= after);
3056		offsets
3057			.map(|(_, offset)| (offset - start).abs() / 1e3)
3058			.fold(0.0, f64::max)
3059	}
3060
3061	/// One 20 ms PCM frame: how far captured audio may drift from its video.
3062	const FRAME_MS: f64 = 20.0;
3063
3064	/// A device clock at the 1000 ppm bound, either way, stays within a frame of its capture
3065	/// stamps, slipping frames at the codec's rate and resampling onto another. Uncorrected, it
3066	/// drifts 30 ms in these 30 s.
3067	#[kio::test]
3068	async fn capture_follows_the_device_clock_onto_the_host_clock() {
3069		for (input_rate, ppm) in [(48_000, 1000.0), (48_000, -1000.0), (44_100, 1000.0), (44_100, -1000.0)] {
3070			let offsets = capture_offsets(Capture {
3071				input_rate,
3072				codec_rate: 48_000,
3073				ppm,
3074				seconds: 30,
3075				late_us: 2_000,
3076				jump: None,
3077			})
3078			.await;
3079			let drift = drift(&offsets, 0.0);
3080			assert!(drift < FRAME_MS, "{input_rate} Hz at {ppm} ppm drifted {drift:.2} ms");
3081		}
3082	}
3083
3084	/// Stamps that jump further than a ratio can slew put the PTS back on them within a second: a
3085	/// suspended host re-anchors so the gap lands in the PTS, and audio queued past its time is
3086	/// dropped until the stamps catch up, so the timeline never runs backwards.
3087	#[kio::test]
3088	async fn capture_recovers_from_a_jump_in_its_stamps() {
3089		for jump in [2_000_000, -500_000] {
3090			let offsets = capture_offsets(Capture {
3091				input_rate: 48_000,
3092				codec_rate: 48_000,
3093				ppm: 0.0,
3094				seconds: 12,
3095				late_us: 2_000,
3096				jump: Some((5, jump)),
3097			})
3098			.await;
3099			let recovered = 1.0 + 5.0 + jump.max(0) as f64 / 1e6 + 1.1;
3100			let drift = drift(&offsets, recovered);
3101			assert!(drift < FRAME_MS, "a {jump} us jump left {drift:.2} ms");
3102			let stamps: Vec<f64> = offsets.iter().map(|(at, offset)| at * 1e6 + offset).collect();
3103			assert!(stamps.is_sorted(), "a {jump} us jump moved the PTS backwards");
3104		}
3105	}
3106}