forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

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