Skip to main content

moq_mux/import/
track.rs

1//! Single-codec importers.
2//!
3//! [`Track`] publishes one MoQ track from whole frames; [`TrackStream`] does the
4//! same from a raw byte stream where frame boundaries have to be inferred. Both
5//! own exactly one track, so they expose [`Track::demand`] / [`Track::name`]
6//! directly rather than fallibly.
7
8use crate::Result;
9use crate::catalog::VideoHint;
10use crate::catalog::hang::CatalogExt;
11use crate::container::Frame;
12
13use super::{AudioFormat, AudioInit, VideoFormat, VideoInit};
14
15/// The caller's video fields, defaulting the codec from the format when the codec carries no extra
16/// parameters (VP8), so a hint with a codec can publish before the first frame.
17fn video_hint(init: &VideoInit, default_codec: Option<hang::catalog::VideoCodec>) -> VideoHint {
18	let mut hint = init.hint.clone();
19	hint.label = init.label.clone();
20	if hint.codec.is_none() {
21		hint.codec = default_codec;
22	}
23	hint
24}
25
26/// The track info for a rendition in `container`. A CMAF track counts in its init's `mdhd` ticks,
27/// as the moq-hang draft requires, so each frame timestamp lands on a media tick.
28fn track_info<E: CatalogExt>(
29	reserved: &crate::catalog::Reserved<E>,
30	priority: i8,
31	container: &hang::catalog::Container,
32) -> Result<moq_net::track::Info> {
33	let info = reserved.track_info(priority);
34	match container {
35		hang::catalog::Container::Cmaf { init, .. } => {
36			let wire = crate::container::fmp4::Wire::from_init(init)?;
37			Ok(info.with_timescale(wire.timescale()?))
38		}
39		_ => Ok(info),
40	}
41}
42
43/// The codec parser fills the decoder fields from the init bytes; the caller adds the label, the
44/// container, and the bitrate when it knows it, which then counts as supplied and replaces any the
45/// init bytes give.
46fn with_init(init: &AudioInit, mut config: hang::catalog::AudioConfig) -> hang::catalog::AudioConfig {
47	config.label = init.label.clone();
48	config.container = init.container.clone();
49	if init.bitrate.is_some() {
50		config.bitrate = init.bitrate;
51	}
52	config
53}
54
55/// Build an H.264 avc3 split + import pair.
56///
57/// The import reads `init` for the codec config (or publishes from `hint` up front); the split then
58/// reads it as the leading bytes of the stream (caching any inline SPS/PPS). Any frames in the init
59/// buffer are published: a final picture with the next decode's timestamp, or at finish.
60fn build_h264_avc3<E: CatalogExt>(
61	track: moq_net::track::Producer,
62	reserved: crate::catalog::Reserved<E>,
63	init: &[u8],
64	hint: VideoHint,
65) -> Result<(crate::codec::h264::Split, crate::codec::h264::Import)> {
66	let mut import = crate::codec::h264::Import::new(track, reserved, hint)?;
67	import.initialize(init)?;
68	let mut split = crate::codec::h264::Split::new();
69	let frames = split.initialize(init)?;
70	import.decode(frames)?;
71	Ok((split, import))
72}
73
74/// Build an H.264 avc1 import, resolving the config and the NALU length size from
75/// the avcC. avc1 has no splitter: each access unit is wrapped directly via
76/// [`crate::codec::h264::avc1_frame`].
77fn build_h264_avc1<E: CatalogExt>(
78	track: moq_net::track::Producer,
79	reserved: crate::catalog::Reserved<E>,
80	init: &[u8],
81	hint: VideoHint,
82) -> Result<(usize, crate::codec::h264::Import)> {
83	let mut import = crate::codec::h264::Import::new(track, reserved, hint)?;
84	import.initialize(init)?;
85	let length_size = crate::codec::h264::Avcc::parse(init)?.length_size;
86	Ok((length_size, import))
87}
88
89/// Build an H.265 split + import pair.
90fn build_h265<E: CatalogExt>(
91	track: moq_net::track::Producer,
92	reserved: crate::catalog::Reserved<E>,
93	init: &[u8],
94	hint: VideoHint,
95) -> Result<(crate::codec::h265::Split, crate::codec::h265::Import)> {
96	let mut import = crate::codec::h265::Import::new(track, reserved, hint)?;
97	import.initialize(init)?;
98	let mut split = crate::codec::h265::Split::new();
99	let frames = split.initialize(init)?;
100	import.decode(frames)?;
101	Ok((split, import))
102}
103
104/// Build an H.265 hvc1 import, resolving the config and the NALU length size from
105/// the hvcC. hvc1 has no splitter: each access unit is wrapped directly via
106/// [`crate::codec::h265::hvc1_frame`].
107fn build_h265_hvc1<E: CatalogExt>(
108	track: moq_net::track::Producer,
109	reserved: crate::catalog::Reserved<E>,
110	init: &[u8],
111	hint: VideoHint,
112) -> Result<(usize, crate::codec::h265::Import)> {
113	let mut import = crate::codec::h265::Import::new(track, reserved, hint)?;
114	import.initialize(init)?;
115	let length_size = crate::codec::h265::Hvcc::parse(init)?.length_size;
116	Ok((length_size, import))
117}
118
119/// Build an AV1 split + import pair.
120fn build_av1<E: CatalogExt>(
121	track: moq_net::track::Producer,
122	reserved: crate::catalog::Reserved<E>,
123	init: &[u8],
124	hint: VideoHint,
125) -> Result<(crate::codec::av1::Split, crate::codec::av1::Import)> {
126	let mut import = crate::codec::av1::Import::new(track, reserved, hint)?;
127	import.initialize(init)?;
128	let mut split = crate::codec::av1::Split::new();
129	// av1C (leading 0x81, ISO/IEC 14496-15) is an out-of-band config record, not an
130	// OBU stream, so it's read for config (above) and dropped here. Raw OBUs are the
131	// leading bytes of the stream and feed the splitter.
132	let frames = if crate::codec::av1::is_av1c(init) {
133		Vec::new()
134	} else {
135		split.decode(init, None)?
136	};
137	import.decode(frames)?;
138	Ok((split, import))
139}
140
141/// An audio format handed to a video-only operation.
142fn not_video(format: AudioFormat) -> crate::Error {
143	crate::Error::WrongKind {
144		format: format.to_string(),
145		actual: "audio",
146		wanted: "video",
147	}
148}
149
150enum TrackKind {
151	/// H.264 Annex B with inline SPS/PPS, published as avc3. The split owns byte
152	/// parsing; the import publishes.
153	H264 {
154		split: crate::codec::h264::Split,
155		import: crate::codec::h264::Import,
156	},
157	/// H.264 length-prefixed NALU with an avcC, published as avc1 or avc3. No splitter: each
158	/// access unit is wrapped directly. `length_size` is the NALU length prefix
159	/// width read from the avcC.
160	Avc1 {
161		length_size: usize,
162		import: crate::codec::h264::Import,
163	},
164	H265 {
165		split: crate::codec::h265::Split,
166		import: crate::codec::h265::Import,
167	},
168	/// H.265 length-prefixed NALU with an hvcC, published as hvc1 or hev1. No splitter: each
169	/// access unit is wrapped directly. `length_size` is the NALU length prefix
170	/// width read from the hvcC.
171	Hvc1 {
172		length_size: usize,
173		import: crate::codec::h265::Import,
174	},
175	Av01 {
176		split: crate::codec::av1::Split,
177		import: crate::codec::av1::Import,
178	},
179	Vp8(crate::codec::vp8::Import),
180	Vp9(crate::codec::vp9::Import),
181	Aac(crate::codec::aac::Import),
182	Opus(crate::codec::opus::Import),
183	Mp3(crate::codec::mp3::Import),
184	Flac(crate::codec::flac::Import),
185}
186
187/// Forward a call to whichever codec importer a [`Track`] holds.
188macro_rules! import {
189	($kind:expr, $import:ident => $body:expr) => {
190		match $kind {
191			TrackKind::H264 { $import, .. } | TrackKind::Avc1 { $import, .. } => $body,
192			TrackKind::H265 { $import, .. } | TrackKind::Hvc1 { $import, .. } => $body,
193			TrackKind::Av01 { $import, .. } => $body,
194			TrackKind::Vp8($import) => $body,
195			TrackKind::Vp9($import) => $body,
196			TrackKind::Aac($import) => $body,
197			TrackKind::Opus($import) => $body,
198			TrackKind::Mp3($import) => $body,
199			TrackKind::Flac($import) => $body,
200		}
201	};
202}
203
204/// A single-codec importer for whole frames.
205///
206/// Use this when the caller already has whole frames (the typical case for files
207/// and reassembled network input). Each [`decode`](Self::decode) call takes one
208/// complete frame.
209///
210/// Video groups by its own keyframes. Audio is independently decodable per frame, so it has no
211/// boundary of its own: this closes a group on the frame that brings it to
212/// [`Join::DEFAULT`](crate::container::Join::DEFAULT) of audio, so the relay sees it finish at once
213/// and keeps one group (one QUIC stream) per span rather than one per packet. Frames forward as they
214/// are written either way. [`cut`](Self::cut) still closes a group early,
215/// and the next span starts from the frame after.
216pub struct Track {
217	kind: TrackKind,
218
219	/// Where the open audio group closes. Unused for video, which groups at its keyframes.
220	audio: Grouping,
221}
222
223/// When an audio track closes its open group.
224#[derive(Default)]
225struct Grouping {
226	join: crate::container::Join,
227	/// The last packet carried audio rather than DTX, so a DTX packet now starts a silence.
228	speaking: bool,
229}
230
231impl Grouping {
232	/// Count a written frame into the open group, and return `Some` with where it ends, when known,
233	/// once the group should close.
234	///
235	/// A frame that doesn't say how long it plays counts as a point, so its group closes on the
236	/// first frame starting a span past it instead. An Opus encoder entering DTX sends a
237	/// header-only `pause` packet, so the first one after audio closes its group, even one it
238	/// opens, rather than leaving it open through the silence; further ones fill groups like any
239	/// other packet.
240	fn fill(&mut self, written: Written, pause: bool) -> Option<Option<moq_net::Timestamp>> {
241		// The duration counts samples at the codec's rate, which the timestamp's scale may not share.
242		let end = written
243			.duration
244			.zip(written.timestamp.scale())
245			.and_then(|(duration, scale)| written.timestamp.checked_add(duration.convert(scale).ok()?).ok());
246		let full = self.join.fill(written.timestamp, end.unwrap_or(written.timestamp));
247		let silenced = pause && self.speaking;
248		self.speaking = !pause;
249		if full.is_none() && !silenced {
250			return None;
251		}
252		self.reset();
253		// A full group ends past its furthest frame, which a rewound frame's own end can fall below,
254		// so a group closed for silence before it is full declares no end.
255		Some(end.and(full))
256	}
257
258	/// Whether a voiced packet at `pts` resumes speech a whole span past the start of the open group
259	/// of DTX packets, so the caller closes that group before writing it: a live join that skips the
260	/// stale group would otherwise skip the resumed audio with it. A packet reordered before the
261	/// group's start is left to the producer to place.
262	fn resumes(&mut self, pause: bool, pts: moq_net::Timestamp) -> bool {
263		let resumes = !pause && !self.speaking && self.join.gaps(pts);
264		if resumes {
265			self.reset();
266		}
267		resumes
268	}
269
270	/// Forget the open group, which closed some other way.
271	fn reset(&mut self) {
272		self.join.reset();
273	}
274}
275
276/// What an audio codec importer wrote: the frame's timestamp, which may come from the clock, and
277/// how long it plays, when its codec or header says.
278pub(crate) struct Written {
279	pub timestamp: moq_net::Timestamp,
280	pub duration: Option<moq_net::Timestamp>,
281}
282
283impl Track {
284	/// Create an importer that publishes a single audio codec onto a reserved track.
285	///
286	/// The caller reserves the track (by name) with
287	/// [`BroadcastProducer::reserve_track`](moq_net::broadcast::Producer::reserve_track); the
288	/// importer accepts it here, at the microsecond timescale or a CMAF init's own. The rendition is
289	/// published from the init bytes, since audio has no in-band config to wait for.
290	pub fn audio<E: CatalogExt>(
291		request: moq_net::track::Request,
292		reserved: crate::catalog::Reserved<E>,
293		init: AudioInit,
294	) -> Result<Self> {
295		let track = request.accept(track_info(&reserved, hang::catalog::PRIORITY.audio, &init.container)?);
296		let data = init.data.as_ref();
297		let kind = match init.format {
298			AudioFormat::Aac => {
299				let config = with_init(&init, crate::codec::aac::config(data)?);
300				TrackKind::Aac(crate::codec::aac::Import::new(track, reserved, config)?)
301			}
302			AudioFormat::Opus => {
303				let config = with_init(&init, crate::codec::opus::config(data)?);
304				TrackKind::Opus(crate::codec::opus::Import::new(track, reserved, config)?)
305			}
306			AudioFormat::Flac => {
307				// `data` is a FLAC header: the `fLaC` marker plus the STREAMINFO block.
308				let config = with_init(&init, crate::codec::flac::config(data)?);
309				TrackKind::Flac(crate::codec::flac::Import::new(track, reserved, config)?)
310			}
311			AudioFormat::Mp3 => {
312				let config = with_init(&init, crate::codec::mp3::config(data)?);
313				TrackKind::Mp3(crate::codec::mp3::Import::new(track, reserved, config)?)
314			}
315		};
316
317		Ok(Self::from_kind(kind))
318	}
319
320	/// Create an importer that publishes a single video codec onto a reserved track.
321	///
322	/// The caller reserves the track as in [`audio`](Self::audio). A video format resolves its
323	/// rendition in band, publishing up front when [`VideoInit::hint`] already carries enough
324	/// (see [`VideoHint`]).
325	pub fn video<E: CatalogExt>(
326		request: moq_net::track::Request,
327		reserved: crate::catalog::Reserved<E>,
328		init: VideoInit,
329	) -> Result<Self> {
330		use hang::catalog::VideoCodec;
331
332		let track = request.accept(track_info(&reserved, init.priority, &init.hint.container)?);
333		let data = init.data.as_ref();
334		let kind = match init.format {
335			VideoFormat::Avc1 => {
336				let (length_size, import) = build_h264_avc1(track, reserved, data, video_hint(&init, None))?;
337				TrackKind::Avc1 { length_size, import }
338			}
339			VideoFormat::H264 => {
340				let (split, import) = build_h264_avc3(track, reserved, data, video_hint(&init, None))?;
341				TrackKind::H264 { split, import }
342			}
343			VideoFormat::Hvc1 => {
344				let (length_size, import) = build_h265_hvc1(track, reserved, data, video_hint(&init, None))?;
345				TrackKind::Hvc1 { length_size, import }
346			}
347			VideoFormat::H265 => {
348				let (split, import) = build_h265(track, reserved, data, video_hint(&init, None))?;
349				TrackKind::H265 { split, import }
350			}
351			VideoFormat::Av01 => {
352				let (split, import) = build_av1(track, reserved, data, video_hint(&init, None))?;
353				TrackKind::Av01 { split, import }
354			}
355			VideoFormat::Vp8 => {
356				let mut import =
357					crate::codec::vp8::Import::new(track, reserved, video_hint(&init, Some(VideoCodec::VP8)))?;
358				import.initialize(data)?;
359				TrackKind::Vp8(import)
360			}
361			VideoFormat::Vp9 => {
362				let mut import = crate::codec::vp9::Import::new(track, reserved, video_hint(&init, None))?;
363				import.initialize(data)?;
364				TrackKind::Vp9(import)
365			}
366		};
367
368		Ok(Self::from_kind(kind))
369	}
370
371	/// Wrap a built codec importer, which is also how the `From` impls lift one in.
372	fn from_kind(kind: TrackKind) -> Self {
373		Self {
374			kind,
375			audio: Grouping::default(),
376		}
377	}
378
379	/// Decode one whole frame.
380	pub fn decode<B: moq_net::IntoBytes>(&mut self, frame: B, pts: Option<moq_net::Timestamp>) -> Result<()> {
381		match self.kind {
382			TrackKind::H264 {
383				ref mut split,
384				ref mut import,
385			} => {
386				// One whole access unit per call, so flush to emit it rather than
387				// waiting for the next start code.
388				let mut frames = split.decode(frame.as_ref(), pts)?;
389				frames.extend(split.flush(pts)?);
390				import.decode(frames)?;
391			}
392			TrackKind::Avc1 {
393				length_size,
394				ref mut import,
395			} => {
396				let pts = pts.ok_or(crate::codec::h264::Error::MissingTimestamp)?;
397				let frame = crate::codec::h264::avc1_frame(frame, length_size, pts)?;
398				import.decode([frame])?;
399			}
400			TrackKind::H265 {
401				ref mut split,
402				ref mut import,
403			} => {
404				let mut frames = split.decode(frame.as_ref(), pts)?;
405				frames.extend(split.flush(pts)?);
406				import.decode(frames)?;
407			}
408			TrackKind::Hvc1 {
409				length_size,
410				ref mut import,
411			} => {
412				let pts = pts.ok_or(crate::codec::h265::Error::MissingTimestamp)?;
413				let frame = crate::codec::h265::hvc1_frame(frame, length_size, pts)?;
414				import.decode([frame])?;
415			}
416			TrackKind::Av01 {
417				ref mut split,
418				ref mut import,
419			} => {
420				let mut frames = split.decode(frame.as_ref(), pts)?;
421				frames.extend(split.flush(pts)?);
422				import.decode(frames)?;
423			}
424			TrackKind::Vp8(ref mut import) => import.decode(frame, pts)?,
425			TrackKind::Vp9(ref mut import) => import.decode(frame, pts)?,
426			// Audio has no boundary of its own: every frame is independently decodable, so the
427			// group runs until it holds its span.
428			TrackKind::Aac(ref mut import) => {
429				let written = import.write(frame.into_bytes(), pts)?;
430				if let Some(end) = self.audio.fill(written, false) {
431					import.close(end)?;
432				}
433			}
434			TrackKind::Opus(ref mut import) => {
435				let pause = frame.as_ref().len() <= 2;
436				// Resolved once, so a packet stamped from the clock is checked where it is written.
437				let pts = import.timestamp(pts)?;
438				if self.audio.resumes(pause, pts) {
439					import.close(None)?;
440				}
441				let written = import.write(frame.into_bytes(), Some(pts))?;
442				if let Some(end) = self.audio.fill(written, pause) {
443					import.close(end)?;
444				}
445			}
446			TrackKind::Mp3(ref mut import) => {
447				let written = import.write(frame.into_bytes(), pts)?;
448				if let Some(end) = self.audio.fill(written, false) {
449					import.close(end)?;
450				}
451			}
452			TrackKind::Flac(ref mut import) => {
453				let written = import.write(frame.into_bytes(), pts)?;
454				if let Some(end) = self.audio.fill(written, false) {
455					import.close(end)?;
456				}
457			}
458		}
459
460		Ok(())
461	}
462
463	/// Finish the importer, flushing any buffered data, and return the [`Finished`] track, which
464	/// keeps it and its catalog rendition published.
465	///
466	/// A finish that fails ends the track with the cause instead, so it can't be retried.
467	pub fn finish(mut self) -> Result<Finished> {
468		// Each decode flushed its whole frame, so a splitter holds at most a picture its init
469		// carried.
470		let flushed = (|| match &mut self.kind {
471			TrackKind::H264 { split, import } => import.decode(split.flush(None)?),
472			TrackKind::H265 { split, import } => import.decode(split.flush(None)?),
473			TrackKind::Av01 { split, import } => import.decode(split.flush(None)?),
474			_ => Ok(()),
475		})();
476		if let Err(err) = flushed {
477			self.abort(err.reason());
478			return Err(err);
479		}
480		let inner = match self.kind {
481			TrackKind::H264 { import, .. } | TrackKind::Avc1 { import, .. } => FinishedKind::Video(import.finish()?),
482			TrackKind::H265 { import, .. } | TrackKind::Hvc1 { import, .. } => FinishedKind::Video(import.finish()?),
483			TrackKind::Av01 { import, .. } => FinishedKind::Video(import.finish()?),
484			TrackKind::Vp8(import) => FinishedKind::Video(import.finish()?),
485			TrackKind::Vp9(import) => FinishedKind::Video(import.finish()?),
486			TrackKind::Aac(import) => FinishedKind::Audio(import.finish()?),
487			TrackKind::Opus(import) => FinishedKind::Audio(import.finish()?),
488			TrackKind::Mp3(import) => FinishedKind::Audio(import.finish()?),
489			TrackKind::Flac(import) => FinishedKind::Audio(import.finish()?),
490		};
491		Ok(Finished { inner })
492	}
493
494	/// Abort the track with `err` instead of finishing it cleanly, so subscribers
495	/// see the real cause rather than [`moq_net::Error::Dropped`]. Consumes the importer.
496	pub fn abort(self, err: moq_net::Error) {
497		import!(self.kind, import => import.abort(err))
498	}
499
500	/// Cut the current group at `end` without finishing the track.
501	///
502	/// Audio closes its own groups once they hold their span; this closes one early, and the next
503	/// span starts from the frame after.
504	pub fn cut(&mut self, end: Option<moq_net::Timestamp>) -> Result<()> {
505		// A rejected end leaves the group open, still measured from its start.
506		import!(&mut self.kind, import => import.cut(end))?;
507		self.audio.reset();
508		Ok(())
509	}
510
511	/// Mark a timeline break, clearing partial frames and restarting handoff measurement.
512	///
513	/// Publishes a marker without lowering advertised values; resumed timestamps must continue forward.
514	pub fn discontinuity(&mut self) -> Result<()> {
515		self.audio.reset();
516		self.reset_split();
517		import!(&mut self.kind, import => import.discontinuity())
518	}
519
520	/// Advertise whether this video rendition is being produced, as the catalog's
521	/// [`enabled`](hang::catalog::VideoConfig::enabled).
522	///
523	/// Disable it when the sender stops for lack of bandwidth (a
524	/// [`rate::Target::Disabled`](crate::rate::Target::Disabled)) and mark the
525	/// [`discontinuity`](Self::discontinuity), so viewers select a lower rendition instead
526	/// of waiting for frames. Enable it again with the keyframe that resumes it. Audio has
527	/// no lower rendition to fall back to, so an audio track refuses with
528	/// [`Error::WrongKind`](crate::Error::WrongKind).
529	pub fn set_enabled(&mut self, enabled: bool) -> Result<()> {
530		match &mut self.kind {
531			TrackKind::H264 { import, .. } | TrackKind::Avc1 { import, .. } => import.set_enabled(enabled)?,
532			TrackKind::H265 { import, .. } | TrackKind::Hvc1 { import, .. } => import.set_enabled(enabled)?,
533			TrackKind::Av01 { import, .. } => import.set_enabled(enabled)?,
534			TrackKind::Vp8(import) => import.set_enabled(enabled)?,
535			TrackKind::Vp9(import) => import.set_enabled(enabled)?,
536			TrackKind::Aac(_) => return Err(not_video(AudioFormat::Aac)),
537			TrackKind::Opus(_) => return Err(not_video(AudioFormat::Opus)),
538			TrackKind::Mp3(_) => return Err(not_video(AudioFormat::Mp3)),
539			TrackKind::Flac(_) => return Err(not_video(AudioFormat::Flac)),
540		}
541		Ok(())
542	}
543
544	/// Drop the partial access unit of a format split from a byte stream.
545	fn reset_split(&mut self) {
546		match &mut self.kind {
547			TrackKind::H264 { split, .. } => split.reset(),
548			TrackKind::H265 { split, .. } => split.reset(),
549			TrackKind::Av01 { split, .. } => split.reset(),
550			TrackKind::Avc1 { .. }
551			| TrackKind::Hvc1 { .. }
552			| TrackKind::Vp8(_)
553			| TrackKind::Vp9(_)
554			| TrackKind::Aac(_)
555			| TrackKind::Opus(_)
556			| TrackKind::Mp3(_)
557			| TrackKind::Flac(_) => {}
558		}
559	}
560
561	/// A watch-only handle to the track's subscriber demand.
562	pub fn demand(&self) -> moq_net::track::Demand {
563		import!(&self.kind, import => import.demand())
564	}
565	/// The name of the track this importer publishes.
566	pub fn name(&self) -> String {
567		self.demand().name().to_string()
568	}
569}
570
571// Lift an already-built opus importer into a `Track` so callers that build their
572// config out-of-band (e.g. moq-gst, which constructs `opus::Config` from gstreamer
573// caps instead of an OpusHead buffer) can keep using `.into()`.
574impl From<crate::codec::opus::Import> for Track {
575	fn from(opus: crate::codec::opus::Import) -> Self {
576		Self::from_kind(TrackKind::Opus(opus))
577	}
578}
579
580impl From<crate::codec::aac::Import> for Track {
581	fn from(aac: crate::codec::aac::Import) -> Self {
582		Self::from_kind(TrackKind::Aac(aac))
583	}
584}
585
586// Lift an already-built mp3 importer into a `Track` so callers that build their
587// config out-of-band (e.g. moq-gst, which reads rate/channels from gstreamer caps
588// rather than parsing a frame header) can keep using `.into()`.
589impl From<crate::codec::mp3::Import> for Track {
590	fn from(mp3: crate::codec::mp3::Import) -> Self {
591		Self::from_kind(TrackKind::Mp3(mp3))
592	}
593}
594
595enum TrackStreamKind {
596	/// H.264 Annex B with inline SPS/PPS, published as avc3. The split owns
597	/// byte parsing; the import publishes.
598	H264 {
599		split: crate::codec::h264::Split,
600		import: crate::codec::h264::Import,
601	},
602	H265 {
603		split: crate::codec::h265::Split,
604		import: crate::codec::h265::Import,
605	},
606	Av01 {
607		split: crate::codec::av1::Split,
608		import: crate::codec::av1::Import,
609	},
610}
611
612/// Forward a call to the splitter and importer a [`TrackStream`] holds.
613macro_rules! stream {
614	($kind:expr, $split:pat, $import:pat => $body:expr) => {
615		match $kind {
616			TrackStreamKind::H264 {
617				split: $split,
618				import: $import,
619			} => $body,
620			TrackStreamKind::H265 {
621				split: $split,
622				import: $import,
623			} => $body,
624			TrackStreamKind::Av01 {
625				split: $split,
626				import: $import,
627			} => $body,
628		}
629	};
630}
631
632/// A single-codec importer for a raw byte stream with unknown frame boundaries.
633///
634/// Use this when the caller does not know the frame boundaries (piped Annex-B
635/// H.264, an fMP4 reader, …); the importer infers them.
636pub struct TrackStream {
637	kind: TrackStreamKind,
638	gate: Gate,
639}
640
641/// Which of the access units a [`TrackStream`] splits it publishes.
642///
643/// The stream's caller cannot see frame boundaries, so the importer, not the caller, drops a
644/// disabled rendition's access units and finds the keyframe that resumes it.
645#[derive(Default)]
646struct Gate {
647	state: GateState,
648	/// Whether an access unit went out, so a disable has a timeline to break.
649	published: bool,
650}
651
652#[derive(Clone, Copy, Default, PartialEq, Eq)]
653enum GateState {
654	#[default]
655	Open,
656	/// Disabled: every access unit is dropped.
657	Closed,
658	/// Enabled again, but still disabled in the catalog until the next keyframe.
659	Resuming,
660}
661
662impl Gate {
663	/// Split `frames` into the access units dropped and those to publish, and report whether
664	/// the first published one resumes the rendition, so the catalog enables it again.
665	fn admit(&mut self, mut frames: Vec<Frame>) -> (Vec<Frame>, Vec<Frame>, bool) {
666		let (kept, resumed) = match self.state {
667			GateState::Open => (0, false),
668			GateState::Closed => (frames.len(), false),
669			GateState::Resuming => match frames.iter().position(|frame| frame.keyframe) {
670				Some(keyframe) => {
671					self.state = GateState::Open;
672					(keyframe, true)
673				}
674				None => (frames.len(), false),
675			},
676		};
677		let publish = frames.split_off(kept);
678		self.published |= !publish.is_empty();
679		(frames, publish, resumed)
680	}
681}
682
683/// Publish split `frames` through a [`TrackStream`]'s gate.
684///
685/// The importer still sees what the gate drops: a stream may carry its config only in band (an
686/// AV1 sequence header), and the keyframe that resumes need not repeat it.
687macro_rules! publish {
688	($gate:expr, $import:expr, $frames:expr) => {{
689		let (dropped, frames, resumed) = $gate.admit($frames);
690		for frame in &dropped {
691			$import.dropped(frame)?;
692		}
693		if resumed {
694			$import.set_enabled(true)?;
695		}
696		$import.decode(frames)
697	}};
698}
699
700impl TrackStream {
701	/// Create an importer that publishes a single codec onto a reserved track.
702	///
703	/// The caller reserves the track with
704	/// [`BroadcastProducer::reserve_track`](moq_net::broadcast::Producer::reserve_track);
705	/// the importer accepts it here, at the microsecond timescale or a CMAF init's own. A [`VideoHint`] carrying a codec publishes the catalog before the
706	/// first frame; any [`VideoInit::data`] seeds the stream (as a call to [`initialize`](Self::initialize)).
707	pub fn video<E: CatalogExt>(
708		request: moq_net::track::Request,
709		reserved: crate::catalog::Reserved<E>,
710		init: VideoInit,
711	) -> Result<Self> {
712		let track = request.accept(track_info(&reserved, init.priority, &init.hint.container)?);
713		let hint = video_hint(&init, None);
714		// Only the self-delimiting codecs can be recovered from a raw byte stream.
715		let kind = match init.format {
716			VideoFormat::H264 => TrackStreamKind::H264 {
717				split: crate::codec::h264::Split::new(),
718				import: crate::codec::h264::Import::new(track, reserved, hint)?,
719			},
720			VideoFormat::H265 => TrackStreamKind::H265 {
721				split: crate::codec::h265::Split::new(),
722				import: crate::codec::h265::Import::new(track, reserved, hint)?,
723			},
724			VideoFormat::Av01 => TrackStreamKind::Av01 {
725				split: crate::codec::av1::Split::new(),
726				import: crate::codec::av1::Import::new(track, reserved, hint)?,
727			},
728			// The rest need length prefixes or an out-of-band config record, so a raw byte stream
729			// carries no boundaries to split on.
730			format => return Err(crate::Error::NotSelfDescribing(format.to_string())),
731		};
732
733		let mut stream = Self {
734			kind,
735			gate: Gate::default(),
736		};
737		if !init.data.is_empty() {
738			stream.initialize(&init.data)?;
739		}
740		Ok(stream)
741	}
742
743	/// Initialize the importer with the given buffer and populate the broadcast.
744	///
745	/// This is not required for self-describing formats like H264.
746	pub fn initialize(&mut self, data: &[u8]) -> Result<()> {
747		match self.kind {
748			TrackStreamKind::H264 {
749				ref mut split,
750				ref mut import,
751			} => {
752				import.initialize(data)?;
753				publish!(self.gate, import, split.initialize(data)?)?;
754			}
755			TrackStreamKind::H265 {
756				ref mut split,
757				ref mut import,
758			} => {
759				import.initialize(data)?;
760				publish!(self.gate, import, split.initialize(data)?)?;
761			}
762			TrackStreamKind::Av01 {
763				ref mut split,
764				ref mut import,
765			} => {
766				import.initialize(data)?;
767				// av1C (leading 0x81) is an out-of-band config record, not an OBU
768				// stream; read for config above and dropped here.
769				let frames = if crate::codec::av1::is_av1c(data) {
770					Vec::new()
771				} else {
772					split.decode(data, None)?
773				};
774				publish!(self.gate, import, frames)?;
775			}
776		}
777
778		Ok(())
779	}
780
781	/// Decode a chunk of the byte stream.
782	pub fn decode(&mut self, data: &[u8]) -> Result<()> {
783		stream!(&mut self.kind, split, import => {
784			publish!(self.gate, import, split.decode(data, None)?)
785		})
786	}
787
788	/// Finish the importer, publishing the access unit still waiting for a following start code,
789	/// and return the [`Finished`] track, which keeps it and its catalog rendition published.
790	///
791	/// A finish that fails ends the track with the cause instead, so it can't be retried.
792	pub fn finish(mut self) -> Result<Finished> {
793		let flushed = (|| stream!(&mut self.kind, split, import => publish!(self.gate, import, split.flush(None)?)))();
794		if let Err(err) = flushed {
795			self.abort(err.reason());
796			return Err(err);
797		}
798		let inner = stream!(self.kind, _, import => FinishedKind::Video(import.finish()?));
799		Ok(Finished { inner })
800	}
801
802	/// Stop or resume publishing this rendition, advertised as the catalog's
803	/// [`enabled`](hang::catalog::VideoConfig::enabled).
804	///
805	/// Disable it when its sender cannot be funded (a
806	/// [`rate::Target::Disabled`](crate::rate::Target::Disabled)). Once anything was published,
807	/// that marks a [`discontinuity`](crate::container::Producer::discontinuity). Every access
808	/// unit decoded until it is enabled again is dropped, so the caller may keep writing the
809	/// stream, though a dropped keyframe still updates the codec config. Enabled again, it
810	/// drops access units until the next keyframe and advertises itself enabled with that
811	/// keyframe.
812	pub fn set_enabled(&mut self, enabled: bool) -> Result<()> {
813		match (enabled, self.gate.state) {
814			(false, GateState::Open) => {
815				let published = self.gate.published;
816				// The splitter keeps its partial NAL, since the next chunk may continue it. The
817				// access unit in flight completes behind the gate, which drops it unless it is
818				// a keyframe that resumes the rendition.
819				stream!(&mut self.kind, _, import => {
820					import.set_enabled(false)?;
821					if published {
822						import.discontinuity()?;
823					}
824				});
825				self.gate.state = GateState::Closed;
826			}
827			(false, GateState::Resuming) => self.gate.state = GateState::Closed,
828			(true, GateState::Closed) => self.gate.state = GateState::Resuming,
829			(false, GateState::Closed) | (true, GateState::Open | GateState::Resuming) => {}
830		}
831		Ok(())
832	}
833
834	/// Abort the track with `err` instead of finishing it cleanly, so subscribers
835	/// see the real cause rather than [`moq_net::Error::Dropped`]. Consumes the importer.
836	pub fn abort(self, err: moq_net::Error) {
837		stream!(self.kind, _, import => import.abort(err))
838	}
839
840	/// Cut the current group at `end` without finishing the track.
841	pub fn cut(&mut self, end: Option<moq_net::Timestamp>) -> Result<()> {
842		stream!(&mut self.kind, _, import => import.cut(end))
843	}
844
845	/// A watch-only handle to the track's subscriber demand.
846	pub fn demand(&self) -> moq_net::track::Demand {
847		stream!(&self.kind, _, import => import.demand())
848	}
849	/// The name of the track this importer publishes.
850	pub fn name(&self) -> String {
851		self.demand().name().to_string()
852	}
853}
854
855/// A [`Track`] or [`TrackStream`] that finished: every frame is published, and the track can
856/// still be aborted, but not written to.
857///
858/// Dropping it releases the track and its catalog rendition, as dropping the importer does.
859///
860/// ```compile_fail,E0599
861/// # fn cannot_decode(mut track: moq_mux::import::track::Finished) {
862/// track.decode(b"", None).unwrap();
863/// # }
864/// ```
865#[must_use = "dropping it releases the track and its catalog rendition"]
866pub struct Finished {
867	inner: FinishedKind,
868}
869
870/// The finished track a [`Finished`] holds, by the catalog section its rendition is in.
871enum FinishedKind {
872	Video(crate::container::Finished<crate::catalog::hang::Wire, hang::catalog::VideoConfig>),
873	Audio(crate::container::Finished<crate::catalog::hang::Wire, hang::catalog::AudioConfig>),
874}
875
876impl Finished {
877	/// The name of the track this importer published.
878	pub fn name(&self) -> &str {
879		match &self.inner {
880			FinishedKind::Video(track) => track.name(),
881			FinishedKind::Audio(track) => track.name(),
882		}
883	}
884
885	/// Abort the track with `err`; see [`moq_net::track::Finished::abort`]. Readers still draining get the clean end
886	/// instead once every group below the end finished.
887	pub fn abort(self, err: moq_net::Error) {
888		match self.inner {
889			FinishedKind::Video(track) => track.abort(err),
890			FinishedKind::Audio(track) => track.abort(err),
891		}
892	}
893}
894
895#[cfg(test)]
896mod tests {
897	use std::time::Duration;
898
899	use super::*;
900	use moq_net::Timestamp;
901
902	fn opus_head() -> Vec<u8> {
903		let mut head = Vec::with_capacity(19);
904		head.extend_from_slice(b"OpusHead");
905		head.push(1);
906		head.push(2);
907		head.extend_from_slice(&0u16.to_le_bytes());
908		head.extend_from_slice(&48000u32.to_le_bytes());
909		head.extend_from_slice(&0u16.to_le_bytes());
910		head.push(0);
911		head
912	}
913
914	fn h264_init() -> Vec<u8> {
915		let mut init = Vec::new();
916		init.extend_from_slice(&[0x00, 0x00, 0x00, 0x01]);
917		init.extend_from_slice(&[
918			0x67, 0x64, 0x00, 0x1f, 0xac, 0x24, 0x84, 0x01, 0x40, 0x16, 0xec, 0x04, 0x40, 0x00, 0x00, 0x03, 0x00, 0x40,
919			0x00, 0x00, 0x0c, 0x23, 0xc6, 0x0c, 0x92,
920		]);
921		init.extend_from_slice(&[0x00, 0x00, 0x00, 0x01]);
922		init.extend_from_slice(&[0x68, 0xee, 0x32, 0xc8, 0xb0]);
923		init
924	}
925
926	fn new_broadcast() -> (moq_net::broadcast::Producer, crate::catalog::Producer) {
927		let mut broadcast = moq_net::broadcast::Info::new().produce();
928		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
929		(broadcast, catalog)
930	}
931
932	#[tokio::test(start_paused = true)]
933	async fn existing_track_opus_uses_existing_name() {
934		let (broadcast, catalog) = new_broadcast();
935		// The importer accepts the reserved track, setting its (microsecond) timescale.
936		let request = broadcast.reserve_track("requested-audio").unwrap();
937		let mut import = Track::audio(
938			request,
939			catalog.reserve(),
940			AudioInit::new(AudioFormat::Opus, opus_head()),
941		)
942		.unwrap();
943
944		assert_eq!(import.name(), "requested-audio");
945		let snapshot = catalog.snapshot();
946		assert!(snapshot.audio.renditions.contains_key("requested-audio"));
947		assert!(!snapshot.audio.renditions.contains_key("0.opus"));
948
949		// Frame delivery and the accepted timescale are covered by `opus_import_delivers_frames`.
950		import
951			.decode(b"opus payload", Some(Timestamp::from_micros(1_000).unwrap()))
952			.unwrap();
953		let _finished = import.finish().unwrap();
954	}
955
956	/// Dropping an importer retires its rendition. A reader that still holds its track is
957	/// handed to the broadcast's handler as a fresh request; once nobody does, the track ends
958	/// cleanly and a later lookup asks for it afresh.
959	#[tokio::test(start_paused = true)]
960	async fn a_dropped_importer_hands_its_reader_to_the_next_request() {
961		let (broadcast, catalog) = new_broadcast();
962		let mut requests = broadcast.requests();
963		let consumer = broadcast.consume();
964		let mut import = Track::audio(
965			broadcast.reserve_track("audio").unwrap(),
966			catalog.reserve(),
967			AudioInit::new(AudioFormat::Opus, opus_head()),
968		)
969		.unwrap();
970		import
971			.decode(b"opus payload", Some(Timestamp::from_micros(1_000).unwrap()))
972			.unwrap();
973
974		let track = consumer.track("audio").unwrap().subscribe(None).await.unwrap();
975		drop(import);
976		assert!(!catalog.snapshot().audio.renditions.contains_key("audio"));
977		let again = requests.requested_track().await.unwrap();
978		assert_eq!(again.name(), "audio");
979
980		let import = Track::audio(again, catalog.reserve(), AudioInit::new(AudioFormat::Opus, opus_head())).unwrap();
981		drop(track);
982		let demand = import.demand();
983		drop(import);
984		assert!(matches!(demand.closed().await, Ok(())));
985		let _later = consumer.track("audio").unwrap().subscribe(None);
986		assert_eq!(requests.requested_track().await.unwrap().name(), "audio");
987	}
988
989	#[tokio::test(start_paused = true)]
990	async fn flac_cut_per_frame_rewind_names_timestamp_and_edge() {
991		let (broadcast, catalog) = new_broadcast();
992		let config = crate::codec::flac::Config {
993			min_block_size: 4608,
994			max_block_size: 4608,
995			min_frame_size: 0,
996			max_frame_size: 0,
997			sample_rate: 48_000,
998			channel_count: 2,
999			bits_per_sample: 24,
1000			total_samples: 0,
1001			md5: [0; 16],
1002		};
1003		let mut import = Track::audio(
1004			broadcast.reserve_track("audio").unwrap(),
1005			catalog.reserve(),
1006			AudioInit::new(AudioFormat::Flac, config.description()),
1007		)
1008		.unwrap();
1009
1010		let floor = 1_790_802_494_898_432;
1011		for timestamp in [floor - 10_000, floor] {
1012			import
1013				.decode(b"flac frame", Some(Timestamp::from_micros(timestamp).unwrap()))
1014				.unwrap();
1015			import.cut(None).unwrap();
1016		}
1017		let err = import
1018			.decode(b"flac frame", Some(Timestamp::from_micros(floor - 1).unwrap()))
1019			.unwrap_err();
1020		assert!(matches!(err, crate::Error::TimestampRewind(_)), "{err:?}");
1021		let message = err.to_string();
1022		assert!(message.contains("1790802494898431 µs"), "{message}");
1023		assert!(message.contains("1790802494898432 µs"), "{message}");
1024	}
1025
1026	#[tokio::test(start_paused = true)]
1027	async fn aac_import_attaches_audio_specific_config() {
1028		let (broadcast, catalog) = new_broadcast();
1029		let config = crate::codec::aac::Config {
1030			profile: 2,
1031			sample_rate: 44_100,
1032			channel_count: 2,
1033		};
1034		let init = config.encode().unwrap();
1035		let request = broadcast.reserve_track("audio").unwrap();
1036
1037		let import = Track::audio(
1038			request,
1039			catalog.reserve(),
1040			AudioInit {
1041				label: Some("English".to_string()),
1042				..AudioInit::new(AudioFormat::Aac, init.clone())
1043			},
1044		)
1045		.unwrap();
1046
1047		assert_eq!(import.name(), "audio");
1048		let snapshot = catalog.snapshot();
1049		let audio = snapshot.audio.renditions.get("audio").unwrap();
1050		assert_eq!(audio.codec.to_string(), "mp4a.40.2");
1051		assert_eq!(audio.sample_rate, config.sample_rate);
1052		assert_eq!(audio.channel_count, config.channel_count);
1053		assert_eq!(audio.description.as_deref(), Some(init.as_ref()));
1054		assert_eq!(audio.label.as_deref(), Some("English"));
1055	}
1056
1057	/// The audio counterpart to [`VideoInit::hint`]'s container: the caller's selection has to reach
1058	/// the published rendition, since the codec parser resolves everything else from the init bytes.
1059	#[tokio::test(start_paused = true)]
1060	async fn an_audio_init_publishes_its_container() {
1061		let (broadcast, catalog) = new_broadcast();
1062		let request = broadcast.reserve_track("audio").unwrap();
1063
1064		let _import = Track::audio(
1065			request,
1066			catalog.reserve(),
1067			AudioInit {
1068				container: hang::catalog::Container::Loc,
1069				..AudioInit::new(AudioFormat::Opus, opus_head())
1070			},
1071		)
1072		.unwrap();
1073
1074		let snapshot = catalog.snapshot();
1075		let audio = snapshot.audio.renditions.get("audio").unwrap();
1076		assert_eq!(audio.container, hang::catalog::Container::Loc);
1077	}
1078
1079	#[tokio::test(start_paused = true)]
1080	async fn unique_track_opus_attaches_catalog_and_retires_on_drop() {
1081		let (broadcast, catalog) = new_broadcast();
1082
1083		// A freshly reserved track attaches its catalog rendition on init.
1084		let name = broadcast.unique_name(".opus");
1085		let request = broadcast.reserve_track(name).unwrap();
1086		let mut import = Track::audio(
1087			request,
1088			catalog.reserve(),
1089			AudioInit::new(AudioFormat::Opus, opus_head()),
1090		)
1091		.unwrap();
1092
1093		assert_eq!(import.name(), "0.opus");
1094		assert!(catalog.snapshot().audio.renditions.contains_key("0.opus"));
1095
1096		import
1097			.decode(b"opus payload", Some(Timestamp::from_micros(2_000).unwrap()))
1098			.unwrap();
1099		let finished = import.finish().unwrap();
1100		assert!(catalog.snapshot().audio.renditions.contains_key("0.opus"));
1101
1102		// Dropping the finished importer retires its rendition from the shared catalog.
1103		drop(finished);
1104		assert!(!catalog.snapshot().audio.renditions.contains_key("0.opus"));
1105	}
1106
1107	/// A CMAF rendition counts in its init's ticks, so its frames can carry the earliest
1108	/// presentation time exactly.
1109	#[tokio::test(start_paused = true)]
1110	async fn cmaf_audio_counts_in_the_init_timescale() {
1111		let (broadcast, catalog) = new_broadcast();
1112		let config = crate::codec::opus::config(&opus_head()).unwrap();
1113		let cmaf = crate::container::fmp4::Muxer::audio(&config)
1114			.unwrap()
1115			.init()
1116			.unwrap()
1117			.unwrap();
1118		let mut init = AudioInit::new(AudioFormat::Opus, opus_head());
1119		init.container = hang::catalog::Container::Cmaf { init: cmaf };
1120
1121		// The CMAF writer refuses a track at any other scale.
1122		let request = broadcast.reserve_track("audio").unwrap();
1123		let mut import = Track::audio(request, catalog.reserve(), init).unwrap();
1124		import
1125			.decode(b"opus payload", Some(Timestamp::from_micros(20_000).unwrap()))
1126			.unwrap();
1127		let _finished = import.finish().unwrap();
1128	}
1129
1130	#[tokio::test(start_paused = true)]
1131	async fn opus_import_delivers_frames() {
1132		let (broadcast, catalog) = new_broadcast();
1133		let track = broadcast
1134			.create_track("audio", hang::container::track_info(hang::catalog::PRIORITY.audio))
1135			.unwrap();
1136		let subscriber = track.subscribe(None);
1137
1138		let config = crate::codec::opus::Config::new(48_000, 2);
1139		let mut import = crate::codec::opus::Import::new(track, catalog.reserve(), config.into()).unwrap();
1140		assert!(catalog.snapshot().audio.renditions.contains_key("audio"));
1141
1142		let mut media = crate::container::Consumer::new(
1143			subscriber,
1144			crate::catalog::hang::Wire::legacy(crate::container::Kind::Data),
1145		);
1146
1147		let payload = b"opus payload".to_vec();
1148		import
1149			.decode(&payload, Some(Timestamp::from_micros(1_000).unwrap()))
1150			.unwrap();
1151
1152		let frame = kio::clock::timeout(Duration::from_secs(1), media.read_frame())
1153			.await
1154			.unwrap()
1155			.unwrap()
1156			.unwrap();
1157		assert_eq!(frame.payload, payload);
1158		assert_eq!(frame.timestamp, Timestamp::from_micros(1_000).unwrap());
1159
1160		let _finished = import.finish().unwrap();
1161	}
1162
1163	/// Count the frames in each group of a finished track, in key order.
1164	async fn collect_groups(subscriber: moq_net::track::Subscriber) -> Vec<usize> {
1165		let mut subscriber = subscriber.ordered();
1166		let mut groups = Vec::new();
1167		while let Some(mut group) = subscriber.next_group().await.unwrap() {
1168			let mut count = 0;
1169			while group.next_frame().await.unwrap().is_some() {
1170				count += 1;
1171			}
1172			groups.push(count);
1173		}
1174		groups
1175	}
1176
1177	fn opus_import(
1178		broadcast: &mut moq_net::broadcast::Producer,
1179		catalog: &crate::catalog::Producer,
1180	) -> (crate::codec::opus::Import, moq_net::track::Subscriber) {
1181		let track = broadcast
1182			.create_track("audio", hang::container::track_info(hang::catalog::PRIORITY.audio))
1183			.unwrap();
1184		// Every group is written before anything reads, which the default
1185		// REAL_TIME budget would collapse to the live edge.
1186		let subscriber =
1187			track.subscribe(
1188				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
1189					moq_net::track::Start::Live {
1190						min: Some(Duration::from_secs(30)),
1191						max: Some(Duration::from_secs(30)),
1192					},
1193				)]),
1194			);
1195		let config = crate::codec::opus::Config::new(48_000, 2);
1196		let import = crate::codec::opus::Import::new(track, catalog.reserve(), config.into()).unwrap();
1197		(import, subscriber)
1198	}
1199
1200	/// An Opus packet whose TOC (config 12, code 1) codes two 10 ms frames: 20 ms of audio.
1201	const OPUS_20MS: &[u8] = b"abc";
1202
1203	/// The packet that brings a group to 100 ms closes it, so a caller that never cuts still gets one
1204	/// group (one QUIC stream) per 100 ms rather than one unbounded group.
1205	#[tokio::test(start_paused = true)]
1206	async fn audio_groups_close_at_one_hundred_milliseconds() {
1207		let (mut broadcast, catalog) = new_broadcast();
1208		let (import, subscriber) = opus_import(&mut broadcast, &catalog);
1209		let mut import: Track = import.into();
1210
1211		for index in 0..12 {
1212			import
1213				.decode(OPUS_20MS, Some(Timestamp::from_micros(index * 20_000).unwrap()))
1214				.unwrap();
1215		}
1216		let _finished = import.finish().unwrap();
1217
1218		assert_eq!(collect_groups(subscriber).await, vec![5, 5, 2]);
1219	}
1220
1221	/// An explicit cut still closes a group early, and the next 100 ms is measured from the frame
1222	/// after it.
1223	#[tokio::test(start_paused = true)]
1224	async fn a_cut_closes_an_audio_group_early() {
1225		let (mut broadcast, catalog) = new_broadcast();
1226		let (import, subscriber) = opus_import(&mut broadcast, &catalog);
1227		let mut import: Track = import.into();
1228
1229		for index in 0..10 {
1230			if index == 3 {
1231				import.cut(None).unwrap();
1232			}
1233			import
1234				.decode(OPUS_20MS, Some(Timestamp::from_micros(index * 20_000).unwrap()))
1235				.unwrap();
1236		}
1237		let _finished = import.finish().unwrap();
1238
1239		assert_eq!(collect_groups(subscriber).await, vec![3, 5, 2]);
1240	}
1241
1242	/// The first DTX packet after audio closes its group instead of leaving it open through the
1243	/// silence, an encoder that keeps sending DTX packets still gets 100 ms groups, not one per
1244	/// packet, and speech resuming after the silence starts a group of its own.
1245	#[tokio::test(start_paused = true)]
1246	async fn a_dtx_packet_closes_its_audio_group() {
1247		let (mut broadcast, catalog) = new_broadcast();
1248		let (import, subscriber) = opus_import(&mut broadcast, &catalog);
1249		let mut import: Track = import.into();
1250
1251		// Five voiced packets fill a group, so the first DTX packet opens one and closes it alone.
1252		for index in 0..5 {
1253			import
1254				.decode(OPUS_20MS, Some(Timestamp::from_micros(index * 20_000).unwrap()))
1255				.unwrap();
1256		}
1257		// Header-only 20 ms packets: the first closes its group, the rest fill their own.
1258		for index in 5..10 {
1259			import
1260				.decode(b"a", Some(Timestamp::from_micros(index * 20_000).unwrap()))
1261				.unwrap();
1262		}
1263		for ts in [2_000_000, 2_020_000] {
1264			import
1265				.decode(OPUS_20MS, Some(Timestamp::from_micros(ts).unwrap()))
1266				.unwrap();
1267		}
1268		let _finished = import.finish().unwrap();
1269
1270		// Speech resuming after the silence closes the open DTX group rather than joining it.
1271		assert_eq!(collect_groups(subscriber).await, vec![5, 1, 4, 2]);
1272	}
1273
1274	/// Speech the broadcast clock stamps still starts a group of its own after a DTX silence.
1275	#[tokio::test(start_paused = true)]
1276	async fn clock_stamped_speech_after_dtx_starts_its_own_group() {
1277		let (mut broadcast, catalog) = new_broadcast();
1278		let (import, subscriber) = opus_import(&mut broadcast, &catalog);
1279		let mut import: Track = import.into();
1280
1281		let write = async |import: &mut Track, packet: &[u8]| {
1282			import.decode(packet, None).unwrap();
1283			kio::clock::sleep(Duration::from_millis(20)).await;
1284		};
1285		for _ in 0..5 {
1286			write(&mut import, OPUS_20MS).await;
1287		}
1288		for _ in 0..3 {
1289			write(&mut import, b"a").await;
1290		}
1291		kio::clock::sleep(Duration::from_secs(2)).await;
1292		for _ in 0..2 {
1293			write(&mut import, OPUS_20MS).await;
1294		}
1295		let _finished = import.finish().unwrap();
1296
1297		assert_eq!(collect_groups(subscriber).await, vec![5, 1, 2, 2]);
1298	}
1299
1300	/// A voiced packet reordered behind DTX packets joins their open group as it did before, rather
1301	/// than closing it and then being refused as a rewind.
1302	#[tokio::test(start_paused = true)]
1303	async fn reordered_speech_joins_the_open_dtx_group() {
1304		let (mut broadcast, catalog) = new_broadcast();
1305		let (import, subscriber) = opus_import(&mut broadcast, &catalog);
1306		let mut import: Track = import.into();
1307
1308		for index in 0..5 {
1309			import
1310				.decode(OPUS_20MS, Some(Timestamp::from_micros(index * 20_000).unwrap()))
1311				.unwrap();
1312		}
1313		for ts in [100_000, 140_000] {
1314			import.decode(b"a", Some(Timestamp::from_micros(ts).unwrap())).unwrap();
1315		}
1316		import
1317			.decode(OPUS_20MS, Some(Timestamp::from_micros(120_000).unwrap()))
1318			.unwrap();
1319		let _finished = import.finish().unwrap();
1320
1321		assert_eq!(collect_groups(subscriber).await, vec![5, 1, 2]);
1322	}
1323
1324	/// A group closed on a frame of unknown length declares no end, so the producer doesn't
1325	/// extrapolate one from the gap before it and move the next group's frames past it.
1326	#[tokio::test(start_paused = true)]
1327	async fn an_unknown_length_leaves_the_group_end_open() {
1328		let (mut broadcast, catalog) = new_broadcast();
1329		let (import, subscriber) = opus_import(&mut broadcast, &catalog);
1330		let mut import: Track = import.into();
1331		let mut media = crate::container::Consumer::new(
1332			subscriber,
1333			crate::catalog::hang::Wire::legacy(crate::container::Kind::Data),
1334		);
1335
1336		// A code-3 packet whose count byte is missing says nothing of its length.
1337		let unknown: &[u8] = &[0x03];
1338		let written = [0, 10_000, 150_000, 160_000];
1339		for ts in written {
1340			import
1341				.decode(unknown, Some(Timestamp::from_micros(ts).unwrap()))
1342				.unwrap();
1343		}
1344		let _finished = import.finish().unwrap();
1345
1346		for ts in written {
1347			let frame = kio::clock::timeout(Duration::from_secs(1), media.read_frame())
1348				.await
1349				.unwrap()
1350				.unwrap()
1351				.unwrap();
1352			assert_eq!(frame.timestamp, Timestamp::from_micros(ts).unwrap());
1353		}
1354	}
1355
1356	/// Each audio codec times its frames from its config or header, so its groups close on the
1357	/// frame that brings them to 100 ms.
1358	#[tokio::test(start_paused = true)]
1359	async fn every_audio_codec_groups_by_its_frame_length() {
1360		let aac = crate::codec::aac::Config {
1361			profile: 2,
1362			sample_rate: 48_000,
1363			channel_count: 2,
1364		};
1365		let flac = crate::codec::flac::Config {
1366			min_block_size: 4096,
1367			max_block_size: 4096,
1368			min_frame_size: 0,
1369			max_frame_size: 0,
1370			sample_rate: 48_000,
1371			channel_count: 2,
1372			bits_per_sample: 16,
1373			total_samples: 0,
1374			md5: [0; 16],
1375		};
1376		// MPEG-1 Layer III, 128 kbps, 44.1 kHz.
1377		let mp3 = [0xFF, 0xFB, 0x90, 0x44];
1378		let cases = [
1379			// 1024 samples at 48 kHz never land on 100 ms, so a group takes the frame past it.
1380			(
1381				AudioFormat::Aac,
1382				aac.encode().unwrap().to_vec(),
1383				vec![0x21, 0x10],
1384				21_333,
1385				[5, 5],
1386			),
1387			// 4096-sample blocks, about 85 ms each.
1388			(
1389				AudioFormat::Flac,
1390				flac.description().to_vec(),
1391				vec![0xFF, 0xF8, 0xCA, 0x18, 0x00],
1392				85_333,
1393				[2, 2],
1394			),
1395			// 1152 samples at 44.1 kHz.
1396			(
1397				AudioFormat::Mp3,
1398				mp3.to_vec(),
1399				[&mp3[..], &[0; 8]].concat(),
1400				26_122,
1401				[4, 4],
1402			),
1403		];
1404		for (format, init, frame, step, expected) in cases {
1405			let (broadcast, catalog) = new_broadcast();
1406			let consumer = broadcast.consume();
1407			let request = broadcast.reserve_track("audio").unwrap();
1408			let mut import = Track::audio(request, catalog.reserve(), AudioInit::new(format, init)).unwrap();
1409			let replay = moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
1410				moq_net::track::Start::Live {
1411					min: Some(Duration::from_secs(30)),
1412					max: Some(Duration::from_secs(30)),
1413				},
1414			)]);
1415			let track = consumer.track("audio").unwrap().subscribe(Some(replay)).await.unwrap();
1416			for index in 0..expected.iter().sum::<usize>() as u64 {
1417				import
1418					.decode(frame.clone(), Some(Timestamp::from_micros(index * step).unwrap()))
1419					.unwrap();
1420			}
1421			let _finished = import.finish().unwrap();
1422			assert_eq!(collect_groups(track).await, expected, "{format:?}");
1423		}
1424	}
1425
1426	#[tokio::test(start_paused = true)]
1427	async fn discontinuity_separates_audio_groups() {
1428		let (mut broadcast, catalog) = new_broadcast();
1429		let (import, subscriber) = opus_import(&mut broadcast, &catalog);
1430		let mut import: Track = import.into();
1431		for pts in [0, 20] {
1432			import
1433				.decode(OPUS_20MS, Some(Timestamp::from_micros(pts * 1_000).unwrap()))
1434				.unwrap();
1435		}
1436		import.discontinuity().unwrap();
1437		for pts in [100, 120] {
1438			import
1439				.decode(OPUS_20MS, Some(Timestamp::from_micros(pts * 1_000).unwrap()))
1440				.unwrap();
1441		}
1442		let _finished = import.finish().unwrap();
1443		// The middle group is the established empty-payload discontinuity marker.
1444		assert_eq!(collect_groups(subscriber).await, vec![2, 1, 2]);
1445	}
1446
1447	/// Cutting after every frame is still available: one group (one QUIC stream) per packet.
1448	#[tokio::test(start_paused = true)]
1449	async fn a_caller_can_still_cut_per_frame() {
1450		let (mut broadcast, catalog) = new_broadcast();
1451		let (import, subscriber) = opus_import(&mut broadcast, &catalog);
1452		let mut import: Track = import.into();
1453
1454		for ts in [0, 20_000, 40_000] {
1455			import
1456				.decode(OPUS_20MS, Some(Timestamp::from_micros(ts).unwrap()))
1457				.unwrap();
1458			import.cut(None).unwrap();
1459		}
1460		let _finished = import.finish().unwrap();
1461
1462		assert_eq!(collect_groups(subscriber).await, vec![1, 1, 1]);
1463	}
1464
1465	/// Driven directly (not through the facade), the codec importer accumulates audio frames into the
1466	/// current group until an explicit `cut`, marking only the first frame of each group a
1467	/// keyframe. This is how a caller drives its own audio grouping.
1468	#[tokio::test(start_paused = true)]
1469	async fn codec_import_accumulates_until_boundary() {
1470		let (mut broadcast, catalog) = new_broadcast();
1471		let (mut import, subscriber) = opus_import(&mut broadcast, &catalog);
1472
1473		import.decode(b"a", Some(Timestamp::from_micros(0).unwrap())).unwrap();
1474		import
1475			.decode(b"b", Some(Timestamp::from_micros(10_000).unwrap()))
1476			.unwrap();
1477		import.cut(None).unwrap();
1478		import
1479			.decode(b"c", Some(Timestamp::from_micros(20_000).unwrap()))
1480			.unwrap();
1481		let _finished = import.finish().unwrap();
1482
1483		assert_eq!(collect_groups(subscriber).await, vec![2, 1]);
1484	}
1485
1486	/// A caller-provided `cut(Some(end))` boundary reaches the bitrate estimator: it finalizes the
1487	/// pending window at `end` so the caller's segment cut is measured. Without it the last window
1488	/// stays open, the 1s averaging window never closes, and no bitrate is detected. Regression for
1489	/// the metrics hole in caller-driven grouping (a bare `cut(None)` stays neutral by design).
1490	#[tokio::test(start_paused = true)]
1491	async fn explicit_cut_finalizes_bitrate_at_boundary() {
1492		let (mut broadcast, catalog) = new_broadcast();
1493		let (mut import, _subscriber) = opus_import(&mut broadcast, &catalog);
1494
1495		// A full second of audio, then an explicit boundary at 1s. The estimator averages bitrate
1496		// over a 1s window, so it's the boundary that closes the final packet's window and carries
1497		// the accumulated duration to the reporting threshold.
1498		let payload = vec![0u8; 4_000];
1499		for us in [0u64, 250_000, 500_000, 750_000] {
1500			import
1501				.decode(&payload, Some(Timestamp::from_micros(us).unwrap()))
1502				.unwrap();
1503		}
1504		import.cut(Some(Timestamp::from_micros(1_000_000).unwrap())).unwrap();
1505		let _finished = import.finish().unwrap();
1506
1507		let audio = catalog.snapshot().audio.renditions.get("audio").cloned().unwrap();
1508		assert!(
1509			audio.bitrate.is_some(),
1510			"an explicit cut boundary should finalize the bitrate window"
1511		);
1512	}
1513
1514	#[tokio::test(start_paused = true)]
1515	async fn existing_track_h264_uses_existing_name_in_catalog() {
1516		let (broadcast, catalog) = new_broadcast();
1517		let request = broadcast.reserve_track("camera").unwrap();
1518
1519		let import = Track::video(
1520			request,
1521			catalog.reserve(),
1522			VideoInit::new(VideoFormat::H264, h264_init()),
1523		)
1524		.unwrap();
1525
1526		assert_eq!(import.name(), "camera");
1527		let snapshot = catalog.snapshot();
1528		let video = snapshot.video.renditions.get("camera").unwrap();
1529		assert_eq!(video.coded_width, Some(1280));
1530		assert_eq!(video.coded_height, Some(720));
1531		assert!(!snapshot.video.renditions.contains_key("0.avc3"));
1532	}
1533
1534	/// A changed key frame just updates the rendition in place; there are no fixed
1535	/// tracks to reject a reconfiguration, so the second key frame succeeds.
1536	#[tokio::test(start_paused = true)]
1537	async fn reconfiguration_updates_in_place() {
1538		let (broadcast, catalog) = new_broadcast();
1539		let request = broadcast.reserve_track("video").unwrap();
1540		let mut import =
1541			Track::video(request, catalog.reserve(), VideoInit::new(VideoFormat::Vp8, Vec::new())).unwrap();
1542
1543		import
1544			.decode(
1545				&[0x10, 0x00, 0x00, 0x9d, 0x01, 0x2a, 0x40, 0x01, 0xf0, 0x00],
1546				Some(Timestamp::from_micros(0).unwrap()),
1547			)
1548			.unwrap();
1549
1550		import
1551			.decode(
1552				&[0x10, 0x00, 0x00, 0x9d, 0x01, 0x2a, 0x80, 0x02, 0xe0, 0x01],
1553				Some(Timestamp::from_micros(33_000).unwrap()),
1554			)
1555			.unwrap();
1556	}
1557
1558	/// An audio format publishes its catalog immediately from the init bytes.
1559	#[tokio::test(start_paused = true)]
1560	async fn audio_publishes_from_init() {
1561		let (broadcast, catalog) = new_broadcast();
1562		let request = broadcast.reserve_track("audio").unwrap();
1563		let _import = Track::audio(
1564			request,
1565			catalog.reserve(),
1566			AudioInit::new(AudioFormat::Opus, opus_head()),
1567		)
1568		.unwrap();
1569
1570		let audio = catalog.snapshot().audio.renditions.get("audio").cloned().unwrap();
1571		assert_eq!(audio.codec.to_string(), "opus");
1572		assert_eq!(audio.sample_rate, 48_000);
1573		assert_eq!(audio.channel_count, 2);
1574	}
1575
1576	/// Each constructor stamps its own kind's priority, so an audio track never goes
1577	/// out at the video priority and queues behind a video backlog.
1578	#[tokio::test(start_paused = true)]
1579	async fn each_kind_ranks_as_itself() {
1580		use hang::catalog::PRIORITY;
1581
1582		let (broadcast, catalog) = new_broadcast();
1583		let consumer = broadcast.consume();
1584
1585		let request = broadcast.reserve_track("audio").unwrap();
1586		let _audio = Track::audio(
1587			request,
1588			catalog.reserve(),
1589			AudioInit::new(AudioFormat::Opus, opus_head()),
1590		)
1591		.unwrap();
1592
1593		let request = broadcast.reserve_track("video").unwrap();
1594		let _video = Track::video(request, catalog.reserve(), VideoInit::new(VideoFormat::Vp8, Vec::new())).unwrap();
1595
1596		let audio = consumer.track("audio").unwrap().info().await.unwrap();
1597		assert_eq!(audio.priority, PRIORITY.audio);
1598
1599		let video = consumer.track("video").unwrap().info().await.unwrap();
1600		assert_eq!(video.priority, PRIORITY.video);
1601
1602		// A higher rung asks for its own priority, below the rendition it sits above.
1603		let request = broadcast.reserve_track("top").unwrap();
1604		let _top = Track::video(
1605			request,
1606			catalog.reserve(),
1607			VideoInit {
1608				priority: PRIORITY.video - 1,
1609				..VideoInit::new(VideoFormat::Vp8, Vec::new())
1610			},
1611		)
1612		.unwrap();
1613		let top = consumer.track("top").unwrap().info().await.unwrap();
1614		assert_eq!(top.priority, PRIORITY.video - 1);
1615	}
1616
1617	/// Disabling a video rendition flips its catalog `enabled` and keeps the rest of it;
1618	/// audio has no lower rendition to fall back to, so it refuses.
1619	#[tokio::test(start_paused = true)]
1620	async fn video_disables_and_audio_refuses() {
1621		let (broadcast, catalog) = new_broadcast();
1622		let request = broadcast.reserve_track("video").unwrap();
1623		let mut video = Track::video(request, catalog.reserve(), VideoInit::new(VideoFormat::Vp8, Vec::new())).unwrap();
1624
1625		video.set_enabled(false).unwrap();
1626		let rendition = catalog.snapshot().video.renditions.get("video").cloned().unwrap();
1627		assert!(!rendition.enabled);
1628		assert_eq!(rendition.codec.to_string(), "vp8");
1629
1630		video.set_enabled(true).unwrap();
1631		assert!(catalog.snapshot().video.renditions["video"].enabled);
1632
1633		let request = broadcast.reserve_track("audio").unwrap();
1634		let mut audio = Track::audio(
1635			request,
1636			catalog.reserve(),
1637			AudioInit::new(AudioFormat::Opus, opus_head()),
1638		)
1639		.unwrap();
1640		assert!(matches!(
1641			audio.set_enabled(false),
1642			Err(crate::Error::WrongKind { actual: "audio", .. })
1643		));
1644	}
1645
1646	/// An audio format with no init bytes errors up front (audio can't resolve its config from frames),
1647	/// rather than registering a track that never publishes.
1648	#[tokio::test(start_paused = true)]
1649	async fn audio_without_init_errors() {
1650		let (broadcast, catalog) = new_broadcast();
1651		let request = broadcast.reserve_track("audio").unwrap();
1652		let result = Track::audio(
1653			request,
1654			catalog.reserve(),
1655			AudioInit::new(AudioFormat::Opus, Vec::new()),
1656		);
1657		assert!(result.is_err(), "opus with no OpusHead should error, not hang");
1658	}
1659
1660	/// A video codec with no extra parameters (VP8) publishes the catalog before the first key frame.
1661	#[tokio::test(start_paused = true)]
1662	async fn video_publishes_before_first_frame() {
1663		let (broadcast, catalog) = new_broadcast();
1664		let request = broadcast.reserve_track("video").unwrap();
1665		let _import = Track::video(
1666			request,
1667			catalog.reserve(),
1668			VideoInit {
1669				label: Some("Main camera".to_string()),
1670				..VideoInit::new(VideoFormat::Vp8, Vec::new())
1671			},
1672		)
1673		.unwrap();
1674
1675		let video = catalog.snapshot().video.renditions.get("video").cloned().unwrap();
1676		assert_eq!(video.codec.to_string(), "vp8");
1677		assert_eq!(video.label.as_deref(), Some("Main camera"));
1678	}
1679
1680	/// An hvcC publishes the catalog at the first keyframe, which says whether the
1681	/// parameter sets also ride in band: dimensions from the parsed SPS and the record
1682	/// itself as the `description`.
1683	#[tokio::test(start_paused = true)]
1684	async fn existing_track_hvc1_uses_existing_name_in_catalog() {
1685		let hvcc = crate::codec::h265::fixtures::hvcc();
1686		let (broadcast, catalog) = new_broadcast();
1687		let request = broadcast.reserve_track("camera").unwrap();
1688
1689		let mut import = Track::video(
1690			request,
1691			catalog.reserve(),
1692			VideoInit::new(VideoFormat::Hvc1, hvcc.clone()),
1693		)
1694		.unwrap();
1695		let idr: &[u8] = &[0x26, 0x01, 0x80, 0xaa]; // IdrWRadl (19)
1696		let mut au = (idr.len() as u32).to_be_bytes().to_vec();
1697		au.extend_from_slice(idr);
1698		import.decode(&au, Some(Timestamp::from_micros(0).unwrap())).unwrap();
1699
1700		assert_eq!(import.name(), "camera");
1701		let snapshot = catalog.snapshot();
1702		let video = snapshot.video.renditions.get("camera").unwrap();
1703		assert_eq!(video.codec.to_string().get(..4), Some("hvc1"));
1704		assert_eq!(video.coded_width, Some(1280));
1705		assert_eq!(video.coded_height, Some(720));
1706		assert_eq!(video.description.as_deref(), Some(hvcc.as_ref()));
1707	}
1708
1709	/// hvc1: a length-prefixed keyframe access unit is delivered verbatim with the
1710	/// keyframe flag set. The payload stays length-prefixed on the wire, matching
1711	/// the out-of-band description the catalog advertises.
1712	#[tokio::test(start_paused = true)]
1713	async fn hvc1_track_delivers_length_prefixed_keyframe() {
1714		let hvcc = crate::codec::h265::fixtures::hvcc();
1715		let (broadcast, catalog) = new_broadcast();
1716		let consumer = broadcast.consume();
1717		let request = broadcast.reserve_track("video").unwrap();
1718		let mut import = Track::video(request, catalog.reserve(), VideoInit::new(VideoFormat::Hvc1, hvcc)).unwrap();
1719
1720		let track = consumer.track("video").unwrap().subscribe(None).await.unwrap();
1721		let mut media =
1722			crate::container::Consumer::new(track, crate::catalog::hang::Wire::legacy(crate::container::Kind::Data));
1723
1724		let idr: &[u8] = &[0x26, 0x01, 0x80, 0xaa]; // IdrWRadl (19)
1725		let mut au = Vec::new();
1726		au.extend_from_slice(&(idr.len() as u32).to_be_bytes());
1727		au.extend_from_slice(idr);
1728
1729		import
1730			.decode(&au, Some(Timestamp::from_micros(1_000).unwrap()))
1731			.unwrap();
1732
1733		let frame = kio::clock::timeout(Duration::from_secs(1), media.read_frame())
1734			.await
1735			.unwrap()
1736			.unwrap()
1737			.unwrap();
1738		assert!(frame.keyframe, "an IDR access unit must open a group");
1739		assert_eq!(frame.payload, au, "the payload must pass through verbatim");
1740		assert_eq!(frame.timestamp, Timestamp::from_micros(1_000).unwrap());
1741
1742		let _finished = import.finish().unwrap();
1743	}
1744
1745	const H264_IDR: &[u8] = &[0x65, 0x88, 0x84, 0x21];
1746	const H265_IDR: &[u8] = &[0x26, 0x01, 0x80, 0xaa];
1747
1748	fn annexb(nals: &[&[u8]]) -> Vec<u8> {
1749		nals.iter().flat_map(|nal| [&[0, 0, 0, 1], *nal].concat()).collect()
1750	}
1751
1752	fn length_prefixed(nal: &[u8]) -> Vec<u8> {
1753		[&(nal.len() as u32).to_be_bytes()[..], nal].concat()
1754	}
1755
1756	/// `av1.mp4`'s av1C, and a temporal unit of its sequence header and a key frame.
1757	fn av1_init_and_keyframe() -> (Vec<u8>, Vec<u8>) {
1758		let mp4 = include_bytes!("../container/fmp4/test_data/av1.mp4");
1759		let mut cursor = std::io::Cursor::new(&mp4[..]);
1760		let moov = loop {
1761			if let mp4_atom::Any::Moov(moov) = <mp4_atom::Any as mp4_atom::Decode>::decode(&mut cursor).unwrap() {
1762				break moov;
1763			}
1764		};
1765		let mp4_atom::Codec::Av01(av01) = &moov.trak[0].mdia.minf.stbl.stsd.codecs[0] else {
1766			panic!("expected av01");
1767		};
1768		let mut av1c = Vec::new();
1769		mp4_atom::Encode::encode(&av01.av1c, &mut av1c).unwrap();
1770		// Skip the box header: the importer takes the record itself.
1771		let av1c = av1c[8..].to_vec();
1772
1773		let mut tu = vec![0x12, 0x00];
1774		tu.extend_from_slice(&av01.av1c.config_obus);
1775		tu.extend_from_slice(&[0x32, 0x01, 0x10]);
1776		(av1c, tu)
1777	}
1778
1779	/// Subscribe to `name` and read its first frame.
1780	async fn first_frame(consumer: &moq_net::broadcast::Consumer, name: &str) -> crate::container::Frame {
1781		let track = consumer.track(name).unwrap().subscribe(None).await.unwrap();
1782		let mut media =
1783			crate::container::Consumer::new(track, crate::catalog::hang::Wire::legacy(crate::container::Kind::Data));
1784		kio::clock::timeout(Duration::from_secs(1), media.read_frame())
1785			.await
1786			.expect("a frame")
1787			.unwrap()
1788			.expect("the track ended without a frame")
1789	}
1790
1791	async fn headers_survive_reset(format: VideoFormat, init: Vec<u8>, keyframe: Vec<u8>) {
1792		let (broadcast, catalog) = new_broadcast();
1793		let consumer = broadcast.consume();
1794		let mut import = Track::video(
1795			broadcast.reserve_track("video").unwrap(),
1796			catalog.reserve(),
1797			VideoInit::new(format, init.clone()),
1798		)
1799		.unwrap();
1800		// Repeated timeline breaks must retain the init until a picture uses it.
1801		for _ in 0..2 {
1802			import.discontinuity().unwrap();
1803		}
1804		let timestamp = Timestamp::from_micros(1_000).unwrap();
1805		import.decode(&keyframe, Some(timestamp)).unwrap();
1806		let _finished = import.finish().unwrap();
1807		let frame = first_frame(&consumer, "video").await;
1808		assert!(frame.keyframe, "{format}");
1809		assert_eq!(frame.timestamp, timestamp, "{format}");
1810		assert_eq!(
1811			frame.payload.as_ref(),
1812			[init.as_slice(), &keyframe].concat(),
1813			"{format}"
1814		);
1815	}
1816
1817	/// A picture an init carries is published at finish when no decode follows it.
1818	async fn init_picture_published_at_finish(format: VideoFormat, init: Vec<u8>) {
1819		let (broadcast, catalog) = new_broadcast();
1820		let consumer = broadcast.consume();
1821		let import = Track::video(
1822			broadcast.reserve_track("video").unwrap(),
1823			catalog.reserve(),
1824			VideoInit::new(format, init.clone()),
1825		)
1826		.unwrap();
1827		let _finished = import.finish().unwrap();
1828		let frame = first_frame(&consumer, "video").await;
1829		assert!(frame.keyframe, "{format}");
1830		assert_eq!(frame.payload.as_ref(), init.as_slice(), "{format}");
1831	}
1832
1833	/// A finish whose flushed access unit fails ends the track with that failure, so a reader
1834	/// sees the publisher fail rather than the track dropped unfinished.
1835	#[tokio::test(start_paused = true)]
1836	async fn a_failed_finish_aborts_the_track() {
1837		let (broadcast, catalog) = new_broadcast();
1838		let consumer = broadcast.consume();
1839		let mut stream = TrackStream::video(
1840			broadcast.reserve_track("video").unwrap(),
1841			catalog.reserve(),
1842			VideoInit::new(VideoFormat::H264, h264_init()),
1843		)
1844		.unwrap();
1845		let mut track = consumer.track("video").unwrap().subscribe(None).await.unwrap();
1846
1847		// A delta slice with no keyframe before it, held by the splitter until the finish flushes it.
1848		stream.decode(&annexb(&[&[0x61, 0xe0, 0x12, 0x34]])).unwrap();
1849		assert!(stream.finish().is_err());
1850
1851		let read = kio::clock::timeout(Duration::from_secs(1), track.recv_group()).await;
1852		let Err(err) = read.expect("the track carried on") else {
1853			panic!("the track ended without a cause");
1854		};
1855		assert!(
1856			matches!(err, moq_net::Error::Stream(moq_net::StreamError::Internal)),
1857			"{err:?}"
1858		);
1859	}
1860
1861	#[tokio::test(start_paused = true)]
1862	async fn avc3_init_picture_published_at_finish() {
1863		let mut init = h264_init();
1864		init.extend_from_slice(&annexb(&[H264_IDR]));
1865		init_picture_published_at_finish(VideoFormat::H264, init).await;
1866	}
1867
1868	#[tokio::test(start_paused = true)]
1869	async fn hev1_init_picture_published_at_finish() {
1870		use crate::codec::h265::fixtures::{PPS, SPS, VPS};
1871		init_picture_published_at_finish(VideoFormat::H265, annexb(&[VPS, SPS, PPS, H265_IDR])).await;
1872	}
1873
1874	#[tokio::test(start_paused = true)]
1875	async fn avc3_init_headers_survive_reset() {
1876		headers_survive_reset(VideoFormat::H264, h264_init(), annexb(&[H264_IDR])).await;
1877	}
1878
1879	#[tokio::test(start_paused = true)]
1880	async fn hev1_init_headers_survive_reset() {
1881		use crate::codec::h265::fixtures::{PPS, SPS, VPS};
1882		headers_survive_reset(VideoFormat::H265, annexb(&[VPS, SPS, PPS]), annexb(&[H265_IDR])).await;
1883	}
1884
1885	#[tokio::test(start_paused = true)]
1886	async fn av01_init_headers_survive_reset() {
1887		let (av1c, _) = av1_init_and_keyframe();
1888		headers_survive_reset(VideoFormat::Av01, av1c[4..].to_vec(), vec![0x32, 0x01, 0x10]).await;
1889	}
1890
1891	/// An av1C with no configOBUs, just its 4-byte header, is a config record the importer
1892	/// reads, not an OBU stream for the splitter to refuse.
1893	#[tokio::test(start_paused = true)]
1894	async fn av01_header_only_av1c_init_is_a_config_record() {
1895		let (av1c, keyframe) = av1_init_and_keyframe();
1896		let (broadcast, catalog) = new_broadcast();
1897		let consumer = broadcast.consume();
1898		let mut import = Track::video(
1899			broadcast.reserve_track("video").unwrap(),
1900			catalog.reserve(),
1901			VideoInit::new(VideoFormat::Av01, av1c[..4].to_vec()),
1902		)
1903		.unwrap();
1904		let timestamp = Timestamp::from_micros(1_000).unwrap();
1905		import.decode(&keyframe, Some(timestamp)).unwrap();
1906		let _finished = import.finish().unwrap();
1907		assert_eq!(
1908			first_frame(&consumer, "video").await.payload.as_ref(),
1909			keyframe.as_slice()
1910		);
1911	}
1912
1913	/// A keyframe after a pre-picture discontinuity carries the retained init header ahead of its own. The
1914	/// keyframe's own, which the decoder applies, configures the catalog.
1915	#[tokio::test(start_paused = true)]
1916	async fn av01_keyframe_header_supersedes_retained_init() {
1917		let (av1c, keyframe) = av1_init_and_keyframe();
1918		let mut stale = av1c[4..].to_vec();
1919		// seq_level_idx 9 (the fixture's level) becomes 8, in the fourth payload byte.
1920		assert_eq!(stale[5], 0x4a);
1921		stale[5] = 0x42;
1922		let (broadcast, catalog) = new_broadcast();
1923		let mut import = Track::video(
1924			broadcast.reserve_track("video").unwrap(),
1925			catalog.reserve(),
1926			VideoInit::new(VideoFormat::Av01, stale.clone()),
1927		)
1928		.unwrap();
1929		let codecs = |catalog: &crate::catalog::Producer| {
1930			let snapshot = catalog.snapshot();
1931			snapshot
1932				.video
1933				.renditions
1934				.values()
1935				.map(|rendition| rendition.codec.to_string()[..10].to_string())
1936				.collect::<Vec<_>>()
1937		};
1938		assert_eq!(codecs(&catalog), ["av01.0.08M"]);
1939		import.discontinuity().unwrap();
1940		import
1941			.decode(&keyframe, Some(Timestamp::from_micros(1_000).unwrap()))
1942			.unwrap();
1943		assert_eq!(codecs(&catalog), ["av01.0.09M"]);
1944	}
1945
1946	/// Every video format a binding can hand [`Track::video`] lands a keyframe on
1947	/// its track. The facade dispatches per codec, and before this only Avc3,
1948	/// Hvc1, and VP8 had ever decoded through it.
1949	#[tokio::test(start_paused = true)]
1950	async fn every_video_format_delivers_a_keyframe() {
1951		use crate::codec::{h264, h265};
1952
1953		let sps = &h264_init()[4..29];
1954		let avcc = [
1955			&[1, sps[1], sps[2], sps[3], 0xff, 0xe1][..],
1956			&(sps.len() as u16).to_be_bytes(),
1957			sps,
1958			&[1],
1959			&(h264::fixtures::PPS.len() as u16).to_be_bytes(),
1960			h264::fixtures::PPS,
1961		]
1962		.concat();
1963		let (av1c, av1_keyframe) = av1_init_and_keyframe();
1964		let vp9_keyframe = vec![0x82, 0x49, 0x83, 0x42, 0x20, 0x13, 0xf0, 0x0e, 0xf0, 0x00];
1965
1966		let cases = [
1967			(VideoFormat::Avc1, avcc, length_prefixed(H264_IDR)),
1968			(
1969				VideoFormat::H265,
1970				Vec::new(),
1971				annexb(&[h265::fixtures::VPS, h265::fixtures::SPS, h265::fixtures::PPS, H265_IDR]),
1972			),
1973			(VideoFormat::Av01, av1c, av1_keyframe),
1974			(VideoFormat::Vp9, Vec::new(), vp9_keyframe),
1975		];
1976		for (format, init, keyframe) in cases {
1977			let (broadcast, catalog) = new_broadcast();
1978			let consumer = broadcast.consume();
1979			let request = broadcast.reserve_track("video").unwrap();
1980			let mut import = Track::video(request, catalog.reserve(), VideoInit::new(format, init)).unwrap();
1981
1982			import
1983				.decode(keyframe, Some(Timestamp::from_micros(1_000).unwrap()))
1984				.unwrap();
1985			let frame = first_frame(&consumer, "video").await;
1986			assert!(frame.keyframe, "{format}: the first frame opens a group");
1987			assert_eq!(frame.timestamp, Timestamp::from_micros(1_000).unwrap(), "{format}");
1988			assert!(
1989				catalog.snapshot().video.renditions.contains_key("video"),
1990				"{format}: no rendition"
1991			);
1992			let _finished = import.finish().unwrap();
1993		}
1994	}
1995
1996	/// MP3 through [`Track::audio`]: the catalog comes from the frame header, and
1997	/// a group spans frames until the caller cuts it. No test had published MP3.
1998	#[tokio::test(start_paused = true)]
1999	async fn mp3_groups_span_frames_until_a_cut() {
2000		// MPEG-1 Layer III, 128 kbps, 44.1 kHz, joint stereo.
2001		let header = [0xFF, 0xFB, 0x90, 0x44];
2002		let (broadcast, catalog) = new_broadcast();
2003		let consumer = broadcast.consume();
2004		let request = broadcast.reserve_track("audio").unwrap();
2005		let mut import = Track::audio(
2006			request,
2007			catalog.reserve(),
2008			AudioInit::new(AudioFormat::Mp3, header.to_vec()),
2009		)
2010		.unwrap();
2011
2012		let audio = catalog.snapshot().audio.renditions["audio"].clone();
2013		assert_eq!((audio.sample_rate, audio.channel_count), (44_100, 2));
2014
2015		// Delay-tolerant, so the first group is still delivered once the second exists.
2016		let replay = moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
2017			moq_net::track::Start::Live {
2018				min: Some(Duration::from_secs(30)),
2019				max: Some(Duration::from_secs(30)),
2020			},
2021		)]);
2022		let mut track = consumer.track("audio").unwrap().subscribe(Some(replay)).await.unwrap();
2023		for i in 0..4u64 {
2024			if i == 2 {
2025				import.cut(None).unwrap();
2026			}
2027			let frame = [&header[..], &[i as u8; 8]].concat();
2028			import
2029				.decode(frame, Some(Timestamp::from_micros(i * 26_122).unwrap()))
2030				.unwrap();
2031		}
2032		let _finished = import.finish().unwrap();
2033
2034		// Frames carrying audio per group, ignoring any empty end-of-group marker.
2035		let mut groups = Vec::new();
2036		while let Some(mut group) = track.recv_group().await.unwrap() {
2037			let mut frames = 0;
2038			while let Some(frame) = group.read_frame().await.unwrap() {
2039				frames += usize::from(
2040					!hang::container::Frame::decode(frame.payload)
2041						.unwrap()
2042						.payload
2043						.is_empty(),
2044				);
2045			}
2046			groups.push(frames);
2047		}
2048		assert_eq!(groups, [2, 2]);
2049	}
2050
2051	/// [`TrackStream`] finds the frames in a raw byte stream however it is chunked,
2052	/// and `finish` flushes the last one. Nothing had decoded through it before.
2053	#[tokio::test(start_paused = true)]
2054	async fn track_stream_splits_a_chunked_byte_stream() {
2055		use crate::codec::h265;
2056
2057		let (_, av1_keyframe) = av1_init_and_keyframe();
2058		let cases = [
2059			(VideoFormat::H264, [h264_init(), annexb(&[H264_IDR])].concat(), H264_IDR),
2060			(
2061				VideoFormat::H265,
2062				annexb(&[h265::fixtures::VPS, h265::fixtures::SPS, h265::fixtures::PPS, H265_IDR]),
2063				H265_IDR,
2064			),
2065			(
2066				VideoFormat::Av01,
2067				av1_keyframe.clone(),
2068				&av1_keyframe[av1_keyframe.len() - 3..],
2069			),
2070		];
2071		for (format, stream, last) in cases {
2072			let (broadcast, catalog) = new_broadcast();
2073			let consumer = broadcast.consume();
2074			let request = broadcast.reserve_track("video").unwrap();
2075			let mut import =
2076				TrackStream::video(request, catalog.reserve(), VideoInit::new(format, Vec::new())).unwrap();
2077
2078			for chunk in stream.chunks(3) {
2079				import.decode(chunk).unwrap();
2080			}
2081			let _finished = import.finish().unwrap();
2082
2083			let frame = first_frame(&consumer, "video").await;
2084			assert!(frame.keyframe, "{format}: the first frame opens a group");
2085			assert!(
2086				frame.payload.ends_with(last),
2087				"{format}: the frame ends with its picture"
2088			);
2089		}
2090	}
2091
2092	/// A disabled [`TrackStream`] drops what it splits and marks the break, so a caller that
2093	/// keeps writing sends nothing. Enabled again, it resumes, and advertises itself enabled,
2094	/// only at the next keyframe.
2095	#[tokio::test(start_paused = true)]
2096	async fn track_stream_disables_and_resumes_at_a_keyframe() {
2097		const H264_P: &[u8] = &[0x41, 0x9a, 0x21, 0x22];
2098
2099		let (broadcast, catalog) = new_broadcast();
2100		let consumer = broadcast.consume();
2101		let request = broadcast.reserve_track("video").unwrap();
2102		let mut import = TrackStream::video(
2103			request,
2104			catalog.reserve(),
2105			VideoInit::new(VideoFormat::H264, Vec::new()),
2106		)
2107		.unwrap();
2108		// Every group is written before anything reads, which the default
2109		// REAL_TIME budget would collapse to the live edge.
2110		let subscriber = consumer
2111			.track("video")
2112			.unwrap()
2113			.subscribe(
2114				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
2115					moq_net::track::Start::Live {
2116						min: Some(Duration::from_secs(30)),
2117						max: Some(Duration::from_secs(30)),
2118					},
2119				)]),
2120			)
2121			.await
2122			.unwrap();
2123		let enabled = || catalog.snapshot().video.renditions["video"].enabled;
2124
2125		let keyframe = [h264_init(), annexb(&[H264_IDR])].concat();
2126		let delta = annexb(&[H264_P]);
2127		// One access unit per frame interval. The splitter holds the last NAL until the next
2128		// start code, so an access unit goes out one write after its last NAL arrives.
2129		async fn write(import: &mut TrackStream, bytes: &[u8]) {
2130			import.decode(bytes).unwrap();
2131			kio::clock::sleep(Duration::from_millis(33)).await;
2132		}
2133		for bytes in [&keyframe, &delta, &delta] {
2134			write(&mut import, bytes).await;
2135		}
2136		// A chunk may end mid-NAL, and the next one continue it across the disable.
2137		let (head, tail) = delta.split_at(6);
2138		write(&mut import, head).await;
2139
2140		import.set_enabled(false).unwrap();
2141		assert!(!enabled());
2142		for bytes in [tail, &keyframe, &delta, &delta] {
2143			write(&mut import, bytes).await;
2144		}
2145
2146		import.set_enabled(true).unwrap();
2147		for bytes in [&delta, &keyframe, &delta] {
2148			write(&mut import, bytes).await;
2149		}
2150		assert!(!enabled(), "enabled before the keyframe that resumes it");
2151		write(&mut import, &delta).await;
2152		assert!(enabled());
2153		let _finished = import.finish().unwrap();
2154
2155		// The first group loses the access units still in the splitter at the disable, the
2156		// marker breaks the timeline, and the resumed group opens on the keyframe: three
2157		// access units and the end marker `finish` bounds the last one with.
2158		assert_eq!(collect_groups(subscriber).await, vec![2, 1, 4]);
2159	}
2160
2161	/// A keyframe dropped while disabled still configures the importer: an AV1 stream may send
2162	/// its sequence header once, and the keyframe that resumes need not repeat it.
2163	#[tokio::test(start_paused = true)]
2164	async fn track_stream_configures_from_a_dropped_keyframe() {
2165		let (_, with_header) = av1_init_and_keyframe();
2166		// A temporal delimiter and a key frame, with no sequence header.
2167		let bare = [0x12, 0x00, 0x32, 0x01, 0x10];
2168
2169		let (broadcast, catalog) = new_broadcast();
2170		let consumer = broadcast.consume();
2171		let request = broadcast.reserve_track("video").unwrap();
2172		let mut import = TrackStream::video(
2173			request,
2174			catalog.reserve(),
2175			VideoInit::new(VideoFormat::Av01, Vec::new()),
2176		)
2177		.unwrap();
2178
2179		import.set_enabled(false).unwrap();
2180		// The next temporal delimiter completes the one carrying the sequence header.
2181		import.decode(&with_header).unwrap();
2182		kio::clock::sleep(Duration::from_millis(33)).await;
2183		import.decode(&bare).unwrap();
2184		kio::clock::sleep(Duration::from_millis(33)).await;
2185
2186		// Finish flushes the last temporal unit, the keyframe that resumes.
2187		import.set_enabled(true).unwrap();
2188		let _finished = import.finish().unwrap();
2189
2190		assert!(catalog.snapshot().video.renditions["video"].enabled);
2191		let frame = first_frame(&consumer, "video").await;
2192		assert!(frame.keyframe, "the resumed group opens on a keyframe");
2193		// The dropped sequence header goes out with it, after its temporal delimiter.
2194		assert_eq!(frame.payload.as_ref(), with_header.as_slice());
2195	}
2196}