forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB00c1b3fTahinli2 months ago1999 commits

esds.rs298 lines, 11.1 KiBHistoryRawDownload
1//! The `esds` box: MPEG-4 ES descriptors, both directions.
2//!
3//! The one field anybody actually wants out of here is
4//! [`Esds::decoder_specific`] — the raw `DecoderSpecificInfo`, which for an AAC
5//! track is its `AudioSpecificConfig` and for an MP3-in-mp4 track is nothing at
6//! all. It is public *bytes*, deliberately: a caller that has to rebuild an ASC
7//! out of a parsed profile/frequency/channel triplet is a caller whose container
8//! threw the bytes away.
9
10use ec_core::{Buf, Error, Result};
11
12/// `ES_Descriptor`.
13const TAG_ES: u8 = 0x03;
14/// `DecoderConfigDescriptor`.
15const TAG_DECODER_CONFIG: u8 = 0x04;
16/// `DecoderSpecificInfo`.
17const TAG_DECODER_SPECIFIC: u8 = 0x05;
18/// `SLConfigDescriptor`.
19const TAG_SL_CONFIG: u8 = 0x06;
20
21/// Object type indications, ISO/IEC 14496-1 table 5: what the elementary stream
22/// actually is, which is the only thing telling an `mp4a` entry holding MP3 from
23/// one holding AAC.
24pub mod object_type {
25 /// MPEG-4 Audio (AAC and the rest of 14496-3).
26 pub const MPEG4_AUDIO: u8 = 0x40;
27 /// MPEG-2 AAC Main/LC/SSR.
28 pub const MPEG2_AAC_MAIN: u8 = 0x66;
29 /// MPEG-2 AAC LC.
30 pub const MPEG2_AAC_LC: u8 = 0x67;
31 /// MPEG-2 AAC SSR.
32 pub const MPEG2_AAC_SSR: u8 = 0x68;
33 /// MPEG-2 Audio Part 3 (MP3 at half rates).
34 pub const MPEG2_AUDIO: u8 = 0x69;
35 /// MPEG-1 Audio (MP3).
36 pub const MPEG1_AUDIO: u8 = 0x6B;
37}
38
39/// An `esds` payload as its fields.
40#[derive(Debug, Clone, PartialEq, Eq, Default)]
41pub struct Esds {
42 /// Elementary stream id; 0 for the single-stream tracks every file has.
43 pub es_id: u16,
44 /// What the stream is: see [`object_type`].
45 pub object_type: u8,
46 /// `streamType` (5 = audio, 4 = video), as the descriptor states it.
47 pub stream_type: u8,
48 /// Decoding buffer size in bytes.
49 pub buffer_size_db: u32,
50 /// Peak bitrate in bits per second, 0 for "not stated".
51 pub max_bitrate: u32,
52 /// Average bitrate in bits per second, 0 for "not stated".
53 pub avg_bitrate: u32,
54 /// The `DecoderSpecificInfo` bytes verbatim — an `AudioSpecificConfig` for
55 /// AAC. [`None`] where the track carries none, which is normal for MP3.
56 pub decoder_specific: Option<Buf>,
57}
58
59impl Esds {
60 /// An AAC descriptor around one `AudioSpecificConfig`, which is what a muxer
61 /// has to write and all it has to write.
62 pub fn aac(config: impl Into<Buf>) -> Esds {
63 Esds {
64 es_id: 0,
65 object_type: object_type::MPEG4_AUDIO,
66 stream_type: 5,
67 buffer_size_db: 0,
68 max_bitrate: 0,
69 avg_bitrate: 0,
70 decoder_specific: Some(config.into()),
71 }
72 }
73
74 /// True for the object types whose `DecoderSpecificInfo` is an
75 /// `AudioSpecificConfig`.
76 pub fn is_aac(&self) -> bool {
77 matches!(
78 self.object_type,
79 object_type::MPEG4_AUDIO
80 | object_type::MPEG2_AAC_MAIN
81 | object_type::MPEG2_AAC_LC
82 | object_type::MPEG2_AAC_SSR
83 )
84 }
85
86 /// Parse the payload of an `esds` box (after its version/flags word).
87 pub fn parse(payload: &[u8]) -> Result<Esds> {
88 let (tag, body, _) = descriptor(payload)?;
89 if tag != TAG_ES {
90 return Err(Error::corrupt(format!(
91 "mp4: esds starts with descriptor 0x{tag:02x}, not an ES_Descriptor"
92 )));
93 }
94 let mut out = Esds {
95 es_id: crate::boxes::be16(body, 0)?,
96 ..Esds::default()
97 };
98 let flags = *body
99 .get(2)
100 .ok_or_else(|| Error::corrupt("mp4: esds ends in its flags"))?;
101 let mut at = 3;
102 if flags & 0x80 != 0 {
103 at += 2; // dependsOn_ES_ID
104 }
105 if flags & 0x40 != 0 {
106 let len = *body
107 .get(at)
108 .ok_or_else(|| Error::corrupt("mp4: esds ends in its URL length"))?;
109 at += 1 + len as usize;
110 }
111 if flags & 0x20 != 0 {
112 at += 2; // OCR_ES_Id
113 }
114 let mut rest = body.get(at..).unwrap_or(&[]);
115 // A descriptor list ends where the descriptors do: a trailing byte too
116 // short to be one is padding (a real export in the library ends its
117 // `esds` with exactly one), not a corrupt file.
118 while rest.len() >= 2 {
119 let Ok((tag, inner, len)) = descriptor(rest) else {
120 break;
121 };
122 if tag == TAG_DECODER_CONFIG {
123 out.object_type = *inner
124 .first()
125 .ok_or_else(|| Error::corrupt("mp4: empty DecoderConfigDescriptor"))?;
126 out.stream_type = inner.get(1).map_or(0, |b| b >> 2);
127 out.buffer_size_db = u32::from_be_bytes([
128 0,
129 inner.get(2).copied().unwrap_or(0),
130 inner.get(3).copied().unwrap_or(0),
131 inner.get(4).copied().unwrap_or(0),
132 ]);
133 out.max_bitrate = crate::boxes::be32(inner, 5).unwrap_or(0);
134 out.avg_bitrate = crate::boxes::be32(inner, 9).unwrap_or(0);
135 let mut inner_rest = inner.get(13..).unwrap_or(&[]);
136 while inner_rest.len() >= 2 {
137 let Ok((tag, dsi, len)) = descriptor(inner_rest) else {
138 break;
139 };
140 if tag == TAG_DECODER_SPECIFIC {
141 out.decoder_specific = Some(Buf::copy_from_slice(dsi));
142 }
143 inner_rest = &inner_rest[len..];
144 }
145 }
146 rest = &rest[len..];
147 }
148 Ok(out)
149 }
150
151 /// The `esds` payload for these fields, version/flags word included.
152 pub fn write(&self) -> Vec<u8> {
153 let mut config = Vec::new();
154 if let Some(dsi) = &self.decoder_specific {
155 descriptor_out(&mut config, TAG_DECODER_SPECIFIC, dsi);
156 }
157 let mut decoder = Vec::with_capacity(13 + config.len());
158 decoder.push(self.object_type);
159 decoder.push((self.stream_type << 2) | 0x01); // upStream 0, reserved 1
160 decoder.extend_from_slice(&self.buffer_size_db.to_be_bytes()[1..]);
161 decoder.extend_from_slice(&self.max_bitrate.to_be_bytes());
162 decoder.extend_from_slice(&self.avg_bitrate.to_be_bytes());
163 decoder.extend_from_slice(&config);
164
165 let mut es = Vec::new();
166 es.extend_from_slice(&self.es_id.to_be_bytes());
167 es.push(0); // no dependency, no URL, no OCR, priority 0
168 descriptor_out(&mut es, TAG_DECODER_CONFIG, &decoder);
169 // SLConfigDescriptor: predefined 2, "the container tells the time".
170 descriptor_out(&mut es, TAG_SL_CONFIG, &[0x02]);
171
172 let mut out = vec![0, 0, 0, 0]; // version 0, flags 0
173 descriptor_out(&mut out, TAG_ES, &es);
174 out
175 }
176}
177
178/// One descriptor at the front of `data`: its tag, its body, and how many bytes
179/// of `data` it took including the header.
180fn descriptor(data: &[u8]) -> Result<(u8, &[u8], usize)> {
181 let tag = *data
182 .first()
183 .ok_or_else(|| Error::corrupt("mp4: descriptor with no tag"))?;
184 let mut len = 0u32;
185 let mut at = 1;
186 // Up to four length bytes, seven bits each — the fifth would be a file
187 // spinning a parser rather than describing a stream.
188 for _ in 0..4 {
189 let b = *data
190 .get(at)
191 .ok_or_else(|| Error::corrupt("mp4: descriptor length runs off the box"))?;
192 at += 1;
193 len = (len << 7) | u32::from(b & 0x7F);
194 if b & 0x80 == 0 {
195 break;
196 }
197 if at == 5 {
198 return Err(Error::corrupt("mp4: descriptor length over four bytes"));
199 }
200 }
201 let end = at + len as usize;
202 if end > data.len() {
203 return Err(Error::corrupt(format!(
204 "mp4: descriptor 0x{tag:02x} states {len} bytes inside {}",
205 data.len() - at
206 )));
207 }
208 Ok((tag, &data[at..end], end))
209}
210
211/// The inverse, with the length in as few bytes as it fits.
212fn descriptor_out(out: &mut Vec<u8>, tag: u8, body: &[u8]) {
213 out.push(tag);
214 let mut len = body.len() as u32;
215 let mut bytes = [0u8; 4];
216 let mut n = 0;
217 loop {
218 bytes[n] = (len & 0x7F) as u8;
219 len >>= 7;
220 n += 1;
221 if len == 0 || n == 4 {
222 break;
223 }
224 }
225 for i in (0..n).rev() {
226 out.push(bytes[i] | if i == 0 { 0 } else { 0x80 });
227 }
228 out.extend_from_slice(body);
229}
230
231#[cfg(test)]
232mod tests {
233 use super::*;
234
235 #[test]
236 fn an_aac_config_survives_the_round_trip_as_bytes() {
237 // 48 kHz stereo AAC-LC: the two bytes edith had to rebuild by hand
238 // because the incumbent parsed them apart and dropped the original.
239 let asc = [0x11u8, 0x90];
240 let bytes = Esds::aac(&asc[..]).write();
241 let (_, _, payload) = crate::boxes::full(&bytes).unwrap();
242 let back = Esds::parse(payload).unwrap();
243 assert!(back.is_aac());
244 assert_eq!(back.object_type, object_type::MPEG4_AUDIO);
245 assert_eq!(back.stream_type, 5);
246 assert_eq!(back.decoder_specific.as_deref(), Some(&asc[..]));
247 }
248
249 #[test]
250 fn long_descriptors_use_the_multi_byte_length() {
251 let big = vec![0xAB; 300];
252 let bytes = Esds::aac(&big[..]).write();
253 let (_, _, payload) = crate::boxes::full(&bytes).unwrap();
254 assert_eq!(
255 Esds::parse(payload).unwrap().decoder_specific.as_deref(),
256 Some(&big[..])
257 );
258 }
259
260 #[test]
261 fn an_mp3_descriptor_carries_no_config_and_is_not_aac() {
262 let mut esds = Esds::aac(&[][..]);
263 esds.object_type = object_type::MPEG1_AUDIO;
264 esds.decoder_specific = None;
265 esds.avg_bitrate = 128_000;
266 let bytes = esds.write();
267 let (_, _, payload) = crate::boxes::full(&bytes).unwrap();
268 let back = Esds::parse(payload).unwrap();
269 assert!(!back.is_aac());
270 assert_eq!(back.avg_bitrate, 128_000);
271 assert_eq!(back.decoder_specific, None);
272 }
273
274 /// The `esds` an export in the real library actually carries: an
275 /// `SLConfigDescriptor` and then one padding byte, which is not a truncated
276 /// descriptor and must not be read as one.
277 #[test]
278 fn a_trailing_padding_byte_is_not_a_broken_descriptor() {
279 let bytes: [u8; 31] = [
280 0x03, 0x19, 0x00, 0x01, 0x00, 0x04, 0x11, 0x40, 0x15, 0x00, 0x02, 0xA9, 0x00, 0x00,
281 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x02, 0x11, 0x90, 0x06, 0x00, 0x00, 0x00,
282 0x00, 0x00, 0x00,
283 ];
284 let esds = Esds::parse(&bytes).expect("the file plays, so it parses");
285 assert!(esds.is_aac());
286 assert_eq!(esds.decoder_specific.as_deref(), Some(&[0x11, 0x90][..]));
287 }
288
289 #[test]
290 fn truncated_descriptors_are_errors() {
291 assert!(Esds::parse(&[]).is_err());
292 assert!(Esds::parse(&[TAG_ES, 0x7F, 0, 0]).is_err()); // states 127 bytes, has 2
293 assert!(Esds::parse(&[TAG_ES, 2, 0, 0]).is_err()); // ends inside the flags
294 assert!(Esds::parse(&[TAG_SL_CONFIG, 1, 2]).is_err()); // not an ES_Descriptor
295 // Four continuation bytes in a row must stop rather than spin.
296 assert!(Esds::parse(&[TAG_ES, 0x80, 0x80, 0x80, 0x80, 0x80]).is_err());
297 }
298}