forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust381.2 MiBcdccbc2Tahinli8 hours ago4263 commits

decode.rs1298 lines, 47.4 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/// 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 crate::knobs::tool_sideinfo_debug()
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 i32::from_ne_bytes(self.0.to_ne_bytes()) as f32
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 /// Core rate an implicit SBR payload may double (ISO/IEC 14496-3 1.6.5.2),
504 /// or `None` when implicit SBR is off: no core rate known yet, the stream's
505 /// config already signals SBR (`sbr` is set), or the core is above 24 kHz.
506 implicit_core: Option<u32>,
507 /// Set once an SBR extension payload has armed `sbr` with no explicit signalling.
508 implicit_on: bool,
509 /// Set by `disable_implicit_sbr`: implicit SBR never arms, whatever the headers say.
510 implicit_off: bool,
511 /// Set once a PS extension has been decoded in a stream whose SBR was
512 /// switched on implicitly (see `implicit_on`).
513 implicit_ps: bool,
514 pns_aus: usize,
515 /// The elements of the last program_config_element seen in the stream, if any.
516 pce: Option<Vec<crate::config::PceElement>>,
517 /// Speaker of each channel of the last raw_data_block, in bitstream order, when every
518 /// element of the block is named by its PCE. `None` keeps the bitstream order.
519 plane_speakers: Option<Vec<crate::config::Speaker>>,
520}
521
522/// Highest core rate at which an implicit SBR payload doubles the output (so the
523/// doubled rate stays at or below 48 kHz). ffmpeg makes the same cut.
524const IMPLICIT_SBR_MAX_CORE_RATE: u32 = 24_000;
525
526impl BlockDecoder {
527 pub fn new(sf_index: u8) -> BlockDecoder {
528 BlockDecoder {
529 books: Books::new(),
530 bank: FilterBank::new(),
531 states: Vec::new(),
532 noise: Noise(0x1f2e_3d4c),
533 sf_index,
534 sbr: None,
535 implicit_core: None,
536 implicit_on: false,
537 implicit_off: false,
538 implicit_ps: false,
539 pns_aus: 0,
540 pce: None,
541 plane_speakers: None,
542 }
543 }
544
545 /// The output order of the last block's planes, as the plane index each output
546 /// channel takes, in FFmpeg's channel-mask order. `None` when no PCE named them.
547 pub fn plane_order(&self, channels: usize) -> Option<Vec<usize>> {
548 let speakers = self.plane_speakers.as_ref()?;
549 if speakers.len() != channels {
550 return None;
551 }
552 let mut order: Vec<usize> = (0..channels).collect();
553 order.sort_by_key(|&i| (speakers[i], i));
554 Some(order)
555 }
556
557 /// Sets the program config element a config carries, for raw blocks that omit it.
558 pub fn set_pce(&mut self, pce: Vec<crate::config::PceElement>) {
559 self.pce = (!pce.is_empty()).then_some(pce);
560 }
561
562 /// The speakers of the channels one element of kind `kind` (`0` SCE, `1` CPE, `3` LFE)
563 /// and instance `tag` carries, per the last PCE. `None` when no PCE names it.
564 fn pce_speakers(&self, kind: u8, tag: u8) -> Option<&[crate::config::Speaker]> {
565 self.pce
566 .as_ref()?
567 .iter()
568 .find(|e| e.kind == kind && e.tag == tag && !e.speakers.is_empty())
569 .map(|e| e.speakers.as_slice())
570 }
571
572 pub fn pns_aus(&self) -> usize {
573 self.pns_aus
574 }
575 pub fn set_sf_index(&mut self, sf_index: u8) {
576 self.sf_index = sf_index;
577 }
578
579 /// Enables (or disables, passing `None`) SBR reconstruction at the
580 /// given extension (doubled) sample rate.
581 pub fn set_sbr_rate(&mut self, rate: Option<u32>) {
582 self.sbr = rate.map(crate::sbr_chain::SbrChain::new);
583 }
584
585 pub fn set_sbr_downsampled(&mut self, on: bool) {
586 if let Some(sbr) = self.sbr.as_mut() {
587 sbr.set_downsampled(on);
588 }
589 }
590
591 /// Marks Parametric Stereo as signalled by the config, for the SBR chain
592 /// (if one is armed): its elements then decode to two channels.
593 pub fn set_sbr_ps(&mut self, on: bool) {
594 if let Some(sbr) = self.sbr.as_mut() {
595 sbr.set_ps_config(on);
596 }
597 }
598
599 /// Arms implicit SBR for a stream whose config does not signal it, at the
600 /// given core rate. Above 24 kHz (or once SBR is already set) it is a no-op:
601 /// an SBR payload there is skipped, and the output stays at the core rate.
602 pub fn set_implicit_core(&mut self, core_rate: u32) {
603 if self.sbr.is_none() && !self.implicit_off {
604 self.implicit_core = (core_rate <= IMPLICIT_SBR_MAX_CORE_RATE).then_some(core_rate);
605 }
606 }
607
608 /// Keeps implicit SBR off for good: an SBR payload is skipped and the output
609 /// stays at the core rate. For core-only decoding of a stream that carries SBR.
610 pub fn disable_implicit_sbr(&mut self) {
611 self.implicit_off = true;
612 self.implicit_core = None;
613 }
614
615 /// Whether SBR was switched on by an implicit payload, not by the config.
616 pub fn implicit_sbr(&self) -> bool {
617 self.implicit_on
618 }
619
620 /// Whether a Parametric Stereo extension was decoded in a stream whose SBR
621 /// is implicit (see [`BlockDecoder::implicit_sbr`]).
622 pub fn implicit_ps(&self) -> bool {
623 self.implicit_ps
624 }
625
626 fn section_data(&self, r: &mut BitReader<'_>, ics: &IcsInfo) -> Result<Vec<Vec<u8>>> {
627 let bits = if ics.window_sequence.is_short() { 3 } else { 5 };
628 let esc = (1u32 << bits) - 1;
629 let mut out = Vec::with_capacity(ics.num_groups);
630 for _ in 0..ics.num_groups {
631 let mut row = vec![ZERO_HCB; ics.max_sfb];
632 let mut k = 0usize;
633 while k < ics.max_sfb {
634 let cb = r.read_bits(4)? as u8;
635 let mut len = 0usize;
636 loop {
637 let incr = r.read_bits(bits)?;
638 len += incr as usize;
639 if incr != esc {
640 break;
641 }
642 }
643 if len == 0 || k + len > ics.max_sfb {
644 return Err(Error::corrupt("aac: section runs past max_sfb"));
645 }
646 row[k..k + len].fill(cb);
647 k += len;
648 }
649 out.push(row);
650 }
651 Ok(out)
652 }
653
654 fn scale_factor_data(
655 &self,
656 r: &mut BitReader<'_>,
657 ics: &IcsInfo,
658 cb: &[Vec<u8>],
659 global_gain: u8,
660 ) -> Result<Vec<Vec<i32>>> {
661 let mut scale = i32::from(global_gain);
662 let mut intensity = 0i32;
663 let mut noise = i32::from(global_gain) - 90;
664 let mut noise_pcm = true;
665 let mut out = Vec::with_capacity(ics.num_groups);
666 for g in 0..ics.num_groups {
667 let mut row = vec![0i32; ics.max_sfb];
668 for sfb in 0..ics.max_sfb {
669 row[sfb] = match cb[g][sfb] {
670 ZERO_HCB => 0,
671 INTENSITY_HCB | INTENSITY_HCB2 => {
672 intensity += self.books.scalefactor.decode(r)? as i32 - 60;
673 intensity
674 }
675 NOISE_HCB => {
676 if noise_pcm {
677 noise_pcm = false;
678 noise += r.read_bits(9)? as i32 - 256;
679 } else {
680 noise += self.books.scalefactor.decode(r)? as i32 - 60;
681 }
682 noise
683 }
684 _ => {
685 scale += self.books.scalefactor.decode(r)? as i32 - 60;
686 if !(0..=255).contains(&scale) {
687 return Err(Error::corrupt("aac: scalefactor out of range"));
688 }
689 scale
690 }
691 };
692 }
693 out.push(row);
694 }
695 Ok(out)
696 }
697
698 /// `spectral_data` (§4.4.2.7) into quantised integers, window-major.
699 fn spectral_data(
700 &self,
701 r: &mut BitReader<'_>,
702 ics: &IcsInfo,
703 cb: &[Vec<u8>],
704 quant: &mut [i32],
705 ) -> Result<()> {
706 for g in 0..ics.num_groups {
707 let start = ics.group_start(g);
708 for sfb in 0..ics.max_sfb {
709 let book = cb[g][sfb];
710 if !(1..=11).contains(&book) {
711 continue;
712 }
713 let spec = &CODEBOOKS[usize::from(book) - 1];
714 let tree = &self.books.spectral[usize::from(book) - 1];
715 let lo = usize::from(ics.swb[sfb]);
716 let hi = usize::from(ics.swb[sfb + 1]);
717 for w in 0..ics.group_len[g] {
718 let base = if ics.window_sequence.is_short() {
719 (start + w) * SHORT_LEN
720 } else {
721 0
722 };
723 let mut k = lo;
724 while k < hi {
725 let mut values = [0i32; 4];
726 let symbol = tree.decode(r)?;
727 decode_tuple(spec, symbol, &mut values);
728 let dim = usize::from(spec.dim);
729 if spec.unsigned {
730 for v in values.iter_mut().take(dim) {
731 if *v != 0 && r.read_bit()? {
732 *v = -*v;
733 }
734 }
735 }
736 if spec.esc {
737 for v in values.iter_mut().take(dim) {
738 if v.unsigned_abs() == 16 {
739 let mut n = 0u32;
740 while r.read_bit()? {
741 n += 1;
742 if n > 20 {
743 return Err(Error::corrupt("aac: escape too long"));
744 }
745 }
746 let magnitude = (1i32 << (n + 4)) | r.read_bits(n + 4)? as i32;
747 *v = if *v < 0 { -magnitude } else { magnitude };
748 }
749 }
750 }
751 for (i, &v) in values.iter().take(dim).enumerate() {
752 if k + i < hi {
753 quant[base + k + i] = v;
754 }
755 }
756 k += dim;
757 }
758 }
759 }
760 }
761 Ok(())
762 }
763
764 /// One `individual_channel_stream` (§4.4.2.4).
765 fn channel_stream(&mut self, r: &mut BitReader<'_>, shared: Option<&IcsInfo>) -> Result<Ics> {
766 let global_gain = r.read_bits(8)? as u8;
767 let ics = match shared {
768 Some(info) => info.clone(),
769 None => parse_ics_info(r, self.sf_index)?,
770 };
771 let cb = self.section_data(r, &ics)?;
772 let sf = self.scale_factor_data(r, &ics, &cb, global_gain)?;
773 let mut pulse = None;
774 if r.read_bit()? {
775 if ics.window_sequence.is_short() {
776 return Err(Error::corrupt("aac: pulse data on a short window"));
777 }
778 pulse = Some(parse_pulse(r)?);
779 }
780 let tns = if r.read_bit()? {
781 parse_tns(r, &ics)?
782 } else {
783 Tns::default()
784 };
785 if r.read_bit()? {
786 return Err(Error::unsupported("aac", "gain control data: SSR profile"));
787 }
788 let mut quant = vec![0i32; FRAME_LEN];
789 self.spectral_data(r, &ics, &cb, &mut quant)?;
790 if let Some(p) = pulse {
791 apply_pulse(&mut quant, &p, &ics);
792 }
793 Ok(Ics {
794 coef: dequantize(&quant, &ics, &cb, &sf),
795 ics,
796 cb,
797 sf,
798 tns,
799 })
800 }
801
802 /// Runs the stereo tools, TNS and the filterbank over one element's
803 /// channels, appending each channel's PCM to `out`.
804 fn finish(&mut self, chans: &mut [Ics], ms: Option<&MsMask>, out: &mut Vec<Vec<f32>>) {
805 // Noise substitution (§4.6.13) must fill its bands before M/S and
806 // intensity stereo run, so those tools combine the noise-filled
807 // coefficients like any other spectral data rather than the zeroes
808 // `dequantize` left behind for NOISE_HCB bands -- matching the
809 // decode order every reference decoder uses.
810 for ch in chans.iter_mut() {
811 fill_noise(ch, &mut self.noise);
812 }
813 if let ([left, right], Some(mask)) = (&mut *chans, ms) {
814 apply_ms(left, right, mask);
815 }
816 if let [left, right] = &mut *chans {
817 apply_intensity(left, right, ms);
818 }
819 for ch in chans.iter_mut() {
820 let windows = if ch.ics.window_sequence.is_short() {
821 8
822 } else {
823 1
824 };
825 for w in 0..windows {
826 let len = if windows == 8 { SHORT_LEN } else { FRAME_LEN };
827 apply_tns(&mut ch.coef[w * len..(w + 1) * len], &ch.tns, &ch.ics, w);
828 }
829 let mut pcm = vec![0.0f32; FRAME_LEN];
830 let index = out.len();
831 while self.states.len() <= index {
832 self.states.push(ChannelState::default());
833 }
834 self.bank
835 .synthesize(&ch.coef, &ch.ics, &mut self.states[index], &mut pcm);
836 out.push(pcm);
837 }
838 }
839
840 /// Decodes one `raw_data_block`, returning one PCM plane per channel in
841 /// bitstream element order.
842 pub fn raw_data_block(&mut self, r: &mut BitReader<'_>) -> Result<Vec<Vec<f32>>> {
843 let mut out: Vec<Vec<f32>> = Vec::new();
844 // The element (tag, channel range, is_cpe) an immediately following
845 // FIL's SBR payload would apply to, per §4.5.1: a fill_element
846 // directly follows the element it decorates.
847 let mut pending: Option<(u8, usize, usize, bool)> = None;
848 let dump_tools = tool_sideinfo_enabled();
849 let au = if dump_tools {
850 next_tool_sideinfo_au()
851 } else {
852 0
853 };
854 let mut pns = false;
855 // Speaker per plane so far; `named` drops to false at the first element a PCE does not name.
856 let mut speakers: Vec<crate::config::Speaker> = Vec::new();
857 let mut named = self.pce.is_some();
858 loop {
859 if r.bits_remaining() < 3 {
860 break;
861 }
862 let id = r.read_bits(3)?;
863 match id {
864 // SCE and LFE are one channel each; CCE (2) is a coupling
865 // element this profile never emits and cannot be skipped
866 // blind, so it is refused rather than silently mis-parsed.
867 0 | 3 => {
868 let tag = r.read_bits(4)? as u8;
869 let start = out.len();
870 let mut ch = [self.channel_stream(r, None)?];
871 pns |= has_pns(&ch[0]);
872 if dump_tools {
873 log_tool_sideinfo(tool_row(au, tag, false, &ch[0], None));
874 }
875 self.finish(&mut ch, None, &mut out);
876 if let (3, Some(sbr), Some(plane)) = (id, self.sbr.as_mut(), out.get_mut(start)) {
877 sbr.bypass_plane(tag, plane);
878 }
879 named &= self.note_speakers(id, tag, 1, &mut speakers);
880 // §4.6.18.1: SBR is never applied to the LFE channel (no
881 // FIL/SBR payload follows it), so it must not become a
882 // pending SBR target -- otherwise a later fallback
883 // (`apply_last`/no-FIL branch) could mistakenly stretch
884 // the LFE plane to double rate using a *different*
885 // element's held SBR data, corrupting it.
886 pending = if id == 0 {
887 Some((tag, start, 1, false))
888 } else {
889 None
890 };
891 }
892 1 => {
893 let tag = r.read_bits(4)? as u8;
894 let start = out.len();
895 let common = r.read_bit()?;
896 let (shared, mask) = if common {
897 let info = parse_ics_info(r, self.sf_index)?;
898 let present = r.read_bits(2)?;
899 let mask = match present {
900 0 => MsMask::None,
901 1 => {
902 let mut bits = vec![vec![false; info.max_sfb]; info.num_groups];
903 for row in bits.iter_mut() {
904 for b in row.iter_mut() {
905 *b = r.read_bit()?;
906 }
907 }
908 MsMask::Some(bits)
909 }
910 2 => MsMask::All,
911 _ => return Err(Error::corrupt("aac: reserved ms_mask_present")),
912 };
913 (Some(info), mask)
914 } else {
915 (None, MsMask::None)
916 };
917 let mut pair = [
918 self.channel_stream(r, shared.as_ref())?,
919 self.channel_stream(r, shared.as_ref())?,
920 ];
921 pns |= pair.iter().any(has_pns);
922 if dump_tools {
923 log_tool_sideinfo(tool_row(au, tag, true, &pair[0], Some(&mask)));
924 }
925 self.finish(&mut pair, Some(&mask), &mut out);
926 named &= self.note_speakers(1, tag, 2, &mut speakers);
927 pending = Some((tag, start, 2, true));
928 }
929 2 => return Err(Error::unsupported("aac", "coupling channel element")),
930 4 => {
931 let _tag = r.read_bits(4)?;
932 let align = r.read_bit()?;
933 let mut count = r.read_bits(8)? as u64;
934 if count == 255 {
935 count += r.read_bits(8)? as u64;
936 }
937 if align {
938 r.align_to_byte();
939 }
940 r.skip_bits(count * 8)?;
941 pending = None;
942 }
943 5 => {
944 let pce = crate::config::parse_program_config(r)?;
945 self.pce = Some(pce.elements);
946 named = self.pce.is_some();
947 speakers.clear();
948 pending = None;
949 }
950 6 => {
951 let mut count = r.read_bits(4)? as u64;
952 if count == 15 {
953 // 15 + esc - 1, written so an escape of 0 cannot underflow.
954 count = 14 + r.read_bits(8)? as u64;
955 }
956 let end_bit = r.bit_position() + count * 8;
957 // Implicit SBR: no SBR in the config, but this FIL is the first
958 // to carry an SBR extension right after an element. Arm the
959 // chain for it; if its payload does not parse, disarm again.
960 let arming = match self.implicit_core {
961 Some(core)
962 if self.sbr.is_none()
963 && pending.is_some()
964 && r.bits_remaining() >= 4
965 && matches!(r.peek_bits(4)?, 13 | 14) =>
966 {
967 self.sbr = Some(crate::sbr_chain::SbrChain::new(core * 2));
968 true
969 }
970 _ => false,
971 };
972 let mut applied = false;
973 if let (Some(sbr), Some((tag, start, n, is_cpe))) =
974 (self.sbr.as_mut(), pending.take())
975 {
976 // extension_payload(): bs_extension_type(4), then
977 // (for SBR) an optional 10-bit CRC, then
978 // sbr_extension_data() itself.
979 if r.bits_remaining() >= 4 {
980 let ext_type = r.peek_bits(4)?;
981 if ext_type == 13 || ext_type == 14 {
982 r.skip_bits(4)?;
983 if ext_type == 14 && r.bits_remaining() >= 10 {
984 r.skip_bits(10)?; // bs_sbr_crc_bits
985 }
986 if let Some(data) = sbr.parse(r, tag, is_cpe) {
987 if data.ps.is_some() && (arming || self.implicit_on) {
988 self.implicit_ps = true;
989 }
990 sbr.apply_planes(tag, is_cpe, &data, &mut out, start, n)?;
991 applied = true;
992 }
993 }
994 }
995 if !applied && !arming {
996 // No fresh SBR payload this frame (no SBR fill
997 // element, or one whose extension_type wasn't
998 // SBR, or a parse failure): §4.6.18 still
999 // requires doubled-rate reconstruction, using
1000 // the last successfully parsed frame's data.
1001 sbr.apply_last_planes(tag, is_cpe, &mut out, start, n)?;
1002 }
1003 }
1004 if arming {
1005 if applied {
1006 self.implicit_on = true;
1007 self.implicit_core = None;
1008 } else {
1009 // The payload did not parse: this was not SBR after all.
1010 self.sbr = None;
1011 }
1012 }
1013 // Resync to the FIL's declared byte boundary regardless
1014 // of how many bits SBR parsing above actually consumed:
1015 // a parse error or trailing padding must never desync
1016 // the elements that follow.
1017 let now = r.bit_position();
1018 if now < end_bit {
1019 r.skip_bits(end_bit - now)?;
1020 }
1021 pending = None;
1022 }
1023 _ => {
1024 // The block ended with no FIL element ever following the
1025 // last SCE/CPE (no SBR fill at all this frame, not even
1026 // a non-SBR one) -- same "unavailable frame" case as the
1027 // no-fresh-payload branch in id 6 above, so fall back to
1028 // the last known SBR data the same way.
1029 if let (Some(sbr), Some((tag, start, n, is_cpe))) = (self.sbr.as_mut(), pending)
1030 {
1031 sbr.apply_last_planes(tag, is_cpe, &mut out, start, n)?;
1032 }
1033 break;
1034 }
1035 }
1036 }
1037 if pns {
1038 self.pns_aus += 1;
1039 }
1040 self.plane_speakers = (named && speakers.len() == out.len()).then_some(speakers);
1041 r.align_to_byte();
1042 Ok(out)
1043 }
1044
1045 /// Records the speakers of `count` planes that element `(id, tag)` adds. Returns whether
1046 /// the PCE named them, which keeps the block's ordering known.
1047 fn note_speakers(
1048 &self,
1049 id: u32,
1050 tag: u8,
1051 count: usize,
1052 speakers: &mut Vec<crate::config::Speaker>,
1053 ) -> bool {
1054 let kind = match id {
1055 0 => 0,
1056 1 => 1,
1057 _ => 3,
1058 };
1059 match self.pce_speakers(kind, tag) {
1060 Some(named) if named.len() == count => {
1061 speakers.extend_from_slice(named);
1062 true
1063 }
1064 _ => false,
1065 }
1066 }
1067}
1068
1069#[derive(Debug)]
1070enum MsMask {
1071 None,
1072 All,
1073 Some(Vec<Vec<bool>>),
1074}
1075
1076impl MsMask {
1077 fn used(&self, g: usize, sfb: usize) -> bool {
1078 match self {
1079 MsMask::None => false,
1080 MsMask::All => true,
1081 MsMask::Some(bits) => bits[g][sfb],
1082 }
1083 }
1084}
1085
1086/// The symbol index back into its tuple; the index is the tuple read as digits
1087/// in base `lav + 1` (unsigned) or `2 * lav + 1` (signed), first coefficient
1088/// most significant.
1089fn decode_tuple(cb: &crate::tables::Codebook, symbol: usize, out: &mut [i32; 4]) {
1090 let span = if cb.unsigned {
1091 usize::from(cb.lav) + 1
1092 } else {
1093 2 * usize::from(cb.lav) + 1
1094 };
1095 let off = if cb.unsigned { 0 } else { i32::from(cb.lav) };
1096 let dim = usize::from(cb.dim);
1097 let mut rest = symbol;
1098 for i in (0..dim).rev() {
1099 out[i] = (rest % span) as i32 - off;
1100 rest /= span;
1101 }
1102}
1103
1104#[derive(Debug)]
1105struct Pulse {
1106 start_sfb: usize,
1107 offsets: Vec<usize>,
1108 amps: Vec<i32>,
1109}
1110
1111fn parse_pulse(r: &mut BitReader<'_>) -> Result<Pulse> {
1112 let count = r.read_bits(2)? as usize + 1;
1113 let start_sfb = r.read_bits(6)? as usize;
1114 let mut offsets = Vec::with_capacity(count);
1115 let mut amps = Vec::with_capacity(count);
1116 for _ in 0..count {
1117 offsets.push(r.read_bits(5)? as usize);
1118 amps.push(r.read_bits(4)? as i32);
1119 }
1120 Ok(Pulse {
1121 start_sfb,
1122 offsets,
1123 amps,
1124 })
1125}
1126
1127fn apply_pulse(quant: &mut [i32], pulse: &Pulse, ics: &IcsInfo) {
1128 if pulse.start_sfb >= ics.swb.len() {
1129 return;
1130 }
1131 let mut k = usize::from(ics.swb[pulse.start_sfb]);
1132 for (&off, &amp) in pulse.offsets.iter().zip(&pulse.amps) {
1133 k += off;
1134 if k >= quant.len() {
1135 return;
1136 }
1137 // The pulse grows the magnitude, keeping whatever sign the coefficient
1138 // already had (§4.6.3).
1139 quant[k] += if quant[k] < 0 { -amp } else { amp };
1140 }
1141}
1142
1143/// `x^(4/3) * 2^((sf - 100) / 4)` per band (§4.6.2), window-major.
1144fn dequantize(quant: &[i32], ics: &IcsInfo, cb: &[Vec<u8>], sf: &[Vec<i32>]) -> Vec<f32> {
1145 let mut coef = vec![0.0f32; FRAME_LEN];
1146 let short = ics.window_sequence.is_short();
1147 for g in 0..ics.num_groups {
1148 let start = ics.group_start(g);
1149 for sfb in 0..ics.max_sfb {
1150 let book = cb[g][sfb];
1151 if !(1..=11).contains(&book) {
1152 continue;
1153 }
1154 let gain = 2f32.powf((sf[g][sfb] - SF_OFFSET) as f32 * 0.25);
1155 let lo = usize::from(ics.swb[sfb]);
1156 let hi = usize::from(ics.swb[sfb + 1]);
1157 for w in 0..ics.group_len[g] {
1158 let base = if short { (start + w) * SHORT_LEN } else { 0 };
1159 for k in lo..hi {
1160 let q = quant[base + k];
1161 if q != 0 {
1162 let mag = (q.unsigned_abs() as f32).powf(4.0 / 3.0) * gain;
1163 coef[base + k] = if q < 0 { -mag } else { mag };
1164 }
1165 }
1166 }
1167 }
1168 }
1169 coef
1170}
1171
1172/// Mid/side to left/right, for every band the mask marks and no other (§4.6.8.1).
1173fn apply_ms(left: &mut Ics, right: &mut Ics, mask: &MsMask) {
1174 let ics = &left.ics;
1175 let short = ics.window_sequence.is_short();
1176 for g in 0..ics.num_groups {
1177 let start = ics.group_start(g);
1178 for sfb in 0..ics.max_sfb {
1179 if !mask.used(g, sfb) || is_intensity(right.cb[g][sfb]) {
1180 continue;
1181 }
1182 let lo = usize::from(ics.swb[sfb]);
1183 let hi = usize::from(ics.swb[sfb + 1]);
1184 for w in 0..ics.group_len[g] {
1185 let base = if short { (start + w) * SHORT_LEN } else { 0 };
1186 for k in base + lo..base + hi {
1187 let (m, s) = (left.coef[k], right.coef[k]);
1188 left.coef[k] = m + s;
1189 right.coef[k] = m - s;
1190 }
1191 }
1192 }
1193 }
1194}
1195
1196/// Builds one `EC_AAC_TOOL_SIDEINFO_DEBUG` row from an already-decoded `Ics`
1197/// (any channel of a CPE, since PNS/IS/TNS presence is per-channel but the
1198/// dump only needs whether the element used the tool at all).
1199fn has_pns(ch: &Ics) -> bool {
1200 ch.cb
1201 .iter()
1202 .any(|group| group.contains(&NOISE_HCB))
1203}
1204
1205fn tool_row(au: usize, tag: u8, is_cpe: bool, ch: &Ics, mask: Option<&MsMask>) -> ToolSideInfoRow {
1206 let mut ms_bands = 0;
1207 let mut pns_bands = 0;
1208 let mut is_bands = 0;
1209 for g in 0..ch.ics.num_groups {
1210 for sfb in 0..ch.ics.max_sfb {
1211 if mask.is_some_and(|m| m.used(g, sfb)) {
1212 ms_bands += 1;
1213 }
1214 match ch.cb[g][sfb] {
1215 NOISE_HCB => pns_bands += 1,
1216 INTENSITY_HCB | INTENSITY_HCB2 => is_bands += 1,
1217 _ => {}
1218 }
1219 }
1220 }
1221 ToolSideInfoRow {
1222 au,
1223 tag,
1224 is_cpe,
1225 window_sequence: ch.ics.window_sequence,
1226 ms_bands,
1227 pns_bands,
1228 is_bands,
1229 tns_present: !ch.tns.filters.is_empty(),
1230 }
1231}
1232
1233fn is_intensity(cb: u8) -> bool {
1234 cb == INTENSITY_HCB || cb == INTENSITY_HCB2
1235}
1236
1237/// Intensity stereo: the right channel's marked bands are the left channel's,
1238/// scaled by `0.5^(is_position / 4)` and signed by the codebook (§4.6.8.2).
1239fn apply_intensity(left: &mut Ics, right: &mut Ics, ms: Option<&MsMask>) {
1240 let ics = right.ics.clone();
1241 let short = ics.window_sequence.is_short();
1242 for g in 0..ics.num_groups {
1243 let start = ics.group_start(g);
1244 for sfb in 0..ics.max_sfb {
1245 let cb = right.cb[g][sfb];
1246 if !is_intensity(cb) {
1247 continue;
1248 }
1249 let mut sign = if cb == INTENSITY_HCB { 1.0 } else { -1.0 };
1250 if ms.is_some_and(|m| m.used(g, sfb)) {
1251 sign = -sign;
1252 }
1253 let scale = sign * 0.5f32.powf(0.25 * right.sf[g][sfb] as f32);
1254 let lo = usize::from(ics.swb[sfb]);
1255 let hi = usize::from(ics.swb[sfb + 1]);
1256 for w in 0..ics.group_len[g] {
1257 let base = if short { (start + w) * SHORT_LEN } else { 0 };
1258 for k in base + lo..base + hi {
1259 right.coef[k] = left.coef[k] * scale;
1260 }
1261 }
1262 }
1263 }
1264}
1265
1266/// Perceptual noise substitution: the band is filled with noise carrying the
1267/// transmitted energy (§4.6.13). The sequence is free, the energy is not.
1268fn fill_noise(ch: &mut Ics, rng: &mut Noise) {
1269 let ics = ch.ics.clone();
1270 let short = ics.window_sequence.is_short();
1271 for g in 0..ics.num_groups {
1272 let start = ics.group_start(g);
1273 for sfb in 0..ics.max_sfb {
1274 if ch.cb[g][sfb] != NOISE_HCB {
1275 continue;
1276 }
1277 let lo = usize::from(ics.swb[sfb]);
1278 let hi = usize::from(ics.swb[sfb + 1]);
1279 for w in 0..ics.group_len[g] {
1280 let base = if short { (start + w) * SHORT_LEN } else { 0 };
1281 let mut energy = 0.0f32;
1282 for k in base + lo..base + hi {
1283 let v = rng.next();
1284 ch.coef[k] = v;
1285 energy += v * v;
1286 }
1287 if energy <= 0.0 {
1288 continue;
1289 }
1290 let target = 2f32.powf(0.25 * ch.sf[g][sfb] as f32);
1291 let scale = target / energy.sqrt();
1292 for k in base + lo..base + hi {
1293 ch.coef[k] *= scale;
1294 }
1295 }
1296 }
1297 }
1298}