Skip to main content

moq_mux/catalog/hang/
container.rs

1use crate::container::{Container, Frame, Kind, cts, fmp4, legacy, loc, raw};
2
3/// Runtime-dispatched wire format for a track described by a hang catalog.
4///
5/// Built from a track's audio or video configuration, including its container, or from a media
6/// role with [`legacy`](Self::legacy), [`loc`](Self::loc), [`raw`](Self::raw), [`cts`](Self::cts),
7/// or [`cmaf`](Self::cmaf). Audio built from an [`AudioConfig`](hang::catalog::AudioConfig) whose
8/// codec states each packet's duration reads it; one built from a role alone reads none.
9pub struct Wire(Format);
10
11enum Format {
12	/// varint timestamp + raw codec bitstream. The original hang wire format.
13	Legacy(Kind, Option<legacy::Audio>),
14	/// ISO-BMFF moof+mdat fragments, holding the track's `trak` box so per-frame writes and reads
15	/// have the timescale and track id available.
16	Cmaf(fmp4::Wire),
17	/// Low Overhead Container. One LOC frame per moq frame.
18	Loc(Kind),
19	/// Zero-byte header: raw codec bitstream timed by the MoQ transport timestamp (DTS == PTS).
20	Raw(Kind, Option<legacy::Audio>),
21	/// QUIC varint composition time offset (in track timescale) + raw codec bitstream, timed by
22	/// the MoQ transport timestamp as its decode time.
23	Cts(Kind, Option<legacy::Audio>),
24}
25
26impl Wire {
27	/// The original hang wire format, a varint timestamp before each payload, for `kind`.
28	pub fn legacy(kind: Kind) -> Self {
29		Self(Format::Legacy(kind, None))
30	}
31
32	/// ISO-BMFF moof+mdat fragments for the track `wire` describes.
33	pub fn cmaf(wire: fmp4::Wire) -> Self {
34		Self(Format::Cmaf(wire))
35	}
36
37	/// The Low Overhead Container, one LOC frame per moq frame, for `kind`.
38	pub fn loc(kind: Kind) -> Self {
39		Self(Format::Loc(kind))
40	}
41
42	/// The raw codec payload timed by the transport timestamp, for `kind`.
43	pub fn raw(kind: Kind) -> Self {
44		Self(Format::Raw(kind, None))
45	}
46
47	/// A composition time offset before the raw codec payload, timed by the transport timestamp as
48	/// its decode time, for `kind`.
49	pub fn cts(kind: Kind) -> Self {
50		Self(Format::Cts(kind, None))
51	}
52
53	/// Configure a wire format for an explicitly named media role.
54	pub fn new(container: &hang::catalog::Container, kind: Kind) -> crate::Result<Self> {
55		match container {
56			hang::catalog::Container::Legacy => Ok(Self::legacy(kind)),
57			hang::catalog::Container::Cmaf { init, .. } => Ok(Self::cmaf(fmp4::Wire::from_init(init)?)),
58			hang::catalog::Container::Loc => Ok(Self::loc(kind)),
59			hang::catalog::Container::Raw => Ok(Self::raw(kind)),
60			hang::catalog::Container::Cts => Ok(Self::cts(kind)),
61			hang::catalog::Container::Unknown(unknown) => Err(crate::Error::unsupported_container(unknown)),
62		}
63	}
64
65	/// The bytes preceding a frame's payload, when they depend on nothing but its timestamp, so the
66	/// payload can stream in after them. `None` for CMAF and CTS.
67	pub(crate) fn prefix(&self, timestamp: moq_net::Timestamp) -> crate::Result<Option<bytes::Bytes>> {
68		match &self.0 {
69			Format::Legacy(kind, _) => legacy::Wire(*kind).prefix(timestamp).map(Some),
70			Format::Loc(kind) => loc::Wire(*kind).prefix(timestamp).map(Some),
71			Format::Raw(kind, _) => Ok(Some(raw::Wire(*kind).prefix())),
72			Format::Cmaf(_) | Format::Cts(..) => Ok(None),
73		}
74	}
75}
76
77impl TryFrom<&hang::catalog::VideoConfig> for Wire {
78	type Error = crate::Error;
79	fn try_from(config: &hang::catalog::VideoConfig) -> crate::Result<Self> {
80		Self::new(&config.container, Kind::Video)
81	}
82}
83
84impl TryFrom<&hang::catalog::AudioConfig> for Wire {
85	type Error = crate::Error;
86	fn try_from(config: &hang::catalog::AudioConfig) -> crate::Result<Self> {
87		let mut container = Self::new(&config.container, Kind::Audio)?;
88		if let Format::Legacy(_, audio) | Format::Raw(_, audio) | Format::Cts(_, audio) = &mut container.0 {
89			*audio = legacy::Audio::new(config);
90		}
91		Ok(container)
92	}
93}
94
95impl TryFrom<&crate::catalog::VideoHint> for Wire {
96	type Error = crate::Error;
97	fn try_from(hint: &crate::catalog::VideoHint) -> crate::Result<Self> {
98		Self::new(&hint.container, Kind::Video)
99	}
100}
101
102/// Whether a rendition's frames can be parsed by this build, logging the ones dropped.
103///
104/// The hang spec requires a consumer to ignore a rendition whose container `kind` it does not
105/// recognize, so filter on this instead of failing the entire broadcast.
106pub(crate) fn supported(rendition: &str, container: &hang::catalog::Container) -> bool {
107	match container {
108		hang::catalog::Container::Unknown(unknown) => {
109			tracing::warn!(rendition, kind = unknown.kind(), "ignoring unknown container");
110			false
111		}
112		_ => true,
113	}
114}
115
116impl Container for Wire {
117	type Error = crate::Error;
118
119	fn end(&self, frame: &Frame) -> Option<moq_net::Timestamp> {
120		match &self.0 {
121			Format::Legacy(kind, _) => legacy::Wire(*kind).end(frame),
122			Format::Cmaf(cmaf) => cmaf.end(frame),
123			Format::Loc(kind) => loc::Wire(*kind).end(frame),
124			Format::Raw(kind, _) => raw::Wire(*kind).end(frame),
125			Format::Cts(kind, _) => cts::Wire(*kind).end(frame),
126		}
127	}
128
129	fn kind(&self) -> Kind {
130		match &self.0 {
131			Format::Legacy(kind, _) | Format::Loc(kind) | Format::Raw(kind, _) | Format::Cts(kind, _) => *kind,
132			Format::Cmaf(wire) => <fmp4::Wire as Container>::kind(wire),
133		}
134	}
135
136	fn writable(&self) -> Result<(), Self::Error> {
137		match &self.0 {
138			Format::Cts(kind, _) => cts::Wire(*kind).writable(),
139			_ => Ok(()),
140		}
141	}
142
143	fn decode_order(&self) -> bool {
144		matches!(self.0, Format::Raw(..) | Format::Cts(..))
145	}
146
147	fn check(&self, frame: &Frame) -> Result<(), Self::Error> {
148		match &self.0 {
149			Format::Raw(kind, _) => raw::Wire(*kind).check(frame),
150			Format::Cts(kind, _) => cts::Wire(*kind).check(frame),
151			_ => Ok(()),
152		}
153	}
154
155	fn finish_group(
156		&self,
157		group: &mut crate::container::Writer<'_>,
158		end: Option<moq_net::Timestamp>,
159	) -> Result<(), Self::Error> {
160		match &self.0 {
161			Format::Legacy(kind, _) => legacy::Wire(*kind).finish_group(group, end),
162			Format::Cmaf(wire) => wire.finish_group(group, end).map_err(Into::into),
163			Format::Loc(kind) => loc::Wire(*kind).finish_group(group, end),
164			Format::Raw(kind, _) => raw::Wire(*kind).finish_group(group, end),
165			Format::Cts(kind, _) => cts::Wire(*kind).finish_group(group, end),
166		}
167	}
168
169	fn write(&self, group: &mut crate::container::Writer<'_>, frames: &[Frame]) -> Result<(), Self::Error> {
170		match &self.0 {
171			Format::Legacy(kind, _) => legacy::Wire(*kind).write(group, frames),
172			Format::Cmaf(cmaf) => cmaf.write(group, frames).map_err(Into::into),
173			Format::Loc(kind) => loc::Wire(*kind).write(group, frames),
174			Format::Raw(kind, _) => raw::Wire(*kind).write(group, frames),
175			Format::Cts(kind, _) => cts::Wire(*kind).write(group, frames),
176		}
177	}
178
179	fn decode(&self, frame: moq_net::frame::Frame) -> Result<Vec<Frame>, Self::Error> {
180		let (mut frames, audio) = match &self.0 {
181			Format::Legacy(kind, audio) => (legacy::Wire(*kind).decode(frame)?, audio),
182			Format::Cmaf(cmaf) => return Ok(cmaf.decode(frame)?),
183			Format::Loc(kind) => return loc::Wire(*kind).decode(frame),
184			Format::Raw(kind, audio) => (raw::Wire(*kind).decode(frame)?, audio),
185			Format::Cts(kind, audio) => (cts::Wire(*kind).decode(frame)?, audio),
186		};
187		// These wires carry no duration, but the codec states each packet's.
188		if let Some(audio) = audio {
189			for frame in &mut frames {
190				frame.duration = audio.duration(&frame.payload);
191			}
192		}
193		Ok(frames)
194	}
195}
196
197#[cfg(test)]
198mod tests {
199	use super::*;
200
201	/// A 20 ms Opus packet: TOC config 31, one frame.
202	const OPUS: [u8; 2] = [31 << 3, 0];
203
204	/// `wire`'s moq frame carrying [`OPUS`] at 20 ms.
205	fn opus_frame(wire: &hang::catalog::Container) -> moq_net::frame::Frame {
206		let at = moq_net::Timestamp::from_micros(20_000).unwrap();
207		let mut payload = match wire {
208			hang::catalog::Container::Legacy => Wire::legacy(Kind::Audio).prefix(at).unwrap().unwrap().to_vec(),
209			hang::catalog::Container::Raw => Vec::new(),
210			// A zero composition offset.
211			hang::catalog::Container::Cts => vec![0],
212			other => unreachable!("{other:?}"),
213		};
214		payload.extend_from_slice(&OPUS);
215		moq_net::frame::Frame::new(at, bytes::Bytes::from(payload))
216	}
217
218	/// Audio built from its config reads each packet's duration from the codec on every wire that
219	/// carries none, and audio built from its role alone reads none.
220	#[test]
221	fn audio_from_its_config_reads_codec_durations() {
222		let wires = [
223			(hang::catalog::Container::Legacy, Wire::legacy(Kind::Audio)),
224			(hang::catalog::Container::Raw, Wire::raw(Kind::Audio)),
225			(hang::catalog::Container::Cts, Wire::cts(Kind::Audio)),
226		];
227		for (wire, role) in wires {
228			let mut config = hang::catalog::AudioConfig::new(hang::catalog::AudioCodec::Opus, 48_000, 2);
229			config.container = wire.clone();
230			let configured = Wire::try_from(&config).unwrap();
231			assert_eq!(configured.kind(), Kind::Audio);
232
233			let frames = configured.decode(opus_frame(&wire)).unwrap();
234			assert_eq!(frames.len(), 1, "{wire:?}");
235			assert_eq!(&frames[0].payload[..], OPUS, "{wire:?}");
236			let duration = frames[0].duration.map(|duration| duration.as_micros().unwrap());
237			assert_eq!(duration, Some(20_000), "{wire:?}");
238
239			let frames = role.decode(opus_frame(&wire)).unwrap();
240			assert_eq!(&frames[0].payload[..], OPUS, "{wire:?}");
241			assert_eq!(frames[0].duration, None, "{wire:?}");
242		}
243	}
244}