forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB52fc2fcTahinli3 months ago295 commits

decode.rs1121 lines, 40.1 KiBHistoryRawDownload
1//! `raw_data_block` decoding: ISO/IEC 14496-3 §4.4.2 syntax, §4.6 tools.
2//!
3//! Band, group and window indices are the domain's own coordinates and address
4//! several parallel arrays at once, so the loops here are written over indices
5//! rather than iterators.
6#![allow(clippy::needless_range_loop)]
7
8use ec_core::{BitReader, Error, Result};
9use ec_dsp::{Mdct, Window};
10
11use crate::huffman::Books;
12use crate::tables::{CODEBOOKS, SWB_LONG, SWB_SHORT, TNS_MAX_BANDS_LONG, TNS_MAX_BANDS_SHORT};
13
14/// Samples one AAC frame carries per channel.
15pub const FRAME_LEN: usize = 1024;
16/// Samples one short block carries.
17pub const SHORT_LEN: usize = 128;
18/// The `sect_cb` value for a band coded as all zeroes.
19const ZERO_HCB: u8 = 0;
20/// The `sect_cb` value for perceptual noise substitution.
21const NOISE_HCB: u8 = 13;
22/// Out-of-phase intensity stereo.
23const INTENSITY_HCB2: u8 = 14;
24/// In-phase intensity stereo.
25const INTENSITY_HCB: u8 = 15;
26/// `sf` is an exponent in quarter-powers of two around this offset (§4.6.2).
27const SF_OFFSET: i32 = 100;
28/// The dequantiser works in the standard's own units, where full scale is
29/// 2^16; the public API speaks the usual +/-1 float range. Checked against a
30/// reference decode in `adts_fixtures_match_ffmpeg_per_channel`, which compares
31/// amplitudes and not just shape.
32pub(crate) const OUTPUT_SCALE: f32 = 1.0 / 65536.0;
33/// The longest TNS filter AAC-LC allows (long blocks; short blocks stop at 7).
34const TNS_MAX_ORDER_LONG: usize = 12;
35const TNS_MAX_ORDER_SHORT: usize = 7;
36
37/// The four window sequences of §4.6.11.
38#[derive(Clone, Copy, PartialEq, Eq, Debug)]
39pub enum WindowSequence {
40 OnlyLong,
41 LongStart,
42 EightShort,
43 LongStop,
44}
45
46impl WindowSequence {
47 fn from_bits(v: u32) -> WindowSequence {
48 match v {
49 1 => WindowSequence::LongStart,
50 2 => WindowSequence::EightShort,
51 3 => WindowSequence::LongStop,
52 _ => WindowSequence::OnlyLong,
53 }
54 }
55
56 /// True for `EIGHT_SHORT_SEQUENCE`, which changes almost every field width.
57 pub fn is_short(self) -> bool {
58 self == WindowSequence::EightShort
59 }
60}
61
62/// One `raw_data_block` element's coding-tool usage, gated by
63/// `EC_AAC_TOOL_SIDEINFO_DEBUG` -- mirrors `sbr_chain::SbrSideInfoRow`'s
64/// pattern for the LC core, so a real file's PNS/M-S/IS/TNS mix can be read
65/// back per AU without re-parsing debug text.
66#[derive(Clone, Debug)]
67pub struct ToolSideInfoRow {
68 pub au: usize,
69 pub tag: u8,
70 pub is_cpe: bool,
71 pub window_sequence: WindowSequence,
72 pub ms_bands: usize,
73 pub pns_bands: usize,
74 pub is_bands: usize,
75 pub tns_present: bool,
76}
77
78static TOOL_SIDEINFO_LOG: std::sync::OnceLock<std::sync::Mutex<Vec<ToolSideInfoRow>>> =
79 std::sync::OnceLock::new();
80static TOOL_SIDEINFO_AU: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
81
82fn tool_sideinfo_enabled() -> bool {
83 std::env::var("EC_AAC_TOOL_SIDEINFO_DEBUG").is_ok()
84}
85
86fn log_tool_sideinfo(row: ToolSideInfoRow) {
87 let log = TOOL_SIDEINFO_LOG.get_or_init(|| std::sync::Mutex::new(Vec::new()));
88 if let Ok(mut l) = log.lock() {
89 l.push(row);
90 }
91}
92
93/// Bumps the shared AU counter once per `raw_data_block`, returning the value
94/// that call's rows should carry.
95fn next_tool_sideinfo_au() -> usize {
96 TOOL_SIDEINFO_AU.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
97}
98
99/// Every row logged so far this process, in call order. Empty unless
100/// `EC_AAC_TOOL_SIDEINFO_DEBUG` was set before decoding.
101pub fn tool_sideinfo_log() -> Vec<ToolSideInfoRow> {
102 let Some(log) = TOOL_SIDEINFO_LOG.get() else {
103 return Vec::new();
104 };
105 log.lock().map(|l| l.clone()).unwrap_or_default()
106}
107
108/// `ics_info` (§4.4.2.1) plus the grouping it implies.
109#[derive(Clone, Debug)]
110pub struct IcsInfo {
111 pub window_sequence: WindowSequence,
112 /// False for the sine window, true for Kaiser-Bessel-derived.
113 pub window_shape_kbd: bool,
114 pub max_sfb: usize,
115 pub num_windows: usize,
116 pub num_groups: usize,
117 /// Windows per group, `num_groups` entries.
118 pub group_len: [usize; 8],
119 /// Band offsets in force for this window shape, `num_swb + 1` entries.
120 pub swb: &'static [u16],
121 /// Highest band a TNS filter may reach at this rate and window length.
122 pub tns_max_bands: usize,
123}
124
125impl IcsInfo {
126 fn num_swb(&self) -> usize {
127 self.swb.len() - 1
128 }
129
130 /// First window index of each group.
131 fn group_start(&self, g: usize) -> usize {
132 self.group_len[..g].iter().sum()
133 }
134}
135
136fn parse_ics_info(r: &mut BitReader<'_>, sf_index: u8) -> Result<IcsInfo> {
137 let _reserved = r.read_bit()?;
138 let window_sequence = WindowSequence::from_bits(r.read_bits(2)?);
139 let window_shape_kbd = r.read_bit()?;
140 let idx = usize::from(sf_index).min(11);
141 let (max_sfb, num_windows, num_groups, group_len, swb, tns_max_bands) =
142 if window_sequence.is_short() {
143 let max_sfb = r.read_bits(4)? as usize;
144 let grouping = r.read_bits(7)?;
145 let mut group_len = [0usize; 8];
146 let mut groups = 1;
147 group_len[0] = 1;
148 for i in 0..7 {
149 if (grouping >> (6 - i)) & 1 == 1 {
150 group_len[groups - 1] += 1;
151 } else {
152 group_len[groups] = 1;
153 groups += 1;
154 }
155 }
156 (
157 max_sfb,
158 8,
159 groups,
160 group_len,
161 SWB_SHORT[idx],
162 TNS_MAX_BANDS_SHORT[idx],
163 )
164 } else {
165 let max_sfb = r.read_bits(6)? as usize;
166 if r.read_bit()? {
167 // AAC-LC has no predictor; LTP/main streams are a different profile.
168 return Err(Error::unsupported(
169 "aac",
170 "predictor_data_present: main or LTP profile, not AAC-LC",
171 ));
172 }
173 let mut group_len = [0usize; 8];
174 group_len[0] = 1;
175 (
176 max_sfb,
177 1,
178 1,
179 group_len,
180 SWB_LONG[idx],
181 TNS_MAX_BANDS_LONG[idx],
182 )
183 };
184 if max_sfb > swb.len() - 1 {
185 return Err(Error::corrupt("aac: max_sfb past the band table"));
186 }
187 Ok(IcsInfo {
188 window_sequence,
189 window_shape_kbd,
190 max_sfb,
191 num_windows,
192 num_groups,
193 group_len,
194 swb,
195 tns_max_bands,
196 })
197}
198
199/// One TNS filter as transmitted, already converted to LPC coefficients.
200#[derive(Clone, Debug, Default)]
201struct TnsFilter {
202 /// Bands the filter spans, counted down from the top.
203 length: usize,
204 order: usize,
205 /// True when the filter runs from high frequency down.
206 downward: bool,
207 lpc: Vec<f32>,
208}
209
210#[derive(Clone, Debug, Default)]
211struct Tns {
212 /// Filters per window.
213 filters: Vec<Vec<TnsFilter>>,
214}
215
216fn parse_tns(r: &mut BitReader<'_>, ics: &IcsInfo) -> Result<Tns> {
217 let short = ics.window_sequence.is_short();
218 let (n_filt_bits, len_bits, order_bits) = if short { (1, 4, 3) } else { (2, 6, 5) };
219 let max_order = if short {
220 TNS_MAX_ORDER_SHORT
221 } else {
222 TNS_MAX_ORDER_LONG
223 };
224 let mut filters = Vec::with_capacity(ics.num_windows);
225 for _ in 0..ics.num_windows {
226 let n_filt = r.read_bits(n_filt_bits)? as usize;
227 let mut coef_res = 0;
228 if n_filt > 0 {
229 coef_res = u32::from(r.read_bit()?);
230 }
231 let mut win = Vec::with_capacity(n_filt);
232 for _ in 0..n_filt {
233 let length = r.read_bits(len_bits)? as usize;
234 let order = r.read_bits(order_bits)? as usize;
235 if order == 0 {
236 win.push(TnsFilter {
237 length,
238 ..TnsFilter::default()
239 });
240 continue;
241 }
242 // A stream may state a longer filter than the profile allows; the
243 // extra taps are dropped rather than the frame refused.
244 let order = order.min(max_order);
245 let downward = r.read_bit()?;
246 let compress = u32::from(r.read_bit()?);
247 let res_bits = coef_res + 3;
248 let bits = res_bits - compress;
249 // §4.6.9.3: the transmitted index is a signed fraction of a quarter
250 // turn, and the two half-step factors keep the mapping symmetric.
251 let iqfac = ((1 << (res_bits - 1)) as f64 - 0.5) / core::f64::consts::FRAC_PI_2;
252 let iqfac_m = ((1 << (res_bits - 1)) as f64 + 0.5) / core::f64::consts::FRAC_PI_2;
253 let mut parcor = Vec::with_capacity(order);
254 for _ in 0..order {
255 let raw = r.read_bits(bits)? as i32;
256 let sign_bit = 1 << (bits - 1);
257 let value = if raw & sign_bit != 0 {
258 raw - (1 << bits)
259 } else {
260 raw
261 };
262 let scaled = if value >= 0 {
263 f64::from(value) / iqfac
264 } else {
265 f64::from(value) / iqfac_m
266 };
267 parcor.push(scaled.sin());
268 }
269 win.push(TnsFilter {
270 length,
271 order,
272 downward,
273 lpc: parcor_to_lpc(&parcor),
274 });
275 }
276 filters.push(win);
277 }
278 Ok(Tns { filters })
279}
280
281/// Reflection coefficients to direct-form LPC (§4.6.9.3), `a[0] == 1`.
282fn parcor_to_lpc(parcor: &[f64]) -> Vec<f32> {
283 let mut a = vec![0.0f64; parcor.len() + 1];
284 let mut tmp = vec![0.0f64; parcor.len() + 1];
285 a[0] = 1.0;
286 for (m, &k) in parcor.iter().enumerate() {
287 for i in 1..=m {
288 tmp[i] = a[i] + k * a[m + 1 - i];
289 }
290 a[1..=m].copy_from_slice(&tmp[1..=m]);
291 a[m + 1] = k;
292 }
293 a.into_iter().map(|v| v as f32).collect()
294}
295
296/// Applies every TNS filter of one window in place (§4.6.9.2).
297fn apply_tns(coef: &mut [f32], tns: &Tns, ics: &IcsInfo, window: usize) {
298 let Some(filters) = tns.filters.get(window) else {
299 return;
300 };
301 let num_swb = ics.num_swb();
302 let mut bottom = num_swb;
303 for filter in filters {
304 let top = bottom;
305 bottom = top.saturating_sub(filter.length);
306 if filter.order == 0 {
307 continue;
308 }
309 let cap = ics.max_sfb.min(ics.tns_max_bands);
310 let start = usize::from(ics.swb[bottom.min(cap)]);
311 let end = usize::from(ics.swb[top.min(cap)]);
312 if end <= start {
313 continue;
314 }
315 let order = filter.order;
316 let mut state = vec![0.0f32; order + 1];
317 let walk = |i: usize, state: &mut Vec<f32>, coef: &mut [f32]| {
318 let mut y = coef[i];
319 for j in 1..=order {
320 y -= filter.lpc[j] * state[j - 1];
321 }
322 for j in (1..=order).rev() {
323 state[j] = state[j - 1];
324 }
325 state[0] = y;
326 coef[i] = y;
327 };
328 if filter.downward {
329 for i in (start..end).rev() {
330 walk(i, &mut state, coef);
331 }
332 } else {
333 for i in start..end {
334 walk(i, &mut state, coef);
335 }
336 }
337 }
338}
339
340/// Per-channel data of one `individual_channel_stream`.
341struct Ics {
342 ics: IcsInfo,
343 /// `sect_cb` by group and band.
344 cb: Vec<Vec<u8>>,
345 /// Scalefactor, intensity position or noise energy by group and band.
346 sf: Vec<Vec<i32>>,
347 coef: Vec<f32>,
348 tns: Tns,
349}
350
351/// The decoder's per-channel memory: the filterbank overlap and the window
352/// shape the next frame's rising edge has to match.
353#[derive(Clone, Debug)]
354pub struct ChannelState {
355 overlap: Vec<f32>,
356 prev_shape_kbd: bool,
357 prev_short: bool,
358}
359
360impl Default for ChannelState {
361 fn default() -> ChannelState {
362 ChannelState {
363 overlap: vec![0.0; FRAME_LEN],
364 prev_shape_kbd: false,
365 prev_short: false,
366 }
367 }
368}
369
370/// The four windows and two transforms the filterbank needs, built once.
371pub struct FilterBank {
372 long: Mdct<f32>,
373 short: Mdct<f32>,
374 sine_long: Vec<f32>,
375 kbd_long: Vec<f32>,
376 sine_short: Vec<f32>,
377 kbd_short: Vec<f32>,
378 scratch_long: Vec<f32>,
379 scratch_short: Vec<f32>,
380}
381
382impl FilterBank {
383 pub fn new() -> FilterBank {
384 FilterBank {
385 long: Mdct::new(2 * FRAME_LEN),
386 short: Mdct::new(2 * SHORT_LEN),
387 sine_long: Window::<f32>::sine(2 * FRAME_LEN).as_slice().to_vec(),
388 kbd_long: Window::<f32>::kbd(2 * FRAME_LEN, 4.0).as_slice().to_vec(),
389 sine_short: Window::<f32>::sine(2 * SHORT_LEN).as_slice().to_vec(),
390 kbd_short: Window::<f32>::kbd(2 * SHORT_LEN, 6.0).as_slice().to_vec(),
391 scratch_long: vec![0.0; 2 * FRAME_LEN],
392 scratch_short: vec![0.0; 2 * SHORT_LEN],
393 }
394 }
395
396 fn long_win(&self, kbd: bool) -> &[f32] {
397 if kbd { &self.kbd_long } else { &self.sine_long }
398 }
399
400 fn short_win(&self, kbd: bool) -> &[f32] {
401 if kbd {
402 &self.kbd_short
403 } else {
404 &self.sine_short
405 }
406 }
407
408 /// Inverse filterbank and overlap-add for one channel (§4.6.11).
409 fn synthesize(
410 &mut self,
411 spec: &[f32],
412 ics: &IcsInfo,
413 state: &mut ChannelState,
414 out: &mut [f32],
415 ) {
416 let mut frame = vec![0.0f32; 2 * FRAME_LEN];
417 match ics.window_sequence {
418 WindowSequence::EightShort => {
419 for w in 0..8 {
420 let src = &spec[w * SHORT_LEN..(w + 1) * SHORT_LEN];
421 self.short.inverse(src, &mut self.scratch_short);
422 let rise = self.short_win(if w == 0 {
423 state.prev_shape_kbd
424 } else {
425 ics.window_shape_kbd
426 });
427 let fall = self.short_win(ics.window_shape_kbd);
428 let base = 448 + w * SHORT_LEN;
429 for i in 0..SHORT_LEN {
430 frame[base + i] += self.scratch_short[i] * rise[i];
431 frame[base + SHORT_LEN + i] +=
432 self.scratch_short[SHORT_LEN + i] * fall[SHORT_LEN + i];
433 }
434 }
435 }
436 seq => {
437 self.long.inverse(spec, &mut self.scratch_long);
438 let prev_long = self.long_win(state.prev_shape_kbd);
439 let prev_short = self.short_win(state.prev_shape_kbd);
440 let cur_long = self.long_win(ics.window_shape_kbd);
441 let cur_short = self.short_win(ics.window_shape_kbd);
442 for i in 0..FRAME_LEN {
443 let rise = match seq {
444 // A stop window opens flat: nothing to overlap with the
445 // short block that preceded it until sample 448.
446 WindowSequence::LongStop => match i {
447 0..448 => 0.0,
448 448..576 => prev_short[i - 448],
449 _ => 1.0,
450 },
451 _ => prev_long[i],
452 };
453 frame[i] = self.scratch_long[i] * rise;
454 }
455 for i in 0..FRAME_LEN {
456 let fall = match seq {
457 WindowSequence::LongStart => match i {
458 0..448 => 1.0,
459 448..576 => cur_short[SHORT_LEN + i - 448],
460 _ => 0.0,
461 },
462 _ => cur_long[FRAME_LEN + i],
463 };
464 frame[FRAME_LEN + i] = self.scratch_long[FRAME_LEN + i] * fall;
465 }
466 }
467 }
468 for i in 0..FRAME_LEN {
469 out[i] = (state.overlap[i] + frame[i]) * OUTPUT_SCALE;
470 }
471 state.overlap.copy_from_slice(&frame[FRAME_LEN..]);
472 state.prev_shape_kbd = ics.window_shape_kbd;
473 state.prev_short = ics.window_sequence.is_short();
474 }
475}
476
477impl Default for FilterBank {
478 fn default() -> FilterBank {
479 FilterBank::new()
480 }
481}
482
483/// Deterministic noise source for PNS; the standard leaves the sequence free,
484/// only the band energy is normative.
485#[derive(Clone, Debug)]
486pub struct Noise(u32);
487
488impl Noise {
489 fn next(&mut self) -> f32 {
490 self.0 = self.0.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
491 (self.0 >> 8) as f32 / (1 << 23) as f32 - 1.0
492 }
493}
494
495/// The syntactic and tool state one `raw_data_block` needs.
496pub struct BlockDecoder {
497 pub books: Books,
498 pub bank: FilterBank,
499 pub states: Vec<ChannelState>,
500 noise: Noise,
501 sf_index: u8,
502 sbr: Option<crate::sbr_chain::SbrChain>,
503}
504
505impl BlockDecoder {
506 pub fn new(sf_index: u8) -> BlockDecoder {
507 BlockDecoder {
508 books: Books::new(),
509 bank: FilterBank::new(),
510 states: Vec::new(),
511 noise: Noise(0x1234_5678),
512 sf_index,
513 sbr: None,
514 }
515 }
516
517 pub fn set_sf_index(&mut self, sf_index: u8) {
518 self.sf_index = sf_index;
519 }
520
521 /// Enables (or disables, passing `None`) SBR reconstruction at the
522 /// given extension (doubled) sample rate.
523 pub fn set_sbr_rate(&mut self, rate: Option<u32>) {
524 self.sbr = rate.map(crate::sbr_chain::SbrChain::new);
525 }
526
527 fn section_data(&self, r: &mut BitReader<'_>, ics: &IcsInfo) -> Result<Vec<Vec<u8>>> {
528 let bits = if ics.window_sequence.is_short() { 3 } else { 5 };
529 let esc = (1u32 << bits) - 1;
530 let mut out = Vec::with_capacity(ics.num_groups);
531 for _ in 0..ics.num_groups {
532 let mut row = vec![ZERO_HCB; ics.max_sfb];
533 let mut k = 0usize;
534 while k < ics.max_sfb {
535 let cb = r.read_bits(4)? as u8;
536 let mut len = 0usize;
537 loop {
538 let incr = r.read_bits(bits)?;
539 len += incr as usize;
540 if incr != esc {
541 break;
542 }
543 }
544 if len == 0 || k + len > ics.max_sfb {
545 return Err(Error::corrupt("aac: section runs past max_sfb"));
546 }
547 row[k..k + len].fill(cb);
548 k += len;
549 }
550 out.push(row);
551 }
552 Ok(out)
553 }
554
555 fn scale_factor_data(
556 &self,
557 r: &mut BitReader<'_>,
558 ics: &IcsInfo,
559 cb: &[Vec<u8>],
560 global_gain: u8,
561 ) -> Result<Vec<Vec<i32>>> {
562 let mut scale = i32::from(global_gain);
563 let mut intensity = 0i32;
564 let mut noise = i32::from(global_gain) - 90;
565 let mut noise_pcm = true;
566 let mut out = Vec::with_capacity(ics.num_groups);
567 for g in 0..ics.num_groups {
568 let mut row = vec![0i32; ics.max_sfb];
569 for sfb in 0..ics.max_sfb {
570 row[sfb] = match cb[g][sfb] {
571 ZERO_HCB => 0,
572 INTENSITY_HCB | INTENSITY_HCB2 => {
573 intensity += self.books.scalefactor.decode(r)? as i32 - 60;
574 intensity
575 }
576 NOISE_HCB => {
577 if noise_pcm {
578 noise_pcm = false;
579 noise += r.read_bits(9)? as i32 - 256;
580 } else {
581 noise += self.books.scalefactor.decode(r)? as i32 - 60;
582 }
583 noise
584 }
585 _ => {
586 scale += self.books.scalefactor.decode(r)? as i32 - 60;
587 if !(0..=255).contains(&scale) {
588 return Err(Error::corrupt("aac: scalefactor out of range"));
589 }
590 scale
591 }
592 };
593 }
594 out.push(row);
595 }
596 Ok(out)
597 }
598
599 /// `spectral_data` (§4.4.2.7) into quantised integers, window-major.
600 fn spectral_data(
601 &self,
602 r: &mut BitReader<'_>,
603 ics: &IcsInfo,
604 cb: &[Vec<u8>],
605 quant: &mut [i32],
606 ) -> Result<()> {
607 for g in 0..ics.num_groups {
608 let start = ics.group_start(g);
609 for sfb in 0..ics.max_sfb {
610 let book = cb[g][sfb];
611 if !(1..=11).contains(&book) {
612 continue;
613 }
614 let spec = &CODEBOOKS[usize::from(book) - 1];
615 let tree = &self.books.spectral[usize::from(book) - 1];
616 let lo = usize::from(ics.swb[sfb]);
617 let hi = usize::from(ics.swb[sfb + 1]);
618 for w in 0..ics.group_len[g] {
619 let base = if ics.window_sequence.is_short() {
620 (start + w) * SHORT_LEN
621 } else {
622 0
623 };
624 let mut k = lo;
625 while k < hi {
626 let mut values = [0i32; 4];
627 let symbol = tree.decode(r)?;
628 decode_tuple(spec, symbol, &mut values);
629 let dim = usize::from(spec.dim);
630 if spec.unsigned {
631 for v in values.iter_mut().take(dim) {
632 if *v != 0 && r.read_bit()? {
633 *v = -*v;
634 }
635 }
636 }
637 if spec.esc {
638 for v in values.iter_mut().take(dim) {
639 if v.unsigned_abs() == 16 {
640 let mut n = 0u32;
641 while r.read_bit()? {
642 n += 1;
643 if n > 20 {
644 return Err(Error::corrupt("aac: escape too long"));
645 }
646 }
647 let magnitude = (1i32 << (n + 4)) | r.read_bits(n + 4)? as i32;
648 *v = if *v < 0 { -magnitude } else { magnitude };
649 }
650 }
651 }
652 for (i, &v) in values.iter().take(dim).enumerate() {
653 if k + i < hi {
654 quant[base + k + i] = v;
655 }
656 }
657 k += dim;
658 }
659 }
660 }
661 }
662 Ok(())
663 }
664
665 /// One `individual_channel_stream` (§4.4.2.4).
666 fn channel_stream(&mut self, r: &mut BitReader<'_>, shared: Option<&IcsInfo>) -> Result<Ics> {
667 let global_gain = r.read_bits(8)? as u8;
668 let ics = match shared {
669 Some(info) => info.clone(),
670 None => parse_ics_info(r, self.sf_index)?,
671 };
672 let cb = self.section_data(r, &ics)?;
673 let sf = self.scale_factor_data(r, &ics, &cb, global_gain)?;
674 let mut pulse = None;
675 if r.read_bit()? {
676 if ics.window_sequence.is_short() {
677 return Err(Error::corrupt("aac: pulse data on a short window"));
678 }
679 pulse = Some(parse_pulse(r)?);
680 }
681 let tns = if r.read_bit()? {
682 parse_tns(r, &ics)?
683 } else {
684 Tns::default()
685 };
686 if r.read_bit()? {
687 return Err(Error::unsupported("aac", "gain control data: SSR profile"));
688 }
689 let mut quant = vec![0i32; FRAME_LEN];
690 self.spectral_data(r, &ics, &cb, &mut quant)?;
691 if let Some(p) = pulse {
692 apply_pulse(&mut quant, &p, &ics);
693 }
694 Ok(Ics {
695 coef: dequantize(&quant, &ics, &cb, &sf),
696 ics,
697 cb,
698 sf,
699 tns,
700 })
701 }
702
703 /// Runs the stereo tools, TNS and the filterbank over one element's
704 /// channels, appending each channel's PCM to `out`.
705 fn finish(&mut self, chans: &mut [Ics], ms: Option<&MsMask>, out: &mut Vec<Vec<f32>>) {
706 // Noise substitution (§4.6.13) must fill its bands before M/S and
707 // intensity stereo run, so those tools combine the noise-filled
708 // coefficients like any other spectral data rather than the zeroes
709 // `dequantize` left behind for NOISE_HCB bands -- matching the
710 // decode order every reference decoder uses.
711 for ch in chans.iter_mut() {
712 fill_noise(ch, &mut self.noise);
713 }
714 if let ([left, right], Some(mask)) = (&mut *chans, ms) {
715 apply_ms(left, right, mask);
716 }
717 if let [left, right] = &mut *chans {
718 apply_intensity(left, right, ms);
719 }
720 for ch in chans.iter_mut() {
721 let windows = if ch.ics.window_sequence.is_short() {
722 8
723 } else {
724 1
725 };
726 for w in 0..windows {
727 let len = if windows == 8 { SHORT_LEN } else { FRAME_LEN };
728 apply_tns(&mut ch.coef[w * len..(w + 1) * len], &ch.tns, &ch.ics, w);
729 }
730 let mut pcm = vec![0.0f32; FRAME_LEN];
731 let index = out.len();
732 while self.states.len() <= index {
733 self.states.push(ChannelState::default());
734 }
735 self.bank
736 .synthesize(&ch.coef, &ch.ics, &mut self.states[index], &mut pcm);
737 out.push(pcm);
738 }
739 }
740
741 /// Decodes one `raw_data_block`, returning one PCM plane per channel in
742 /// bitstream element order.
743 pub fn raw_data_block(&mut self, r: &mut BitReader<'_>) -> Result<Vec<Vec<f32>>> {
744 let mut out: Vec<Vec<f32>> = Vec::new();
745 // The element (tag, channel range, is_cpe) an immediately following
746 // FIL's SBR payload would apply to, per §4.5.1: a fill_element
747 // directly follows the element it decorates.
748 let mut pending: Option<(u8, usize, usize, bool)> = None;
749 let dump_tools = tool_sideinfo_enabled();
750 let au = if dump_tools { next_tool_sideinfo_au() } else { 0 };
751 loop {
752 if r.bits_remaining() < 3 {
753 break;
754 }
755 let id = r.read_bits(3)?;
756 match id {
757 // SCE and LFE are one channel each; CCE (2) is a coupling
758 // element this profile never emits and cannot be skipped
759 // blind, so it is refused rather than silently mis-parsed.
760 0 | 3 => {
761 let tag = r.read_bits(4)? as u8;
762 let start = out.len();
763 let mut ch = [self.channel_stream(r, None)?];
764 if dump_tools {
765 log_tool_sideinfo(tool_row(au, tag, false, &ch[0], None));
766 }
767 self.finish(&mut ch, None, &mut out);
768 // §4.6.18.1: SBR is never applied to the LFE channel (no
769 // FIL/SBR payload follows it), so it must not become a
770 // pending SBR target -- otherwise a later fallback
771 // (`apply_last`/no-FIL branch) could mistakenly stretch
772 // the LFE plane to double rate using a *different*
773 // element's held SBR data, corrupting it.
774 pending = if id == 0 {
775 Some((tag, start, 1, false))
776 } else {
777 None
778 };
779 }
780 1 => {
781 let tag = r.read_bits(4)? as u8;
782 let start = out.len();
783 let common = r.read_bit()?;
784 let (shared, mask) = if common {
785 let info = parse_ics_info(r, self.sf_index)?;
786 let present = r.read_bits(2)?;
787 let mask = match present {
788 0 => MsMask::None,
789 1 => {
790 let mut bits = vec![vec![false; info.max_sfb]; info.num_groups];
791 for row in bits.iter_mut() {
792 for b in row.iter_mut() {
793 *b = r.read_bit()?;
794 }
795 }
796 MsMask::Some(bits)
797 }
798 2 => MsMask::All,
799 _ => return Err(Error::corrupt("aac: reserved ms_mask_present")),
800 };
801 (Some(info), mask)
802 } else {
803 (None, MsMask::None)
804 };
805 let mut pair = [
806 self.channel_stream(r, shared.as_ref())?,
807 self.channel_stream(r, shared.as_ref())?,
808 ];
809 if dump_tools {
810 log_tool_sideinfo(tool_row(au, tag, true, &pair[0], Some(&mask)));
811 }
812 self.finish(&mut pair, Some(&mask), &mut out);
813 pending = Some((tag, start, 2, true));
814 }
815 2 => return Err(Error::unsupported("aac", "coupling channel element")),
816 4 => {
817 let _tag = r.read_bits(4)?;
818 let align = r.read_bit()?;
819 let mut count = r.read_bits(8)? as u64;
820 if count == 255 {
821 count += r.read_bits(8)? as u64;
822 }
823 if align {
824 r.align_to_byte();
825 }
826 r.skip_bits(count * 8)?;
827 pending = None;
828 }
829 5 => {
830 crate::config::skip_program_config(r)?;
831 pending = None;
832 }
833 6 => {
834 let mut count = r.read_bits(4)? as u64;
835 if count == 15 {
836 count += r.read_bits(8)? as u64 - 1;
837 }
838 let end_bit = r.bit_position() + count * 8;
839 if let (Some(sbr), Some((tag, start, n, is_cpe))) =
840 (self.sbr.as_mut(), pending.take())
841 {
842 // extension_payload(): bs_extension_type(4), then
843 // (for SBR) an optional 10-bit CRC, then
844 // sbr_extension_data() itself.
845 let mut applied = false;
846 if r.bits_remaining() >= 4 {
847 let ext_type = r.peek_bits(4)?;
848 if ext_type == 13 || ext_type == 14 {
849 r.skip_bits(4)?;
850 if ext_type == 14 && r.bits_remaining() >= 10 {
851 r.skip_bits(10)?; // bs_sbr_crc_bits
852 }
853 if let Some(data) = sbr.parse(r, tag, is_cpe) {
854 sbr.apply(tag, is_cpe, &data, &mut out[start..start + n]);
855 applied = true;
856 }
857 }
858 }
859 if !applied {
860 // No fresh SBR payload this frame (no SBR fill
861 // element, or one whose extension_type wasn't
862 // SBR, or a parse failure): §4.6.18 still
863 // requires doubled-rate reconstruction, using
864 // the last successfully parsed frame's data.
865 sbr.apply_last(tag, is_cpe, &mut out[start..start + n]);
866 }
867 }
868 // Resync to the FIL's declared byte boundary regardless
869 // of how many bits SBR parsing above actually consumed:
870 // a parse error or trailing padding must never desync
871 // the elements that follow.
872 let now = r.bit_position();
873 if now < end_bit {
874 r.skip_bits(end_bit - now)?;
875 }
876 pending = None;
877 }
878 _ => {
879 // The block ended with no FIL element ever following the
880 // last SCE/CPE (no SBR fill at all this frame, not even
881 // a non-SBR one) -- same "unavailable frame" case as the
882 // no-fresh-payload branch in id 6 above, so fall back to
883 // the last known SBR data the same way.
884 if let (Some(sbr), Some((tag, start, n, is_cpe))) =
885 (self.sbr.as_mut(), pending)
886 {
887 sbr.apply_last(tag, is_cpe, &mut out[start..start + n]);
888 }
889 break;
890 }
891 }
892 }
893 r.align_to_byte();
894 Ok(out)
895 }
896}
897
898#[derive(Debug)]
899enum MsMask {
900 None,
901 All,
902 Some(Vec<Vec<bool>>),
903}
904
905impl MsMask {
906 fn used(&self, g: usize, sfb: usize) -> bool {
907 match self {
908 MsMask::None => false,
909 MsMask::All => true,
910 MsMask::Some(bits) => bits[g][sfb],
911 }
912 }
913}
914
915/// The symbol index back into its tuple; the index is the tuple read as digits
916/// in base `lav + 1` (unsigned) or `2 * lav + 1` (signed), first coefficient
917/// most significant.
918fn decode_tuple(cb: &crate::tables::Codebook, symbol: usize, out: &mut [i32; 4]) {
919 let span = if cb.unsigned {
920 usize::from(cb.lav) + 1
921 } else {
922 2 * usize::from(cb.lav) + 1
923 };
924 let off = if cb.unsigned { 0 } else { i32::from(cb.lav) };
925 let dim = usize::from(cb.dim);
926 let mut rest = symbol;
927 for i in (0..dim).rev() {
928 out[i] = (rest % span) as i32 - off;
929 rest /= span;
930 }
931}
932
933#[derive(Debug)]
934struct Pulse {
935 start_sfb: usize,
936 offsets: Vec<usize>,
937 amps: Vec<i32>,
938}
939
940fn parse_pulse(r: &mut BitReader<'_>) -> Result<Pulse> {
941 let count = r.read_bits(2)? as usize + 1;
942 let start_sfb = r.read_bits(6)? as usize;
943 let mut offsets = Vec::with_capacity(count);
944 let mut amps = Vec::with_capacity(count);
945 for _ in 0..count {
946 offsets.push(r.read_bits(5)? as usize);
947 amps.push(r.read_bits(4)? as i32);
948 }
949 Ok(Pulse {
950 start_sfb,
951 offsets,
952 amps,
953 })
954}
955
956fn apply_pulse(quant: &mut [i32], pulse: &Pulse, ics: &IcsInfo) {
957 if pulse.start_sfb >= ics.swb.len() {
958 return;
959 }
960 let mut k = usize::from(ics.swb[pulse.start_sfb]);
961 for (&off, &amp) in pulse.offsets.iter().zip(&pulse.amps) {
962 k += off;
963 if k >= quant.len() {
964 return;
965 }
966 // The pulse grows the magnitude, keeping whatever sign the coefficient
967 // already had (§4.6.3).
968 quant[k] += if quant[k] < 0 { -amp } else { amp };
969 }
970}
971
972/// `x^(4/3) * 2^((sf - 100) / 4)` per band (§4.6.2), window-major.
973fn dequantize(quant: &[i32], ics: &IcsInfo, cb: &[Vec<u8>], sf: &[Vec<i32>]) -> Vec<f32> {
974 let mut coef = vec![0.0f32; FRAME_LEN];
975 let short = ics.window_sequence.is_short();
976 for g in 0..ics.num_groups {
977 let start = ics.group_start(g);
978 for sfb in 0..ics.max_sfb {
979 let book = cb[g][sfb];
980 if !(1..=11).contains(&book) {
981 continue;
982 }
983 let gain = 2f32.powf((sf[g][sfb] - SF_OFFSET) as f32 * 0.25);
984 let lo = usize::from(ics.swb[sfb]);
985 let hi = usize::from(ics.swb[sfb + 1]);
986 for w in 0..ics.group_len[g] {
987 let base = if short { (start + w) * SHORT_LEN } else { 0 };
988 for k in lo..hi {
989 let q = quant[base + k];
990 if q != 0 {
991 let mag = (q.unsigned_abs() as f32).powf(4.0 / 3.0) * gain;
992 coef[base + k] = if q < 0 { -mag } else { mag };
993 }
994 }
995 }
996 }
997 }
998 coef
999}
1000
1001/// Mid/side to left/right, for every band the mask marks and no other (§4.6.8.1).
1002fn apply_ms(left: &mut Ics, right: &mut Ics, mask: &MsMask) {
1003 let ics = &left.ics;
1004 let short = ics.window_sequence.is_short();
1005 for g in 0..ics.num_groups {
1006 let start = ics.group_start(g);
1007 for sfb in 0..ics.max_sfb {
1008 if !mask.used(g, sfb) || is_intensity(right.cb[g][sfb]) {
1009 continue;
1010 }
1011 let lo = usize::from(ics.swb[sfb]);
1012 let hi = usize::from(ics.swb[sfb + 1]);
1013 for w in 0..ics.group_len[g] {
1014 let base = if short { (start + w) * SHORT_LEN } else { 0 };
1015 for k in base + lo..base + hi {
1016 let (m, s) = (left.coef[k], right.coef[k]);
1017 left.coef[k] = m + s;
1018 right.coef[k] = m - s;
1019 }
1020 }
1021 }
1022 }
1023}
1024
1025/// Builds one `EC_AAC_TOOL_SIDEINFO_DEBUG` row from an already-decoded `Ics`
1026/// (any channel of a CPE, since PNS/IS/TNS presence is per-channel but the
1027/// dump only needs whether the element used the tool at all).
1028fn tool_row(au: usize, tag: u8, is_cpe: bool, ch: &Ics, mask: Option<&MsMask>) -> ToolSideInfoRow {
1029 let mut ms_bands = 0;
1030 let mut pns_bands = 0;
1031 let mut is_bands = 0;
1032 for g in 0..ch.ics.num_groups {
1033 for sfb in 0..ch.ics.max_sfb {
1034 if mask.is_some_and(|m| m.used(g, sfb)) {
1035 ms_bands += 1;
1036 }
1037 match ch.cb[g][sfb] {
1038 NOISE_HCB => pns_bands += 1,
1039 INTENSITY_HCB | INTENSITY_HCB2 => is_bands += 1,
1040 _ => {}
1041 }
1042 }
1043 }
1044 ToolSideInfoRow {
1045 au,
1046 tag,
1047 is_cpe,
1048 window_sequence: ch.ics.window_sequence,
1049 ms_bands,
1050 pns_bands,
1051 is_bands,
1052 tns_present: !ch.tns.filters.is_empty(),
1053 }
1054}
1055
1056fn is_intensity(cb: u8) -> bool {
1057 cb == INTENSITY_HCB || cb == INTENSITY_HCB2
1058}
1059
1060/// Intensity stereo: the right channel's marked bands are the left channel's,
1061/// scaled by `0.5^(is_position / 4)` and signed by the codebook (§4.6.8.2).
1062fn apply_intensity(left: &mut Ics, right: &mut Ics, ms: Option<&MsMask>) {
1063 let ics = right.ics.clone();
1064 let short = ics.window_sequence.is_short();
1065 for g in 0..ics.num_groups {
1066 let start = ics.group_start(g);
1067 for sfb in 0..ics.max_sfb {
1068 let cb = right.cb[g][sfb];
1069 if !is_intensity(cb) {
1070 continue;
1071 }
1072 let mut sign = if cb == INTENSITY_HCB { 1.0 } else { -1.0 };
1073 if ms.is_some_and(|m| m.used(g, sfb)) {
1074 sign = -sign;
1075 }
1076 let scale = sign * 0.5f32.powf(0.25 * right.sf[g][sfb] as f32);
1077 let lo = usize::from(ics.swb[sfb]);
1078 let hi = usize::from(ics.swb[sfb + 1]);
1079 for w in 0..ics.group_len[g] {
1080 let base = if short { (start + w) * SHORT_LEN } else { 0 };
1081 for k in base + lo..base + hi {
1082 right.coef[k] = left.coef[k] * scale;
1083 }
1084 }
1085 }
1086 }
1087}
1088
1089/// Perceptual noise substitution: the band is filled with noise carrying the
1090/// transmitted energy (§4.6.13). The sequence is free, the energy is not.
1091fn fill_noise(ch: &mut Ics, rng: &mut Noise) {
1092 let ics = ch.ics.clone();
1093 let short = ics.window_sequence.is_short();
1094 for g in 0..ics.num_groups {
1095 let start = ics.group_start(g);
1096 for sfb in 0..ics.max_sfb {
1097 if ch.cb[g][sfb] != NOISE_HCB {
1098 continue;
1099 }
1100 let lo = usize::from(ics.swb[sfb]);
1101 let hi = usize::from(ics.swb[sfb + 1]);
1102 for w in 0..ics.group_len[g] {
1103 let base = if short { (start + w) * SHORT_LEN } else { 0 };
1104 let mut energy = 0.0f32;
1105 for k in base + lo..base + hi {
1106 let v = rng.next();
1107 ch.coef[k] = v;
1108 energy += v * v;
1109 }
1110 if energy <= 0.0 {
1111 continue;
1112 }
1113 let target = 2f32.powf(0.25 * ch.sf[g][sfb] as f32);
1114 let scale = target / energy.sqrt();
1115 for k in base + lo..base + hi {
1116 ch.coef[k] *= scale;
1117 }
1118 }
1119 }
1120 }
1121}