forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

config.rs488 lines, 16.3 KiBHistoryRawDownload
1//! AudioSpecificConfig (ISO/IEC 14496-3 §1.6.2) and ADTS (§1.A.2) framing.
2
3use ec_core::{BitReader, BitWriter, Error, Result};
4
5use crate::tables::SAMPLE_RATES;
6
7/// AAC Low Complexity.
8pub const AOT_AAC_LC: u8 = 2;
9/// Spectral Band Replication (HE-AAC v1).
10pub const AOT_SBR: u8 = 5;
11/// Parametric Stereo (HE-AAC v2).
12pub const AOT_PS: u8 = 29;
13
14/// A rate's `samplingFrequencyIndex`, or `None` when AAC cannot carry it.
15pub fn sf_index_for_rate(rate: u32) -> Option<u8> {
16 SAMPLE_RATES
17 .iter()
18 .position(|&r| r == rate)
19 .map(|i| i as u8)
20}
21
22/// The rate a `samplingFrequencyIndex` names; 0 for the escape and reserved
23/// values.
24pub fn sample_rate_for_index(index: u8) -> u32 {
25 SAMPLE_RATES.get(usize::from(index)).copied().unwrap_or(0)
26}
27
28/// A decoded AudioSpecificConfig.
29#[derive(Clone, Debug, PartialEq, Eq)]
30pub struct AudioSpecificConfig {
31 /// Audio object type; 2 is AAC-LC, the only one this decoder codes.
32 pub object_type: u8,
33 pub sample_rate: u32,
34 pub sf_index: u8,
35 /// Channels the configuration implies, PCE included.
36 pub channels: u16,
37 /// `channelConfiguration`; 0 means the layout came from a PCE.
38 pub channel_config: u8,
39 /// True when the config signals SBR, i.e. HE-AAC.
40 pub sbr_present: bool,
41 /// True when the config signals Parametric Stereo, i.e. HE-AAC v2.
42 pub ps_present: bool,
43 /// The rate SBR would output at, when signalled.
44 pub extension_sample_rate: Option<u32>,
45 /// The program config element the config carries when `channel_config` is 0. Raw
46 /// blocks may then omit it, so their speaker layout comes from here.
47 pub pce: Vec<PceElement>,
48}
49
50/// Channels implied by `channelConfiguration` (ISO 14496-3 tbl 1.19).
51pub fn channels_for_config(config: u8) -> u16 {
52 match config {
53 1..=6 => u16::from(config),
54 7 => 8,
55 _ => 0,
56 }
57}
58
59fn object_type(r: &mut BitReader<'_>) -> Result<u8> {
60 let t = r.read_bits(5)? as u8;
61 if t == 31 {
62 return Ok(32 + r.read_bits(6)? as u8);
63 }
64 Ok(t)
65}
66
67fn sampling_frequency(r: &mut BitReader<'_>) -> Result<(u8, u32)> {
68 let index = r.read_bits(4)? as u8;
69 if index == 15 {
70 return Ok((index, r.read_bits(24)?));
71 }
72 Ok((index, sample_rate_for_index(index)))
73}
74
75/// Parses an AudioSpecificConfig, the `esds`/`CodecPrivate` payload.
76pub fn parse_audio_specific_config(data: &[u8]) -> Result<AudioSpecificConfig> {
77 let mut r = BitReader::new(data);
78 let mut object = object_type(&mut r)?;
79 let (mut sf_index, mut rate) = sampling_frequency(&mut r)?;
80 let mut channel_config = r.read_bits(4)? as u8;
81 let mut sbr = false;
82 let mut ps = false;
83 let mut ext_rate = None;
84 if object == AOT_SBR || object == AOT_PS {
85 sbr = true;
86 ps = object == AOT_PS;
87 let (_, er) = sampling_frequency(&mut r)?;
88 ext_rate = Some(er);
89 object = object_type(&mut r)?;
90 if object == 22 {
91 let _ext_channel_config = r.read_bits(4)?;
92 }
93 } else if object == AOT_AAC_LC {
94 // GASpecificConfig; the fields matter only for the PCE that may follow.
95 let _frame_length_flag = r.read_bit()?;
96 if r.read_bit()? {
97 let _core_coder_delay = r.read_bits(14)?;
98 }
99 let _extension_flag = r.read_bit()?;
100 if channel_config == 0 {
101 let pce = parse_program_config(&mut r)?;
102 channel_config = 0;
103 sf_index = pce.sf_index;
104 rate = sample_rate_for_index(pce.sf_index);
105 return Ok(AudioSpecificConfig {
106 object_type: object,
107 sample_rate: rate,
108 sf_index,
109 channels: pce.channels,
110 channel_config,
111 sbr_present: false,
112 ps_present: false,
113 extension_sample_rate: None,
114 pce: pce.elements,
115 });
116 }
117 // A backward-compatible SBR signal rides in a sync extension at the end.
118 if r.bits_remaining() >= 16 && r.read_bits(11)? == 0x2B7 {
119 let ext = object_type(&mut r)?;
120 if ext == AOT_SBR && r.read_bit()? {
121 sbr = true;
122 let (_, er) = sampling_frequency(&mut r)?;
123 ext_rate = Some(er);
124 }
125 }
126 }
127 if rate == 0 {
128 return Err(Error::corrupt("aac: reserved samplingFrequencyIndex"));
129 }
130 Ok(AudioSpecificConfig {
131 object_type: object,
132 sample_rate: rate,
133 sf_index,
134 channels: channels_for_config(channel_config),
135 channel_config,
136 sbr_present: sbr,
137 ps_present: ps,
138 extension_sample_rate: ext_rate,
139 pce: Vec::new(),
140 })
141}
142
143/// Serialises the two-byte (plus SBR extension) AudioSpecificConfig.
144///
145/// `AOT_SBR`/`AOT_PS` are the *explicit* signalling form (§1.6.2.1's "SBR
146/// config"): a core `sf_index`/`channel_config`, then the extension
147/// (`SBR`-output) `sf_index` and an `extensionAudioObjectType` of AAC-LC
148/// before the GASpecificConfig that form always carries -- without those
149/// fields a decoder that trusts the object type (rather than only its
150/// bare-ADTS implicit per-frame detection) has no extension rate to read and
151/// never reports itself as HE-AAC.
152pub fn write_audio_specific_config(cfg: &AudioSpecificConfig) -> Vec<u8> {
153 let mut w = BitWriter::new();
154 w.write_bits(u32::from(cfg.object_type), 5);
155 w.write_bits(u32::from(cfg.sf_index), 4);
156 w.write_bits(u32::from(cfg.channel_config), 4);
157 if cfg.object_type == AOT_SBR || cfg.object_type == AOT_PS {
158 let ext_rate = cfg.extension_sample_rate.unwrap_or(cfg.sample_rate * 2);
159 let ext_sf_index = sf_index_for_rate(ext_rate).unwrap_or(3);
160 w.write_bits(u32::from(ext_sf_index), 4);
161 w.write_bits(u32::from(AOT_AAC_LC), 5); // extensionAudioObjectType
162 }
163 w.write_bit(false); // frameLengthFlag: 1024 samples
164 w.write_bit(false); // dependsOnCoreCoder
165 w.write_bit(false); // extensionFlag
166 w.align_to_byte();
167 w.into_bytes()
168}
169
170/// The AudioSpecificConfig an AAC-LC track of this shape needs.
171pub fn audio_specific_config_bytes(sample_rate: u32, channels: u16) -> Vec<u8> {
172 let sf_index = sf_index_for_rate(sample_rate).unwrap_or(3);
173 write_audio_specific_config(&AudioSpecificConfig {
174 object_type: AOT_AAC_LC,
175 sample_rate,
176 sf_index,
177 channels,
178 channel_config: config_for_channels(channels),
179 sbr_present: false,
180 ps_present: false,
181 extension_sample_rate: None,
182 pce: Vec::new(),
183 })
184}
185
186/// The `channelConfiguration` that carries this many channels.
187pub fn config_for_channels(channels: u16) -> u8 {
188 match channels {
189 1..=6 => channels as u8,
190 8 => 7,
191 _ => 0,
192 }
193}
194
195/// A loudspeaker position, named as FFmpeg's channel masks name it. The derived
196/// order is the mask bit order, which is the order FFmpeg writes its output in.
197#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
198#[allow(clippy::upper_case_acronyms)] // FFmpeg's and ISO's own speaker names.
199pub enum Speaker {
200 FL,
201 FR,
202 FC,
203 LFE,
204 BL,
205 BR,
206 FLC,
207 FRC,
208 BC,
209 SL,
210 SR,
211}
212
213/// One element a program_config_element lists: its syntactic kind (`0` SCE, `1` CPE,
214/// `3` LFE, as in the raw data block's `id_syn_ele`), its instance tag, and the
215/// speaker of each of its channels. `speakers` is empty when the PCE's layout is
216/// one this crate does not name, and the decoder then keeps the bitstream order.
217#[derive(Clone, Debug, PartialEq, Eq)]
218pub struct PceElement {
219 pub kind: u8,
220 pub tag: u8,
221 pub speakers: Vec<Speaker>,
222}
223
224/// What a program_config_element says about the stream.
225#[derive(Clone, Debug, Default)]
226pub struct ProgramConfig {
227 pub sf_index: u8,
228 pub channels: u16,
229 /// The listed elements, in PCE order (front, side, back, LFE).
230 pub elements: Vec<PceElement>,
231}
232
233/// Names the speakers of a PCE's elements from the list each sits in.
234///
235/// Front elements run from the centre outwards: a centre SCE is FC, the outermost
236/// front pair is FL/FR, and an inner pair is FLC/FRC. Side and back pairs are SL/SR
237/// and BL/BR, a back SCE is BC, and each LFE is LFE. A layout outside those shapes
238/// (two centres, a third front pair, two side pairs, ...) names nothing, which the
239/// caller treats as an unknown layout.
240fn name_speakers(
241 front: &[(u8, u8)],
242 side: &[(u8, u8)],
243 back: &[(u8, u8)],
244 lfe: &[u8],
245) -> Option<Vec<Vec<Speaker>>> {
246 use Speaker::*;
247 let mut names: Vec<Vec<Speaker>> = Vec::new();
248 // Front, from the centre outwards: walk the list backwards so the last pair is outermost.
249 let mut front_names = vec![Vec::new(); front.len()];
250 let (mut pairs, mut centres) = (0usize, 0usize);
251 for (i, &(kind, _)) in front.iter().enumerate().rev() {
252 if kind == 1 {
253 front_names[i] = match pairs {
254 0 => vec![FL, FR],
255 1 => vec![FLC, FRC],
256 _ => return None,
257 };
258 pairs += 1;
259 } else {
260 if centres == 1 {
261 return None;
262 }
263 centres += 1;
264 front_names[i] = vec![FC];
265 }
266 }
267 names.extend(front_names);
268 let mut side_names = Vec::new();
269 for &(kind, _) in side {
270 if kind != 1 || !side_names.is_empty() {
271 return None;
272 }
273 side_names.push(vec![SL, SR]);
274 }
275 names.extend(side_names);
276 let mut back_names = Vec::new();
277 for &(kind, _) in back {
278 let next = match (kind, back_names.is_empty()) {
279 (1, true) => vec![BL, BR],
280 (0, true) => vec![BC],
281 _ => return None,
282 };
283 back_names.push(next);
284 }
285 names.extend(back_names);
286 if lfe.len() > 1 {
287 return None;
288 }
289 names.extend(lfe.iter().map(|_| vec![LFE]));
290 Some(names)
291}
292
293/// Parses a program_config_element, the channel layout a `channelConfiguration` of 0 carries.
294pub fn parse_program_config(r: &mut BitReader<'_>) -> Result<ProgramConfig> {
295 let _tag = r.read_bits(4)?;
296 let _object_type = r.read_bits(2)?;
297 let sf_index = r.read_bits(4)? as u8;
298 let front_n = r.read_bits(4)? as usize;
299 let side_n = r.read_bits(4)? as usize;
300 let back_n = r.read_bits(4)? as usize;
301 let lfe_n = r.read_bits(2)? as usize;
302 let assoc = r.read_bits(3)? as usize;
303 let cc = r.read_bits(4)? as usize;
304 if r.read_bit()? {
305 let _mono_mixdown = r.read_bits(4)?;
306 }
307 if r.read_bit()? {
308 let _stereo_mixdown = r.read_bits(4)?;
309 }
310 if r.read_bit()? {
311 let _matrix_mixdown = r.read_bits(3)?;
312 }
313 let mut channels = 0u16;
314 let read_cpe_tag = |r: &mut BitReader<'_>| -> Result<(u8, u8)> {
315 let cpe = r.read_bit()?;
316 let tag = r.read_bits(4)? as u8;
317 Ok((u8::from(cpe), tag))
318 };
319 let mut front = Vec::with_capacity(front_n);
320 for _ in 0..front_n {
321 front.push(read_cpe_tag(r)?);
322 }
323 let mut side = Vec::with_capacity(side_n);
324 for _ in 0..side_n {
325 side.push(read_cpe_tag(r)?);
326 }
327 let mut back = Vec::with_capacity(back_n);
328 for _ in 0..back_n {
329 back.push(read_cpe_tag(r)?);
330 }
331 let mut lfe = Vec::with_capacity(lfe_n);
332 for _ in 0..lfe_n {
333 lfe.push(r.read_bits(4)? as u8);
334 }
335 for _ in 0..assoc {
336 let _tag = r.read_bits(4)?;
337 }
338 for _ in 0..cc {
339 let _is_ind_sw = r.read_bit()?;
340 let _tag = r.read_bits(4)?;
341 }
342 r.align_to_byte();
343 let comment = r.read_bits(8)? as u64;
344 r.skip_bits(comment * 8)?;
345
346 for &(kind, _) in front.iter().chain(&side).chain(&back) {
347 channels += if kind == 1 { 2 } else { 1 };
348 }
349 channels += lfe.len() as u16;
350
351 // Speakers come back in the listing order (front, side, back, LFE), one entry per element.
352 let named = name_speakers(&front, &side, &back, &lfe).unwrap_or_default();
353 let listed = front
354 .iter()
355 .chain(&side)
356 .chain(&back)
357 .map(|&(kind, tag)| (kind, tag))
358 .chain(lfe.iter().map(|&tag| (3, tag)));
359 let mut elements = Vec::new();
360 for (i, (kind, tag)) in listed.enumerate() {
361 // An unnamed layout leaves `named` short, so every element then reads as unknown.
362 let speakers = named.get(i).cloned().unwrap_or_default();
363 elements.push(PceElement { kind, tag, speakers });
364 }
365 Ok(ProgramConfig {
366 sf_index,
367 channels,
368 elements,
369 })
370}
371
372/// An ADTS frame header (§1.A.2.2).
373#[derive(Clone, Copy, Debug, PartialEq, Eq)]
374pub struct AdtsHeader {
375 pub object_type: u8,
376 pub sf_index: u8,
377 pub sample_rate: u32,
378 pub channels: u16,
379 pub channel_config: u8,
380 /// Whole frame length in bytes, header included.
381 pub frame_length: usize,
382 /// Header length in bytes: 7, or 9 when the CRC is present.
383 pub header_len: usize,
384 pub raw_blocks: u8,
385}
386
387/// True when `data` opens on an ADTS syncword.
388pub fn is_adts(data: &[u8]) -> bool {
389 data.len() >= 2 && data[0] == 0xFF && data[1] & 0xF6 == 0xF0
390}
391
392/// Parses one ADTS header.
393pub fn parse_adts(data: &[u8]) -> Result<AdtsHeader> {
394 if data.len() < 7 {
395 return Err(Error::NeedMore);
396 }
397 let mut r = BitReader::new(data);
398 if r.read_bits(12)? != 0xFFF {
399 return Err(Error::corrupt("aac: no ADTS syncword"));
400 }
401 let _id = r.read_bit()?;
402 let layer = r.read_bits(2)?;
403 if layer != 0 {
404 return Err(Error::corrupt("aac: ADTS layer is not zero"));
405 }
406 let protection_absent = r.read_bit()?;
407 let object_type = r.read_bits(2)? as u8 + 1;
408 let sf_index = r.read_bits(4)? as u8;
409 let _private = r.read_bit()?;
410 let channel_config = r.read_bits(3)? as u8;
411 let _original = r.read_bit()?;
412 let _home = r.read_bit()?;
413 let _copyright_id = r.read_bit()?;
414 let _copyright_start = r.read_bit()?;
415 let frame_length = r.read_bits(13)? as usize;
416 let _fullness = r.read_bits(11)?;
417 let raw_blocks = r.read_bits(2)? as u8 + 1;
418 let header_len = if protection_absent { 7 } else { 9 };
419 if frame_length < header_len {
420 return Err(Error::corrupt("aac: ADTS frame shorter than its header"));
421 }
422 let sample_rate = sample_rate_for_index(sf_index);
423 if sample_rate == 0 {
424 return Err(Error::corrupt("aac: reserved samplingFrequencyIndex"));
425 }
426 Ok(AdtsHeader {
427 object_type,
428 sf_index,
429 sample_rate,
430 channels: channels_for_config(channel_config),
431 channel_config,
432 frame_length,
433 header_len,
434 raw_blocks,
435 })
436}
437
438/// Serialises a 7-byte ADTS header (no CRC).
439pub fn write_adts_header(header: &AdtsHeader) -> Vec<u8> {
440 let mut w = BitWriter::with_capacity(7);
441 w.write_bits(0xFFF, 12);
442 w.write_bit(false); // MPEG-4
443 w.write_bits(0, 2); // layer
444 w.write_bit(true); // protection absent
445 w.write_bits(u32::from(header.object_type.saturating_sub(1)), 2);
446 w.write_bits(u32::from(header.sf_index), 4);
447 w.write_bit(false); // private
448 w.write_bits(u32::from(header.channel_config), 3);
449 w.write_bit(false); // original
450 w.write_bit(false); // home
451 w.write_bit(false); // copyright id
452 w.write_bit(false); // copyright start
453 w.write_bits(header.frame_length as u32, 13);
454 w.write_bits(0x7FF, 11); // buffer fullness: variable rate
455 w.write_bits(u32::from(header.raw_blocks.saturating_sub(1)), 2);
456 w.into_bytes()
457}
458
459#[cfg(test)]
460mod tests {
461 use super::*;
462
463 /// An explicit-SBR AudioSpecificConfig (object type 5) round-trips its
464 /// core AND extension sample rate through `write`/`parse` -- the write
465 /// side that a bare-ADTS ASC needs so a decoder trusting the object type
466 /// (rather than implicit per-frame detection) reports HE-AAC at the
467 /// doubled rate.
468 #[test]
469 fn explicit_sbr_config_round_trips() {
470 let cfg = AudioSpecificConfig {
471 object_type: AOT_SBR,
472 sample_rate: 22050,
473 sf_index: sf_index_for_rate(22050).unwrap(),
474 channels: 1,
475 channel_config: 1,
476 sbr_present: true,
477 ps_present: false,
478 extension_sample_rate: Some(44100),
479 pce: Vec::new(),
480 };
481 let bytes = write_audio_specific_config(&cfg);
482 let parsed = parse_audio_specific_config(&bytes).expect("parses");
483 assert!(parsed.sbr_present, "explicit SBR must round-trip as SBR");
484 assert_eq!(parsed.sample_rate, 22050);
485 assert_eq!(parsed.extension_sample_rate, Some(44100));
486 assert_eq!(parsed.channels, 1);
487 }
488}