forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB978e685Tahinli3 months ago627 commits

decode.rs871 lines, 32.0 KiBHistoryRawDownload
1//! AAC-LC decode assembly: `raw_data_block` → individual channels → spectral
2//! reconstruction → filterbank → PCM (ISO 14496-3 §4.4 / §4.6).
3//!
4//! Supports long (`ONLY_LONG`), transition (`LONG_START`/`LONG_STOP`) and short
5//! (`EIGHT_SHORT`) windows with grouped scalefactors/sections, regular Huffman
6//! codebooks, pulse data and M/S stereo, synthesised via the verified IMDCT +
7//! windowed overlap-add (2048 for long, 8×256 for short). Output is normalised
8//! to float [-1, 1] and is bit-exact against FFmpeg on real AAC-LC files.
9//!
10//! **Tool coverage.** TNS is parsed *and applied* (`parse_tns` → `apply_tns`, on
11//! both the SCE and CPE paths); PNS (`NOISE_HCB`) bands are filled with
12//! energy-scaled noise; intensity stereo is applied via `apply_is`, including
13//! the M/S sign flip. Only `gain_control_data` is rejected as unsupported. This
14//! matters to the encoder campaign: the encoder-side arms for TNS, PNS and
15//! intensity stereo (see `docs/codec-aac-great-gate.md`) can all be gated on
16//! round-trip through this decoder, with no decode work needed first.
17
18use crate::bits::BitReader;
19use crate::codebook::{decode_tuple, CODEBOOKS, INTENSITY_HCB2, NOISE_HCB, ZERO_HCB};
20use crate::dsp;
21use crate::ics::{parse_ics_info, IcsInfo, WindowSequence};
22use crate::swb::swb_offsets;
23use crate::tables::{spectral_book, SCALEFACTOR_BOOK};
24use crate::{DecodedAudio, Error, Result, SAMPLE_RATES};
25
26const FRAME_LEN: usize = 1024;
27const LONG_N: usize = 2048;
28const SHORT_N: usize = 256;
29const SHORT_HALF: usize = 128;
30/// The ISO reconstruction is on a ~16-bit scale; normalise to float [-1, 1]
31/// (verified bit-exact vs FFmpeg).
32const OUTPUT_NORM: f32 = 1.0 / 32768.0;
33
34// raw_data_block element identifiers (id_syn_ele).
35const ID_SCE: u32 = 0;
36const ID_CPE: u32 = 1;
37const ID_CCE: u32 = 2;
38const ID_LFE: u32 = 3;
39const ID_DSE: u32 = 4;
40const ID_PCE: u32 = 5;
41const ID_FIL: u32 = 6;
42const ID_END: u32 = 7;
43
44/// Stateful AAC-LC decoder: holds per-channel overlap memory and the windows.
45pub struct Decoder {
46 sample_rate: u32,
47 fs_index: u8,
48 /// Per-channel overlap-add memory (second half of the previous frame).
49 overlap: Vec<[f32; FRAME_LEN]>,
50 /// Per-channel previous window shape (false = sine, true = KBD).
51 prev_kbd: Vec<bool>,
52 /// Set when a fill_element carried SBR payload (implicit HE-AAC signalling).
53 saw_sbr: bool,
54 /// Per-channel previous window sequence.
55 prev_seq: Vec<WindowSequence>,
56 sine: Vec<f32>,
57 kbd: Vec<f32>,
58 sine_s: Vec<f32>,
59 kbd_s: Vec<f32>,
60 /// Deterministic PRNG state for PNS noise fill.
61 rng: u32,
62}
63
64impl Decoder {
65 pub fn new(sample_rate: u32) -> Decoder {
66 Decoder {
67 sample_rate,
68 fs_index: fs_index_for(sample_rate),
69 overlap: Vec::new(),
70 prev_kbd: Vec::new(),
71 saw_sbr: false,
72 prev_seq: Vec::new(),
73 sine: dsp::sine_window(LONG_N),
74 kbd: dsp::kbd_window(LONG_N, 4.0),
75 sine_s: dsp::sine_window(SHORT_N),
76 kbd_s: dsp::kbd_window(SHORT_N, 6.0),
77 rng: 0x1234_5678,
78 }
79 }
80
81 /// True once a `fill_element` carrying SBR payload has been seen — implicit
82 /// HE-AAC signalling. The core still decodes; the high band does not exist.
83 pub fn saw_sbr(&self) -> bool {
84 self.saw_sbr
85 }
86
87 /// Decode one raw access unit into interleaved-`f32` PCM.
88 pub fn decode(&mut self, au: &[u8], pts: Option<i64>) -> Result<DecodedAudio> {
89 let mut r = BitReader::new(au);
90 let mut outputs: Vec<Vec<f32>> = Vec::new();
91 let mut ch = 0usize;
92
93 loop {
94 if r.bits_left() < 3 {
95 break;
96 }
97 match r.read_bits(3)? {
98 ID_SCE | ID_LFE => {
99 let _tag = r.read_bits(4)?;
100 let mut c = decode_channel(&mut r, self.fs_index, None, &mut self.rng)?;
101 apply_tns(&mut c.spec, &c.tns, &c.info, self.fs_index);
102 outputs.push(self.synthesize(ch, &c.info, &c.spec));
103 ch += 1;
104 }
105 ID_CPE => {
106 let _tag = r.read_bits(4)?;
107 let common = r.read_bool()?;
108 let (info, ms_used) = if common {
109 let info = parse_ics_info(&mut r, self.fs_index)?;
110 let ms = read_ms_used(&mut r, &info)?;
111 (Some(info), ms)
112 } else {
113 (None, Vec::new())
114 };
115 let info_ref = info.as_ref();
116 let mut c0 = decode_channel(&mut r, self.fs_index, info_ref, &mut self.rng)?;
117 let mut c1 = decode_channel(&mut r, self.fs_index, info_ref, &mut self.rng)?;
118 let fs = self.fs_index;
119 // M/S and intensity stereo require a shared window/grouping.
120 if common {
121 apply_ms(&c0.info, &ms_used, fs, &c1.cb, &mut c0.spec, &mut c1.spec);
122 apply_is(
123 &c0.info,
124 &ms_used,
125 fs,
126 &c1.cb,
127 &c1.sf,
128 &c0.spec,
129 &mut c1.spec,
130 );
131 }
132 apply_tns(&mut c0.spec, &c0.tns, &c0.info, fs);
133 apply_tns(&mut c1.spec, &c1.tns, &c1.info, fs);
134 outputs.push(self.synthesize(ch, &c0.info, &c0.spec));
135 outputs.push(self.synthesize(ch + 1, &c1.info, &c1.spec));
136 ch += 2;
137 }
138 ID_FIL => {
139 let mut count = r.read_bits(4)? as usize;
140 if count == 15 {
141 // count = 15 + next8 - 1; group as (count + next8) - 1 so a
142 // zero escape byte can't underflow usize (`0usize - 1` panics).
143 count = count + r.read_bits(8)? as usize - 1;
144 }
145 // Peek the 4-bit extension_type before skipping: SBR payload
146 // here is how *implicit* HE-AAC signalling works, where the
147 // config says nothing but the fill elements carry SBR anyway
148 // (a shape MPEG-TS broadcast really produces). Recording it
149 // lets the caller learn the output rate is doubled instead of
150 // being handed half-speed audio.
151 if count > 0 {
152 let ext = r.read_bits(4)?;
153 if ext == 13 || ext == 14 {
154 self.saw_sbr = true;
155 }
156 r.skip(count * 8 - 4)?;
157 }
158 }
159 ID_DSE => {
160 let _tag = r.read_bits(4)?;
161 let align = r.read_bool()?;
162 let mut count = r.read_bits(8)? as usize;
163 if count == 255 {
164 count += r.read_bits(8)? as usize;
165 }
166 if align {
167 r.byte_align();
168 }
169 r.skip(count * 8)?;
170 }
171 ID_END => break,
172 ID_CCE | ID_PCE => {
173 return Err(Error::unsupported(
174 "aac: coupling / program-config elements not supported",
175 ));
176 }
177 _ => unreachable!(),
178 }
179 }
180
181 if outputs.is_empty() {
182 return Err(Error::invalid("aac: no channel elements in frame"));
183 }
184 Ok(interleave(outputs, self.sample_rate, pts))
185 }
186
187 /// Build the 2048-sample analysis window for a long/transition block: left
188 /// half follows the previous block's shape, right half the current's.
189 fn long_window(&self, seq: WindowSequence, prev_kbd: bool, cur_kbd: bool) -> Vec<f32> {
190 let long_prev = if prev_kbd { &self.kbd } else { &self.sine };
191 let long_cur = if cur_kbd { &self.kbd } else { &self.sine };
192 let short_prev = if prev_kbd { &self.kbd_s } else { &self.sine_s };
193 let short_cur = if cur_kbd { &self.kbd_s } else { &self.sine_s };
194 let mut w = vec![0f32; LONG_N];
195
196 if seq == WindowSequence::LongStop {
197 for n in 0..128 {
198 w[448 + n] = short_prev[n];
199 }
200 for s in w.iter_mut().take(FRAME_LEN).skip(576) {
201 *s = 1.0;
202 }
203 } else {
204 w[..FRAME_LEN].copy_from_slice(&long_prev[..FRAME_LEN]);
205 }
206
207 if seq == WindowSequence::LongStart {
208 for s in w.iter_mut().take(FRAME_LEN + 448).skip(FRAME_LEN) {
209 *s = 1.0;
210 }
211 for n in 0..128 {
212 w[FRAME_LEN + 448 + n] = short_cur[128 + n];
213 }
214 } else {
215 w[FRAME_LEN..].copy_from_slice(&long_cur[FRAME_LEN..]);
216 }
217 w
218 }
219
220 /// Synthesise eight 256-IMDCT short windows into a normalised 2048 frame.
221 fn short_frame(&self, spec: &[f32; FRAME_LEN], cur_kbd: bool) -> Vec<f32> {
222 let sw = if cur_kbd { &self.kbd_s } else { &self.sine_s };
223 let mut frame = vec![0f32; LONG_N];
224 for w in 0..8 {
225 let time = dsp::imdct(&spec[w * SHORT_HALF..(w + 1) * SHORT_HALF]); // 256
226 let off = 448 + w * SHORT_HALF;
227 for n in 0..SHORT_N {
228 frame[off + n] += time[n] * sw[n] * OUTPUT_NORM;
229 }
230 }
231 frame
232 }
233
234 /// IMDCT + window + overlap-add for one channel's spectrum → 1024 samples.
235 fn synthesize(&mut self, ch: usize, info: &IcsInfo, spec: &[f32; FRAME_LEN]) -> Vec<f32> {
236 while self.overlap.len() <= ch {
237 self.overlap.push([0.0; FRAME_LEN]);
238 self.prev_kbd.push(false);
239 self.prev_seq.push(WindowSequence::OnlyLong);
240 }
241
242 let frame = if info.window_sequence == WindowSequence::EightShort {
243 self.short_frame(spec, info.window_shape_kbd)
244 } else {
245 let time = dsp::imdct(spec); // 2048
246 let win = self.long_window(
247 info.window_sequence,
248 self.prev_kbd[ch],
249 info.window_shape_kbd,
250 );
251 (0..LONG_N)
252 .map(|n| time[n] * win[n] * OUTPUT_NORM)
253 .collect()
254 };
255
256 let mut out = vec![0.0f32; FRAME_LEN];
257 for n in 0..FRAME_LEN {
258 out[n] = frame[n] + self.overlap[ch][n];
259 }
260 for n in 0..FRAME_LEN {
261 self.overlap[ch][n] = frame[FRAME_LEN + n];
262 }
263 self.prev_kbd[ch] = info.window_shape_kbd;
264 self.prev_seq[ch] = info.window_sequence;
265 out
266 }
267}
268
269/// Decode one `individual_channel_stream` to a dequantized spectrum. For short
270/// blocks the layout is window-major (eight 128-bin windows).
271struct Channel {
272 info: IcsInfo,
273 spec: [f32; FRAME_LEN],
274 cb: Vec<Vec<u8>>,
275 sf: Vec<Vec<i32>>,
276 tns: Tns,
277}
278
279fn decode_channel(
280 r: &mut BitReader,
281 fs_index: u8,
282 common_info: Option<&IcsInfo>,
283 rng: &mut u32,
284) -> Result<Channel> {
285 let global_gain = r.read_bits(8)? as i32;
286 let info = match common_info {
287 Some(i) => i.clone(),
288 None => parse_ics_info(r, fs_index)?,
289 };
290
291 let is_short = info.window_sequence == WindowSequence::EightShort;
292 let swb = swb_offsets(!is_short, fs_index);
293 let max_sfb = info.max_sfb as usize;
294 if max_sfb + 1 > swb.len() {
295 return Err(Error::invalid("aac: max_sfb out of range"));
296 }
297 let window_len = if is_short { SHORT_HALF } else { FRAME_LEN };
298
299 let sfb_cb = read_sections(r, info.num_window_groups, max_sfb, is_short)?;
300 let sf = read_scalefactors(r, &sfb_cb, global_gain)?;
301
302 let pulse = if r.read_bool()? {
303 Some(read_pulse(r)?)
304 } else {
305 None
306 };
307 let tns = if r.read_bool()? {
308 parse_tns(r, &info)?
309 } else {
310 Tns::default()
311 };
312 if r.read_bool()? {
313 return Err(Error::unsupported("aac: gain control not supported"));
314 }
315
316 let mut quant = [0i32; FRAME_LEN];
317 read_spectrum(r, &sfb_cb, &info, swb, window_len, &mut quant)?;
318 if let (Some(p), false) = (&pulse, is_short) {
319 apply_pulse(&mut quant, p, swb);
320 }
321
322 // Inverse quantization, per group/window with the group's band scalefactor.
323 // PNS (NOISE_HCB) bands are filled with energy-scaled random noise instead.
324 let mut spec = [0f32; FRAME_LEN];
325 let mut wbase = 0usize;
326 for (g, group) in sfb_cb.iter().enumerate() {
327 for (sfb, &cb) in group.iter().enumerate() {
328 if cb == ZERO_HCB {
329 continue;
330 }
331 if sfb + 1 >= swb.len() {
332 break; // malformed: more coded bands than the swb offset table holds
333 }
334 let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
335 for w in 0..info.window_group_length[g] as usize {
336 let base = (wbase + w) * window_len;
337 if cb == NOISE_HCB {
338 fill_noise(rng, &mut spec, base + s, base + e, sf[g][sfb]);
339 } else {
340 let gain = dsp::sf_gain(sf[g][sfb]);
341 for i in s..e {
342 spec[base + i] = dsp::dequant(quant[base + i]) * gain;
343 }
344 }
345 }
346 }
347 wbase += info.window_group_length[g] as usize;
348 }
349 Ok(Channel {
350 info,
351 spec,
352 cb: sfb_cb,
353 sf,
354 tns,
355 })
356}
357
358/// section_data: a codebook number per scalefactor band, per group.
359fn read_sections(
360 r: &mut BitReader,
361 groups: usize,
362 max_sfb: usize,
363 is_short: bool,
364) -> Result<Vec<Vec<u8>>> {
365 let bits = if is_short { 3 } else { 5 };
366 let esc = (1u32 << bits) - 1;
367 let mut out = Vec::with_capacity(groups);
368 for _ in 0..groups {
369 let mut cbs = vec![0u8; max_sfb];
370 let mut k = 0usize;
371 while k < max_sfb {
372 let cb = r.read_bits(4)? as u8;
373 let mut len = 0usize;
374 loop {
375 let incr = r.read_bits(bits)? as usize;
376 len += incr;
377 if incr as u32 != esc {
378 break;
379 }
380 }
381 if k + len > max_sfb {
382 return Err(Error::invalid("aac: section overruns max_sfb"));
383 }
384 for c in cbs.iter_mut().skip(k).take(len) {
385 *c = cb;
386 }
387 k += len;
388 }
389 out.push(cbs);
390 }
391 Ok(out)
392}
393
394/// scale_factor_data: differentially-coded scalefactors (regular codebooks).
395fn read_scalefactors(
396 r: &mut BitReader,
397 sfb_cb: &[Vec<u8>],
398 global_gain: i32,
399) -> Result<Vec<Vec<i32>>> {
400 let mut acc = global_gain;
401 let mut noise = global_gain - 90; // PNS noise-energy accumulator
402 let mut noise_pcm = true;
403 let mut is_pos = 0i32; // intensity-stereo position accumulator
404 let mut out = Vec::with_capacity(sfb_cb.len());
405 for group in sfb_cb {
406 let mut sf = vec![0i32; group.len()];
407 for (sfb, &cb) in group.iter().enumerate() {
408 if cb == ZERO_HCB {
409 continue;
410 } else if cb >= INTENSITY_HCB2 {
411 is_pos += SCALEFACTOR_BOOK.decode(r)? as i32 - 60;
412 sf[sfb] = is_pos;
413 } else if cb == NOISE_HCB {
414 // PNS: first noise energy is a 9-bit PCM delta, rest are Huffman.
415 if noise_pcm {
416 noise_pcm = false;
417 noise += r.read_bits(9)? as i32 - 256;
418 } else {
419 noise += SCALEFACTOR_BOOK.decode(r)? as i32 - 60;
420 }
421 sf[sfb] = noise;
422 } else {
423 acc += SCALEFACTOR_BOOK.decode(r)? as i32 - 60;
424 sf[sfb] = acc;
425 }
426 }
427 out.push(sf);
428 }
429 Ok(out)
430}
431
432/// spectral_data: Huffman-decode quantized coefficients per group/band/window.
433fn read_spectrum(
434 r: &mut BitReader,
435 sfb_cb: &[Vec<u8>],
436 info: &IcsInfo,
437 swb: &[u16],
438 window_len: usize,
439 quant: &mut [i32; FRAME_LEN],
440) -> Result<()> {
441 let mut wbase = 0usize;
442 for (g, group) in sfb_cb.iter().enumerate() {
443 for (sfb, &cb) in group.iter().enumerate() {
444 // ZERO, NOISE (PNS) and intensity bands carry no spectral data.
445 if cb == ZERO_HCB || cb == NOISE_HCB || cb >= INTENSITY_HCB2 {
446 continue;
447 }
448 // Skip books that carry no spectral data or are out of range: the
449 // filter above misses INTENSITY_HCB (14) and reserved (12), which
450 // would index CODEBOOKS out of bounds on malformed (or intensity)
451 // input. `.get` skips them (intensity is applied later in apply_is).
452 let Some(meta) = CODEBOOKS.get(cb as usize) else {
453 continue;
454 };
455 let book = spectral_book(cb);
456 let dim = meta.dim as usize;
457 if sfb + 1 >= swb.len() {
458 break; // malformed: more coded bands than the swb offset table holds
459 }
460 let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
461 for w in 0..info.window_group_length[g] as usize {
462 let base = (wbase + w) * window_len;
463 let mut i = s;
464 let mut tuple = [0i32; 4];
465 while i + dim <= e {
466 decode_tuple(meta, book, r, &mut tuple)?;
467 quant[base + i..base + i + dim].copy_from_slice(&tuple[..dim]);
468 i += dim;
469 }
470 }
471 }
472 wbase += info.window_group_length[g] as usize;
473 }
474 Ok(())
475}
476
477/// xorshift32 → uniform f32 in [-1, 1). Decoder-local; PNS noise is random by
478/// design, so it is energy-matched (not sample-exact) across decoders.
479fn next_rand(s: &mut u32) -> f32 {
480 *s ^= *s << 13;
481 *s ^= *s >> 17;
482 *s ^= *s << 5;
483 (*s as f32 / u32::MAX as f32) * 2.0 - 1.0
484}
485
486/// Fill `spec[start..end]` with random noise whose spectral energy matches the
487/// transmitted `noise_energy` (ISO 14496-3 §4.6.13): unit-energy random vector
488/// scaled so band energy = 2^(noise_energy/2).
489fn fill_noise(rng: &mut u32, spec: &mut [f32], start: usize, end: usize, noise_energy: i32) {
490 let mut energy = 0f64;
491 for i in start..end {
492 let v = next_rand(rng);
493 spec[i] = v;
494 energy += (v as f64) * (v as f64);
495 }
496 if energy <= 0.0 {
497 return;
498 }
499 let scale = (2f64.powf(0.25 * noise_energy as f64) / energy.sqrt()) as f32;
500 for v in spec[start..end].iter_mut() {
501 *v *= scale;
502 }
503}
504
505struct Pulse {
506 start_sfb: usize,
507 offsets: Vec<u32>,
508 amps: Vec<u32>,
509}
510
511fn read_pulse(r: &mut BitReader) -> Result<Pulse> {
512 let n = r.read_bits(2)? as usize; // number_pulse - 1
513 let start_sfb = r.read_bits(6)? as usize;
514 let mut offsets = Vec::with_capacity(n + 1);
515 let mut amps = Vec::with_capacity(n + 1);
516 for _ in 0..=n {
517 offsets.push(r.read_bits(5)?);
518 amps.push(r.read_bits(4)?);
519 }
520 Ok(Pulse {
521 start_sfb,
522 offsets,
523 amps,
524 })
525}
526
527fn apply_pulse(quant: &mut [i32; FRAME_LEN], p: &Pulse, swb: &[u16]) {
528 let mut k = *swb.get(p.start_sfb).unwrap_or(&0) as usize;
529 for (off, amp) in p.offsets.iter().zip(&p.amps) {
530 k += *off as usize;
531 if k < FRAME_LEN {
532 if quant[k] > 0 {
533 quant[k] += *amp as i32;
534 } else {
535 quant[k] -= *amp as i32;
536 }
537 }
538 }
539}
540
541/// One TNS noise-shaping filter (a span of bands + its LPC synthesis filter).
542struct TnsFilter {
543 length: usize, // span in scalefactor bands (from the top down)
544 order: usize,
545 direction: bool, // true = downward (high→low) filtering
546 lpc: Vec<f32>, // lpc[0]=1, lpc[1..=order]
547}
548
549/// TNS data for a channel: filters per window.
550#[derive(Default)]
551struct Tns {
552 windows: Vec<Vec<TnsFilter>>,
553}
554
555/// Max TNS-affected band per sampling-frequency index (ISO Table 4.A.45/46).
556pub(crate) const TNS_MAX_LONG: [u8; 13] = [31, 31, 34, 40, 42, 51, 46, 46, 42, 42, 42, 39, 39];
557pub(crate) const TNS_MAX_SHORT: [u8; 13] = [9, 9, 10, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14];
558
559/// Parse TNS, dequantizing PARCOR coefficients and converting them to LPC.
560fn parse_tns(r: &mut BitReader, info: &IcsInfo) -> Result<Tns> {
561 use std::f32::consts::PI;
562 let short = info.window_sequence == WindowSequence::EightShort;
563 let (nf_bits, len_bits, ord_bits) = if short { (1, 4, 3) } else { (2, 6, 5) };
564 let mut windows = Vec::with_capacity(info.num_windows);
565 for _ in 0..info.num_windows {
566 let mut filters = Vec::new();
567 let n_filt = r.read_bits(nf_bits)?;
568 let coef_res = if n_filt > 0 { r.read_bits(1)? } else { 0 };
569 for _ in 0..n_filt {
570 let length = r.read_bits(len_bits)? as usize;
571 let order = r.read_bits(ord_bits)? as usize;
572 let (mut direction, mut lpc) = (false, Vec::new());
573 if order > 0 {
574 direction = r.read_bool()?;
575 let coef_compress = r.read_bits(1)?;
576 let res_bits = 3 + coef_res; // 3 or 4
577 let coef_bits = res_bits - coef_compress;
578 let iqfac = ((1i32 << (res_bits - 1)) as f32 - 0.5) / (PI / 2.0);
579 let iqfac_m = ((1i32 << (res_bits - 1)) as f32 + 0.5) / (PI / 2.0);
580 let mut parcor = vec![0f32; order];
581 for p in parcor.iter_mut() {
582 let raw = r.read_bits(coef_bits)? as i32;
583 let c = if raw & (1 << (coef_bits - 1)) != 0 {
584 raw - (1 << coef_bits)
585 } else {
586 raw
587 };
588 let t = if c >= 0 {
589 c as f32 / iqfac
590 } else {
591 c as f32 / iqfac_m
592 };
593 *p = t.sin();
594 }
595 lpc = parcor_to_lpc(&parcor);
596 }
597 filters.push(TnsFilter {
598 length,
599 order,
600 direction,
601 lpc,
602 });
603 }
604 windows.push(filters);
605 }
606 Ok(Tns { windows })
607}
608
609/// PARCOR (reflection) → LPC coefficients via the step-up recursion.
610fn parcor_to_lpc(parcor: &[f32]) -> Vec<f32> {
611 let order = parcor.len();
612 let mut lpc = vec![0f32; order + 1];
613 lpc[0] = 1.0;
614 for m in 1..=order {
615 let mut tmp = lpc.clone();
616 for i in 1..m {
617 tmp[i] = lpc[i] + parcor[m - 1] * lpc[m - i];
618 }
619 lpc[..m].copy_from_slice(&tmp[..m]);
620 lpc[m] = parcor[m - 1];
621 }
622 lpc
623}
624
625/// Apply TNS: an all-pole (synthesis) filter over each filter's band span,
626/// per window, in the coded direction (ISO 14496-3 §4.6.9.3).
627fn apply_tns(spec: &mut [f32; FRAME_LEN], tns: &Tns, info: &IcsInfo, fs_index: u8) {
628 if tns.windows.iter().all(|w| w.is_empty()) {
629 return;
630 }
631 let short = info.window_sequence == WindowSequence::EightShort;
632 let swb = swb_offsets(!short, fs_index);
633 let window_len = if short { SHORT_HALF } else { FRAME_LEN };
634 let tns_max = if short {
635 TNS_MAX_SHORT[fs_index as usize]
636 } else {
637 TNS_MAX_LONG[fs_index as usize]
638 } as usize;
639 let mmm = tns_max.min(info.max_sfb as usize);
640
641 for (w, filters) in tns.windows.iter().enumerate() {
642 let mut bottom = info.num_swb;
643 for f in filters {
644 let top = bottom;
645 bottom = top.saturating_sub(f.length);
646 if f.order == 0 {
647 continue;
648 }
649 let start = swb[bottom.min(mmm)] as usize;
650 let end = swb[top.min(mmm)] as usize;
651 if end <= start {
652 continue;
653 }
654 let size = end - start;
655 let base = w * window_len;
656 let (mut idx, inc): (isize, isize) = if f.direction {
657 ((base + end - 1) as isize, -1)
658 } else {
659 ((base + start) as isize, 1)
660 };
661 let mut state = vec![0f32; f.order];
662 for _ in 0..size {
663 let p = idx as usize;
664 let mut y = spec[p];
665 for j in 0..f.order {
666 y -= state[j] * f.lpc[j + 1];
667 }
668 for j in (1..f.order).rev() {
669 state[j] = state[j - 1];
670 }
671 state[0] = y;
672 spec[p] = y;
673 idx += inc;
674 }
675 }
676 }
677}
678
679/// M/S stereo flags (`num_window_groups × max_sfb`) for a common-window CPE.
680fn read_ms_used(r: &mut BitReader, info: &IcsInfo) -> Result<Vec<bool>> {
681 let n = info.num_window_groups * info.max_sfb as usize;
682 match r.read_bits(2)? {
683 0 => Ok(vec![false; n]),
684 2 => Ok(vec![true; n]),
685 1 => {
686 let mut v = vec![false; n];
687 for slot in v.iter_mut() {
688 *slot = r.read_bool()?;
689 }
690 Ok(v)
691 }
692 _ => Err(Error::unsupported("aac: reserved ms_mask_present")),
693 }
694}
695
696/// Reconstruct L/R from Mid/Side on the flagged bands (group/window aware).
697/// Intensity-coded bands of the right channel are excluded (handled by IS).
698fn apply_ms(
699 info: &IcsInfo,
700 ms_used: &[bool],
701 fs_index: u8,
702 cb1: &[Vec<u8>],
703 s0: &mut [f32; FRAME_LEN],
704 s1: &mut [f32; FRAME_LEN],
705) {
706 if ms_used.is_empty() {
707 return;
708 }
709 let is_short = info.window_sequence == WindowSequence::EightShort;
710 let swb = swb_offsets(!is_short, fs_index);
711 let window_len = if is_short { SHORT_HALF } else { FRAME_LEN };
712 let max_sfb = info.max_sfb as usize;
713 let mut wbase = 0usize;
714 for g in 0..info.num_window_groups {
715 for sfb in 0..max_sfb {
716 if ms_used[g * max_sfb + sfb] && cb1[g][sfb] < INTENSITY_HCB2 {
717 if sfb + 1 >= swb.len() {
718 break; // malformed: more coded bands than the swb offset table holds
719 }
720 let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
721 for w in 0..info.window_group_length[g] as usize {
722 let base = (wbase + w) * window_len;
723 for i in s..e {
724 let (mid, side) = (s0[base + i], s1[base + i]);
725 s0[base + i] = mid + side;
726 s1[base + i] = mid - side;
727 }
728 }
729 }
730 }
731 wbase += info.window_group_length[g] as usize;
732 }
733}
734
735/// Intensity stereo (ISO 14496-3 §4.6.8.2.3): the right channel's IS bands are
736/// `± 2^(-is_position/4)` times the left channel. Sign is negative for
737/// INTENSITY_HCB2, and flipped again when the band is M/S-flagged.
738fn apply_is(
739 info: &IcsInfo,
740 ms_used: &[bool],
741 fs_index: u8,
742 cb1: &[Vec<u8>],
743 sf1: &[Vec<i32>],
744 s0: &[f32; FRAME_LEN],
745 s1: &mut [f32; FRAME_LEN],
746) {
747 let is_short = info.window_sequence == WindowSequence::EightShort;
748 let swb = swb_offsets(!is_short, fs_index);
749 let window_len = if is_short { SHORT_HALF } else { FRAME_LEN };
750 let max_sfb = info.max_sfb as usize;
751 let mut wbase = 0usize;
752 for g in 0..info.num_window_groups {
753 for sfb in 0..max_sfb {
754 let cb = cb1[g][sfb];
755 if cb >= INTENSITY_HCB2 {
756 let mut scale = 0.5f32.powf(0.25 * sf1[g][sfb] as f32);
757 if cb == INTENSITY_HCB2 {
758 scale = -scale; // out of phase
759 }
760 if !ms_used.is_empty() && ms_used[g * max_sfb + sfb] {
761 scale = -scale; // M/S flips intensity sign
762 }
763 if sfb + 1 >= swb.len() {
764 break; // malformed: more coded bands than the swb offset table holds
765 }
766 let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
767 for w in 0..info.window_group_length[g] as usize {
768 let base = (wbase + w) * window_len;
769 for i in s..e {
770 s1[base + i] = scale * s0[base + i];
771 }
772 }
773 }
774 }
775 wbase += info.window_group_length[g] as usize;
776 }
777}
778
779/// Interleave decoded channels, **reordering AAC element order into the standard
780/// interleave order** the rest of the workspace uses (FL, FR, FC, LFE, BL, BR).
781///
782/// AAC carries 5.1 as `C, L, R, Ls, Rs, LFE`; every WAV writer and filter here
783/// expects `L, R, C, LFE, Ls, Rs`. Emitting element order straight out would put
784/// the centre channel in the left speaker. Mono and stereo are identity, so this
785/// changes nothing for the overwhelmingly common cases.
786fn interleave(outputs: Vec<Vec<f32>>, sample_rate: u32, pts: Option<i64>) -> DecodedAudio {
787 let nch = outputs.len();
788 let order = crate::encode::aac_to_interleave_order(nch);
789 let mut samples = Vec::with_capacity(FRAME_LEN * nch);
790 for n in 0..FRAME_LEN {
791 match &order {
792 Some(map) => {
793 for &src in map {
794 samples.push(outputs[src][n]);
795 }
796 }
797 // No defined layout (a PCE stream, once supported): pass elements
798 // through in stream order rather than guessing.
799 None => {
800 for ch in &outputs {
801 samples.push(ch[n]);
802 }
803 }
804 }
805 }
806 DecodedAudio {
807 sample_rate,
808 channels: nch as u16,
809 samples,
810 pts,
811 }
812}
813
814fn fs_index_for(rate: u32) -> u8 {
815 SAMPLE_RATES
816 .iter()
817 .position(|&r| r == rate)
818 .map(|i| i as u8)
819 .unwrap_or(3) // default 48 kHz layout
820}
821
822#[cfg(test)]
823mod tests {
824 use super::*;
825
826 #[test]
827 fn section_and_scalefactors_parse() {
828 // One group, one cb=1 section of length 2 (long, 5-bit length).
829 // bits: cb(0001) len_incr(00010) → 0001_0001 0... = 0x11 0x00
830 let mut r = BitReader::new(&[0x11, 0x00]);
831 let cb = read_sections(&mut r, 1, 2, false).unwrap();
832 assert_eq!(cb, vec![vec![1, 1]]);
833 }
834
835 #[test]
836 fn scalefactors_accumulate_from_global_gain() {
837 // Two regular bands; SF deltas both index 60 ("0" = delta 0) → both
838 // equal global_gain. Two "0" bits → 0x00.
839 let sfb_cb = vec![vec![1u8, 1u8]];
840 let mut r = BitReader::new(&[0x00]);
841 let sf = read_scalefactors(&mut r, &sfb_cb, 100).unwrap();
842 assert_eq!(sf, vec![vec![100, 100]]);
843 }
844
845 /// End-to-end: a hand-built ONLY_LONG SCE frame, one cb1 codeword giving a
846 /// single non-zero coefficient. Decoded PCM must equal the IMDCT of that
847 /// spectrum, windowed and normalised — using the verified DSP as oracle.
848 #[test]
849 fn hand_built_frame_matches_independent_imdct() {
850 let au = [0x00, 0xC8, 0x00, 0x84, 0x21, 0x1E];
851 let mut dec = Decoder::new(48_000);
852 let af = dec.decode(&au, Some(0)).unwrap();
853 assert_eq!(af.channels, 1);
854 assert_eq!(af.frames(), FRAME_LEN);
855 let got: Vec<f32> = af.samples;
856
857 let mut spec = [0f32; FRAME_LEN];
858 spec[0] = -1.0;
859 let time = dsp::imdct(&spec);
860 let win = dsp::sine_window(LONG_N);
861 for n in 0..FRAME_LEN {
862 let expected = time[n] * win[n] / 32768.0;
863 assert!(
864 (got[n] - expected).abs() < 1e-4,
865 "sample {n}: got {} want {}",
866 got[n],
867 expected
868 );
869 }
870 }
871}