1use crate::catalog::hang::CatalogExt;
9use crate::container::Frame;
10use crate::import::track::Written;
11use moq_net::Timestamp;
12
13#[derive(Debug, Clone, thiserror::Error)]
15#[non_exhaustive]
16pub enum Error {
17 #[error("MP3 frame header must be at least 4 bytes")]
19 HeaderTooShort,
20
21 #[error("missing MP3 frame sync")]
23 MissingSync,
24
25 #[error("reserved MPEG version")]
27 ReservedVersion,
28
29 #[error("not an MPEG Layer III (MP3) frame")]
32 NotLayer3,
33
34 #[error("reserved MP3 sample rate")]
36 ReservedSampleRate,
37}
38
39pub type Result<T> = std::result::Result<T, Error>;
41
42pub struct Config {
44 pub sample_rate: u32,
46 pub channel_count: u32,
48}
49
50impl Config {
51 pub fn parse(data: &[u8]) -> Result<Self> {
58 if data.len() < 4 {
59 return Err(Error::HeaderTooShort);
60 }
61
62 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 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], 0b10 => [22050, 24000, 16000][sr_index], 0b00 => [11025, 12000, 8000][sr_index], _ => return Err(Error::ReservedVersion),
84 };
85
86 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
96pub(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
104pub struct Import {
116 track: crate::container::Producer<crate::catalog::hang::Wire, hang::catalog::AudioConfig>,
117}
118
119impl Import {
120 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 let wire = crate::catalog::hang::Wire::try_from(&config)?;
133 let track = reserved.audio(track, wire, config)?;
137 Ok(Self { track })
138 }
139
140 pub fn demand(&self) -> moq_net::track::Demand {
142 self.track.track().demand()
143 }
144
145 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 pub fn abort(self, err: moq_net::Error) {
158 self.track.abort(err);
159 }
160
161 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 pub fn cut(&mut self, end: Option<moq_net::Timestamp>) -> crate::Result<()> {
172 self.track.cut(end)?;
173 Ok(())
174 }
175
176 pub fn discontinuity(&mut self) -> crate::Result<()> {
178 self.track.discontinuity()
179 }
180
181 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 pub(crate) fn write(&mut self, payload: bytes::Bytes, pts: Option<Timestamp>) -> crate::Result<Written> {
192 let timestamp = self.track.timestamp(pts)?;
193 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
208pub 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 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 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 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 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 assert_eq!(micros([0xFF, 0xFB, 0x94, 0x44]), 24_000);
261 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 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}