rusty_aac 2.2.0

Pure-Rust AAC decoder (LC, Main, LTP, HE-AAC v1/v2 SBR+PS, ER LD/ELD; sample-exact vs FFmpeg on the ISO conformance suite) and AAC-LC encoder (~5x faster than FFmpeg's native encoder, PEAQ-measured). No C/FFI. ADTS/MP4/LATM-LOAS, 7.1 + PCE layouts.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
//! One `individual_channel_stream` (ISO 14496-3 §4.4.2.7): `ics_info` (with Main
//! prediction / LTP side info and SSR gain control), section data,
//! scalefactors, pulse data, TNS, spectral data — and its dequantisation,
//! including PNS noise from the reference decoder's generator so noise bands are
//! sample-identical across decoders rather than merely energy-equal.

// Untrusted input: narrowing casts are lint-enforced here (H-17).
#![warn(
    clippy::cast_possible_truncation,
    clippy::cast_sign_loss,
    clippy::cast_possible_wrap
)]

use crate::bits::BitReader;
use crate::codebook::{CODEBOOKS, INTENSITY_HCB, INTENSITY_HCB2, NOISE_HCB, ZERO_HCB};
use crate::config::aot;
use crate::ics::{IcsInfo, WindowSequence};
use crate::swb::swb_offsets;
use crate::tables::SCALEFACTOR_BOOK;
use crate::tables_ext::{
    AAC_PRED_SFB_MAX, SWB_OFFSET_120, SWB_OFFSET_480, SWB_OFFSET_512, SWB_OFFSET_960,
    TNS_MAX_BANDS_480, TNS_MAX_BANDS_512,
};
use crate::{Error, Result};

/// Max TNS-affected band per sampling-frequency index (ISO Table 4.A.45/46).
pub const TNS_MAX_LONG: [u8; 13] = [31, 31, 34, 40, 42, 51, 46, 46, 42, 42, 42, 39, 39];
pub const TNS_MAX_SHORT: [u8; 13] = [9, 9, 10, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14];

pub const MAX_LTP_LONG_SFB: usize = 40;
pub const MAX_PREDICTORS: usize = 672;

/// What the stream is, as far as one channel's syntax is concerned.
#[derive(Clone, Copy)]
pub struct Syntax {
    pub aot: u8,
    pub sf_index: u8,
    /// 1024 / 960 / 512 / 480.
    pub frame_len: usize,
}

impl Syntax {
    pub fn eld(&self) -> bool {
        self.aot == aot::ER_AAC_ELD
    }
    pub fn er(&self) -> bool {
        matches!(
            self.aot,
            aot::ER_AAC_LC | aot::ER_AAC_LTP | aot::ER_AAC_LD | aot::ER_AAC_ELD
        )
    }
    pub fn low_delay(&self) -> bool {
        matches!(self.aot, aot::ER_AAC_LD | aot::ER_AAC_ELD)
    }
    fn long_swb(&self) -> Result<&'static [u16]> {
        let i = self.sf_index as usize;
        let t = match (self.low_delay(), self.frame_len) {
            (true, 480) => SWB_OFFSET_480[i],
            (true, _) => SWB_OFFSET_512[i],
            (false, 960) => SWB_OFFSET_960[i],
            (false, _) => Some(swb_offsets(true, self.sf_index)),
        };
        t.ok_or_else(|| {
            Error::unsupported("aac: no scalefactor-band table for this low-delay rate")
        })
    }
    fn short_swb(&self) -> &'static [u16] {
        if self.frame_len == 960 {
            SWB_OFFSET_120[self.sf_index as usize]
                .unwrap_or_else(|| swb_offsets(false, self.sf_index))
        } else {
            swb_offsets(false, self.sf_index)
        }
    }
}

#[derive(Clone, Copy)]
pub struct Ltp {
    pub present: bool,
    pub lag: usize,
    pub coef: f32,
    pub used: [bool; MAX_LTP_LONG_SFB],
}

impl Default for Ltp {
    fn default() -> Self {
        Self {
            present: false,
            lag: 0,
            coef: 0.0,
            used: [false; MAX_LTP_LONG_SFB],
        }
    }
}

/// Persistent + per-frame ICS state (FFmpeg's `IndividualChannelStream`).
#[derive(Clone)]
pub struct Ics {
    pub info: IcsInfo,
    pub prev_seq: WindowSequence,
    pub prev_kbd: bool,
    pub swb: &'static [u16],
    pub tns_max_bands: u8,
    pub predictor_present: bool,
    pub predictor_reset_group: u8,
    pub prediction_used: [bool; 41],
    pub ltp: Ltp,
}

impl Default for Ics {
    fn default() -> Self {
        Self {
            info: IcsInfo {
                window_sequence: WindowSequence::OnlyLong,
                window_shape_kbd: false,
                max_sfb: 0,
                num_windows: 1,
                num_window_groups: 1,
                window_group_length: vec![1],
                num_swb: 0,
            },
            prev_seq: WindowSequence::OnlyLong,
            prev_kbd: false,
            swb: &[0],
            tns_max_bands: 0,
            predictor_present: false,
            predictor_reset_group: 0,
            prediction_used: [false; 41],
            ltp: Ltp::default(),
        }
    }
}

fn seq_from_bits(v: u32) -> WindowSequence {
    match v {
        0 => WindowSequence::OnlyLong,
        1 => WindowSequence::LongStart,
        2 => WindowSequence::EightShort,
        _ => WindowSequence::LongStop,
    }
}

pub fn decode_ltp(r: &mut BitReader, ltp: &mut Ltp, max_sfb: usize) -> Result<()> {
    ltp.lag = r.read_bits(11)? as usize;
    ltp.coef = crate::tables_ext::LTP_COEF[r.read_bits(3)? as usize];
    for sfb in 0..max_sfb.min(MAX_LTP_LONG_SFB) {
        ltp.used[sfb] = r.read_bool()?;
    }
    Ok(())
}

/// `ics_info()` — updates the window history exactly as the reference does.
pub fn parse_ics_info(r: &mut BitReader, sx: &Syntax, ics: &mut Ics) -> Result<()> {
    if !sx.eld() {
        let _reserved = r.read_bit()?;
        ics.prev_seq = ics.info.window_sequence;
        ics.info.window_sequence = seq_from_bits(r.read_bits(2)?);
        if sx.aot == aot::ER_AAC_LD && ics.info.window_sequence != WindowSequence::OnlyLong {
            ics.info.window_sequence = WindowSequence::OnlyLong;
            return Err(Error::invalid(
                "aac: AAC-LD is only defined for ONLY_LONG_SEQUENCE",
            ));
        }
        ics.prev_kbd = ics.info.window_shape_kbd;
        ics.info.window_shape_kbd = r.read_bool()?;
    }
    // The grouping is rebuilt in the Vec the ICS already owns (capacity <= 8
    // after the first short block): a fresh `vec!` per channel per frame was
    // an allocation plus a free.
    ics.info.num_window_groups = 1;
    let groups = &mut ics.info.window_group_length;
    groups.clear();
    groups.push(1);
    ics.predictor_present = false;
    if ics.info.window_sequence == WindowSequence::EightShort {
        ics.info.max_sfb = r.read_u8(4)?;
        let groups = &mut ics.info.window_group_length;
        for _ in 0..7 {
            if r.read_bool()? {
                // Cannot fail: `groups` was given its first entry just above.
                *groups.last_mut().unwrap() += 1;
            } else {
                groups.push(1);
            }
        }
        ics.info.num_window_groups = ics.info.window_group_length.len();
        ics.info.num_windows = 8;
        ics.swb = sx.short_swb();
        ics.tns_max_bands = TNS_MAX_SHORT[sx.sf_index as usize];
    } else {
        ics.info.max_sfb = r.read_u8(6)?;
        ics.info.num_windows = 1;
        ics.swb = sx.long_swb()?;
        let i = sx.sf_index as usize;
        ics.tns_max_bands = match (sx.low_delay(), sx.frame_len) {
            (true, 480) => TNS_MAX_BANDS_480[i],
            (true, _) => TNS_MAX_BANDS_512[i],
            _ => TNS_MAX_LONG[i],
        };
        if !sx.eld() {
            ics.predictor_present = r.read_bool()?;
            ics.predictor_reset_group = 0;
        }
        if ics.predictor_present {
            if sx.aot == aot::AAC_MAIN {
                if r.read_bool()? {
                    ics.predictor_reset_group = r.read_u8(5)?;
                    if ics.predictor_reset_group == 0 || ics.predictor_reset_group > 30 {
                        return Err(Error::invalid("aac: invalid predictor reset group"));
                    }
                }
                let n = (ics.info.max_sfb as usize).min(AAC_PRED_SFB_MAX[i] as usize);
                for sfb in 0..n {
                    ics.prediction_used[sfb] = r.read_bool()?;
                }
            } else if sx.aot == aot::AAC_LC || sx.aot == aot::ER_AAC_LC {
                return Err(Error::invalid("aac: prediction is not allowed in AAC-LC"));
            } else {
                if sx.aot == aot::ER_AAC_LD {
                    return Err(Error::unsupported("aac: LTP in ER AAC-LD is not supported"));
                }
                ics.ltp.present = r.read_bool()?;
                if ics.ltp.present {
                    let m = ics.info.max_sfb as usize;
                    decode_ltp(r, &mut ics.ltp, m)?;
                }
            }
        }
    }
    ics.info.num_swb = ics.swb.len() - 1;
    if ics.info.max_sfb as usize > ics.info.num_swb {
        ics.info.max_sfb = 0;
        return Err(Error::invalid(
            "aac: max_sfb exceeds the number of scalefactor bands",
        ));
    }
    Ok(())
}

/// Dequantised TNS reflection coefficients `sin(c / iqfac)` (ISO 14496-3
/// §4.6.9.3), indexed by the raw two's-complement code, for
/// [`coef_compress·2` + `coef_res`]: 3-bit, 4-bit, compressed 3-bit, compressed
/// 4-bit. These are the 8-digit values the reference decoders tabulate (not
/// correctly-rounded sines): matching them keeps the recursive TNS filter
/// sample-exact.
const TNS_PARCOR: [&[f32]; 4] = [
    &[
        0.0,
        0.43388373,
        0.78183150,
        0.97492790,
        -0.98480773,
        -0.86602539,
        -0.64278758,
        -0.34202015,
    ],
    &[
        0.0,
        0.20791170,
        0.40673664,
        0.58778524,
        0.74314481,
        0.86602539,
        0.95105654,
        0.99452192,
        -0.99573416,
        -0.96182561,
        -0.89516330,
        -0.79801720,
        -0.67369562,
        -0.52643216,
        -0.36124167,
        -0.18374951,
    ],
    &[0.0, 0.43388373, -0.64278758, -0.34202015],
    &[
        0.0,
        0.20791170,
        0.40673664,
        0.58778524,
        -0.67369562,
        -0.52643216,
        -0.36124167,
        -0.18374951,
    ],
];

/// One TNS filter: band span, order, direction, LPC (lpc[0] = 1).
#[derive(Clone, Default)]
pub struct TnsFilter {
    pub length: usize,
    pub order: usize,
    pub direction: bool,
    pub lpc: Vec<f32>,
}

#[derive(Clone, Default)]
pub struct Tns {
    pub present: bool,
    pub windows: Vec<Vec<TnsFilter>>,
}

fn parcor_to_lpc(parcor: &[f32]) -> Vec<f32> {
    let order = parcor.len();
    let mut lpc = vec![0f32; order + 1];
    lpc[0] = 1.0;
    for m in 1..=order {
        let mut tmp = lpc.clone();
        for i in 1..m {
            tmp[i] = lpc[i] + parcor[m - 1] * lpc[m - i];
        }
        lpc[..m].copy_from_slice(&tmp[..m]);
        lpc[m] = parcor[m - 1];
    }
    lpc
}

pub fn parse_tns(r: &mut BitReader, sx: &Syntax, info: &IcsInfo) -> Result<Tns> {
    let short = info.window_sequence == WindowSequence::EightShort;
    let max_order = if short {
        7
    } else if sx.aot == aot::AAC_MAIN {
        20
    } else {
        12
    };
    let (nf_bits, len_bits, ord_bits) = if short { (1, 4, 3) } else { (2, 6, 5) };
    let mut windows = Vec::with_capacity(info.num_windows);
    for _ in 0..info.num_windows {
        let mut filters = Vec::new();
        let n_filt = r.read_bits(nf_bits)?;
        let coef_res = if n_filt > 0 { r.read_bits(1)? } else { 0 };
        for _ in 0..n_filt {
            let length = r.read_bits(len_bits)? as usize;
            let order = r.read_bits(ord_bits)? as usize;
            if order > max_order {
                return Err(Error::invalid("aac: TNS filter order too large"));
            }
            let (mut direction, mut lpc) = (false, Vec::new());
            if order > 0 {
                direction = r.read_bool()?;
                let coef_compress = r.read_bits(1)?;
                let res_bits = 3 + coef_res;
                let coef_bits = res_bits - coef_compress;
                let table = TNS_PARCOR[2 * coef_compress as usize + coef_res as usize];
                let mut parcor = vec![0f32; order];
                for p in &mut parcor {
                    *p = table[r.read_bits(coef_bits)? as usize];
                }
                lpc = parcor_to_lpc(&parcor);
            }
            filters.push(TnsFilter {
                length,
                order,
                direction,
                lpc,
            });
        }
        windows.push(filters);
    }
    Ok(Tns {
        present: true,
        windows,
    })
}

/// SSR `gain_control_data` — parsed and discarded (the reference decoders do the
/// same: the SSR filterbank is not implemented anywhere in practice).
fn skip_gain_control(r: &mut BitReader, seq: WindowSequence) -> Result<()> {
    let mode: [(usize, bool, u32); 4] = [(1, false, 5), (2, true, 2), (8, false, 2), (2, true, 5)];
    let (wd_num, wd_test, aloc) = mode[seq as usize];
    let max_band = r.read_bits(2)?;
    for _ in 0..max_band {
        for wd in 0..wd_num {
            let adjust_num = r.read_bits(3)?;
            for _ in 0..adjust_num {
                r.skip(4 + if wd == 0 && wd_test { 4 } else { aloc as usize })?;
            }
        }
    }
    Ok(())
}

/// Decoded channel payload (FFmpeg's `SingleChannelElement`, per-frame part).
#[derive(Clone)]
pub struct ChannelData {
    pub band_type: [u8; 128],
    /// Regular: scalefactor offset; intensity: position; noise: energy (each
    /// range-checked by `decode_ics`).
    pub sfo: [i32; 128],
    pub tns: Tns,
    /// Spectral coefficients, windows at a stride of 128.
    pub coeffs: Vec<f32>,
    /// Quantized-integer scratch, reused across frames. Never needs clearing:
    /// the dequantiser reads exactly the bands the spectral decode wrote.
    pub quant: Vec<i32>,
}

impl Default for ChannelData {
    fn default() -> Self {
        Self {
            band_type: [0; 128],
            sfo: [0; 128],
            tns: Tns::default(),
            coeffs: vec![0.0; 1024],
            quant: vec![0; 1024],
        }
    }
}

/// `lcg_random`, the reference decoder's PNS generator.
#[inline]
pub fn lcg_random(prev: u32) -> u32 {
    prev.wrapping_mul(1664525).wrapping_add(1013904223)
}

struct Pulse {
    pos: [usize; 4],
    amp: [i32; 4],
    n: usize,
}

/// `individual_channel_stream()` from `global_gain` to dequantised spectrum.
pub fn decode_ics(
    r: &mut BitReader,
    sx: &Syntax,
    ics: &mut Ics,
    cd: &mut ChannelData,
    common_window: bool,
    rng: &mut u32,
) -> Result<()> {
    let prof_ics = crate::prof::scope(crate::prof::Stage::DecIcs);
    let global_gain = r.read_i32(8)?;
    if !common_window {
        parse_ics_info(r, sx, ics)?;
    }
    let info = &ics.info;
    let max_sfb = info.max_sfb as usize;
    let short = info.window_sequence == WindowSequence::EightShort;

    // section_data
    let bits = if short { 3 } else { 5 };
    let esc = (1u32 << bits) - 1;
    cd.band_type = [0; 128];
    for g in 0..info.num_window_groups {
        let mut k = 0usize;
        while k < max_sfb {
            let cb = r.read_u8(4)?;
            if cb == 12 {
                return Err(Error::invalid("aac: invalid band type 12"));
            }
            let mut end = k;
            loop {
                let incr = r.read_bits(bits)?;
                end += incr as usize;
                if end > max_sfb {
                    return Err(Error::invalid("aac: section overruns max_sfb"));
                }
                if incr != esc {
                    break;
                }
            }
            for b in k..end {
                cd.band_type[g * max_sfb + b] = cb;
            }
            k = end;
        }
    }

    // scale_factor_data
    let (mut off0, mut off1, mut off2) = (global_gain, global_gain - 90, 0i32);
    let mut noise_flag = true;
    for g in 0..info.num_window_groups {
        for sfb in 0..max_sfb {
            let idx = g * max_sfb + sfb;
            match cd.band_type[idx] {
                ZERO_HCB => cd.sfo[idx] = 0,
                INTENSITY_HCB | INTENSITY_HCB2 => {
                    off2 += i32::from(SCALEFACTOR_BOOK.decode(r)?) - 60;
                    // Intensity positions and noise energies share the
                    // regular scalefactor's dynamic range (0..=255 there, so
                    // a gain of 2^(-100/4)..2^(155/4)). FFmpeg clips values
                    // outside it and reports the case as unimplemented; only
                    // a damaged frame reaches it, and a clipped noise band at
                    // 2^(155/4) decodes ~10^4 over full scale. Refuse the
                    // frame instead, like an out-of-range scalefactor.
                    if !(-155..=100).contains(&off2) {
                        return Err(Error::invalid("aac: intensity position out of range"));
                    }
                    cd.sfo[idx] = off2;
                }
                NOISE_HCB => {
                    if noise_flag {
                        noise_flag = false;
                        off1 += r.read_i32(9)? - 256;
                    } else {
                        off1 += i32::from(SCALEFACTOR_BOOK.decode(r)?) - 60;
                    }
                    if !(-100..=155).contains(&off1) {
                        return Err(Error::invalid("aac: noise energy out of range"));
                    }
                    cd.sfo[idx] = off1;
                }
                _ => {
                    off0 += i32::from(SCALEFACTOR_BOOK.decode(r)?) - 60;
                    if !(0..=255).contains(&off0) {
                        return Err(Error::invalid("aac: scalefactor out of range"));
                    }
                    cd.sfo[idx] = off0;
                }
            }
        }
    }

    // pulse / tns / gain control
    let mut pulse = None;
    cd.tns = Tns::default();
    if !sx.eld() && r.read_bool()? {
        if short {
            return Err(Error::invalid(
                "aac: pulse tool not allowed in eight short sequence",
            ));
        }
        let n = r.read_bits(2)? as usize + 1;
        let start = r.read_bits(6)? as usize;
        if start >= info.num_swb {
            return Err(Error::invalid("aac: pulse data corrupt"));
        }
        let limit = ics.swb[info.num_swb] as usize;
        let mut p = Pulse {
            pos: [0; 4],
            amp: [0; 4],
            n,
        };
        p.pos[0] = ics.swb[start] as usize + r.read_bits(5)? as usize;
        if p.pos[0] >= limit {
            return Err(Error::invalid("aac: pulse data corrupt"));
        }
        p.amp[0] = r.read_i32(4)?;
        for i in 1..n {
            p.pos[i] = r.read_bits(5)? as usize + p.pos[i - 1];
            if p.pos[i] >= limit {
                return Err(Error::invalid("aac: pulse data corrupt"));
            }
            p.amp[i] = r.read_i32(4)?;
        }
        pulse = Some(p);
    }
    let tns_present = r.read_bool()?;
    if tns_present && !sx.er() {
        cd.tns = parse_tns(r, sx, info)?;
    }
    if !sx.eld() && r.read_bool()? {
        skip_gain_control(r, info.window_sequence)?;
    }
    if tns_present && sx.er() {
        cd.tns = parse_tns(r, sx, info)?;
    }

    // spectral_data (integers first, so pulses stay exact)
    drop(prof_ics); // the stages must not nest, or shares double-count
    let prof_spec = crate::prof::scope(crate::prof::Stage::DecSpectral);
    crate::prof::bump(crate::prof::Counter::ChannelFrames, 1);
    crate::prof::bump(crate::prof::Counter::ShortFrames, usize::from(short));
    crate::prof::bump(
        crate::prof::Counter::TnsChannels,
        usize::from(cd.tns.present),
    );
    let swb = ics.swb;
    // Taken for the call (a failed frame just reallocates it next time).
    let mut quant = std::mem::take(&mut cd.quant);
    quant.resize(1024, 0);
    // Without pulses (which edit the integers before dequantisation) a coded
    // band is dequantised as it is decoded, straight into the coefficients:
    // the same `dequant_with(q) * gain` on the same integers, minus a pass over
    // the integer scratch. `fused[idx]` marks the bands done that way.
    let fuse = pulse.is_none();
    let mut fused = [false; 128];
    let pow43 = crate::dsp::pow43_table();
    let small = super::spectral::SmallPow43::get();
    let mut wbase = 0usize;
    for g in 0..info.num_window_groups {
        let glen = info.window_group_length[g] as usize;
        for sfb in 0..max_sfb {
            let cb = cd.band_type[g * max_sfb + sfb];
            if cb == ZERO_HCB || cb == NOISE_HCB || cb >= INTENSITY_HCB2 {
                continue;
            }
            let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
            let meta = CODEBOOKS
                .get(cb as usize)
                .ok_or_else(|| Error::invalid("aac: bad spectral codebook"))?;
            let fb = super::spectral::fast_book(cb);
            let dim = meta.dim as usize;
            crate::prof::bump(crate::prof::Counter::Codewords, glen * (e - s) / dim);
            crate::prof::bump(crate::prof::Counter::CodedCoeffs, glen * (e - s));
            // Whole tuples only (band widths are multiples of 4 in every table).
            let n = (e - s) / dim * dim;
            if fuse && n == e - s {
                let idx = g * max_sfb + sfb;
                fused[idx] = true;
                let gain = crate::dsp::sf_gain(cd.sfo[idx]);
                for w in 0..glen {
                    let base = (wbase + w) * 128;
                    let out = &mut cd.coeffs[base + s..base + e];
                    if dim == 4 {
                        super::spectral::decode_run_dequant::<4>(
                            cb, fb, r, out, gain, small, pow43,
                        )?;
                    } else {
                        super::spectral::decode_run_dequant::<2>(
                            cb, fb, r, out, gain, small, pow43,
                        )?;
                    }
                }
                continue;
            }
            for w in 0..glen {
                let base = (wbase + w) * 128;
                let out = &mut quant[base + s..base + s + n];
                if dim == 4 {
                    super::spectral::decode_run::<4>(cb, fb, r, out)?;
                } else {
                    super::spectral::decode_run::<2>(cb, fb, r, out)?;
                }
            }
        }
        wbase += glen;
    }

    // Pulses add to single long-window coefficients of regular bands, away from 0.
    if let Some(p) = pulse {
        let mut band = 0usize;
        for i in 0..p.n {
            let k = p.pos[i];
            while swb[band + 1] as usize <= k {
                band += 1;
            }
            let bt = cd.band_type[band];
            if bt == ZERO_HCB || bt == NOISE_HCB || bt >= INTENSITY_HCB2 {
                continue;
            }
            if quant[k] > 0 {
                quant[k] += p.amp[i];
            } else {
                quant[k] -= p.amp[i];
            }
        }
    }

    // Dequantisation; PNS bands from the reference generator.
    drop(prof_spec); // the stages must not nest, or shares double-count
    let _prof = crate::prof::scope(crate::prof::Stage::DecDequant);
    // Every coefficient gets exactly one write: coded bands are dequantised or
    // noise-filled below, and only the uncoded spans - zero / intensity bands
    // and each window's tail above swb[max_sfb] - are zeroed. (Zeroing all
    // 1024 first, then overwriting the coded bands, was a 4 KB memset per
    // channel per frame.)
    let win_len = if info.num_windows == 8 {
        128
    } else {
        cd.coeffs.len()
    };
    let top = swb[max_sfb] as usize;
    let mut wbase = 0usize;
    for g in 0..info.num_window_groups {
        let glen = info.window_group_length[g] as usize;
        for w in 0..glen {
            let base = (wbase + w) * 128;
            cd.coeffs[base + top..base + win_len].fill(0.0);
        }
        for sfb in 0..max_sfb {
            let idx = g * max_sfb + sfb;
            let cb = cd.band_type[idx];
            if cb == ZERO_HCB || cb >= INTENSITY_HCB2 {
                let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
                crate::prof::bump(crate::prof::Counter::ZeroCoeffs, glen * (e - s));
                for w in 0..glen {
                    let base = (wbase + w) * 128;
                    cd.coeffs[base + s..base + e].fill(0.0);
                }
                continue;
            }
            let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
            if cb == NOISE_HCB {
                crate::prof::bump(crate::prof::Counter::PnsCoeffs, glen * (e - s));
                let g_amp = 2f32.powf(0.25 * cd.sfo[idx] as f32);
                for w in 0..glen {
                    let base = (wbase + w) * 128;
                    let band = &mut cd.coeffs[base + s..base + e];
                    for v in band.iter_mut() {
                        *rng = lcg_random(*rng);
                        #[allow(
                            clippy::cast_possible_wrap,
                            reason = "the reference generator reinterprets its u32 state as signed"
                        )]
                        let signed = *rng as i32;
                        *v = signed as f32;
                    }
                    let energy: f32 = band.iter().map(|v| v * v).sum();
                    let scale = g_amp / energy.sqrt();
                    for v in band.iter_mut() {
                        *v *= scale;
                    }
                }
                continue;
            }
            if fused[idx] {
                continue;
            }
            let gain = crate::dsp::sf_gain(cd.sfo[idx]);
            for w in 0..glen {
                let base = (wbase + w) * 128;
                let (out, q) = (
                    &mut cd.coeffs[base + s..base + e],
                    &quant[base + s..base + e],
                );
                for (c, &q) in out.iter_mut().zip(q) {
                    *c = crate::dsp::dequant_with(pow43, q) * gain;
                }
            }
        }
        wbase += glen;
    }
    cd.quant = quant;
    Ok(())
}

#[cfg(test)]
mod tests {
    use crate::encode::BitWriter;
    use crate::tables::SCALEFACTOR_BOOK;
    use crate::{AacDecoder, AudioSpecificConfig, Error};

    fn decoder(channels: u16) -> AacDecoder {
        AacDecoder::with_config(AudioSpecificConfig {
            object_type: 2,
            sample_rate: 44_100,
            channels,
        })
    }

    fn sf_delta(w: &mut BitWriter, delta: i32) {
        let (code, len) = SCALEFACTOR_BOOK.code(usize::try_from(delta + 60).unwrap());
        w.write(code, u32::from(len));
    }

    /// `ics_info` for one long window, `max_sfb` bands, no prediction.
    fn ics_info(w: &mut BitWriter, max_sfb: u32) {
        w.write(0, 1); // ics_reserved_bit
        w.write(0, 2); // ONLY_LONG_SEQUENCE
        w.write(0, 1); // window_shape
        w.write(max_sfb, 6);
        w.write(0, 1); // predictor_data_present
    }

    /// One section of `cb` over `n` bands (long window: 5-bit lengths).
    fn section(w: &mut BitWriter, cb: u32, n: u32) {
        w.write(cb, 4);
        w.write(n, 5);
    }

    fn no_tools(w: &mut BitWriter) {
        w.write(0, 1); // pulse_data_present
        w.write(0, 1); // tns_data_present
        w.write(0, 1); // gain_control_data_present
    }

    /// A mono access unit: one SCE whose bands are all PNS. The first noise
    /// energy is the 9-bit PCM value `first9` (offset `- 256` from
    /// `global_gain - 90`), the rest are Huffman deltas.
    fn sce_noise(global_gain: u32, first9: u32, deltas: &[i32]) -> Vec<u8> {
        let n = 1 + u32::try_from(deltas.len()).unwrap();
        let mut w = BitWriter::new();
        w.write(0, 3); // ID_SCE
        w.write(0, 4);
        w.write(global_gain, 8);
        ics_info(&mut w, n);
        section(&mut w, 13, n); // NOISE_HCB
        w.write(first9, 9);
        for &d in deltas {
            sf_delta(&mut w, d);
        }
        no_tools(&mut w);
        w.write(7, 3); // ID_END
        w.into_bytes()
    }

    /// A stereo access unit: a common-window CPE, channel 0 silent and every
    /// band of channel 1 intensity-coded with the given position deltas.
    fn cpe_intensity(deltas: &[i32]) -> Vec<u8> {
        let n = u32::try_from(deltas.len()).unwrap();
        let mut w = BitWriter::new();
        w.write(1, 3); // ID_CPE
        w.write(0, 4);
        w.write(1, 1); // common_window
        ics_info(&mut w, n);
        w.write(0, 2); // ms_mask_present
        w.write(100, 8); // channel 0: global_gain
        section(&mut w, 0, n); // ZERO_HCB
        no_tools(&mut w);
        w.write(100, 8); // channel 1: global_gain
        section(&mut w, 15, n); // INTENSITY_HCB
        for &d in deltas {
            sf_delta(&mut w, d);
        }
        no_tools(&mut w);
        w.write(7, 3); // ID_END
        w.into_bytes()
    }

    fn peak(samples: &[f32]) -> f32 {
        samples.iter().fold(0f32, |m, &x| m.max(x.abs()))
    }

    /// The mechanism behind a damaged `corrupt_pce_6_1.aac`: one flipped bit sends a
    /// PNS energy to 254/255, which used to be clipped to 155 and decoded at
    /// 3.99e4 x full scale (FFmpeg 8.0.1 does the same on that packet).
    #[test]
    fn noise_energy_outside_window_refuses_the_frame() {
        let mut dec = decoder(1);
        // global_gain 100: energies start at 10.
        let ok = dec.decode(&sce_noise(100, 256 + 10, &[]), None).unwrap();
        assert!(
            peak(&ok.samples) <= 1.0,
            "valid PNS frame peaks at {}",
            peak(&ok.samples)
        );
        // The window's edges still decode (bit-identical to before)...
        dec.decode(&sce_noise(100, 256 + 145, &[]), None).unwrap();
        dec.decode(&sce_noise(0, 256 - 10, &[]), None).unwrap();
        // ...one step past either edge is refused, by the PCM start or a delta.
        for au in [
            sce_noise(100, 256 + 146, &[]),
            sce_noise(100, 511, &[]),
            sce_noise(0, 256 - 11, &[]),
            sce_noise(100, 256 + 100, &[46]),
            sce_noise(100, 256 + 145, &[1]),
        ] {
            let err = decoder(1).decode(&au, None).unwrap_err();
            assert!(matches!(err, Error::InvalidData(_)), "{err:?}");
        }
        // A refused frame leaves the decoder usable.
        assert!(dec.decode(&sce_noise(100, 511, &[]), None).is_err());
        let next = dec.decode(&sce_noise(100, 256 + 10, &[]), None).unwrap();
        assert!(peak(&next.samples) <= 1.0);
    }

    #[test]
    fn intensity_position_outside_window_refuses_the_frame() {
        decoder(2).decode(&cpe_intensity(&[60, 40]), None).unwrap();
        decoder(2)
            .decode(&cpe_intensity(&[-60, -60, -35]), None)
            .unwrap();
        for au in [cpe_intensity(&[60, 41]), cpe_intensity(&[-60, -60, -36])] {
            let err = decoder(2).decode(&au, None).unwrap_err();
            assert!(matches!(err, Error::InvalidData(_)), "{err:?}");
        }
    }
}