Skip to main content

moq_mux/codec/
mp3.rs

1//! MP3 (MPEG-1/2/2.5 Audio Layer III).
2//!
3//! Audio carried verbatim: each frame is published whole. The header is parsed
4//! only for the catalog config (sample rate, channels); the audio is never
5//! decoded and there is no out-of-band configuration record. [`Import`] publishes
6//! raw MP3 frames to a moq broadcast.
7
8use crate::catalog::hang::CatalogExt;
9use crate::container::Frame;
10use crate::import::track::Written;
11use moq_net::Timestamp;
12
13/// MP3 parsing errors.
14#[derive(Debug, Clone, thiserror::Error)]
15#[non_exhaustive]
16pub enum Error {
17	/// The buffer was shorter than the 4-byte MPEG audio frame header.
18	#[error("MP3 frame header must be at least 4 bytes")]
19	HeaderTooShort,
20
21	/// The 11-bit frame sync (`0xFFE`) was missing.
22	#[error("missing MP3 frame sync")]
23	MissingSync,
24
25	/// The MPEG version field was the reserved value `01`.
26	#[error("reserved MPEG version")]
27	ReservedVersion,
28
29	/// The layer field was not Layer III, so this is not an MP3 frame (Layer I/II
30	/// are MP1/MP2, the reserved value is invalid).
31	#[error("not an MPEG Layer III (MP3) frame")]
32	NotLayer3,
33
34	/// The sample-rate index was the reserved value `11`.
35	#[error("reserved MP3 sample rate")]
36	ReservedSampleRate,
37}
38
39/// A result using this module's error type.
40pub type Result<T> = std::result::Result<T, Error>;
41
42/// Typed MP3 configuration parsed from an MPEG audio frame header.
43pub struct Config {
44	/// Sampling frequency in Hz.
45	pub sample_rate: u32,
46	/// Channel count (1 for the mono channel mode, 2 otherwise).
47	pub channel_count: u32,
48}
49
50impl Config {
51	/// Parse the catalog config from the start of an MPEG Layer III frame.
52	///
53	/// Reads the 4-byte frame header (ISO/IEC 11172-3 ยง2.4.1.2): verifies the
54	/// frame sync and that the layer is III, then derives the sample rate from
55	/// the version + sample-rate index and the channel count from the channel
56	/// mode. The buffer is not advanced; the frame is published whole.
57	pub fn parse(data: &[u8]) -> Result<Self> {
58		if data.len() < 4 {
59			return Err(Error::HeaderTooShort);
60		}
61
62		// 11-bit frame sync: all of byte 0 plus the top 3 bits of byte 1.
63		if data[0] != 0xFF || (data[1] & 0xE0) != 0xE0 {
64			return Err(Error::MissingSync);
65		}
66
67		let version = (data[1] >> 3) & 0x03;
68		let layer = (data[1] >> 1) & 0x03;
69		// Layer is encoded inverted: 0b01 == Layer III.
70		if layer != 0b01 {
71			return Err(Error::NotLayer3);
72		}
73
74		let sr_index = ((data[2] >> 2) & 0x03) as usize;
75		if sr_index == 0b11 {
76			return Err(Error::ReservedSampleRate);
77		}
78
79		let sample_rate = match version {
80			0b11 => [44100, 48000, 32000][sr_index], // MPEG-1
81			0b10 => [22050, 24000, 16000][sr_index], // MPEG-2
82			0b00 => [11025, 12000, 8000][sr_index],  // MPEG-2.5
83			_ => return Err(Error::ReservedVersion),
84		};
85
86		// Channel mode 0b11 is single channel (mono); the rest are two-channel.
87		let channel_count = if (data[3] >> 6) & 0x03 == 0b11 { 1 } else { 2 };
88
89		Ok(Self {
90			sample_rate,
91			channel_count,
92		})
93	}
94}
95
96/// How long the MPEG Layer III frame at the start of `data` plays, from its header: 1152 samples
97/// for MPEG-1, half that for MPEG-2 and 2.5. `None` when the header doesn't parse.
98pub(crate) fn duration(data: &[u8]) -> Option<Timestamp> {
99	let config = Config::parse(data).ok()?;
100	let samples = if (data[1] >> 3) & 0x03 == 0b11 { 1152 } else { 576 };
101	Timestamp::from_scale(samples, config.sample_rate.into()).ok()
102}
103
104/// MP3 importer.
105///
106/// Publishes raw MP3 frames to a single moq track. Build it with [`new`](Self::new),
107/// passing the track producer and the [`catalog::Reserved`](crate::catalog::Reserved)
108/// it reserves its rendition from.
109///
110/// Every MP3 frame is independently decodable, so [`decode`](Self::decode) marks only the first
111/// frame of each group a keyframe (the rest extend it): frames accumulate into the current group
112/// until the caller [`cut`](Self::cut)s. The
113/// [`import::Track`](crate::import::Track) facade cuts once a group holds 100 ms. MP3 carries its
114/// config in band, so the rendition has no out-of-band description.
115pub struct Import {
116	track: crate::container::Producer<crate::catalog::hang::Wire, hang::catalog::AudioConfig>,
117}
118
119impl Import {
120	/// Publish on an existing track producer with a resolved catalog config.
121	///
122	/// Build one from a frame header with [`config`], or from an out-of-band [`Config`] via `into()`.
123	/// The rendition publishes immediately.
124	pub fn new<E: CatalogExt>(
125		track: moq_net::track::Producer,
126		reserved: crate::catalog::Reserved<E>,
127		config: hang::catalog::AudioConfig,
128	) -> crate::Result<Self> {
129		tracing::debug!(name = ?track.name(), ?config, "starting track");
130		// The caller's config names the container; the writer is built from that same value so the
131		// wire cannot disagree with what the rendition advertises.
132		let wire = crate::catalog::hang::Wire::try_from(&config)?;
133		// Build the writer before advertising the rendition: it is fallible (enrolling the track in
134		// the broadcast timeline can collide), and a rendition published for a track we then fail to
135		// produce would be advertised to consumers but never served.
136		let track = reserved.audio(track, wire, config)?;
137		Ok(Self { track })
138	}
139
140	/// A watch-only handle to this track's subscriber demand.
141	pub fn demand(&self) -> moq_net::track::Demand {
142		self.track.track().demand()
143	}
144
145	/// Finish the track, flushing the current group, and return the [`Finished`](crate::container::Finished)
146	/// track, which keeps it and its catalog rendition published.
147	///
148	/// A finish that fails ends the track with the cause instead, so it can't be retried.
149	pub fn finish(
150		self,
151	) -> crate::Result<crate::container::Finished<crate::catalog::hang::Wire, hang::catalog::AudioConfig>> {
152		self.track.finish()
153	}
154
155	/// Abort the track with `err` instead of finishing it cleanly, so subscribers
156	/// see the real cause rather than [`moq_net::Error::Dropped`]. Consumes this importer.
157	pub fn abort(self, err: moq_net::Error) {
158		self.track.abort(err);
159	}
160
161	/// Close the current group at `end`, or without declaring an end when none is known, so the
162	/// producer doesn't extrapolate one from the gap before the last frame.
163	pub(crate) fn close(&mut self, end: Option<moq_net::Timestamp>) -> crate::Result<()> {
164		match end {
165			Some(end) => self.track.cut(Some(end)),
166			None => self.track.cut_unended(),
167		}
168	}
169
170	/// Cut the current group at `end` without finishing the track.
171	pub fn cut(&mut self, end: Option<moq_net::Timestamp>) -> crate::Result<()> {
172		self.track.cut(end)?;
173		Ok(())
174	}
175
176	/// Mark a timeline break and restart measurement without lowering advertised values.
177	pub fn discontinuity(&mut self) -> crate::Result<()> {
178		self.track.discontinuity()
179	}
180
181	/// Publish one MP3 frame, stamping `pts` or a wall clock when absent.
182	///
183	/// MP3 is independently decodable, so the frame is marked a keyframe only when it starts a group
184	/// (see [`Producer::needs_keyframe`](crate::container::Producer::needs_keyframe)); otherwise it
185	/// extends the current group. The caller bounds groups via [`cut`](Self::cut).
186	pub fn decode<B: moq_net::IntoBytes>(&mut self, frame: B, pts: Option<Timestamp>) -> crate::Result<()> {
187		self.write(frame.into_bytes(), pts).map(|_| ())
188	}
189
190	/// [`decode`](Self::decode), returning the frame's timestamp and how long it plays, if known.
191	pub(crate) fn write(&mut self, payload: bytes::Bytes, pts: Option<Timestamp>) -> crate::Result<Written> {
192		let timestamp = self.track.timestamp(pts)?;
193		// Only the first frame of each group is a keyframe, so the group spans until the caller cuts
194		// instead of opening one group (one QUIC stream) per packet.
195		let keyframe = self.track.needs_keyframe();
196		let duration = duration(&payload);
197		self.track.write(Frame {
198			timestamp,
199			decode: None,
200			payload,
201			keyframe,
202			duration: None,
203		})?;
204		Ok(Written { timestamp, duration })
205	}
206}
207
208/// Build a catalog config from an MP3 frame header. Errors on a malformed or empty buffer.
209pub fn config(init: &[u8]) -> crate::Result<hang::catalog::AudioConfig> {
210	Ok(Config::parse(init)?.into())
211}
212
213impl From<Config> for hang::catalog::AudioConfig {
214	/// Build a catalog config from a config resolved out of band (e.g. gstreamer caps).
215	fn from(config: Config) -> Self {
216		let mut audio =
217			hang::catalog::AudioConfig::new(hang::catalog::AudioCodec::Mp3, config.sample_rate, config.channel_count);
218		audio.container = hang::catalog::Container::Legacy;
219		audio
220	}
221}
222
223#[cfg(test)]
224mod tests {
225	use super::*;
226
227	#[test]
228	fn parses_mpeg1_stereo() {
229		// MPEG-1 Layer III, 128 kbps, 44.1 kHz, joint stereo.
230		let header = [0xFF, 0xFB, 0x90, 0x44];
231		let cfg = Config::parse(&header).unwrap();
232		assert_eq!(cfg.sample_rate, 44100);
233		assert_eq!(cfg.channel_count, 2);
234	}
235
236	#[test]
237	fn parses_mpeg1_mono() {
238		// Same header but channel mode 0b11 (mono) in the top bits of byte 3.
239		let header = [0xFF, 0xFB, 0x90, 0xC4];
240		let cfg = Config::parse(&header).unwrap();
241		assert_eq!(cfg.channel_count, 1);
242	}
243
244	#[test]
245	fn parses_mpeg2_sample_rate() {
246		// MPEG-2 (version 0b10), Layer III, sample-rate index 0 -> 22.05 kHz.
247		let header = [0xFF, 0xF3, 0x90, 0x44];
248		let cfg = Config::parse(&header).unwrap();
249		assert_eq!(cfg.sample_rate, 22050);
250	}
251
252	#[test]
253	fn mpeg2_frames_hold_half_the_samples() {
254		let micros = |header: [u8; 4]| {
255			std::time::Duration::try_from(duration(&header).unwrap())
256				.unwrap()
257				.as_micros()
258		};
259		// MPEG-1 at 48 kHz: 1152 samples.
260		assert_eq!(micros([0xFF, 0xFB, 0x94, 0x44]), 24_000);
261		// MPEG-2 at 24 kHz: 576 samples.
262		assert_eq!(micros([0xFF, 0xF3, 0x94, 0x44]), 24_000);
263		assert_eq!(duration(&[0xFF, 0xFD, 0x90, 0x44]), None, "a Layer II frame");
264	}
265
266	#[test]
267	fn rejects_layer2() {
268		// Layer II is 0b10, i.e. an MP2 (not MP3) frame.
269		let header = [0xFF, 0xFD, 0x90, 0x44];
270		assert!(matches!(Config::parse(&header), Err(Error::NotLayer3)));
271	}
272
273	#[test]
274	fn rejects_missing_sync() {
275		assert!(matches!(
276			Config::parse(&[0x00, 0x00, 0x00, 0x00]),
277			Err(Error::MissingSync)
278		));
279	}
280
281	#[test]
282	fn rejects_short() {
283		assert!(matches!(Config::parse(&[0xFF, 0xFB]), Err(Error::HeaderTooShort)));
284	}
285}