forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust382.4 MiBe18142dTahinli11 hours ago4543 commits

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