forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBcbbd6e2Tahinli2 months ago2369 commits

config.rs354 lines, 11.9 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}
46
47/// Channels implied by `channelConfiguration` (ISO 14496-3 tbl 1.19).
48pub fn channels_for_config(config: u8) -> u16 {
49 match config {
50 1..=6 => u16::from(config),
51 7 => 8,
52 _ => 0,
53 }
54}
55
56fn object_type(r: &mut BitReader<'_>) -> Result<u8> {
57 let t = r.read_bits(5)? as u8;
58 if t == 31 {
59 return Ok(32 + r.read_bits(6)? as u8);
60 }
61 Ok(t)
62}
63
64fn sampling_frequency(r: &mut BitReader<'_>) -> Result<(u8, u32)> {
65 let index = r.read_bits(4)? as u8;
66 if index == 15 {
67 return Ok((index, r.read_bits(24)?));
68 }
69 Ok((index, sample_rate_for_index(index)))
70}
71
72/// Parses an AudioSpecificConfig, the `esds`/`CodecPrivate` payload.
73pub fn parse_audio_specific_config(data: &[u8]) -> Result<AudioSpecificConfig> {
74 let mut r = BitReader::new(data);
75 let mut object = object_type(&mut r)?;
76 let (mut sf_index, mut rate) = sampling_frequency(&mut r)?;
77 let mut channel_config = r.read_bits(4)? as u8;
78 let mut sbr = false;
79 let mut ps = false;
80 let mut ext_rate = None;
81 if object == AOT_SBR || object == AOT_PS {
82 sbr = true;
83 ps = object == AOT_PS;
84 let (_, er) = sampling_frequency(&mut r)?;
85 ext_rate = Some(er);
86 object = object_type(&mut r)?;
87 if object == 22 {
88 let _ext_channel_config = r.read_bits(4)?;
89 }
90 } else if object == AOT_AAC_LC {
91 // GASpecificConfig; the fields matter only for the PCE that may follow.
92 let _frame_length_flag = r.read_bit()?;
93 if r.read_bit()? {
94 let _core_coder_delay = r.read_bits(14)?;
95 }
96 let _extension_flag = r.read_bit()?;
97 if channel_config == 0 {
98 let pce = parse_program_config(&mut r)?;
99 channel_config = 0;
100 sf_index = pce.sf_index;
101 rate = sample_rate_for_index(pce.sf_index);
102 return Ok(AudioSpecificConfig {
103 object_type: object,
104 sample_rate: rate,
105 sf_index,
106 channels: pce.channels,
107 channel_config,
108 sbr_present: false,
109 ps_present: false,
110 extension_sample_rate: None,
111 });
112 }
113 // A backward-compatible SBR signal rides in a sync extension at the end.
114 if r.bits_remaining() >= 16 && r.read_bits(11)? == 0x2B7 {
115 let ext = object_type(&mut r)?;
116 if ext == AOT_SBR && r.read_bit()? {
117 sbr = true;
118 let (_, er) = sampling_frequency(&mut r)?;
119 ext_rate = Some(er);
120 }
121 }
122 }
123 if rate == 0 {
124 return Err(Error::corrupt("aac: reserved samplingFrequencyIndex"));
125 }
126 Ok(AudioSpecificConfig {
127 object_type: object,
128 sample_rate: rate,
129 sf_index,
130 channels: channels_for_config(channel_config),
131 channel_config,
132 sbr_present: sbr,
133 ps_present: ps,
134 extension_sample_rate: ext_rate,
135 })
136}
137
138/// Serialises the two-byte (plus SBR extension) AudioSpecificConfig.
139///
140/// `AOT_SBR`/`AOT_PS` are the *explicit* signalling form (§1.6.2.1's "SBR
141/// config"): a core `sf_index`/`channel_config`, then the extension
142/// (`SBR`-output) `sf_index` and an `extensionAudioObjectType` of AAC-LC
143/// before the GASpecificConfig that form always carries -- without those
144/// fields a decoder that trusts the object type (rather than only its
145/// bare-ADTS implicit per-frame detection) has no extension rate to read and
146/// never reports itself as HE-AAC.
147pub fn write_audio_specific_config(cfg: &AudioSpecificConfig) -> Vec<u8> {
148 let mut w = BitWriter::new();
149 w.write_bits(u32::from(cfg.object_type), 5);
150 w.write_bits(u32::from(cfg.sf_index), 4);
151 w.write_bits(u32::from(cfg.channel_config), 4);
152 if cfg.object_type == AOT_SBR || cfg.object_type == AOT_PS {
153 let ext_rate = cfg.extension_sample_rate.unwrap_or(cfg.sample_rate * 2);
154 let ext_sf_index = sf_index_for_rate(ext_rate).unwrap_or(3);
155 w.write_bits(u32::from(ext_sf_index), 4);
156 w.write_bits(u32::from(AOT_AAC_LC), 5); // extensionAudioObjectType
157 }
158 w.write_bit(false); // frameLengthFlag: 1024 samples
159 w.write_bit(false); // dependsOnCoreCoder
160 w.write_bit(false); // extensionFlag
161 w.align_to_byte();
162 w.into_bytes()
163}
164
165/// The AudioSpecificConfig an AAC-LC track of this shape needs.
166pub fn audio_specific_config_bytes(sample_rate: u32, channels: u16) -> Vec<u8> {
167 let sf_index = sf_index_for_rate(sample_rate).unwrap_or(3);
168 write_audio_specific_config(&AudioSpecificConfig {
169 object_type: AOT_AAC_LC,
170 sample_rate,
171 sf_index,
172 channels,
173 channel_config: config_for_channels(channels),
174 sbr_present: false,
175 ps_present: false,
176 extension_sample_rate: None,
177 })
178}
179
180/// The `channelConfiguration` that carries this many channels.
181pub fn config_for_channels(channels: u16) -> u8 {
182 match channels {
183 1..=6 => channels as u8,
184 8 => 7,
185 _ => 0,
186 }
187}
188
189/// What a program_config_element says about the stream.
190#[derive(Clone, Debug, Default)]
191pub struct ProgramConfig {
192 pub sf_index: u8,
193 pub channels: u16,
194}
195
196/// Parses a program_config_element far enough to count its channels.
197pub fn parse_program_config(r: &mut BitReader<'_>) -> Result<ProgramConfig> {
198 let _tag = r.read_bits(4)?;
199 let _object_type = r.read_bits(2)?;
200 let sf_index = r.read_bits(4)? as u8;
201 let front = r.read_bits(4)? as usize;
202 let side = r.read_bits(4)? as usize;
203 let back = r.read_bits(4)? as usize;
204 let lfe = r.read_bits(2)? as usize;
205 let assoc = r.read_bits(3)? as usize;
206 let cc = r.read_bits(4)? as usize;
207 if r.read_bit()? {
208 let _mono_mixdown = r.read_bits(4)?;
209 }
210 if r.read_bit()? {
211 let _stereo_mixdown = r.read_bits(4)?;
212 }
213 if r.read_bit()? {
214 let _matrix_mixdown = r.read_bits(3)?;
215 }
216 let mut channels = 0u16;
217 for _ in 0..front + side + back {
218 channels += if r.read_bit()? { 2 } else { 1 };
219 let _tag = r.read_bits(4)?;
220 }
221 channels += lfe as u16;
222 for _ in 0..lfe + assoc {
223 let _tag = r.read_bits(4)?;
224 }
225 for _ in 0..cc {
226 let _is_ind_sw = r.read_bit()?;
227 let _tag = r.read_bits(4)?;
228 }
229 r.align_to_byte();
230 let comment = r.read_bits(8)? as u64;
231 r.skip_bits(comment * 8)?;
232 Ok(ProgramConfig { sf_index, channels })
233}
234
235pub(crate) fn skip_program_config(r: &mut BitReader<'_>) -> Result<()> {
236 parse_program_config(r).map(|_| ())
237}
238
239/// An ADTS frame header (§1.A.2.2).
240#[derive(Clone, Copy, Debug, PartialEq, Eq)]
241pub struct AdtsHeader {
242 pub object_type: u8,
243 pub sf_index: u8,
244 pub sample_rate: u32,
245 pub channels: u16,
246 pub channel_config: u8,
247 /// Whole frame length in bytes, header included.
248 pub frame_length: usize,
249 /// Header length in bytes: 7, or 9 when the CRC is present.
250 pub header_len: usize,
251 pub raw_blocks: u8,
252}
253
254/// True when `data` opens on an ADTS syncword.
255pub fn is_adts(data: &[u8]) -> bool {
256 data.len() >= 2 && data[0] == 0xFF && data[1] & 0xF6 == 0xF0
257}
258
259/// Parses one ADTS header.
260pub fn parse_adts(data: &[u8]) -> Result<AdtsHeader> {
261 if data.len() < 7 {
262 return Err(Error::NeedMore);
263 }
264 let mut r = BitReader::new(data);
265 if r.read_bits(12)? != 0xFFF {
266 return Err(Error::corrupt("aac: no ADTS syncword"));
267 }
268 let _id = r.read_bit()?;
269 let layer = r.read_bits(2)?;
270 if layer != 0 {
271 return Err(Error::corrupt("aac: ADTS layer is not zero"));
272 }
273 let protection_absent = r.read_bit()?;
274 let object_type = r.read_bits(2)? as u8 + 1;
275 let sf_index = r.read_bits(4)? as u8;
276 let _private = r.read_bit()?;
277 let channel_config = r.read_bits(3)? as u8;
278 let _original = r.read_bit()?;
279 let _home = r.read_bit()?;
280 let _copyright_id = r.read_bit()?;
281 let _copyright_start = r.read_bit()?;
282 let frame_length = r.read_bits(13)? as usize;
283 let _fullness = r.read_bits(11)?;
284 let raw_blocks = r.read_bits(2)? as u8 + 1;
285 let header_len = if protection_absent { 7 } else { 9 };
286 if frame_length < header_len {
287 return Err(Error::corrupt("aac: ADTS frame shorter than its header"));
288 }
289 let sample_rate = sample_rate_for_index(sf_index);
290 if sample_rate == 0 {
291 return Err(Error::corrupt("aac: reserved samplingFrequencyIndex"));
292 }
293 Ok(AdtsHeader {
294 object_type,
295 sf_index,
296 sample_rate,
297 channels: channels_for_config(channel_config),
298 channel_config,
299 frame_length,
300 header_len,
301 raw_blocks,
302 })
303}
304
305/// Serialises a 7-byte ADTS header (no CRC).
306pub fn write_adts_header(header: &AdtsHeader) -> Vec<u8> {
307 let mut w = BitWriter::with_capacity(7);
308 w.write_bits(0xFFF, 12);
309 w.write_bit(false); // MPEG-4
310 w.write_bits(0, 2); // layer
311 w.write_bit(true); // protection absent
312 w.write_bits(u32::from(header.object_type.saturating_sub(1)), 2);
313 w.write_bits(u32::from(header.sf_index), 4);
314 w.write_bit(false); // private
315 w.write_bits(u32::from(header.channel_config), 3);
316 w.write_bit(false); // original
317 w.write_bit(false); // home
318 w.write_bit(false); // copyright id
319 w.write_bit(false); // copyright start
320 w.write_bits(header.frame_length as u32, 13);
321 w.write_bits(0x7FF, 11); // buffer fullness: variable rate
322 w.write_bits(u32::from(header.raw_blocks.saturating_sub(1)), 2);
323 w.into_bytes()
324}
325
326#[cfg(test)]
327mod tests {
328 use super::*;
329
330 /// An explicit-SBR AudioSpecificConfig (object type 5) round-trips its
331 /// core AND extension sample rate through `write`/`parse` -- the write
332 /// side that a bare-ADTS ASC needs so a decoder trusting the object type
333 /// (rather than implicit per-frame detection) reports HE-AAC at the
334 /// doubled rate.
335 #[test]
336 fn explicit_sbr_config_round_trips() {
337 let cfg = AudioSpecificConfig {
338 object_type: AOT_SBR,
339 sample_rate: 22050,
340 sf_index: sf_index_for_rate(22050).unwrap(),
341 channels: 1,
342 channel_config: 1,
343 sbr_present: true,
344 ps_present: false,
345 extension_sample_rate: Some(44100),
346 };
347 let bytes = write_audio_specific_config(&cfg);
348 let parsed = parse_audio_specific_config(&bytes).expect("parses");
349 assert!(parsed.sbr_present, "explicit SBR must round-trip as SBR");
350 assert_eq!(parsed.sample_rate, 22050);
351 assert_eq!(parsed.extension_sample_rate, Some(44100));
352 assert_eq!(parsed.channels, 1);
353 }
354}