Skip to main content

moq_mux/container/legacy/
mod.rs

1//! The original hang wire format.
2//!
3//! Each moq frame holds one media frame: a varint-encoded presentation timestamp
4//! followed by the raw codec bitstream, written to the transport at the newest presentation time
5//! so far in its group, so a B-frame never takes it backwards.
6//! Simple but ad-hoc; new broadcasts should use [`crate::container::cts`] instead.
7
8use crate::container::{Container, Frame, Kind};
9
10/// Hang Legacy wire format configured for the track's media role.
11pub struct Wire(
12	/// The kind of content carried by the track.
13	pub Kind,
14);
15
16impl Wire {
17	/// Write `frame` to `group` at the newest presentation time so far, so a B-frame never takes
18	/// the transport backwards, while its prefix keeps its own.
19	fn write_frame(group: &mut crate::container::Writer<'_>, frame: hang::container::Frame) -> crate::Result<()> {
20		let mut buf = bytes::BytesMut::with_capacity(8 + frame.payload.len());
21		frame.encode(&mut buf)?;
22		let transport = match group.latest() {
23			Some(latest) if frame.timestamp < latest => latest,
24			_ => frame.timestamp,
25		};
26		group.write_frame(transport, buf.freeze())?;
27		Ok(())
28	}
29
30	/// The bytes preceding a frame's payload: its varint timestamp.
31	pub(crate) fn prefix(&self, timestamp: moq_net::Timestamp) -> crate::Result<bytes::Bytes> {
32		let mut prefix = bytes::BytesMut::new();
33		hang::container::Frame {
34			timestamp,
35			payload: bytes::Bytes::new(),
36		}
37		.encode(&mut prefix)?;
38		Ok(prefix.freeze())
39	}
40}
41
42impl Container for Wire {
43	type Error = crate::Error;
44
45	fn end(&self, frame: &Frame) -> Option<moq_net::Timestamp> {
46		(self.0 != Kind::Data && frame.payload.is_empty()).then_some(frame.timestamp)
47	}
48
49	fn kind(&self) -> Kind {
50		self.0
51	}
52
53	fn finish_group(
54		&self,
55		group: &mut crate::container::Writer<'_>,
56		end: Option<moq_net::Timestamp>,
57	) -> Result<(), Self::Error> {
58		if self.0 == Kind::Video
59			&& let Some(timestamp) = end
60		{
61			Self::write_frame(
62				group,
63				hang::container::Frame {
64					timestamp,
65					payload: bytes::Bytes::new(),
66				},
67			)?;
68		}
69		Ok(())
70	}
71
72	fn write(&self, group: &mut crate::container::Writer<'_>, frames: &[Frame]) -> Result<(), Self::Error> {
73		for frame in frames {
74			let hang_frame = hang::container::Frame {
75				timestamp: frame.timestamp,
76				payload: frame.payload.clone(),
77			};
78			Self::write_frame(group, hang_frame)?;
79		}
80		Ok(())
81	}
82
83	fn decode(&self, frame: moq_net::frame::Frame) -> Result<Vec<Frame>, Self::Error> {
84		// On a data track an object with no bytes is its discontinuity marker, not a frame.
85		// Elsewhere it is malformed, so it fails to decode below.
86		if self.0 == Kind::Data && frame.payload.is_empty() {
87			return Ok(Vec::new());
88		}
89
90		let hang_frame = hang::container::Frame::decode(frame.payload)?;
91		// The transport time only keeps a group in order, so it says nothing of when a frame decodes.
92		Ok(vec![Frame {
93			timestamp: hang_frame.timestamp,
94			decode: None,
95			payload: hang_frame.payload,
96			// Legacy doesn't carry the keyframe bit on the wire; the
97			// wrapping Consumer fills it in from group position.
98			keyframe: false,
99			// Legacy carries no per-frame duration.
100			duration: None,
101		}])
102	}
103}
104
105/// How long each packet of a Legacy audio track plays, as its codec states.
106///
107/// Legacy frames carry no duration; the hang draft leaves it to the codec. Knowing it, a reader
108/// tells a group that ends where the next one starts from one followed by lost audio. Group keys
109/// can't say: they are starts, and a wire without skips (moq-lite-05 and 06) reports the starts
110/// between two groups as it does a loss.
111#[derive(Clone, Copy, Debug, PartialEq, Eq)]
112pub(crate) struct Audio(Packets);
113
114#[derive(Clone, Copy, Debug, PartialEq, Eq)]
115enum Packets {
116	/// Read from each packet's TOC byte, in 48 kHz samples.
117	Opus,
118	/// The same number of samples in every packet, at the codec's rate: AAC's core may run below
119	/// the track's.
120	Fixed { samples: u32, rate: u32 },
121	/// Interleaved 32-bit samples, so the payload's length says.
122	Pcm { frame_bytes: u32, rate: u32 },
123}
124
125impl Audio {
126	/// The packet clock of `config`'s codec, or `None` when a packet doesn't state its duration
127	/// without decoding it.
128	pub(crate) fn new(config: &hang::catalog::AudioConfig) -> Option<Self> {
129		let rate = config.sample_rate;
130		if rate == 0 {
131			return None;
132		}
133		let packets = match &config.codec {
134			hang::catalog::AudioCodec::Opus => Packets::Opus,
135			// AAC codes 960 or 1024 samples per packet at its core's rate, which SBR and PS may
136			// double on output. The AudioSpecificConfig names both; without one, only AAC-LC's
137			// rate is the catalog's, at the usual 1024.
138			hang::catalog::AudioCodec::AAC(aac) => {
139				let (samples, rate) = match &config.description {
140					Some(asc) => crate::codec::aac::frame_clock(asc),
141					None => (aac.profile == 2).then_some((1024, rate)),
142				}?;
143				Packets::Fixed { samples, rate }
144			}
145			// Layer II codes 1152 samples per frame.
146			hang::catalog::AudioCodec::Mp2 => Packets::Fixed { samples: 1152, rate },
147			hang::catalog::AudioCodec::Pcm => Packets::Pcm {
148				frame_bytes: config.channel_count.checked_mul(4).filter(|bytes| *bytes > 0)?,
149				rate,
150			},
151			_ => return None,
152		};
153		Some(Self(packets))
154	}
155
156	/// How long `payload` plays, or `None` when it doesn't parse as one packet.
157	pub(crate) fn duration(&self, payload: &[u8]) -> Option<moq_net::Timestamp> {
158		if payload.is_empty() {
159			return None;
160		}
161		let (samples, rate) = match self.0 {
162			Packets::Opus => (crate::codec::opus::packet_samples(payload)?, 48_000),
163			Packets::Fixed { samples, rate } => (samples, rate),
164			Packets::Pcm { frame_bytes, rate } => {
165				let frame_bytes = frame_bytes as usize;
166				if !payload.len().is_multiple_of(frame_bytes) {
167					return None;
168				}
169				(u32::try_from(payload.len() / frame_bytes).ok()?, rate)
170			}
171		};
172		moq_net::Timestamp::from_scale(samples.into(), rate.into()).ok()
173	}
174}
175
176#[cfg(test)]
177mod tests {
178	use super::*;
179
180	fn config(codec: hang::catalog::AudioCodec, sample_rate: u32, channel_count: u32) -> hang::catalog::AudioConfig {
181		hang::catalog::AudioConfig::new(codec, sample_rate, channel_count)
182	}
183
184	fn micros(duration: Option<moq_net::Timestamp>) -> Option<u128> {
185		duration.map(|duration| std::time::Duration::try_from(duration).unwrap().as_micros())
186	}
187
188	#[test]
189	fn opus_states_each_packet_in_its_toc() {
190		let audio = Audio::new(&config(hang::catalog::AudioCodec::Opus, 48_000, 2)).unwrap();
191		// CELT FB at 2.5 ms and 20 ms, one frame each.
192		assert_eq!(micros(audio.duration(&[16 << 3, 0])), Some(2_500));
193		assert_eq!(micros(audio.duration(&[31 << 3, 0])), Some(20_000));
194		// Two 20 ms frames.
195		assert_eq!(micros(audio.duration(&[(31 << 3) | 1, 0])), Some(40_000));
196		// An empty payload is a marker, not a packet.
197		assert_eq!(audio.duration(&[]), None);
198	}
199
200	#[test]
201	fn aac_lc_mp2_and_pcm_state_a_fixed_or_measured_count() {
202		let aac = hang::catalog::AudioCodec::AAC(hang::catalog::AAC { profile: 2 });
203		let audio = Audio::new(&config(aac, 48_000, 2)).unwrap();
204		assert_eq!(micros(audio.duration(&[0xff])), Some(21_333));
205
206		let audio = Audio::new(&config(hang::catalog::AudioCodec::Mp2, 48_000, 2)).unwrap();
207		assert_eq!(micros(audio.duration(&[0xff])), Some(24_000));
208
209		let audio = Audio::new(&config(hang::catalog::AudioCodec::Pcm, 1_000, 2)).unwrap();
210		// Ten stereo frames of 32-bit samples are 10 ms at 1 kHz.
211		assert_eq!(micros(audio.duration(&[0; 80])), Some(10_000));
212		assert_eq!(audio.duration(&[0; 81]), None, "a partial sample frame");
213	}
214
215	#[test]
216	fn a_codec_whose_packets_vary_states_nothing() {
217		let he = hang::catalog::AudioCodec::AAC(hang::catalog::AAC { profile: 5 });
218		assert_eq!(Audio::new(&config(he, 48_000, 2)), None);
219	}
220
221	#[test]
222	fn aac_states_its_configs_frame_length_at_its_core_rate() {
223		let lc = hang::catalog::AudioCodec::AAC(hang::catalog::AAC { profile: 2 });
224		let he = hang::catalog::AudioCodec::AAC(hang::catalog::AAC { profile: 5 });
225		for (codec, sample_rate, asc, duration) in [
226			// A 48 kHz core with SBR at 96 kHz behind a sync extension, then at the core's own rate.
227			(lc.clone(), 96_000, &[0x11, 0x90, 0x56, 0xe5, 0x80][..], 21_333),
228			(lc.clone(), 48_000, &[0x11, 0x90, 0x56, 0xe5, 0x98][..], 21_333),
229			// Plain AAC-LC, and explicit SBR over a 48 kHz core at 96 kHz.
230			(lc.clone(), 48_000, &[0x11, 0x90][..], 21_333),
231			(he.clone(), 96_000, &[0x29, 0x90, 0x08, 0x00][..], 21_333),
232			// frameLengthFlag set: 960 samples, plain and under explicit SBR over a 24 kHz core.
233			(lc, 48_000, &[0x11, 0x94][..], 20_000),
234			(he, 48_000, &[0x2b, 0x11, 0x8a, 0x00][..], 40_000),
235		] {
236			let mut aac = config(codec, sample_rate, 2);
237			aac.description = Some(bytes::Bytes::copy_from_slice(asc));
238			let audio = Audio::new(&aac).unwrap();
239			assert_eq!(micros(audio.duration(&[0xff])), Some(duration), "{asc:02x?}");
240		}
241	}
242}