Skip to main content

moq_mux/container/fmp4/
export.rs

1use crate::container::Delay;
2use std::collections::{HashMap, HashSet, VecDeque};
3use std::task::Poll;
4use std::time::Duration;
5
6use bytes::Bytes;
7use hang::catalog::{AudioCodec, AudioConfig, Catalog, Container, VideoConfig};
8use mp4_atom::DecodeMaybe;
9
10use crate::Result;
11use crate::catalog::Stream;
12use crate::container::Frame;
13use crate::container::consumer::Event;
14use crate::container::fmp4::Error;
15use crate::container::{ExportSource, Resume};
16use moq_net::Timestamp;
17
18/// How long, on the local clock from the first frame read, the init segment may wait for
19/// every track's codec configuration before the export fails.
20///
21/// The init segment declares every track, so it waits until each one can be described.
22/// An Annex-B H.264 or H.265 source whose catalog codec string and dimensions determine
23/// the sample entry is described immediately. High AVC profiles whose chroma or bit depth
24/// the string does not carry, HEVC beyond Main and Main Still Picture, and a catalog that
25/// leaves out dimensions still wait for the first keyframe's parameter sets. The other
26/// tracks keep reading meanwhile, so they don't fall behind the subscription's max delay,
27/// and their fragments are written right after the init, each up to [`INIT_SHARE`]. The
28/// local clock times the wait because the publisher's timestamps may never advance.
29const INIT_WAIT: Duration = Duration::from_secs(30);
30
31/// The bytes of media a track may hold while the init segment waits: what its consumer may
32/// buffer ahead of the reader. A track past it stops reading, leaving its backlog to the
33/// transport, which the subscription's max delay bounds.
34const INIT_SHARE: usize = crate::container::consumer::DEFAULT_MAX_BUFFER;
35
36/// Subscribe to a moq broadcast and produce a single fMP4 / CMAF byte stream.
37///
38/// Built from a [`Source`](crate::Source), `Export` subscribes to the hang catalog,
39/// (un)subscribes per-rendition tracks as the catalog changes, decodes both Legacy and
40/// CMAF tracks via a per-track source, and re-encodes everything as a merged init
41/// segment + moof+mdat fragments, each track in presentation-timestamp order (see
42/// [`poll_next`](Self::poll_next) for how far that holds across tracks). This is what an fMP4
43/// player (e.g. ffplay, MSE) expects.
44///
45/// Use [`poll_next`](Self::poll_next) to pull byte chunks: the first call returns the merged
46/// init segment (ftyp + multi-track moov), subsequent calls return moof+mdat
47/// fragments. By default a fragment is a group, emitted when the group closes. A video
48/// keyframe also rolls the fragment within a group; audio follows publisher cuts. [`with_fragment_duration`](Self::with_fragment_duration) caps the
49/// fragment duration on top of that, for downstream consumers that throttle by
50/// fragment rate. Returns `None` when the broadcast ends.
51///
52/// The init segment declares every enabled rendition in the catalog once each can be
53/// described, and fragments cut while it waits are written right after it. Each track holds
54/// at most its consumer's max buffer meanwhile, and the export fails with
55/// [`TrackUndescribed`](Error::TrackUndescribed) once the init has waited 30 s on the local
56/// clock. Annex-B H.264 and H.265 whose catalog codec string and dimensions determine the
57/// sample entry are described at the first catalog, as avc3 or hev1 with parameter sets in
58/// the samples. From then on the track set is fixed: a rendition that leaves the catalog, as
59/// a disabled one (`enabled: false`) does, is unsubscribed and idles. On its return it is resubscribed after
60/// the last group read, under the track it was declared as, when its sample entry is
61/// unchanged. That comparison covers the catalog-derived record, so an Annex-B encoder that
62/// restarts with a new parameter set can return. A rendition the catalog moves to another
63/// track (a new `track` or `broadcast`) continues under its declared track the same way, from
64/// the new track's first sync sample past what was read. A new rendition, a changed sample
65/// entry, or a return that replays media already written fails the export.
66///
67/// A rendition whose track fails ends alone while another track still reads, and a new
68/// rendition of its medium continues it the same way, under its declared track: a publisher
69/// that loses a source, such as a microphone, lists a replacement under a new name. A new
70/// rendition that joins while a track of its medium still reads waits to continue that one
71/// should it fail, and fails the export once no track of its medium could.
72///
73/// [`poll_next_chunk`](Self::poll_next_chunk) returns the same bytes as a [`Chunk`], which
74/// separates the init segment from a [`Fragment`] carrying whether it begins at a
75/// sync sample and how long it lasts. A segmenting consumer (e.g. an HLS/LL-HLS
76/// packager) needs that to map fragments onto segments and parts; narrow the catalog
77/// to a single rendition with [`Stream::select`](crate::catalog::Stream::select) so the
78/// fragments belong to one track.
79pub struct Export<S: Stream> {
80	source: crate::Source,
81	catalog: Feed<S>,
82	delay: Delay,
83	fragment_duration: Option<Duration>,
84
85	/// The tracks being read, by rendition name. Before the init a rendition that leaves the
86	/// catalog is dropped; after it, the track moves to `departed` once written out.
87	tracks: HashMap<String, Fmp4Track>,
88
89	/// Renditions that left the catalog after the init, kept out of the polled set so one
90	/// returning reuses its track. A late rendition that wrote nothing is dropped instead,
91	/// so a publisher cycling names holds only what it recorded.
92	departed: HashMap<String, Fmp4Track>,
93
94	/// Renditions that joined after the init while a declared track of their medium still
95	/// reads: each waits to continue a declared track of its medium that fails
96	/// ([`Phase::Lost`]), and fails the export once none is left that could.
97	spares: HashMap<String, Rendition>,
98
99	/// Failed renditions ignored while still listed: one a spare replaced, or one whose track
100	/// failed before the init described it.
101	retired: HashSet<String>,
102
103	init: Init,
104
105	/// Keep a rendition that joins after the init segment instead of failing, for a writer
106	/// that declares it elsewhere. Its fragments carry a track id the init never declared.
107	late: bool,
108
109	/// The `tkhd.track_id` the next new rendition gets.
110	next_track_id: u32,
111
112	/// The `mfhd.sequence_number` the next fragment gets.
113	///
114	/// One counter for the file rather than one per track: ISO/IEC 14496-12 section
115	/// 8.8.5 wants the number to increase from one movie fragment to the next, and a
116	/// per-track counter written into a multi-track file steps backwards on every other
117	/// fragment. Each track's own numbers still ascend within the shared sequence, which
118	/// is what CMAF asks for.
119	sequence_number: u32,
120}
121
122/// Where the catalog subscription stands.
123enum Feed<S> {
124	Live(S),
125	/// The publisher ended the catalog.
126	Ended,
127	/// [`Export::stop`] dropped it, so media no track could be described for is discarded.
128	Stopped,
129}
130
131impl<S> Feed<S> {
132	fn live(&self) -> bool {
133		matches!(self, Feed::Live(_))
134	}
135}
136
137/// Whether the init segment went out, which fixes the track set.
138enum Init {
139	/// Fragments cut before the init segment, written right after it in the order they were cut,
140	/// and the [`INIT_WAIT`] deadline, armed at the first frame any source reads.
141	Waiting {
142		queued: VecDeque<(String, Fragment)>,
143		deadline: Option<Box<kio::clock::Sleep>>,
144	},
145	/// `first_late` is the first track id the init does not declare, and `queued` the
146	/// fragments cut while it waited, still to go out.
147	Written {
148		first_late: u32,
149		queued: VecDeque<Fragment>,
150	},
151}
152
153impl Init {
154	fn written(&self) -> bool {
155		matches!(self, Init::Written { .. })
156	}
157
158	/// Whether the init waited out [`INIT_WAIT`], arming the deadline once a frame was `read`.
159	fn poll_expired(&mut self, read: bool, waiter: &kio::Waiter) -> bool {
160		let Init::Waiting { deadline, .. } = self else {
161			return false;
162		};
163		if read && deadline.is_none() {
164			*deadline = Some(Box::new(kio::clock::sleep(INIT_WAIT)));
165		}
166		deadline
167			.as_mut()
168			.is_some_and(|deadline| waiter.poll_future(std::pin::Pin::new(deadline)).is_ready())
169	}
170
171	/// The init segment went out, declaring every track id below `first_late`.
172	fn write(&mut self, first_late: u32) {
173		if let Init::Waiting { queued, .. } = self {
174			let queued = std::mem::take(queued)
175				.into_iter()
176				.map(|(_, fragment)| fragment)
177				.collect();
178			*self = Init::Written { first_late, queued };
179		}
180	}
181}
182
183/// One emitted CMAF chunk: the init segment, then media fragments.
184///
185/// The two carry different metadata, so they are separate variants rather than one
186/// struct with fields that are meaningless on the init. The set is closed by the
187/// container format, so a `match` on it stays exhaustive.
188#[derive(Clone, Debug)]
189pub enum Chunk {
190	/// The merged init segment (ftyp + multi-track moov), emitted once, first.
191	Init(Bytes),
192
193	/// One moof+mdat fragment.
194	Fragment(Fragment),
195}
196
197impl Chunk {
198	/// The encoded bytes, whichever kind of chunk this is.
199	pub fn data(&self) -> &Bytes {
200		match self {
201			Chunk::Init(data) => data,
202			Chunk::Fragment(fragment) => &fragment.data,
203		}
204	}
205
206	/// Consume the chunk for its encoded bytes, dropping any metadata.
207	pub fn into_data(self) -> Bytes {
208		match self {
209			Chunk::Init(data) => data,
210			Chunk::Fragment(fragment) => fragment.data,
211		}
212	}
213
214	/// The init segment's bytes, or `None` for a media fragment.
215	pub fn init(self) -> Option<Bytes> {
216		match self {
217			Chunk::Init(data) => Some(data),
218			Chunk::Fragment(_) => None,
219		}
220	}
221
222	/// The media fragment, or `None` for the init segment.
223	pub fn fragment(self) -> Option<Fragment> {
224		match self {
225			Chunk::Init(_) => None,
226			Chunk::Fragment(fragment) => Some(fragment),
227		}
228	}
229}
230
231/// One moof+mdat fragment, with the metadata a segmenting consumer needs.
232#[derive(Clone, Debug)]
233pub struct Fragment {
234	/// The encoded moof+mdat bytes.
235	pub data: Bytes,
236
237	/// A fragment that begins at a sync sample, so it can start a segment.
238	/// Video fragments are independent only at a GOP boundary (keyframe); audio
239	/// fragments are always independent.
240	pub independent: bool,
241
242	/// Presentation duration of the fragment.
243	pub duration: Duration,
244}
245
246/// A rendition's latest catalog entry.
247#[allow(
248	clippy::large_enum_variant,
249	reason = "one per rendition, so the variant sizes never add up to an allocation's worth; only large when extra features grow the video config"
250)]
251enum Rendition {
252	Video(VideoConfig),
253	Audio(AudioConfig),
254}
255
256impl Rendition {
257	fn subscribe(&self, source: &crate::Source, name: &str, delay: Delay) -> Result<Option<ExportSource>> {
258		match self {
259			Rendition::Video(config) => ExportSource::for_fmp4_video(source, name, config, delay),
260			Rendition::Audio(config) => ExportSource::for_audio(source, name, config, delay),
261		}
262	}
263
264	/// Whether `export` still reads the track this entry names.
265	fn read_by(&self, export: &ExportSource, source: &crate::Source, name: &str) -> bool {
266		match self {
267			Rendition::Video(config) => export.reads(source, name, config),
268			Rendition::Audio(config) => export.reads(source, name, config),
269		}
270	}
271
272	fn is_video(&self) -> bool {
273		matches!(self, Rendition::Video(_))
274	}
275
276	/// Whether frames may present out of decode order: what the catalog's `reorder` declares,
277	/// else whatever the codec allows.
278	fn may_reorder(&self) -> bool {
279		match self {
280			Rendition::Video(config) => match config.reorder {
281				Some(depth) => depth > 0,
282				None => crate::codec::video::max_reorder(config) > 0,
283			},
284			Rendition::Audio(_) => false,
285		}
286	}
287
288	/// Fallback duration for a trailing frame that carries no per-sample duration.
289	fn default_frame(&self) -> Duration {
290		match self {
291			Rendition::Video(config) => {
292				Duration::from_secs_f64(1.0 / super::usable_video_framerate(config).unwrap_or(30.0))
293			}
294			Rendition::Audio(config) => super::audio_default_frame(config),
295		}
296	}
297}
298
299/// How a track is declared in the init segment.
300struct Declaration {
301	trak: mp4_atom::Trak,
302	trex: mp4_atom::Trex,
303	/// The source init's ftyp, for a CMAF rendition.
304	ftyp: Option<mp4_atom::Ftyp>,
305	/// An Opus sample entry synthesized without the catalog's OpusHead, so its pre-skip
306	/// and input sample rate are guesses a later description may correct.
307	provisional: bool,
308}
309
310/// Where a track's subscription stands.
311enum Phase {
312	/// Reading the rendition's subscription.
313	Reading(Subscription),
314	/// The subscription ended while the rendition stays in the catalog.
315	Ended(Subscription),
316	/// The track failed while the rendition stays in the catalog. A rendition of its medium
317	/// that joins later continues it, as a publisher lists a reopened source.
318	Lost(Subscription),
319	/// The rendition left the catalog after the init. One that returns resumes here.
320	Departed(Resume),
321	/// [`Export::stop`] ended the read.
322	Stopped,
323}
324
325/// A track's subscription to its rendition.
326struct Subscription {
327	source: ExportSource,
328	/// Checked against the track's declaration. Until then its frames are dropped: they
329	/// come before the codec configuration they need.
330	described: bool,
331}
332
333/// A run of frames that becomes one fragment.
334struct Batch {
335	frames: Vec<Frame>,
336	/// The first frame was a keyframe, so the fragment can start an HLS segment.
337	/// Meaningless for audio.
338	independent: bool,
339}
340
341/// The frames a track accumulates for its next moof+mdat, flushed when the next frame
342/// opens a group or on the duration cap.
343#[derive(Default)]
344enum Buffer {
345	#[default]
346	Empty,
347	Open(Batch),
348	/// The source group closed, so the fragment can be emitted.
349	Closed(Batch),
350}
351
352impl Buffer {
353	fn batch(&self) -> Option<&Batch> {
354		match self {
355			Buffer::Empty => None,
356			Buffer::Open(batch) | Buffer::Closed(batch) => Some(batch),
357		}
358	}
359
360	fn is_empty(&self) -> bool {
361		self.batch().is_none()
362	}
363
364	fn is_closed(&self) -> bool {
365		matches!(self, Buffer::Closed(_))
366	}
367
368	fn first(&self) -> Option<&Frame> {
369		self.batch()?.frames.first()
370	}
371
372	fn last(&self) -> Option<&Frame> {
373		self.batch()?.frames.last()
374	}
375
376	fn last_mut(&mut self) -> Option<&mut Frame> {
377		match self {
378			Buffer::Empty => None,
379			Buffer::Open(batch) | Buffer::Closed(batch) => batch.frames.last_mut(),
380		}
381	}
382
383	/// Append to the open run, or open one with `frame`.
384	fn push(&mut self, frame: Frame) {
385		match self {
386			Buffer::Open(batch) => batch.frames.push(frame),
387			_ => {
388				*self = Buffer::Open(Batch {
389					independent: frame.keyframe,
390					frames: vec![frame],
391				})
392			}
393		}
394	}
395
396	/// End the open run, so its fragment can go out.
397	fn close(&mut self) {
398		*self = match std::mem::take(self) {
399			Buffer::Open(batch) => Buffer::Closed(batch),
400			buffer => buffer,
401		};
402	}
403
404	fn take(&mut self) -> Option<Batch> {
405		match std::mem::take(self) {
406			Buffer::Empty => None,
407			Buffer::Open(batch) | Buffer::Closed(batch) => Some(batch),
408		}
409	}
410}
411
412struct Fmp4Track {
413	phase: Phase,
414
415	config: Rendition,
416
417	/// The `trak` from the first time the track could be described. A later description
418	/// must keep its sample entry, except to settle a provisional one.
419	declaration: Option<Declaration>,
420
421	/// The next decoded frame from the source, used for cross-track timestamp ordering.
422	pending: Option<Frame>,
423
424	buffer: Buffer,
425
426	/// True if this track is video. Its samples are independently decodable only
427	/// at a keyframe; audio samples always are.
428	is_video: bool,
429
430	/// True for Opus audio, whose packets carry their duration in the TOC byte.
431	opus: bool,
432
433	/// Fallback duration for a trailing frame that carries no per-sample duration
434	/// (Legacy / LOC sources). Derived from the catalog framerate / sample rate.
435	default_frame: Duration,
436
437	/// The latest presentation time written, so a resubscription that replays it fails
438	/// instead of writing the track's history twice.
439	written: Option<Duration>,
440
441	/// Where the last written fragment's decode timeline ended, in ticks at `timescale`.
442	///
443	/// A fragment cut inside a GOP continues from here rather than anchoring at its first
444	/// frame's presentation time: with reordered video that frame is often a reference
445	/// presented after the B-frames decoded next, so its presentation time would put the
446	/// fragment's `tfdt` ahead of the one that follows.
447	decode_end: Option<u64>,
448
449	/// The bytes of media read before the init segment, held against [`INIT_SHARE`].
450	held: usize,
451
452	track_id: u32,
453	/// Kept from the first catalog entry, so a later framerate change doesn't move the
454	/// track off the timescale its fragments are already written in.
455	timescale: u64,
456}
457
458impl Fmp4Track {
459	fn new(source: ExportSource, config: Rendition, track_id: u32) -> Result<Self> {
460		let timescale = match &config {
461			Rendition::Video(config) => catalog_timescale_video(config)?,
462			Rendition::Audio(config) => catalog_timescale_audio(config)?,
463		};
464		Ok(Self {
465			phase: Phase::Reading(Subscription {
466				source,
467				described: false,
468			}),
469			is_video: config.is_video(),
470			opus: matches!(&config, Rendition::Audio(config) if matches!(config.codec, AudioCodec::Opus)),
471			default_frame: config.default_frame(),
472			config,
473			declaration: None,
474			pending: None,
475			buffer: Buffer::Empty,
476			written: None,
477			decode_end: None,
478			held: 0,
479			track_id,
480			timescale,
481		})
482	}
483
484	/// When the next content this track will contribute starts: the first frame of
485	/// its buffered run, or its pending frame when the buffer is empty.
486	///
487	/// A [`Duration`] rather than a [`Timestamp`], whose ordering settles a
488	/// cross-scale tie by scale, so 48 kHz audio would sort ahead of 90 kHz video
489	/// at the same instant.
490	fn next_start(&self) -> Option<Duration> {
491		self.buffer
492			.first()
493			.or(self.pending.as_ref())
494			.and_then(|frame| crate::container::time(frame.timestamp))
495	}
496
497	/// The subscription, while the rendition is in the catalog.
498	fn subscription(&self) -> Option<&Subscription> {
499		match &self.phase {
500			Phase::Reading(subscription) | Phase::Ended(subscription) | Phase::Lost(subscription) => Some(subscription),
501			Phase::Departed(_) | Phase::Stopped => None,
502		}
503	}
504
505	fn subscription_mut(&mut self) -> Option<&mut Subscription> {
506		match &mut self.phase {
507			Phase::Reading(subscription) | Phase::Ended(subscription) | Phase::Lost(subscription) => Some(subscription),
508			Phase::Departed(_) | Phase::Stopped => None,
509		}
510	}
511
512	/// Nothing more will be read: the subscription ended, or the rendition left.
513	fn finished(&self) -> bool {
514		!matches!(self.phase, Phase::Reading(_))
515	}
516
517	fn described(&self) -> bool {
518		self.subscription().is_some_and(|subscription| subscription.described)
519	}
520
521	/// The source signalled end-of-track.
522	fn end(&mut self) {
523		self.phase = match std::mem::replace(&mut self.phase, Phase::Stopped) {
524			Phase::Reading(subscription) => Phase::Ended(subscription),
525			phase => phase,
526		};
527	}
528
529	/// The track failed: its rendition reads no more, unless a later one of its medium continues it.
530	fn lose(&mut self) {
531		self.phase = match std::mem::replace(&mut self.phase, Phase::Stopped) {
532			Phase::Reading(subscription) => Phase::Lost(subscription),
533			phase => phase,
534		};
535	}
536
537	fn lost(&self) -> bool {
538		matches!(self.phase, Phase::Lost(_))
539	}
540
541	/// The rendition left the catalog after the init: end the subscription, keeping where
542	/// it stopped for a return. What was already read still goes out.
543	fn depart(&mut self) {
544		self.phase = match std::mem::replace(&mut self.phase, Phase::Stopped) {
545			Phase::Reading(subscription) | Phase::Ended(subscription) => Phase::Departed(subscription.source.resume()),
546			phase => phase,
547		};
548	}
549
550	/// Apply a newer catalog entry for the same rendition.
551	fn reconfigure(&mut self, name: &str, config: Rendition) -> Result<()> {
552		if config.is_video() != self.is_video {
553			return Err(Error::TrackChanged(name.to_string()).into());
554		}
555		if let (Rendition::Video(video), Some(subscription)) = (&config, self.subscription_mut())
556			&& !subscription.source.note_catalog(video)
557		{
558			return Err(Error::TrackChanged(name.to_string()).into());
559		}
560		self.default_frame = config.default_frame();
561		self.config = config;
562		self.describe(name)
563	}
564
565	/// End what the rendition read from the track it moved off: the frame read ahead is
566	/// dropped, and the buffered run goes out as a fragment of its own, before the new track's.
567	fn moved(&mut self) {
568		self.pending = None;
569		self.buffer.close();
570	}
571
572	/// Resubscribe a rendition that left the catalog after the init and came back, or moved
573	/// to another track.
574	fn rejoin(&mut self, name: &str, config: Rendition, source: ExportSource) -> Result<()> {
575		self.phase = Phase::Reading(Subscription {
576			source,
577			described: false,
578		});
579		self.reconfigure(name, config)
580	}
581
582	/// Describe the track from its catalog entry and source, once both hold everything its
583	/// sample entry needs, and hold it to the sample entry it was first described with.
584	fn describe(&mut self, name: &str) -> Result<()> {
585		let Some(declaration) = self.declaration()? else {
586			return Ok(());
587		};
588		match &mut self.declaration {
589			Some(declared) => {
590				let guessed = declared.provisional || declaration.provisional;
591				if sample_entry(&declared.trak, guessed) != sample_entry(&declaration.trak, guessed) {
592					return Err(Error::TrackChanged(name.to_string()).into());
593				}
594				// The OpusHead settles a guessed entry. An init already written keeps its
595				// guessed pre-skip: a few milliseconds of untrimmed encoder delay cost less
596				// than restarting the file mid-stream.
597				if declared.provisional && !declaration.provisional {
598					*declared = declaration;
599				}
600			}
601			None => self.declaration = Some(declaration),
602		}
603		if let Some(subscription) = self.subscription_mut() {
604			subscription.described = true;
605		}
606		Ok(())
607	}
608
609	/// The `trak` this track would be declared with now, or `None` while its source has
610	/// yet to deliver codec configuration or geometry the catalog leaves out.
611	///
612	/// CMAF tracks pass their existing init segment through; Legacy tracks synthesize a
613	/// `trak` from codec config + dimensions.
614	fn declaration(&self) -> Result<Option<Declaration>> {
615		let init = match &self.config {
616			Rendition::Video(config) => match &config.container {
617				Container::Cmaf { init, .. } => init,
618				Container::Legacy | Container::Loc | Container::Raw | Container::Cts => {
619					let Some(Subscription { source, .. }) = self.subscription() else {
620						return Ok(None);
621					};
622					if !source.header_ready() || !source.video_geometry_ready(config) {
623						return Ok(None);
624					}
625					// H.264/H.265 need a synthesized config record here; VP8 has none. The
626					// catalog's own record wins, since the source kept the one it subscribed with.
627					let description = config
628						.description
629						.as_ref()
630						.filter(|d| !d.is_empty())
631						.or(source.description())
632						.map(|d| d.as_ref());
633					let config = source.video_config(config).unwrap_or_else(|| config.clone());
634					let trak = super::synthesize_video_trak(self.track_id, self.timescale, &config, description)?;
635					return Ok(Some(Declaration::synthesized(trak)));
636				}
637				Container::Unknown(unknown) => return Err(crate::Error::unsupported_container(unknown)),
638			},
639			Rendition::Audio(config) => match &config.container {
640				Container::Cmaf { init, .. } => init,
641				Container::Legacy | Container::Loc | Container::Raw | Container::Cts => {
642					let trak = super::synthesize_audio_trak(self.track_id, self.timescale, config)?;
643					let mut declaration = Declaration::synthesized(trak);
644					declaration.provisional = matches!(config.codec, AudioCodec::Opus) && config.description.is_none();
645					return Ok(Some(declaration));
646				}
647				Container::Unknown(unknown) => return Err(crate::Error::unsupported_container(unknown)),
648			},
649		};
650
651		let mut ftyp = None;
652		let mut traks = Vec::new();
653		let mut trexs = Vec::new();
654		extract_init(init, self.track_id, &mut ftyp, &mut traks, &mut trexs)?;
655		let mut trak = match <[mp4_atom::Trak; 1]>::try_from(traks) {
656			Ok([trak]) => trak,
657			Err(traks) if traks.is_empty() => return Err(Error::NoTracks.into()),
658			Err(_) => return Err(Error::MultipleTracks.into()),
659		};
660		// Fragments are written at the timescale the track was created with, which a later
661		// init for the same rendition may not share.
662		trak.mdia.mdhd.timescale = super::mdhd_timescale(self.timescale)?;
663		let trex = trexs.pop().unwrap_or_else(|| default_trex(self.track_id));
664		Ok(Some(Declaration {
665			trak,
666			trex,
667			ftyp,
668			provisional: false,
669		}))
670	}
671}
672
673impl Declaration {
674	fn synthesized(trak: mp4_atom::Trak) -> Self {
675		Self {
676			trex: default_trex(trak.tkhd.track_id),
677			trak,
678			ftyp: None,
679			provisional: false,
680		}
681	}
682}
683
684/// The `stsd` a returning or reconfigured rendition must keep, without the AAC bitrate
685/// hints a catalog's `bitrate` churns: decoders ignore them. With `guessed`, one side's
686/// Opus pre-skip and input rate (metadata) were made up without an OpusHead, so only the
687/// rest must agree. Its gain was not: a wrong gain changes every sample, so a nonzero one
688/// fails.
689fn sample_entry(trak: &mp4_atom::Trak, guessed: bool) -> mp4_atom::Stsd {
690	let mut stsd = trak.mdia.minf.stbl.stsd.clone();
691	for codec in &mut stsd.codecs {
692		match codec {
693			mp4_atom::Codec::Mp4a(mp4a) => {
694				mp4a.esds.es_desc.dec_config.max_bitrate = 0;
695				mp4a.esds.es_desc.dec_config.avg_bitrate = 0;
696				mp4a.btrt = None;
697			}
698			mp4_atom::Codec::Opus(opus) if guessed => {
699				opus.dops.pre_skip = 0;
700				opus.dops.input_sample_rate = 0;
701			}
702			_ => {}
703		}
704	}
705	stsd
706}
707
708fn default_trex(track_id: u32) -> mp4_atom::Trex {
709	mp4_atom::Trex {
710		track_id,
711		default_sample_description_index: 1,
712		..Default::default()
713	}
714}
715
716impl<S: Stream> Export<S> {
717	/// Subscribe to `source` and produce fMP4 byte chunks, driving track
718	/// (un)subscription from `catalog`.
719	///
720	/// `catalog` is any [`Stream`] of catalog snapshots, typically a
721	/// [`catalog::Consumer`](crate::catalog::Consumer) directly, or narrowed to
722	/// one rendition set via [`Stream::select`](crate::catalog::Stream::select).
723	pub fn new(source: crate::Source, catalog: S) -> Self {
724		Self {
725			source,
726			catalog: Feed::Live(catalog),
727			delay: Delay::default(),
728			fragment_duration: None,
729			tracks: HashMap::new(),
730			departed: HashMap::new(),
731			spares: HashMap::new(),
732			retired: HashSet::new(),
733			init: Init::Waiting {
734				queued: VecDeque::new(),
735				deadline: None,
736			},
737			late: false,
738			next_track_id: 1,
739			sequence_number: 1,
740		}
741	}
742
743	/// Set how far behind the live edge each per-track source plays: [`Delay::min`] is where it
744	/// starts, and [`Delay::max`] how late a group may fall before it is skipped.
745	///
746	/// See [`Consumer`](crate::container::Consumer) for the per-track start and skip behavior.
747	/// Defaults to zero for both (start at the live edge, skip aggressively).
748	pub fn with_delay(mut self, delay: Delay) -> Self {
749		self.delay = delay;
750		self
751	}
752
753	/// Cap the fragment (moof+mdat) duration.
754	///
755	/// By default a fragment is a group: one per GOP for video, and for audio one per
756	/// group the publisher cut, which is a packet for a live encoder and a segment for
757	/// an fMP4 import. Setting this caps each fragment to roughly `duration` of frames,
758	/// useful for downstream consumers that throttle by fragment rate, or to bound an
759	/// audio track whose publisher never cuts it. [`Duration::ZERO`] emits one fragment
760	/// per frame. Video with unknown duration waits for the next timestamp or endpoint
761	/// marker; audio and samples with explicit durations remain immediate. Otherwise
762	/// the cap applies in addition to the group boundary.
763	///
764	/// A fragment cut inside a GOP continues the decode timeline where the previous one
765	/// ended, so B-frame video keeps increasing decode times. Such a fragment cannot see
766	/// the reordering around it, so unless the catalog declares `reorder: 0` (or the codec
767	/// never reorders), a video sample with unknown duration lasts no longer than the
768	/// catalog frame rate's cadence.
769	///
770	/// Accepts either `Duration` or `Option<Duration>` (where `None` restores
771	/// the per-group default).
772	pub fn with_fragment_duration(mut self, duration: impl Into<Option<Duration>>) -> Self {
773		self.fragment_duration = duration.into();
774		self
775	}
776
777	/// Keep renditions that join after the init segment, whose fragments then carry track
778	/// ids the init does not declare. See [`declaration`](Self::declaration).
779	pub(crate) fn with_late_tracks(mut self) -> Self {
780		self.late = true;
781		self
782	}
783
784	/// Stop reading the broadcast. The export still writes out the media it read, the
785	/// fragment each track was buffering included, then ends.
786	///
787	/// Stopping before the init segment could be written ends the export without writing.
788	pub(crate) fn stop(&mut self) {
789		self.catalog = Feed::Stopped;
790		for track in self.tracks.values_mut() {
791			track.phase = Phase::Stopped;
792		}
793	}
794
795	/// The `trak` and `trex` declaring `track_id`, once the track could be described.
796	pub(crate) fn declaration(&self, track_id: u32) -> Option<(&mp4_atom::Trak, &mp4_atom::Trex)> {
797		self.declarations()
798			.find(|(id, _, _)| *id == track_id)
799			.map(|(_, trak, trex)| (trak, trex))
800	}
801
802	/// Every track id with its `trak` and `trex`, the tracks being read first.
803	pub(crate) fn declarations(&self) -> impl Iterator<Item = (u32, &mp4_atom::Trak, &mp4_atom::Trex)> {
804		self.tracks.values().chain(self.departed.values()).filter_map(|track| {
805			let declaration = track.declaration.as_ref()?;
806			Some((track.track_id, &declaration.trak, &declaration.trex))
807		})
808	}
809
810	/// Get the next byte chunk.
811	///
812	/// The first call returns the merged init segment (ftyp + multi-track moov); each
813	/// subsequent call returns one moof+mdat fragment. Returns `None` when the catalog
814	/// and every track have ended.
815	///
816	/// A track's own fragments always ascend in timestamp. Across tracks the order is
817	/// only approximate: a fragment leaves when its group closes or a frame rolls it, so a
818	/// video GOP follows the audio fragments that overlap it, and two video renditions
819	/// rolling on keyframes that do not coincide interleave by up to a GOP. Holding
820	/// fragments back to sort them would cost the length of the longest GOP in added
821	/// latency, which a live export should not pay for an ordering no fMP4 consumer
822	/// needs: a demuxer indexes by track and reads `tfdt`. Narrow the catalog to a
823	/// single rendition with [`Stream::select`](crate::catalog::Stream::select) where
824	/// the order matters.
825	#[cfg_attr(feature = "async", kio::wrapper)]
826	pub fn poll_next(&mut self, waiter: &kio::Waiter) -> Poll<Result<Option<Bytes>>> {
827		Poll::Ready(Ok(
828			std::task::ready!(self.poll_next_chunk(waiter)?).map(Chunk::into_data)
829		))
830	}
831
832	/// Like [`poll_next`](Self::poll_next) but gets a [`Chunk`], which tells the init segment
833	/// apart from a [`Fragment`] and carries that fragment's segmenting metadata.
834	#[cfg_attr(feature = "async", kio::wrapper)]
835	pub fn poll_next_chunk(&mut self, waiter: &kio::Waiter) -> Poll<Result<Option<Chunk>>> {
836		// Appending a frame to a track's buffer restarts the search for work by
837		// going around this loop again, never by re-entering the function: a
838		// track buffers a whole GOP, and stack use must stay flat however many
839		// samples that is.
840		loop {
841			// 1. Drain catalog updates and (un)subscribe tracks accordingly.
842			while let Feed::Live(catalog) = &mut self.catalog {
843				match catalog.poll_next(waiter)? {
844					Poll::Ready(Some(snapshot)) => self.update_catalog(&snapshot.value.without_ext())?,
845					Poll::Ready(None) => {
846						self.catalog = Feed::Ended;
847						break;
848					}
849					Poll::Pending => break,
850				}
851			}
852
853			// 2. Fill any empty pending slots by polling each source. ExportSource
854			// has already applied any codec-shape transform (Annex-B to
855			// length-prefixed) and absorbed parameter-only frames.
856			//
857			// A track that can't be described yet drops its frames, so the source keeps
858			// polling for the SPS/PPS-bearing keyframe instead of parking. Before the init, a
859			// track that holds its share parks instead.
860			let waiting = !self.init.written();
861			let mut lost = Vec::new();
862			for (name, track) in &mut self.tracks {
863				if track.pending.is_some() || track.buffer.is_closed() || (waiting && track.held >= INIT_SHARE) {
864					continue;
865				}
866				while let Phase::Reading(subscription) = &mut track.phase {
867					let event = match subscription.source.poll_event(waiter) {
868						Poll::Ready(Err(err)) if subscription.source.lost() => {
869							track.lose();
870							lost.push((name.clone(), err));
871							break;
872						}
873						event => event?,
874					};
875					match event {
876						Poll::Ready(Some(Event::Frame { frame, .. })) => {
877							// A keyframe may carry new parameter sets, so check it still matches.
878							if !track.described() || frame.keyframe {
879								track.describe(name)?;
880								if !track.described() {
881									continue;
882								}
883							}
884							if waiting {
885								track.held += crate::container::consumer::frame_cost(&frame);
886							}
887							track.pending = Some(frame);
888							break;
889						}
890						Poll::Ready(Some(Event::FrameEnd { end, .. })) => {
891							if track.is_video
892								&& let Some(last) = track.buffer.last_mut()
893								&& last.duration.is_none()
894							{
895								last.duration =
896									timestamp_gap(last.timestamp, end, moq_net::Timescale::new(track.timescale)?)?;
897								if self.fragment_duration == Some(Duration::ZERO) && last.duration.is_some() {
898									break;
899								}
900							}
901						}
902						// The fragment ends at the gap the next group reads.
903						Poll::Ready(Some(Event::Cut { .. })) => {}
904						Poll::Ready(Some(Event::GroupEnd)) => {
905							if track.buffer.is_empty() {
906								continue;
907							}
908							track.buffer.close();
909							break;
910						}
911						Poll::Ready(None) => {
912							track.end();
913							break;
914						}
915						Poll::Pending => break,
916					}
917				}
918			}
919			let mut continued = false;
920			for (name, err) in lost {
921				continued |= self.survive(&name, err)?;
922			}
923			// A track that ended may have been the last a spare could continue. A continued track's
924			// new source is read before parking, since nothing else would wake the export for it.
925			if self.settle_spares()? || continued {
926				continue;
927			}
928
929			// 3. Emit the init segment once every track can be described, then the
930			// fragments queued while it waited.
931			if let Init::Waiting { queued, .. } = &self.init {
932				if self.init_ready() {
933					let init = self.build_init()?;
934					self.init.write(self.next_track_id);
935					return Poll::Ready(Ok(Some(Chunk::Init(init))));
936				}
937				if !self.catalog.live() && self.tracks.values().all(Fmp4Track::finished) {
938					// Media was read but can't be written without every track's description.
939					if !queued.is_empty() && !matches!(self.catalog, Feed::Stopped) {
940						return Poll::Ready(Err(Error::TrackUndescribed(self.undescribed()).into()));
941					}
942					return Poll::Ready(Ok(None));
943				}
944				// Any frame read starts the wait, even a parameter set the source absorbed.
945				let read = self
946					.tracks
947					.values()
948					.filter_map(Fmp4Track::subscription)
949					.any(|sub| sub.source.read());
950				if self.init.poll_expired(read, waiter) {
951					return Poll::Ready(Err(Error::TrackUndescribed(self.undescribed()).into()));
952				}
953			} else if let Init::Written { queued, .. } = &mut self.init
954				&& let Some(fragment) = queued.pop_front()
955			{
956				return Poll::Ready(Ok(Some(Chunk::Fragment(fragment))));
957			}
958
959			// 4. A closed group is complete even when the track remains live. Emit it
960			// (or an ended track's tail) once no other track holds earlier content.
961			if let Some(name) = self.completed_fragment() {
962				let track = self.tracks.get_mut(&name).unwrap();
963				let batch = track.buffer.take().unwrap();
964				let fragment = emit_fragment(&name, track, &mut self.sequence_number, batch, None)?;
965				if let Some(chunk) = self.deliver(name, fragment) {
966					return Poll::Ready(Ok(Some(chunk)));
967				}
968				continue;
969			}
970
971			// 5. Pick the track whose pending frame starts earliest and decide whether
972			// to flush its buffer before appending the new frame. Video leads on a tie
973			// so the interleave does not depend on map order.
974			let chosen = self
975				.tracks
976				.iter()
977				.filter_map(|(name, t)| {
978					let f = t.pending.as_ref()?;
979					Some((crate::container::time(f.timestamp)?, !t.is_video, name.clone()))
980				})
981				.min()
982				.map(|(_, _, name)| name);
983
984			if let Some(name) = chosen {
985				let frag = self.fragment_duration;
986				let track = self.tracks.get_mut(&name).unwrap();
987				let frame = track.pending.take().unwrap();
988				// A zero cap emits one sample at a time. Unknown video duration still
989				// needs a successor timestamp or endpoint before it can be encoded.
990				let fragment = if frag == Some(Duration::ZERO) {
991					if let Some(batch) = track.buffer.take() {
992						// A catalog change can leave buffered frames behind. Drain them
993						// first and retry this frame on the next poll.
994						let fragment = emit_fragment(&name, track, &mut self.sequence_number, batch, Some(&frame))?;
995						track.pending = Some(frame);
996						fragment
997					} else if track.is_video && frame.duration.is_none() {
998						track.buffer.push(frame);
999						continue;
1000					} else {
1001						let batch = Batch {
1002							independent: frame.keyframe,
1003							frames: vec![frame],
1004						};
1005						emit_fragment(&name, track, &mut self.sequence_number, batch, None)?
1006					}
1007				} else if should_flush(&track.buffer, &frame, frag) {
1008					let batch = track.buffer.take().unwrap();
1009					let fragment = emit_fragment(&name, track, &mut self.sequence_number, batch, Some(&frame))?;
1010					// The flushed run is done; the incoming frame opens the next buffer.
1011					track.buffer.push(frame);
1012					fragment
1013				} else {
1014					track.buffer.push(frame);
1015					// Frame appended to buffer; go round again to look for more work or a flush.
1016					continue;
1017				};
1018				if let Some(chunk) = self.deliver(name, fragment) {
1019					return Poll::Ready(Ok(Some(chunk)));
1020				}
1021				continue;
1022			}
1023
1024			// 6. Nothing pending anywhere. Step 4 has already written every completed
1025			// fragment that was next in order, so what's left is one held back by a track
1026			// that stalled without ending. Write it anyway, earliest first, rather
1027			// than wait out a track that may never speak again.
1028			let flushable = self
1029				.tracks
1030				.iter()
1031				.filter_map(|(name, t)| {
1032					let first = crate::container::time(t.buffer.first()?.timestamp)?;
1033					(t.finished() || t.buffer.is_closed()).then(|| (first, !t.is_video, name.clone()))
1034				})
1035				.min()
1036				.map(|(_, _, name)| name);
1037
1038			if let Some(name) = flushable {
1039				let track = self.tracks.get_mut(&name).unwrap();
1040				let batch = track.buffer.take().unwrap();
1041				let fragment = emit_fragment(&name, track, &mut self.sequence_number, batch, None)?;
1042				if let Some(chunk) = self.deliver(name, fragment) {
1043					return Poll::Ready(Ok(Some(chunk)));
1044				}
1045				continue;
1046			}
1047
1048			// 7. If catalog is closed and every track is finished and drained, we're done.
1049			if self.init.written()
1050				&& !self.catalog.live()
1051				&& self.tracks.values().all(|t| t.finished() && t.buffer.is_empty())
1052			{
1053				return Poll::Ready(Ok(None));
1054			}
1055
1056			return Poll::Pending;
1057		}
1058	}
1059
1060	/// Hand a fragment to the caller, or queue it behind the init segment that has yet
1061	/// to go out.
1062	fn deliver(&mut self, name: String, fragment: Fragment) -> Option<Chunk> {
1063		match &mut self.init {
1064			Init::Written { .. } => Some(Chunk::Fragment(fragment)),
1065			Init::Waiting { queued, .. } => {
1066				queued.push_back((name, fragment));
1067				None
1068			}
1069		}
1070	}
1071
1072	/// The renditions holding up the init segment, by name.
1073	fn undescribed(&self) -> Vec<String> {
1074		let mut names: Vec<String> = self
1075			.tracks
1076			.iter()
1077			.filter(|(_, track)| !track.described())
1078			.map(|(name, _)| name.clone())
1079			.collect();
1080		names.sort();
1081		names
1082	}
1083
1084	/// The earliest completed group or ended track tail, if no track holds earlier content.
1085	fn completed_fragment(&self) -> Option<String> {
1086		let earliest = self.tracks.values().filter_map(Fmp4Track::next_start).min()?;
1087		self.tracks
1088			.iter()
1089			.filter_map(|(name, track)| {
1090				let first = crate::container::time(track.buffer.first()?.timestamp)?;
1091				// A stopped track's pending frame joins its buffer first.
1092				let complete = (track.finished() && track.pending.is_none())
1093					|| track.buffer.is_closed()
1094					|| (self.fragment_duration == Some(Duration::ZERO)
1095						&& track.buffer.last().is_some_and(|frame| frame.duration.is_some()));
1096				complete.then_some((first, !track.is_video, name))
1097			})
1098			.filter(|(start, _, _)| *start <= earliest)
1099			.min()
1100			.map(|(_, _, name)| name.clone())
1101	}
1102
1103	fn update_catalog(&mut self, catalog: &Catalog) -> Result<()> {
1104		// A rendition we can't parse is ignored rather than failing the whole export. (An
1105		// escaping `broadcast` reference is already gone: the catalog stream drops those.)
1106		let mut catalog = catalog.clone();
1107		catalog
1108			.video
1109			.renditions
1110			.retain(|name, config| crate::catalog::hang::supported(name, &config.container));
1111		catalog
1112			.audio
1113			.renditions
1114			.retain(|name, config| crate::catalog::hang::supported(name, &config.container));
1115		self.source.retain_selectable(&mut catalog);
1116
1117		let video = catalog
1118			.video
1119			.renditions
1120			.into_iter()
1121			.map(|(name, config)| (name, Rendition::Video(config)));
1122		let audio = catalog
1123			.audio
1124			.renditions
1125			.into_iter()
1126			.map(|(name, config)| (name, Rendition::Audio(config)));
1127
1128		let mut active = HashSet::new();
1129		let mut listed = HashSet::new();
1130		let mut spares = HashMap::new();
1131		for (name, config) in video.chain(audio) {
1132			// A name used by both a video and an audio rendition is the video one.
1133			if active.contains(&name) || !listed.insert(name.clone()) || self.retired.contains(&name) {
1134				continue;
1135			}
1136			if !self.tracks.contains_key(&name)
1137				&& !self.departed.contains_key(&name)
1138				&& self.init.written()
1139				&& !self.late
1140			{
1141				if !self.spares.contains_key(&name) {
1142					tracing::warn!(track = %name, "rendition joined after the init; it waits to continue a failed one");
1143				}
1144				spares.insert(name, config);
1145				continue;
1146			}
1147			if !self.tracks.contains_key(&name)
1148				&& let Some(track) = self.departed.remove(&name)
1149			{
1150				self.tracks.insert(name.clone(), track);
1151			}
1152			let moved = self
1153				.tracks
1154				.get(&name)
1155				.and_then(Fmp4Track::subscription)
1156				.is_some_and(|subscription| !config.read_by(&subscription.source, &self.source, &name));
1157			// Before the init nothing of a moved rendition went out, so it starts over as a new one.
1158			if moved && let Init::Waiting { queued, .. } = &mut self.init {
1159				self.tracks.remove(&name);
1160				queued.retain(|(queued, _)| *queued != name);
1161			}
1162			match self.tracks.get_mut(&name) {
1163				Some(track) if track.subscription().is_some() && !moved => track.reconfigure(&name, config)?,
1164				Some(track) => {
1165					let Some(source) = config.subscribe(&self.source, &name, self.delay)? else {
1166						continue;
1167					};
1168					// The publisher still caches the group the rendition left on, which a fresh
1169					// subscription would start at, so resume after what was read. A move is new
1170					// content, which continues past what was read under the declared track.
1171					let source = match std::mem::replace(&mut track.phase, Phase::Stopped) {
1172						Phase::Reading(previous) | Phase::Ended(previous) | Phase::Lost(previous) => {
1173							track.moved();
1174							source.continuing(&previous.source)
1175						}
1176						Phase::Departed(resume) => source.resuming(&resume),
1177						Phase::Stopped => source,
1178					};
1179					track.rejoin(&name, config, source)?;
1180				}
1181				None => {
1182					// Subscribe via ExportSource, which applies any per-codec transform
1183					// (Annex-B → length-prefixed) at pull time.
1184					let Some(source) = config.subscribe(&self.source, &name, self.delay)? else {
1185						continue;
1186					};
1187					let mut track = Fmp4Track::new(source, config, self.next_track_id)?;
1188					self.next_track_id += 1;
1189					track.describe(&name)?;
1190					self.tracks.insert(name.clone(), track);
1191				}
1192			}
1193			active.insert(name);
1194		}
1195
1196		match &mut self.init {
1197			Init::Written { first_late, .. } => {
1198				// The init declared these tracks, so keep them for a rendition that returns.
1199				// Ending the subscription writes out what was already read. A failed track stays
1200				// for a spare to continue, which may join as its rendition leaves.
1201				for (name, track) in &mut self.tracks {
1202					if !active.contains(name) && !track.lost() {
1203						track.depart();
1204					}
1205				}
1206				// A departed track still holding media waits for the next catalog to move.
1207				let drained = self.tracks.extract_if(|_, track| {
1208					track.subscription().is_none() && track.pending.is_none() && track.buffer.is_empty()
1209				});
1210				for (name, track) in drained {
1211					if track.written.is_some() || track.track_id < *first_late {
1212						self.departed.insert(name, track);
1213					}
1214				}
1215			}
1216			Init::Waiting { queued, .. } => {
1217				self.tracks.retain(|name, _| active.contains(name));
1218				queued.retain(|(name, _)| active.contains(name));
1219			}
1220		}
1221		self.retired.retain(|name| listed.contains(name));
1222		self.spares = spares;
1223		self.settle_spares().map(|_| ())
1224	}
1225
1226	/// Whether the export outlives the failure of track `name`, which ended it.
1227	///
1228	/// A spare of its medium continues it at once. Otherwise, while another track still reads,
1229	/// only that rendition ends: a publisher that loses a source, such as a microphone, may list
1230	/// a replacement, which continues it then. With nothing left reading, the failure is the
1231	/// export's, as before.
1232	///
1233	/// Returns whether a spare continued a track, whose new source has yet to be polled.
1234	fn survive(&mut self, name: &str, err: crate::Error) -> Result<bool> {
1235		// Before the init a track that could not be described declares nothing, and its rendition
1236		// is not read again while the publisher keeps it listed.
1237		if !self.init.written()
1238			&& let Some(track) = self.tracks.get(name)
1239			&& !track.described()
1240		{
1241			self.tracks.remove(name);
1242			self.retired.insert(name.to_string());
1243		}
1244		let continued = self.settle_spares()?;
1245		if !self
1246			.tracks
1247			.values()
1248			.any(|track| matches!(track.phase, Phase::Reading(_)))
1249		{
1250			return Err(err);
1251		}
1252		if self.tracks.get(name).is_some_and(Fmp4Track::lost) {
1253			tracing::warn!(track = name, %err, "rendition failed; the export keeps its other media");
1254		}
1255		Ok(continued)
1256	}
1257
1258	/// Continue each failed track with a spare of its medium, holding the other spares while a
1259	/// track of their medium still reads. Failing that, a spare continues a declared track of its
1260	/// medium that left the catalog, which may have failed unread as its rendition left: a
1261	/// publisher can retire the failed rendition in the snapshot that lists its replacement. A
1262	/// spare with none of these is a new rendition the init never declared, which fails the
1263	/// export. Returns whether a spare continued a track, whose new source has yet to be polled.
1264	fn settle_spares(&mut self) -> Result<bool> {
1265		let mut names: Vec<String> = self.spares.keys().cloned().collect();
1266		names.sort();
1267		let mut continued = false;
1268		for name in names {
1269			let is_video = self.spares[&name].is_video();
1270			let medium = |track: &Fmp4Track| track.is_video == is_video;
1271			let pick = |tracks: &HashMap<String, Fmp4Track>, phase: fn(&Phase) -> bool| {
1272				tracks
1273					.iter()
1274					.filter(|(_, track)| medium(track) && phase(&track.phase))
1275					.map(|(key, track)| (track.track_id, key.clone()))
1276					.min()
1277					.map(|(_, key)| key)
1278			};
1279			let reading = self
1280				.tracks
1281				.values()
1282				.any(|track| medium(track) && matches!(track.phase, Phase::Reading(_)));
1283			let lost = pick(&self.tracks, |phase| matches!(phase, Phase::Lost(_)));
1284			let track = match lost {
1285				Some(key) => self.tracks.remove(&key).map(|track| (key, track)),
1286				None if reading => continue,
1287				None => match pick(&self.tracks, |phase| matches!(phase, Phase::Departed(_))) {
1288					Some(key) => self.tracks.remove(&key).map(|track| (key, track)),
1289					None => pick(&self.departed, |_| true).and_then(|key| self.departed.remove_entry(&key)),
1290				},
1291			};
1292			let Some((previous, mut track)) = track else {
1293				return Err(Error::TrackAdded(name).into());
1294			};
1295			let config = self.spares.remove(&name).expect("a listed spare");
1296			let Some(source) = config.subscribe(&self.source, &name, self.delay)? else {
1297				// The catalog entry names no track to read, so the declared track stays as it was.
1298				match track.phase {
1299					Phase::Departed(_) if track.subscription().is_none() && track.buffer.is_empty() => {
1300						self.departed.insert(previous, track)
1301					}
1302					_ => self.tracks.insert(previous, track),
1303				};
1304				continue;
1305			};
1306			let source = match std::mem::replace(&mut track.phase, Phase::Stopped) {
1307				Phase::Lost(failed) => {
1308					self.retired.insert(previous.clone());
1309					source.continuing(&failed.source)
1310				}
1311				Phase::Departed(resume) => source.resuming(&resume),
1312				_ => unreachable!("picked a lost or departed track"),
1313			};
1314			tracing::info!(track = %name, replaces = %previous, "continuing a declared rendition");
1315			track.moved();
1316			track.rejoin(&name, config, source)?;
1317			self.tracks.insert(name, track);
1318			continued = true;
1319		}
1320		Ok(continued)
1321	}
1322
1323	/// The bytes of media the export holds between its sources and the output.
1324	#[cfg(test)]
1325	pub(super) fn held(&self) -> usize {
1326		let frames = self.tracks.values().flat_map(|track| {
1327			let buffered = track.buffer.batch().into_iter().flat_map(|batch| &batch.frames);
1328			buffered.chain(&track.pending)
1329		});
1330		let queued = match &self.init {
1331			Init::Waiting { queued, .. } => queued.iter().map(|(_, fragment)| fragment).collect::<Vec<_>>(),
1332			Init::Written { queued, .. } => queued.iter().collect(),
1333		};
1334		frames.map(|frame| frame.payload.len()).sum::<usize>()
1335			+ queued.iter().map(|fragment| fragment.data.len()).sum::<usize>()
1336	}
1337
1338	/// True once every track can be described, so the merged init segment can be built.
1339	fn init_ready(&self) -> bool {
1340		!self.tracks.is_empty() && self.tracks.values().all(Fmp4Track::described)
1341	}
1342
1343	/// Build the merged ftyp + multi-track moov init segment, video first, each kind in
1344	/// the order its renditions joined.
1345	fn build_init(&self) -> Result<Bytes> {
1346		let mut tracks: Vec<&Fmp4Track> = self.tracks.values().collect();
1347		tracks.sort_by_key(|track| (!track.is_video, track.track_id));
1348
1349		let mut traks = Vec::new();
1350		let mut trexs = Vec::new();
1351		let mut ftyp = None;
1352		for track in tracks {
1353			let declaration = track.declaration.as_ref().expect("init_ready checked every track");
1354			ftyp = ftyp.or_else(|| declaration.ftyp.clone());
1355			traks.push(declaration.trak.clone());
1356			trexs.push(declaration.trex.clone());
1357		}
1358
1359		Ok(crate::container::fmp4::encode_init(ftyp, traks, trexs)?)
1360	}
1361}
1362
1363/// Pull ftyp + moov from a single-track CMAF init segment and merge into the
1364/// caller's accumulators, rewriting the track id to `track_id`.
1365///
1366/// The source init carries whatever id the track had in ITS broadcast (e.g. an
1367/// audio track that was second in the source is `2`), but our fragments are always
1368/// re-encoded with the exporter's own `track.track_id` (see [`encode_fragment`]) --
1369/// nothing is passed through. So the moov MUST adopt that same id, or a player
1370/// loads an init declaring track N and then a fragment claiming a different track
1371/// and rejects it ("no tfhd for track"). It also keeps a merged multi-track moov
1372/// from colliding when two single-track source inits both used id `1`.
1373pub(crate) fn extract_init(
1374	init: &Bytes,
1375	track_id: u32,
1376	ftyp_data: &mut Option<mp4_atom::Ftyp>,
1377	traks: &mut Vec<mp4_atom::Trak>,
1378	trexs: &mut Vec<mp4_atom::Trex>,
1379) -> Result<()> {
1380	let mut cursor = std::io::Cursor::new(init.as_ref());
1381	while let Some(atom) = mp4_atom::Any::decode_maybe(&mut cursor).map_err(crate::Error::mp4)? {
1382		match atom {
1383			mp4_atom::Any::Ftyp(f) if ftyp_data.is_none() => {
1384				*ftyp_data = Some(f);
1385			}
1386			mp4_atom::Any::Moov(moov) => {
1387				for mut trak in moov.trak {
1388					trak.tkhd.track_id = track_id;
1389					// Import already applied the source edit to Hang timestamps. Drop
1390					// it here; encode_init restores only Opus priming's inverse mapping
1391					// after the output track timescales have been settled.
1392					trak.edts = None;
1393					// tkhd.duration is in the *movie* timescale, and the merged moov
1394					// picks its own (the first trak's media scale), so whatever the
1395					// source stated is now read at a scale it wasn't written in. A
1396					// merged multi-track moov can't hold one scale that suits every
1397					// source anyway, so declare it unknown like the rest of the init.
1398					trak.tkhd.duration = super::UNKNOWN_DURATION;
1399					traks.push(trak);
1400				}
1401				if let Some(mvex) = moov.mvex {
1402					for mut trex in mvex.trex {
1403						trex.track_id = track_id;
1404						trexs.push(trex);
1405					}
1406				}
1407			}
1408			_ => {}
1409		}
1410	}
1411	Ok(())
1412}
1413
1414/// Should we flush `buffer` before appending the incoming `frame`?
1415///
1416/// Triggers when `frame` opens a group, or on the duration cap. The keyframe bit is the
1417/// group boundary on every track: a video keyframe closes a GOP, and an audio frame
1418/// carries it only where the publisher cut a group, which is the boundary the file
1419/// should keep rather than one invented here. Per-frame output is handled before
1420/// this check.
1421fn should_flush(buffer: &Buffer, frame: &Frame, fragment_duration: Option<Duration>) -> bool {
1422	let batch = match buffer {
1423		Buffer::Empty => return false,
1424		Buffer::Closed(_) => return true,
1425		Buffer::Open(batch) => batch,
1426	};
1427	if frame.keyframe {
1428		return true;
1429	}
1430	let Some(cap) = fragment_duration else {
1431		return false;
1432	};
1433	// Frames within a track are in *decode* order; B-frames have non-monotonic
1434	// PTS, so the span of the buffer is min..max of all PTS.
1435	let mut ptss = std::iter::once(frame)
1436		.chain(&batch.frames)
1437		.filter_map(|f| crate::container::time(f.timestamp));
1438	let Some(first) = ptss.next() else {
1439		return false;
1440	};
1441	let (min, max) = ptss.fold((first, first), |(min, max), pts| (min.min(pts), max.max(pts)));
1442	max.saturating_sub(min) >= cap
1443}
1444
1445/// Encode a buffered run of samples as a single CMAF moof+mdat fragment,
1446/// consuming the next `mfhd` sequence number of the file.
1447///
1448/// A run that opens a GOP (and every audio run) anchors its `tfdt` at its first frame's
1449/// presentation time, which re-syncs the decode timeline after a gap the durations did not
1450/// cover. A run cut inside a GOP continues the timeline where the track's previous fragment
1451/// ended, so decode times never step back however the GOP is reordered.
1452fn encode_fragment(
1453	track: &mut Fmp4Track,
1454	sequence_number: &mut u32,
1455	frames: Vec<Frame>,
1456	opens_gop: bool,
1457) -> Result<Bytes> {
1458	let Some(first) = frames.first() else {
1459		return Err(Error::NoFrames.into());
1460	};
1461	let timescale = moq_net::Timescale::new(track.timescale)?;
1462	let base_dts = match track.decode_end {
1463		Some(end) if !opens_gop => end,
1464		_ => super::base_ticks(first, timescale)?,
1465	};
1466	let info = crate::container::fmp4::FragmentInfo {
1467		track_id: track.track_id,
1468		timescale,
1469		sequence_number: *sequence_number,
1470		kind: if track.is_video {
1471			super::Kind::Video
1472		} else {
1473			super::Kind::Audio
1474		},
1475	};
1476	let (data, decode_end) = super::encode_at(info, base_dts, &frames)?;
1477	*sequence_number += 1;
1478	track.decode_end = Some(decode_end);
1479	Ok(data)
1480}
1481
1482/// Encode a buffered run and wrap it with the metadata a segmenting consumer needs.
1483///
1484/// A fragment that starts at a sync sample must start after everything the track already
1485/// wrote. A keyframe presents after every frame decoded before it, so only a source that
1486/// went back in time breaks this, such as a resubscription replaying cached groups.
1487fn emit_fragment(
1488	name: &str,
1489	track: &mut Fmp4Track,
1490	sequence_number: &mut u32,
1491	batch: Batch,
1492	successor: Option<&Frame>,
1493) -> Result<Fragment> {
1494	let Batch {
1495		mut frames,
1496		independent,
1497	} = batch;
1498	apply_codec_durations(&mut frames, track.opus);
1499	// A run that starts or ends inside a GOP sees only part of its reordering.
1500	let partial = !independent || successor.is_some_and(|next| !next.keyframe);
1501	// Every audio sample is independently decodable, so every audio fragment is
1502	// independent; video is only when its buffer opened on a keyframe (a GOP boundary).
1503	let independent = !track.is_video || independent;
1504	if let (Some(first), Some(written)) = (frames.first(), track.written) {
1505		let start = Duration::try_from(first.timestamp)?;
1506		if independent && start <= written {
1507			return Err(Error::TrackRewound {
1508				track: name.to_string(),
1509				start,
1510				written,
1511			}
1512			.into());
1513		}
1514	}
1515	for frame in &frames {
1516		track.written = track.written.max(Some(Duration::try_from(frame.timestamp)?));
1517	}
1518	let timescale = moq_net::Timescale::new(track.timescale)?;
1519	let run = if partial && track.config.may_reorder() {
1520		Run::PartialGop
1521	} else {
1522		Run::Whole
1523	};
1524	infer_missing_durations(&mut frames, successor, track.default_frame, timescale, run)?;
1525	let duration = fragment_duration(&frames, track.default_frame, timescale)?;
1526	let data = encode_fragment(track, sequence_number, frames, independent)?;
1527	Ok(Fragment {
1528		data,
1529		independent,
1530		duration,
1531	})
1532}
1533
1534/// Presentation duration of a fragment.
1535///
1536/// When every sample carries a duration (the CMAF case) the per-sample durations
1537/// tile the timeline, so their sum is exact. Legacy / LOC sources carry none, so
1538/// fall back to the presentation span plus one `default_frame` for the trailing
1539/// sample (which has no successor to bound it).
1540fn fragment_duration(frames: &[Frame], default_frame: Duration, timescale: moq_net::Timescale) -> Result<Duration> {
1541	if frames.is_empty() {
1542		return Ok(Duration::ZERO);
1543	}
1544	if frames
1545		.iter()
1546		.all(|f| f.duration.is_some_and(|duration| !duration.is_zero()))
1547	{
1548		// Sum output ticks before converting once, so per-sample nanosecond rounding cannot accumulate.
1549		let ticks = frames.iter().try_fold(0u64, |sum, frame| -> Result<u64> {
1550			let ticks = super::trun_duration(frame.duration.unwrap(), timescale)?;
1551			sum.checked_add(u64::from(ticks))
1552				.ok_or_else(|| moq_net::TimeOverflow.into())
1553		})?;
1554		return Ok(Timestamp::new(ticks, timescale)?.try_into()?);
1555	}
1556	let mut min = Duration::MAX;
1557	let mut max = Duration::ZERO;
1558	for f in frames {
1559		let pts = Duration::try_from(f.timestamp)?;
1560		min = min.min(pts);
1561		max = max.max(pts);
1562	}
1563	Ok((max - min) + default_frame)
1564}
1565
1566/// Fill in the durations the codec states outright, before anything has to be inferred
1567/// from a neighbouring frame.
1568///
1569/// Opus packets carry their duration in the TOC byte (at 48 kHz), so an Opus track never
1570/// has to look at its neighbours at all -- which matters most at a group boundary, where
1571/// the neighbour is off limits (see [`infer_missing_durations`]) and the fallback would
1572/// otherwise mis-time every packet of a one-packet-per-group audio track.
1573pub(crate) fn apply_codec_durations(frames: &mut [Frame], opus: bool) {
1574	if !opus {
1575		return;
1576	}
1577	for frame in frames {
1578		if frame.duration.is_none() {
1579			frame.duration = crate::codec::opus::packet_samples(&frame.payload)
1580				.and_then(|samples| Timestamp::from_scale(samples as u64, 48_000).ok());
1581		}
1582	}
1583}
1584
1585/// Fill in the duration of every remaining frame from the timestamp of the frame that
1586/// follows it, as long as that frame is in the same group.
1587///
1588/// The gap between two frames is only a duration while they sit on one continuous
1589/// timeline, and a group boundary is where that stops holding. Groups are independently
1590/// decodable, so a publisher may pause and resume across one (moq-boy keeps its PTS on a
1591/// clock that runs through the pause), a subscriber may join mid-stream or skip to a
1592/// newer group, and a fetch may span a hole. Consecutive sequence numbers do not rule any
1593/// of that out, so the gap across a boundary is treated as a discontinuity, never a
1594/// duration. Reading it as one makes a single sample last as long as the gap: a recording
1595/// that woke a paused publisher got a 2405 second video sample, whose `EXTINF` put the HLS
1596/// video timeline 9620 seconds ahead of audio and stalled the player outright.
1597///
1598/// The last frame before a boundary falls back to `default_frame` (the catalog framerate /
1599/// sample rate), which is what the gap works out to anyway on a continuous constant-rate
1600/// source -- the two answers only diverge when there IS a gap.
1601///
1602/// The publisher is the one that actually knows where its group's content ends, and
1603/// [`Producer::cut`](crate::container::Producer::cut) is how it says so: the durations it
1604/// writes arrive already set and are left alone here.
1605///
1606/// Frames arrive in decode order, so a gap is a decode duration only when presentation order
1607/// matches it. A run whose timestamps go backwards is reordered video, and every frame takes
1608/// the catalog cadence. A [`Run::PartialGop`] cannot rule reordering out from its own frames,
1609/// since the B-frames that would reveal it may sit in a neighbouring run, so no gap there may
1610/// exceed the cadence: in reordered video the gap to the next frame decoded spans the frames
1611/// decoded after it, and a longer duration would push the decode timeline past the next GOP.
1612pub(crate) fn infer_missing_durations(
1613	frames: &mut [Frame],
1614	successor: Option<&Frame>,
1615	default_frame: Duration,
1616	timescale: moq_net::Timescale,
1617	run: Run,
1618) -> Result<()> {
1619	let infer_from_pts = pts_monotonic(frames, successor);
1620	let cadence = fallback_duration(default_frame, timescale);
1621
1622	for i in 0..frames.len() {
1623		let successor = infer_from_pts
1624			.then(|| duration_bound(frames, successor, i))
1625			.flatten()
1626			.cloned();
1627		let stated = frames[i].duration.is_some_and(|duration| !duration.is_zero());
1628		infer_missing_duration(&mut frames[i], successor.as_ref(), default_frame, timescale)?;
1629		if run == Run::PartialGop
1630			&& !stated
1631			&& let (Some(inferred), Some(cadence)) = (frames[i].duration, cadence)
1632			&& let (Some(longer), Some(shorter)) = (crate::container::time(inferred), crate::container::time(cadence))
1633			&& longer > shorter
1634		{
1635			frames[i].duration = Some(cadence);
1636		}
1637	}
1638
1639	Ok(())
1640}
1641
1642/// How much of its reordering a run of frames passed to [`infer_missing_durations`] shows.
1643#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1644pub(crate) enum Run {
1645	/// Whole GOPs, or media that presents in decode order, so its own timestamps show
1646	/// whether it is reordered.
1647	Whole,
1648	/// Video that may reorder, cut inside a GOP, whose reordering may only show in a
1649	/// neighbouring run.
1650	PartialGop,
1651}
1652
1653/// Infer one frame's duration from a known same-group successor, else the catalog cadence.
1654pub(crate) fn infer_missing_duration(
1655	frame: &mut Frame,
1656	successor: Option<&Frame>,
1657	default_frame: Duration,
1658	timescale: moq_net::Timescale,
1659) -> Result<()> {
1660	if frame.duration.is_some_and(|duration| !duration.is_zero()) {
1661		return Ok(());
1662	}
1663
1664	frame.duration = match successor {
1665		Some(next) => timestamp_gap(frame.timestamp, next.timestamp, timescale)?,
1666		None => None,
1667	}
1668	.or_else(|| fallback_duration(default_frame, timescale))
1669	.filter(|duration| !duration.is_zero());
1670	Ok(())
1671}
1672
1673/// Snap floating-point catalog cadence to an output tick only when the mismatch is no more
1674/// than the nanosecond precision used by `Duration`.
1675fn fallback_duration(default_frame: Duration, timescale: moq_net::Timescale) -> Option<Timestamp> {
1676	if let Some(ticks) = super::rounded_duration_ticks(default_frame, timescale.as_u64()) {
1677		Timestamp::new(ticks, timescale).ok()
1678	} else {
1679		Timestamp::try_from(default_frame).ok()
1680	}
1681}
1682
1683/// Quantize two absolute instants at the output scale, then subtract their tick positions.
1684///
1685/// Quantizing endpoints instead of each gap independently carries fractional ticks forward:
1686/// a microsecond clock alternating 33,333 and 33,334 microsecond steps at 30 kHz produces
1687/// consecutive 1,000-tick samples instead of either drifting or failing as inexact.
1688///
1689/// `None` when `end` does not land on a later tick: a backwards gap, or two instants this
1690/// scale cannot tell apart, which time nothing just as a repeated timestamp does.
1691pub(super) fn timestamp_gap(
1692	start: Timestamp,
1693	end: Timestamp,
1694	timescale: moq_net::Timescale,
1695) -> Result<Option<Timestamp>> {
1696	let start_ticks = super::timestamp_ticks(start, timescale)?;
1697	let end_ticks = super::timestamp_ticks(end, timescale)?;
1698	match end_ticks.checked_sub(start_ticks) {
1699		Some(ticks) if ticks > 0 => Ok(Some(Timestamp::new(ticks, timescale)?)),
1700		_ => Ok(None),
1701	}
1702}
1703
1704fn pts_monotonic(frames: &[Frame], successor: Option<&Frame>) -> bool {
1705	let frames_monotonic = frames.windows(2).all(|pair| pair[1].timestamp >= pair[0].timestamp);
1706	// Only a successor we'd actually read from gets a say: one in the next group bounds
1707	// nothing here, so a rewind across that boundary must not veto inference either.
1708	let successor_monotonic = match (frames.last(), successor.filter(|next| !next.keyframe)) {
1709		(Some(last), Some(successor)) => successor.timestamp >= last.timestamp,
1710		_ => true,
1711	};
1712	frames_monotonic && successor_monotonic
1713}
1714
1715/// The frame that bounds `frames[index]`'s duration, or `None` when the only candidate is
1716/// in the next group.
1717///
1718/// Every group starts with a keyframe -- the wire may carry the flag, and
1719/// [`Consumer`](crate::container::Consumer) asserts it on each group's first frame
1720/// regardless -- so a keyframe is where a group boundary can be. Video only ever meets one
1721/// as the successor (a keyframe flushes the fragment before it can be appended), but audio
1722/// has no keyframe roll, so a boundary can also fall interior to `frames`; both land here.
1723fn duration_bound<'a>(frames: &'a [Frame], successor: Option<&'a Frame>, index: usize) -> Option<&'a Frame> {
1724	frames.get(index + 1).or(successor).filter(|next| !next.keyframe)
1725}
1726
1727pub(crate) fn catalog_timescale_video(config: &VideoConfig) -> Result<u64> {
1728	Ok(match &config.container {
1729		Container::Cmaf { init, .. } => {
1730			parse_timescale_from_init(init).unwrap_or_else(|_| crate::container::fmp4::default_video_timescale(config))
1731		}
1732		Container::Loc | Container::Legacy | Container::Raw | Container::Cts => {
1733			crate::container::fmp4::default_video_timescale(config)
1734		}
1735		Container::Unknown(unknown) => return Err(crate::Error::unsupported_container(unknown)),
1736	})
1737}
1738
1739pub(crate) fn catalog_timescale_audio(config: &hang::catalog::AudioConfig) -> Result<u64> {
1740	Ok(match &config.container {
1741		Container::Cmaf { init, .. } => parse_timescale_from_init(init).unwrap_or(config.sample_rate as u64),
1742		Container::Loc | Container::Legacy | Container::Raw | Container::Cts => config.sample_rate as u64,
1743		Container::Unknown(unknown) => return Err(crate::Error::unsupported_container(unknown)),
1744	})
1745}
1746
1747fn parse_timescale_from_init(init: &[u8]) -> Result<u64> {
1748	let mut cursor = std::io::Cursor::new(init);
1749	while let Some(atom) = mp4_atom::Any::decode_maybe(&mut cursor).map_err(crate::Error::mp4)? {
1750		if let mp4_atom::Any::Moov(moov) = atom {
1751			let trak = moov.trak.first().ok_or(Error::NoTracks)?;
1752			return Ok(trak.mdia.mdhd.timescale as u64);
1753		}
1754	}
1755	Err(Error::NoMoov.into())
1756}
1757
1758#[cfg(test)]
1759mod tests {
1760	use bytes::Bytes;
1761
1762	use super::*;
1763
1764	fn ts(micros: u64) -> Timestamp {
1765		Timestamp::from_micros(micros).unwrap()
1766	}
1767
1768	fn duration_micros(frame: &Frame) -> u128 {
1769		frame.duration.unwrap().as_micros().unwrap()
1770	}
1771
1772	fn frame(timestamp_us: u64, duration_us: Option<u64>) -> Frame {
1773		Frame {
1774			timestamp: ts(timestamp_us),
1775			decode: None,
1776			duration: duration_us.map(ts),
1777			payload: Bytes::from_static(&[0xDE, 0xAD]),
1778			keyframe: false,
1779		}
1780	}
1781
1782	// A rendition moving off a track whose group already closed keeps that fragment.
1783	#[test]
1784	fn closing_a_closed_buffer_keeps_its_frames() {
1785		let mut buffer = Buffer::Empty;
1786		buffer.push(group_start(0));
1787		buffer.close();
1788		buffer.close();
1789		assert!(buffer.is_closed());
1790		assert_eq!(buffer.take().map(|batch| batch.frames.len()), Some(1));
1791	}
1792
1793	/// A frame that opens a group. Every group starts with a keyframe, so this is what
1794	/// the far side of a group boundary looks like to `infer_missing_durations`.
1795	fn group_start(timestamp_us: u64) -> Frame {
1796		Frame {
1797			keyframe: true,
1798			..frame(timestamp_us, None)
1799		}
1800	}
1801
1802	#[test]
1803	fn infer_missing_durations_uses_default_for_trailing_sample() {
1804		let mut frames = vec![frame(0, Some(0)), frame(41_667, None), frame(83_334, None)];
1805		infer_missing_durations(
1806			&mut frames,
1807			None,
1808			Duration::from_millis(33),
1809			moq_net::Timescale::MICRO,
1810			Run::Whole,
1811		)
1812		.unwrap();
1813
1814		assert_eq!(frames[0].duration, Some(ts(41_667)));
1815		assert_eq!(frames[1].duration, Some(ts(41_667)));
1816		assert_eq!(frames[2].duration, Some(ts(33_000)));
1817		assert_eq!(
1818			fragment_duration(
1819				&frames,
1820				Duration::from_millis(33),
1821				frames[0].duration.unwrap().scale().unwrap()
1822			)
1823			.unwrap(),
1824			Duration::from_micros(116_334)
1825		);
1826	}
1827
1828	#[test]
1829	fn infer_missing_duration_uses_default_for_single_frame() {
1830		let mut frames = vec![frame(83_333, Some(0))];
1831		infer_missing_durations(
1832			&mut frames,
1833			None,
1834			Duration::from_millis(40),
1835			moq_net::Timescale::MICRO,
1836			Run::Whole,
1837		)
1838		.unwrap();
1839
1840		assert_eq!(frames[0].duration, Some(ts(40_000)));
1841		assert_eq!(
1842			fragment_duration(
1843				&frames,
1844				Duration::from_millis(40),
1845				frames[0].duration.unwrap().scale().unwrap()
1846			)
1847			.unwrap(),
1848			Duration::from_millis(40)
1849		);
1850	}
1851
1852	/// The duration cap splits a GOP across fragments, so the successor is a delta frame
1853	/// in the SAME group. In video that presents in decode order that one is a real bound
1854	/// and is still used.
1855	#[test]
1856	fn infer_trailing_duration_from_successor_frame() {
1857		let successor = frame(83_334, None);
1858		let mut frames = vec![frame(41_667, None)];
1859		infer_missing_durations(
1860			&mut frames,
1861			Some(&successor),
1862			Duration::from_millis(33),
1863			moq_net::Timescale::MICRO,
1864			Run::Whole,
1865		)
1866		.unwrap();
1867
1868		assert_eq!(frames[0].duration, Some(ts(41_667)));
1869		assert_eq!(
1870			fragment_duration(
1871				&frames,
1872				Duration::from_millis(33),
1873				frames[0].duration.unwrap().scale().unwrap()
1874			)
1875			.unwrap(),
1876			Duration::from_micros(41_667)
1877		);
1878	}
1879
1880	/// Video that may reorder, cut inside a GOP, cannot tell a reference frame's gap to the
1881	/// B-frames decoded after it from a duration, so no inferred duration there exceeds the
1882	/// cadence. A shorter gap still times its frame, and a stated duration is kept.
1883	#[test]
1884	fn a_partial_gop_caps_inferred_durations_at_the_cadence() {
1885		let successor = frame(100_000, None);
1886		let mut frames = vec![frame(0, Some(50_000)), frame(10_000, None), frame(20_000, None)];
1887		infer_missing_durations(
1888			&mut frames,
1889			Some(&successor),
1890			Duration::from_millis(33),
1891			moq_net::Timescale::MICRO,
1892			Run::PartialGop,
1893		)
1894		.unwrap();
1895
1896		let durations: Vec<_> = frames.iter().map(duration_micros).collect();
1897		assert_eq!(durations, vec![50_000, 10_000, 33_000]);
1898	}
1899
1900	/// The last frame lands 11 us after its predecessor, the one-tick 90 kHz bump ffmpeg gives
1901	/// a repeated DTS. Both quantize to one output tick, so the earlier frame falls back to
1902	/// the cadence, as it does for a repeated timestamp.
1903	#[test]
1904	fn inferred_microsecond_clock_carries_fractional_ticks_forward() {
1905		let timescale = moq_net::Timescale::new(30_000).unwrap();
1906		let mut frames = vec![
1907			frame(0, None),
1908			frame(33_333, None),
1909			frame(66_667, None),
1910			frame(66_678, None),
1911		];
1912		infer_missing_durations(
1913			&mut frames,
1914			None,
1915			Duration::from_nanos(33_333_333),
1916			timescale,
1917			Run::Whole,
1918		)
1919		.unwrap();
1920
1921		let durations: Vec<_> = frames
1922			.iter()
1923			.map(|frame| {
1924				let duration = frame.duration.unwrap();
1925				(duration.value(), duration.scale())
1926			})
1927			.collect();
1928		assert_eq!(durations, vec![(1_000, Some(timescale)); 4]);
1929	}
1930
1931	/// The regression for the stalled HLS player: a subscriber that got a stale cached group
1932	/// and then jumped to live sees a huge gap across the boundary. That gap is a
1933	/// discontinuity, not a duration, so the frame before it must NOT swallow it -- it
1934	/// takes `default_frame` and the fragment stays one frame long.
1935	#[test]
1936	fn infer_stops_at_a_group_boundary() {
1937		let next_group = group_start(2_405_070_000);
1938		let mut frames = vec![frame(63_244, None)];
1939		infer_missing_durations(
1940			&mut frames,
1941			Some(&next_group),
1942			Duration::from_millis(33),
1943			moq_net::Timescale::MICRO,
1944			Run::Whole,
1945		)
1946		.unwrap();
1947
1948		assert_eq!(frames[0].duration, Some(ts(33_000)));
1949		assert_eq!(
1950			fragment_duration(
1951				&frames,
1952				Duration::from_millis(33),
1953				frames[0].duration.unwrap().scale().unwrap()
1954			)
1955			.unwrap(),
1956			Duration::from_millis(33)
1957		);
1958	}
1959
1960	/// The HLS fetch origin concatenates a segment's groups into one fragment, so a
1961	/// boundary can sit interior to `frames`. It bounds the frame before it just the
1962	/// same.
1963	#[test]
1964	fn infer_stops_at_an_interior_group_boundary() {
1965		let mut frames = vec![frame(0, None), frame(21_333, None), group_start(600_000_000)];
1966		infer_missing_durations(
1967			&mut frames,
1968			None,
1969			Duration::from_millis(21),
1970			moq_net::Timescale::MICRO,
1971			Run::Whole,
1972		)
1973		.unwrap();
1974
1975		assert_eq!(frames[0].duration, Some(ts(21_333)), "same group, real delta");
1976		assert_eq!(duration_micros(&frames[1]), 21_000, "bounded by the next group");
1977		assert_eq!(duration_micros(&frames[2]), 21_000, "nothing after it at all");
1978	}
1979
1980	/// The HLS fetch origin concatenates a segment's groups, and for audio those are often
1981	/// one packet each -- so EVERY packet sits at a boundary and none of them may be timed
1982	/// by the next. Opus states its own duration, which is what keeps that exact instead of
1983	/// dropping each packet onto the ~21.3 ms `1024/sample_rate` fallback.
1984	#[test]
1985	fn codec_durations_keep_one_packet_groups_exact() {
1986		// 20 ms of 48 kHz stereo Opus: TOC config 15 (SILK/WB 20 ms), one frame.
1987		let packet = Bytes::from_static(&[0x78, 0x00, 0x00, 0x00]);
1988		let mut frames: Vec<Frame> = (0..3)
1989			.map(|i| Frame {
1990				payload: packet.clone(),
1991				..group_start(i * 20_000)
1992			})
1993			.collect();
1994
1995		apply_codec_durations(&mut frames, true);
1996		infer_missing_durations(
1997			&mut frames,
1998			None,
1999			Duration::from_micros(21_333),
2000			moq_net::Timescale::MICRO,
2001			Run::Whole,
2002		)
2003		.unwrap();
2004
2005		for f in &frames {
2006			assert_eq!(
2007				f.duration.unwrap().as_micros().unwrap(),
2008				20_000,
2009				"TOC duration, not the fallback"
2010			);
2011		}
2012	}
2013
2014	/// A rewind across a group boundary bounds nothing here, so it must not veto
2015	/// inference for the frames that do have an in-group successor.
2016	#[test]
2017	fn infer_ignores_a_rewound_group_boundary() {
2018		let next_group = group_start(0);
2019		let mut frames = vec![frame(1_000_000, None), frame(1_033_000, None)];
2020		infer_missing_durations(
2021			&mut frames,
2022			Some(&next_group),
2023			Duration::from_millis(50),
2024			moq_net::Timescale::MICRO,
2025			Run::Whole,
2026		)
2027		.unwrap();
2028
2029		assert_eq!(
2030			frames[0].duration,
2031			Some(ts(33_000)),
2032			"in-group delta survives the rewind"
2033		);
2034		assert_eq!(duration_micros(&frames[1]), 50_000, "last in group falls back");
2035	}
2036
2037	#[test]
2038	fn infer_missing_durations_avoids_non_monotonic_pts() {
2039		let successor = frame(66_000, None);
2040		let mut frames = vec![frame(0, None), frame(99_000, None), frame(33_000, None)];
2041		infer_missing_durations(
2042			&mut frames,
2043			Some(&successor),
2044			Duration::from_millis(33),
2045			moq_net::Timescale::MICRO,
2046			Run::Whole,
2047		)
2048		.unwrap();
2049
2050		assert_eq!(frames[0].duration, Some(ts(33_000)));
2051		assert_eq!(frames[1].duration, Some(ts(33_000)));
2052		assert_eq!(frames[2].duration, Some(ts(33_000)));
2053		assert_eq!(
2054			fragment_duration(
2055				&frames,
2056				Duration::from_millis(33),
2057				frames[0].duration.unwrap().scale().unwrap()
2058			)
2059			.unwrap(),
2060			Duration::from_micros(99_000)
2061		);
2062	}
2063
2064	// Import already applied the source edit to Hang timestamps. Export must discard it
2065	// before encode_init rebuilds any codec-specific presentation shift.
2066	#[test]
2067	fn extract_init_strips_edit_lists() {
2068		use mp4_atom::Encode;
2069
2070		let trak = mp4_atom::Trak {
2071			edts: Some(mp4_atom::Edts {
2072				elst: Some(mp4_atom::Elst {
2073					entries: vec![mp4_atom::ElstEntry::default()],
2074				}),
2075			}),
2076			..Default::default()
2077		};
2078		let moov = mp4_atom::Moov {
2079			trak: vec![trak],
2080			..Default::default()
2081		};
2082		let mut init = Vec::new();
2083		moov.encode(&mut init).unwrap();
2084
2085		let mut traks = Vec::new();
2086		let mut trexs = Vec::new();
2087		let mut ftyp = None;
2088		extract_init(&Bytes::from(init), 1, &mut ftyp, &mut traks, &mut trexs).unwrap();
2089
2090		assert_eq!(traks.len(), 1);
2091		assert!(traks[0].edts.is_none(), "the source edit must not be applied twice");
2092	}
2093
2094	// tkhd.duration is in the movie timescale, which the merged moov replaces with its own. A
2095	// duration carried over from the source is then read at a scale it wasn't written in: a 30
2096	// second track authored at a 1 kHz movie scale reads as 0.625s once the moov says 48 kHz.
2097	#[test]
2098	fn extract_init_clears_a_stale_track_duration() {
2099		use mp4_atom::Encode;
2100
2101		let moov = mp4_atom::Moov {
2102			mvhd: mp4_atom::Mvhd {
2103				timescale: 1_000,
2104				..Default::default()
2105			},
2106			trak: vec![mp4_atom::Trak {
2107				tkhd: mp4_atom::Tkhd {
2108					duration: 30_000, // 30s at the source's 1 kHz movie scale
2109					..Default::default()
2110				},
2111				mdia: mp4_atom::Mdia {
2112					mdhd: mp4_atom::Mdhd {
2113						timescale: 48_000,
2114						..Default::default()
2115					},
2116					..Default::default()
2117				},
2118				..Default::default()
2119			}],
2120			..Default::default()
2121		};
2122		let mut init = Vec::new();
2123		moov.encode(&mut init).unwrap();
2124
2125		let mut traks = Vec::new();
2126		let mut trexs = Vec::new();
2127		let mut ftyp = None;
2128		extract_init(&Bytes::from(init), 1, &mut ftyp, &mut traks, &mut trexs).unwrap();
2129
2130		assert_eq!(traks.len(), 1);
2131		assert_eq!(
2132			traks[0].tkhd.duration,
2133			u64::MAX,
2134			"a live fragmented init declares an unknown duration"
2135		);
2136	}
2137}