Skip to main content

moq_mux/container/
mod.rs

1//! Container formats.
2//!
3//! A container decides how a media frame is laid out inside a moq-lite
4//! frame: framing overhead, whether multiple samples can share one moq
5//! frame, and whether the same encoding doubles as a file format on disk.
6//!
7//! Each submodule implements one format. The wire-level ones implement
8//! the [`Container`] trait, so [`Producer<C>`] and [`Consumer<C>`] can
9//! be generic over the choice. The catalog announces a container per
10//! track; [`catalog::hang::Wire`](crate::catalog::hang::Wire)
11//! dispatches the right implementation at runtime.
12
13use bytes::Bytes;
14
15mod consumer;
16mod declared;
17pub use declared::ReorderError;
18mod decode;
19mod group;
20mod input;
21mod join;
22mod producer;
23mod source;
24#[cfg(test)]
25pub(crate) mod test_util;
26mod text;
27mod ttml;
28mod writer;
29
30pub mod cts;
31pub mod flv;
32pub mod fmp4;
33pub mod legacy;
34pub mod loc;
35pub mod mkv;
36pub mod mp4;
37pub mod raw;
38pub mod ts;
39
40pub use consumer::{Consumer, DELAY_MAX, Delay, Playout};
41pub use group::GroupConsumer;
42pub(crate) use input::Input;
43pub use join::Join;
44pub use producer::{Finished, Guard, Producer};
45pub(crate) use source::{ExportSource, Resume};
46pub use writer::Writer;
47
48/// The media role that determines how a container represents frame durations.
49#[derive(Clone, Copy, Debug, PartialEq, Eq)]
50pub enum Kind {
51	/// Audio packets carry codec-defined durations.
52	Audio,
53	/// Video frames can need a duration marker at group end.
54	Video,
55	/// Opaque data has no sample-duration semantics.
56	Data,
57}
58
59/// One item of a [`Consumer`] read, in delivery order.
60#[derive(Clone, Debug)]
61pub enum Read {
62	/// A media frame from `group`.
63	Frame {
64		/// The group's sequence number. Only equality means anything: numbers may skip.
65		group: u64,
66		/// The media frame delivered by the group.
67		frame: Frame,
68	},
69	/// Media after an item already read will never reach this reader: a group was skipped,
70	/// evicted, or never arrived. A decoder resumes from here without the references or
71	/// state that media built. Joining mid-track is not a gap: nothing was read before it.
72	///
73	/// The span is an upper bound, and `timestamp` is in the scale of the item that follows.
74	Gap {
75		/// The furthest presentation point already read. Without a per-frame duration this
76		/// is the last frame's timestamp, one frame early.
77		timestamp: moq_net::Timestamp,
78		/// How long until the next item resumes, so it also covers any declared pause.
79		duration: std::time::Duration,
80	},
81	/// The publisher declared that its media stops at `end`: it paused, switched source, or
82	/// finished. Frames that follow from the same `group` are the stopped encoder's final
83	/// packets (an audio codec's drain), whose output at or past `end` is padding. The next
84	/// group starts fresh.
85	End {
86		/// The group's sequence number. Only equality means anything: numbers may skip.
87		group: u64,
88		/// Where the media stops, at the scale the marker was encoded with.
89		end: moq_net::Timestamp,
90	},
91}
92
93/// A decoded media frame: timestamp, payload bytes, keyframe flag.
94///
95/// `payload` is the raw codec bitstream that gets handed to the decoder.
96/// The exact shape depends on the codec (Annex B for H.264/H.265, OBU for
97/// AV1, and so on).
98#[derive(Clone, Debug)]
99pub struct Frame {
100	/// Presentation timestamp.
101	///
102	/// Each container picks its own native scale: fmp4 uses the source
103	/// `mdhd.timescale`, mkv uses nanoseconds, legacy is fixed at microseconds.
104	/// LOC defaults to microseconds but a decoded frame keeps whatever per-frame
105	/// timescale the wire carried, so an exporter can re-emit without forcing
106	/// micros. Frames within a track must be in *decode* order, not display
107	/// order. B-frames may have non-monotonic presentation timestamps.
108	pub timestamp: moq_net::Timestamp,
109
110	/// Decode timestamp, when it differs from [`timestamp`](Self::timestamp), or `None` when the
111	/// frame decodes at its presentation time.
112	///
113	/// A [decode-order](Container::decode_order) container writes each frame to the transport at
114	/// its decode time and groups by it: `raw`, which therefore refuses a reordered frame, and
115	/// `cts`, which this build still only reads (a decoded `cts` frame reports it). Other
116	/// containers ignore it: they carry the presentation time in the payload and stamp the
117	/// transport with the newest one so far in the group, since a group's timestamps never
118	/// decrease.
119	pub decode: Option<moq_net::Timestamp>,
120
121	/// Sample duration in the frame's own scale, when the container reports it.
122	///
123	/// CMAF carries a per-sample duration (trun sample-duration). Legacy and LOC
124	/// can fill it from a duration marker that has already landed when a
125	/// [`GroupConsumer`] reads the frame, as in a fetched group. Streaming
126	/// muxers receive the later endpoint separately, so media stays immediately available.
127	/// The [`Consumer`] adds it to `timestamp` to learn how far a group has
128	/// presented, so it can advance to a newer group as soon as the gap is
129	/// covered instead of waiting out the max delay budget.
130	pub duration: Option<moq_net::Timestamp>,
131
132	/// Encoded codec payload.
133	pub payload: Bytes,
134
135	/// Whether this frame opens a group, or is a video keyframe.
136	///
137	/// Containers that carry the bit on the wire (CMAF reads it from
138	/// trun sample-flags) set it for video; containers that don't (Legacy,
139	/// LOC) leave it `false`. The wrapping [`Consumer`] still asserts
140	/// "first frame in a group is a keyframe" as a fallback, so the
141	/// Legacy/LOC case lands correctly without anyone having to know. For
142	/// audio, whose samples are all independently decodable, that fallback
143	/// is the only source: the bit marks the group boundary the publisher
144	/// drew, never a per-sample sync flag.
145	pub keyframe: bool,
146}
147
148/// A media timestamp's time since its track's zero, or `None` when [unscaled](moq_net::Timestamp::unscaled).
149///
150/// A [`Consumer`] refuses an unscaled frame as it decodes, so every frame an export reads has a
151/// time; where nothing can return the error, skipping one only has to never panic.
152pub(crate) fn time(timestamp: moq_net::Timestamp) -> Option<std::time::Duration> {
153	std::time::Duration::try_from(timestamp).ok()
154}
155
156/// `timestamp` in microseconds for a message, or its debug form when unscaled.
157fn micros(timestamp: moq_net::Timestamp) -> String {
158	match timestamp.as_micros() {
159		Ok(micros) => format!("{micros} µs"),
160		Err(_) => format!("{timestamp:?}"),
161	}
162}
163
164/// The later of two timestamps, `a` when they don't compare: [`moq_net::Timestamp`] has no
165/// [`Ord`], since an unscaled one orders against no scaled one.
166pub(crate) fn later(a: moq_net::Timestamp, b: moq_net::Timestamp) -> moq_net::Timestamp {
167	if b > a { b } else { a }
168}
169
170/// The earlier of two timestamps, `a` when they don't compare; see [`later`].
171pub(crate) fn earlier(a: moq_net::Timestamp, b: moq_net::Timestamp) -> moq_net::Timestamp {
172	if b < a { b } else { a }
173}
174
175/// The decode time `delay` before `presentation`, in its scale, or the timeline's zero for a
176/// picture that decodes before it, so decode times stay in order and never pass a presentation time.
177pub(crate) fn decode_time(
178	presentation: moq_net::Timestamp,
179	delay: moq_net::Timestamp,
180) -> Result<moq_net::Timestamp, moq_net::Error> {
181	let scale = presentation.scale().ok_or(moq_net::Error::TimestampMismatch)?;
182	let delay = delay.convert(scale).map_err(|_| moq_net::Error::TimestampMismatch)?;
183	moq_net::Timestamp::new(presentation.value().saturating_sub(delay.value()), scale)
184		.map_err(|_| moq_net::Error::TimestampMismatch)
185}
186
187/// Stamp `frame` with the duration that ends at `bound`, unless it already has one.
188pub(crate) fn close_duration(frame: &mut Frame, bound: moq_net::Timestamp) {
189	if frame.duration.is_some() {
190		return;
191	}
192	let (Ok(bound), Ok(timestamp)) = (bound.as_micros(), frame.timestamp.as_micros()) else {
193		return;
194	};
195	let Some(delta) = bound.checked_sub(timestamp) else {
196		return;
197	};
198	if delta == 0 {
199		return;
200	}
201	let Ok(delta) = u64::try_from(delta) else {
202		return;
203	};
204	if let Ok(duration) = moq_net::Timestamp::from_micros(delta) {
205		frame.duration = Some(duration);
206	}
207}
208
209/// A non-keyframe frame arrived with no open group.
210///
211/// A track must open with a keyframe (and so must the frame after
212/// [`cut`](Producer::cut)).
213/// [`Producer::write`] returns this so a caller joining mid-stream can skip
214/// frames until the first keyframe instead of treating it as fatal.
215#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
216#[error("missing keyframe: a group must open on a keyframe")]
217pub struct MissingKeyframe;
218
219/// An explicit endpoint precedes a frame of the group it ends.
220#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
221#[error("group endpoint precedes a frame of its own")]
222pub struct InvalidEnd;
223
224/// A group starts before the previous group did: the source restarted, which is a new broadcast.
225#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
226#[error(
227	"frame timestamp {} is below the previous group's start {}",
228	micros(*.timestamp),
229	micros(*.floor)
230)]
231pub struct TimestampRewind {
232	/// The refused frame's timestamp.
233	pub timestamp: moq_net::Timestamp,
234	/// The lowest allowed timestamp: the previous group's start.
235	pub floor: moq_net::Timestamp,
236}
237
238/// Encode and decode media frames over a moq-lite group.
239///
240/// Implementors decide how many [`Frame`]s map onto one moq-lite frame:
241/// Legacy and LOC write one media frame per moq-lite frame; CMAF can
242/// pack many samples into a single moof+mdat fragment.
243pub trait Container {
244	/// Container-specific error. Must be convertible from [`moq_net::Error`]
245	/// (so IO errors propagate), [`MissingKeyframe`], [`InvalidEnd`], and
246	/// [`TimestampRewind`] (so the producer can reject invalid group boundaries).
247	type Error: std::error::Error
248		+ Send
249		+ Sync
250		+ Unpin
251		+ From<moq_net::Error>
252		+ From<MissingKeyframe>
253		+ From<InvalidEnd>
254		+ From<TimestampRewind>;
255
256	/// Encode one or more frames into moq-lite frames written to `group`, whose first frame
257	/// creates it on the track.
258	fn write(&self, group: &mut Writer<'_>, frames: &[Frame]) -> Result<(), Self::Error>;
259
260	/// Decode one moq-lite frame read from a group into media frames.
261	///
262	/// A single moq-lite frame may carry several media frames (e.g. all samples in a
263	/// CMAF fragment), or none (a CMAF fragment with zero samples), which is not the
264	/// end of the group.
265	///
266	/// On a data track an empty batch is the discontinuity marker, so a data
267	/// container returns one only for an object with no bytes, and refuses any
268	/// other object that decodes to no frames.
269	fn decode(&self, frame: moq_net::frame::Frame) -> Result<Vec<Frame>, Self::Error>;
270
271	/// Return the endpoint timestamp when `frame` carries empty-payload metadata.
272	///
273	/// For video this bounds the preceding frame; for audio it bounds source samples
274	/// before terminal codec packets. A consumer never submits the marker to a decoder.
275	/// Formats without endpoint metadata use the default.
276	fn end(&self, _frame: &Frame) -> Option<moq_net::Timestamp> {
277		None
278	}
279
280	/// The media role, when this format represents an audio or video track.
281	fn kind(&self) -> Kind {
282		Kind::Data
283	}
284
285	/// Whether the transport carries each frame's [`decode`](Frame::decode) time, so a
286	/// [`Producer`] groups frames by it. Otherwise the producer ignores decode times and the
287	/// payload carries each frame's presentation time.
288	fn decode_order(&self) -> bool {
289		false
290	}
291
292	/// Refuse a format this build can read but not write, before a producer is built for it.
293	///
294	/// A catalog checks this before advertising a rendition, so a consumer never sees one whose
295	/// first write would fail.
296	fn writable(&self) -> Result<(), Self::Error> {
297		Ok(())
298	}
299
300	/// Refuse a frame this format has no encoding for, by default any frame of an unwritable format.
301	///
302	/// A [`Producer`] checks each frame on entry, before it cuts a group or buffers anything, so a
303	/// refused frame leaves the open group and the buffered frames as they were.
304	fn check(&self, _frame: &Frame) -> Result<(), Self::Error> {
305		self.writable()
306	}
307
308	/// Write any format-specific endpoint before the producer closes the group.
309	fn finish_group(
310		&self,
311		_group: &mut crate::container::Writer<'_>,
312		_end: Option<moq_net::Timestamp>,
313	) -> Result<(), Self::Error> {
314		Ok(())
315	}
316}