Skip to main content

moq_mux/container/fmp4/
muxer.rs

1//! One-shot CMAF muxing for individually fetched groups.
2
3use std::task::{Poll, ready};
4use std::time::Duration;
5
6use bytes::Bytes;
7use hang::catalog::{AudioConfig, Container as CatalogContainer, VideoCodec, VideoConfig};
8use moq_net::Timestamp;
9
10use crate::catalog::hang::Wire as HangWire;
11use crate::codec::av1;
12use crate::container::Frame;
13use crate::container::source::{
14	VideoTransform, build_video_transform, catalog_dimensions, codec_dimensions, in_band_dimensions,
15};
16
17use super::export::{
18	Run, apply_codec_durations, catalog_timescale_audio, catalog_timescale_video, extract_init,
19	infer_missing_durations, timestamp_gap,
20};
21use super::{Error, synthesize_audio_trak, synthesize_video_trak};
22
23/// The single track id used by a muxer's init segment and fragments.
24///
25/// A muxer serves one rendition standalone, so the id carries no information; a fixed value
26/// keeps a synthesized init and its fragments trivially consistent.
27const TRACK_ID: u32 = 1;
28
29/// Whether the muxer serves a video or an audio rendition, with its catalog config.
30#[allow(
31	clippy::large_enum_variant,
32	reason = "one per muxer, so the variant sizes never add up to an allocation's worth; only large when extra features grow the video config"
33)]
34enum Kind {
35	Video(VideoConfig),
36	Audio(AudioConfig),
37}
38
39/// Muxes one rendition's fetched groups into standalone CMAF, without a live subscription.
40///
41/// The pull-based [`Export`](super::Export) subscribes to a whole broadcast and interleaves
42/// its tracks; `Muxer` is the building block for a fetch-on-demand consumer (an HLS/DASH
43/// origin) that retrieves one group at a time via
44/// [`track::Consumer::fetch_group`](moq_net::track::Consumer::fetch_group):
45///
46/// 1. [`read`](Self::read) decodes a fetched group into media [`Frame`]s, normalizing the
47///    codec shape (Annex-B H.264/H.265 becomes length-prefixed, with the config record
48///    synthesized from the in-band parameter sets).
49/// 2. [`init`](Self::init) builds the rendition's init segment (ftyp+moov).
50/// 3. [`fragment`](Self::fragment) encodes frames as one moof+mdat whose `tfdt` carries their
51///    real presentation time, so a fragment built from a mid-stream group stands alone.
52///
53/// For video missing codec configuration or geometry, [`init`](Self::init) returns `None` until a
54/// group has been [`read`](Self::read) to resolve the missing fields from a keyframe.
55pub struct Muxer {
56	kind: Kind,
57	container: HangWire,
58	transform: Option<VideoTransform>,
59	/// Resolved codec config record: the catalog `description`, or synthesized by the
60	/// transform from in-band parameter sets.
61	description: Option<Bytes>,
62	timescale: moq_net::Timescale,
63	/// Fallback duration for frames that carry none (Legacy / LOC sources), derived from the
64	/// catalog framerate / sample rate.
65	default_frame: Duration,
66	/// True for Opus audio, whose packets state their own duration in the TOC byte.
67	opus: bool,
68}
69
70impl Muxer {
71	/// A muxer for a video rendition described by `config`.
72	pub fn video(config: &VideoConfig) -> crate::Result<Self> {
73		let container = config.try_into()?;
74		let framerate = super::usable_video_framerate(config).unwrap_or(30.0);
75		let description = config.description.as_ref().filter(|b| !b.is_empty()).cloned();
76		let mut config = config.clone();
77		if catalog_dimensions(&config).is_none()
78			&& let Some((width, height)) = codec_dimensions(&config.codec, description.as_deref(), &[])?
79		{
80			config.coded_width = Some(width);
81			config.coded_height = Some(height);
82		}
83		Ok(Self {
84			container,
85			transform: build_video_transform(&config),
86			description,
87			timescale: moq_net::Timescale::new(catalog_timescale_video(&config)?).map_err(Error::from)?,
88			default_frame: Duration::from_secs_f64(1.0 / framerate),
89			opus: false,
90			kind: Kind::Video(config),
91		})
92	}
93
94	/// A muxer for an audio rendition described by `config`.
95	pub fn audio(config: &AudioConfig) -> crate::Result<Self> {
96		let container = config.try_into()?;
97		Ok(Self {
98			container,
99			transform: None,
100			description: config.description.as_ref().filter(|b| !b.is_empty()).cloned(),
101			timescale: moq_net::Timescale::new(catalog_timescale_audio(config)?).map_err(Error::from)?,
102			default_frame: super::audio_default_frame(config),
103			opus: matches!(config.codec, hang::catalog::AudioCodec::Opus),
104			kind: Kind::Audio(config.clone()),
105		})
106	}
107
108	/// The media timescale this muxer's init segment and fragments are expressed in.
109	///
110	/// Derived from the catalog: a `Cmaf` rendition's own init scale, a cadence-compatible scale
111	/// for video (falling back to 90 kHz) and the sample rate for audio, unless
112	/// [`with_timescale`](Self::with_timescale) overrode it.
113	pub fn timescale(&self) -> moq_net::Timescale {
114		self.timescale
115	}
116
117	/// Emit at an explicit timescale instead of the one derived from the catalog.
118	///
119	/// For a consumer whose downstream timeline is fixed, for example an HLS or DASH origin
120	/// working in 90 kHz ticks.
121	///
122	/// Errors for a `Cmaf` rendition, whose init segment passes through from the catalog at its
123	/// own scale: overriding would leave the init and the fragments on different timelines. Also
124	/// errors above `u32::MAX`, which the init segment's `mdhd.timescale` field cannot hold.
125	pub fn with_timescale(mut self, timescale: moq_net::Timescale) -> crate::Result<Self> {
126		if matches!(self.catalog_container(), CatalogContainer::Cmaf { .. }) {
127			return Err(Error::TimescaleOverride.into());
128		}
129		// Reject here rather than at init(), so the failure lands on the call that is wrong.
130		super::mdhd_timescale(timescale.as_u64())?;
131		self.timescale = timescale;
132		Ok(self)
133	}
134
135	/// The rendition's catalog container, whichever kind of track this is.
136	fn catalog_container(&self) -> &CatalogContainer {
137		match &self.kind {
138			Kind::Video(config) => &config.container,
139			Kind::Audio(config) => &config.container,
140		}
141	}
142
143	/// Decode one fetched group into media frames, in decode order.
144	///
145	/// Reads the group to its end, so call it only on a finished group (a live group would
146	/// block until the publisher closes it). Parameter-set frames are absorbed into the codec
147	/// config record; the group's first emitted frame is marked a keyframe (a group opens on
148	/// one by convention).
149	#[cfg(feature = "async")]
150	pub async fn read(&mut self, group: &mut moq_net::group::Consumer) -> crate::Result<Vec<Frame>> {
151		let mut out = Vec::new();
152		kio::wait(|waiter| self.poll_read(waiter, group, &mut out)).await
153	}
154
155	/// [`read`](Self::read), polled: ready with the group's frames once it ends. Pass the same
156	/// empty `out` to every poll of one group, which holds the frames decoded so far.
157	pub fn poll_read(
158		&mut self,
159		waiter: &kio::Waiter,
160		group: &mut moq_net::group::Consumer,
161		out: &mut Vec<Frame>,
162	) -> Poll<crate::Result<Vec<Frame>>> {
163		use crate::container::Container as _;
164
165		while let Some(wire) = ready!(group.poll_read_frame(waiter))? {
166			for frame in self.container.decode(wire)? {
167				if let Some(bound) = self.container.end(&frame) {
168					if matches!(self.kind, Kind::Video(_))
169						&& let Some(last) = out.last_mut()
170						&& last.duration.is_none()
171					{
172						last.duration = super::export::timestamp_gap(last.timestamp, bound, self.timescale)?;
173					}
174					continue;
175				}
176				let Some(transform) = self.transform.as_mut() else {
177					self.resolve_video_dimensions(&frame.payload)?;
178					out.push(frame);
179					continue;
180				};
181				let payload = transform.transform(frame.payload.clone(), frame.keyframe)?;
182				// Track the transform's record even after it is first set: a mid-stream
183				// reconfiguration rebuilds the avcC/hvcC with new parameter sets.
184				if let Some(d) = transform.codec_private()
185					&& self.description.as_ref() != Some(d)
186				{
187					self.description = Some(d.clone());
188				}
189				self.resolve_video_dimensions(&frame.payload)?;
190				if let Some(payload) = payload {
191					out.push(Frame { payload, ..frame });
192				}
193			}
194		}
195		let mut out = std::mem::take(out);
196		if let Some(first) = out.first_mut() {
197			first.keyframe = true;
198		}
199		Poll::Ready(Ok(out))
200	}
201
202	/// The picture size `keyframe` decodes to: from its in-band parameter sets (Annex-B, or
203	/// length-prefixed beside an avc3/hev1 record) or its frame header (VP8, VP9, and AV1, whose
204	/// frame may override its sequence maximum), else the catalog `description`, or `None` for audio
205	/// or a codec that declares neither.
206	///
207	/// Pass a group's first frame: the picture size of a track may change at any keyframe, which
208	/// only the media says, so reading this per group tells which config muxes it. It leaves the
209	/// [`init`](Self::init) untouched.
210	pub fn picture_size(&mut self, keyframe: &Frame) -> crate::Result<Option<(u32, u32)>> {
211		let Kind::Video(config) = &self.kind else {
212			return Ok(None);
213		};
214		let payload = &keyframe.payload;
215		let description = match self.transform.as_mut() {
216			Some(transform) => {
217				transform.transform(payload.clone(), true)?;
218				transform.codec_private().cloned()
219			}
220			None => {
221				let description = self.description.as_deref().unwrap_or_default();
222				let size = match &config.codec {
223					VideoCodec::AV1(_) => av1::frame_size(payload, description.get(4..).unwrap_or_default())?,
224					codec if !description.is_empty() => in_band_dimensions(codec, description, payload)?,
225					_ => None,
226				};
227				if size.is_some() {
228					return Ok(size);
229				}
230				self.description.clone()
231			}
232		};
233		codec_dimensions(&config.codec, description.as_deref(), payload)
234	}
235
236	fn resolve_video_dimensions(&mut self, payload: &[u8]) -> crate::Result<()> {
237		let Kind::Video(config) = &mut self.kind else {
238			return Ok(());
239		};
240		if catalog_dimensions(config).is_some() {
241			return Ok(());
242		}
243		if let Some((width, height)) = codec_dimensions(&config.codec, self.description.as_deref(), payload)? {
244			config.coded_width = Some(width);
245			config.coded_height = Some(height);
246		}
247		Ok(())
248	}
249
250	/// Build the rendition's CMAF init segment (ftyp+moov), or `None` if it isn't buildable yet.
251	///
252	/// A `Cmaf` rendition's catalog init passes through (with the track id normalized to match
253	/// [`fragment`](Self::fragment)); a `Legacy`/`Loc` rendition's is synthesized from the catalog
254	/// config. `None` means a video rendition whose codec config or geometry hasn't been resolved
255	/// yet: [`read`](Self::read) a group (its keyframe carries those fields) and call again.
256	pub fn init(&self) -> crate::Result<Option<Bytes>> {
257		// An inline codec carries its config in-band, so the init can't be built until a keyframe
258		// group has been read.
259		if self.transform.is_some() && self.description.is_none() {
260			return Ok(None);
261		}
262		if matches!(
263			self.catalog_container(),
264			CatalogContainer::Legacy | CatalogContainer::Loc | CatalogContainer::Raw | CatalogContainer::Cts
265		) && let Kind::Video(config) = &self.kind
266			&& catalog_dimensions(config).is_none()
267		{
268			return Ok(None);
269		}
270
271		let mut traks: Vec<mp4_atom::Trak> = Vec::new();
272		let mut trexs: Vec<mp4_atom::Trex> = Vec::new();
273		let mut ftyp: Option<mp4_atom::Ftyp> = None;
274
275		match self.catalog_container() {
276			CatalogContainer::Cmaf { init, .. } => {
277				extract_init(init, TRACK_ID, &mut ftyp, &mut traks, &mut trexs)?;
278			}
279			CatalogContainer::Legacy | CatalogContainer::Loc | CatalogContainer::Raw | CatalogContainer::Cts => {
280				let trak = match &self.kind {
281					Kind::Video(config) => {
282						synthesize_video_trak(TRACK_ID, self.timescale.as_u64(), config, self.description.as_deref())?
283					}
284					Kind::Audio(config) => synthesize_audio_trak(TRACK_ID, self.timescale.as_u64(), config)?,
285				};
286				trexs.push(mp4_atom::Trex {
287					track_id: trak.tkhd.track_id,
288					default_sample_description_index: 1,
289					..Default::default()
290				});
291				traks.push(trak);
292			}
293			CatalogContainer::Unknown(unknown) => return Err(crate::Error::unsupported_container(unknown)),
294		}
295
296		Ok(Some(super::encode_init(ftyp, traks, trexs)?))
297	}
298
299	/// Encode frames as one moof+mdat fragment.
300	///
301	/// The `tfdt` base decode time is the first frame's real presentation timestamp (at the
302	/// init segment's timescale), so the fragment is self-contained regardless of which group
303	/// it came from. Frames without a duration get one inferred from the following frame's
304	/// timestamp (falling back to the catalog frame rate / sample rate), so multi-sample
305	/// fragments stay decodable. `sequence` is the moof sequence number, informative only.
306	///
307	/// `frames` may span several groups, and a sample is never timed by one in the next group
308	/// even so: consecutive sequence numbers say nothing about whether the publisher paused
309	/// across the boundary.
310	///
311	/// `end`, when the caller knows where the content ends (such as the next segment's start),
312	/// times the last presented sample if neither its codec nor a duration marker does.
313	pub fn fragment(&self, sequence: u32, frames: &[Frame], end: Option<Timestamp>) -> crate::Result<Bytes> {
314		let frames = self.resolve_durations(frames, end)?;
315		Ok(super::encode_fragment(self.fragment_info(sequence), &frames)?)
316	}
317
318	/// Give every frame a duration: the one its codec states, else `end` for the last presented
319	/// one, else the gap to its successor in this slice, else the catalog frame rate / sample
320	/// rate.
321	fn resolve_durations(&self, frames: &[Frame], end: Option<Timestamp>) -> crate::Result<Vec<Frame>> {
322		let mut frames = frames.to_vec();
323		apply_codec_durations(&mut frames, self.opus);
324		if let Some(end) = end
325			&& let Some(last) = frames.iter_mut().max_by_key(|frame| frame.timestamp.as_micros().ok())
326			&& last.duration.is_none()
327			// Quantized at the output scale like the gaps between samples, so any end gap is
328			// whole ticks; one within a tick falls back like a sample with no successor.
329			&& let Some(duration) = timestamp_gap(last.timestamp, end, self.timescale)?
330		{
331			last.duration = Some(duration);
332		}
333		infer_missing_durations(&mut frames, None, self.default_frame, self.timescale, Run::Whole)?;
334		Ok(frames)
335	}
336
337	/// Where a fragment sits: this muxer's single track, at its resolved timescale.
338	fn fragment_info(&self, sequence: u32) -> super::FragmentInfo {
339		super::FragmentInfo {
340			track_id: TRACK_ID,
341			timescale: self.timescale,
342			sequence_number: sequence,
343			kind: match self.kind {
344				Kind::Audio(_) => super::Kind::Audio,
345				Kind::Video(_) => super::Kind::Video,
346			},
347		}
348	}
349}
350
351#[cfg(test)]
352mod tests {
353	use super::*;
354	use hang::catalog::{AudioCodec, VideoCodec};
355
356	/// A millisecond track: the frames written here carry timestamps. It sets no max age, so a
357	/// group finished whole stays readable after its span has passed.
358	fn timed() -> moq_net::track::Info {
359		moq_net::track::Info::default()
360			.with_timescale(moq_net::Timescale::MILLI)
361			.with_max_age(None)
362	}
363
364	fn frame(micros: u64, keyframe: bool) -> Frame {
365		Frame {
366			timestamp: Timestamp::from_micros(micros).unwrap(),
367			decode: None,
368			payload: Bytes::from_static(&[0xDE, 0xAD]),
369			keyframe,
370			duration: None,
371		}
372	}
373
374	// A fetched Legacy group round-trips through the muxer into a self-contained fragment:
375	// synthesized init, keyframe-marked first sample, and a tfdt carrying the real PTS.
376	#[tokio::test]
377	async fn legacy_group_round_trips() {
378		let track = moq_net::broadcast::Info::new()
379			.produce()
380			.create_track("v", timed())
381			.unwrap();
382		let mut subscriber = track.subscribe(None).ordered();
383		let mut producer = crate::container::Producer::new(track, HangWire::legacy(crate::container::Kind::Data));
384		producer.write(frame(10_000_000, true)).unwrap();
385		producer.write(frame(10_033_000, false)).unwrap();
386		let _finished = producer.finish().unwrap();
387
388		let mut group = subscriber.next_group().await.unwrap().expect("a group");
389
390		let mut muxer = video_muxer();
391
392		let init = muxer.init().unwrap().expect("init buildable for an out-of-band codec");
393		assert_eq!(&init[4..8], b"ftyp");
394
395		let frames = muxer.read(&mut group).await.unwrap();
396		assert_eq!(frames.len(), 2);
397		assert!(frames[0].keyframe, "the group's first frame is a keyframe");
398
399		let fragment = muxer.fragment(7, &frames, None).unwrap();
400		assert_eq!(&fragment[4..8], b"moof");
401
402		// Decode it back: timestamps survive at the muxer's timescale (framerate * 1000).
403		let timescale = moq_net::Timescale::new(30_000).unwrap();
404		let decoded = super::super::decode(
405			fragment,
406			None,
407			super::super::Track::new(timescale, crate::container::fmp4::Kind::Video),
408		)
409		.unwrap();
410		assert_eq!(decoded.len(), 2);
411		assert_eq!(decoded[0].timestamp.as_micros().unwrap(), 10_000_000);
412		assert!(decoded[0].keyframe);
413		assert_eq!(decoded[1].timestamp.as_micros().unwrap(), 10_033_000);
414	}
415
416	/// A duration marker times the group's last sample through fmp4 (and HLS, which
417	/// uses the same [`Muxer::read`] / [`Muxer::fragment`] path).
418	#[tokio::test]
419	async fn a_duration_marker_times_the_trailing_sample() {
420		let track = moq_net::broadcast::Info::new()
421			.produce()
422			.create_track("v", timed())
423			.unwrap();
424		let mut subscriber = track.subscribe(None).ordered();
425		let mut producer = crate::container::Producer::new(track, HangWire::legacy(crate::container::Kind::Video));
426		producer.write(frame(10_000_000, true)).unwrap();
427		producer.write(frame(10_033_000, false)).unwrap();
428		producer.cut(Some(Timestamp::from_micros(10_066_000).unwrap())).unwrap();
429		let _finished = producer.finish().unwrap();
430
431		let mut group = subscriber.next_group().await.unwrap().expect("a group");
432		let mut muxer = video_muxer();
433		let frames = muxer.read(&mut group).await.unwrap();
434		assert_eq!(frames.len(), 2, "the marker is not a sample");
435		assert_eq!(frames[1].duration.unwrap().as_micros().unwrap(), 33_000);
436
437		let fragment = muxer.fragment(0, &frames, None).unwrap();
438		assert_eq!(super::super::sample_durations(&fragment), vec![Some(990), Some(990)]);
439	}
440
441	#[tokio::test]
442	async fn dimensionless_vp8_init_waits_for_keyframe_geometry() {
443		let track = moq_net::broadcast::Info::new()
444			.produce()
445			.create_track("v", timed())
446			.unwrap();
447		let mut subscriber = track.subscribe(None).ordered();
448		let mut producer = crate::container::Producer::new(track, HangWire::legacy(crate::container::Kind::Data));
449		producer
450			.write(Frame {
451				timestamp: Timestamp::ZERO,
452				decode: None,
453				// Key frame tag, start code, and 320x240 geometry.
454				payload: Bytes::from_static(&[0x10, 0x00, 0x00, 0x9d, 0x01, 0x2a, 0x40, 0x01, 0xf0, 0x00]),
455				keyframe: true,
456				duration: None,
457			})
458			.unwrap();
459		let _finished = producer.finish().unwrap();
460		let mut group = subscriber.next_group().await.unwrap().expect("a group");
461
462		let config = VideoConfig::new(VideoCodec::VP8);
463		let mut muxer = Muxer::video(&config).unwrap();
464		assert!(muxer.init().unwrap().is_none(), "geometry is unresolved before media");
465
466		let frames = muxer.read(&mut group).await.unwrap();
467		assert_eq!(frames.len(), 1);
468		let init = muxer.init().unwrap().expect("keyframe geometry makes init buildable");
469		let wire = super::super::Wire::from_init(&init).unwrap();
470		let mp4_atom::Codec::Vp08(vp08) = &wire.trak().mdia.minf.stbl.stsd.codecs[0] else {
471			panic!("expected VP8 sample entry");
472		};
473		assert_eq!((vp08.visual.width, vp08.visual.height), (320, 240));
474	}
475
476	#[test]
477	fn malformed_fixed_description_errors_instead_of_waiting_for_geometry() {
478		let mut config = VideoConfig::new(hang::catalog::H264 {
479			profile: 0x42,
480			constraints: 0,
481			level: 0x1f,
482			inline: false,
483		});
484		config.description = Some(Bytes::from_static(&[1]));
485
486		assert!(matches!(
487			Muxer::video(&config),
488			Err(crate::Error::H264(crate::codec::h264::Error::AvccTooShort))
489		));
490	}
491
492	// A 30 fps Legacy VP8 rendition: no description needed, so the muxer builds without media.
493	fn video_muxer() -> Muxer {
494		let mut config = VideoConfig::new(VideoCodec::VP8);
495		config.coded_width = Some(320);
496		config.coded_height = Some(240);
497		config.framerate = Some(30.0);
498		Muxer::video(&config).unwrap()
499	}
500
501	// Each keyframe reports the size its own parameter sets or frame header declare, so a track
502	// that resizes in band is read group by group; one carrying none keeps the active set's.
503	#[test]
504	fn a_keyframe_reports_its_in_band_picture_size() {
505		use crate::codec::h264::fixtures::{PPS, SPS_ANAMORPHIC, SPS_EXTENDED_SAR};
506		let annexb = |nals: &[&[u8]]| {
507			let payload: Vec<u8> = nals.iter().flat_map(|nal| [&[0, 0, 0, 1][..], nal].concat()).collect();
508			Frame {
509				payload: payload.into(),
510				..frame(0, true)
511			}
512		};
513		let idr = &[0x65, 0x88, 0x84, 0x21][..];
514		let mut config = VideoConfig::new(VideoCodec::H264(hang::catalog::H264 {
515			profile: 0x64,
516			constraints: 0,
517			level: 0x28,
518			inline: true,
519		}));
520		config.framerate = Some(25.0);
521		let mut muxer = Muxer::video(&config).unwrap();
522		let sizes = [
523			annexb(&[SPS_ANAMORPHIC, PPS, idr]),
524			annexb(&[SPS_EXTENDED_SAR, PPS, idr]),
525			annexb(&[idr]),
526		]
527		.map(|keyframe| muxer.picture_size(&keyframe).unwrap());
528		assert_eq!(sizes, [Some((1440, 1080)), Some((64, 48)), Some((64, 48))]);
529		assert!(muxer.init().unwrap().is_none(), "probing builds no init");
530
531		// avc3 and hev1 keep their sets in band beside a record, which fixes only the NAL length
532		// size: a keyframe's own SPS wins, and one without keeps the record's.
533		let length_prefixed = |nals: &[&[u8]]| {
534			let payload: Vec<u8> = nals
535				.iter()
536				.flat_map(|nal| [&(nal.len() as u32).to_be_bytes()[..], nal].concat())
537				.collect();
538			Frame {
539				payload: payload.into(),
540				..frame(0, true)
541			}
542		};
543		let mut avc3 = config.clone();
544		avc3.description = Some(
545			crate::codec::h264::build_avcc(&[Bytes::from_static(SPS_ANAMORPHIC)], &[Bytes::from_static(PPS)]).unwrap(),
546		);
547		let mut muxer = Muxer::video(&avc3).unwrap();
548		let sizes = [length_prefixed(&[SPS_EXTENDED_SAR, PPS, idr]), length_prefixed(&[idr])]
549			.map(|keyframe| muxer.picture_size(&keyframe).unwrap());
550		assert_eq!(sizes, [Some((64, 48)), Some((1440, 1080))]);
551
552		use crate::codec::h265::fixtures as h265;
553		let mut hev1 = crate::codec::h265::config_from_hvcc(&h265::hvcc()).unwrap();
554		let VideoCodec::H265(codec) = &mut hev1.codec else {
555			unreachable!("an hvcC describes H.265")
556		};
557		codec.in_band = true;
558		hev1.framerate = Some(25.0);
559		let mut muxer = Muxer::video(&hev1).unwrap();
560		let slice = &[0x26, 0x01, 0xaf][..];
561		let sizes = [
562			length_prefixed(&[h265::VPS, h265::SPS_ANAMORPHIC, h265::PPS, slice]),
563			length_prefixed(&[slice]),
564		]
565		.map(|keyframe| muxer.picture_size(&keyframe).unwrap());
566		assert_eq!(sizes, [Some((1440, 1080)), Some((1280, 720))]);
567
568		// An AV1 key frame's own size, not its sequence maximum, read against the av1C's sequence
569		// header when the unit carries none.
570		use crate::codec::av1::fixtures::RESIZED_KEY;
571		let (sequence, unit) = RESIZED_KEY[2..].split_at(13);
572		let av1 = crate::codec::av1::config_from_av1c(&[&[0x81, 0x00, 0x0c, 0x00], sequence].concat()).unwrap();
573		let mut muxer = Muxer::video(&av1).unwrap();
574		let sizes = [RESIZED_KEY, unit].map(|payload| {
575			let keyframe = Frame {
576				payload: Bytes::copy_from_slice(payload),
577				..frame(0, true)
578			};
579			muxer.picture_size(&keyframe).unwrap()
580		});
581		assert_eq!(sizes, [Some((320, 240)), Some((320, 240))]);
582
583		// VP8 declares its size in every keyframe header, whatever the catalog says.
584		let keyframe = Frame {
585			payload: Bytes::from_static(&[0x10, 0x00, 0x00, 0x9d, 0x01, 0x2a, 0x80, 0x02, 0xe0, 0x01]),
586			..frame(0, true)
587		};
588		assert_eq!(video_muxer().picture_size(&keyframe).unwrap(), Some((640, 480)));
589		let audio = AudioConfig::new(AudioCodec::Opus, 48_000, 2);
590		assert_eq!(Muxer::audio(&audio).unwrap().picture_size(&keyframe).unwrap(), None);
591	}
592
593	#[test]
594	fn fragment_with_no_frames_is_empty() {
595		assert!(video_muxer().fragment(0, &[], None).unwrap().is_empty());
596	}
597
598	/// A known end times the last sample, unless its codec already states its duration: an end
599	/// rounded to the millisecond would cut a sub-millisecond Opus packet short.
600	#[test]
601	fn an_end_times_only_an_untimed_last_sample() {
602		let at = |micros| Timestamp::from_micros(micros).unwrap();
603		let video = [frame(0, true), frame(33_000, false)];
604		let fragment = video_muxer().fragment(0, &video, Some(at(66_000))).unwrap();
605		assert_eq!(super::super::sample_durations(&fragment), vec![Some(990), Some(990)]);
606
607		// 20 ms of 48 kHz Opus: TOC config 15 (SILK/WB 20 ms), one frame.
608		let opus = Muxer::audio(&AudioConfig::new(AudioCodec::Opus, 48_000, 2)).unwrap();
609		let packet = Frame {
610			timestamp: at(3_980_500),
611			decode: None,
612			payload: Bytes::from_static(&[0x78, 0x00, 0x00, 0x00]),
613			keyframe: true,
614			duration: None,
615		};
616		let fragment = opus.fragment(0, &[packet], Some(at(4_000_000))).unwrap();
617		assert_eq!(super::super::sample_durations(&fragment), vec![Some(960)]);
618	}
619
620	/// The end gap is measured at the output timescale, like the gaps between samples: one that
621	/// is no whole number of ticks still times the sample, and so does one finer than the
622	/// sample's own scale.
623	#[test]
624	fn an_end_is_quantized_at_the_output_timescale() {
625		let at = |micros| Timestamp::from_micros(micros).unwrap();
626		let video = [frame(0, true), frame(33_333, false)];
627		let fragment = video_muxer().fragment(0, &video, Some(at(66_666))).unwrap();
628		assert_eq!(
629			super::super::sample_durations(&fragment),
630			vec![Some(1_000), Some(1_000)]
631		);
632
633		let coarse = Frame {
634			timestamp: Timestamp::new(1, moq_net::Timescale::new(1).unwrap()).unwrap(),
635			..frame(0, true)
636		};
637		let fragment = video_muxer().fragment(0, &[coarse], Some(at(1_500_000))).unwrap();
638		assert_eq!(super::super::sample_durations(&fragment), vec![Some(15_000)]);
639	}
640
641	#[test]
642	fn ntsc_fallback_duration_uses_the_derived_timescale() {
643		let mut config = VideoConfig::new(VideoCodec::VP8);
644		config.framerate = Some(30_000.0 / 1001.0);
645		let muxer = Muxer::video(&config).unwrap();
646		assert_eq!(muxer.timescale().as_u64(), 30_000);
647
648		let frame = Frame {
649			timestamp: Timestamp::ZERO,
650			decode: None,
651			payload: Bytes::from_static(&[0xDE, 0xAD]),
652			keyframe: true,
653			duration: None,
654		};
655		let fragment = muxer.fragment(0, std::slice::from_ref(&frame), None).unwrap();
656		assert_eq!(super::super::sample_durations(&fragment), vec![Some(1001)]);
657	}
658
659	#[test]
660	fn microsecond_pts_quantize_without_timeline_drift() {
661		let muxer = video_muxer();
662		let input = [0, 33_333, 66_667].map(|micros| Frame {
663			timestamp: Timestamp::from_micros(micros).unwrap(),
664			decode: None,
665			payload: Bytes::from_static(&[0xDE, 0xAD]),
666			keyframe: micros == 0,
667			duration: None,
668		});
669
670		let fragment = muxer.fragment(0, &input, None).unwrap();
671		assert_eq!(super::super::sample_durations(&fragment), vec![Some(1_000); 3]);
672		assert_eq!(super::super::timeline(&fragment), (0, vec![0; 3]));
673	}
674
675	#[test]
676	fn low_framerate_fallback_fits_mp4_timing_fields() {
677		let mut config = VideoConfig::new(VideoCodec::VP8);
678		config.coded_width = Some(320);
679		config.coded_height = Some(240);
680		config.framerate = Some(0.0011);
681		let muxer = Muxer::video(&config).unwrap();
682		assert_eq!(muxer.timescale().as_u64(), 11);
683		assert!(muxer.init().unwrap().is_some());
684
685		let frame = Frame {
686			timestamp: Timestamp::ZERO,
687			decode: None,
688			payload: Bytes::from_static(&[0xDE, 0xAD]),
689			keyframe: true,
690			duration: None,
691		};
692		let fragment = muxer.fragment(0, &[frame], None).unwrap();
693		assert_eq!(super::super::sample_durations(&fragment), vec![Some(10_000)]);
694	}
695
696	#[test]
697	fn unusable_framerate_uses_the_standard_fallback_rate() {
698		let mut config = VideoConfig::new(VideoCodec::VP8);
699		config.framerate = Some(0.0005);
700		let muxer = Muxer::video(&config).unwrap();
701		let timescale = moq_net::Timescale::new(90_000).unwrap();
702		assert_eq!(muxer.timescale(), timescale);
703
704		let frame = Frame {
705			timestamp: Timestamp::ZERO,
706			decode: None,
707			payload: Bytes::from_static(&[0xDE, 0xAD]),
708			keyframe: true,
709			duration: None,
710		};
711		let decoded = super::super::decode(
712			muxer.fragment(0, &[frame], None).unwrap(),
713			None,
714			super::super::Track::new(timescale, crate::container::fmp4::Kind::Video),
715		)
716		.unwrap();
717		assert_eq!(decoded[0].duration.unwrap().as_scale(timescale).unwrap(), 3_000);
718	}
719
720	// A downstream timeline fixed at 90 kHz overrides the framerate-derived default, and the
721	// init and the fragments have to agree on it.
722	#[test]
723	fn with_timescale_overrides_the_catalog_derived_scale() {
724		let timescale = moq_net::Timescale::new(90_000).unwrap();
725		assert_eq!(video_muxer().timescale().as_u64(), 30_000, "framerate * 1000");
726
727		let muxer = video_muxer().with_timescale(timescale).unwrap();
728		assert_eq!(muxer.timescale(), timescale);
729
730		let init = muxer.init().unwrap().expect("init buildable for an out-of-band codec");
731		let trak = super::super::Wire::from_init(&init).unwrap();
732		assert_eq!(trak.trak().mdia.mdhd.timescale, 90_000);
733
734		// One 30 fps frame period is 3000 ticks at 90 kHz.
735		let frame = Frame {
736			timestamp: Timestamp::from_scale(3_000, 90_000).unwrap(),
737			decode: None,
738			payload: Bytes::from_static(&[0xDE, 0xAD]),
739			keyframe: true,
740			duration: Some(Timestamp::from_scale(3_000, 90_000).unwrap()),
741		};
742		let decoded = super::super::decode(
743			muxer.fragment(0, &[frame], None).unwrap(),
744			None,
745			super::super::Track::new(timescale, crate::container::fmp4::Kind::Video),
746		)
747		.unwrap();
748		assert_eq!(decoded[0].timestamp.as_micros().unwrap(), 33_333);
749	}
750
751	#[test]
752	fn with_timescale_recomputes_the_fallback_frame_duration() {
753		let timescale = moq_net::Timescale::new(90_000).unwrap();
754		let muxer = video_muxer().with_timescale(timescale).unwrap();
755		let frame = Frame {
756			timestamp: Timestamp::ZERO,
757			decode: None,
758			payload: Bytes::from_static(&[0xDE, 0xAD]),
759			keyframe: true,
760			duration: None,
761		};
762
763		let decoded = super::super::decode(
764			muxer.fragment(0, &[frame], None).unwrap(),
765			None,
766			super::super::Track::new(timescale, crate::container::fmp4::Kind::Video),
767		)
768		.unwrap();
769		assert_eq!(decoded[0].duration.unwrap().as_scale(timescale).unwrap(), 3_000);
770	}
771
772	// mdhd.timescale is 32 bits, but moq_net::Timescale spans the whole QUIC varint range. A
773	// wider scale used to truncate into the init while the fragments kept the full value,
774	// silently putting them on different timelines.
775	#[test]
776	fn with_timescale_rejects_a_scale_too_large_for_mdhd() {
777		let too_large = moq_net::Timescale::new(u64::from(u32::MAX) + 1).unwrap();
778		// Muxer isn't Debug, so match the Result rather than unwrap_err() it.
779		assert!(matches!(
780			video_muxer().with_timescale(too_large),
781			Err(crate::Error::Cmaf(Error::TimescaleTooLarge(_)))
782		));
783
784		// The largest scale the field can hold is still accepted.
785		let largest = moq_net::Timescale::new(u64::from(u32::MAX)).unwrap();
786		let muxer = video_muxer().with_timescale(largest).unwrap();
787		assert_eq!(muxer.timescale(), largest);
788	}
789
790	// The same truncation was reachable without with_timescale at all: the video timescale is
791	// `framerate * 1000`, so an absurd catalog framerate overflows the field on its own.
792	#[test]
793	fn init_rejects_a_catalog_scale_too_large_for_mdhd() {
794		let mut config = VideoConfig::new(VideoCodec::VP8);
795		config.coded_width = Some(320);
796		config.coded_height = Some(240);
797		config.framerate = Some(5_000_000.0); // 5e9 ticks, past u32::MAX
798		let err = Muxer::video(&config).unwrap().init().unwrap_err();
799		assert!(
800			matches!(err, crate::Error::Cmaf(Error::TimescaleTooLarge(_))),
801			"got {err:?}"
802		);
803	}
804
805	// A Cmaf rendition's init passes through from the catalog at its own scale, so an override
806	// would leave the init and the fragments on different timelines.
807	#[test]
808	fn with_timescale_rejects_a_cmaf_rendition() {
809		// Any valid single-track init will do; a synthesized one saves a fixture. Build it at
810		// 48 kHz so the scale can only have come from the init: the framerate below would
811		// otherwise derive 30_000, and the catalog carries no timescale of its own.
812		let init = video_muxer()
813			.with_timescale(moq_net::Timescale::new(48_000).unwrap())
814			.unwrap()
815			.init()
816			.unwrap()
817			.unwrap();
818		let mut config = VideoConfig::new(VideoCodec::VP8);
819		config.framerate = Some(30.0);
820		config.container = CatalogContainer::Cmaf { init };
821
822		let muxer = Muxer::video(&config).unwrap();
823		assert_eq!(muxer.timescale().as_u64(), 48_000, "read from the init segment");
824		assert!(muxer.with_timescale(moq_net::Timescale::new(90_000).unwrap()).is_err());
825	}
826
827	// The HLS origin accumulates every group of a (multi-group) audio segment into ONE fragment,
828	// and for audio those groups are often one packet each -- so every sample sits at a group
829	// boundary and none of them may borrow the next packet's timestamp (consecutive sequence
830	// numbers don't rule out a publisher pausing across the boundary). Opus stating its own
831	// duration is what keeps the whole run exact anyway, rather than dropping every packet onto
832	// the ~21.3 ms 1024/sample_rate fallback.
833	#[tokio::test]
834	async fn audio_fragment_takes_durations_from_the_codec() {
835		use hang::catalog::AudioCodec;
836
837		let config = AudioConfig::new(AudioCodec::Opus, 48_000, 2);
838		let muxer = Muxer::audio(&config).unwrap();
839
840		// 20 ms of 48 kHz Opus: TOC config 15 (SILK wideband, 20 ms), one frame per packet.
841		let packet = Bytes::from_static(&[0x78, 0x00, 0x00, 0x00]);
842		let frames: Vec<Frame> = (0..4)
843			.map(|i| Frame {
844				payload: packet.clone(),
845				..frame(i * 20_000, true)
846			})
847			.collect();
848		let fragment = muxer.fragment(0, &frames, None).unwrap();
849
850		let timescale = moq_net::Timescale::new(48_000).unwrap();
851		let decoded = super::super::decode(
852			fragment,
853			None,
854			super::super::Track::new(timescale, crate::container::fmp4::Kind::Video),
855		)
856		.unwrap();
857		assert_eq!(decoded.len(), 4);
858		for f in &decoded {
859			assert_eq!(
860				f.duration.unwrap().as_micros().unwrap(),
861				20_000,
862				"TOC duration, not the fallback"
863			);
864		}
865	}
866}