forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

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