Skip to main content

moq_mux/container/fmp4/
mod.rs

1//! Fragmented MP4 (fMP4 / CMAF).
2//!
3//! A widely supported file format that's also a viable wire format.
4//! Each moq frame carries one moof+mdat fragment, optionally with
5//! several samples packed inside. [`Wire`] is the wire-level
6//! container; [`Import`] parses external fMP4 streams and [`Export`]
7//! produces them.
8
9mod edit;
10mod export;
11mod import;
12pub(crate) mod metadata;
13mod muxer;
14mod sample;
15mod text;
16
17pub use export::*;
18pub use import::*;
19pub use muxer::*;
20
21/// The largest text sample [`Import`] holds whole.
22///
23/// A text sample is rewritten only once its last byte arrives, so a larger one is refused before
24/// any of it is staged. It matches moq-net's 32 MiB frame bound,
25/// which the rewritten sample must fit.
26/// Media samples stream into their frames and have no such bound.
27const MAX_HELD_BYTES: usize = 32 * 1024 * 1024;
28
29/// The largest metadata box body parsed on import or from received CMAF.
30///
31/// A larger declaration is refused at its header, before buffering or expanding its body.
32/// Parsing expands a body up to tenfold (a 4-byte `trun` entry becomes a 40-byte
33/// [`TrunEntry`](mp4_atom::TrunEntry)), so this keeps a parse within [`MAX_HELD_BYTES`].
34/// Counts and retained metadata-tree entries are checked separately, including entries that
35/// consume no bytes. Media payloads in `mdat` keep their transport-owned bound.
36pub(crate) const MAX_METADATA_BYTES: usize = MAX_HELD_BYTES / 16;
37
38/// The most samples parsed or planned for one CMAF fragment.
39///
40/// Every sample's byte range is resolved before any of the fragment publishes, at about 200 bytes
41/// a sample, so a fragment at this bound plans within [`MAX_HELD_BYTES`]. A `moof` at
42/// [`MAX_METADATA_BYTES`] holds this many 16-byte `trun` entries. A shorter fragment is also held
43/// to one sample per metadata byte past the first 4,096.
44const MAX_FRAGMENT_SAMPLES: u64 = (MAX_METADATA_BYTES / 16) as u64;
45
46/// Samples a fragment may declare beyond one per byte of its metadata.
47///
48/// A `trun` entry is at least 4 bytes, so only a run without per-sample fields, which stores just
49/// a count, can declare more samples than it has bytes. Its plan is reserved before any payload
50/// arrives, so this keeps a few-byte `moof` from planning megabytes. A live fragment is a handful
51/// of samples.
52pub(crate) const FRAGMENT_SAMPLE_BASE: u64 = 4096;
53
54/// The most tracks [`Import`] accepts from one `moov`, refused before any is created.
55///
56/// Each track costs about 16 KiB to parse and set up, and keeps its catalog entry and output
57/// state for as long as the import runs. Real files declare a handful.
58const MAX_TRACKS: usize = 256;
59
60#[cfg(test)]
61mod export_test;
62#[cfg(test)]
63mod import_test;
64
65use std::time::Duration;
66
67use bytes::Bytes;
68use hang::catalog::{AudioCodec, AudioConfig, VideoCodec, VideoConfig};
69use mp4_atom::Atom;
70
71use moq_net::Timestamp;
72
73use crate::container::{Container, Frame};
74
75/// Fragmented MP4 parsing, muxing, and transport errors.
76#[derive(Debug, Clone, thiserror::Error)]
77#[non_exhaustive]
78pub enum Error {
79	/// Container display metadata has no valid catalog aspect ratio.
80	#[error("invalid display aspect: {0}")]
81	InvalidAspect(&'static str),
82
83	/// A subtitle sample cannot be reconstructed with valid text and timing.
84	#[error("invalid subtitle: {0}")]
85	InvalidSubtitle(&'static str),
86
87	/// Parsing or encoding an MP4 atom failed.
88	#[error("mp4: {0}")]
89	Mp4(#[source] std::sync::Arc<dyn std::error::Error + Send + Sync>),
90
91	/// A MoQ transport operation failed.
92	#[error("moq: {0}")]
93	Moq(#[from] moq_net::Error),
94
95	/// Parsing the FLAC configuration failed.
96	#[error("flac: {0}")]
97	Flac(#[from] crate::codec::flac::Error),
98
99	/// Parsing or encoding the Opus configuration failed.
100	#[error("opus: {0}")]
101	Opus(#[from] crate::codec::opus::Error),
102
103	/// A group was opened without a keyframe.
104	#[error("missing keyframe: a group must open on a keyframe")]
105	MissingKeyframe(#[from] crate::container::MissingKeyframe),
106
107	/// An explicit video endpoint precedes its last frame.
108	#[error("{0}")]
109	InvalidEnd(#[from] crate::container::InvalidEnd),
110
111	/// A frame's timestamp sits below the live edge earlier groups reached.
112	#[error("{0}")]
113	TimestampRewind(#[from] crate::container::TimestampRewind),
114
115	/// A timestamp calculation overflowed.
116	#[error("timestamp overflow")]
117	TimestampOverflow(#[from] moq_net::TimeOverflow),
118
119	/// The fragment has no traf box.
120	#[error("no traf in moof")]
121	NoTraf,
122
123	/// The track fragment has no tfdt box.
124	#[error("no tfdt in traf")]
125	NoTfdt,
126
127	/// The presentation timestamp calculation overflowed.
128	#[error("PTS overflow")]
129	PtsOverflow,
130
131	/// The fragment has no moof box.
132	#[error("missing moof")]
133	NoMoof,
134
135	/// The fragment has no mdat box.
136	#[error("missing mdat")]
137	NoMdat,
138
139	/// The initialization segment has no moov box.
140	#[error("missing moov")]
141	NoMoov,
142
143	/// The moov box has no tracks.
144	#[error("no tracks in moov")]
145	NoTracks,
146
147	/// The moov box has multiple tracks where only one is supported.
148	#[error("multiple tracks in moov, use Trak instead")]
149	MultipleTracks,
150
151	/// The named codec cannot supply a synthesized CMAF initialization segment.
152	#[error("can't synthesize CMAF init for {0}")]
153	UnsupportedSynthesis(String),
154
155	/// The track handler declares unsupported subtitle media.
156	#[error("subtitle tracks are not supported")]
157	UnsupportedSubtitle,
158
159	/// The track handler has an unrecognized four-character code.
160	#[error("unknown track handler: {0:?}")]
161	UnknownTrackHandler([u8; 4]),
162
163	/// The sample description has no codec entry.
164	#[error("missing codec")]
165	MissingCodec,
166
167	/// The sample description has multiple codec entries.
168	#[error("multiple codecs")]
169	MultipleCodecs,
170
171	/// The sample entry has an unrecognized codec, named by its four-character code.
172	#[error("unknown codec: {0}")]
173	UnknownCodec(String),
174
175	/// A `colr` box code point past H.273's 255.
176	#[error("invalid colr code point: {0}")]
177	InvalidColr(u16),
178
179	/// A Spherical Video V2 `sv3d` or `st3d` box the catalog cannot describe, or a malformed one.
180	#[error("unsupported spherical video: {0}")]
181	UnsupportedSpatial(&'static str),
182
183	/// The sample entry declares a codec moq-mux does not carry, named by its four-character code.
184	#[error("unsupported codec: {0}")]
185	UnsupportedCodec(String),
186
187	/// The sample entry declares unsupported MPEG-2 media.
188	#[error("unsupported codec: MPEG2")]
189	UnsupportedMpeg2,
190
191	/// An AAC sample entry needs DecoderSpecificInfo to identify its codec profile.
192	#[error("AAC sample entry missing DecoderSpecificInfo")]
193	MissingDecoderSpecific,
194
195	/// A second moof box arrived before the preceding fragment was complete.
196	#[error("duplicate moof")]
197	DuplicateMoof,
198
199	/// A second moov would re-declare the track set the first one already declared.
200	#[error("duplicate moov")]
201	DuplicateMoov,
202
203	/// The track fragment has no trun box.
204	#[error("missing trun")]
205	MissingTrun,
206
207	/// The track fragment has no decode-time box.
208	#[error("missing tfdt")]
209	MissingTfdt,
210
211	/// The named video codec lacks the configuration needed to synthesize a CMAF init.
212	#[error("video codec {0} needs a description (codec config record) to synthesize a CMAF init")]
213	MissingVideoDescription(String),
214
215	/// A synthesized video track has no usable encoded dimensions.
216	#[error("missing video dimensions for codec: {0}")]
217	MissingVideoDimensions(String),
218
219	/// The fragment data offset cannot address its sample data.
220	#[error("invalid data offset")]
221	InvalidDataOffset,
222
223	/// Streaming import requires each track's sample bytes in decode order.
224	#[error("backwards per-track data offset is unsupported for streaming import")]
225	BackwardsDataOffset,
226
227	/// A metadata body over 2 MiB is refused before parsing.
228	#[error("{kind} declares {size} bytes, more than the {MAX_METADATA_BYTES} a metadata parser accepts")]
229	MetadataTooLarge {
230		/// The box type's four-character code.
231		kind: String,
232		/// The body size its header declares.
233		size: usize,
234	},
235
236	/// A text sample is rewritten whole, so one larger than moq-net's 32 MiB frame bound
237	/// is refused before any of its bytes
238	/// are staged.
239	#[error("text sample of {0} bytes is more than the {MAX_HELD_BYTES} an importer holds")]
240	TextSampleTooLarge(usize),
241
242	/// A fragment declaring more than 131,072 samples, or more than one sample per byte
243	/// of its metadata past a small base, is refused before parsing. A `trun` without per-sample
244	/// fields declares its count in four bytes, so the byte bound alone does not limit it.
245	#[error("moof declares {0} samples, more than a fragment of its size accepts")]
246	TooManySamples(u64),
247
248	/// A `moov` declaring more than 256 tracks is refused before any is created.
249	#[error("moov declares {0} tracks, more than the {MAX_TRACKS} an importer accepts")]
250	TooManyTracks(usize),
251
252	/// Absolute file offsets cannot be resolved in a standalone fragment.
253	#[error("absolute base_data_offset is unsupported; use moof-relative offsets")]
254	UnsupportedBaseDataOffset,
255
256	/// Every media sample must contain at least one byte.
257	#[error("empty media sample")]
258	EmptySample,
259
260	/// The frame timestamp carries a fragment's earliest presentation time exactly only when the
261	/// track counts in the same ticks as the media.
262	#[error("track timescale {track:?} doesn't match the CMAF mdhd timescale {mdhd:?}")]
263	TimescaleMismatch {
264		/// The timescale declared by the MoQ track, if any.
265		track: Option<moq_net::Timescale>,
266		/// The media timescale declared by the mdhd box.
267		mdhd: moq_net::Timescale,
268	},
269
270	/// The fragment references an undeclared track ID.
271	#[error("unknown track {0}")]
272	UnknownTrack(u32),
273
274	/// The first sample in the group is not a keyframe.
275	#[error("no keyframe at start of group")]
276	NoKeyframe,
277
278	/// The sample byte range extends outside the mdat payload.
279	#[error("track sample range {start}..{end} is out of bounds of mdat (len {len})")]
280	SampleRangeOutOfBounds {
281		/// The first sample byte offset in the mdat payload.
282		start: usize,
283		/// The exclusive end offset in the mdat payload.
284		end: usize,
285		/// The mdat payload length in bytes.
286		len: usize,
287	},
288
289	/// Fragment encoding was requested with no frames.
290	#[error("encode_fragment called with no frames")]
291	NoFrames,
292
293	/// The named audio codec lacks the configuration needed to synthesize a CMAF init.
294	#[error("audio codec {0} needs a description (AudioSpecificConfig) to synthesize a CMAF init")]
295	MissingAudioDescription(String),
296
297	/// An Opus catalog entry whose OpusHead contradicts its channel count.
298	#[error("Opus head has {head} channels but the catalog declares {catalog}")]
299	OpusChannelCount {
300		/// The channel count declared by the catalog.
301		catalog: u32,
302		/// The channel count declared by the OpusHead.
303		head: u32,
304	},
305
306	/// An audio config whose sample rate or channel count is zero, or whose channel count does
307	/// not fit a sample entry's 16-bit field.
308	#[error("audio config of {sample_rate} Hz and {channel_count} channels does not fit a sample entry")]
309	InvalidAudioConfig {
310		/// The catalog sample rate.
311		sample_rate: u32,
312		/// The catalog channel count.
313		channel_count: u32,
314	},
315
316	/// A non-final sample has no duration, so its decode timeline cannot be recovered.
317	#[error("multi-sample fragment has a non-final sample with no duration; DTS is unrecoverable")]
318	MissingSampleDuration,
319
320	/// `mdhd.timescale` is a 32-bit field, so a larger scale would reach the init segment
321	/// truncated while the fragments kept the full value, putting them on different timelines.
322	#[error("timescale {0} does not fit the 32-bit mdhd field")]
323	TimescaleTooLarge(u64),
324
325	/// A `Cmaf` rendition's init passes through from the catalog at its own scale, so
326	/// [`Muxer::with_timescale`] can't move it without desynchronising it from the fragments.
327	#[error("a CMAF rendition's timescale comes from its init segment and can't be overridden")]
328	TimescaleOverride,
329
330	/// A sample duration is a 32-bit `trun` field. A larger value would wrap in the media
331	/// while the fragment metadata kept the full duration, putting them on different timelines.
332	#[error("sample duration {0} does not fit the 32-bit trun field")]
333	SampleDurationTooLarge(u64),
334
335	/// A positive sample duration must occupy at least one tick in the output timescale.
336	#[error("sample duration is shorter than one tick at timescale {0}")]
337	SampleDurationTooSmall(u64),
338
339	/// Repeatedly flooring fractional sample ticks would make the decode timeline drift.
340	#[error("sample duration is not exactly representable at timescale {0}")]
341	SampleDurationInexact(u64),
342
343	/// Presentation timestamps do not reveal decode duration for reordered video.
344	#[error("duration-less video needs stated durations or presentation-ordered inference")]
345	MissingVideoDuration,
346
347	/// Each fragment restates its decode time, so a stale one lands two different samples on
348	/// the same timestamp. ffmpeg writes one when `frag_every_frame` interleaves audio and
349	/// video; `-frag_duration` cuts just as finely and stamps the fragments correctly.
350	#[error(
351		"track {track}: fragment decode time {decode_time:?} does not advance past {previous:?}; \
352		 ffmpeg repeats a tfdt when frag_every_frame interleaves audio and video, use -frag_duration instead"
353	)]
354	NonMonotonicDecodeTime {
355		/// The track containing the rejected fragment.
356		track: u32,
357		/// The rejected fragment's decode time in the track's timescale.
358		decode_time: moq_net::Timestamp,
359		/// The preceding fragment's decode time in the track's timescale.
360		previous: moq_net::Timestamp,
361	},
362
363	/// The init segment fixes the track set, so a rendition that joins later can't be written,
364	/// unless it continues a declared track of its medium that failed.
365	#[error("rendition {0} joined after the init segment; restart the export to include it")]
366	TrackAdded(String),
367
368	/// A rendition's sample entry no longer matches the one the init segment declared.
369	#[error("rendition {0} changed its codec configuration after it was declared")]
370	TrackChanged(String),
371
372	/// A rendition restarted at or before media already written for it, such as a
373	/// resubscription replaying cached groups.
374	#[error("rendition {track} went back in time: a fragment starts at {start:?}, after {written:?} was written")]
375	TrackRewound {
376		/// The rendition name.
377		track: String,
378		/// The rejected fragment's presentation time.
379		start: std::time::Duration,
380		/// The latest presentation time already written for the rendition.
381		written: std::time::Duration,
382	},
383
384	/// The init segment waited too long, or the broadcast ended, before these renditions
385	/// delivered the codec configuration their track needs.
386	#[error("renditions {0:?} never delivered their codec configuration")]
387	TrackUndescribed(Vec<String>),
388
389	/// A track's edit list does more than delay the track and start its media at one time.
390	#[error("unsupported edit list: {0}")]
391	UnsupportedEditList(&'static str),
392
393	/// A fragment written to a regular MP4 can't be indexed in its final `moov`.
394	#[error("track {track} can't be indexed: {reason}")]
395	Unindexable {
396		/// The fragment's track id.
397		track: u32,
398		/// What the sample tables can't express.
399		reason: &'static str,
400	},
401
402	/// A regular MP4's chapter list holds 255 chapters.
403	#[error("{0} chapters, more than the 255 a chapter list holds")]
404	TooManyChapters(usize),
405
406	/// A regular MP4's chapter list holds titles of 255 bytes.
407	#[error("a chapter title of {0} bytes, more than the 255 a chapter list holds")]
408	ChapterTitleTooLong(usize),
409
410	/// A file to repair is not a recording that an MP4 export left unfinished.
411	#[error("not an unfinished mp4 recording: {0}")]
412	Unrepairable(&'static str),
413}
414
415impl Error {
416	/// An mp4 atom error, kept opaque so an mp4-atom bump is no moq-mux break.
417	pub(crate) fn mp4(err: mp4_atom::Error) -> Self {
418		Error::Mp4(std::sync::Arc::new(err))
419	}
420
421	/// A sample entry this crate does not carry, named by the four-character code it encodes with.
422	pub(crate) fn unsupported_codec(codec: &mp4_atom::Codec) -> Self {
423		use mp4_atom::Encode;
424		let mut buf = Vec::new();
425		let name = match codec.encode(&mut buf) {
426			Ok(()) if buf.len() >= 8 => String::from_utf8_lossy(&buf[4..8]).into_owned(),
427			_ => "?".to_string(),
428		};
429		Error::UnsupportedCodec(name)
430	}
431}
432
433/// A result using this module's error type.
434pub type Result<T> = std::result::Result<T, Error>;
435
436/// The media carried by a CMAF track.
437#[derive(Debug, Clone, Copy, PartialEq, Eq)]
438pub(crate) enum Kind {
439	Audio,
440	Video,
441}
442
443impl Kind {
444	fn from_handler(handler: mp4_atom::FourCC) -> Result<Self> {
445		match handler.as_ref() {
446			b"soun" => Ok(Self::Audio),
447			b"vide" => Ok(Self::Video),
448			b"sbtl" => Err(Error::UnsupportedSubtitle),
449			_ => Err(Error::UnknownTrackHandler(handler.into())),
450		}
451	}
452
453	/// The publisher priority for this kind of media.
454	fn priority(self) -> i8 {
455		match self {
456			Self::Video => hang::catalog::PRIORITY.video,
457			Self::Audio => hang::catalog::PRIORITY.audio,
458		}
459	}
460}
461
462/// CMAF container: encodes/decodes a single track's moof+mdat fragments.
463///
464/// Build from a CMAF init segment with [`Wire::from_init`], which refuses a track that is
465/// neither audio nor video.
466///
467/// The parsed track is heap-allocated so that embedding `Wire`
468/// in other enums (e.g. [`catalog::hang::Wire`](crate::catalog::hang::Wire))
469/// doesn't bloat unrelated variants.
470pub struct Wire {
471	trak: Box<mp4_atom::Trak>,
472	defaults: sample::Defaults,
473	kind: Kind,
474}
475
476impl Wire {
477	/// Wrap an already-parsed track, with no `trex` for its samples to fall back to.
478	#[cfg(test)]
479	pub(crate) fn new(trak: mp4_atom::Trak) -> Result<Self> {
480		Ok(Self {
481			kind: Kind::from_handler(trak.mdia.hdlr.handler)?,
482			trak: Box::new(trak),
483			defaults: sample::Defaults::default(),
484		})
485	}
486
487	/// Parse a CMAF init segment (ftyp+moov), extracting the single track and its `trex` defaults.
488	pub fn from_init(init_data: &[u8]) -> Result<Self> {
489		metadata::check(init_data)?;
490		use mp4_atom::DecodeMaybe;
491
492		let mut cursor = std::io::Cursor::new(init_data);
493		while let Some(atom) = mp4_atom::Any::decode_maybe(&mut cursor).map_err(crate::container::fmp4::Error::mp4)? {
494			if let mp4_atom::Any::Moov(mut moov) = atom {
495				let trak = match moov.trak.len() {
496					1 => moov.trak.remove(0),
497					0 => return Err(Error::NoTracks),
498					_ => return Err(Error::MultipleTracks),
499				};
500				let defaults = sample::Defaults::from_moov(&moov, trak.tkhd.track_id);
501				return Ok(Self {
502					kind: Kind::from_handler(trak.mdia.hdlr.handler)?,
503					trak: Box::new(trak),
504					defaults,
505				});
506			}
507		}
508		Err(Error::NoMoov)
509	}
510
511	/// Borrow the MP4 track atom describing this wire container.
512	#[cfg(test)]
513	pub(crate) fn trak(&self) -> &mp4_atom::Trak {
514		&self.trak
515	}
516
517	/// The media timescale, which a CMAF track must count in.
518	pub(crate) fn timescale(&self) -> Result<moq_net::Timescale> {
519		Ok(moq_net::Timescale::new(self.trak.mdia.mdhd.timescale as u64)?)
520	}
521
522	/// What decoding this track's fragments needs.
523	fn track(&self) -> Result<Track> {
524		Ok(Track {
525			timescale: self.timescale()?,
526			kind: self.kind,
527			defaults: self.defaults,
528		})
529	}
530}
531
532impl Container for Wire {
533	fn kind(&self) -> crate::container::Kind {
534		match self.kind {
535			Kind::Audio => crate::container::Kind::Audio,
536			Kind::Video => crate::container::Kind::Video,
537		}
538	}
539
540	type Error = Error;
541
542	fn write(
543		&self,
544		group: &mut crate::container::Writer<'_>,
545		frames: &[Frame],
546	) -> std::result::Result<(), Self::Error> {
547		let timescale = self.timescale()?;
548		if group.timescale() != Some(timescale) {
549			return Err(Error::TimescaleMismatch {
550				track: group.timescale(),
551				mdhd: timescale,
552			});
553		}
554		let track_id = self.trak.tkhd.track_id;
555		encode(
556			group,
557			frames,
558			FragmentInfo {
559				timescale,
560				track_id,
561				sequence_number: group.frame_count() as u32,
562				kind: self.kind,
563			},
564		)
565	}
566
567	fn decode(&self, frame: moq_net::frame::Frame) -> std::result::Result<Vec<Frame>, Self::Error> {
568		// CMAF carries no data track, so an object with no bytes is no marker and fails to decode.
569		// A scale-less track's unscaled key is no broadcast time, so its samples keep their `tfdt`.
570		let timestamp = frame.timestamp.scale().map(|_| frame.timestamp);
571		decode(frame.payload, timestamp, self.track()?)
572	}
573}
574
575/// What decoding a track's fragments needs from its init segment.
576#[derive(Debug, Clone, Copy)]
577pub(crate) struct Track {
578	/// The `mdhd` timescale the samples count in.
579	pub timescale: moq_net::Timescale,
580	/// Whether the samples are audio or video.
581	pub kind: Kind,
582	/// The `trex` values a sample falls back to.
583	pub defaults: sample::Defaults,
584}
585
586#[cfg(test)]
587impl Track {
588	/// A track whose fragments carry every sample value, as `encode` writes them.
589	pub fn new(timescale: moq_net::Timescale, kind: Kind) -> Self {
590		Self {
591			timescale,
592			kind,
593			defaults: Default::default(),
594		}
595	}
596}
597
598/// Decode one moof+mdat fragment into its samples.
599///
600/// Each sample's size, duration, and flags resolve through [`sample::Defaults`], and a video
601/// sample is a keyframe when [`sample::Sample::is_sync`].
602///
603/// `Kind::Audio` says the track's samples are all independently decodable. Packagers flag every
604/// audio sample a sync sample, which as a [`Frame::keyframe`] would open a group per sample,
605/// so an audio sample decodes with the bit clear and the consumer marks the group start.
606///
607/// `timestamp` is the moq-lite frame timestamp, which is the broadcast timeline: the fragment's
608/// earliest sample presents at it. `tfdt` and the `trun` offsets only place the samples relative
609/// to each other, since a publisher may move a passthrough track to another timeline without
610/// rewriting the payload. A scale-less track's frame (`None`) has no broadcast time, so its samples
611/// present at the time `tfdt` gives them.
612pub(crate) fn decode(data: Bytes, timestamp: Option<Timestamp>, track: Track) -> Result<Vec<Frame>> {
613	metadata::check(&data)?;
614	use mp4_atom::DecodeMaybe;
615
616	let Track {
617		timescale,
618		kind,
619		defaults,
620	} = track;
621
622	// A slice cursor like the other fMP4 decodes: mp4-atom's `Any` decoder is large and compiles
623	// once per reader type.
624	let mut cursor = std::io::Cursor::new(data.as_ref());
625	let mut moof = None;
626	let mut mdat = None;
627
628	loop {
629		let start = cursor.position() as usize;
630		let Some(atom) = mp4_atom::Any::decode_maybe(&mut cursor).map_err(crate::container::fmp4::Error::mp4)? else {
631			break;
632		};
633		match atom {
634			mp4_atom::Any::Moof(m) => moof = Some((start, m)),
635			mp4_atom::Any::Mdat(m) => mdat = Some((cursor.position() as usize - m.data.len(), m.data)),
636			_ => {}
637		}
638	}
639
640	let (moof_start, moof) = moof.ok_or(Error::NoMoof)?;
641	let (mdat_start, mdat_data) = mdat.ok_or(Error::NoMdat)?;
642	let traf = moof.traf.first().ok_or(Error::NoTraf)?;
643
644	let data_start = mdat_start.checked_sub(moof_start).ok_or(Error::InvalidDataOffset)?;
645	let tfdt = traf.tfdt.as_ref().ok_or(Error::NoTfdt)?;
646	let base_dts = tfdt.base_media_decode_time;
647	let mut resolver = sample::Resolver::new(data_start, mdat_data.len());
648
649	// Rounded the way `encode` stamps it, so a timestamp the track carried at another scale
650	// lands back on the tick it was written at.
651	let anchor = timestamp.map(|t| timestamp_ticks(t, timescale)).transpose()?;
652
653	let mut frames = Vec::new();
654	let mut ptss = Vec::new();
655	let mut dts = i128::from(base_dts);
656	for resolved in resolver.resolve(traf, defaults)? {
657		let sample::Resolved { sample, cts, range } = resolved?;
658		ptss.push(dts + i128::from(cts));
659		let payload = Bytes::copy_from_slice(&mdat_data[range]);
660		let keyframe = kind == Kind::Video && sample.is_sync();
661		let duration = sample
662			.duration
663			.map(|d| Timestamp::new(d as u64, timescale))
664			.transpose()?;
665		frames.push(Frame {
666			// Placeholder until the earliest PTS is known.
667			timestamp: Timestamp::ZERO,
668			decode: None,
669			payload,
670			keyframe,
671			duration,
672		});
673		dts += i128::from(sample.duration.unwrap_or(0));
674	}
675
676	let (anchor, earliest) = match anchor {
677		Some(anchor) => (anchor, ptss.iter().copied().min().unwrap_or_default()),
678		None => (0, 0),
679	};
680	for (frame, pts) in frames.iter_mut().zip(ptss) {
681		let ticks = u64::try_from(pts - earliest)
682			.ok()
683			.and_then(|offset| anchor.checked_add(offset))
684			.ok_or(Error::PtsOverflow)?;
685		// Preserve the fmp4 track's native scale through the pipeline.
686		frame.timestamp = Timestamp::new(ticks, timescale)?;
687	}
688
689	Ok(frames)
690}
691
692fn encode(group: &mut crate::container::Writer<'_>, frames: &[Frame], info: FragmentInfo) -> Result<()> {
693	// The fragment may carry several samples; the net frame's timestamp is the
694	// fragment's earliest presentation time, which `decode` anchors its samples to.
695	// It is rounded to the track's ticks the same way the samples are, so the two agree.
696	let Some(earliest) = frames
697		.iter()
698		.map(|f| f.timestamp)
699		.reduce(|earliest, timestamp| if timestamp < earliest { timestamp } else { earliest })
700	else {
701		return Ok(());
702	};
703	let timestamp = Timestamp::new(timestamp_ticks(earliest, info.timescale)?, info.timescale)?;
704
705	let bytes = encode_fragment(info, frames)?;
706	group.write_frame(timestamp, bytes)?;
707
708	Ok(())
709}
710
711/// Which track a fragment belongs to, and where it sits in that track.
712///
713/// Bundled rather than passed positionally because `track_id` and `sequence_number` are both
714/// `u32`, so a swapped pair would still compile.
715#[derive(Debug, Clone, Copy)]
716pub(crate) struct FragmentInfo {
717	/// The `tfhd` track id, which must match the one the init segment declares.
718	pub track_id: u32,
719	/// The track's media timescale, which every timestamp is re-expressed at.
720	pub timescale: moq_net::Timescale,
721	/// The `mfhd` sequence number, informative only.
722	pub sequence_number: u32,
723	/// Audio tracks carry only sync samples: the [`Frame::keyframe`]
724	/// bit only marks the group start there, so it must not decide the sample flags.
725	pub kind: Kind,
726}
727
728/// Encode a single-traf moof+mdat fragment anchored at its own first frame.
729///
730/// The fragment stands alone: its `tfdt` is `frames[0]`'s presentation time, so it decodes
731/// without reference to whatever came before it.
732///
733/// Returns an empty `Bytes` when `frames` is empty.
734pub(crate) fn encode_fragment(info: FragmentInfo, frames: &[Frame]) -> Result<Bytes> {
735	let Some(first) = frames.first() else {
736		return Ok(Bytes::new());
737	};
738	Ok(encode_at(info, base_ticks(first, info.timescale)?, frames)?.0)
739}
740
741/// A frame's presentation time as a tick count at the track's timescale.
742///
743/// When the importer preserved the source scale (the common passthrough case) this is a no-op;
744/// otherwise it's a single rescale rather than the legacy `micros * scale / 1_000_000`
745/// round-trip.
746fn base_ticks(frame: &Frame, timescale: moq_net::Timescale) -> Result<u64> {
747	timestamp_ticks(frame.timestamp, timescale)
748}
749
750/// Round an absolute timestamp to its nearest tick at the output scale. Refuses an
751/// [unscaled](Timestamp::unscaled) one, which has no time.
752fn timestamp_ticks(timestamp: Timestamp, timescale: moq_net::Timescale) -> Result<u64> {
753	let source_scale = u128::from(timestamp.scale().ok_or(moq_net::TimeOverflow)?.as_u64());
754	let scaled = u128::from(timestamp.value()) * u128::from(timescale.as_u64());
755	let ticks = (scaled + source_scale / 2) / source_scale;
756	u64::try_from(ticks).map_err(|_| Error::PtsOverflow)
757}
758
759/// Encode a single-traf moof+mdat fragment whose decode timeline starts at `base_dts` ticks.
760///
761/// Performs the two-pass encoding required by ISO/IEC 14496-12: encode once
762/// to learn the moof size, then again with `trun.data_offset` pointing past
763/// the moof and mdat header.
764///
765/// `base_dts` is already at the track's timescale, so it is the same unit the `trun` sample
766/// durations are written in. That's what lets [`Export`] carry a timeline across
767/// calls without a rounding step between them.
768///
769/// Frames arrive in decode order carrying presentation timestamps. DTS is authored by
770/// accumulating sample durations from `base_dts`, and each sample stores `PTS - DTS` as its
771/// signed composition offset, so a reordered frame keeps its presentation time even when the
772/// fragment holds a single sample.
773///
774/// Returns the fragment with the decode time it ends at, which is where the next fragment on
775/// the same timeline continues, or an empty `Bytes` and `base_dts` when `frames` is empty.
776pub(super) fn encode_at(info: FragmentInfo, base_dts: u64, frames: &[Frame]) -> Result<(Bytes, u64)> {
777	let FragmentInfo {
778		track_id,
779		timescale,
780		sequence_number,
781		kind,
782	} = info;
783
784	use mp4_atom::Encode;
785
786	if frames.is_empty() {
787		return Ok((Bytes::new(), base_dts));
788	}
789
790	let mut dts = base_dts;
791
792	let entries: Vec<_> = frames
793		.iter()
794		.map(|f| {
795			let flags = if kind == Kind::Audio || f.keyframe {
796				0x0200_0000
797			} else {
798				0x0001_0000
799			};
800			// Write the sample-duration back at the track's scale when we know it, so
801			// fMP4 -> fMP4 round-trips it. Frames without one stay byte-identical.
802			let duration = f.duration.map(|d| trun_duration(d, timescale)).transpose()?;
803			let pts = i128::from(timestamp_ticks(f.timestamp, timescale)?);
804			let cts = pts - i128::from(dts);
805			let cts = i32::try_from(cts).map_err(|_| Error::PtsOverflow)?;
806
807			// Frame timestamps are PTS while sample order is decode order. Author DTS
808			// by accumulating durations and store PTS-DTS as the signed CTS.
809			if let Some(duration) = duration {
810				dts = dts.checked_add(u64::from(duration)).ok_or(Error::PtsOverflow)?;
811			}
812
813			Ok(mp4_atom::TrunEntry {
814				duration,
815				size: Some(f.payload.len() as u32),
816				flags: Some(flags),
817				cts: (cts != 0).then_some(cts.into()),
818			})
819		})
820		.collect::<Result<_>>()?;
821
822	let mdat_data: Vec<u8> = frames.iter().flat_map(|f| f.payload.iter().copied()).collect();
823
824	let build_moof = |data_offset| mp4_atom::Moof {
825		mfhd: mp4_atom::Mfhd { sequence_number },
826		traf: vec![mp4_atom::Traf {
827			tfhd: mp4_atom::Tfhd {
828				track_id,
829				..Default::default()
830			},
831			tfdt: Some(mp4_atom::Tfdt {
832				base_media_decode_time: base_dts,
833			}),
834			trun: vec![mp4_atom::Trun {
835				data_offset: Some(data_offset),
836				samples: entries.clone().into(),
837			}],
838			..Default::default()
839		}],
840	};
841
842	// First pass to learn the moof size.
843	let mut buf = Vec::new();
844	build_moof(0)
845		.encode(&mut buf)
846		.map_err(crate::container::fmp4::Error::mp4)?;
847	let moof_size = buf.len();
848
849	// Second pass with data_offset = moof_size + 8 (mdat header).
850	buf.clear();
851	build_moof((moof_size + 8) as i32)
852		.encode(&mut buf)
853		.map_err(crate::container::fmp4::Error::mp4)?;
854
855	let mdat = mp4_atom::Mdat { data: mdat_data };
856	mdat.encode(&mut buf).map_err(crate::container::fmp4::Error::mp4)?;
857
858	Ok((Bytes::from(buf), dts))
859}
860
861/// Convert a duration to the exact value stored in a 32-bit `trun` sample-duration field.
862fn trun_duration(duration: Timestamp, timescale: moq_net::Timescale) -> Result<u32> {
863	let source_timescale = duration.scale().ok_or(moq_net::TimeOverflow)?.as_u64();
864	let output_timescale = timescale.as_u64();
865	let scaled = u128::from(duration.value()) * u128::from(output_timescale);
866	let ticks = scaled / u128::from(source_timescale);
867	if !duration.is_zero() && ticks == 0 {
868		return Err(Error::SampleDurationTooSmall(timescale.as_u64()));
869	}
870	if scaled % u128::from(source_timescale) != 0 {
871		return Err(Error::SampleDurationInexact(output_timescale));
872	}
873	u32::try_from(ticks).map_err(|_| Error::SampleDurationTooLarge(u64::try_from(ticks).unwrap_or(u64::MAX)))
874}
875
876/// Synthesize a CMAF `Trak` for a video rendition that has no init segment.
877///
878/// Used by the fMP4 exporter when its source is a `Container::Legacy` or `Loc`
879/// track. H.264/H.265 need a configuration record (`description`). When the
880/// catalog codec string determined that record, it lists no parameter sets and
881/// the sample entry is avc3 or hev1; the sets stay in the samples. A record built
882/// from the bitstream still carries them. VP8 carries no out-of-band config, so
883/// `description` is `None` for it.
884/// The colour an ISOBMFF `colr` box signals. `nclx` carries H.273 code points and a range,
885/// QuickTime's `nclc` the code points alone, and an ICC profile none at all. A code point past 255
886/// has no H.273 meaning, so it is refused.
887pub(crate) fn colr_color(colr: &mp4_atom::Colr) -> Result<Option<hang::catalog::Color>> {
888	let (primaries, transfer, matrix, full_range) = match *colr {
889		mp4_atom::Colr::Nclx {
890			colour_primaries,
891			transfer_characteristics,
892			matrix_coefficients,
893			full_range_flag,
894		} => (
895			colour_primaries,
896			transfer_characteristics,
897			matrix_coefficients,
898			Some(full_range_flag),
899		),
900		mp4_atom::Colr::Nclc {
901			colour_primaries,
902			transfer_characteristics,
903			matrix_coefficients,
904		} => (colour_primaries, transfer_characteristics, matrix_coefficients, None),
905		_ => return Ok(None),
906	};
907	let code = |value: u16| u8::try_from(value).map_err(|_| Error::InvalidColr(value));
908	Ok(crate::codec::color::cicp(
909		code(primaries)?,
910		code(transfer)?,
911		code(matrix)?,
912		full_range,
913	))
914}
915
916/// The projection and stereo packing Spherical Video V2's `sv3d` and `st3d` boxes signal, each
917/// `None` for flat or mono video. Apple's `vexu` and `hfov` are not read.
918///
919/// The catalog has no cubemap, mesh, pose, or eye order beyond left-right and top-bottom, and an
920/// absent field claims flat, mono video, so those are refused rather than dropped. So is a box the
921/// sample entry repeats or could not decode, since it may say any of them.
922pub(crate) fn spatial(
923	spatial: Option<&mp4_atom::Spatial>,
924) -> Result<(Option<hang::catalog::Projection>, Option<hang::catalog::Stereo>)> {
925	use mp4_atom::{Atom, Cbmp, Equi, Mshp, Prhd, Proj, ProjKind, St3d, Sv3d};
926
927	let Some(spatial) = spatial else {
928		return Ok((None, None));
929	};
930	let unsupported = |reason| Err(Error::UnsupportedSpatial(reason));
931	let kept =
932		|unknown: &[mp4_atom::Any], kinds: &[mp4_atom::FourCC]| unknown.iter().any(|atom| kinds.contains(&atom.kind()));
933	if kept(&spatial.unknown, &[St3d::KIND, Sv3d::KIND]) {
934		return unsupported("repeated or malformed st3d or sv3d");
935	}
936
937	let stereo = match spatial.st3d.map(|st3d| st3d.stereo_mode) {
938		None | Some(St3d::MONO) => None,
939		Some(St3d::LEFT_RIGHT) => Some(hang::catalog::Stereo::LeftRight),
940		Some(St3d::TOP_BOTTOM) => Some(hang::catalog::Stereo::TopBottom),
941		Some(_) => return unsupported("stereo mode"),
942	};
943
944	let Some(sv3d) = &spatial.sv3d else {
945		return Ok((None, stereo));
946	};
947	if kept(&sv3d.unknown, &[Proj::KIND]) {
948		return unsupported("repeated or malformed proj");
949	}
950	let proj = sv3d
951		.proj
952		.as_ref()
953		.ok_or(Error::UnsupportedSpatial("sv3d without proj"))?;
954	if kept(&proj.unknown, &[Prhd::KIND, Equi::KIND, Cbmp::KIND, Mshp::KIND]) {
955		return unsupported("repeated or malformed projection");
956	}
957	if let Some(prhd) = proj.prhd
958		&& (prhd.pose_yaw_degrees, prhd.pose_pitch_degrees, prhd.pose_roll_degrees) != (0, 0, 0)
959	{
960		return unsupported("nonzero pose");
961	}
962	let projection = match &proj.kind {
963		Some(ProjKind::Equi(equi)) => crate::codec::spatial::equirectangular(
964			equi.projection_bounds_top,
965			equi.projection_bounds_bottom,
966			equi.projection_bounds_left,
967			equi.projection_bounds_right,
968		)
969		.map_err(Error::UnsupportedSpatial)?,
970		Some(ProjKind::Cbmp(_)) => return unsupported("cubemap projection"),
971		Some(ProjKind::Mshp(_)) => return unsupported("mesh projection"),
972		_ => return unsupported("unknown projection"),
973	};
974	Ok((Some(projection), stereo))
975}
976
977/// The `nclx` box for a catalog colour, or `None` when it has no code point or range to carry.
978/// An absent code point is written as unspecified (2) and an absent range as limited.
979fn color_colr(color: Option<&hang::catalog::Color>) -> Option<mp4_atom::Colr> {
980	let color = color?;
981	if color.primaries.is_none() && color.transfer.is_none() && color.matrix.is_none() && color.range.is_none() {
982		return None;
983	}
984	Some(mp4_atom::Colr::Nclx {
985		colour_primaries: color.primaries.unwrap_or(2).into(),
986		transfer_characteristics: color.transfer.unwrap_or(2).into(),
987		matrix_coefficients: color.matrix.unwrap_or(2).into(),
988		full_range_flag: color.range == Some(hang::catalog::ColorRange::Full),
989	})
990}
991
992/// Write the catalog colour into a `vpcC`, so it never contradicts the `colr` box written beside
993/// it. A VP9 codec string may carry a container's placeholder BT.709, so once the catalog knows any
994/// colour, the fields it leaves out are written unspecified (2) rather than kept.
995fn vpcc_color(mut vpcc: mp4_atom::VpcC, color: Option<&hang::catalog::Color>) -> mp4_atom::VpcC {
996	let Some(color) = color else {
997		return vpcc;
998	};
999	vpcc.color_primaries = color.primaries.unwrap_or(2);
1000	vpcc.transfer_characteristics = color.transfer.unwrap_or(2);
1001	vpcc.matrix_coefficients = color.matrix.unwrap_or(2);
1002	vpcc.video_full_range_flag = color.range == Some(hang::catalog::ColorRange::Full);
1003	vpcc
1004}
1005
1006pub(crate) fn synthesize_video_trak(
1007	track_id: u32,
1008	timescale: u64,
1009	config: &VideoConfig,
1010	description: Option<&[u8]>,
1011) -> Result<mp4_atom::Trak> {
1012	if !matches!(
1013		config.codec,
1014		VideoCodec::H264(_) | VideoCodec::H265(_) | VideoCodec::AV1(_) | VideoCodec::VP8 | VideoCodec::VP9(_)
1015	) {
1016		return Err(Error::UnsupportedSynthesis(format!("video codec {:?}", config.codec)));
1017	}
1018
1019	let width = u16::try_from(
1020		config
1021			.coded_width
1022			.ok_or_else(|| Error::MissingVideoDimensions(config.codec.to_string()))?,
1023	)
1024	.map_err(|_| Error::MissingVideoDimensions(config.codec.to_string()))?;
1025	let height = u16::try_from(
1026		config
1027			.coded_height
1028			.ok_or_else(|| Error::MissingVideoDimensions(config.codec.to_string()))?,
1029	)
1030	.map_err(|_| Error::MissingVideoDimensions(config.codec.to_string()))?;
1031	if width == 0 || height == 0 {
1032		return Err(Error::MissingVideoDimensions(config.codec.to_string()));
1033	}
1034	let visual = mp4_atom::Visual {
1035		data_reference_index: 1,
1036		width,
1037		height,
1038		..Default::default()
1039	};
1040
1041	// Codecs that carry an out-of-band config record require `description`.
1042	let require_description = || description.ok_or_else(|| Error::MissingVideoDescription(config.codec.to_string()));
1043
1044	let colr = color_colr(config.color.as_ref()).into_iter().collect();
1045	let sample_entry = match &config.codec {
1046		VideoCodec::H264(h264) => {
1047			let mut cursor = std::io::Cursor::new(require_description()?);
1048			let avcc = mp4_atom::Avcc::decode_body(&mut cursor).map_err(Error::mp4)?;
1049			// avc3 when the samples may still carry parameter sets: a catalog record
1050			// passes the samples through as they are, and empty lists are the in-band
1051			// entry. A record built from the first keyframe strips them from the
1052			// samples, so it stays avc1.
1053			let catalog_record = config.description.as_ref().is_some_and(|d| !d.is_empty());
1054			let empty = avcc.sequence_parameter_sets.is_empty() && avcc.picture_parameter_sets.is_empty();
1055			if h264.inline && (catalog_record || empty) {
1056				mp4_atom::Codec::from(mp4_atom::Avc3 {
1057					visual,
1058					avcc,
1059					colr,
1060					..Default::default()
1061				})
1062			} else {
1063				mp4_atom::Codec::from(mp4_atom::Avc1 {
1064					visual,
1065					avcc,
1066					colr,
1067					..Default::default()
1068				})
1069			}
1070		}
1071		VideoCodec::H265(h265) => {
1072			let mut cursor = std::io::Cursor::new(require_description()?);
1073			let hvcc = mp4_atom::Hvcc::decode_body(&mut cursor).map_err(Error::mp4)?;
1074			// `in_band` (catalog) ↔ hev1 sample entry; otherwise hvc1.
1075			if h265.in_band {
1076				mp4_atom::Codec::from(mp4_atom::Hev1 {
1077					visual,
1078					hvcc,
1079					colr,
1080					..Default::default()
1081				})
1082			} else {
1083				mp4_atom::Codec::from(mp4_atom::Hvc1 {
1084					visual,
1085					hvcc,
1086					colr,
1087					..Default::default()
1088				})
1089			}
1090		}
1091		VideoCodec::AV1(av1) => mp4_atom::Codec::from(mp4_atom::Av01 {
1092			visual,
1093			av1c: crate::codec::av1::av1c_from_av1(av1),
1094			colr,
1095			..Default::default()
1096		}),
1097		VideoCodec::VP8 => mp4_atom::Codec::from(mp4_atom::Vp08 {
1098			visual,
1099			vpcc: vpcc_color(crate::codec::vp8::vpcc(), config.color.as_ref()),
1100			colr,
1101			..Default::default()
1102		}),
1103		VideoCodec::VP9(vp9) => mp4_atom::Codec::from(mp4_atom::Vp09 {
1104			visual,
1105			vpcc: vpcc_color(crate::codec::vp9::vpcc(vp9), config.color.as_ref()),
1106			colr,
1107			..Default::default()
1108		}),
1109		other => unreachable!("unsupported codecs rejected before geometry synthesis: {other:?}"),
1110	};
1111
1112	Ok(build_video_trak(
1113		track_id,
1114		mdhd_timescale(timescale)?,
1115		sample_entry,
1116		width,
1117		height,
1118	))
1119}
1120
1121/// The OpusHead mapping for a `dOps` channel mapping table, checked by [`crate::codec::opus::Mapping::new`].
1122///
1123/// Family 3 is refused: its OpusHead carries a demixing matrix (RFC 8486 §3.2) where
1124/// `dOps` has a table, so neither side can describe the other.
1125pub(crate) fn opus_mapping(mapping: &mp4_atom::OpusChannelMapping) -> Result<crate::codec::opus::Mapping> {
1126	if mapping.family == 3 {
1127		return Err(crate::codec::opus::Error::UnsupportedMappingFamily(3).into());
1128	}
1129	Ok(crate::codec::opus::Mapping::new(crate::codec::opus::mapping::Config {
1130		family: mapping.family,
1131		streams: mapping.stream_count,
1132		coupled: mapping.coupled_count,
1133		table: &mapping.channel_mapping,
1134	})?)
1135}
1136
1137/// The `dOps` channel mapping table for an OpusHead mapping, refusing family 3 as
1138/// [`opus_mapping`] does.
1139fn dops_mapping(mapping: &crate::codec::opus::Mapping) -> Result<mp4_atom::OpusChannelMapping> {
1140	if mapping.family() == 3 {
1141		return Err(crate::codec::opus::Error::UnsupportedMappingFamily(3).into());
1142	}
1143	Ok(mp4_atom::OpusChannelMapping {
1144		family: mapping.family(),
1145		stream_count: mapping.streams(),
1146		coupled_count: mapping.coupled(),
1147		channel_mapping: mapping.table().to_vec(),
1148	})
1149}
1150
1151/// Synthesize a CMAF `Trak` for an audio rendition that has no init segment.
1152pub(crate) fn synthesize_audio_trak(track_id: u32, timescale: u64, config: &AudioConfig) -> Result<mp4_atom::Trak> {
1153	use mp4_atom::Decode;
1154
1155	let channel_count = u16::try_from(config.channel_count)
1156		.ok()
1157		.filter(|&count| count > 0 && config.sample_rate > 0)
1158		.ok_or(Error::InvalidAudioConfig {
1159			sample_rate: config.sample_rate,
1160			channel_count: config.channel_count,
1161		})?;
1162	let audio = mp4_atom::Audio {
1163		data_reference_index: 1,
1164		channel_count,
1165		sample_size: 16,
1166		// The 16.16 field can't hold a rate past 65,535 Hz, so it is 0 there, as ffmpeg writes
1167		// it; the codec's own config (esds, dOps, dfLa) carries the real rate.
1168		sample_rate: mp4_atom::FixedPoint::from(u16::try_from(config.sample_rate).unwrap_or(0)),
1169	};
1170
1171	let sample_entry = match &config.codec {
1172		AudioCodec::Opus => {
1173			let head = match &config.description {
1174				Some(description) => {
1175					let head = crate::codec::opus::Config::parse(&mut description.as_ref())?;
1176					if head.channel_count != config.channel_count {
1177						return Err(Error::OpusChannelCount {
1178							catalog: config.channel_count,
1179							head: head.channel_count,
1180						});
1181					}
1182					head
1183				}
1184				// Without a head there is no mapping table, which only mono and stereo go without.
1185				None if channel_count <= 2 => crate::codec::opus::Config::new(config.sample_rate, config.channel_count),
1186				None => return Err(crate::codec::opus::Error::UnsupportedChannelCount(config.channel_count).into()),
1187			};
1188			mp4_atom::Codec::from(mp4_atom::Opus {
1189				audio,
1190				dops: mp4_atom::Dops {
1191					// The head's count, which matches the catalog's, fits its one byte.
1192					output_channel_count: head.channel_count as u8,
1193					pre_skip: head.pre_skip,
1194					input_sample_rate: head.sample_rate,
1195					output_gain: head.output_gain,
1196					channel_mapping: head.mapping.as_ref().map(dops_mapping).transpose()?,
1197				},
1198				btrt: None,
1199			})
1200		}
1201		AudioCodec::AAC(_) => {
1202			// The catalog `description` is the AudioSpecificConfig (set by the TS
1203			// importer via aac::Config::encode, or carried over from a CMAF source).
1204			// mp4_atom models the esds DecoderSpecific as the parsed
1205			// AudioSpecificConfig, so decode the blob back into that shape.
1206			let description = config
1207				.description
1208				.as_ref()
1209				.ok_or_else(|| Error::MissingAudioDescription(config.codec.to_string()))?;
1210			let mut cursor = std::io::Cursor::new(description.as_ref());
1211			let dec_specific =
1212				mp4_atom::esds::DecoderSpecific::decode(&mut cursor).map_err(crate::container::fmp4::Error::mp4)?;
1213
1214			// Safari and AVFoundation reject an AAC track whose DecoderConfigDescriptor is all
1215			// zeros: they endOfStream("decode") on the *init* append, which leaves the
1216			// ManagedMediaSource ended and every later audio and video append failing. The
1217			// catalog bitrate is optional and real publishers omit it, so fall back to the
1218			// AAC-LC values ffmpeg and the iTunes encoders write. A zero or wider-than-u32
1219			// bitrate takes the fallback as well, since writing it back would rebuild the
1220			// all-zero descriptor this exists to avoid.
1221			let bitrate = config.bitrate.and_then(|b| u32::try_from(b).ok()).filter(|b| *b > 0);
1222			let (max_bitrate, avg_bitrate) = match bitrate {
1223				Some(bitrate) => (bitrate, bitrate),
1224				None => (256_000, 128_000),
1225			};
1226			mp4_atom::Codec::from(mp4_atom::Mp4a {
1227				audio,
1228				esds: mp4_atom::Esds {
1229					es_desc: mp4_atom::esds::EsDescriptor {
1230						// ISO/IEC 14496-14 §5.6: ES_ID is 0 in an MP4 file (the track id carries identity).
1231						es_id: 0,
1232						dec_config: mp4_atom::esds::DecoderConfig {
1233							object_type_indication: 0x40, // MPEG-4 AAC
1234							stream_type: 0x05,            // audio
1235							up_stream: 0,
1236							// 24 KiB, the decoder buffer those same encoders declare.
1237							buffer_size_db: mp4_atom::u24::from([0x00, 0x60, 0x00]),
1238							max_bitrate,
1239							avg_bitrate,
1240							dec_specific: Some(dec_specific),
1241						},
1242						..Default::default()
1243					},
1244				},
1245				btrt: None,
1246				taic: None,
1247			})
1248		}
1249		AudioCodec::Flac => {
1250			// The catalog `description` is the FLAC header (`fLaC` marker + STREAMINFO).
1251			// Parse it back into the STREAMINFO fields the `dfLa` box stores.
1252			let description = config
1253				.description
1254				.as_ref()
1255				.ok_or_else(|| Error::MissingAudioDescription(config.codec.to_string()))?;
1256			let info = crate::codec::flac::Config::parse(&mut description.as_ref())?;
1257
1258			let stream_info = mp4_atom::FlacMetadataBlock::StreamInfo {
1259				minimum_block_size: info.min_block_size,
1260				maximum_block_size: info.max_block_size,
1261				// Frame sizes are 24-bit; clamp defensively so the conversion can't fail.
1262				minimum_frame_size: info.min_frame_size.min(0xFF_FFFF).try_into().expect("fits in u24"),
1263				maximum_frame_size: info.max_frame_size.min(0xFF_FFFF).try_into().expect("fits in u24"),
1264				sample_rate: info.sample_rate,
1265				num_channels_minus_one: info.channel_count.saturating_sub(1) as u8,
1266				bits_per_sample_minus_one: info.bits_per_sample.saturating_sub(1) as u8,
1267				number_of_interchannel_samples: info.total_samples,
1268				md5_checksum: info.md5.to_vec(),
1269			};
1270
1271			mp4_atom::Codec::from(mp4_atom::Flac {
1272				audio,
1273				dfla: mp4_atom::Dfla {
1274					blocks: vec![stream_info],
1275				},
1276			})
1277		}
1278		other => return Err(Error::UnsupportedSynthesis(format!("audio codec {:?}", other))),
1279	};
1280
1281	Ok(build_audio_trak(track_id, mdhd_timescale(timescale)?, sample_entry))
1282}
1283
1284/// All-ones: the ISO/IEC 14496-12 spelling of "duration not known up front", which is always
1285/// the case for the live fragmented streams synthesized here. Zero reads as an empty file to a
1286/// strict parser, and VLC refuses to play one.
1287const UNKNOWN_DURATION: u64 = u64::MAX;
1288
1289fn build_video_trak(
1290	track_id: u32,
1291	timescale: u32,
1292	sample_entry: mp4_atom::Codec,
1293	width: u16,
1294	height: u16,
1295) -> mp4_atom::Trak {
1296	mp4_atom::Trak {
1297		tkhd: mp4_atom::Tkhd {
1298			track_id,
1299			enabled: true,
1300			// track_in_movie. A player is entitled to skip a track the presentation doesn't
1301			// claim, and the flags field is 0x000001 rather than 0x000003 without it.
1302			in_movie: true,
1303			duration: UNKNOWN_DURATION,
1304			width: mp4_atom::FixedPoint::from(width),
1305			height: mp4_atom::FixedPoint::from(height),
1306			..Default::default()
1307		},
1308		mdia: build_mdia(timescale, b"vide", true, sample_entry),
1309		..Default::default()
1310	}
1311}
1312
1313fn build_audio_trak(track_id: u32, timescale: u32, sample_entry: mp4_atom::Codec) -> mp4_atom::Trak {
1314	mp4_atom::Trak {
1315		tkhd: mp4_atom::Tkhd {
1316			track_id,
1317			enabled: true,
1318			in_movie: true,
1319			duration: UNKNOWN_DURATION,
1320			// Full volume (8.8 fixed point). The default is 0, which is a muted track, and
1321			// only an audio track carries a meaningful value.
1322			volume: mp4_atom::FixedPoint::from(1),
1323			..Default::default()
1324		},
1325		mdia: build_mdia(timescale, b"soun", false, sample_entry),
1326		..Default::default()
1327	}
1328}
1329
1330/// Assemble a fragmented init segment (ftyp + moov) around already-built traks.
1331///
1332/// `ftyp` is the one a passed-through CMAF init carried, if any; otherwise a plain `isom` one
1333/// is synthesized. The `mvhd` is ours either way, so it declares the unknown duration and the
1334/// movie timescale of the assembled init rather than of whatever source a trak came from.
1335/// [`extract_init`] normalizes a passed-through trak to match.
1336pub(crate) fn encode_init(
1337	ftyp: Option<mp4_atom::Ftyp>,
1338	mut traks: Vec<mp4_atom::Trak>,
1339	trexs: Vec<mp4_atom::Trex>,
1340) -> Result<Bytes> {
1341	use mp4_atom::Encode;
1342
1343	let ftyp = ftyp.unwrap_or(mp4_atom::Ftyp {
1344		major_brand: b"isom".into(),
1345		minor_version: 0x200,
1346		compatible_brands: vec![b"isom".into(), b"iso6".into(), b"mp41".into()],
1347	});
1348	// Hang places every decoded Opus sample one pre-skip before its packet timestamp.
1349	// dOps alone describes decoder priming; ISO BMFF needs an edit to express that
1350	// presentation shift. Rebuild it after the output track timescales are settled.
1351	for trak in &mut traks {
1352		let skip = priming(trak);
1353		if skip != 0 {
1354			trak.edts = Some(mp4_atom::Edts {
1355				elst: Some(mp4_atom::Elst {
1356					entries: vec![mp4_atom::ElstEntry {
1357						// A live edit's duration is implicit in the fragments that follow.
1358						segment_duration: 0,
1359						media_time: Some(skip),
1360						media_rate: mp4_atom::FixedPoint::from(1),
1361					}],
1362				}),
1363			});
1364		}
1365	}
1366	let timescale = traks.first().map(|t| t.mdia.mdhd.timescale).unwrap_or(1000);
1367	let next_track_id = traks.iter().map(|t| t.tkhd.track_id).max().unwrap_or(0) + 1;
1368
1369	let moov = mp4_atom::Moov {
1370		mvhd: mp4_atom::Mvhd {
1371			timescale,
1372			duration: UNKNOWN_DURATION,
1373			// Normal playback rate and full volume (16.16 and 8.8 fixed point). Both default
1374			// to 0, which declares a stopped, muted presentation.
1375			rate: mp4_atom::FixedPoint::from(1),
1376			volume: mp4_atom::FixedPoint::from(1),
1377			// The next id a track could take, so it must be past every one already present.
1378			next_track_id,
1379			..Default::default()
1380		},
1381		trak: traks,
1382		mvex: (!trexs.is_empty()).then(|| mp4_atom::Mvex {
1383			trex: trexs,
1384			..Default::default()
1385		}),
1386		..Default::default()
1387	};
1388
1389	let mut buf = Vec::new();
1390	ftyp.encode(&mut buf).map_err(crate::container::fmp4::Error::mp4)?;
1391	moov.encode(&mut buf).map_err(crate::container::fmp4::Error::mp4)?;
1392	Ok(Bytes::from(buf))
1393}
1394
1395/// An Opus track's pre-skip in its media timescale, or zero for any other track.
1396pub(crate) fn priming(trak: &mp4_atom::Trak) -> u64 {
1397	match trak.mdia.minf.stbl.stsd.codecs.as_slice() {
1398		[mp4_atom::Codec::Opus(opus)] => u64::from(opus.dops.pre_skip) * u64::from(trak.mdia.mdhd.timescale) / 48_000,
1399		_ => 0,
1400	}
1401}
1402
1403/// Narrow a media timescale to the 32-bit `mdhd` field, rejecting what would truncate.
1404///
1405/// `moq_net::Timescale` permits the whole QUIC varint range, so a caller-supplied scale can be
1406/// wider than the field. Truncating would put the init segment and the fragments on different
1407/// timelines, silently, so refuse instead.
1408fn mdhd_timescale(timescale: u64) -> Result<u32> {
1409	u32::try_from(timescale).map_err(|_| Error::TimescaleTooLarge(timescale))
1410}
1411
1412fn build_mdia(timescale: u32, handler: &[u8; 4], is_video: bool, sample_entry: mp4_atom::Codec) -> mp4_atom::Mdia {
1413	mp4_atom::Mdia {
1414		mdhd: mp4_atom::Mdhd {
1415			timescale,
1416			..Default::default()
1417		},
1418		hdlr: mp4_atom::Hdlr {
1419			handler: mp4_atom::FourCC::new(handler),
1420			name: String::new(),
1421		},
1422		minf: mp4_atom::Minf {
1423			vmhd: is_video.then(mp4_atom::Vmhd::default),
1424			smhd: (!is_video).then(mp4_atom::Smhd::default),
1425			dinf: mp4_atom::Dinf {
1426				dref: mp4_atom::Dref {
1427					entries: vec![mp4_atom::DrefEntry::Url(mp4_atom::Url::default())],
1428				},
1429			},
1430			stbl: mp4_atom::Stbl {
1431				stsd: mp4_atom::Stsd {
1432					codecs: vec![sample_entry],
1433				},
1434				..Default::default()
1435			},
1436			..Default::default()
1437		},
1438	}
1439}
1440
1441/// Default video timescale when the catalog doesn't supply one.
1442///
1443/// Used by the fMP4 exporter when synthesizing an init segment for a Legacy or LOC source.
1444/// Prefer `framerate * 1000`, then the common NTSC denominator, an exact scale for the
1445/// nanosecond-rounded cadence, and finally the highest safe approximate scale.
1446///
1447/// A framerate that scales to less than one tick takes the fallback too: zero and negative land
1448/// on 0 through `as u64`, which is not a timescale anything accepts, and a non-finite one is
1449/// filtered out before the cast, since infinity would saturate to `u64::MAX`, past the varint
1450/// range a `Timescale` holds.
1451pub(crate) fn default_video_timescale(config: &VideoConfig) -> u64 {
1452	usable_video_framerate(config)
1453		.and_then(select_video_timescale)
1454		.unwrap_or(90_000)
1455}
1456
1457/// The fallback duration of an audio frame that states none: ~1024 samples, which SBR doubles
1458/// along with the output rate the catalog names.
1459pub(crate) fn audio_default_frame(config: &AudioConfig) -> Duration {
1460	let samples = match &config.codec {
1461		AudioCodec::AAC(aac) if matches!(aac.profile, 5 | 29) => 2048.0,
1462		_ => 1024.0,
1463	};
1464	Duration::from_secs_f64(samples / config.sample_rate.max(1) as f64)
1465}
1466
1467/// A finite catalog framerate with a synthesized scale and duration that fit their MP4 fields.
1468pub(crate) fn usable_video_framerate(config: &VideoConfig) -> Option<f64> {
1469	config
1470		.framerate
1471		.filter(|fps| fps.is_finite() && *fps > 0.0 && (*fps * 1000.0) as u64 > 0)
1472		.filter(|fps| select_video_timescale(*fps).is_some())
1473}
1474
1475/// Choose a scale that represents the rounded cadence without overflowing `trun` duration.
1476fn select_video_timescale(framerate: f64) -> Option<u64> {
1477	let preferred = (framerate * 1000.0) as u64;
1478
1479	let frame = Duration::from_secs_f64(1.0 / framerate);
1480	for timescale in [preferred, (framerate * 1001.0).round() as u64] {
1481		if duration_fits_trun(frame, timescale) {
1482			return Some(timescale);
1483		}
1484	}
1485
1486	const NANOS_PER_SECOND: u128 = 1_000_000_000;
1487	let exact = NANOS_PER_SECOND / gcd(frame.as_nanos(), NANOS_PER_SECOND);
1488	let exact = u64::try_from(exact).ok()?;
1489	if duration_fits_trun(frame, exact) {
1490		return Some(exact);
1491	}
1492	if let Some(timescale) = rational_timescale(frame) {
1493		return Some(timescale);
1494	}
1495
1496	let max_scale = u128::from(u32::MAX)
1497		.checked_mul(NANOS_PER_SECOND)?
1498		.checked_div(frame.as_nanos())?
1499		.min(u128::from(u32::MAX));
1500	let max_scale = u64::try_from(max_scale).ok()?;
1501	duration_fits_trun(frame, max_scale).then_some(max_scale)
1502}
1503
1504/// Find a small rational scale whose rounded cadence stays within one nanosecond.
1505fn rational_timescale(duration: Duration) -> Option<u64> {
1506	const NANOS_PER_SECOND: u128 = 1_000_000_000;
1507	let mut numerator = duration.as_nanos();
1508	let mut denominator = NANOS_PER_SECOND;
1509	let (mut previous_ticks, mut ticks) = (0_u128, 1_u128);
1510	let (mut previous_scale, mut scale) = (1_u128, 0_u128);
1511
1512	while denominator != 0 {
1513		let coefficient = numerator / denominator;
1514		let next_ticks = coefficient.checked_mul(ticks)?.checked_add(previous_ticks)?;
1515		let next_scale = coefficient.checked_mul(scale)?.checked_add(previous_scale)?;
1516		if next_ticks > u128::from(u32::MAX) || next_scale > u128::from(u32::MAX) {
1517			break;
1518		}
1519
1520		let candidate = u64::try_from(next_scale).ok()?;
1521		if duration_fits_trun(duration, candidate) {
1522			return Some(candidate);
1523		}
1524
1525		(previous_ticks, ticks) = (ticks, next_ticks);
1526		(previous_scale, scale) = (scale, next_scale);
1527		(numerator, denominator) = (denominator, numerator % denominator);
1528	}
1529
1530	None
1531}
1532
1533/// Whether the scale represents the rounded cadence and keeps its sample duration 32-bit.
1534fn duration_fits_trun(duration: Duration, timescale: u64) -> bool {
1535	timescale > 0 && rounded_duration_ticks(duration, timescale).is_some_and(|ticks| u32::try_from(ticks).is_ok())
1536}
1537
1538/// Convert a rounded duration to ticks when it is within one nanosecond of an exact tick.
1539fn rounded_duration_ticks(duration: Duration, timescale: u64) -> Option<u64> {
1540	const NANOS_PER_SECOND: u128 = 1_000_000_000;
1541	let scaled = duration.as_nanos().checked_mul(u128::from(timescale))?;
1542	let rounded = scaled.checked_add(NANOS_PER_SECOND / 2)? / NANOS_PER_SECOND;
1543	let exact = rounded.checked_mul(NANOS_PER_SECOND)?;
1544	if scaled.abs_diff(exact) > u128::from(timescale) {
1545		return None;
1546	}
1547	u64::try_from(rounded).ok()
1548}
1549
1550/// Greatest common divisor for reducing exact timestamp ratios.
1551fn gcd(mut a: u128, mut b: u128) -> u128 {
1552	while b != 0 {
1553		(a, b) = (b, a % b);
1554	}
1555	a
1556}
1557
1558/// The decode timeline a fragment actually carries: its `tfdt` and each sample's composition
1559/// offset. This is what a player reads, as opposed to the PTS [`decode`] reconstructs from it.
1560#[cfg(test)]
1561pub(crate) fn timeline(fragment: &Bytes) -> (u64, Vec<i64>) {
1562	let traf = first_traf(fragment);
1563	let cts = traf.trun[0].samples.iter().map(|e| e.cts.unwrap_or_default()).collect();
1564	(traf.tfdt.as_ref().unwrap().base_media_decode_time, cts)
1565}
1566
1567/// How long each sample in a fragment claims to last, as written into its `trun`.
1568#[cfg(test)]
1569pub(crate) fn sample_durations(fragment: &Bytes) -> Vec<Option<u32>> {
1570	first_traf(fragment).trun[0]
1571		.samples
1572		.iter()
1573		.map(|e| e.duration)
1574		.collect()
1575}
1576
1577/// One case of `test_data/sample-defaults.json`, which `js/hang` decodes too.
1578#[cfg(test)]
1579#[serde_with::serde_as]
1580#[derive(serde::Deserialize)]
1581pub(crate) struct Fixture {
1582	pub name: String,
1583	#[serde_as(as = "serde_with::base64::Base64")]
1584	pub init: Vec<u8>,
1585	#[serde_as(as = "serde_with::base64::Base64")]
1586	pub fragment: Vec<u8>,
1587	pub samples: Vec<FixtureSample>,
1588}
1589
1590/// A sample a [`Fixture`] decodes to, timed in microseconds.
1591#[cfg(test)]
1592#[derive(serde::Deserialize, Debug, PartialEq)]
1593pub(crate) struct FixtureSample {
1594	pub timestamp: u64,
1595	pub duration: u64,
1596	pub keyframe: bool,
1597	pub data: Vec<u8>,
1598}
1599
1600#[cfg(test)]
1601impl From<&Frame> for FixtureSample {
1602	fn from(frame: &Frame) -> Self {
1603		Self {
1604			timestamp: frame.timestamp.as_micros().unwrap() as u64,
1605			duration: frame.duration.map_or(0, |d| d.as_micros().unwrap() as u64),
1606			keyframe: frame.keyframe,
1607			data: frame.payload.to_vec(),
1608		}
1609	}
1610}
1611
1612#[cfg(test)]
1613pub(crate) fn fixtures() -> Vec<Fixture> {
1614	#[derive(serde::Deserialize)]
1615	struct File {
1616		cases: Vec<Fixture>,
1617	}
1618	let file: File = serde_json::from_str(include_str!("test_data/sample-defaults.json")).unwrap();
1619	file.cases
1620}
1621
1622#[cfg(test)]
1623fn first_traf(fragment: &Bytes) -> mp4_atom::Traf {
1624	use mp4_atom::DecodeMaybe;
1625
1626	let mut cursor = std::io::Cursor::new(fragment.as_ref());
1627	while let Some(atom) = mp4_atom::Any::decode_maybe(&mut cursor).unwrap() {
1628		if let mp4_atom::Any::Moof(moof) = atom {
1629			return moof.traf.into_iter().next().expect("a traf");
1630		}
1631	}
1632	panic!("no moof");
1633}
1634
1635#[cfg(test)]
1636mod tests {
1637	use crate::container::test_util::Lazy;
1638	#[test]
1639	fn received_metadata_is_bounded() {
1640		let mut bounded = true;
1641		for (name, data) in super::metadata::tests::attacks(b"moov") {
1642			bounded &= super::metadata::tests::measure(name, || super::Wire::from_init(&data).is_err());
1643		}
1644		let config = AudioConfig::new(AudioCodec::Opus, 48_000, 2);
1645		let wire = Wire::new(synthesize_audio_trak(1, 48_000, &config).unwrap()).unwrap();
1646		for (name, data) in super::metadata::tests::attacks(b"moof") {
1647			bounded &= super::metadata::tests::measure(name, || {
1648				wire.decode(moq_net::frame::Frame::new(Timestamp::unscaled(0), data.clone()))
1649					.is_err()
1650			});
1651		}
1652		assert!(bounded);
1653	}
1654
1655	use super::*;
1656
1657	fn ts(micros: u64) -> Timestamp {
1658		Timestamp::from_micros(micros).unwrap()
1659	}
1660
1661	fn info(track_id: u32, timescale: moq_net::Timescale, sequence_number: u32) -> FragmentInfo {
1662		FragmentInfo {
1663			track_id,
1664			timescale,
1665			sequence_number,
1666			kind: Kind::Video,
1667		}
1668	}
1669
1670	// An AAC-LC / 44.1 kHz / stereo AudioSpecificConfig, the catalog `description` shape.
1671	fn aac_config(bitrate: Option<u64>) -> AudioConfig {
1672		let mut config = AudioConfig::new(AudioCodec::AAC(hang::catalog::AAC { profile: 2 }), 44_100, 2);
1673		config.description = Some(Bytes::from_static(&[0x12, 0x10]));
1674		config.bitrate = bitrate;
1675		config
1676	}
1677
1678	#[test]
1679	fn he_aac_default_frame_spans_the_core_frame() {
1680		// 1024 core samples at 24 kHz, named as 2048 at the 48 kHz output.
1681		for profile in [5, 29] {
1682			let config = AudioConfig::new(AudioCodec::AAC(hang::catalog::AAC { profile }), 48_000, 2);
1683			assert_eq!(audio_default_frame(&config), Duration::from_secs_f64(1024.0 / 24_000.0));
1684		}
1685		let lc = AudioConfig::new(AudioCodec::AAC(hang::catalog::AAC { profile: 2 }), 48_000, 2);
1686		assert_eq!(audio_default_frame(&lc), Duration::from_secs_f64(1024.0 / 48_000.0));
1687	}
1688
1689	/// The moov an encoded init segment carries, so a test asserts on what a player parses
1690	/// rather than on the struct that went in.
1691	fn moov(init: &Bytes) -> mp4_atom::Moov {
1692		use mp4_atom::DecodeMaybe;
1693
1694		let mut cursor = std::io::Cursor::new(init.as_ref());
1695		while let Some(atom) = mp4_atom::Any::decode_maybe(&mut cursor).unwrap() {
1696			if let mp4_atom::Any::Moov(moov) = atom {
1697				return moov;
1698			}
1699		}
1700		panic!("no moov");
1701	}
1702
1703	fn dec_config(trak: &mp4_atom::Trak) -> mp4_atom::esds::DecoderConfig {
1704		match &trak.mdia.minf.stbl.stsd.codecs[0] {
1705			mp4_atom::Codec::Mp4a(mp4a) => mp4a.esds.es_desc.dec_config.clone(),
1706			other => panic!("expected mp4a, got {other:?}"),
1707		}
1708	}
1709
1710	// Safari and AVFoundation reject an all-zero DecoderConfigDescriptor on the *init* append,
1711	// which ends the ManagedMediaSource and fails every append after it. The catalog bitrate is
1712	// optional and real publishers omit it, so a synthesized esds must not lean on it.
1713	#[test]
1714	fn synthesized_aac_init_has_non_zero_bitrates() {
1715		let inferred = dec_config(&synthesize_audio_trak(1, 44_100, &aac_config(None)).unwrap());
1716		assert_ne!(u32::from(inferred.buffer_size_db), 0);
1717		assert_ne!(inferred.max_bitrate, 0);
1718		assert_ne!(inferred.avg_bitrate, 0);
1719
1720		let stated = dec_config(&synthesize_audio_trak(1, 44_100, &aac_config(Some(96_000))).unwrap());
1721		assert_eq!(stated.max_bitrate, 96_000, "the catalog's bitrate wins");
1722		assert_eq!(stated.avg_bitrate, 96_000);
1723
1724		// A stated bitrate the field can't carry rebuilds the same all-zero descriptor, so it
1725		// takes the fallback rather than the catalog.
1726		for unusable in [Some(0), Some(u64::from(u32::MAX) + 1)] {
1727			let config = dec_config(&synthesize_audio_trak(1, 44_100, &aac_config(unusable)).unwrap());
1728			assert_eq!(config.max_bitrate, inferred.max_bitrate, "{unusable:?}");
1729			assert_eq!(config.avg_bitrate, inferred.avg_bitrate, "{unusable:?}");
1730		}
1731	}
1732
1733	// `framerate * 1000` is 0 for a zero, negative or non-finite catalog framerate, and 0 is not
1734	// a timescale: Timescale::new rejects it, so Muxer::video would fail to build at all.
1735	#[test]
1736	fn default_video_timescale_ignores_an_unusable_framerate() {
1737		let mut config = VideoConfig::new(hang::catalog::VideoCodec::VP8);
1738		for unusable in [0.0, -30.0, f64::NAN, f64::INFINITY, 0.0005] {
1739			config.framerate = Some(unusable);
1740			assert_eq!(default_video_timescale(&config), 90_000, "{unusable}");
1741		}
1742
1743		config.framerate = Some(30.0);
1744		assert_eq!(default_video_timescale(&config), 30_000);
1745
1746		config.framerate = Some(30_000.0 / 1001.0);
1747		assert_eq!(default_video_timescale(&config), 30_000);
1748	}
1749
1750	#[test]
1751	fn default_video_timescale_keeps_low_cadence_within_trun() {
1752		let mut config = VideoConfig::new(hang::catalog::VideoCodec::VP8);
1753		for framerate in [0.2001, 0.0011] {
1754			config.framerate = Some(framerate);
1755			let timescale = default_video_timescale(&config);
1756			let duration = Duration::from_secs_f64(1.0 / framerate);
1757			let ticks = rounded_duration_ticks(duration, timescale).unwrap();
1758
1759			assert!(timescale <= u64::from(u32::MAX));
1760			assert!(ticks <= u64::from(u32::MAX));
1761		}
1762
1763		assert_eq!(default_video_timescale(&config), 11);
1764	}
1765
1766	// A live fragmented stream's duration isn't known up front. Zero reads as an empty file to a
1767	// strict parser: VLC refuses to play one.
1768	#[test]
1769	fn synthesized_init_declares_unknown_duration() {
1770		let trak = synthesize_audio_trak(1, 44_100, &aac_config(None)).unwrap();
1771		assert_eq!(trak.tkhd.duration, u64::MAX);
1772
1773		let init = encode_init(None, vec![trak], Vec::new()).unwrap();
1774		let moov = moov(&init);
1775		assert_eq!(moov.mvhd.duration, u64::MAX);
1776		assert_eq!(moov.trak[0].tkhd.duration, u64::MAX);
1777	}
1778
1779	/// Opus media time counts priming; Hang time places the first kept sample at the
1780	/// first frame timestamp. Both init sources must express the same inverse mapping.
1781	#[test]
1782	fn opus_init_maps_hang_timestamps_to_media() {
1783		for timescale in [48_000, 1_000_000] {
1784			for pre_skip in [0, 312, u16::MAX] {
1785				let mut config = AudioConfig::new(AudioCodec::Opus, 48_000, 2);
1786				config.description = Some(
1787					crate::codec::opus::Config::new(48_000, 2)
1788						.with_pre_skip(pre_skip)
1789						.encode()
1790						.unwrap(),
1791				);
1792				for source_edit in [false, true] {
1793					let mut trak = synthesize_audio_trak(1, timescale, &config).unwrap();
1794					if source_edit {
1795						trak.edts = Some(mp4_atom::Edts {
1796							elst: Some(mp4_atom::Elst {
1797								entries: vec![mp4_atom::ElstEntry {
1798									media_time: Some(96000),
1799									..Default::default()
1800								}],
1801							}),
1802						});
1803						let mut init = Vec::new();
1804						mp4_atom::Encode::encode(
1805							&mp4_atom::Moov {
1806								trak: vec![trak],
1807								..Default::default()
1808							},
1809							&mut init,
1810						)
1811						.unwrap();
1812						let mut traks = Vec::new();
1813						extract_init(&Bytes::from(init), 1, &mut None, &mut traks, &mut Vec::new()).unwrap();
1814						trak = traks.pop().unwrap();
1815					}
1816					let init = encode_init(None, vec![trak], Vec::new()).unwrap();
1817					let moov = moov(&init);
1818					let trak = &moov.trak[0];
1819					let skip = u64::from(pre_skip) * timescale / 48_000;
1820					if skip == 0 {
1821						assert!(trak.edts.is_none());
1822					} else {
1823						let entries = &trak.edts.as_ref().unwrap().elst.as_ref().unwrap().entries;
1824						assert_eq!(entries.len(), 1);
1825						assert_eq!(entries[0].media_time, Some(skip));
1826						assert_eq!(entries[0].segment_duration, 0, "the live duration is implicit");
1827						assert_eq!(entries[0].media_rate, mp4_atom::FixedPoint::from(1));
1828					}
1829					let edit = edit::Edit::new(trak, moov.mvhd.timescale).unwrap();
1830					for pts in [0, skip, timescale * 10] {
1831						assert_eq!(edit.present(pts).unwrap(), Some(pts), "the importer inverts the edit");
1832					}
1833				}
1834			}
1835		}
1836	}
1837
1838	// The header defaults are all the "off" value: a track the presentation doesn't claim, a
1839	// stopped playback rate, a muted volume, and a next id that collides with the track already
1840	// there. A strict player is entitled to act on any of them.
1841	#[test]
1842	fn synthesized_init_headers_describe_a_playable_presentation() {
1843		let audio = synthesize_audio_trak(1, 44_100, &aac_config(None)).unwrap();
1844		let init = encode_init(None, vec![audio], Vec::new()).unwrap();
1845		let moov = moov(&init);
1846
1847		assert_eq!(moov.mvhd.rate.integer(), 1, "normal playback rate");
1848		assert_eq!(moov.mvhd.volume.integer(), 1, "full volume");
1849		assert_eq!(moov.mvhd.next_track_id, 2, "past the only track id");
1850
1851		let tkhd = &moov.trak[0].tkhd;
1852		assert!(tkhd.enabled && tkhd.in_movie, "flags 0x000003");
1853		assert_eq!(tkhd.volume.integer(), 1, "an audio track carries the volume");
1854	}
1855
1856	// A video track's volume stays 0: the field only means something for audio.
1857	#[test]
1858	fn synthesized_video_init_sets_the_track_flags() {
1859		let mut config = VideoConfig::new(hang::catalog::VideoCodec::VP8);
1860		config.coded_width = Some(320);
1861		config.coded_height = Some(240);
1862		config.framerate = Some(30.0);
1863		let video = synthesize_video_trak(1, 30_000, &config, None).unwrap();
1864		let init = encode_init(None, vec![video], Vec::new()).unwrap();
1865		let moov = moov(&init);
1866
1867		let tkhd = &moov.trak[0].tkhd;
1868		assert!(tkhd.enabled && tkhd.in_movie, "flags 0x000003");
1869		assert_eq!(tkhd.volume.integer(), 0);
1870	}
1871
1872	#[test]
1873	fn synthesized_video_init_rejects_missing_dimensions() {
1874		let config = VideoConfig::new(hang::catalog::VideoCodec::VP8);
1875		let error = synthesize_video_trak(1, 30_000, &config, None).unwrap_err();
1876		assert!(matches!(error, Error::MissingVideoDimensions(_)));
1877	}
1878
1879	#[test]
1880	fn decode_reads_trun_sample_duration() {
1881		use mp4_atom::Encode;
1882
1883		// Microsecond timescale so each tick maps 1:1 to the Timestamp's µs.
1884		// Without a data_offset, decode() reads the run from the start of the mdat, so a
1885		// hand-built moof+mdat with explicit per-sample durations is enough.
1886		let timescale = moq_net::Timescale::MICRO;
1887		let moof = mp4_atom::Moof {
1888			mfhd: mp4_atom::Mfhd { sequence_number: 0 },
1889			traf: vec![mp4_atom::Traf {
1890				tfhd: mp4_atom::Tfhd {
1891					track_id: 1,
1892					..Default::default()
1893				},
1894				tfdt: Some(mp4_atom::Tfdt {
1895					base_media_decode_time: 0,
1896				}),
1897				trun: vec![mp4_atom::Trun {
1898					data_offset: None,
1899					samples: vec![
1900						mp4_atom::TrunEntry {
1901							size: Some(2),
1902							duration: Some(33_333),
1903							..Default::default()
1904						},
1905						mp4_atom::TrunEntry {
1906							size: Some(2),
1907							duration: Some(33_333),
1908							..Default::default()
1909						},
1910					]
1911					.into(),
1912				}],
1913				..Default::default()
1914			}],
1915		};
1916
1917		let mut buf = Vec::new();
1918		moof.encode(&mut buf).unwrap();
1919		mp4_atom::Mdat {
1920			data: vec![0xDE, 0xAD, 0xBE, 0xEF],
1921		}
1922		.encode(&mut buf)
1923		.unwrap();
1924
1925		let frames = decode(Bytes::from(buf), None, Track::new(timescale, Kind::Video)).unwrap();
1926		assert_eq!(frames.len(), 2);
1927		assert_eq!(frames[0].timestamp, ts(0));
1928		assert_eq!(frames[0].duration, Some(ts(33_333)));
1929		assert_eq!(frames[1].timestamp, ts(33_333));
1930		assert_eq!(frames[1].duration, Some(ts(33_333)));
1931	}
1932
1933	#[test]
1934	fn duration_round_trips_through_encode() {
1935		// A frame with a known duration must survive encode -> decode.
1936		let timescale = moq_net::Timescale::MICRO;
1937		let input = vec![Frame {
1938			timestamp: ts(0),
1939			decode: None,
1940			payload: Bytes::from_static(&[0xDE, 0xAD]),
1941			keyframe: true,
1942			duration: Some(ts(33_333)),
1943		}];
1944
1945		let fragment = encode_fragment(info(1, timescale, 0), &input).unwrap();
1946		let frames = decode(fragment, None, Track::new(timescale, Kind::Video)).unwrap();
1947
1948		assert_eq!(frames.len(), 1);
1949		assert_eq!(frames[0].duration, Some(ts(33_333)));
1950	}
1951
1952	// A trun sample duration is 32 bits. Narrowing silently would make the media claim a
1953	// shorter duration than the metadata returned to the fragmenting consumer.
1954	#[test]
1955	fn encode_fragment_rejects_a_duration_too_large_for_trun() {
1956		let timescale = moq_net::Timescale::new(u64::from(u32::MAX)).unwrap();
1957		let over = u64::from(u32::MAX) + 1;
1958		let frame = Frame {
1959			timestamp: Timestamp::from_scale(0, timescale.as_u64()).unwrap(),
1960			decode: None,
1961			payload: Bytes::from_static(&[0xDE, 0xAD]),
1962			keyframe: true,
1963			duration: Some(Timestamp::from_scale(over, timescale.as_u64()).unwrap()),
1964		};
1965
1966		let err = encode_fragment(info(1, timescale, 0), std::slice::from_ref(&frame)).unwrap_err();
1967		assert!(matches!(err, Error::SampleDurationTooLarge(ticks) if ticks == over));
1968
1969		let largest = Frame {
1970			duration: Some(Timestamp::from_scale(u64::from(u32::MAX), timescale.as_u64()).unwrap()),
1971			..frame
1972		};
1973		let fragment = encode_fragment(info(1, timescale, 0), &[largest]).unwrap();
1974		assert_eq!(sample_durations(&fragment), vec![Some(u32::MAX)]);
1975	}
1976
1977	// A positive duration that becomes zero ticks would leave tfdt stationary while the
1978	// fragment metadata still advances, so a coarse override has to fail explicitly.
1979	#[test]
1980	fn encode_fragment_rejects_a_duration_shorter_than_one_tick() {
1981		let timescale = moq_net::Timescale::SECOND;
1982		let frame = Frame {
1983			timestamp: Timestamp::from_secs(0).unwrap(),
1984			decode: None,
1985			payload: Bytes::from_static(&[0xDE, 0xAD]),
1986			keyframe: true,
1987			duration: Some(Timestamp::from_millis(33).unwrap()),
1988		};
1989
1990		let err = encode_fragment(info(1, timescale, 0), std::slice::from_ref(&frame)).unwrap_err();
1991		assert!(matches!(err, Error::SampleDurationTooSmall(1)));
1992
1993		let one_tick = Frame {
1994			duration: Some(Timestamp::from_secs(1).unwrap()),
1995			..frame
1996		};
1997		let fragment = encode_fragment(info(1, timescale, 0), &[one_tick]).unwrap();
1998		assert_eq!(sample_durations(&fragment), vec![Some(1)]);
1999	}
2000
2001	// Flooring every 1/24-second sample at a 1 kHz output scale would lose 16 ticks per
2002	// second. The caller must choose a scale that represents the duration exactly.
2003	#[test]
2004	fn encode_fragment_rejects_an_inexact_sample_duration() {
2005		let input_scale = moq_net::Timescale::new(24).unwrap();
2006		let output_scale = moq_net::Timescale::MILLI;
2007		let frame = Frame {
2008			timestamp: Timestamp::new(0, input_scale).unwrap(),
2009			decode: None,
2010			payload: Bytes::from_static(&[0xDE, 0xAD]),
2011			keyframe: true,
2012			duration: Some(Timestamp::new(1, input_scale).unwrap()),
2013		};
2014
2015		let err = encode_fragment(info(1, output_scale, 0), std::slice::from_ref(&frame)).unwrap_err();
2016		assert!(matches!(err, Error::SampleDurationInexact(1_000)));
2017
2018		let exact_scale = moq_net::Timescale::new(24_000).unwrap();
2019		let fragment = encode_fragment(info(1, exact_scale, 0), &[frame]).unwrap();
2020		assert_eq!(sample_durations(&fragment), vec![Some(1_000)]);
2021	}
2022
2023	// tfdt is 64 bits. A timestamp rescaled past that range must fail rather than wrap the
2024	// fragment back onto an unrelated point in the presentation.
2025	#[test]
2026	fn encode_fragment_rejects_a_pts_too_large_for_tfdt() {
2027		let timescale = moq_net::Timescale::new(u64::from(u32::MAX)).unwrap();
2028		let frame = Frame {
2029			timestamp: Timestamp::from_secs(1 << 40).unwrap(),
2030			decode: None,
2031			payload: Bytes::from_static(&[0xDE, 0xAD]),
2032			keyframe: true,
2033			duration: None,
2034		};
2035
2036		let err = encode_fragment(info(1, timescale, 0), &[frame]).unwrap_err();
2037		assert!(matches!(err, Error::PtsOverflow));
2038	}
2039
2040	#[test]
2041	fn reordered_pts_round_trips_with_cts() {
2042		let timescale = moq_net::Timescale::new(1_000_000).unwrap();
2043		let input = vec![
2044			Frame {
2045				timestamp: ts(0),
2046				decode: None,
2047				payload: Bytes::from_static(&[0x00]),
2048				keyframe: true,
2049				duration: Some(ts(33_000)),
2050			},
2051			Frame {
2052				timestamp: ts(99_000),
2053				decode: None,
2054				payload: Bytes::from_static(&[0x01]),
2055				keyframe: false,
2056				duration: Some(ts(33_000)),
2057			},
2058			Frame {
2059				timestamp: ts(33_000),
2060				decode: None,
2061				payload: Bytes::from_static(&[0x02]),
2062				keyframe: false,
2063				duration: Some(ts(33_000)),
2064			},
2065		];
2066
2067		let fragment = encode_fragment(info(1, timescale, 0), &input).unwrap();
2068		let frames = decode(fragment, None, Track::new(timescale, Kind::Video)).unwrap();
2069
2070		assert_eq!(frames.len(), input.len());
2071		for (actual, expected) in frames.iter().zip(&input) {
2072			assert_eq!(actual.timestamp, expected.timestamp);
2073			assert_eq!(actual.duration, expected.duration);
2074			assert_eq!(actual.payload, expected.payload);
2075		}
2076	}
2077
2078	/// Packagers flag every audio sample a sync sample. Decoded as keyframes, those would
2079	/// each open a group, so audio decodes with the bit clear: the group start is the
2080	/// consumer's to mark.
2081	#[test]
2082	fn audio_samples_decode_without_the_keyframe_bit() {
2083		let timescale = moq_net::Timescale::new(48_000).unwrap();
2084		let input: Vec<Frame> = (0..3)
2085			.map(|i| Frame {
2086				timestamp: Timestamp::new(i * 960, timescale).unwrap(),
2087				decode: None,
2088				payload: Bytes::from_static(&[0x00]),
2089				keyframe: i == 0,
2090				duration: Some(Timestamp::new(960, timescale).unwrap()),
2091			})
2092			.collect();
2093		let fragment = encode_fragment(
2094			FragmentInfo {
2095				kind: Kind::Audio,
2096				..info(1, timescale, 0)
2097			},
2098			&input,
2099		)
2100		.unwrap();
2101
2102		// On the wire every sample is a sync sample, whatever the keyframe bit said.
2103		let flags: Vec<u32> = first_traf(&fragment).trun[0]
2104			.samples
2105			.iter()
2106			.map(|entry| entry.flags.unwrap())
2107			.collect();
2108		assert_eq!(flags, vec![0x0200_0000; 3]);
2109
2110		let audio = decode(fragment.clone(), None, Track::new(timescale, Kind::Audio)).unwrap();
2111		assert!(
2112			audio.iter().all(|frame| !frame.keyframe),
2113			"audio never decodes a keyframe"
2114		);
2115		let video = decode(fragment, None, Track::new(timescale, Kind::Video)).unwrap();
2116		assert!(
2117			video.iter().all(|frame| frame.keyframe),
2118			"the sync flag is a video keyframe"
2119		);
2120	}
2121
2122	/// A fragment that leaves sample values to `tfhd` or the init segment's `trex` decodes the way
2123	/// `js/hang` decodes the same fixtures.
2124	#[test]
2125	fn decodes_the_sample_defaults_fixtures() {
2126		for fixture in fixtures() {
2127			let wire = Wire::from_init(&fixture.init).unwrap();
2128			let frames = decode(Bytes::from(fixture.fragment), None, wire.track().unwrap())
2129				.unwrap_or_else(|err| panic!("{}: {err}", fixture.name));
2130			let samples: Vec<FixtureSample> = frames.iter().map(FixtureSample::from).collect();
2131			assert_eq!(samples, fixture.samples, "{}", fixture.name);
2132		}
2133	}
2134
2135	#[test]
2136	fn unsupported_track_handler_is_rejected() {
2137		assert!(matches!(
2138			Kind::from_handler((*b"text").into()),
2139			Err(Error::UnknownTrackHandler(_))
2140		));
2141	}
2142
2143	/// The wire container tells audio from video by the handler its init declares.
2144	#[test]
2145	fn wire_knows_an_audio_track_by_its_handler() {
2146		let audio = Wire::new(synthesize_audio_trak(1, 44_100, &aac_config(None)).unwrap()).unwrap();
2147		assert_eq!(audio.kind, Kind::Audio);
2148
2149		let mut config = VideoConfig::new(hang::catalog::VideoCodec::VP8);
2150		config.coded_width = Some(320);
2151		config.coded_height = Some(240);
2152		let video = Wire::new(synthesize_video_trak(1, 90_000, &config, None).unwrap()).unwrap();
2153		assert_eq!(video.kind, Kind::Video);
2154	}
2155
2156	/// A track that is neither audio nor video is refused when the container is built, so
2157	/// nothing reads it as a data track.
2158	#[test]
2159	fn wire_refuses_a_track_that_is_neither_audio_nor_video() {
2160		let mut trak = synthesize_audio_trak(1, 44_100, &aac_config(None)).unwrap();
2161		trak.mdia.hdlr.handler = (*b"sbtl").into();
2162		assert!(matches!(Wire::new(trak), Err(Error::UnsupportedSubtitle)));
2163	}
2164
2165	fn sample(micros: u64) -> Frame {
2166		Frame {
2167			timestamp: ts(micros),
2168			decode: None,
2169			payload: Bytes::from_static(&[0xAB]),
2170			keyframe: false,
2171			duration: Some(ts(33_000)),
2172		}
2173	}
2174
2175	fn micros(frames: &[Frame]) -> Vec<u128> {
2176		frames.iter().map(|f| f.timestamp.as_micros().unwrap()).collect()
2177	}
2178
2179	/// The frame timestamp is the broadcast timeline: a passthrough fragment whose `tfdt` still
2180	/// carries its source PTS decodes at the frame timestamp, keeping its B-frame order.
2181	#[test]
2182	fn decode_times_samples_from_the_frame_timestamp() {
2183		let timescale = moq_net::Timescale::MICRO;
2184		let source = 3_600_000_000;
2185		let input = [sample(source), sample(source + 66_000), sample(source + 33_000)];
2186		let fragment = encode_fragment(info(1, timescale, 0), &input).unwrap();
2187
2188		let frames = decode(fragment, Some(ts(10_000_000)), Track::new(timescale, Kind::Video)).unwrap();
2189		assert_eq!(micros(&frames), [10_000_000, 10_066_000, 10_033_000]);
2190	}
2191
2192	/// A fragment can open on a sample that presents after a later one (open-GOP leading
2193	/// pictures, or a cut mid-GOP). The earliest presentation time is the anchor, on both sides.
2194	#[tokio::test]
2195	async fn the_frame_timestamp_is_the_earliest_presentation_time() {
2196		let mut config = VideoConfig::new(hang::catalog::VideoCodec::VP8);
2197		config.coded_width = Some(320);
2198		config.coded_height = Some(240);
2199		let timescale = moq_net::Timescale::MICRO;
2200		let wire = Wire::new(synthesize_video_trak(1, 1_000_000, &config, None).unwrap()).unwrap();
2201
2202		let broadcast = moq_net::broadcast::Info::new().produce();
2203		let info = moq_net::track::Info::default().with_timescale(timescale);
2204		let track = broadcast.create_track("video", info).unwrap();
2205		let mut group = Lazy::appending(&track);
2206		let input = [sample(100_000), sample(33_000), sample(66_000)];
2207		wire.write(&mut group.writer(), &input).unwrap();
2208
2209		let frame = group.consume().read_frame().await.unwrap().unwrap();
2210		assert_eq!(frame.timestamp.as_micros().unwrap(), 33_000);
2211
2212		let frames = decode(
2213			frame.payload.clone(),
2214			Some(frame.timestamp),
2215			Track::new(timescale, Kind::Video),
2216		)
2217		.unwrap();
2218		assert_eq!(micros(&frames), [100_000, 33_000, 66_000]);
2219
2220		let shifted = decode(frame.payload, Some(ts(5_000_000)), Track::new(timescale, Kind::Video)).unwrap();
2221		assert_eq!(micros(&shifted), [5_067_000, 5_000_000, 5_033_000]);
2222	}
2223
2224	/// A scale-less track's frames carry no broadcast time, so their samples present at `tfdt`.
2225	#[test]
2226	fn an_untimed_fragment_decodes_at_its_tfdt() {
2227		let mut config = VideoConfig::new(hang::catalog::VideoCodec::VP8);
2228		config.coded_width = Some(320);
2229		config.coded_height = Some(240);
2230		let timescale = moq_net::Timescale::MICRO;
2231		let wire = Wire::new(synthesize_video_trak(1, 1_000_000, &config, None).unwrap()).unwrap();
2232
2233		let source = 3_600_000_000;
2234		let input = [sample(source), sample(source + 66_000), sample(source + 33_000)];
2235		let fragment = encode_fragment(info(1, timescale, 0), &input).unwrap();
2236
2237		let frames = wire
2238			.decode(moq_net::frame::Frame::new(Timestamp::unscaled(0), fragment))
2239			.unwrap();
2240		let source = u128::from(source);
2241		assert_eq!(micros(&frames), [source, source + 66_000, source + 33_000]);
2242	}
2243
2244	/// A track at another scale than the media couldn't carry the earliest presentation time
2245	/// exactly, so writing a fragment to it fails.
2246	#[test]
2247	fn write_refuses_a_track_at_another_timescale() {
2248		let mut config = VideoConfig::new(hang::catalog::VideoCodec::VP8);
2249		config.coded_width = Some(320);
2250		config.coded_height = Some(240);
2251		let wire = Wire::new(synthesize_video_trak(1, 90_000, &config, None).unwrap()).unwrap();
2252
2253		let broadcast = moq_net::broadcast::Info::new().produce();
2254		let info = moq_net::track::Info::default().with_timescale(moq_net::Timescale::MILLI);
2255		let track = broadcast.create_track("video", info).unwrap();
2256		let mut group = Lazy::appending(&track);
2257
2258		let err = wire.write(&mut group.writer(), &[sample(0)]).unwrap_err();
2259		assert!(matches!(err, Error::TimescaleMismatch { .. }), "got {err:?}");
2260	}
2261
2262	/// A run whose samples extend beyond the payload is refused.
2263	#[test]
2264	fn decode_refuses_a_run_past_the_payload() {
2265		use mp4_atom::{DecodeMaybe, Encode};
2266
2267		let timescale = moq_net::Timescale::MICRO;
2268		let fragment = encode_fragment(info(1, timescale, 0), &[sample(0), sample(33_000)]).unwrap();
2269
2270		let mut cursor = std::io::Cursor::new(fragment.as_ref());
2271		let Some(mp4_atom::Any::Moof(mut moof)) = mp4_atom::Any::decode_maybe(&mut cursor).unwrap() else {
2272			panic!("a moof first");
2273		};
2274		let mdat = &fragment[cursor.position() as usize..];
2275		let offset = moof.traf[0].trun[0].data_offset.as_mut().unwrap();
2276		*offset += 1;
2277
2278		let mut skewed = Vec::new();
2279		moof.encode(&mut skewed).unwrap();
2280		skewed.extend_from_slice(mdat);
2281
2282		let err = decode(Bytes::from(skewed), None, Track::new(timescale, Kind::Video)).unwrap_err();
2283		assert!(matches!(err, Error::SampleRangeOutOfBounds { .. }), "got {err:?}");
2284	}
2285
2286	/// A frame timestamp the track carries at another scale anchors to the nearest tick, the way
2287	/// `encode` stamps it.
2288	#[test]
2289	fn decode_rounds_the_frame_timestamp_to_the_nearest_tick() {
2290		let timescale = moq_net::Timescale::new(90_000).unwrap();
2291		let fragment = encode_fragment(info(1, timescale, 0), &[sample(0)]).unwrap();
2292
2293		// Tick 100 is 1111.1 µs, which a microsecond track truncates to 1111.
2294		let frames = decode(fragment, Some(ts(1_111)), Track::new(timescale, Kind::Video)).unwrap();
2295		assert_eq!(frames[0].timestamp, Timestamp::new(100, timescale).unwrap());
2296	}
2297
2298	#[test]
2299	fn decode_without_duration_reports_none() {
2300		// encode_fragment writes no sample-duration for a duration-less frame,
2301		// so decode must report None (and output stays byte-identical to before).
2302		let timescale = moq_net::Timescale::new(90_000).unwrap();
2303		let frames = vec![Frame {
2304			timestamp: ts(0),
2305			decode: None,
2306			payload: Bytes::from_static(&[0xDE, 0xAD]),
2307			keyframe: true,
2308			duration: None,
2309		}];
2310
2311		let fragment = encode_fragment(info(1, timescale, 0), &frames).unwrap();
2312		let frames = decode(fragment, None, Track::new(timescale, Kind::Video)).unwrap();
2313
2314		assert_eq!(frames.len(), 1);
2315		assert_eq!(frames[0].duration, None);
2316	}
2317
2318	#[test]
2319	fn decode_zero_duration_reports_none() {
2320		use mp4_atom::Encode;
2321
2322		let timescale = moq_net::Timescale::new(24_000).unwrap();
2323		let moof = mp4_atom::Moof {
2324			mfhd: mp4_atom::Mfhd { sequence_number: 0 },
2325			traf: vec![mp4_atom::Traf {
2326				tfhd: mp4_atom::Tfhd {
2327					track_id: 1,
2328					default_sample_duration: Some(0),
2329					default_sample_size: Some(2),
2330					..Default::default()
2331				},
2332				tfdt: Some(mp4_atom::Tfdt {
2333					base_media_decode_time: 2_000,
2334				}),
2335				trun: vec![mp4_atom::Trun {
2336					data_offset: None,
2337					samples: vec![mp4_atom::TrunEntry {
2338						size: None,
2339						duration: None,
2340						..Default::default()
2341					}]
2342					.into(),
2343				}],
2344				..Default::default()
2345			}],
2346		};
2347
2348		let mut buf = Vec::new();
2349		moof.encode(&mut buf).unwrap();
2350		mp4_atom::Mdat { data: vec![0xDE, 0xAD] }.encode(&mut buf).unwrap();
2351
2352		let frames = decode(Bytes::from(buf), None, Track::new(timescale, Kind::Video)).unwrap();
2353		assert_eq!(frames.len(), 1);
2354		assert_eq!(frames[0].timestamp.as_micros().unwrap(), 83_333);
2355		assert_eq!(frames[0].duration, None);
2356	}
2357}