Skip to main content

rusty_aac/
encode.rs

1//! In-house **AAC-LC encoder** (see `docs/finished/codec-aac-encoder.md` for the brick
2//! ledger). Bricks 1–7 are complete: encode-side primitives inverting the decoder
3//! (bit writer, spectral-codebook encoder, header/config serializers), the forward
4//! filterbank, the quantizer + rate loop, a Bark-spreading psychoacoustic model,
5//! block switching, M/S stereo, and container/CLI integration.
6//!
7//! **What this encoder does NOT yet do** — the arms tracked by
8//! `docs/finished/codec-aac-great-gate.md`. Naming them here keeps a fit from being run
9//! against a mis-documented encoder:
10//!
11//! * The psy model drives **long blocks only**; short blocks code with flat
12//!   scalefactors and a single window group (arm A1).
13//! * The signal-to-mask ratio is a **constant 18 dB** — no tonality/SFM term
14//!   (arm A2), and no absolute threshold of hearing, so nothing here is a
15//!   function of absolute level (arm A4).
16//! * **TNS, PNS and intensity stereo are never emitted** (arms A3/A6/A7), though
17//!   `crate::decode` implements all three.
18//! * The rate loop searches **one global base offset** against a **constant
19//!   per-frame budget** — there is no outer per-band distortion loop (arm A12)
20//!   and no bit reservoir or VBR mode (arm A5).
21//! * Window shape is hardcoded sine (arm A8) and the transient detector uses an
22//!   absolute energy ratio (arm A9).
23
24use crate::codebook::{Codebook, CODEBOOKS, INTENSITY_HCB, INTENSITY_HCB2, NOISE_HCB};
25use crate::ics::{IcsInfo, WindowSequence};
26use crate::prof::{self, Kernel, Stage};
27use crate::swb::swb_offsets;
28use crate::tables::spectral_book;
29use crate::{AdtsHeader, AudioSpecificConfig, Error, Result};
30use std::collections::{HashMap, VecDeque};
31use std::sync::{Arc, Mutex, OnceLock};
32
33// ---------------------------------------------------------------------------
34// Bit writer — MSB-first, the mirror of the decoder's `BitReader`.
35// ---------------------------------------------------------------------------
36///
37/// Bits gather in a 64-bit accumulator and leave it 32 at a time, so a write is
38/// a shift, an or and (every fourth byte) one 4-byte store, not a loop over its
39/// bits: the per-bit writer it replaced, with its bit-by-bit `append`, was 6% of
40/// encoding.
41pub struct BitWriter {
42    buf: Vec<u8>,
43    /// The pending bits, in the low `nbits` bits (higher bits are stale).
44    acc: u64,
45    /// Pending bit count, always below 32 between calls.
46    nbits: u32,
47}
48
49impl BitWriter {
50    #[must_use]
51    pub fn new() -> Self {
52        Self {
53            buf: Vec::new(),
54            acc: 0,
55            nbits: 0,
56        }
57    }
58
59    /// Append the low `n` bits of `val` (`n <= 32`), most-significant bit first.
60    #[inline]
61    pub fn write(&mut self, val: u32, n: u32) {
62        debug_assert!(n <= 32, "BitWriter::write takes at most 32 bits");
63        let mask = (1u64 << n) - 1;
64        // `nbits < 32` and `n <= 32`, so the pending bits still fit in 64.
65        self.acc = (self.acc << n) | (u64::from(val) & mask);
66        self.nbits += n;
67        if self.nbits >= 32 {
68            self.nbits -= 32;
69            self.buf
70                .extend_from_slice(&((self.acc >> self.nbits) as u32).to_be_bytes());
71        }
72    }
73
74    #[inline]
75    pub fn write_bool(&mut self, b: bool) {
76        self.write(u32::from(b), 1);
77    }
78
79    /// Append everything `other` holds, bit for bit.
80    pub fn append(&mut self, other: &Self) {
81        if self.nbits == 0 {
82            self.buf.extend_from_slice(&other.buf);
83        } else {
84            let mut words = other.buf.chunks_exact(4);
85            for w in &mut words {
86                self.write(u32::from_be_bytes([w[0], w[1], w[2], w[3]]), 32);
87            }
88            for &byte in words.remainder() {
89                self.write(u32::from(byte), 8);
90            }
91        }
92        self.write(other.acc as u32, other.nbits);
93    }
94
95    /// Total bits written so far.
96    #[must_use]
97    pub fn bit_len(&self) -> usize {
98        self.buf.len() * 8 + self.nbits as usize
99    }
100
101    /// Pad to a byte boundary with zero bits and return the bytes.
102    #[must_use]
103    pub fn into_bytes(mut self) -> Vec<u8> {
104        let mut n = self.nbits;
105        while n >= 8 {
106            n -= 8;
107            self.buf.push((self.acc >> n) as u8);
108        }
109        if n != 0 {
110            self.buf.push((self.acc << (8 - n)) as u8);
111        }
112        self.buf
113    }
114}
115
116impl Default for BitWriter {
117    fn default() -> Self {
118        Self::new()
119    }
120}
121
122// ---------------------------------------------------------------------------
123// Spectral codebook encoding — the inverse of `codebook::apply_index`.
124// ---------------------------------------------------------------------------
125
126/// Pack a `dim`-tuple of quantized coefficients into codebook `cb`'s base-`modulo`
127/// Huffman index, or None if the tuple isn't representable by that codebook.
128#[allow(
129    clippy::trivially_copy_pass_by_ref,
130    reason = "measured: passing the 4-byte Codebook by value cost +0.7% encode / +1.4% decode instructions in the inlined hot loops"
131)]
132fn tuple_index(cb: &Codebook, tuple: &[i32]) -> Option<u32> {
133    let dim = cb.dim as usize;
134    let lav = u32::from(cb.lav);
135    let modulo = if cb.unsigned { lav + 1 } else { 2 * lav + 1 };
136    let mut index = 0u32;
137    for &c in &tuple[..dim] {
138        let mag = c.unsigned_abs();
139        let digit = if cb.unsigned {
140            if cb.esc {
141                mag.min(lav) // book 11: a magnitude ≥ lav clamps to lav and escapes
142            } else if mag <= lav {
143                mag
144            } else {
145                return None;
146            }
147        } else if mag <= lav {
148            (c + lav as i32) as u32
149        } else {
150            return None;
151        };
152        index = index * modulo + digit;
153    }
154    Some(index)
155}
156
157/// Bits to code `tuple` with codebook `cb_num`, or None if unrepresentable.
158#[must_use]
159pub fn spectral_bits(cb_num: usize, tuple: &[i32]) -> Option<usize> {
160    let cb = &CODEBOOKS[cb_num];
161    let idx = tuple_index(cb, tuple)?;
162    let (_, len) = spectral_book(cb_num as u8).code(idx as usize);
163    let dim = cb.dim as usize;
164    let mut bits = len as usize;
165    if cb.unsigned {
166        bits += tuple[..dim].iter().filter(|&&c| c != 0).count(); // one sign bit each
167    }
168    if cb.esc {
169        for &c in &tuple[..dim] {
170            if c.unsigned_abs() >= u32::from(cb.lav) {
171                bits += escape_bits(c.unsigned_abs());
172            }
173        }
174    }
175    Some(bits)
176}
177
178/// Emit `tuple` with codebook `cb_num`: codeword, then sign bits (unsigned books),
179/// then escape sequences (book 11). Caller ensures `spectral_bits` is Some.
180///
181/// # Panics
182///
183/// If `cb_num` is not a spectral codebook or `tuple` is not representable in it
184/// (the caller's contract).
185pub fn spectral_emit(cb_num: usize, tuple: &[i32], w: &mut BitWriter) {
186    let cb = &CODEBOOKS[cb_num];
187    let dim = cb.dim as usize;
188    let idx = tuple_index(cb, tuple).expect("representable tuple");
189    let (code, len) = spectral_book(cb_num as u8).code(idx as usize);
190    w.write(code, u32::from(len));
191    if cb.unsigned {
192        for &c in &tuple[..dim] {
193            if c != 0 {
194                w.write_bool(c < 0);
195            }
196        }
197    }
198    if cb.esc {
199        for &c in &tuple[..dim] {
200            if c.unsigned_abs() >= u32::from(cb.lav) {
201                emit_escape(c.unsigned_abs(), w);
202            }
203        }
204    }
205}
206
207/// Escape length for magnitude `m` (≥ 16): `2N+5` bits, `2^(N+4) ≤ m < 2^(N+5)`.
208fn escape_bits(m: u32) -> usize {
209    let n = m.ilog2() - 4;
210    2 * n as usize + 5
211}
212
213/// Escape sequence (ISO §4.6.3.3): N leading 1-bits, a 0, then N+4 bits of
214/// `m - 2^(N+4)`.
215fn emit_escape(m: u32, w: &mut BitWriter) {
216    let n = m.ilog2() - 4;
217    for _ in 0..n {
218        w.write_bool(true);
219    }
220    w.write_bool(false);
221    let bits = n + 4;
222    w.write(m - (1 << bits), bits);
223}
224
225// ---------------------------------------------------------------------------
226// Header / config serializers — inverses of the decoder's parsers.
227// ---------------------------------------------------------------------------
228
229/// The `AudioSpecificConfig` bytes for an AAC-LC stream — the MP4 `esds`
230/// `DecoderSpecificInfo` the muxer needs (2 bytes for standard rates).
231#[must_use]
232pub fn audio_specific_config_bytes(sample_rate: u32, channels: u16) -> Vec<u8> {
233    write_audio_specific_config(&AudioSpecificConfig {
234        object_type: 2, // AAC-LC
235        sample_rate,
236        channels,
237    })
238}
239
240/// Serialize an `AudioSpecificConfig` (ISO §1.6.2.1) — the `esds`/`stsd` config
241/// bytes the MP4 muxer needs. Inverse of `parse_audio_specific_config`.
242#[must_use]
243pub fn write_audio_specific_config(cfg: &AudioSpecificConfig) -> Vec<u8> {
244    let mut w = BitWriter::new();
245    if cfg.object_type >= 31 {
246        w.write(31, 5);
247        w.write(u32::from(cfg.object_type - 32), 6);
248    } else {
249        w.write(u32::from(cfg.object_type), 5);
250    }
251    if let Some(i) = crate::sf_index_for_rate(cfg.sample_rate) {
252        w.write(u32::from(i), 4);
253    } else {
254        w.write(0x0F, 4);
255        w.write(cfg.sample_rate, 24);
256    }
257    w.write(u32::from(cfg.channels), 4);
258    w.into_bytes()
259}
260
261/// Serialize a 7-byte ADTS frame header (no CRC) — inverse of `parse_adts`.
262/// `hdr.frame_length` must include this 7-byte header.
263///
264/// # Panics
265///
266/// If `hdr.sample_rate` is not one of the thirteen standard AAC rates.
267#[must_use]
268pub fn write_adts_header(hdr: &AdtsHeader) -> Vec<u8> {
269    let sf = crate::sf_index_for_rate(hdr.sample_rate).expect("standard rate for ADTS");
270    let mut w = BitWriter::new();
271    w.write(0xFFF, 12); // syncword
272    w.write(0, 1); // MPEG-4
273    w.write(0, 2); // layer (00)
274    w.write_bool(true); // protection_absent → 7-byte header, no CRC
275    w.write(u32::from(hdr.object_type - 1), 2); // profile
276    w.write(u32::from(sf), 4);
277    w.write(0, 1); // private
278    w.write(u32::from(hdr.channels), 3); // channel config
279    w.write(0, 4); // orig/home/copyright id+start
280    w.write(hdr.frame_length as u32, 13);
281    w.write(0x7FF, 11); // buffer fullness (VBR marker)
282    w.write(0, 2); // num_raw_data_blocks - 1
283    w.into_bytes()
284}
285
286/// Serialize `ics_info` for AAC-LC — inverse of `parse_ics_info`.
287pub fn encode_ics_info(w: &mut BitWriter, info: &IcsInfo) {
288    w.write(0, 1); // ics_reserved
289    w.write(info.window_sequence.to_bits(), 2);
290    w.write_bool(info.window_shape_kbd);
291    if info.window_sequence.is_short() {
292        w.write(u32::from(info.max_sfb), 4);
293        w.write(grouping_bits(&info.window_group_length), 7);
294    } else {
295        w.write(u32::from(info.max_sfb), 6);
296        w.write(0, 1); // predictor_data_present (AAC-LC = 0)
297    }
298}
299
300/// The 7 `scale_factor_grouping` bits from window-group lengths (inverse of the
301/// parser's grouping walk): the bit for window i+1 is 1 if it continues the
302/// current group, 0 if it starts a new one.
303fn grouping_bits(group_lengths: &[u8]) -> u32 {
304    let mut is_start = [false; 8];
305    let mut w = 0usize;
306    for &len in group_lengths {
307        if w < 8 {
308            is_start[w] = true;
309        }
310        w += len as usize;
311    }
312    let mut sfg = 0u32;
313    for i in 0..7 {
314        if !is_start[i + 1] {
315            sfg |= 1 << (6 - i);
316        }
317    }
318    sfg
319}
320
321// ---------------------------------------------------------------------------
322// Filterbank — forward long-block MDCT (inverse of the decoder's synthesis).
323// ---------------------------------------------------------------------------
324pub const FRAME_LEN: usize = 1024;
325pub const LONG_N: usize = 2048;
326const SHORT_N: usize = 256;
327const SHORT_HALF: usize = 128;
328/// 1 / `OUTPUT_NORM`: the decoder scales its output by 1/32768, so the encoder
329/// scales the spectrum up by 32768 to land in the AAC coefficient domain.
330const SPEC_SCALE: f32 = 32768.0;
331
332/// Forward long-block filterbank: window the overlapping 2048 input samples
333/// (previous frame's 1024 ++ current 1024) and forward-MDCT to 1024 coefficients,
334/// scaled so the decoder's `imdct · window · (1/32768) + overlap-add` reconstructs
335/// the input (TDAC). `win` is the 2048-length window (sine or KBD).
336#[must_use]
337pub fn analyze_long(prev: &[f32; FRAME_LEN], cur: &[f32; FRAME_LEN], win: &[f32]) -> Vec<f32> {
338    let _prof = prof::scope(Stage::EncMdct);
339    // Written into fresh capacity: both halves are fully computed, so the zero
340    // fill of a `vec![0f32; LONG_N]` was overhead.
341    let mut windowed = Vec::<f32>::with_capacity(LONG_N);
342    let w = windowed.spare_capacity_mut();
343    for n in 0..FRAME_LEN {
344        w[n].write(prev[n] * win[n] * SPEC_SCALE);
345        w[FRAME_LEN + n].write(cur[n] * win[FRAME_LEN + n] * SPEC_SCALE);
346    }
347    // SAFETY: LONG_N = 2·FRAME_LEN and the loop wrote both halves in full.
348    unsafe { windowed.set_len(LONG_N) };
349    crate::dsp::mdct_fast(&windowed)
350}
351
352/// Forward short-block filterbank: eight 256-sample windows (128-hop) tiled across
353/// [448, 1600) of the prev++cur 2048 buffer, each windowed + MDCT'd to 128 coeffs,
354/// laid out window-major (the exact inverse of the decoder's `short_frame`). The
355/// uncovered [0,448)/[1600,2048) regions are bridged by the LongStart/LongStop
356/// neighbours — which is why `EightShort` must sit between transition blocks.
357#[must_use]
358pub fn analyze_short(prev: &[f32; FRAME_LEN], cur: &[f32; FRAME_LEN], sw: &[f32]) -> Vec<f32> {
359    let _prof = prof::scope(Stage::EncMdct);
360    let mut buf = [0f32; LONG_N];
361    buf[..FRAME_LEN].copy_from_slice(prev);
362    buf[FRAME_LEN..].copy_from_slice(cur);
363    let mut spec = vec![0f32; FRAME_LEN];
364    for w in 0..8 {
365        let off = 448 + w * SHORT_HALF;
366        let mut windowed = [0f32; SHORT_N];
367        for (n, s) in windowed.iter_mut().enumerate() {
368            *s = buf[off + n] * sw[n] * SPEC_SCALE;
369        }
370        let coeffs = crate::dsp::mdct_fast(&windowed);
371        spec[w * SHORT_HALF..(w + 1) * SHORT_HALF].copy_from_slice(&coeffs);
372    }
373    spec
374}
375
376/// The 2048-sample analysis window for a long or transition block — the exact
377/// encode-side twin of the decoder's `long_window`.
378///
379/// **The left half follows the PREVIOUS block's shape, the right half the
380/// current's** (`prev_kbd` / `cur_kbd`), because that is what the decoder does:
381/// each overlap region must be windowed identically on both sides or TDAC fails
382/// and the overlap-add leaves audible seams. LongStart/LongStop taper one side to
383/// a short window so the sequence stays TDAC-exact.
384///
385/// The decoder seeds `prev_kbd = false` for the first frame of a stream
386/// (`decode.rs`), so the encoder must too.
387#[allow(clippy::too_many_arguments)]
388fn long_window(
389    seq: WindowSequence,
390    prev_kbd: bool,
391    cur_kbd: bool,
392    sine_l: &[f32],
393    kbd_l: &[f32],
394    sine_s: &[f32],
395    kbd_s: &[f32],
396) -> Vec<f32> {
397    let long_prev = if prev_kbd { kbd_l } else { sine_l };
398    let long_cur = if cur_kbd { kbd_l } else { sine_l };
399    let short_prev = if prev_kbd { kbd_s } else { sine_s };
400    let short_cur = if cur_kbd { kbd_s } else { sine_s };
401
402    let mut w = vec![0f32; LONG_N];
403    if seq == WindowSequence::LongStop {
404        w[448..448 + SHORT_HALF].copy_from_slice(&short_prev[..SHORT_HALF]);
405        for s in w.iter_mut().take(FRAME_LEN).skip(576) {
406            *s = 1.0;
407        }
408    } else {
409        w[..FRAME_LEN].copy_from_slice(&long_prev[..FRAME_LEN]);
410    }
411    if seq == WindowSequence::LongStart {
412        for s in w.iter_mut().take(FRAME_LEN + 448).skip(FRAME_LEN) {
413            *s = 1.0;
414        }
415        w[FRAME_LEN + 448..FRAME_LEN + 448 + SHORT_HALF].copy_from_slice(&short_cur[SHORT_HALF..]);
416    } else {
417        w[FRAME_LEN..].copy_from_slice(&long_cur[FRAME_LEN..]);
418    }
419    w
420}
421
422/// **The Rung 0 gate signal**: order-2 LPC prediction gain over the frame's time
423/// samples — a cheap tonality proxy.
424///
425/// Chosen over the spectral flatness measure the lab validates because SFM needs
426/// a spectrum, and the window shape must be decided *before* the spectrum exists
427/// (the shape determines the window that produces it). Computing a probe MDCT per
428/// frame just to pick a window would roughly double filterbank cost for a
429/// small-by-design win — dominated on `bits-per-op` grounds before it started.
430///
431/// This is O(3n) multiply-adds and needs no transform. Tonal signals are strongly
432/// predictable from two past samples; noise is not. Validated against the
433/// per-class truth table in `lab::signals` before being wired here.
434///
435/// Returns `R[0] / E₂ ≥ 1`.
436pub(crate) fn time_tonality(x: &[f32]) -> f32 {
437    let n = x.len();
438    if n < 8 {
439        return 1.0;
440    }
441    let mut r = [0f64; 3];
442    for (lag, slot) in r.iter_mut().enumerate() {
443        let mut acc = 0f64;
444        for i in 0..n - lag {
445            acc += f64::from(x[i]) * f64::from(x[i + lag]);
446        }
447        *slot = acc;
448    }
449    if r[0] <= 1e-12 {
450        return 1.0;
451    }
452    let r0 = r[0] * 1.0001; // white-noise correction — keeps Levinson stable
453    let k1 = r[1] / r0;
454    let e1 = r0 * (1.0 - k1 * k1);
455    if e1 <= 1e-12 {
456        return 1.0;
457    }
458    let k2 = (r[2] - k1 * r[1]) / e1;
459    let e2 = e1 * (1.0 - k2 * k2);
460    ((r0 / e2.max(1e-12)) as f32).max(1.0)
461}
462
463// ---------------------------------------------------------------------------
464// Psychoacoustic model (brick 4) — per-SFB masking thresholds drive per-band
465// scalefactor allocation, so quantization noise is shaped to the audible floor.
466// ---------------------------------------------------------------------------
467
468/// Traunmüller's Hz→Bark (critical-band rate).
469fn hz_to_bark(f: f64) -> f64 {
470    let f = f.max(1.0);
471    26.81 * f / (1960.0 + f) - 0.53
472}
473
474/// Spreading of a masker's energy to a maskee `dz` Bark away (`dz` = maskee −
475/// masker): steep ~27 dB/Bark toward lower bands, gentle ~10 dB/Bark upward.
476fn spreading(dz: f64) -> f64 {
477    let slope_db = if dz >= 0.0 { -10.0 } else { -27.0 };
478    10f64.powf(slope_db * dz.abs() / 10.0)
479}
480
481/// The Bark-spreading matrix `S[i·n+j] = spreading(bark[i]-bark[j])` for one band
482/// geometry — fixed per (`sample_rate`, band count), so it's built once and cached,
483/// turning each frame's masking into a matrix-vector product (no runtime powf).
484/// `n_coeffs` is the number of spectral coefficients the band table spans — 1024
485/// for a long block, 128 for one short window. It sets the coefficient→Hz
486/// mapping, so passing the long value for a short block would place every band
487/// eight octaves too low and spread the mask against the wrong neighbours.
488fn spreading_matrix(swb: &[u16], sample_rate: u32, n_coeffs: usize) -> Arc<Vec<f64>> {
489    type Cache = Mutex<HashMap<(u32, usize, usize), Arc<Vec<f64>>>>;
490    static CACHE: OnceLock<Cache> = OnceLock::new();
491    let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new()));
492    let key = (sample_rate, swb.len(), n_coeffs);
493    let mut c = cache.lock().unwrap();
494    if let Some(m) = c.get(&key) {
495        return m.clone();
496    }
497    let num_swb = swb.len() - 1;
498    let bark: Vec<f64> = (0..num_swb)
499        .map(|sfb| {
500            let center = f64::midpoint(f64::from(swb[sfb]), f64::from(swb[sfb + 1]));
501            // n_coeffs coefficients span 0..sr/2.
502            hz_to_bark(center * f64::from(sample_rate) * 0.5 / n_coeffs as f64)
503        })
504        .collect();
505    let mut mat = vec![0f64; num_swb * num_swb];
506    for i in 0..num_swb {
507        for j in 0..num_swb {
508            mat[i * num_swb + j] = spreading(bark[i] - bark[j]);
509        }
510    }
511    let arc = Arc::new(mat);
512    c.insert(key, arc.clone());
513    arc
514}
515
516/// Per-SFB masking threshold (energy units): spread the band energies on the
517/// Bark scale, then sit the mask a fixed ratio below the spread signal.
518///
519/// `pub(crate)` so [`crate::lab::quality`] can score coding noise against the
520/// encoder's own mask (the NMR metric), in the same band geometry and energy
521/// domain the encoder allocates in.
522#[cfg(any(test, feature = "lab"))]
523pub(crate) fn masking_thresholds(spec: &[f32], swb: &[u16], sample_rate: u32) -> Vec<f64> {
524    let num_swb = swb.len() - 1;
525    let mut energy = vec![0.0f64; num_swb];
526    for sfb in 0..num_swb {
527        let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
528        energy[sfb] = spec[s..e]
529            .iter()
530            .map(|&x| f64::from(x).powi(2))
531            .sum::<f64>()
532            + 1e-3;
533    }
534    masking_from_energy(&energy, swb, sample_rate, FRAME_LEN, None)
535}
536
537/// The default signal-to-mask ratio: the mask sits 18 dB below the spread signal,
538/// for every band and every kind of content.
539///
540/// **Arm A2** replaces this constant with a function of tonality. It is census
541/// category 4 — a knob whose own doc-comment names the physical signal it tracks,
542/// shipping as a constant. Kept as the byte-identical fallback.
543const SMR_FLAT: f64 = 0.0158; // 10^(-18/10)
544
545thread_local! {
546    /// The flat signal-to-mask ratio (linear) of the frame this thread is
547    /// coding, from [`AacTuning::mask_smr_db`]: set per frame by
548    /// `encode_frame` and per segment by the frame-demand pre-pass (each wholly
549    /// on one worker thread), so the psy model needs no extra argument for it.
550    /// [`SMR_FLAT`] (18 dB) outside an encode.
551    static MASK_SMR: std::cell::Cell<f64> = const { std::cell::Cell::new(SMR_FLAT) };
552}
553
554/// [`AacTuning::mask_smr_db`] applies to streams under this rate a
555/// channel; from it up the mask is the 2.1.2 18 dB. Measured (PEAQ, all
556/// low-rate tools on): 24 dB is worth +0.41 BD-ODG on stereo vocal at 48-64
557/// kbps a channel, but cost stereo vocal 0.15 ODG at 96 kbps a channel (192
558/// kbps stereo) and mono vocal 0.08-0.13 at 96-160 kbps; at 18 dB every clip
559/// there is within 0.02 of 2.1.2 or better.
560const MASK_SMR_MAX_BPS_PER_CHANNEL: u32 = 96_000;
561
562/// The linear ratio for a flat SMR of `db` decibels: [`SMR_FLAT`] itself at
563/// 18 dB, so that setting keeps the 2.1.2 masks bit for bit.
564fn smr_ratio(db: f32) -> f64 {
565    if (f64::from(db) - 18.0).abs() < 1e-9 {
566        SMR_FLAT
567    } else {
568        10f64.powf(-f64::from(db) / 10.0)
569    }
570}
571
572/// The psychoacoustic arms in flight, threaded down to every coding path.
573///
574/// A struct rather than loose bools because these arms compose: A1 decides
575/// *whether* short blocks get a mask at all, A2 decides *what* that mask is, and
576/// both must reach the CPE path and the SCE path identically or the two paths
577/// silently encode to different models — the inconsistency great-gate's P0.9
578/// hygiene batch exists to prevent.
579///
580/// `PsyCfg::default()` is all-off = the encoder exactly as it shipped.
581#[derive(Debug, Clone, Copy, Default)]
582pub(crate) struct PsyCfg {
583    /// Arm A1 — psy model on short blocks (else flat scalefactors).
584    pub short_block_psy: bool,
585    /// Arm 1a — real window grouping on short blocks, with the short-block psy
586    /// model run per group and centred across groups.
587    pub window_grouping: bool,
588    /// Arm A2 — tonality-adaptive SMR (else flat 18 dB).
589    pub tonality_smr: bool,
590    /// Arm A3 — emit TNS on long blocks.
591    pub tns: bool,
592    /// Arm A6 — Perceptual Noise Substitution.
593    pub pns: bool,
594    /// Arm A7 — intensity stereo.
595    pub intensity: bool,
596    /// Arm A13 — demand-proportional stereo bit split.
597    pub stereo_bit_split: bool,
598}
599
600/// Per-band masking threshold from precomputed band energies.
601///
602/// Split out from [`masking_thresholds`] so short blocks (whose band energies are
603/// summed across the eight windows of a group) and long blocks share one masking
604/// model — great-gate P1: consolidate duplicated probe skeletons into one path,
605/// or a fit spanning both learns the inconsistency rather than the content.
606///
607/// `tonality` is **arm A2**: `None` uses the flat 18 dB [`SMR_FLAT`] (the shipped
608/// behavior, byte-identical); `Some(t)` interpolates the classic tonal/noise
609/// masker offsets per band.
610fn masking_from_energy(
611    energy: &[f64],
612    swb: &[u16],
613    sample_rate: u32,
614    n_coeffs: usize,
615    tonality: Option<&[f32]>,
616) -> Vec<f64> {
617    let spread = spread_energy(energy, swb, sample_rate, n_coeffs);
618    masking_from_spread(&spread, swb, sample_rate, n_coeffs, tonality)
619}
620
621/// Each band's spread energy: every band's energy as it reaches this band on
622/// the Bark scale, its own included at full weight.
623fn spread_energy(energy: &[f64], swb: &[u16], sample_rate: u32, n_coeffs: usize) -> Vec<f64> {
624    let num_swb = swb.len() - 1;
625    let mat = spreading_matrix(swb, sample_rate, n_coeffs);
626    (0..num_swb)
627        .map(|i| {
628            let row = &mat[i * num_swb..(i + 1) * num_swb];
629            (0..num_swb).map(|j| energy[j] * row[j]).sum()
630        })
631        .collect()
632}
633
634/// The mask from [`spread_energy`]: a signal-to-mask ratio below the spread
635/// signal, floored at the threshold of hearing.
636fn masking_from_spread(
637    spread: &[f64],
638    swb: &[u16],
639    sample_rate: u32,
640    n_coeffs: usize,
641    tonality: Option<&[f32]>,
642) -> Vec<f64> {
643    let num_swb = swb.len() - 1;
644    (0..num_swb)
645        .map(|i| {
646            let spread = spread[i];
647            let smr = match tonality {
648                None => MASK_SMR.with(std::cell::Cell::get),
649                Some(t) => {
650                    let center = f64::midpoint(f64::from(swb[i]), f64::from(swb[i + 1]));
651                    let bark = hz_to_bark(center * f64::from(sample_rate) * 0.5 / n_coeffs as f64);
652                    smr_for(f64::from(t[i]), bark)
653                }
654            };
655            spread * smr
656        })
657        .zip(ath_long(swb, sample_rate, n_coeffs).iter())
658        .map(|(thr, &ath)| thr.max(ath))
659        .collect()
660}
661
662/// The absolute threshold of hearing (Terhardt's approximation), in dB SPL, at
663/// `hz`, capped at [`ATH_CAP_DB`].
664fn ath_db(hz: f64) -> f64 {
665    let f = (hz / 1000.0).max(0.02);
666    let db = 3.64 * f.powf(-0.8) - 6.5 * (-0.6 * (f - 3.3).powi(2)).exp() + 1e-3 * f.powi(4);
667    db.min(ATH_CAP_DB)
668}
669
670/// Ceiling on the hearing floor, in dB SPL (-80 dBFS). Terhardt's curve rises
671/// past 65 dB SPL at 16 kHz and past full scale near 18 kHz; uncapped, it acts
672/// as a bandwidth cut and drops quiet high detail that PEAQ still hears.
673/// Measured (PEAQ ODG vs the floor-less encoder, same decoder): a 50 dB cap
674/// cost stereo guitar 0.33 at 128 kbps and 0.20 at 320 kbps; at 20 dB those
675/// are at parity (-0.001, +0.002) while piano keeps +0.93 at 128 kbps.
676const ATH_CAP_DB: f64 = 20.0;
677
678/// Energy, in this encoder's long-block coefficient domain, of a full-scale
679/// sine: the reference the threshold of hearing is placed against (0 dBFS =
680/// [`ATH_FULL_SCALE_SPL`]). Measured once through the encoder's own long
681/// filterbank, so it tracks `SPEC_SCALE` and the MDCT normalisation exactly.
682fn full_scale_sine_energy() -> f64 {
683    static E: OnceLock<f64> = OnceLock::new();
684    *E.get_or_init(|| {
685        let n2 = 2 * FRAME_LEN;
686        let win: Vec<f32> = (0..n2)
687            .map(|n| (std::f64::consts::PI * (n as f64 + 0.5) / n2 as f64).sin() as f32)
688            .collect();
689        // 1 kHz at 48 kHz: a whole number of cycles per frame does not matter
690        // for the energy, which is what is measured.
691        let s = |n: usize| (2.0 * std::f64::consts::PI * 1000.0 * n as f64 / 48_000.0).sin() as f32;
692        let mut prev = [0f32; FRAME_LEN];
693        let mut cur = [0f32; FRAME_LEN];
694        for n in 0..FRAME_LEN {
695            prev[n] = s(n);
696            cur[n] = s(FRAME_LEN + n);
697        }
698        analyze_long(&prev, &cur, &win)
699            .iter()
700            .map(|&x| f64::from(x).powi(2))
701            .sum()
702    })
703}
704
705/// Sound pressure level a full-scale sine is taken to play at: 100 dB, 4 dB
706/// above the usual 16-bit convention of 96, which lowers the floor by 4 dB --
707/// margin for listening louder than the convention assumes. Measured (PEAQ
708/// ODG vs the floor-less encoder, same decoder): at 96 dB stereo vocal lost
709/// 0.15 at 320 kbps and mono piano 0.31 at 128 kbps; 100 dB is the setting
710/// the sweep found at parity on the losing clips.
711const ATH_FULL_SCALE_SPL: f64 = 100.0;
712
713/// Per-band absolute-threshold floor for the long-block mask (energy units):
714/// the energy a tone at the band's quietest audible level would have. A band
715/// whose content sits below it is inaudible, so its mask never falls below it.
716///
717/// Without this floor the mask scaled with each band's own energy, however
718/// small: a band holding only a tone's window leakage got a mask 18 dB below
719/// that leakage and was coded as if it mattered. On a 440 Hz tone at 96 kbps
720/// that spent the frame on ~450 near-silent coefficients and left the tone
721/// with 7 quantizer levels (17 dB SNR, and a 1.5x level error at 21 kbps):
722/// `remade_ffmpeg_rs#129`.
723///
724/// Long blocks only (`n_coeffs == FRAME_LEN`): short-block band energies are
725/// summed over a window group whose size this function does not see, so they
726/// keep the relative mask (short-block psy is off by default).
727fn ath_long(swb: &[u16], sample_rate: u32, n_coeffs: usize) -> Arc<Vec<f64>> {
728    type Cache = Mutex<HashMap<(u32, usize, usize), Arc<Vec<f64>>>>;
729    static CACHE: OnceLock<Cache> = OnceLock::new();
730    let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new()));
731    let key = (sample_rate, swb.len(), n_coeffs);
732    if let Some(a) = cache.lock().unwrap().get(&key) {
733        return a.clone();
734    }
735    let num_swb = swb.len() - 1;
736    let ath: Vec<f64> = if n_coeffs == FRAME_LEN {
737        let e_fs = full_scale_sine_energy();
738        let hz_per_line = f64::from(sample_rate) * 0.5 / n_coeffs as f64;
739        (0..num_swb)
740            .map(|sfb| {
741                let min_db = (usize::from(swb[sfb])..usize::from(swb[sfb + 1]))
742                    .map(|k| ath_db((k as f64 + 0.5) * hz_per_line))
743                    .fold(f64::INFINITY, f64::min);
744                e_fs * 10f64.powf((min_db - ATH_FULL_SCALE_SPL) / 10.0)
745            })
746            .collect()
747    } else {
748        vec![0.0; num_swb]
749    };
750    let arc = Arc::new(ath);
751    cache.lock().unwrap().insert(key, arc.clone());
752    arc
753}
754
755/// **Arm A2.** Signal-to-mask ratio as a function of band tonality and Bark.
756///
757/// The classic asymmetry: a *tonal* masker hides noise poorly, so the mask must
758/// sit far below it (≈ 14.5 + bark dB); a *noise-like* masker hides noise well
759/// (≈ 5.5 dB). Interpolating on the tonality index is the standard MPEG form.
760///
761/// Today's encoder applies 18 dB to everything, so a pure tone and band-limited
762/// noise at equal energy get identical treatment — which is what this replaces.
763///
764/// Returned as a linear energy ratio (`10^(−dB/10)`), matching [`SMR_FLAT`].
765///
766/// # The noise end is 5.5 dB — and pinning it to 18 dB was measured and REFUTED
767///
768/// The obvious-looking "safety" tweak is to pin the noise end to the shipped flat
769/// 18 dB, so arm A2 can only ever give a band *more* protection than today and
770/// never less. Measured on the corpus, that made things **worse**, not safer:
771///
772/// | noise end | mean Δaudible% | worst class |
773/// |---|---|---|
774/// | 5.5 dB (textbook) | **−0.312** | +0.720 |
775/// | 18.0 dB (pinned) | −0.006 | **+2.185** |
776///
777/// The reason is that an SMR pair is a **bit-allocation balance, not two
778/// independent protections**. Raising the tonal end buys precision only because
779/// lowering the noise end frees the bits to pay for it. Pin the noise end and the
780/// tonal end becomes pure extra demand against a fixed budget — the rate loop
781/// answers by lifting the global base, and *every* band gets coarser. The
782/// "conservative" variant regressed three times as hard as the one it was meant
783/// to protect against.
784///
785/// Keep the textbook pair. A2's remaining per-class failures are a **dispatch**
786/// problem (route the arm by content class), not a constant to retune.
787const SMR_NOISE_DB: f64 = 5.5;
788fn smr_for(tonality: f64, bark: f64) -> f64 {
789    let t = tonality.clamp(0.0, 1.0);
790    let db = t * (14.5 + bark) + (1.0 - t) * SMR_NOISE_DB;
791    // Clamp to a sane band: below ~5 dB the mask stops protecting anything, and
792    // above ~30 dB the rate loop is asked for precision no bitrate can buy.
793    let db = db.clamp(5.0, 30.0);
794    10f64.powf(-db / 10.0)
795}
796
797/// Per-SFB scalefactor offsets (relative to a common base the rate loop sets):
798/// higher where masking is generous, lower where noise would be audible. From
799/// `noise ∝ 2^(0.375·sf)·Σ√|X|`, the sf hitting `noise = threshold` is
800/// `log2(threshold/Σ√|X|)/0.375`; we normalize + clamp so deltas stay codeable.
801/// Per-SFB tonality index in `[0, 1]` from the spectral flatness measure — **arm
802/// A2's signal**. 0 = noise-like, 1 = pure tone.
803///
804/// `SFM = geometric_mean(|X|²) / arithmetic_mean(|X|²)`, in dB, through the
805/// classic `min(SFM_dB / −60, 1)`.
806pub(crate) fn band_tonality(spec: &[f32], swb: &[u16], nwin: usize, wlen: usize) -> Vec<f32> {
807    let n = swb.len() - 1;
808    let mut out = vec![0f32; n];
809    for b in 0..n {
810        let (s, e) = (swb[b] as usize, swb[b + 1] as usize);
811        let (mut log_sum, mut lin_sum, mut cnt) = (0f64, 0f64, 0usize);
812        for w in 0..nwin {
813            let base = w * wlen;
814            for k in s..e {
815                let Some(&x) = spec.get(base + k) else {
816                    continue;
817                };
818                // Floored well below any audible coefficient so a single exact
819                // zero cannot drag the geometric mean to 0 and fake a pure tone.
820                let p = (f64::from(x) * f64::from(x)).max(1e-10);
821                log_sum += p.ln();
822                lin_sum += p;
823                cnt += 1;
824            }
825        }
826        if cnt == 0 {
827            continue;
828        }
829        let gm = (log_sum / cnt as f64).exp();
830        let am = lin_sum / cnt as f64;
831        let sfm_db = 10.0 * (gm / am.max(1e-30)).log10();
832        out[b] = ((sfm_db / -60.0) as f32).clamp(0.0, 1.0);
833    }
834    out
835}
836
837/// The long-block psy model: per-band offsets from the masking thresholds,
838/// the starved-frame reduction (see [`Offsets`]) and the [`peak_hold`] caps,
839/// which need the channel's `target_bits` to bound what they ask for.
840fn perceptual_offsets(
841    spec: &[f32],
842    swb: &[u16],
843    sample_rate: u32,
844    tonality_smr: bool,
845    target_bits: usize,
846) -> Offsets {
847    let _prof = prof::scope(Stage::EncPsy);
848    let num_swb = swb.len() - 1;
849    let mut energy = vec![0.0f64; num_swb];
850    for sfb in 0..num_swb {
851        let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
852        energy[sfb] = spec[s..e]
853            .iter()
854            .map(|&x| f64::from(x).powi(2))
855            .sum::<f64>()
856            + 1e-3;
857    }
858    let ton = tonality_smr.then(|| band_tonality(spec, swb, 1, FRAME_LEN));
859    let spread = spread_energy(&energy, swb, sample_rate, FRAME_LEN);
860    let thr = masking_from_spread(&spread, swb, sample_rate, FRAME_LEN, ton.as_deref());
861
862    let mut raw = vec![0.0f64; num_swb];
863    let mut noise_scale = vec![0.0f64; num_swb];
864    for sfb in 0..num_swb {
865        let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
866        energy[sfb] = spec[s..e].iter().map(|&x| f64::from(x).powi(2)).sum();
867        noise_scale[sfb] = spec[s..e]
868            .iter()
869            .map(|&x| f64::from(x.abs()).sqrt())
870            .sum::<f64>()
871            + 1e-6;
872        raw[sfb] = (thr[sfb] / noise_scale[sfb]).log2() / 0.375;
873    }
874    let cap = peak_hold(
875        spec,
876        swb,
877        sample_rate,
878        &energy,
879        &spread,
880        &noise_scale,
881        target_bits,
882    );
883    // Center on the energy-bearing bands — empty bands have huge `thr/noise_scale`
884    // (they quantize to ZERO anyway) and would otherwise skew a plain mean.
885    let etot: f64 = energy.iter().sum::<f64>() + 1e-9;
886    let center: f64 = (0..num_swb).map(|i| raw[i] * energy[i]).sum::<f64>() / etot;
887    let off = raw
888        .iter()
889        .map(|&r| ((r - center).round() as i32).clamp(-60, 60))
890        .collect();
891    // The starved-frame reduction (see `Offsets`): every band's mask relative to
892    // the loudest energy-bearing band's, in the fourth-root domain.
893    let thr_ref = (0..num_swb)
894        .filter(|&i| energy[i] > 0.0)
895        .map(|i| thr[i])
896        .fold(0f64, f64::max);
897    if thr_ref <= 0.0 {
898        return Offsets::flat(off);
899    }
900    let surplus = SURPLUS.with(std::cell::Cell::get).then(|| {
901        let density = |i: usize| thr[i] / f64::from(swb[i + 1] - swb[i]);
902        let mut floor: Vec<i32> = (0..num_swb)
903            .map(|i| no_clamp_sf(&spec[usize::from(swb[i])..usize::from(swb[i + 1])]))
904            .collect();
905        // A scalefactor delta codes at most 60 steps: no band may run on past
906        // that under the highest floor.
907        let deepest = floor.iter().copied().max().unwrap_or(0) - 60;
908        for f in &mut floor {
909            *f = (*f).max(deepest);
910        }
911        let top = (0..num_swb)
912            .filter(|&i| energy[i] > 0.0)
913            .map(density)
914            .fold(0f64, f64::max);
915        Surplus {
916            gap: (0..num_swb)
917                .map(|i| ((top / density(i)).log2() / 0.375).max(0.0).round() as i32)
918                .collect(),
919            floor,
920            start: (center + NMR0_SF_OFFSET).round() as i32 - SURPLUS_MARGIN_STEPS,
921        }
922    });
923    let ratio: Vec<f32> = thr
924        .iter()
925        .map(|&t| ((t / thr_ref).sqrt().sqrt()).min(1.0) as f32)
926        .collect();
927    Offsets {
928        off,
929        cap,
930        ratio,
931        thr_ref,
932        // `raw + NMR0_SF_OFFSET` is where a band's noise meets its mask, so the
933        // base putting the bands at their masks is `center + NMR0_SF_OFFSET`.
934        mask_base: (center + NMR0_SF_OFFSET).round() as i32,
935        surplus,
936    }
937}
938
939/// Where a band's quantization noise meets its mask, relative to `raw` in
940/// [`perceptual_offsets`]: the uniform-rounding noise of the `x^0.75` quantizer
941/// is `(4/27)·2^(0.375·(sf−100))·Σ√|x|`, so noise = `thr` at
942/// `sf = 100 + log2(thr/Σ√|x|)/0.375 + log2(27/4)/0.375`. The 100 is the
943/// scalefactor origin; `raw` is measured from it, and `log2(27/4)/0.375 = 7.35`.
944const NMR0_SF_OFFSET: f64 = 107.35;
945
946/// Per-band scalefactor offsets from the psy model, and what [`Offsets::sf`]
947/// needs to keep a starved frame's loud bands accurate.
948///
949/// The rate loop searches one `base` and codes band `b` at `base + off[b]`:
950/// a uniform step, so every band's noise-to-mask ratio moves together. That is
951/// right while the budget covers the masks. Past them (`base > mask_base`) it is
952/// not: a loud tone over quiet broadband noise at 53 kbps a channel (a 5.1
953/// stream at 320 kbps) had every band raised 13 dB over its mask, which left
954/// the noise bands coded as a few stray ±1s, still taking 95% of the bits, and
955/// the tone with a single quantizer level: 6 dB SNR, its level set by which
956/// side of one step it landed on (`remade_ffmpeg_rs#129`).
957///
958/// Past the masks the thresholds are raised the 3GPP way instead (TS 26.403
959/// §5.6.1.2, the reduction FDK-AAC and FFmpeg's psy model use):
960/// `thr' = (thr^¼ + r)^4`, with `r` set so the loudest band rises exactly as the
961/// uniform step would. A quiet band's threshold climbs towards `r^4` far faster
962/// than a loud band's, so the bits it was wasting go to the bands that carry
963/// the signal. Below the masks (`base <= mask_base`) nothing changes.
964///
965/// One base step past the masks already lifts a band 50 dB under the loudest by
966/// 11 steps, so the rate loop's search variable (the *level*) runs in
967/// [`STARVED_SUBSTEPS`] sub-steps of the base there; a whole-step search left
968/// up to half the frame unspent.
969#[derive(Debug, Clone)]
970pub(crate) struct Offsets {
971    off: Vec<i32>,
972    /// Per band, the highest scalefactor [`peak_hold`] allows (255 for none);
973    /// empty for no holds.
974    cap: Vec<i32>,
975    /// Per band, `(thr / thr_ref)^¼` in `(0, 1]`; empty for no reduction
976    /// (short blocks keep the uniform step).
977    ratio: Vec<f32>,
978    /// The loudest band's mask, which `ratio` is relative to.
979    thr_ref: f64,
980    /// The base at which the bands' quantization noise reaches their masks.
981    mask_base: i32,
982    /// How bits left over far below the masks are spent; `None` for the
983    /// uniform step all the way down.
984    surplus: Option<Surplus>,
985}
986
987/// How a frame with bits to spare spends them (see [`SURPLUS_MARGIN_STEPS`]).
988#[derive(Debug, Clone)]
989struct Surplus {
990    /// Per band, how many steps its mask per line sits under the highest one.
991    gap: Vec<i32>,
992    /// Per band, the lowest scalefactor that clamps no coefficient and stays
993    /// within a codeable delta of every other band's.
994    floor: Vec<i32>,
995    /// The base below which the noise starts to level out.
996    start: i32,
997}
998
999/// How far below the masks every band's noise goes, in base steps of 1.13 dB
1000/// (13 = 14.7 dB), before a frame with bits to spare starts levelling the
1001/// noise across its bands.
1002///
1003/// The uniform step lowers every band's noise-to-mask ratio together, however
1004/// far under the masks that takes them. On tonal content at a high rate most of
1005/// the surplus then went into bands that were already inaudible (a tone's
1006/// window leakage: 51 dB waveform SNR for two pure tones at 320 kbps, where
1007/// the reference encoder in `remade_ffmpeg_rs#211` reaches 82), while the bands
1008/// carrying the signal kept nearly all of the error energy. Below this margin
1009/// a band whose mask is low drops half as fast as the loudest one, until the
1010/// two reach the same noise per line.
1011///
1012/// Measured with PEAQ at 192, 256 and 320 kbps stereo (9 music clips, 4 time
1013/// offsets each): ODG -0.000, +0.001 and +0.013 on average, no clip beyond the
1014/// noise, 0 to 6 dB more SNR, 13 dB on the pure tones. Letting a low band stop
1015/// dead instead of dropping half as fast gains up to 25 dB on piano, but costs
1016/// it 0.12 ODG at this margin and up to 0.24 at a 3 dB one.
1017const SURPLUS_MARGIN_STEPS: i32 = 13;
1018
1019/// The surplus policy runs for mono and stereo streams from this rate a
1020/// channel; every other stream codes as before, bit for bit. Multichannel lost
1021/// up to 0.23 ODG at the margins that would have helped its pure tones.
1022const SURPLUS_MIN_BPS_PER_CHANNEL: u32 = 96_000;
1023
1024thread_local! {
1025    /// Whether the frame this thread is coding runs the surplus policy: set
1026    /// per frame by `encode_frame`, like [`SECTION_TRELLIS`].
1027    static SURPLUS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1028}
1029
1030/// The lowest scalefactor at which no line of `band` quantizes past `MAX_QUANT`.
1031fn no_clamp_sf(band: &[f32]) -> i32 {
1032    let maxp = band
1033        .iter()
1034        .fold(0f64, |a, &x| a.max(f64::from(x.abs())))
1035        .powf(0.75);
1036    if maxp <= 1e-9 {
1037        0
1038    } else {
1039        (100.0 - (f64::from(MAX_QUANT) / maxp).log2() / 0.1875).ceil() as i32
1040    }
1041}
1042
1043/// Levels per base step past the masks (see [`Offsets`]).
1044const STARVED_SUBSTEPS: i32 = 8;
1045
1046impl std::ops::Deref for Offsets {
1047    type Target = [i32];
1048    fn deref(&self) -> &[i32] {
1049        &self.off
1050    }
1051}
1052
1053impl Offsets {
1054    /// Offsets with no starved-frame reduction: always the uniform step.
1055    pub(crate) fn flat(off: Vec<i32>) -> Self {
1056        Self {
1057            off,
1058            cap: Vec::new(),
1059            ratio: Vec::new(),
1060            thr_ref: 0.0,
1061            mask_base: i32::MAX,
1062            surplus: None,
1063        }
1064    }
1065
1066    /// The highest level the rate loop needs to search: every band at 255.
1067    /// Past the family's top the caps are released one step a level, so any
1068    /// budget, however small, stays reachable.
1069    pub(crate) fn max_level(&self) -> i32 {
1070        self.top_level() + if self.cap.is_empty() { 0 } else { 255 }
1071    }
1072
1073    /// The level at which every band without a hold has reached 255.
1074    fn top_level(&self) -> i32 {
1075        if self.ratio.is_empty() || self.mask_base >= 255 {
1076            255
1077        } else {
1078            self.mask_base.max(0) + (255 - self.mask_base.max(0)) * STARVED_SUBSTEPS
1079        }
1080    }
1081
1082    /// Apply the holds to the family's scalefactors at `level`.
1083    fn held(&self, level: i32, mut sf: Vec<i32>) -> Vec<i32> {
1084        if !self.cap.is_empty() {
1085            let release = (level - self.top_level()).max(0);
1086            for (s, &c) in sf.iter_mut().zip(&self.cap) {
1087                *s = (*s).min((c + release).min(255));
1088            }
1089        }
1090        if let Some(su) = &self.surplus {
1091            for (s, &f) in sf.iter_mut().zip(&su.floor) {
1092                *s = (*s).max(f).min(255);
1093            }
1094        }
1095        sf
1096    }
1097
1098    /// How many steps over the uniform `fam + off[b]` the surplus policy
1099    /// leaves each band, or `None` at or above its start.
1100    fn surplus_lag(&self, fam: i32) -> Option<impl Iterator<Item = i32> + '_> {
1101        let su = self.surplus.as_ref()?;
1102        let below = su.start - fam;
1103        (below > 0).then(|| su.gap.iter().map(move |&g| (g.min(below) + 1) / 2))
1104    }
1105
1106    /// Share one reduction between the two channels of a pair coded at a common
1107    /// level: ratios against the louder channel's loudest band, and the later of
1108    /// the two mask bases, so the uniform region (and its output) is unchanged.
1109    ///
1110    /// A silent channel (the side of two identical ones) has no masks to share.
1111    /// Under the surplus policy it follows the other, whose offsets stay as
1112    /// they are; its lines are zero at any scalefactor. Otherwise both fall
1113    /// back to the uniform step.
1114    pub(crate) fn join(a: &mut Self, b: &mut Self) {
1115        match (&a.surplus, &b.surplus) {
1116            (Some(_), None) => {
1117                *b = a.clone();
1118                return;
1119            }
1120            (None, Some(_)) => {
1121                *a = b.clone();
1122                return;
1123            }
1124            _ => {}
1125        }
1126        if a.ratio.is_empty() || b.ratio.is_empty() {
1127            *a = Self::flat(std::mem::take(&mut a.off));
1128            *b = Self::flat(std::mem::take(&mut b.off));
1129            return;
1130        }
1131        let thr_ref = a.thr_ref.max(b.thr_ref);
1132        let mask_base = a.mask_base.max(b.mask_base);
1133        for o in [a, b] {
1134            let k = (o.thr_ref / thr_ref).sqrt().sqrt() as f32;
1135            for q in &mut o.ratio {
1136                *q *= k;
1137            }
1138            o.thr_ref = thr_ref;
1139            o.mask_base = mask_base;
1140        }
1141    }
1142
1143    /// Per-band scalefactors at search level `level`, each clamped to the
1144    /// codeable range. Up to `mask_base` the level is the common base; past it,
1145    /// [`STARVED_SUBSTEPS`] levels make one base step for the loudest band, and
1146    /// every other band rises by the reduction on top; a [`peak_hold`] cap then
1147    /// bounds its band from above. Never below the uniform `base + off[b]` or,
1148    /// for a held band, its cap, both at or over [`min_base`]'s no-clamp floor;
1149    /// non-decreasing in `level`, so the rate loop's search stays monotone.
1150    pub(crate) fn sf(&self, level: i32) -> Vec<i32> {
1151        let fam = level.min(self.top_level());
1152        if fam <= self.mask_base || self.ratio.is_empty() {
1153            let sf = match self.surplus_lag(fam) {
1154                Some(lag) => self
1155                    .off
1156                    .iter()
1157                    .zip(lag)
1158                    .map(|(&o, l)| (fam + o + l).clamp(0, 255))
1159                    .collect(),
1160                None => self.off.iter().map(|&o| (fam + o).clamp(0, 255)).collect(),
1161            };
1162            return self.held(level, sf);
1163        }
1164        let d = f64::from(fam - self.mask_base) / f64::from(STARVED_SUBSTEPS);
1165        let base = f64::from(self.mask_base) + d;
1166        // The loudest band's threshold rises by 2^(0.375·d), its fourth root by
1167        // u = 2^(0.09375·d), so r = u − 1 in units of that root.
1168        let u = (0.093_75 * d).exp2();
1169        let sf = self
1170            .off
1171            .iter()
1172            .zip(&self.ratio)
1173            .map(|(&o, &q)| {
1174                let q = f64::from(q).max(1e-6);
1175                // Steps beyond the uniform rise: log2(thr' / (thr·u^4)) / 0.375.
1176                let extra = (4.0 / 0.375 * ((q + u - 1.0) / (q * u)).log2()).max(0.0);
1177                ((base + f64::from(o) + extra).round() as i32).clamp(0, 255)
1178            })
1179            .collect();
1180        self.held(level, sf)
1181    }
1182}
1183
1184/// The SNR, in dB, at which [`peak_hold`] holds a dominant band.
1185///
1186/// Measured on the downstream 5.1 gate signal (a 0.25 tone per channel over
1187/// 0.03 x uniform noise) and the 57-row PEAQ table, with
1188/// [`PEAK_HOLD_DOMINANCE`] at 30: 24 dB gives 20.8 dB SNR at 320 kbps 5.1 and
1189/// a PEAQ mean of +0.033 (33 rows better, 14 worse, worst -0.065); 27 dB gives
1190/// 21.5 dB but worst row -0.091 and 20 rows worse.
1191const PEAK_HOLD_SNR_DB: f64 = 24.0;
1192
1193/// How much a band's own energy must exceed what every other band spreads into
1194/// it for [`peak_hold`] to hold it.
1195///
1196/// At 1, flat noise passes in nearly every band and the holds starve the tone
1197/// (5.6 dB on the gate at 128 kbps 5.1); at 10, harmonic music passes too
1198/// (guitar rows down to -0.36 ODG); at 100 or more, a tone straddling a band
1199/// edge fails it and its channel's level drifts (+0.6..+0.85 dB on the #129
1200/// repro). 30 separates the tones from both.
1201const PEAK_HOLD_DOMINANCE: f64 = 30.0;
1202
1203/// The largest share of a frame's bits the holds may ask for; past it the
1204/// hold SNR comes down for every held band alike. 0.15 and 0.25 measured the
1205/// same; 0.08 cost the gate 2 dB at 128 kbps 5.1.
1206const PEAK_HOLD_BIT_SHARE: f64 = 0.25;
1207
1208/// The narrow-band SNR floor: a per-band scalefactor cap that holds every
1209/// *dominant* band (one whose own energy is at least [`PEAK_HOLD_DOMINANCE`]
1210/// times what the other bands spread into it, i.e. a tone standing clear of
1211/// its surroundings) at [`PEAK_HOLD_SNR_DB`], or at the threshold in quiet,
1212/// whichever is coarser. Empty when no band qualifies.
1213///
1214/// Why: the uniform noise-to-mask family never lets a tone's band beat its
1215/// 18 dB mask until every band of a broadband noise bed under it has reached
1216/// its own mask too, about 144 kbps a channel for white noise. Below that, a
1217/// tone over noise came back at a flat ~16 dB SNR from 128 to 512 kbps 5.1
1218/// (88-96% of the error within 150 Hz of the tone), and its level swung by up
1219/// to 0.6 dB with the rate. A cap costs a held band its share of the frame
1220/// but no syntax: the scalefactor is the band's own.
1221///
1222/// The holds ask for about one bit a line per 6 dB; when that is more than
1223/// [`PEAK_HOLD_BIT_SHARE`] of `target_bits`, the hold SNR is scaled down. A
1224/// cap never goes under the band's no-clamp floor (see [`min_base`]). Long
1225/// blocks only.
1226fn peak_hold(
1227    spec: &[f32],
1228    swb: &[u16],
1229    sample_rate: u32,
1230    energy: &[f64],
1231    spread: &[f64],
1232    noise_scale: &[f64],
1233    target_bits: usize,
1234) -> Vec<i32> {
1235    let num_swb = swb.len() - 1;
1236    let dominant: Vec<bool> = (0..num_swb)
1237        .map(|b| {
1238            // `spread` was built from `energy + 1e-3`; what is left after the
1239            // band's own part is what every other band spreads into it.
1240            let others = (spread[b] - energy[b] - 1e-3).max(0.0);
1241            energy[b] > 0.0 && energy[b] >= PEAK_HOLD_DOMINANCE * others
1242        })
1243        .collect();
1244    if !dominant.iter().any(|&d| d) {
1245        return Vec::new();
1246    }
1247    let lines: usize = (0..num_swb)
1248        .filter(|&b| dominant[b])
1249        .map(|b| usize::from(swb[b + 1] - swb[b]))
1250        .sum();
1251    let ask = lines as f64 * PEAK_HOLD_SNR_DB / 6.02;
1252    let hold_db = PEAK_HOLD_SNR_DB * (PEAK_HOLD_BIT_SHARE * target_bits as f64 / ask).min(1.0);
1253    let m = 10f64.powf(-hold_db / 10.0);
1254    let ath = ath_long(swb, sample_rate, FRAME_LEN);
1255    (0..num_swb)
1256        .map(|b| {
1257            if !dominant[b] {
1258                return 255;
1259            }
1260            let (s, e) = (swb[b] as usize, swb[b + 1] as usize);
1261            let noise = (energy[b] * m).max(ath[b]);
1262            let cap = ((noise / noise_scale[b]).log2() / 0.375 + NMR0_SF_OFFSET).round();
1263            // Never under the band's no-clamp floor (see `min_base`).
1264            let min_sf = f64::from(no_clamp_sf(&spec[s..e]));
1265            cap.max(min_sf).clamp(0.0, 255.0) as i32
1266        })
1267        .collect()
1268}
1269
1270// ---------------------------------------------------------------------------
1271// Quantization + coding — brick 4: per-band scalefactors (psy-driven), cheapest
1272// codebook per band, rate loop over the common base, raw_data_block assembly.
1273// ---------------------------------------------------------------------------
1274
1275/// The Rung 0 gate's transient-veto threshold, as a percentile of the clip's own
1276/// frame-attack distribution. Frames above it always take the sine window.
1277///
1278/// PROVISIONAL. 0.75 is a placeholder pending a calculator fit; it is set high
1279/// (veto only the top quartile) so the veto is conservative — it gives up KBD on
1280/// some stationary frames rather than risk smearing an onset.
1281const SHAPE_ATTACK_VETO_PCT: f32 = 0.75;
1282
1283/// Arm A13's routing threshold: how correlated a channel pair must be before the
1284/// joint rate loop replaces the even per-channel split. Sits in the measured gap
1285/// between wide content (0.25, where joint loses) and real stereo music
1286/// (0.47-0.84, where it wins).
1287const JOINT_STEREO_MIN_CORR: f32 = 0.35;
1288
1289/// Spectral correlation of a channel pair, `|<L,R>| / sqrt(<L,L><R,R>)`.
1290/// 1 = identical, 0 = orthogonal. O(n) over the spectra the caller already has.
1291fn pair_correlation(l: &[f32], r: &[f32]) -> f32 {
1292    let n = l.len().min(r.len());
1293    let (mut dot, mut el, mut er) = (0f64, 0f64, 0f64);
1294    for i in 0..n {
1295        let (a, b) = (f64::from(l[i]), f64::from(r[i]));
1296        dot += a * b;
1297        el += a * a;
1298        er += b * b;
1299    }
1300    if el <= 1e-9 || er <= 1e-9 {
1301        return 1.0; // a silent channel is trivially "agreeable"
1302    }
1303    (dot.abs() / (el.sqrt() * er.sqrt())) as f32
1304}
1305
1306const ID_SCE: u32 = 0;
1307const ID_CPE: u32 = 1;
1308const ID_LFE: u32 = 3;
1309const ID_END: u32 = 7;
1310const ZERO_HCB: u8 = 0;
1311const ESC_HCB: u8 = 11;
1312
1313// ---------------------------------------------------------------------------
1314// Channel element layout (ISO 14496-3 Table 1.19).
1315//
1316// `channel_configuration` in the ADTS header / AudioSpecificConfig does not just
1317// count channels — it *names the element sequence a decoder will expect*. Writing
1318// `channel_config = 6` and then emitting six SCEs is not "6 channels", it is a
1319// non-conformant stream: a conforming decoder reads SCE, CPE, CPE, LFE.
1320//
1321// Our own decoder happened to tolerate it (it appends elements in order), which
1322// is exactly how the bug survived — self-round-trip is not conformance.
1323// ---------------------------------------------------------------------------
1324
1325/// One channel element to emit, naming its source channels **in input order**.
1326#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1327pub(crate) enum Elem {
1328    /// `single_channel_element` carrying input channel `.0`.
1329    Sce(usize),
1330    /// `channel_pair_element` carrying input channels `.0` (left) and `.1` (right).
1331    Cpe(usize, usize),
1332    /// `lfe_channel_element` carrying input channel `.0`. Long blocks only.
1333    Lfe(usize),
1334}
1335
1336impl Elem {
1337    /// The 3-bit element id written to the bitstream.
1338    fn id(self) -> u32 {
1339        match self {
1340            Self::Sce(_) => ID_SCE,
1341            Self::Cpe(_, _) => ID_CPE,
1342            Self::Lfe(_) => ID_LFE,
1343        }
1344    }
1345}
1346
1347/// The element sequence for `channels`, with source indices in the **standard
1348/// interleave order** the caller pushes (`WAVE_FORMAT_EXTENSIBLE` / FFmpeg order:
1349/// FL, FR, FC, LFE, BL, BR).
1350///
1351/// The reordering is the substance here. AAC orders a 5.1 stream
1352/// `C, L, R, Ls, Rs, LFE`; interleaved PCM arrives `L, R, C, LFE, Ls, Rs`. Emitting
1353/// them in arrival order would put the centre channel in the left speaker.
1354///
1355/// Returns `None` for channel counts with no defined `channel_configuration`
1356/// (0, or > 6): those need a `program_config_element`, which we do not yet write.
1357pub(crate) fn element_plan(channels: usize) -> Option<Vec<Elem>> {
1358    Some(match channels {
1359        // config 1 — mono.
1360        1 => vec![Elem::Sce(0)],
1361        // config 2 — stereo.
1362        2 => vec![Elem::Cpe(0, 1)],
1363        // config 3 — 3.0: C, L/R.
1364        3 => vec![Elem::Sce(2), Elem::Cpe(0, 1)],
1365        // config 4 — 4.0: C, L/R, rear centre.
1366        4 => vec![Elem::Sce(2), Elem::Cpe(0, 1), Elem::Sce(3)],
1367        // config 5 — 5.0: C, L/R, Ls/Rs.
1368        5 => vec![Elem::Sce(2), Elem::Cpe(0, 1), Elem::Cpe(3, 4)],
1369        // config 6 — 5.1: C, L/R, Ls/Rs, LFE.
1370        6 => vec![Elem::Sce(2), Elem::Cpe(0, 1), Elem::Cpe(4, 5), Elem::Lfe(3)],
1371        _ => return None,
1372    })
1373}
1374
1375const MAX_QUANT: i32 = 8191;
1376
1377/// Spectral lines an `lfe_channel_element` normally codes: the lowest 12, 281
1378/// Hz at 48 kHz (FFmpeg's encoder codes the same three bands).
1379const LFE_LINES: usize = 12;
1380
1381/// Above [`LFE_LINES`], an LFE frame is coded only when that part carries at
1382/// least this fraction of the frame's energy (-20 dB).
1383const LFE_HIGH_FRACTION: f64 = 0.01;
1384
1385/// Band-limit an LFE frame's spectrum to its lowest [`LFE_LINES`] lines, unless
1386/// the content above them is substantial.
1387///
1388/// The LFE feeds a subwoofer. Coded full band, a 55 Hz tone over -41 dBFS
1389/// broadband noise spent its share on the noise and came back at 15 dB SNR
1390/// instead of 26 (`remade_ffmpeg_rs#129`); the bits it leaves now go to the
1391/// other elements through the frame's pooling. A mix that does route real
1392/// content above 281 Hz to the LFE (more than 1% of its energy) keeps it, so
1393/// the channel still comes back at its level.
1394fn lfe_band_limit(spec: &mut [f32]) {
1395    let energy = |x: &[f32]| x.iter().map(|&v| f64::from(v) * f64::from(v)).sum::<f64>();
1396    let (low, high) = (energy(&spec[..LFE_LINES]), energy(&spec[LFE_LINES..]));
1397    if high < LFE_HIGH_FRACTION * (low + high) {
1398        spec[LFE_LINES..].fill(0.0);
1399    }
1400}
1401
1402/// The per-channel ICS body budget's ceiling: the 6144-bit decoder input buffer
1403/// per channel (ISO 14496-3 §4.5.3) less the element (7) and frame (59) overhead.
1404const MAX_CHANNEL_BITS: usize = 6144 - 7 - 59;
1405
1406/// What TNS can add to a channel's body, which the rate loop does not count:
1407/// 64 bits of `tns_data` (order 12) and the zero sections that hold `max_sfb`
1408/// up (two 9-bit headers), rounded up. Kept free under [`MAX_CHANNEL_BITS`], or
1409/// a block at the buffer's limit came out a byte over it.
1410const TNS_RESERVE_BITS: usize = 96;
1411
1412/// Input samples are clamped to ±8× full scale (NaN becomes silence) at the push
1413/// boundary. Real audio is untouched; hostile values (±Inf, 1e30) would otherwise
1414/// drive every band to maximal escape codes and a block no rate decision can
1415/// shrink below the decoder buffer.
1416pub const MAX_INPUT_AMPLITUDE: f32 = 8.0;
1417
1418#[inline]
1419fn sanitize(x: f32) -> f32 {
1420    if x.is_nan() {
1421        0.0
1422    } else {
1423        x.clamp(-MAX_INPUT_AMPLITUDE, MAX_INPUT_AMPLITUDE)
1424    }
1425}
1426
1427/// Quantize one coefficient at global gain `gg` (the tests' reference).
1428#[cfg(test)]
1429fn quantize(x: f32, gg: i32) -> i32 {
1430    if x == 0.0 {
1431        return 0;
1432    }
1433    let scale = 2f64.powf(-0.1875 * f64::from(gg - 100));
1434    let q = nearest_level(f64::from(x.abs()).powf(0.75) * scale);
1435    if x < 0.0 {
1436        -q
1437    } else {
1438        q
1439    }
1440}
1441
1442/// `2^(-0.1875·(sf-100))`, the quantizer scale, tabulated once over all 256 gains
1443/// so the rate loop never repeats the exponent.
1444fn scale_table() -> &'static [f64; 256] {
1445    static T: OnceLock<[f64; 256]> = OnceLock::new();
1446    T.get_or_init(|| {
1447        let mut t = [0f64; 256];
1448        for (sf, e) in t.iter_mut().enumerate() {
1449            *e = 2f64.powf(-0.1875 * (sf as f64 - 100.0));
1450        }
1451        t
1452    })
1453}
1454
1455/// Per-magnitude coefficient bit cost (half a book-11 pair), tabulated so the rate
1456/// loop's *search* can price a frame in O(n) without the full codebook selection —
1457/// only the exact refinement does the real search.
1458fn coef_bits() -> &'static [u16] {
1459    static T: OnceLock<Vec<u16>> = OnceLock::new();
1460    T.get_or_init(|| {
1461        (0..=MAX_QUANT)
1462            .map(|m| (spectral_bits(ESC_HCB as usize, &[m, m]).unwrap_or(64) / 2) as u16)
1463            .collect()
1464    })
1465}
1466
1467/// Per-coefficient `|x|^0.75` and sign, precomputed once per frame so the rate
1468/// loop can re-quantize at each candidate gain without repeating the 0.75-power
1469/// (the single hottest op after the MDCT). Bit-exact with [`quantize`].
1470struct Xpow {
1471    pow: Vec<f64>,
1472    sign: Vec<i32>,
1473}
1474
1475impl Xpow {
1476    fn new(spec: &[f32]) -> Self {
1477        let _prof = prof::scope(Stage::EncXpow);
1478        // Both arrays are built straight into fresh capacity: every element is
1479        // computed, so the zero fill of a `vec![0; n]` (two per channel per
1480        // frame, 12 KB) was pure overhead.
1481        let n = spec.len();
1482        #[cfg(all(feature = "simd", target_arch = "x86_64"))]
1483        {
1484            if has_avx2() {
1485                let (mut pow, mut sign) = (Vec::with_capacity(n), Vec::with_capacity(n));
1486                // SAFETY: runtime AVX2 check; both buffers have capacity `n`, the
1487                // twin writes all `n` elements of each, and only then is the
1488                // length set.
1489                unsafe {
1490                    xpow_avx2_raw(spec, pow.as_mut_ptr(), sign.as_mut_ptr());
1491                    pow.set_len(n);
1492                    sign.set_len(n);
1493                }
1494                prof::count(Kernel::Xpow, true, n);
1495                return Self { pow, sign };
1496            }
1497        }
1498        prof::count(Kernel::Xpow, false, n);
1499        // |x|^0.75 = |x|^½·|x|^¼ = √|x|·√√|x| — two sqrts vectorize; `powf` doesn't.
1500        // (For x=0, pow=0 so the sign is irrelevant — the quant is 0 either way.)
1501        let pow = spec
1502            .iter()
1503            .map(|&x| {
1504                let s = f64::from(x.abs()).sqrt();
1505                s * s.sqrt()
1506            })
1507            .collect();
1508        let sign = spec.iter().map(|&x| if x < 0.0 { -1 } else { 1 }).collect();
1509        Self { pow, sign }
1510    }
1511
1512    /// Max `|x|^0.75` over `[s, e)` — the no-clamp-floor input (= `(max|x|)^0.75`).
1513    fn max_pow(&self, s: usize, e: usize) -> f64 {
1514        self.pow[s..e].iter().copied().fold(0.0, f64::max)
1515    }
1516
1517    fn len(&self) -> usize {
1518        self.pow.len()
1519    }
1520}
1521
1522/// Codeword lengths of every spectral codebook, packed so ONE walk over a band
1523/// prices all eleven books at once (`codec-eliminate-redundancy` move #4).
1524///
1525/// The books come in pairs that share a tuple index (1/2, 3/4, 5/6, 7/8, 9/10:
1526/// same `dim`, `lav` and signedness, different code lengths), and every
1527/// unsigned dim-2 book (7..=11) can be indexed by the magnitudes clamped to 16.
1528/// So per tuple one index and one or two table loads add every eligible book's
1529/// codeword length into 16-bit lanes of an integer accumulator. A lane can hold
1530/// any band: the longest codeword is 19 bits and a call sees at most 1024 tuples
1531/// (19 456 < 65 536), so lanes never carry into each other.
1532///
1533/// A book whose `lav` cannot hold a tuple stores 0 in its lane there; such a book
1534/// is never consulted, because a band is only priced with books whose `lav`
1535/// covers the band's peak.
1536struct CostTables {
1537    /// Books 1 | 2 << 16 at the signed dim-4 index `27a + 9b + 3c + d + 40`.
1538    s12: [u32; 81],
1539    /// Books 3 | 4 << 16 at the unsigned dim-4 index `27|a| + 9|b| + 3|c| + |d|`.
1540    u34: [u32; 81],
1541    /// Books 5 | 6 << 16 at the signed dim-2 index `9a + b + 40`.
1542    s56: [u32; 81],
1543    /// Books 7 | 8 << 16 | 9 << 32 | 10 << 48 at `17 min(|a|,16) + min(|b|,16)`.
1544    u7_10: [u64; 289],
1545    /// Book 11 at the same index.
1546    u11: [u32; 289],
1547}
1548
1549fn cost_tables() -> &'static CostTables {
1550    static T: OnceLock<CostTables> = OnceLock::new();
1551    T.get_or_init(|| {
1552        let len = |cb: u8, tuple: &[i32]| -> u64 {
1553            tuple_index(&CODEBOOKS[cb as usize], tuple)
1554                .map_or(0, |i| u64::from(spectral_book(cb).code(i as usize).1))
1555        };
1556        let mut t = CostTables {
1557            s12: [0; 81],
1558            u34: [0; 81],
1559            s56: [0; 81],
1560            u7_10: [0; 289],
1561            u11: [0; 289],
1562        };
1563        for i in 0..81i32 {
1564            let d = [i / 27, i / 9 % 3, i / 3 % 3, i % 3];
1565            let signed = d.map(|x| x - 1);
1566            t.s12[i as usize] = (len(1, &signed) | len(2, &signed) << 16) as u32;
1567            t.u34[i as usize] = (len(3, &d) | len(4, &d) << 16) as u32;
1568            let pair = [i / 9 - 4, i % 9 - 4];
1569            t.s56[i as usize] = (len(5, &pair) | len(6, &pair) << 16) as u32;
1570        }
1571        for i in 0..289i32 {
1572            let pair = [i / 17, i % 17];
1573            t.u7_10[i as usize] =
1574                len(7, &pair) | len(8, &pair) << 16 | len(9, &pair) << 32 | len(10, &pair) << 48;
1575            t.u11[i as usize] = len(11, &pair) as u32;
1576        }
1577        t
1578    })
1579}
1580
1581/// Every book's bit cost over the tuples added so far ([`CostTables`] lanes,
1582/// plus the sign bits every unsigned book pays and book 11's escapes), and the
1583/// peak magnitude that decides which books may code the band.
1584#[derive(Default)]
1585struct BandCost {
1586    a12: u32,
1587    a34: u32,
1588    a56: u32,
1589    a7_10: u64,
1590    a11: u32,
1591    /// Non-zero coefficients: one sign bit each in every unsigned book.
1592    nz: u32,
1593    /// Book 11's escape sequences.
1594    esc: u32,
1595    /// The largest magnitude seen.
1596    maxq: u32,
1597}
1598
1599impl BandCost {
1600    /// The dim-2 books over `q` (an even number of coefficients), and the peak.
1601    ///
1602    /// Books 5/6 are indexed by the values clamped to their `lav` so the index is
1603    /// always in range; where a value exceeds 4 the lane is never read (the band's
1604    /// peak then rules books 5/6 out), so the clamp changes no cost that is used.
1605    #[inline(always)]
1606    fn add2(&mut self, t: &CostTables, q: &[i32]) {
1607        for p in q.chunks_exact(2) {
1608            let (a, b) = (p[0].unsigned_abs(), p[1].unsigned_abs());
1609            self.maxq = self.maxq.max(a).max(b);
1610            self.a56 += t.s56[(9 * p[0].clamp(-4, 4) + p[1].clamp(-4, 4) + 40) as usize];
1611            let i = (17 * a.min(16) + b.min(16)) as usize;
1612            self.a7_10 += t.u7_10[i];
1613            self.a11 += t.u11[i];
1614            self.nz += u32::from(a != 0) + u32::from(b != 0);
1615        }
1616    }
1617
1618    /// The dim-4 books over `q` (a multiple of 4 coefficients), only valid once
1619    /// the peak is known to be at most 2 (book 1/2 lanes only at most 1).
1620    #[inline(always)]
1621    fn add4(&mut self, t: &CostTables, q: &[i32]) {
1622        let books12 = self.maxq <= 1;
1623        for c in q.chunks_exact(4) {
1624            if books12 {
1625                let i = 27 * c[0] + 9 * c[1] + 3 * c[2] + c[3] + 40;
1626                self.a12 += t.s12[i as usize];
1627            }
1628            let u = 27 * c[0].unsigned_abs()
1629                + 9 * c[1].unsigned_abs()
1630                + 3 * c[2].unsigned_abs()
1631                + c[3].unsigned_abs();
1632            self.a34 += t.u34[u as usize];
1633        }
1634    }
1635
1636    /// Book 11's escape sequences over `q` (magnitudes of 16 and up).
1637    #[cold]
1638    fn add_esc(&mut self, q: &[i32]) {
1639        for &c in q {
1640            let m = c.unsigned_abs();
1641            if m >= 16 {
1642                self.esc += escape_bits(m) as u32;
1643            }
1644        }
1645    }
1646
1647    /// The cheapest eligible book for a band of `width` coefficients per window,
1648    /// and its bits: books tried in order 1..=11, a later book winning only when
1649    /// strictly cheaper (the per-book search's tie-break). Eligible are the books
1650    /// whose `lav` holds the peak (the `lav`s rise with the book number, so they
1651    /// are a suffix) and whose `dim` divides the width.
1652    fn best(&self, width: usize) -> (u8, usize) {
1653        let cost = self.costs(width);
1654        let mut best = (ESC_HCB, usize::MAX);
1655        for (cb, &bits) in cost.iter().enumerate().skip(1) {
1656            if bits != u32::MAX && (bits as usize) < best.1 {
1657                best = (cb as u8, bits as usize);
1658            }
1659        }
1660        best
1661    }
1662
1663    /// Every book's bits for the band (index 0 unused), `u32::MAX` for a book
1664    /// that cannot code it: the eligibility rule of [`best`](Self::best). The
1665    /// section trellis prices all of them at once (see [`band_book_costs`]).
1666    fn costs(&self, width: usize) -> [u32; 12] {
1667        let lane = |v: u64, k: u32| (v >> (16 * k)) & 0xffff;
1668        let nz = u64::from(self.nz);
1669        let (a12, a34, a56) = (
1670            u64::from(self.a12),
1671            u64::from(self.a34),
1672            u64::from(self.a56),
1673        );
1674        let cost: [u64; 12] = [
1675            0,
1676            lane(a12, 0),
1677            lane(a12, 1),
1678            lane(a34, 0) + nz,
1679            lane(a34, 1) + nz,
1680            lane(a56, 0),
1681            lane(a56, 1),
1682            lane(self.a7_10, 0) + nz,
1683            lane(self.a7_10, 1) + nz,
1684            lane(self.a7_10, 2) + nz,
1685            lane(self.a7_10, 3) + nz,
1686            u64::from(self.a11) + nz + u64::from(self.esc),
1687        ];
1688        let mut first = match self.maxq {
1689            1 => 1,
1690            2 => 3,
1691            3 | 4 => 5,
1692            5..=7 => 7,
1693            8..=12 => 9,
1694            _ => 11,
1695        };
1696        if width % 4 != 0 {
1697            first = first.max(5);
1698        }
1699        let mut out = [u32::MAX; 12];
1700        if width % 2 != 0 {
1701            return out;
1702        }
1703        for cb in first..12 {
1704            out[cb] = u32::try_from(cost[cb]).unwrap_or(u32::MAX - 1);
1705        }
1706        out
1707    }
1708}
1709
1710/// The cheapest representable spectral codebook for one SFB's coefficients, and
1711/// its bit cost. ZERO for a silent band; dim-4 books only for 4-aligned bands.
1712/// Books whose LAV can't hold the band's peak are skipped up front (only the
1713/// escape book covers arbitrarily large values).
1714///
1715/// One walk prices every book ([`BandCost`]). The per-book search it replaced
1716/// ([`best_codebook_for_band_ref`], kept as the test oracle) re-walked the band
1717/// once per candidate book through an out-of-line [`spectral_bits`] per tuple,
1718/// and was 75% of all encoder instructions.
1719fn best_codebook_for_band(quant: &[i32], s: usize, e: usize) -> (u8, usize) {
1720    let q = &quant[s..e];
1721    if q.len() % 2 != 0 {
1722        // No book can code an odd band; only its silence matters (cold: every
1723        // AAC band width is a multiple of 4).
1724        return if q.iter().all(|&v| v == 0) {
1725            (ZERO_HCB, 0)
1726        } else {
1727            (ESC_HCB, usize::MAX)
1728        };
1729    }
1730    let t = cost_tables();
1731    let mut cost = BandCost::default();
1732    cost.add2(t, q);
1733    if cost.maxq == 0 {
1734        return (ZERO_HCB, 0);
1735    }
1736    if cost.maxq <= 2 && q.len() % 4 == 0 {
1737        cost.add4(t, q);
1738    }
1739    if cost.maxq >= 16 {
1740        cost.add_esc(q);
1741    }
1742    cost.best(q.len())
1743}
1744
1745/// The per-book search [`best_codebook_for_band`] replaced: the oracle its tests
1746/// compare against.
1747#[cfg(test)]
1748fn best_codebook_for_band_ref(quant: &[i32], s: usize, e: usize) -> (u8, usize) {
1749    let maxq = quant[s..e]
1750        .iter()
1751        .map(|&q| q.unsigned_abs())
1752        .max()
1753        .unwrap_or(0);
1754    if maxq == 0 {
1755        return (ZERO_HCB, 0);
1756    }
1757    let mut best = (ESC_HCB, usize::MAX);
1758    for cb in 1..=11u8 {
1759        let meta = &CODEBOOKS[cb as usize];
1760        let dim = meta.dim as usize;
1761        if (e - s) % dim != 0 || (!meta.esc && u32::from(meta.lav) < maxq) {
1762            continue;
1763        }
1764        let mut bits = 0usize;
1765        let mut ok = true;
1766        let mut i = s;
1767        while i < e {
1768            if let Some(b) = spectral_bits(cb as usize, &quant[i..i + dim]) {
1769                bits += b;
1770            } else {
1771                ok = false;
1772                break;
1773            }
1774            i += dim;
1775        }
1776        if ok && bits < best.1 {
1777            best = (cb, bits);
1778        }
1779    }
1780    best
1781}
1782
1783/// Bits for `section_data` given per-SFB codebooks (adjacent equal cbs merge into
1784/// one 4-bit codebook + 5-bit run-length increments).
1785fn section_bits(cbs: &[u8]) -> usize {
1786    let esc = 31usize;
1787    let mut bits = 0usize;
1788    let mut k = 0usize;
1789    while k < cbs.len() {
1790        let cb = cbs[k];
1791        let mut len = 1usize;
1792        while k + len < cbs.len() && cbs[k + len] == cb {
1793            len += 1;
1794        }
1795        bits += 4;
1796        let mut l = len;
1797        while l >= esc {
1798            bits += 5;
1799            l -= esc;
1800        }
1801        bits += 5;
1802        k += len;
1803    }
1804    bits
1805}
1806
1807thread_local! {
1808    /// [`AacTuning::section_trellis`] for the frame this thread is
1809    /// coding, set once per frame by `encode_frame` (frames code on worker
1810    /// threads, each frame wholly on one), so the coding kernels need no extra
1811    /// argument for it.
1812    static SECTION_TRELLIS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1813}
1814
1815fn section_trellis_on() -> bool {
1816    SECTION_TRELLIS.with(std::cell::Cell::get)
1817}
1818
1819/// Bits of the scalefactor of an all-zero band carried inside another
1820/// codebook's section: its scalefactor is sent as a zero delta (see
1821/// [`zero_band_sf`]), the one-bit `SCALEFACTOR_BOOK` code.
1822const CARRIED_ZERO_SF_BITS: u32 = 1;
1823
1824/// Spectral bits of one band (one window group of a short frame:
1825/// `nwin` windows of `wlen` lines from `win0`) under every codebook 0..=11;
1826/// `u32::MAX` where the book cannot code it. Book 0 (`ZERO_HCB`) is free for
1827/// an all-zero band and impossible otherwise.
1828fn band_book_costs(
1829    quant: &[i32],
1830    s: usize,
1831    e: usize,
1832    win0: usize,
1833    nwin: usize,
1834    wlen: usize,
1835) -> [u32; 12] {
1836    let mut out = [u32::MAX; 12];
1837    let mut maxq = 0u32;
1838    for w in win0..win0 + nwin {
1839        for &q in &quant[w * wlen + s..w * wlen + e] {
1840            maxq = maxq.max(q.unsigned_abs());
1841        }
1842    }
1843    if maxq == 0 {
1844        // An all-zero band: every book codes it as its zero tuple repeated,
1845        // a per-book constant, so no tuple need be looked up.
1846        out[0] = 0;
1847        let zt = zero_tuple_bits();
1848        let tuples_per = |dim: usize| ((e - s) / dim * nwin) as u32;
1849        for cb in 1..=11usize {
1850            let dim = CODEBOOKS[cb].dim as usize;
1851            if (e - s) % dim == 0 {
1852                out[cb] = tuples_per(dim) * zt[cb] + CARRIED_ZERO_SF_BITS;
1853            }
1854        }
1855        return out;
1856    }
1857    if (e - s) % 2 != 0 {
1858        // Cold: every AAC band width is a multiple of 4.
1859        return band_book_costs_ref(quant, s, e, win0, nwin, wlen);
1860    }
1861    // One walk prices every book, the kernel `best_codebook_for_band` and
1862    // `best_codebook_short` choose from.
1863    let band = |w: usize| &quant[w * wlen + s..w * wlen + e];
1864    let t = cost_tables();
1865    let mut cost = BandCost::default();
1866    for w in win0..win0 + nwin {
1867        cost.add2(t, band(w));
1868    }
1869    if cost.maxq <= 2 && (e - s) % 4 == 0 {
1870        for w in win0..win0 + nwin {
1871            cost.add4(t, band(w));
1872        }
1873    }
1874    if cost.maxq >= 16 {
1875        for w in win0..win0 + nwin {
1876            cost.add_esc(band(w));
1877        }
1878    }
1879    cost.costs(e - s)
1880}
1881
1882/// [`band_book_costs`] for a non-zero band by a per-book search through
1883/// [`spectral_bits`]: the cold path for an odd band width and the oracle of
1884/// the one-walk pricing's test.
1885#[cold]
1886fn band_book_costs_ref(
1887    quant: &[i32],
1888    s: usize,
1889    e: usize,
1890    win0: usize,
1891    nwin: usize,
1892    wlen: usize,
1893) -> [u32; 12] {
1894    let mut out = [u32::MAX; 12];
1895    let maxq = (win0..win0 + nwin)
1896        .flat_map(|w| quant[w * wlen + s..w * wlen + e].iter())
1897        .map(|q| q.unsigned_abs())
1898        .max()
1899        .unwrap_or(0);
1900    for cb in 1..=11u8 {
1901        let meta = &CODEBOOKS[cb as usize];
1902        let dim = meta.dim as usize;
1903        if (e - s) % dim != 0 || (!meta.esc && u32::from(meta.lav) < maxq) {
1904            continue;
1905        }
1906        let mut bits = 0u32;
1907        let mut ok = true;
1908        'w: for w in win0..win0 + nwin {
1909            let base = w * wlen;
1910            let mut i = s;
1911            while i < e {
1912                if let Some(b) = spectral_bits(cb as usize, &quant[base + i..base + i + dim]) {
1913                    bits += b as u32;
1914                } else {
1915                    ok = false;
1916                    break 'w;
1917                }
1918                i += dim;
1919            }
1920        }
1921        if ok {
1922            out[cb as usize] = bits;
1923        }
1924    }
1925    out
1926}
1927
1928/// Bits of each book's all-zero tuple (index 0 unused).
1929fn zero_tuple_bits() -> &'static [u32; 12] {
1930    static T: OnceLock<[u32; 12]> = OnceLock::new();
1931    T.get_or_init(|| {
1932        let mut t = [0u32; 12];
1933        for (cb, b) in t.iter_mut().enumerate().skip(1) {
1934            let dim = CODEBOOKS[cb].dim as usize;
1935            *b = spectral_bits(cb, &[0i32; 4][..dim]).unwrap_or(u32::MAX as usize / 4096) as u32;
1936        }
1937        t
1938    })
1939}
1940
1941/// **Section trellis.** The per-band codebooks of one window group that
1942/// minimise spectral bits plus `section_data`, by a Viterbi over (band,
1943/// codebook): a section costs `hdr` bits (4-bit codebook + one length field),
1944/// so it can pay to code a band with a larger book than its cheapest, or to
1945/// carry an all-zero band inside a neighbouring section, rather than open a
1946/// new section. `costs` is [`band_book_costs`] per band. Length-escape fields
1947/// of long runs are not priced here; the exact count is `section_bits`.
1948fn trellis_books(costs: &[[u32; 12]], hdr: u32) -> Vec<u8> {
1949    const INF: u64 = u64::MAX / 4;
1950    let n = costs.len();
1951    if n == 0 {
1952        return Vec::new();
1953    }
1954    let mut dp = vec![[INF; 12]; n];
1955    let mut from = vec![[0u8; 12]; n];
1956    for cb in 0..12 {
1957        if costs[0][cb] != u32::MAX {
1958            dp[0][cb] = u64::from(hdr) + u64::from(costs[0][cb]);
1959        }
1960    }
1961    for b in 1..n {
1962        // Best predecessor overall (a section break) and per book (a run).
1963        let (mut best, mut arg) = (INF, 0u8);
1964        for p in 0..12 {
1965            if dp[b - 1][p] < best {
1966                best = dp[b - 1][p];
1967                arg = p as u8;
1968            }
1969        }
1970        for cb in 0..12 {
1971            let c = costs[b][cb];
1972            if c == u32::MAX {
1973                continue;
1974            }
1975            let stay = dp[b - 1][cb];
1976            let brk = best.saturating_add(u64::from(hdr));
1977            let (v, f) = if stay <= brk {
1978                (stay, cb as u8)
1979            } else {
1980                (brk, arg)
1981            };
1982            dp[b][cb] = v.saturating_add(u64::from(c));
1983            from[b][cb] = f;
1984        }
1985    }
1986    let mut cb = (0..12).min_by_key(|&c| dp[n - 1][c]).unwrap_or(11) as u8;
1987    let mut out = vec![0u8; n];
1988    for b in (0..n).rev() {
1989        out[b] = cb;
1990        cb = from[b][cb as usize];
1991    }
1992    out
1993}
1994
1995/// Scalefactors in coded order (`cbs` order) with every all-zero band that a
1996/// section carries under a regular codebook (`is_zero(i)`) given the previous
1997/// regular band's scalefactor, or the first one's if none precedes it: a zero
1998/// delta, one bit, and never a step the ±60 delta range cannot code. The
1999/// band's value does not matter to the decoder (its lines are all zero).
2000fn zero_band_sf(cbs: &[u8], sf: &[i32], is_zero: impl Fn(usize) -> bool) -> Vec<i32> {
2001    let mut out = sf.to_vec();
2002    let regular = |i: usize| cbs[i] != ZERO_HCB && cbs[i] < NOISE_HCB;
2003    let first = (0..cbs.len())
2004        .find(|&i| regular(i) && !is_zero(i))
2005        .map(|i| sf[i]);
2006    let mut last = first;
2007    for i in 0..cbs.len() {
2008        if !regular(i) {
2009            continue;
2010        }
2011        if is_zero(i) {
2012            if let Some(v) = last {
2013                out[i] = v;
2014            }
2015        } else {
2016            last = Some(sf[i]);
2017        }
2018    }
2019    out
2020}
2021
2022/// Long-block codebooks for `quant` over `0..max_sfb`: the cheapest book per
2023/// band, or the [`trellis_books`] choice when the section trellis is on.
2024fn long_books(quant: &[i32], swb: &[u16], max_sfb: usize) -> (Vec<u8>, usize) {
2025    if section_trellis_on() {
2026        let costs: Vec<[u32; 12]> = (0..max_sfb)
2027            .map(|b| {
2028                band_book_costs(
2029                    quant,
2030                    usize::from(swb[b]),
2031                    usize::from(swb[b + 1]),
2032                    0,
2033                    1,
2034                    FRAME_LEN,
2035                )
2036            })
2037            .collect();
2038        let cbs = trellis_books(&costs, 9);
2039        let bits = cbs
2040            .iter()
2041            .zip(&costs)
2042            .map(|(&c, k)| k[c as usize] as usize)
2043            .sum();
2044        return (cbs, bits);
2045    }
2046    let mut cbs = Vec::with_capacity(max_sfb);
2047    let mut spec_bits = 0usize;
2048    for sfb in 0..max_sfb {
2049        let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
2050        let (cb, bits) = best_codebook_for_band(quant, s, e);
2051        cbs.push(cb);
2052        spec_bits += bits;
2053    }
2054    (cbs, spec_bits)
2055}
2056
2057/// Short-block codebooks for one window group (windows `w0..w0+nwin`), as
2058/// [`long_books`].
2059fn short_books(
2060    quant: &[i32],
2061    swb: &[u16],
2062    max_sfb: usize,
2063    w0: usize,
2064    nwin: usize,
2065) -> (Vec<u8>, usize) {
2066    if section_trellis_on() {
2067        let costs: Vec<[u32; 12]> = (0..max_sfb)
2068            .map(|b| {
2069                band_book_costs(
2070                    quant,
2071                    usize::from(swb[b]),
2072                    usize::from(swb[b + 1]),
2073                    w0,
2074                    nwin,
2075                    SHORT_HALF,
2076                )
2077            })
2078            .collect();
2079        let cbs = trellis_books(&costs, 7);
2080        let bits = cbs
2081            .iter()
2082            .zip(&costs)
2083            .map(|(&c, k)| k[c as usize] as usize)
2084            .sum();
2085        return (cbs, bits);
2086    }
2087    let mut cbs = Vec::with_capacity(max_sfb);
2088    let mut bits = 0usize;
2089    for sfb in 0..max_sfb {
2090        let (cb, b) = best_codebook_short(quant, swb, sfb, w0, nwin);
2091        cbs.push(cb);
2092        bits += b;
2093    }
2094    (cbs, bits)
2095}
2096
2097/// Is band `sfb` of window group (`w0`, `nwin`) all zero in `quant`?
2098fn band_is_zero(
2099    quant: &[i32],
2100    swb: &[u16],
2101    sfb: usize,
2102    w0: usize,
2103    nwin: usize,
2104    wlen: usize,
2105) -> bool {
2106    let (s, e) = (usize::from(swb[sfb]), usize::from(swb[sfb + 1]));
2107    (w0..w0 + nwin).all(|w| quant[w * wlen + s..w * wlen + e].iter().all(|&q| q == 0))
2108}
2109
2110/// [`zero_band_sf`] for a long block's (`cbs`, `sf`, `quant`).
2111fn zero_band_sf_long(cbs: &[u8], sf: &[i32], quant: &[i32], swb: &[u16]) -> Vec<i32> {
2112    zero_band_sf(cbs, sf, |i| band_is_zero(quant, swb, i, 0, 1, FRAME_LEN))
2113}
2114
2115/// [`zero_band_sf`] for a short block's group-major (`cbs`, `sf_flat`).
2116fn zero_band_sf_short(
2117    cbs: &[u8],
2118    sf_flat: &[i32],
2119    quant: &[i32],
2120    swb: &[u16],
2121    groups: &[u8],
2122    max_sfb: usize,
2123) -> Vec<i32> {
2124    if max_sfb == 0 {
2125        return sf_flat.to_vec();
2126    }
2127    let starts: Vec<(usize, usize)> = group_windows(groups).collect();
2128    zero_band_sf(cbs, sf_flat, |i| {
2129        let (g, sfb) = (i / max_sfb, i % max_sfb);
2130        band_is_zero(quant, swb, sfb, starts[g].0, starts[g].1, SHORT_HALF)
2131    })
2132}
2133
2134/// Per-band scalefactors from a common `base` plus the psy offsets (see
2135/// [`Offsets::sf`]), each clamped to the codeable range.
2136fn scalefactors(offsets: &Offsets, base: i32) -> Vec<i32> {
2137    offsets.sf(base)
2138}
2139
2140/// `global_gain` = the first coded band's scalefactor (the differential reference);
2141/// 100 for a silent frame with no coded bands.
2142fn global_gain(cbs: &[u8], sf: &[i32]) -> i32 {
2143    // Only a REGULAR band seeds the differential chain. A PNS band's `sf` is a
2144    // noise-energy value on its own accumulator and an intensity band's is a
2145    // stereo position — seeding global_gain from either desynchronizes every
2146    // scalefactor that follows.
2147    cbs.iter()
2148        .position(|&cb| cb != ZERO_HCB && cb < NOISE_HCB)
2149        .map_or(100, |sfb| sf[sfb])
2150}
2151
2152/// Bits to code the per-band scalefactors as `SCALEFACTOR_BOOK` deltas from a
2153/// running accumulator seeded at `gg`.
2154fn scalefactor_bits(cbs: &[u8], sf: &[i32], gg: i32) -> usize {
2155    let mut acc = gg;
2156    let mut noise = gg - 90;
2157    let mut noise_pcm = true;
2158    let mut is_pos = 0i32;
2159    let mut bits = 0usize;
2160    for (sfb, &cb) in cbs.iter().enumerate() {
2161        if cb == ZERO_HCB {
2162            continue;
2163        }
2164        if cb >= crate::codebook::INTENSITY_HCB2 {
2165            let d = (sf[sfb] - is_pos).clamp(-60, 60);
2166            bits += crate::tables::SCALEFACTOR_BOOK.code((d + 60) as usize).1 as usize;
2167            is_pos += d;
2168        } else if cb == NOISE_HCB {
2169            if noise_pcm {
2170                noise_pcm = false;
2171                let d = (sf[sfb] - noise).clamp(-256, 255);
2172                bits += 9;
2173                noise += d;
2174            } else {
2175                let d = (sf[sfb] - noise).clamp(-60, 60);
2176                bits += crate::tables::SCALEFACTOR_BOOK.code((d + 60) as usize).1 as usize;
2177                noise += d;
2178            }
2179        } else {
2180            let d = (sf[sfb] - acc).clamp(-60, 60);
2181            bits += crate::tables::SCALEFACTOR_BOOK.code((d + 60) as usize).1 as usize;
2182            acc += d;
2183        }
2184    }
2185    bits
2186}
2187
2188/// Runtime AVX2 availability (detected once).
2189#[cfg(all(feature = "simd", target_arch = "x86_64"))]
2190fn has_avx2() -> bool {
2191    static AVX2: OnceLock<bool> = OnceLock::new();
2192    *AVX2.get_or_init(|| std::is_x86_feature_detected!("avx2"))
2193}
2194
2195#[cfg(all(feature = "simd-avx512", target_arch = "x86_64"))]
2196fn has_avx512() -> bool {
2197    static AVX512: OnceLock<bool> = OnceLock::new();
2198    *AVX512.get_or_init(|| std::is_x86_feature_detected!("avx512f"))
2199}
2200
2201/// Where `|x|^0.75·scale` stops coding as 0 and becomes 1 is `0.5^0.75 =
2202/// 0.5946`, the point whose reconstruction `x = q^(4/3)` is equally far from 0
2203/// and from 1. Below [`NEAREST_T1`] the quantizer adds this, `1 - 0.5^0.75`,
2204/// before flooring, so 0.5946 becomes 1.
2205const NEAREST_BIAS: f64 = 0.405_396_442_498_639_5;
2206/// The point between 1 and 2: `((1 + 2^(4/3)) / 2)^0.75`. Flooring with
2207/// [`NEAREST_BIAS`] keeps everything under it at 1.
2208const NEAREST_T1: f64 = 1.527_987_809_325_255;
2209
2210/// The quantizer level whose reconstruction is nearest the input, for
2211/// `v = |x|^0.75·scale >= 0`, clamped to `MAX_QUANT`.
2212///
2213/// The decoder rebuilds `|x| = q^(4/3)` (times the step), so rounding `v` to
2214/// the nearest integer is not rounding `x` to the nearest level: every `v` in
2215/// `[0.5, 0.595)` codes as 1 and comes back up to 2.5x too loud, and every `v`
2216/// in `[1.5, 1.528)` codes as 2. At coarse steps, which a starved channel runs
2217/// at (a 5.1 stream at 320 kbps is 53 kbps a channel), those levels carry most
2218/// of the signal, and round-half-up made whole channels 2-4 dB louder than
2219/// their input (`remade_ffmpeg_rs#129`). Above 2 the midpoints sit within
2220/// 0.017 of `k + 0.5`, so plain rounding is kept there.
2221#[inline]
2222fn nearest_level(v: f64) -> i32 {
2223    if v < NEAREST_T1 {
2224        (v + NEAREST_BIAS).floor() as i32
2225    } else {
2226        (v.round() as i32).min(MAX_QUANT)
2227    }
2228}
2229
2230/// Quantize one band into `out`: `out[k] = sign[k]·nearest_level(pow[k]·scale)`.
2231/// This is the encoder's hottest kernel — the rate loop runs it ~11× per frame — so it
2232/// has an AVX2 path. AVX2 has no round-half-away-from-zero, so the twins use
2233/// `floor(v + HALF_DOWN)` with `HALF_DOWN` the double just below ½: for `v ≥ 0` that
2234/// equals `round(v)` exactly. (`floor(v + 0.5)` does NOT — at the double just below ½
2235/// the sum rounds up to 1.0 — which `quantize_simd_matches_scalar` pins.) Below
2236/// [`NEAREST_T1`] the twins add [`NEAREST_BIAS`] instead, one compare-and-blend.
2237fn quantize_band(pow: &[f64], sign: &[i32], scale: f64, out: &mut [i32]) {
2238    // The twins read `pow`/`sign` for every index of `out`; re-slicing here makes
2239    // that bound local (a short input panics instead of reading past its end).
2240    let (pow, sign) = (&pow[..out.len()], &sign[..out.len()]);
2241    #[cfg(all(feature = "simd-avx512", target_arch = "x86_64"))]
2242    if has_avx512() {
2243        // SAFETY: AVX-512F + AVX2 detected at runtime; the three slices have the
2244        // same length (re-sliced above), which is all `quantize_band_avx512` needs.
2245        unsafe { quantize_band_avx512(pow, sign, scale, out) };
2246        prof::count(Kernel::Quantize, true, out.len());
2247        return;
2248    }
2249    #[cfg(all(feature = "simd", target_arch = "x86_64"))]
2250    if has_avx2() {
2251        // SAFETY: AVX2 detected at runtime; the three slices have the same length
2252        // (re-sliced above), which is all `quantize_band_avx2` needs.
2253        unsafe { quantize_band_avx2(pow, sign, scale, out) };
2254        prof::count(Kernel::Quantize, true, out.len());
2255        return;
2256    }
2257    prof::count(Kernel::Quantize, false, out.len());
2258    quantize_band_scalar(pow, sign, scale, out);
2259}
2260
2261/// The largest double below ½ (`0.5 − 2⁻⁵⁴`). Adding it then flooring rounds half
2262/// away from zero for non-negative input without the 0.49999999999999994 overshoot.
2263#[cfg(all(feature = "simd", target_arch = "x86_64"))]
2264const HALF_DOWN: f64 = 0.499_999_999_999_999_94;
2265
2266fn quantize_band_scalar(pow: &[f64], sign: &[i32], scale: f64, out: &mut [i32]) {
2267    for k in 0..out.len() {
2268        out[k] = sign[k] * nearest_level(pow[k] * scale);
2269    }
2270}
2271
2272/// AVX2 quantize — four coefficients per iteration. Bit-exact with the scalar path
2273/// (`floor(v + HALF_DOWN) == round(v)` for `v ≥ 0`, and `floor(v + NEAREST_BIAS)`
2274/// below [`NEAREST_T1`], exactly the scalar's two cases; the clamp is applied
2275/// before the f64→i32 narrowing so nothing overflows).
2276///
2277/// # Safety
2278///
2279/// AVX2 must be available, and `pow.len()` and `sign.len()` must be at least
2280/// `out.len()`: the vector body reads `pow[i..i + 4]` / `sign[i..i + 4]` and
2281/// writes `out[i..i + 4]` for `i + 4 <= out.len()`; the tail is safe indexing.
2282#[cfg(all(feature = "simd", target_arch = "x86_64"))]
2283#[target_feature(enable = "avx2")]
2284#[inline]
2285unsafe fn quantize_band_avx2(pow: &[f64], sign: &[i32], scale: f64, out: &mut [i32]) {
2286    use std::arch::x86_64::*;
2287    let n = out.len();
2288    let vscale = _mm256_set1_pd(scale);
2289    let vhalf = _mm256_set1_pd(HALF_DOWN);
2290    let vmax = _mm256_set1_pd(f64::from(MAX_QUANT));
2291    let (vt1, vbias) = (_mm256_set1_pd(NEAREST_T1), _mm256_set1_pd(NEAREST_BIAS));
2292    let mut i = 0;
2293    while i + 4 <= n {
2294        let v = _mm256_mul_pd(_mm256_loadu_pd(pow.as_ptr().add(i)), vscale);
2295        let add = _mm256_blendv_pd(vhalf, vbias, _mm256_cmp_pd::<_CMP_LT_OQ>(v, vt1));
2296        let r = _mm256_floor_pd(_mm256_add_pd(v, add)); // = nearest_level(v) for v ≥ 0
2297        let qabs = _mm256_cvttpd_epi32(_mm256_min_pd(r, vmax)); // clamp then f64→i32
2298        let s = _mm_loadu_si128(sign.as_ptr().add(i).cast::<__m128i>());
2299        _mm_storeu_si128(
2300            out.as_mut_ptr().add(i).cast::<__m128i>(),
2301            _mm_mullo_epi32(qabs, s),
2302        );
2303        i += 4;
2304    }
2305    while i < n {
2306        out[i] = sign[i] * nearest_level(pow[i] * scale);
2307        i += 1;
2308    }
2309}
2310
2311/// AVX-512 quantize — eight coefficients per iteration (2× the AVX2 width). Bit-exact:
2312/// for the quantizer's always-nonnegative input, `trunc(min(v+HALF_DOWN, MAX+0.5))`
2313/// equals `min(round(v), MAX)`, so a single truncating narrow does round+clamp;
2314/// below [`NEAREST_T1`] the addend is [`NEAREST_BIAS`] instead (a masked blend).
2315/// Runtime-gated above AVX2; on AVX2-only hosts this path never runs (untested there —
2316/// the math mirrors the AVX2 kernel exactly, and its tail is the shared scalar reference).
2317///
2318/// # Safety
2319///
2320/// AVX-512F and AVX2 must be available, and `pow.len()` and `sign.len()` must be
2321/// at least `out.len()`: eight lanes per trip for `i + 8 <= out.len()`, then
2322/// the safe scalar tail.
2323#[cfg(all(feature = "simd-avx512", target_arch = "x86_64"))]
2324#[target_feature(enable = "avx512f,avx2")]
2325#[allow(
2326    clippy::incompatible_msrv,
2327    reason = "the opt-in `simd-avx512` feature needs Rust 1.89 (stable AVX-512 intrinsics); the crate's 1.85 MSRV holds for every other feature set (README)"
2328)]
2329unsafe fn quantize_band_avx512(pow: &[f64], sign: &[i32], scale: f64, out: &mut [i32]) {
2330    use std::arch::x86_64::*;
2331    let n = out.len();
2332    let vscale = _mm512_set1_pd(scale);
2333    let vhalf = _mm512_set1_pd(HALF_DOWN);
2334    let vmaxph = _mm512_set1_pd(f64::from(MAX_QUANT) + 0.5); // clamp v+0.5 so trunc yields MAX
2335    let (vt1, vbias) = (_mm512_set1_pd(NEAREST_T1), _mm512_set1_pd(NEAREST_BIAS));
2336    let mut i = 0;
2337    while i + 8 <= n {
2338        let v = _mm512_mul_pd(_mm512_loadu_pd(pow.as_ptr().add(i)), vscale);
2339        let add = _mm512_mask_blend_pd(_mm512_cmp_pd_mask::<_CMP_LT_OQ>(v, vt1), vhalf, vbias);
2340        let c = _mm512_min_pd(_mm512_add_pd(v, add), vmaxph);
2341        let qabs = _mm512_cvttpd_epi32(c); // 8 f64 → 8 i32; trunc = floor for c ≥ 0
2342        let s = _mm256_loadu_si256(sign.as_ptr().add(i).cast::<__m256i>());
2343        _mm256_storeu_si256(
2344            out.as_mut_ptr().add(i).cast::<__m256i>(),
2345            _mm256_mullo_epi32(qabs, s),
2346        );
2347        i += 8;
2348    }
2349    while i < n {
2350        out[i] = sign[i] * nearest_level(pow[i] * scale);
2351        i += 1;
2352    }
2353}
2354
2355/// AVX2 `Xpow` builder: `pow[i] = |x|^0.75` via `√|x|·√√|x|` (two vector sqrts), and
2356/// `sign[i] = ±1` from the sign bit — four coefficients per iteration.
2357///
2358/// # Safety
2359///
2360/// AVX2 must be available (the lengths are asserted).
2361#[cfg(all(feature = "simd", target_arch = "x86_64"))]
2362#[target_feature(enable = "avx2")]
2363#[cfg(test)]
2364unsafe fn xpow_avx2(spec: &[f32], pow: &mut [f64], sign: &mut [i32]) {
2365    assert!(pow.len() >= spec.len() && sign.len() >= spec.len());
2366    xpow_avx2_raw(spec, pow.as_mut_ptr(), sign.as_mut_ptr());
2367}
2368
2369/// [`xpow_avx2`] through raw pointers, so `Xpow::new` can fill uninitialised
2370/// capacity.
2371///
2372/// # Safety
2373/// AVX2 must be available, and `pow` / `sign` must be valid for `spec.len()`
2374/// writes; every one of those elements is written.
2375#[cfg(all(feature = "simd", target_arch = "x86_64"))]
2376#[target_feature(enable = "avx2")]
2377unsafe fn xpow_avx2_raw(spec: &[f32], pow: *mut f64, sign: *mut i32) {
2378    use std::arch::x86_64::*;
2379    let n = spec.len();
2380    let absmask = _mm256_castsi256_pd(_mm256_set1_epi64x(0x7fff_ffff_ffff_ffffu64 as i64));
2381    let one = _mm256_set1_pd(1.0);
2382    let mut i = 0;
2383    while i + 4 <= n {
2384        let x = _mm256_cvtps_pd(_mm_loadu_ps(spec.as_ptr().add(i))); // 4 f32 → 4 f64
2385        let a = _mm256_and_pd(x, absmask); // |x|
2386        let s = _mm256_sqrt_pd(a); // |x|^½
2387        _mm256_storeu_pd(pow.add(i), _mm256_mul_pd(s, _mm256_sqrt_pd(s)));
2388        // ±1.0 carrying x's sign bit → i32 (x=0 gives +1; harmless, pow is 0).
2389        let signed = _mm256_or_pd(one, _mm256_andnot_pd(absmask, x));
2390        _mm_storeu_si128(sign.add(i).cast::<__m128i>(), _mm256_cvttpd_epi32(signed));
2391        i += 4;
2392    }
2393    while i < n {
2394        let s = f64::from(spec[i].abs()).sqrt();
2395        pow.add(i).write(s * s.sqrt());
2396        sign.add(i).write(if spec[i] < 0.0 { -1 } else { 1 });
2397        i += 1;
2398    }
2399}
2400
2401/// **Deterministic work counters** (feature `lab`) — the PRIMARY evidence for any
2402/// gate's speed half, per `codec-measurement` §15.
2403///
2404/// A counter is immune to scheduler drift, needs one run, and SIZES the effect;
2405/// a clock at these magnitudes cannot be promoted to a verdict no matter how many
2406/// pairs it gets. The gate-calculator's `work` column is fed from here.
2407///
2408/// Counts the rate loop's exact-coder evaluations — the encoder's dominant inner
2409/// cost and precisely the quantity a psy arm moves, because changing the offsets
2410/// changes how many bases the loop must try.
2411#[cfg(feature = "lab")]
2412pub mod work {
2413    use std::sync::atomic::{AtomicU64, Ordering};
2414
2415    // GLOBAL, not thread-local. `encode_stream` fans frames out across worker
2416    // threads, so a thread-local counter is drained on the main thread AFTER the
2417    // workers have exited and reads **zero** — which is exactly what the first
2418    // harvest reported (`WORK NULL: 0 vs 0`). A counter that reads flat is a
2419    // defect report, not reassurance (`codec-measurement`, order of instruments).
2420    static CODE_FRAME_EVALS: AtomicU64 = AtomicU64::new(0);
2421    static QUANT_BANDS: AtomicU64 = AtomicU64::new(0);
2422
2423    #[inline]
2424    pub(crate) fn bump_code_frame() {
2425        CODE_FRAME_EVALS.fetch_add(1, Ordering::Relaxed);
2426    }
2427
2428    #[inline]
2429    pub(crate) fn bump_quant_bands(n: u64) {
2430        QUANT_BANDS.fetch_add(n, Ordering::Relaxed);
2431    }
2432
2433    /// Read and clear both counters.
2434    ///
2435    /// `Relaxed` is sufficient: these are pure counters, never used to order
2436    /// other memory, and the harvest reads them only after `finish()` has joined
2437    /// every worker — so the joins provide the happens-before edge.
2438    pub fn take() -> (u64, u64) {
2439        (
2440            CODE_FRAME_EVALS.swap(0, Ordering::Relaxed),
2441            QUANT_BANDS.swap(0, Ordering::Relaxed),
2442        )
2443    }
2444}
2445
2446#[cfg(not(feature = "lab"))]
2447mod work {
2448    #[inline]
2449    pub(crate) fn bump_code_frame() {}
2450    #[inline]
2451    pub(crate) fn bump_quant_bands(_: u64) {}
2452}
2453
2454/// Shared coder body: quantize the frame into the caller-owned `quant` (per-band
2455/// scalefactors `sf`, which cover the whole spectrum so no pre-zeroing is needed),
2456/// pick per-band codebooks, and return (codebooks, ICS body bits, `max_sfb`). Splitting
2457/// this out lets the rate loop reuse one buffer instead of allocating per candidate.
2458fn code_core(xp: &Xpow, swb: &[u16], sf: &[i32], quant: &mut [i32]) -> (Vec<u8>, usize, usize) {
2459    work::bump_code_frame();
2460    let num_swb = swb.len() - 1;
2461    work::bump_quant_bands((swb.len() - 1) as u64);
2462    let prof_q = prof::scope(Stage::EncQuant);
2463    quantize_frame(xp, swb, sf, quant);
2464    drop(prof_q);
2465    let _prof_cb = prof::scope(Stage::EncCodebook);
2466    let mut max_sfb = 0usize;
2467    for sfb in 0..num_swb {
2468        let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
2469        if quant[s..e].iter().any(|&q| q != 0) {
2470            max_sfb = sfb + 1;
2471        }
2472    }
2473    let (cbs, spec_bits) = long_books(quant, swb, max_sfb);
2474    let sf_bits = if section_trellis_on() {
2475        let sfz = zero_band_sf_long(&cbs, sf, quant, swb);
2476        scalefactor_bits(&cbs, &sfz, global_gain(&cbs, &sfz))
2477    } else {
2478        scalefactor_bits(&cbs, sf, global_gain(&cbs, sf))
2479    };
2480    // global_gain(8) + ics_info(~11) + 3 flag bits + sections + scalefactors + spectrum.
2481    let body = 8 + 11 + 3 + section_bits(&cbs) + sf_bits + spec_bits;
2482    (cbs, body, max_sfb)
2483}
2484
2485/// Quantize every band of a long frame at its scalefactor into `quant`, each
2486/// band exactly as [`quantize_band`] does. One ISA dispatch per frame: with
2487/// AVX2 the band loop runs inside [`quantize_bands_avx2`], so the per-band
2488/// dispatch, call and constant setup (the rate loop quantizes ~690K bands per
2489/// 18 s of stereo) are paid once.
2490fn quantize_frame(xp: &Xpow, swb: &[u16], sf: &[i32], quant: &mut [i32]) {
2491    let scale = scale_table();
2492    let num_swb = swb.len() - 1;
2493    #[cfg(all(feature = "simd", target_arch = "x86_64"))]
2494    {
2495        // The opt-in AVX-512 kernel stays on the per-band path.
2496        #[cfg(feature = "simd-avx512")]
2497        let avx512 = has_avx512();
2498        #[cfg(not(feature = "simd-avx512"))]
2499        let avx512 = false;
2500        if !avx512 && has_avx2() {
2501            // SAFETY: AVX2 detected at runtime; `quantize_bands_avx2` cuts each
2502            // band out of `pow`, `sign` and `quant` with checked slicing, so
2503            // every kernel call gets three slices of one length.
2504            unsafe { quantize_bands_avx2(&xp.pow, &xp.sign, swb, sf, scale, quant) };
2505            prof::count(Kernel::Quantize, true, usize::from(swb[num_swb] - swb[0]));
2506            return;
2507        }
2508    }
2509    for sfb in 0..num_swb {
2510        let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
2511        let sc = scale[sf[sfb].clamp(0, 255) as usize];
2512        quantize_band(&xp.pow[s..e], &xp.sign[s..e], sc, &mut quant[s..e]);
2513    }
2514}
2515
2516/// The band loop of [`quantize_frame`] compiled for AVX2, so
2517/// [`quantize_band_avx2`] inlines into it.
2518///
2519/// # Safety
2520///
2521/// AVX2 must be available. Bounds are checked: each band is sliced out of
2522/// `pow`, `sign` and `out` with safe indexing before the kernel sees it.
2523#[cfg(all(feature = "simd", target_arch = "x86_64"))]
2524#[target_feature(enable = "avx2")]
2525unsafe fn quantize_bands_avx2(
2526    pow: &[f64],
2527    sign: &[i32],
2528    swb: &[u16],
2529    sf: &[i32],
2530    scale: &[f64; 256],
2531    out: &mut [i32],
2532) {
2533    for sfb in 0..swb.len() - 1 {
2534        let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
2535        let sc = scale[sf[sfb].clamp(0, 255) as usize];
2536        quantize_band_avx2(&pow[s..e], &sign[s..e], sc, &mut out[s..e]);
2537    }
2538}
2539
2540/// Owned-buffer wrapper over [`code_core`] for the one-shot callers (final coding).
2541fn code_frame(xp: &Xpow, swb: &[u16], sf: &[i32]) -> (Vec<u8>, usize, usize, Vec<i32>) {
2542    let mut quant = vec![0i32; xp.len()];
2543    let (cbs, body, max_sfb) = code_core(xp, swb, sf, &mut quant);
2544    (cbs, body, max_sfb, quant)
2545}
2546
2547/// The smallest common `base` such that no band clamps its loudest coefficient
2548/// past `MAX_QUANT` (each band's own no-clamp floor, minus that band's offset).
2549///
2550/// Under the surplus policy every band stops at its own floor instead, so the
2551/// search may run on until the last band reaches it (a negative base, since
2552/// the bands with low masks lag the base).
2553fn min_base(xp: &Xpow, swb: &[u16], offsets: &Offsets) -> i32 {
2554    if let Some(su) = &offsets.surplus {
2555        return su
2556            .floor
2557            .iter()
2558            .zip(&su.gap)
2559            .zip(offsets.iter())
2560            .map(|((&f, &g), &o)| f.max(0) - o - (g + 1) / 2)
2561            .min()
2562            .unwrap_or(0)
2563            .min(255);
2564    }
2565    let num_swb = swb.len() - 1;
2566    let mut floor = 0i32;
2567    for sfb in 0..num_swb {
2568        let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
2569        let maxp = xp.max_pow(s, e); // = (max|x|)^0.75
2570        if maxp <= 1e-9 {
2571            continue;
2572        }
2573        let min_sf = (100.0 - (f64::from(MAX_QUANT) / maxp).log2() / 0.1875).ceil() as i32;
2574        floor = floor.max(min_sf - offsets[sfb]);
2575    }
2576    floor.clamp(0, 255)
2577}
2578
2579/// Fast body-bit estimate at a candidate `base`: quantize (cheap) and price each
2580/// coefficient from the `coef_bits` table — no codebook search. Monotone in `base`,
2581/// so it seeds the search; the exact refinement corrects it.
2582fn estimate_bits(xp: &Xpow, swb: &[u16], offsets: &Offsets, base: i32) -> usize {
2583    let _prof = prof::scope(Stage::EncEstimate);
2584    let scale = scale_table();
2585    let sf = offsets.sf(base);
2586    let ct = coef_bits();
2587    let num_swb = swb.len() - 1;
2588    let mut bits = 22usize; // global_gain + ics_info + flags, approx
2589    let mut qbuf = [0i32; 128]; // one band (max long SWB width is 96)
2590    for sfb in 0..num_swb {
2591        let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
2592        let w = e - s;
2593        let sc = scale[sf[sfb] as usize];
2594        quantize_band(&xp.pow[s..e], &xp.sign[s..e], sc, &mut qbuf[..w]);
2595        let mut band = 0usize;
2596        let mut nonzero = false;
2597        for &q in &qbuf[..w] {
2598            let m = q.unsigned_abs() as usize;
2599            if m != 0 {
2600                nonzero = true;
2601                band += ct[m] as usize;
2602            }
2603        }
2604        if nonzero {
2605            bits += 9 + band; // ~section + scalefactor + spectrum for the band
2606        }
2607    }
2608    bits
2609}
2610
2611/// The smallest common `base` (≥ the no-clamp floor) whose ICS body fits
2612/// `target_bits` — finest quality within budget. A fast estimate seeds the search;
2613/// the exact coder then walks to the true boundary (identical to a full search, but
2614/// only a couple of exact evaluations instead of eight). Body bits fall as `base`
2615/// rises.
2616#[cfg(test)]
2617fn rate_loop(xp: &Xpow, swb: &[u16], offsets: &Offsets, target_bits: usize) -> i32 {
2618    rate_loop_coded(xp, swb, offsets, target_bits).0
2619}
2620
2621/// A frame as [`code_frame`] returns it: (codebooks, ICS body bits, `max_sfb`,
2622/// quantized spectrum).
2623type Coded = (Vec<u8>, usize, usize, Vec<i32>);
2624
2625/// [`rate_loop`], also returning the frame coded at the chosen base: the
2626/// search's last fitting evaluation is that coding, so the caller need not
2627/// code the frame again (it used to, one exact evaluation in three or four).
2628fn rate_loop_coded(
2629    xp: &Xpow,
2630    swb: &[u16],
2631    offsets: &Offsets,
2632    target_bits: usize,
2633) -> (i32, Vec<i32>, Coded) {
2634    let min_b = min_base(xp, swb, offsets);
2635    // Phase 1: binary-search the cheap estimate.
2636    let max_level = offsets.max_level();
2637    let (mut lo, mut hi) = (min_b, max_level);
2638    while lo < hi {
2639        let mid = (lo + hi).div_euclid(2);
2640        if estimate_bits(xp, swb, offsets, mid) <= target_bits {
2641            hi = mid;
2642        } else {
2643            lo = mid + 1;
2644        }
2645    }
2646    // Phase 2: refine to the exact smallest fitting base with the real coder, reusing
2647    // one quant buffer across the (few) exact evaluations and keeping the last
2648    // fitting one (always the returned base's, when the search evaluated it).
2649    let mut quant = vec![0i32; xp.len()];
2650    let mut best: Option<(i32, Coded)> = None;
2651    let mut exact = |b: i32| {
2652        let sf = scalefactors(offsets, b);
2653        let (cbs, body, max_sfb) = code_core(xp, swb, &sf, &mut quant);
2654        let fits = body <= target_bits;
2655        if fits {
2656            let keep = std::mem::take(&mut quant);
2657            quant = best
2658                .take()
2659                .map_or_else(|| vec![0i32; xp.len()], |(_, old)| old.3);
2660            best = Some((b, (cbs, body, max_sfb, keep)));
2661        }
2662        fits
2663    };
2664    let mut base = lo;
2665    if exact(base) {
2666        while base > min_b && exact(base - 1) {
2667            base -= 1;
2668        }
2669    } else {
2670        while base < max_level && !exact(base) {
2671            base += 1;
2672        }
2673    }
2674    let sf = scalefactors(offsets, base);
2675    match best {
2676        Some((b, coded)) if b == base => (base, sf, coded),
2677        _ => {
2678            let coded = code_frame(xp, swb, &sf);
2679            (base, sf, coded)
2680        }
2681    }
2682}
2683
2684/// `section_data` (single group, long block): 4-bit codebook + 5-bit run-length
2685/// increments (esc = 31 continues the run).
2686fn write_sections(w: &mut BitWriter, cbs: &[u8]) {
2687    let esc = 31u32;
2688    let mut k = 0usize;
2689    while k < cbs.len() {
2690        let cb = cbs[k];
2691        let mut len = 1usize;
2692        while k + len < cbs.len() && cbs[k + len] == cb {
2693            len += 1;
2694        }
2695        w.write(u32::from(cb), 4);
2696        let mut l = len as u32;
2697        while l >= esc {
2698            w.write(esc, 5);
2699            l -= esc;
2700        }
2701        w.write(l, 5);
2702        k += len;
2703    }
2704}
2705
2706/// `scale_factor_data`: each coded band's scalefactor as a `SCALEFACTOR_BOOK` delta
2707/// from a running accumulator seeded at `gg` (matching the decoder).
2708fn write_scalefactors(w: &mut BitWriter, cbs: &[u8], sf: &[i32], gg: i32) {
2709    // THREE independent accumulators, exactly as `decode::read_scalefactors`
2710    // maintains them. Folding PNS or intensity values into the regular chain
2711    // desynchronizes every later band, which decodes as garbage rather than as a
2712    // slightly wrong gain.
2713    let mut acc = gg;
2714    let mut noise = gg - 90;
2715    let mut noise_pcm = true;
2716    let mut is_pos = 0i32;
2717    for (sfb, &cb) in cbs.iter().enumerate() {
2718        if cb == ZERO_HCB {
2719            continue;
2720        }
2721        if cb >= crate::codebook::INTENSITY_HCB2 {
2722            let d = (sf[sfb] - is_pos).clamp(-60, 60);
2723            let (code, len) = crate::tables::SCALEFACTOR_BOOK.code((d + 60) as usize);
2724            w.write(code, u32::from(len));
2725            is_pos += d;
2726        } else if cb == NOISE_HCB {
2727            if noise_pcm {
2728                // The first PNS band is a 9-bit PCM delta, not a Huffman one.
2729                noise_pcm = false;
2730                let d = (sf[sfb] - noise).clamp(-256, 255);
2731                w.write((d + 256) as u32, 9);
2732                noise += d;
2733            } else {
2734                let d = (sf[sfb] - noise).clamp(-60, 60);
2735                let (code, len) = crate::tables::SCALEFACTOR_BOOK.code((d + 60) as usize);
2736                w.write(code, u32::from(len));
2737                noise += d;
2738            }
2739        } else {
2740            let d = (sf[sfb] - acc).clamp(-60, 60);
2741            let (code, len) = crate::tables::SCALEFACTOR_BOOK.code((d + 60) as usize);
2742            w.write(code, u32::from(len));
2743            acc += d;
2744        }
2745    }
2746}
2747
2748/// **Arm A6 — Perceptual Noise Substitution.**
2749///
2750/// Replace a noise-like band's coefficients with a single transmitted *energy*;
2751/// the decoder refills it with scaled random noise (`decode::fill_noise`). The
2752/// band costs a scalefactor instead of a spectrum, which at low rates is the
2753/// difference between coding a band and zeroing it.
2754///
2755/// The P0 baseline is the motivation: `speech-noisy` and `noise-like` sit at
2756/// 99%+ audible from 64-128k and only clear at 192k — broadband noise has no
2757/// maskers to hide under and is unaffordable, which is exactly the problem PNS
2758/// exists to solve.
2759///
2760/// The gate is deliberately conservative on all three axes, because PNS destroys
2761/// phase and is audibly destructive on a harmonic band (the `music-tonal`
2762/// anti-class):
2763///
2764/// * **frequency** — only above `PNS_MIN_HZ`; PNS on the bass is never right,
2765/// * **tonality** — only bands the SFM calls noise-like,
2766/// * **energy** — only bands actually carrying signal.
2767///
2768/// Returns the noise-energy value to transmit for each substituted band.
2769/// `fill_noise` produces band energy `2^(ne/2)`, so `ne = 2*log2(E)`.
2770fn pns_bands(
2771    spec: &[f32],
2772    swb: &[u16],
2773    sample_rate: u32,
2774    tonality: &[f32],
2775    max_sfb: usize,
2776) -> Vec<Option<i32>> {
2777    const PNS_MIN_HZ: f64 = 4000.0;
2778    const PNS_MAX_TONALITY: f32 = 0.10;
2779    /// A frame this tonal overall gets NO PNS at all, whatever individual bands
2780    /// say. See the band-level trap below.
2781    const PNS_MAX_FRAME_TONALITY: f32 = 0.15;
2782    /// A band must carry at least this fraction of the frame's MEAN band energy
2783    /// to be worth substituting — population-relative (law 1), not absolute.
2784    const PNS_MIN_ENERGY_FRAC: f64 = 0.5;
2785
2786    let num_swb = swb.len() - 1;
2787    let mut out = vec![None; num_swb];
2788
2789    // Band energies once, and the frame's energy-weighted tonality.
2790    let mut energies = vec![0f64; num_swb];
2791    for sfb in 0..num_swb {
2792        let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
2793        energies[sfb] = spec[s..e.min(spec.len())]
2794            .iter()
2795            .map(|&x| f64::from(x) * f64::from(x))
2796            .sum();
2797    }
2798    let total: f64 = energies.iter().sum::<f64>() + 1e-9;
2799    let frame_tonality = (0..num_swb)
2800        .map(|i| energies[i] * f64::from(tonality[i]))
2801        .sum::<f64>()
2802        / total;
2803
2804    // **The band-level trap, measured.** A near-EMPTY band has a flat spectrum,
2805    // so its spectral flatness measure reads as maximally *noise-like* — SFM
2806    // cannot distinguish "broadband noise" from "almost nothing". A band-only
2807    // gate therefore substitutes noise into the empty bands surrounding a pure
2808    // tone, which is how the first version of this fired on a 6 kHz sine.
2809    //
2810    // Two guards, because they fail in different directions: the frame-level veto
2811    // refuses tonal CONTENT outright, and the relative energy floor refuses
2812    // individual bands with nothing in them.
2813    if frame_tonality as f32 > PNS_MAX_FRAME_TONALITY {
2814        return out;
2815    }
2816    let mean_band = total / num_swb as f64;
2817
2818    for sfb in 0..num_swb.min(max_sfb) {
2819        let lo_hz = f64::from(swb[sfb]) * f64::from(sample_rate) * 0.5 / FRAME_LEN as f64;
2820        if lo_hz < PNS_MIN_HZ || tonality[sfb] > PNS_MAX_TONALITY {
2821            continue;
2822        }
2823        let energy = energies[sfb];
2824        if energy <= 1.0 || energy < mean_band * PNS_MIN_ENERGY_FRAC {
2825            continue; // nothing meaningful there to substitute
2826        }
2827        let ne = (2.0 * energy.log2()).round() as i32;
2828        out[sfb] = Some(ne.clamp(-100, 255));
2829    }
2830    out
2831}
2832
2833/// The bits [`spectral_emit`] writes for every whole `dim`-tuple of `q` with
2834/// spectral book `cb` (1..=11; every tuple representable, magnitudes at most
2835/// `MAX_QUANT`), in fewer writes: the book and its table are looked up once per
2836/// band, each codeword goes out together with its sign bits as one write (at
2837/// most 19 + 4 bits), and each escape sequence as one write (`2N + 5 <= 21`
2838/// bits for `N <= 8`). `spectral_emit` stays the per-tuple reference.
2839///
2840/// Each book gets its own instance of the loop ([`emit_book`]), so the tuple
2841/// index is straight-line arithmetic on constants instead of
2842/// [`tuple_index`]'s run-time `dim`/`lav` walk.
2843fn emit_band(w: &mut BitWriter, cb: u8, q: &[i32]) {
2844    let book = spectral_book(cb);
2845    match cb {
2846        1 | 2 => emit_book::<4, false, 1, false>(w, book, q),
2847        3 | 4 => emit_book::<4, true, 2, false>(w, book, q),
2848        5 | 6 => emit_book::<2, false, 4, false>(w, book, q),
2849        7 | 8 => emit_book::<2, true, 7, false>(w, book, q),
2850        9 | 10 => emit_book::<2, true, 12, false>(w, book, q),
2851        11 => emit_book::<2, true, 16, true>(w, book, q),
2852        _ => panic!("not a spectral codebook: {cb}"),
2853    }
2854}
2855
2856/// [`emit_band`] for one book shape: `DIM`-tuples, magnitudes plus sign bits
2857/// when `UNSIGNED`, values up to `LAV` (book 11, `ESC`, clamps to `LAV` and
2858/// escape-codes the rest). An unrepresentable tuple panics, as
2859/// [`spectral_emit`] does.
2860fn emit_book<const DIM: usize, const UNSIGNED: bool, const LAV: u32, const ESC: bool>(
2861    w: &mut BitWriter,
2862    book: &crate::huffman::HuffBook,
2863    q: &[i32],
2864) {
2865    let modulo = if UNSIGNED { LAV + 1 } else { 2 * LAV + 1 };
2866    for t in q.chunks_exact(DIM) {
2867        let mut idx = 0u32;
2868        for &c in t {
2869            let mag = c.unsigned_abs();
2870            assert!(ESC || mag <= LAV, "representable tuple");
2871            let digit = if !UNSIGNED {
2872                (c + LAV as i32) as u32
2873            } else if ESC {
2874                mag.min(LAV)
2875            } else {
2876                mag
2877            };
2878            idx = idx * modulo + digit;
2879        }
2880        let (code, len) = book.code(idx as usize);
2881        let (mut val, mut n) = (code, u32::from(len));
2882        if UNSIGNED {
2883            for &c in t {
2884                if c != 0 {
2885                    val = (val << 1) | u32::from(c < 0);
2886                    n += 1;
2887                }
2888            }
2889        }
2890        w.write(val, n);
2891        if ESC {
2892            for &c in t {
2893                let m = c.unsigned_abs();
2894                if m >= LAV {
2895                    // N ones, a zero, then N + 4 bits of m - 2^(N+4) (ISO §4.6.3.3).
2896                    let e = m.ilog2() - 4;
2897                    let prefix = ((1u32 << e) - 1) << 1;
2898                    w.write((prefix << (e + 4)) | (m - (1 << (e + 4))), 2 * e + 5);
2899                }
2900            }
2901        }
2902    }
2903}
2904
2905/// `spectral_data`: per regular SFB, code coefficient tuples with the band's book.
2906fn write_spectrum(w: &mut BitWriter, quant: &[i32], cbs: &[u8], swb: &[u16]) {
2907    for (sfb, &cb) in cbs.iter().enumerate() {
2908        // ZERO, NOISE (PNS) and intensity bands carry no spectral data — their
2909        // whole point is that the coefficients are not transmitted.
2910        if cb == ZERO_HCB || cb >= NOISE_HCB {
2911            continue;
2912        }
2913        let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
2914        emit_band(w, cb, &quant[s..e]);
2915    }
2916}
2917
2918/// Encode one channel as a `single_channel_element` for a long or transition block
2919/// (`seq` ∈ {`OnlyLong`, `LongStart`, LongStop}): psy offsets → rate loop over the
2920/// common base → per-band scalefactors → coded ICS.
2921#[allow(clippy::too_many_arguments)]
2922fn encode_channel_element(
2923    w: &mut BitWriter,
2924    tag: u32,
2925    spec: &[f32],
2926    swb: &[u16],
2927    seq: WindowSequence,
2928    sample_rate: u32,
2929    target_bits: usize,
2930    cur_kbd: bool,
2931    psy: PsyCfg,
2932    elem_id: u32,
2933) {
2934    // Pass 1, un-filtered: the TNS span depends on max_sfb, which only exists
2935    // after quantization. This pass exists to learn it.
2936    let offsets0 = perceptual_offsets(spec, swb, sample_rate, psy.tonality_smr, target_bits);
2937    let xp0 = Xpow::new(spec);
2938    let (_, sf0, (cbs0, _, max_sfb0, quant0)) = rate_loop_coded(&xp0, swb, &offsets0, target_bits);
2939
2940    // Arm A3. Only engage when the coded range already reaches TNS_MAX_LONG, so
2941    // the decoder's span `min(TNS_MAX_LONG, max_sfb)` is pinned to TNS_MAX_LONG
2942    // on BOTH sides regardless of what the re-quantization does to max_sfb. The
2943    // alternative (span depending on a max_sfb that pass 2 can move) is a
2944    // bitstream desync waiting to happen.
2945    let fs_index = crate::sf_index_for_rate(sample_rate).unwrap_or(4);
2946    let tns_max = crate::decode::TNS_MAX_LONG[fs_index as usize] as usize;
2947    let mut tns: Option<TnsEnc> = None;
2948    // ARM A3 ROUTING GATE. Spectral LPC prediction gain alone is NOT a transient
2949    // detector: a peaky TONAL spectrum predicts just as well as an impulsive one,
2950    // so a gain-only gate fires on sustained content, where temporal noise
2951    // shaping has nothing to shape and simply costs bits. Measured (PEAQ, vs the
2952    // previous default): tonal -1.02, mixed -1.14, quiet -1.05, while percussive
2953    // moved only -0.01. It was firing almost exclusively on the wrong content.
2954    //
2955    // The fix is to require the frame to be transient-ADJACENT: only the
2956    // LongStart / LongStop frames that bracket a detected attack. Those are
2957    // exactly the long blocks that carry pre-echo, and the window sequence
2958    // already names them, so the gate is free.
2959    let tns_frame_ok = seq != WindowSequence::OnlyLong;
2960    let (cbs, sf, max_sfb, quant) = if psy.tns && tns_frame_ok && max_sfb0 >= tns_max {
2961        let mut filtered = spec.to_vec();
2962        match tns_analyze_long(&mut filtered, swb, fs_index, max_sfb0) {
2963            Some(t) => {
2964                let offsets =
2965                    perceptual_offsets(&filtered, swb, sample_rate, psy.tonality_smr, target_bits);
2966                let xp = Xpow::new(&filtered);
2967                let tns_target = target_bits.min(MAX_CHANNEL_BITS - TNS_RESERVE_BITS);
2968                let (_, sf, (mut cbs, _, msfb, quant)) =
2969                    rate_loop_coded(&xp, swb, &offsets, tns_target);
2970                // Hold max_sfb at or above tns_max, padding with ZERO bands, so
2971                // the decoder's TNS span is exactly the one we filtered.
2972                let msfb = msfb.max(tns_max);
2973                cbs.resize(msfb, ZERO_HCB);
2974                tns = Some(t);
2975                (cbs, sf, msfb, quant)
2976            }
2977            None => (cbs0, sf0, max_sfb0, quant0),
2978        }
2979    } else {
2980        (cbs0, sf0, max_sfb0, quant0)
2981    };
2982    // Arm A6 — PNS. Substituted bands trade their spectrum for one energy value.
2983    //
2984    // Skipped when TNS fired: the decoder fills noise BEFORE inverse-filtering,
2985    // so with TNS active the transmitted energy would have to be expressed in the
2986    // filtered domain. That combination is not yet validated, and a wrong energy
2987    // there is not a small error - it is a band of noise at the wrong level.
2988    let (mut cbs, mut sf) = (cbs, sf);
2989    if psy.pns && tns.is_none() {
2990        let ton = band_tonality(spec, swb, 1, FRAME_LEN);
2991        for (b, ne) in pns_bands(spec, swb, sample_rate, &ton, max_sfb)
2992            .into_iter()
2993            .enumerate()
2994        {
2995            if let (Some(ne), Some(cb)) = (ne, cbs.get_mut(b)) {
2996                if *cb != ZERO_HCB && *cb < NOISE_HCB {
2997                    *cb = NOISE_HCB;
2998                    sf[b] = ne;
2999                }
3000            }
3001        }
3002    }
3003    if section_trellis_on() {
3004        sf = zero_band_sf_long(&cbs, &sf, &quant, swb);
3005    }
3006    let gg = global_gain(&cbs, &sf);
3007
3008    w.write(elem_id, 3);
3009    w.write(tag, 4);
3010    w.write(gg as u32, 8);
3011    let info = IcsInfo {
3012        window_sequence: seq,
3013        window_shape_kbd: cur_kbd,
3014        max_sfb: max_sfb as u8,
3015        num_windows: 1,
3016        num_window_groups: 1,
3017        window_group_length: vec![1],
3018        num_swb: swb.len() - 1,
3019    };
3020    encode_ics_info(w, &info);
3021    write_sections(w, &cbs);
3022    write_scalefactors(w, &cbs, &sf, gg);
3023    w.write(0, 1); // pulse_data_present
3024    match &tns {
3025        Some(t) => {
3026            w.write(1, 1); // tns_data_present
3027            write_tns_long(w, t);
3028        }
3029        None => w.write(0, 1),
3030    }
3031    w.write(0, 1); // gain_control_data_present
3032    write_spectrum(w, &quant, &cbs, swb);
3033}
3034
3035// ---------------------------------------------------------------------------
3036// Arm A3 (Rung 3) — Temporal Noise Shaping.
3037//
3038// The AAC tool for pre-echo, and a large part of why AAC beats MP3 on speech.
3039// The decoder has implemented it since day one (`decode::apply_tns`); the encoder
3040// emitted `tns_data_present = 0` at all three sites.
3041//
3042// The decoder runs an ALL-POLE (synthesis) filter over the spectrum:
3043//     orig[n] = resid[n] - SUM_k lpc[k] * orig[n-k]
3044// so the encoder must run the matching ALL-ZERO (analysis) filter:
3045//     resid[n] = orig[n] + SUM_k lpc[k] * orig[n-k]
3046// with the state holding past *inputs* (the original spectrum), not past outputs.
3047// Getting that inversion backwards does not sound slightly worse; it diverges.
3048// ---------------------------------------------------------------------------
3049
3050/// One TNS filter the encoder decided to apply, in emit form.
3051#[derive(Debug, Clone)]
3052pub(crate) struct TnsEnc {
3053    /// Span in scalefactor bands, counted down from the top.
3054    pub length: usize,
3055    pub order: usize,
3056    /// Quantized PARCOR indices (4-bit two's complement, `coef_res = 1`).
3057    pub idx: Vec<i32>,
3058}
3059
3060/// Coefficient resolution we emit: `coef_res = 1` (4-bit), `coef_compress = 0`.
3061/// The widest grid AAC-LC offers, so quantization error in the filter itself is
3062/// as small as the syntax allows.
3063const TNS_COEF_RES: u32 = 1;
3064const TNS_COEF_BITS: u32 = 4;
3065/// Max order for AAC-LC long blocks (the syntax allows 5 bits; 12 is the ISO cap).
3066const TNS_MAX_ORDER: usize = 12;
3067/// Prediction gain below which TNS is not worth its bits. PROVISIONAL — the
3068/// classic value; the calculator has not fitted it.
3069const TNS_MIN_GAIN: f64 = 1.4;
3070
3071/// Quantize one PARCOR value to the 4-bit grid and return `(index, dequantized)`.
3072///
3073/// Exact inverse of the decoder's dequantizer, including its **asymmetric**
3074/// scale factors (`iqfac` for non-negative, `iqfac_m` for negative) — a single
3075/// shared factor would round half the coefficients to the wrong index.
3076fn quantize_parcor(p: f32) -> (i32, f32) {
3077    use std::f32::consts::PI;
3078    let res_bits = 3 + TNS_COEF_RES;
3079    let iqfac = ((1i32 << (res_bits - 1)) as f32 - 0.5) / (PI / 2.0);
3080    let iqfac_m = ((1i32 << (res_bits - 1)) as f32 + 0.5) / (PI / 2.0);
3081    let t = p.clamp(-0.999, 0.999).asin();
3082    let lo = -(1i32 << (TNS_COEF_BITS - 1));
3083    let hi = (1i32 << (TNS_COEF_BITS - 1)) - 1;
3084    let c = if t >= 0.0 {
3085        (t * iqfac).round() as i32
3086    } else {
3087        (t * iqfac_m).round() as i32
3088    }
3089    .clamp(lo, hi);
3090    // Reconstruct exactly as the decoder will.
3091    let t_back = if c >= 0 {
3092        c as f32 / iqfac
3093    } else {
3094        c as f32 / iqfac_m
3095    };
3096    (c, t_back.sin())
3097}
3098
3099/// PARCOR (reflection coefficients) -> LPC, matching `decode::parcor_to_lpc`.
3100fn parcor_to_lpc_enc(parcor: &[f32]) -> Vec<f32> {
3101    let order = parcor.len();
3102    let mut lpc = vec![0f32; order + 1];
3103    lpc[0] = 1.0;
3104    for m in 1..=order {
3105        let mut tmp = lpc.clone();
3106        for i in 1..m {
3107            tmp[i] = lpc[i] + parcor[m - 1] * lpc[m - i];
3108        }
3109        lpc[..m].copy_from_slice(&tmp[..m]);
3110        lpc[m] = parcor[m - 1];
3111    }
3112    lpc
3113}
3114
3115/// Levinson-Durbin over `spec[start..end]`, returning `(parcor, prediction_gain)`.
3116fn spectral_parcor(spec: &[f32], start: usize, end: usize, order: usize) -> (Vec<f32>, f64) {
3117    let n = end.saturating_sub(start);
3118    if n <= order + 1 {
3119        return (Vec::new(), 1.0);
3120    }
3121    let x = &spec[start..end];
3122    let mut r = vec![0f64; order + 1];
3123    for (lag, slot) in r.iter_mut().enumerate() {
3124        let mut acc = 0f64;
3125        for i in 0..n - lag {
3126            acc += f64::from(x[i]) * f64::from(x[i + lag]);
3127        }
3128        *slot = acc;
3129    }
3130    if r[0] <= 1e-12 {
3131        return (Vec::new(), 1.0);
3132    }
3133    let r0 = r[0] * 1.0001; // white-noise correction
3134    r[0] = r0;
3135    let mut a = vec![0f64; order + 1];
3136    let mut parcor = Vec::with_capacity(order);
3137    let mut err = r0;
3138    for i in 1..=order {
3139        let mut acc = r[i];
3140        for j in 1..i {
3141            acc -= a[j] * r[i - j];
3142        }
3143        let k = acc / err;
3144        if !k.is_finite() || k.abs() >= 0.999 {
3145            break;
3146        }
3147        let prev: Vec<f64> = a[1..i].to_vec();
3148        for j in 1..i {
3149            a[j] = prev[j - 1] - k * prev[i - j - 1];
3150        }
3151        a[i] = k;
3152        parcor.push(k as f32);
3153        err *= 1.0 - k * k;
3154        if err <= 1e-12 {
3155            break;
3156        }
3157    }
3158    (parcor, r0 / err.max(1e-12))
3159}
3160
3161/// **The Rung 3 gate + arm.** Decide whether to apply TNS to a long block and, if
3162/// so, filter `spec` in place and return the data to emit.
3163///
3164/// `max_sfb_hint` must be the `max_sfb` that will be written, because the decoder
3165/// filters over `min(TNS_MAX_LONG, max_sfb)` bands — encoder and decoder must
3166/// agree on the span exactly or the inverse filter runs over the wrong region.
3167///
3168/// Returns `None` when the gate declines (prediction gain below threshold, span
3169/// too short, or a degenerate fit), in which case `spec` is untouched and the
3170/// caller emits `tns_data_present = 0` — the byte-identical fallback.
3171pub(crate) fn tns_analyze_long(
3172    spec: &mut [f32],
3173    swb: &[u16],
3174    fs_index: u8,
3175    max_sfb: usize,
3176) -> Option<TnsEnc> {
3177    let _prof = prof::scope(Stage::EncTns);
3178    let num_swb = swb.len() - 1;
3179    let tns_max = crate::decode::TNS_MAX_LONG[fs_index as usize] as usize;
3180    let mmm = tns_max.min(max_sfb);
3181    if mmm < 4 {
3182        return None;
3183    }
3184    // One filter spanning the top of the coded range down to band `bottom`. The
3185    // decoder derives `start`/`end` from `length` the same way.
3186    let bottom = mmm / 4; // skip the lowest quarter: TNS on the bass is harmful
3187    let length = num_swb.saturating_sub(bottom);
3188    let start = swb[bottom.min(mmm)] as usize;
3189    let end = swb[mmm] as usize;
3190    if end <= start + TNS_MAX_ORDER + 1 {
3191        return None;
3192    }
3193
3194    let (parcor_raw, gain) = spectral_parcor(spec, start, end, TNS_MAX_ORDER);
3195    if parcor_raw.is_empty() || gain < TNS_MIN_GAIN {
3196        return None; // the gate: not worth its bits
3197    }
3198
3199    // Quantize to the shipping 4-bit grid, and keep the DEQUANTIZED values —
3200    // filtering with the unquantized ones would leave the decoder running a
3201    // slightly different filter, which shows up as drift across the band.
3202    let mut idx = Vec::with_capacity(parcor_raw.len());
3203    let mut parcor = Vec::with_capacity(parcor_raw.len());
3204    for &p in &parcor_raw {
3205        let (c, dq) = quantize_parcor(p);
3206        idx.push(c);
3207        parcor.push(dq);
3208    }
3209    // Drop trailing zero-index coefficients: they cost 4 bits each and do nothing.
3210    while idx.len() > 1 && *idx.last().unwrap() == 0 {
3211        idx.pop();
3212        parcor.pop();
3213    }
3214    let order = idx.len();
3215    if order == 0 {
3216        return None;
3217    }
3218
3219    let lpc = parcor_to_lpc_enc(&parcor);
3220
3221    // The ANALYSIS filter (all-zero), upward direction, state = past inputs.
3222    // Indexed rather than iterated: the filter reads and writes the same slice
3223    // element each step, which an iterator form cannot express without a copy.
3224    #[allow(clippy::needless_range_loop)]
3225    let mut state = vec![0f32; order];
3226    #[allow(clippy::needless_range_loop)]
3227    for p in start..end {
3228        let xn = spec[p];
3229        let mut y = xn;
3230        for j in 0..order {
3231            y += state[j] * lpc[j + 1];
3232        }
3233        for j in (1..order).rev() {
3234            state[j] = state[j - 1];
3235        }
3236        state[0] = xn;
3237        spec[p] = y;
3238    }
3239
3240    Some(TnsEnc { length, order, idx })
3241}
3242
3243/// Emit `tns_data` for a long block (`n_filt` 2 bits, `length` 6, `order` 5).
3244/// Mirrors `decode::parse_tns` exactly.
3245pub(crate) fn write_tns_long(w: &mut BitWriter, tns: &TnsEnc) {
3246    w.write(1, 2); // n_filt = 1
3247    w.write(TNS_COEF_RES, 1); // coef_res
3248    w.write(tns.length as u32, 6);
3249    w.write(tns.order as u32, 5);
3250    if tns.order > 0 {
3251        w.write(0, 1); // direction: upward (low -> high)
3252        w.write(0, 1); // coef_compress = 0
3253        for &c in &tns.idx {
3254            let masked = (c as u32) & ((1u32 << TNS_COEF_BITS) - 1);
3255            w.write(masked, TNS_COEF_BITS);
3256        }
3257    }
3258}
3259
3260// ---------------------------------------------------------------------------
3261// Block switching (brick 5) — transient detection, window-sequence assignment,
3262// and the short-block coding path (eight 128-bin windows, one group).
3263// ---------------------------------------------------------------------------
3264
3265/// Flag each 1024-sample frame that contains a transient: a 128-sample sub-block
3266/// whose energy leaps above the recent running average (an attack). Frame 0 is
3267/// never flagged — nothing precedes it to open a `LongStart` transition from.
3268///
3269/// `pub(crate)` so [`crate::lab::signals`] can record what the *shipping*
3270/// detector decides alongside the campaign's replacement signal — the
3271/// gate-calculator's `shipped` column (arm A9).
3272pub(crate) fn detect_transients(chan: &[f32], nframes: usize) -> Vec<bool> {
3273    const RATIO: f64 = 10.0;
3274    // (arm A9 replaces the guard below; see `detect_transients_relative`)
3275    let mut flags = vec![false; nframes];
3276    let mut avg = 0.0f64;
3277    for (f, flag) in flags.iter_mut().enumerate() {
3278        let mut attack = 1.0f64;
3279        for sb in 0..8 {
3280            let start = f * FRAME_LEN + sb * SHORT_HALF;
3281            let e: f64 = (0..SHORT_HALF)
3282                .map(|i| {
3283                    let x = f64::from(chan.get(start + i).copied().unwrap_or(0.0));
3284                    x * x
3285                })
3286                .sum();
3287            if avg > 1e-3 {
3288                attack = attack.max(e / avg);
3289            }
3290            avg = 0.75 * avg + 0.25 * e;
3291        }
3292        if f > 0 && attack > RATIO {
3293            *flag = true;
3294        }
3295    }
3296    flags
3297}
3298
3299/// Per-frame **population-relative** max attack ratio — the level-invariant
3300/// replacement for [`detect_transients`]'s absolute `avg > 1e-3` guard (arm A9).
3301///
3302/// The running average is floored at a fraction of *this clip's own* mean
3303/// sub-block energy, so both numerator and floor scale with level and the ratio
3304/// is unchanged by a gain change. The shipping detector's absolute floor makes it
3305/// blind on quiet content and, because the average decays 0.75× per sub-block, on
3306/// sparse attacks over a quiet floor at *any* level.
3307///
3308/// Used by the Rung 0 shape gate as a transient veto; it is also the signal arm
3309/// A9 will replace the detector's threshold with.
3310pub(crate) fn frame_attack_ratios(chan: &[f32], nframes: usize) -> Vec<f32> {
3311    frame_attack_ratios_with(chan, nframes, false)
3312}
3313
3314/// Energy of the [`SHORT_HALF`]-sample sub-block of `chan` starting at
3315/// `start` (samples past the end are silence). With `highpass`, of the
3316/// second difference `x[n] - 2x[n-1] + x[n-2]` instead (samples before 0 are
3317/// silence): a +12 dB/octave tilt, so an attack carried by its high
3318/// frequencies stands out over a sustained low-frequency body.
3319fn sub_block_energy(chan: &[f32], start: usize, highpass: bool) -> f64 {
3320    let at = |i: usize| f64::from(chan.get(i).copied().unwrap_or(0.0));
3321    (start..start + SHORT_HALF)
3322        .map(|n| {
3323            let x = if highpass {
3324                let x1 = if n >= 1 { at(n - 1) } else { 0.0 };
3325                let x2 = if n >= 2 { at(n - 2) } else { 0.0 };
3326                at(n) - 2.0 * x1 + x2
3327            } else {
3328                at(n)
3329            };
3330            x * x
3331        })
3332        .sum()
3333}
3334
3335/// [`frame_attack_ratios`] on plain (`highpass = false`) or high-passed
3336/// sub-block energies (see [`sub_block_energy`]).
3337pub(crate) fn frame_attack_ratios_with(chan: &[f32], nframes: usize, highpass: bool) -> Vec<f32> {
3338    let mut sub: Vec<f64> = Vec::with_capacity(nframes * 8);
3339    for f in 0..nframes {
3340        for sb in 0..8 {
3341            sub.push(sub_block_energy(
3342                chan,
3343                f * FRAME_LEN + sb * SHORT_HALF,
3344                highpass,
3345            ));
3346        }
3347    }
3348    let mean_e = sub.iter().sum::<f64>() / sub.len().max(1) as f64;
3349    let floor = (mean_e * 1e-3).max(f64::MIN_POSITIVE);
3350
3351    let mut avg = 0.0f64;
3352    let mut out = Vec::with_capacity(nframes);
3353    for f in 0..nframes {
3354        let mut amax = 1.0f32;
3355        for sb in 0..8 {
3356            let e = sub[f * 8 + sb];
3357            amax = amax.max((e / avg.max(floor)) as f32);
3358            avg = 0.75 * avg + 0.25 * e;
3359        }
3360        out.push(amax);
3361    }
3362    out
3363}
3364
3365/// **Arm A9 — the level-invariant transient detector.**
3366///
3367/// Same decision rule as [`detect_transients`] (`attack ratio > 10`), on a signal
3368/// that is actually defined. The shipped detector guards its ratio with
3369/// `avg > 1e-3` — an **absolute** energy floor — which has two consequences the
3370/// P1 truth table pinned:
3371///
3372/// * the identical waveform 40 dB quieter stops being detected at all, and
3373/// * because the running average decays 0.75x per sub-block, it falls under the
3374///   floor across the quiet stretch between sparse attacks, so castanet-like
3375///   content is missed **at any level** — measured: zero frames flagged on the
3376///   percussive corpus class whose p95 attack ratio is ~30000x.
3377///
3378/// The ratio itself is already scale-invariant; only the guard was not. This
3379/// version floors the running average relative to the clip's own mean sub-block
3380/// energy instead, which is the law-1 form and leaves the threshold meaning what
3381/// it says.
3382///
3383/// This is not merely a quality knob: arm A1 (short-block psy) can only reach
3384/// frames that are coded as short blocks, so a detector that never fires makes A1
3385/// unmeasurable. A9 is A1's prerequisite.
3386pub(crate) fn detect_transients_relative(
3387    chan: &[f32],
3388    nframes: usize,
3389    highpass: bool,
3390) -> Vec<bool> {
3391    const RATIO: f32 = 10.0;
3392    let ratios = frame_attack_ratios_with(chan, nframes, highpass);
3393    (0..nframes)
3394        .map(|f| f > 0 && ratios.get(f).copied().unwrap_or(1.0) > RATIO)
3395        .collect()
3396}
3397
3398/// Assign a valid AAC window sequence to each frame from the transient flags. A
3399/// short run is bracketed by LongStart/LongStop; runs a single frame apart are
3400/// merged (a lone gap can't be both a stop and a start).
3401fn assign_sequences(transient: &[bool]) -> Vec<WindowSequence> {
3402    use WindowSequence::{EightShort, LongStart, LongStop, OnlyLong};
3403    let n = transient.len();
3404    let mut short = transient.to_vec();
3405    for i in 1..n.saturating_sub(1) {
3406        if !short[i] && short[i - 1] && short[i + 1] {
3407            short[i] = true;
3408        }
3409    }
3410    let mut seq = vec![OnlyLong; n];
3411    let mut i = 0;
3412    while i < n {
3413        if short[i] {
3414            let a = i;
3415            while i < n && short[i] {
3416                seq[i] = EightShort;
3417                i += 1;
3418            }
3419            if a > 0 {
3420                seq[a - 1] = LongStart;
3421            }
3422            if i < n {
3423                seq[i] = LongStop;
3424            }
3425        } else {
3426            i += 1;
3427        }
3428    }
3429    seq
3430}
3431
3432/// Cheapest codebook (and its bit cost) for one SFB across all short windows of a
3433/// single group, matched to how the decoder reads it (per-SFB codebook, per-window
3434/// coefficients).
3435///
3436/// The same one-walk pricing as [`best_codebook_for_band`], accumulated over the
3437/// group's windows; [`best_codebook_short_ref`], the per-book search it
3438/// replaced, is the test oracle.
3439fn best_codebook_short(
3440    quant: &[i32],
3441    swb: &[u16],
3442    sfb: usize,
3443    win0: usize,
3444    nwin: usize,
3445) -> (u8, usize) {
3446    let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
3447    let band = |win: usize| &quant[win * SHORT_HALF + s..win * SHORT_HALF + e];
3448    let wins = win0..win0 + nwin;
3449    if (e - s) % 2 != 0 {
3450        // No book can code an odd band (cold: every AAC band width is a
3451        // multiple of 4).
3452        return if wins.clone().all(|w| band(w).iter().all(|&v| v == 0)) {
3453            (ZERO_HCB, 0)
3454        } else {
3455            (ESC_HCB, usize::MAX)
3456        };
3457    }
3458    let t = cost_tables();
3459    let mut cost = BandCost::default();
3460    for win in wins.clone() {
3461        cost.add2(t, band(win));
3462    }
3463    if cost.maxq == 0 {
3464        return (ZERO_HCB, 0);
3465    }
3466    if cost.maxq <= 2 && (e - s) % 4 == 0 {
3467        for win in wins.clone() {
3468            cost.add4(t, band(win));
3469        }
3470    }
3471    if cost.maxq >= 16 {
3472        for win in wins {
3473            cost.add_esc(band(win));
3474        }
3475    }
3476    cost.best(e - s)
3477}
3478
3479/// The per-book search [`best_codebook_short`] replaced: the oracle its tests
3480/// compare against.
3481#[cfg(test)]
3482fn best_codebook_short_ref(
3483    quant: &[i32],
3484    swb: &[u16],
3485    sfb: usize,
3486    win0: usize,
3487    nwin: usize,
3488) -> (u8, usize) {
3489    let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
3490    let wins = win0..win0 + nwin;
3491    let mut maxq = 0u32;
3492    for win in wins.clone() {
3493        let base = win * SHORT_HALF;
3494        for &q in &quant[base + s..base + e] {
3495            maxq = maxq.max(q.unsigned_abs());
3496        }
3497    }
3498    if maxq == 0 {
3499        return (ZERO_HCB, 0);
3500    }
3501    let mut best = (ESC_HCB, usize::MAX);
3502    for cb in 1..=11u8 {
3503        let meta = &CODEBOOKS[cb as usize];
3504        let dim = meta.dim as usize;
3505        if (e - s) % dim != 0 || (!meta.esc && u32::from(meta.lav) < maxq) {
3506            continue;
3507        }
3508        let mut bits = 0usize;
3509        let mut ok = true;
3510        'windows: for win in wins.clone() {
3511            let base = win * SHORT_HALF;
3512            let mut i = s;
3513            while i < e {
3514                if let Some(b) = spectral_bits(cb as usize, &quant[base + i..base + i + dim]) {
3515                    bits += b;
3516                } else {
3517                    ok = false;
3518                    break 'windows;
3519                }
3520                i += dim;
3521            }
3522        }
3523        if ok && bits < best.1 {
3524            best = (cb, bits);
3525        }
3526    }
3527    best
3528}
3529
3530/// `(first window, window count)` of each group, from the group lengths.
3531fn group_windows(groups: &[u8]) -> impl Iterator<Item = (usize, usize)> + '_ {
3532    groups.iter().scan(0usize, |w0, &len| {
3533        let r = (*w0, len as usize);
3534        *w0 += len as usize;
3535        Some(r)
3536    })
3537}
3538
3539/// Per-group scalefactors (`groups.len() × num_swb`) flattened to the coded
3540/// order the bitstream carries (`groups.len() × max_sfb`).
3541fn flatten_short_sf(sf: &[i32], num_swb: usize, max_sfb: usize, ngroups: usize) -> Vec<i32> {
3542    (0..ngroups)
3543        .flat_map(|g| sf[g * num_swb..g * num_swb + max_sfb].iter().copied())
3544        .collect()
3545}
3546
3547/// **Arm 1a — window grouping.** Split the eight short windows into runs of
3548/// similar energy: a new group starts where a window's energy differs from its
3549/// group's running mean by more than [`GROUP_SPLIT`]. A quiet pre-attack stretch
3550/// then has scalefactors of its own instead of sharing the attack's. `specs` are
3551/// the channels that share the `ics_info` (both channels of a common-window CPE).
3552fn short_groups(specs: &[&[f32]]) -> Vec<u8> {
3553    let mut e = [0f64; 8];
3554    for spec in specs {
3555        for (w, ew) in e.iter_mut().enumerate() {
3556            *ew += spec[w * SHORT_HALF..(w + 1) * SHORT_HALF]
3557                .iter()
3558                .map(|&x| f64::from(x) * f64::from(x))
3559                .sum::<f64>();
3560        }
3561    }
3562    let floor = e.iter().sum::<f64>() * 1e-6 + 1e-9;
3563    let mut groups = Vec::with_capacity(8);
3564    let (mut len, mut sum) = (1u8, e[0]);
3565    for &ew in &e[1..] {
3566        let ratio = (ew + floor) / (sum / f64::from(len) + floor);
3567        if !(1.0 / GROUP_SPLIT..=GROUP_SPLIT).contains(&ratio) {
3568            groups.push(len);
3569            len = 1;
3570            sum = ew;
3571        } else {
3572            len += 1;
3573            sum += ew;
3574        }
3575    }
3576    groups.push(len);
3577    groups
3578}
3579
3580/// Energy ratio (window vs its group's mean) that starts a new group: 6 dB.
3581const GROUP_SPLIT: f64 = 4.0;
3582
3583/// Bits for short-block `section_data` (3-bit run-length increments, esc = 7).
3584fn section_bits_short(cbs: &[u8]) -> usize {
3585    let esc = 7usize;
3586    let mut bits = 0usize;
3587    let mut k = 0usize;
3588    while k < cbs.len() {
3589        let cb = cbs[k];
3590        let mut len = 1usize;
3591        while k + len < cbs.len() && cbs[k + len] == cb {
3592            len += 1;
3593        }
3594        bits += 4;
3595        let mut l = len;
3596        while l >= esc {
3597            bits += 3;
3598            l -= esc;
3599        }
3600        bits += 3;
3601        k += len;
3602    }
3603    bits
3604}
3605
3606/// Quantize all eight short windows with a per-SFB scalefactor (one group; flat
3607/// this brick), pick per-SFB codebooks, and return (codebooks, body bits, `max_sfb`,
3608/// window-major quantized spectrum).
3609fn code_frame_short(
3610    xp: &Xpow,
3611    swb: &[u16],
3612    sf: &[i32],
3613    groups: &[u8],
3614) -> (Vec<u8>, usize, usize, Vec<i32>, Vec<i32>) {
3615    work::bump_code_frame();
3616    let num_swb = swb.len() - 1;
3617    work::bump_quant_bands(((swb.len() - 1) * 8) as u64);
3618    let scale = scale_table();
3619    let prof_q = prof::scope(Stage::EncQuant);
3620    let mut quant = vec![0i32; FRAME_LEN];
3621    for (g, (w0, nwin)) in group_windows(groups).enumerate() {
3622        for win in w0..w0 + nwin {
3623            let base = win * SHORT_HALF;
3624            for sfb in 0..num_swb {
3625                let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
3626                let sc = scale[sf[g * num_swb + sfb].clamp(0, 255) as usize];
3627                quantize_band(
3628                    &xp.pow[base + s..base + e],
3629                    &xp.sign[base + s..base + e],
3630                    sc,
3631                    &mut quant[base + s..base + e],
3632                );
3633            }
3634        }
3635    }
3636    drop(prof_q);
3637    let _prof_cb = prof::scope(Stage::EncCodebook);
3638    let mut max_sfb = 0usize;
3639    for sfb in 0..num_swb {
3640        let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
3641        if (0..8).any(|win| {
3642            let base = win * SHORT_HALF;
3643            quant[base + s..base + e].iter().any(|&q| q != 0)
3644        }) {
3645            max_sfb = sfb + 1;
3646        }
3647    }
3648    let mut cbs = Vec::with_capacity(groups.len() * max_sfb);
3649    let mut spec_bits = 0usize;
3650    let mut section_bits = 0usize;
3651    for (w0, nwin) in group_windows(groups) {
3652        let start = cbs.len();
3653        let (g_cbs, bits) = short_books(&quant, swb, max_sfb, w0, nwin);
3654        cbs.extend_from_slice(&g_cbs);
3655        spec_bits += bits;
3656        section_bits += section_bits_short(&cbs[start..]);
3657    }
3658    let mut sf_flat = flatten_short_sf(sf, num_swb, max_sfb, groups.len());
3659    if section_trellis_on() {
3660        sf_flat = zero_band_sf_short(&cbs, &sf_flat, &quant, swb, groups, max_sfb);
3661    }
3662    let gg = global_gain(&cbs, &sf_flat);
3663    // global_gain(8) + ics_info(short ~18) + 3 flags + sections + scalefactors + spectrum.
3664    let body = 8 + 18 + 3 + section_bits + scalefactor_bits(&cbs, &sf_flat, gg) + spec_bits;
3665    (cbs, body, max_sfb, quant, sf_flat)
3666}
3667
3668/// The smallest flat scalefactor that avoids clamping the loudest short coefficient
3669/// past `MAX_QUANT`.
3670fn min_base_short(xp: &Xpow) -> i32 {
3671    let maxp = xp.max_pow(0, xp.len());
3672    if maxp <= 1e-9 {
3673        return 0;
3674    }
3675    (100.0 - (f64::from(MAX_QUANT) / maxp).log2() / 0.1875)
3676        .ceil()
3677        .clamp(0.0, 255.0) as i32
3678}
3679
3680/// **Arm A1 — the short-block psychoacoustic model.**
3681///
3682/// Per-SFB scalefactor offsets for an `EightShort` frame. The band energies are
3683/// summed **across the eight windows** of the group, because with one window group
3684/// a scalefactor covers band `b` of all eight windows — so the mask must be
3685/// computed over exactly the coefficients that scalefactor governs.
3686///
3687/// The band geometry is the short SWB table over a 128-coefficient window, hence
3688/// `n_coeffs = SHORT_HALF`: reusing the long block's 1024 here would place every
3689/// band three octaves too low and spread the mask against the wrong neighbours.
3690///
3691/// Before this arm, short blocks coded with **flat** scalefactors — no noise
3692/// shaping at all on precisely the content where masking matters most.
3693///
3694/// # MEASURED REFUTATION (2026-08-08): this is harmful WITHOUT window grouping
3695///
3696/// Once arm A9 made short blocks actually occur, A1 became measurable — and it
3697/// made things **worse**, on both the class it was built for and the one it was
3698/// meant to be neutral on:
3699///
3700/// | arm | percussive 64k/128k | speech-clean 64k/128k |
3701/// |---|---|---|
3702/// | A9 alone | −2.81 / −6.10 | +1.56 / +1.18 |
3703/// | A9 + A1 | −1.18 / −5.50 | +2.33 / +1.46 |
3704///
3705/// The cause is the group-summed energy above. With **one** window group a single
3706/// scalefactor governs band `b` of all eight windows, so the mask must be derived
3707/// from their sum — which hands the quiet pre-attack windows a mask sized by the
3708/// attack. That is precisely the pre-echo the tool was supposed to suppress: a
3709/// flat scalefactor at least errs uniformly, whereas an attack-sized mask
3710/// actively licenses noise where the ear is most sensitive.
3711///
3712/// **This overturns a plan correction I made earlier.** Reading the emit path, I
3713/// argued grouping was a follow-up rather than a prerequisite, because per-SFB
3714/// shaping is available with one group. That is true and irrelevant: the shaping
3715/// available with one group is shaping in the *wrong domain*. Arm 1a (window
3716/// grouping) is a genuine prerequisite for A1, exactly as the original plan said.
3717/// Do not enable `short_block_psy` before grouping exists.
3718fn perceptual_offsets_short(
3719    spec: &[f32],
3720    swb: &[u16],
3721    sample_rate: u32,
3722    tonality_smr: bool,
3723) -> Vec<i32> {
3724    let _prof = prof::scope(Stage::EncPsy);
3725    let num_swb = swb.len() - 1;
3726    let mut energy = vec![0.0f64; num_swb];
3727    let mut noise_scale = vec![0.0f64; num_swb];
3728    for sfb in 0..num_swb {
3729        let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
3730        for win in 0..8 {
3731            let base = win * SHORT_HALF;
3732            for k in s..e {
3733                let Some(&x) = spec.get(base + k) else {
3734                    continue;
3735                };
3736                energy[sfb] += f64::from(x) * f64::from(x);
3737                noise_scale[sfb] += f64::from(x.abs()).sqrt();
3738            }
3739        }
3740    }
3741    let mut e_masked: Vec<f64> = energy.iter().map(|&e| e + 1e-3).collect();
3742    let ton = tonality_smr.then(|| band_tonality(spec, swb, 8, SHORT_HALF));
3743    let thr = masking_from_energy(&e_masked, swb, sample_rate, SHORT_HALF, ton.as_deref());
3744    e_masked.clear();
3745
3746    let raw: Vec<f64> = (0..num_swb)
3747        .map(|sfb| (thr[sfb] / (noise_scale[sfb] + 1e-6)).log2() / 0.375)
3748        .collect();
3749    // Centre on the energy-bearing bands, exactly as the long-block path does.
3750    let etot: f64 = energy.iter().sum::<f64>() + 1e-9;
3751    let center: f64 = (0..num_swb).map(|i| raw[i] * energy[i]).sum::<f64>() / etot;
3752    raw.iter()
3753        .map(|&r| ((r - center).round() as i32).clamp(-60, 60))
3754        .collect()
3755}
3756
3757/// Rate loop for a short block: smallest common base (≥ no-clamp floor) whose body
3758/// fits `target_bits`. `offsets` is arm A1's per-band shape (all zeros reproduces
3759/// **Arms A1 + 1a — the short-block psy model per window group.**
3760///
3761/// [`perceptual_offsets_short`] sums band energy across all eight windows, which
3762/// hands quiet pre-attack windows a mask sized by the attack (its measured
3763/// refutation). Here each group gets its own masking threshold, and the offsets
3764/// are centred **across** groups: a quiet group therefore sits below the attack
3765/// group and is coded with finer steps, which is the pre-echo protection the
3766/// short block exists for. Offsets are clamped to ±30 so any two coded
3767/// scalefactors stay within the bitstream's ±60 delta. Returns
3768/// `groups.len() × num_swb` offsets, group-major.
3769fn perceptual_offsets_short_grouped(
3770    spec: &[f32],
3771    swb: &[u16],
3772    sample_rate: u32,
3773    tonality_smr: bool,
3774    groups: &[u8],
3775) -> Vec<i32> {
3776    let _prof = prof::scope(Stage::EncPsy);
3777    let num_swb = swb.len() - 1;
3778    let mut raw = Vec::with_capacity(groups.len() * num_swb);
3779    let mut energy = Vec::with_capacity(groups.len() * num_swb);
3780    for (w0, nwin) in group_windows(groups) {
3781        let sub = &spec[w0 * SHORT_HALF..(w0 + nwin) * SHORT_HALF];
3782        let mut e_band = vec![0.0f64; num_swb];
3783        let mut noise_scale = vec![0.0f64; num_swb];
3784        for sfb in 0..num_swb {
3785            let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
3786            for win in 0..nwin {
3787                let base = win * SHORT_HALF;
3788                for &x in &sub[base + s..base + e] {
3789                    e_band[sfb] += f64::from(x) * f64::from(x);
3790                    noise_scale[sfb] += f64::from(x.abs()).sqrt();
3791                }
3792            }
3793        }
3794        let e_masked: Vec<f64> = e_band.iter().map(|&e| e + 1e-3).collect();
3795        let ton = tonality_smr.then(|| band_tonality(sub, swb, nwin, SHORT_HALF));
3796        let thr = masking_from_energy(&e_masked, swb, sample_rate, SHORT_HALF, ton.as_deref());
3797        for sfb in 0..num_swb {
3798            raw.push((thr[sfb] / (noise_scale[sfb] + 1e-6)).log2() / 0.375);
3799        }
3800        energy.extend_from_slice(&e_band);
3801    }
3802    let etot: f64 = energy.iter().sum::<f64>() + 1e-9;
3803    let center: f64 = raw.iter().zip(&energy).map(|(r, e)| r * e).sum::<f64>() / etot;
3804    raw.iter()
3805        .map(|&r| ((r - center).round() as i32).clamp(-30, 30))
3806        .collect()
3807}
3808
3809/// Short-block scalefactor offsets for the configured arms: grouped psy (1a),
3810/// single-group psy (A1), or flat. Returns `groups.len() × num_swb` values.
3811fn short_offsets(
3812    spec: &[f32],
3813    swb: &[u16],
3814    sample_rate: u32,
3815    psy: PsyCfg,
3816    groups: &[u8],
3817) -> Offsets {
3818    Offsets::flat(if psy.window_grouping {
3819        perceptual_offsets_short_grouped(spec, swb, sample_rate, psy.tonality_smr, groups)
3820    } else if psy.short_block_psy {
3821        perceptual_offsets_short(spec, swb, sample_rate, psy.tonality_smr)
3822    } else {
3823        vec![0i32; groups.len() * (swb.len() - 1)]
3824    })
3825}
3826
3827/// The window grouping for a short frame whose `ics_info` the `specs` share:
3828/// real groups under arm 1a, else one group of eight.
3829fn short_grouping(specs: &[&[f32]], psy: PsyCfg) -> Vec<u8> {
3830    if psy.window_grouping {
3831        short_groups(specs)
3832    } else {
3833        vec![8]
3834    }
3835}
3836
3837/// the flat-scalefactor behavior byte-identically).
3838fn rate_loop_short(
3839    xp: &Xpow,
3840    swb: &[u16],
3841    offsets: &Offsets,
3842    target_bits: usize,
3843    groups: &[u8],
3844) -> i32 {
3845    if section_trellis_on() {
3846        let est = |b: i32| estimate_bits_short(xp, swb, offsets, b, groups);
3847        let exact = |b: i32| code_frame_short(xp, swb, &scalefactors(offsets, b), groups).1;
3848        return seeded_level(min_base_short(xp), 255, target_bits, est, exact);
3849    }
3850    let mut lo = min_base_short(xp);
3851    let mut hi = 255i32;
3852    while lo < hi {
3853        let mid = (lo + hi) / 2;
3854        let sf = scalefactors(offsets, mid);
3855        if code_frame_short(xp, swb, &sf, groups).1 <= target_bits {
3856            hi = mid;
3857        } else {
3858            lo = mid + 1;
3859        }
3860    }
3861    lo
3862}
3863
3864/// The short-block analogue of [`estimate_bits`]: every window of every
3865/// group quantized at `base`, each coefficient priced from `coef_bits`, and a
3866/// flat 7 bits a coded band (section and scalefactor). Seeds the search only.
3867fn estimate_bits_short(
3868    xp: &Xpow,
3869    swb: &[u16],
3870    offsets: &Offsets,
3871    base: i32,
3872    groups: &[u8],
3873) -> usize {
3874    let _prof = prof::scope(Stage::EncEstimate);
3875    let scale = scale_table();
3876    let sf = offsets.sf(base);
3877    let ct = coef_bits();
3878    let num_swb = swb.len() - 1;
3879    let mut bits = 29usize; // global_gain + short ics_info + flags, approx
3880    let mut qbuf = [0i32; SHORT_HALF];
3881    for (g, (w0, nwin)) in group_windows(groups).enumerate() {
3882        for sfb in 0..num_swb {
3883            let (s, e) = (usize::from(swb[sfb]), usize::from(swb[sfb + 1]));
3884            let sc = scale[sf[g * num_swb + sfb].clamp(0, 255) as usize];
3885            let (mut band, mut nonzero) = (0usize, false);
3886            for win in w0..w0 + nwin {
3887                let at = win * SHORT_HALF;
3888                quantize_band(
3889                    &xp.pow[at + s..at + e],
3890                    &xp.sign[at + s..at + e],
3891                    sc,
3892                    &mut qbuf[..e - s],
3893                );
3894                for &q in &qbuf[..e - s] {
3895                    let m = q.unsigned_abs() as usize;
3896                    if m != 0 {
3897                        nonzero = true;
3898                        band += usize::from(ct[m.min(ct.len() - 1)]);
3899                    }
3900                }
3901            }
3902            if nonzero {
3903                bits += 7 + band;
3904            }
3905        }
3906    }
3907    bits
3908}
3909
3910/// The smallest level in `[min_level, max_level]` whose `exact` bits fit
3911/// `target`: a binary search on the cheap `est` seeds a walk with `exact`
3912/// (the search shape of [`rate_loop_coded`]). Same answer as a binary search
3913/// on `exact` wherever the exact bits fall monotonically in the level, for a
3914/// handful of exact evaluations instead of one a step.
3915fn seeded_level(
3916    min_level: i32,
3917    max_level: i32,
3918    target: usize,
3919    est: impl Fn(i32) -> usize,
3920    exact: impl Fn(i32) -> usize,
3921) -> i32 {
3922    let (mut lo, mut hi) = (min_level, max_level);
3923    while lo < hi {
3924        let mid = (lo + hi) / 2;
3925        if est(mid) <= target {
3926            hi = mid;
3927        } else {
3928            lo = mid + 1;
3929        }
3930    }
3931    let mut level = lo;
3932    if exact(level) <= target {
3933        while level > min_level && exact(level - 1) <= target {
3934            level -= 1;
3935        }
3936    } else {
3937        while level < max_level && exact(level) > target {
3938            level += 1;
3939        }
3940    }
3941    level
3942}
3943
3944/// `short_block` `section_data` (4-bit codebook + 3-bit run increments, esc = 7).
3945fn write_sections_short(w: &mut BitWriter, cbs: &[u8]) {
3946    let esc = 7u32;
3947    let mut k = 0usize;
3948    while k < cbs.len() {
3949        let cb = cbs[k];
3950        let mut len = 1usize;
3951        while k + len < cbs.len() && cbs[k + len] == cb {
3952            len += 1;
3953        }
3954        w.write(u32::from(cb), 4);
3955        let mut l = len as u32;
3956        while l >= esc {
3957            w.write(esc, 3);
3958            l -= esc;
3959        }
3960        w.write(l, 3);
3961        k += len;
3962    }
3963}
3964
3965/// `short_block` `spectral_data`: per group, per SFB, per window of the group,
3966/// coefficient tuples (the grouped-interleaved order the decoder reads).
3967fn write_spectrum_short(
3968    w: &mut BitWriter,
3969    quant: &[i32],
3970    cbs: &[u8],
3971    swb: &[u16],
3972    groups: &[u8],
3973    max_sfb: usize,
3974) {
3975    for (g, (w0, nwin)) in group_windows(groups).enumerate() {
3976        for sfb in 0..max_sfb {
3977            let cb = cbs[g * max_sfb + sfb];
3978            if cb == ZERO_HCB {
3979                continue;
3980            }
3981            let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
3982            for win in w0..w0 + nwin {
3983                let base = win * SHORT_HALF;
3984                emit_band(w, cb, &quant[base + s..base + e]);
3985            }
3986        }
3987    }
3988}
3989
3990/// `short_block` `section_data` for every window group (runs never cross a group).
3991fn write_sections_short_grouped(w: &mut BitWriter, cbs: &[u8], ngroups: usize, max_sfb: usize) {
3992    for g in 0..ngroups {
3993        write_sections_short(w, &cbs[g * max_sfb..(g + 1) * max_sfb]);
3994    }
3995}
3996
3997/// Encode one channel as an `EightShort` `single_channel_element`. One group of 8
3998/// windows with flat scalefactors unless arm A1 (`psy.short_block_psy`) supplies a
3999/// per-band shape, or arm 1a (`psy.window_grouping`) real groups shaped per group.
4000#[allow(clippy::too_many_arguments)]
4001fn encode_channel_element_short(
4002    w: &mut BitWriter,
4003    tag: u32,
4004    spec: &[f32],
4005    swb: &[u16],
4006    target_bits: usize,
4007    cur_kbd: bool,
4008    sample_rate: u32,
4009    psy: PsyCfg,
4010) {
4011    let xp = Xpow::new(spec);
4012    let groups = short_grouping(&[spec], psy);
4013    let offsets = short_offsets(spec, swb, sample_rate, psy, &groups);
4014    let base = rate_loop_short(&xp, swb, &offsets, target_bits, &groups);
4015    let sf = scalefactors(&offsets, base);
4016    let (cbs, _, max_sfb, quant, sf_flat) = code_frame_short(&xp, swb, &sf, &groups);
4017    let gg = global_gain(&cbs, &sf_flat);
4018
4019    w.write(ID_SCE, 3);
4020    w.write(tag, 4);
4021    w.write(gg as u32, 8);
4022    let info = IcsInfo {
4023        window_sequence: WindowSequence::EightShort,
4024        window_shape_kbd: cur_kbd,
4025        max_sfb: max_sfb as u8,
4026        num_windows: 8,
4027        num_window_groups: groups.len(),
4028        window_group_length: groups.clone(),
4029        num_swb: swb.len() - 1,
4030    };
4031    encode_ics_info(w, &info);
4032    write_sections_short_grouped(w, &cbs, groups.len(), max_sfb);
4033    write_scalefactors(w, &cbs, &sf_flat, gg);
4034    w.write(0, 1); // pulse_data_present
4035    w.write(0, 1); // tns_data_present
4036    w.write(0, 1); // gain_control_data_present
4037    write_spectrum_short(w, &quant, &cbs, swb, &groups, max_sfb);
4038}
4039
4040// ---------------------------------------------------------------------------
4041// Stereo (brick 6) — a channel_pair_element with a common window and per-SFB M/S
4042// (mid/side) coding where the channels are correlated enough to pay off.
4043// ---------------------------------------------------------------------------
4044
4045/// Per-SFB M/S decision + mixed spectra. M/S wins when `E_M·E_S < E_L·E_R` (the
4046/// correlation criterion — raw energy always halves under the ½ scaling, so the
4047/// *product* is what predicts bit savings). Returns (ch0 = M or L, ch1 = S or R,
4048/// per-SFB `ms_used`).
4049fn mid_side(
4050    l: &[f32],
4051    r: &[f32],
4052    swb: &[u16],
4053    is_short: bool,
4054    is_veto: &[bool],
4055    groups: &[u8],
4056) -> (Vec<f32>, Vec<f32>, Vec<bool>) {
4057    let num_swb = swb.len() - 1;
4058    let wlen = if is_short { SHORT_HALF } else { FRAME_LEN };
4059    let groups: &[u8] = if is_short { groups } else { &[1] };
4060    let mut ch0 = l.to_vec();
4061    let mut ch1 = r.to_vec();
4062    let mut ms = vec![false; groups.len() * num_swb];
4063    for (g, (w0, nwin)) in group_windows(groups).enumerate() {
4064        for sfb in 0..num_swb {
4065            let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
4066            let (mut el, mut er, mut em, mut es) = (0.0f64, 0.0, 0.0, 0.0);
4067            for win in w0..w0 + nwin {
4068                let base = win * wlen;
4069                for i in s..e {
4070                    let (lv, rv) = (f64::from(l[base + i]), f64::from(r[base + i]));
4071                    let (m, sd) = ((lv + rv) * 0.5, (lv - rv) * 0.5);
4072                    el += lv * lv;
4073                    er += rv * rv;
4074                    em += m * m;
4075                    es += sd * sd;
4076                }
4077            }
4078            // A band claimed by intensity stereo (arm A7) must stay L/R.
4079            if em * es < el * er && !is_veto.get(sfb).copied().unwrap_or(false) {
4080                ms[g * num_swb + sfb] = true;
4081                for win in w0..w0 + nwin {
4082                    let base = win * wlen;
4083                    for i in s..e {
4084                        let (lv, rv) = (l[base + i], r[base + i]);
4085                        ch0[base + i] = (lv + rv) * 0.5;
4086                        ch1[base + i] = (lv - rv) * 0.5;
4087                    }
4088                }
4089            }
4090        }
4091    }
4092    (ch0, ch1, ms)
4093}
4094
4095/// Quantize one CPE channel to a target: psy per-band scalefactors (long) or flat
4096/// (short). Returns (per-SFB scalefactors, quantized spectrum).
4097fn quantize_channel(
4098    spec: &[f32],
4099    swb: &[u16],
4100    is_short: bool,
4101    sample_rate: u32,
4102    target_bits: usize,
4103    psy: PsyCfg,
4104    groups: &[u8],
4105) -> (Vec<i32>, Vec<i32>) {
4106    let xp = Xpow::new(spec);
4107    if is_short {
4108        let offsets = short_offsets(spec, swb, sample_rate, psy, groups);
4109        let base = rate_loop_short(&xp, swb, &offsets, target_bits, groups);
4110        let sf = scalefactors(&offsets, base);
4111        let (_, _, _, quant, _) = code_frame_short(&xp, swb, &sf, groups);
4112        (sf, quant)
4113    } else {
4114        let offsets = perceptual_offsets(spec, swb, sample_rate, psy.tonality_smr, target_bits);
4115        let (_, sf, (_, _, _, quant)) = rate_loop_coded(&xp, swb, &offsets, target_bits);
4116        (sf, quant)
4117    }
4118}
4119
4120/// The highest SFB with a non-zero coefficient in either channel (both channels of
4121/// a common-window CPE share `max_sfb`).
4122fn joint_max_sfb(q0: &[i32], q1: &[i32], swb: &[u16], is_short: bool) -> usize {
4123    let num_swb = swb.len() - 1;
4124    let nwin = if is_short { 8 } else { 1 };
4125    let wlen = if is_short { SHORT_HALF } else { FRAME_LEN };
4126    let nz = |q: &[i32], s: usize, e: usize| {
4127        (0..nwin).any(|win| {
4128            let b = win * wlen;
4129            q[b + s..b + e].iter().any(|&x| x != 0)
4130        })
4131    };
4132    let mut m = 0;
4133    for sfb in 0..num_swb {
4134        let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
4135        if nz(q0, s, e) || nz(q1, s, e) {
4136            m = sfb + 1;
4137        }
4138    }
4139    m
4140}
4141
4142/// Per-SFB codebooks for one channel over `0..max_sfb` (for every window group of
4143/// a short frame, group-major).
4144fn codebooks(quant: &[i32], swb: &[u16], is_short: bool, max_sfb: usize, groups: &[u8]) -> Vec<u8> {
4145    if is_short {
4146        group_windows(groups)
4147            .flat_map(|(w0, nwin)| short_books(quant, swb, max_sfb, w0, nwin).0)
4148            .collect()
4149    } else {
4150        long_books(quant, swb, max_sfb).0
4151    }
4152}
4153
4154/// `ms_mask_present` (2 bits) + the per-SFB mask when mixed.
4155fn write_ms_used(w: &mut BitWriter, ms_used: &[bool]) {
4156    if ms_used.iter().all(|&b| !b) {
4157        w.write(0, 2);
4158    } else if ms_used.iter().all(|&b| b) {
4159        w.write(2, 2);
4160    } else {
4161        w.write(1, 2);
4162        for &b in ms_used {
4163            w.write_bool(b);
4164        }
4165    }
4166}
4167
4168/// One channel's `individual_channel_stream` body inside a common-window CPE:
4169/// `global_gain`, `section_data`, `scale_factor_data`, the three flag bits, `spectral_data`
4170/// (no `ics_info` — it is shared).
4171#[allow(
4172    clippy::too_many_arguments,
4173    reason = "one argument per syntax element the bitstream writes; a struct would only rename them"
4174)]
4175fn write_channel_data(
4176    w: &mut BitWriter,
4177    cbs: &[u8],
4178    sf: &[i32],
4179    quant: &[i32],
4180    swb: &[u16],
4181    is_short: bool,
4182    groups: &[u8],
4183    max_sfb: usize,
4184) {
4185    let sf_flat;
4186    let sf = if is_short {
4187        let f = flatten_short_sf(sf, swb.len() - 1, max_sfb, groups.len());
4188        sf_flat = if section_trellis_on() {
4189            zero_band_sf_short(cbs, &f, quant, swb, groups, max_sfb)
4190        } else {
4191            f
4192        };
4193        &sf_flat[..]
4194    } else if section_trellis_on() {
4195        sf_flat = zero_band_sf_long(cbs, sf, quant, swb);
4196        &sf_flat[..]
4197    } else {
4198        sf
4199    };
4200    let gg = global_gain(cbs, sf);
4201    w.write(gg as u32, 8);
4202    if is_short {
4203        write_sections_short_grouped(w, cbs, groups.len(), max_sfb);
4204    } else {
4205        write_sections(w, cbs);
4206    }
4207    write_scalefactors(w, cbs, sf, gg);
4208    w.write(0, 1); // pulse_data_present
4209    w.write(0, 1); // tns_data_present
4210    w.write(0, 1); // gain_control_data_present
4211    if is_short {
4212        write_spectrum_short(w, quant, cbs, swb, groups, max_sfb);
4213    } else {
4214        write_spectrum(w, quant, cbs, swb);
4215    }
4216}
4217
4218/// **Arm A13 — joint rate loop over a channel pair.**
4219///
4220/// # The defect this fixes
4221///
4222/// A CPE's two channels were each given `frame_budget / channel_count` bits and
4223/// run through **independent** rate loops. That is a fixed 50/50 split, so when
4224/// M/S makes the side channel nearly empty its bits are simply wasted — the mid
4225/// channel, which is what the listener hears, still gets only half the frame.
4226///
4227/// Measured on perfectly-correlated stereo (`L == R`, so `S ≡ 0`) at 128 kbps,
4228/// per-channel reconstruction SNR:
4229///
4230/// | encoder | SNR |
4231/// |---|---|
4232/// | independent per-channel loops | **10.6 dB** |
4233/// | ffmpeg native AAC | **38.8 dB** |
4234///
4235/// # Why the obvious fix did not work
4236///
4237/// The first attempt split the budget by each channel's perceptual entropy. It
4238/// made things *worse* (8.5 dB), because PE is degenerate under a purely
4239/// relative masking model: the mask is `SMR × spread(signal)`, so `E/thr ≈
4240/// 1/SMR` for **any** non-silent channel regardless of its level. Both channels
4241/// report near-identical "demand" whatever they contain. A level-blind demand
4242/// estimate cannot allocate between levels.
4243///
4244/// # What actually works
4245///
4246/// Run **one** rate loop over the pair and give both channels a **common base**
4247/// scalefactor. A common base means a common quantizer step, i.e. both channels
4248/// are coded to the same noise floor relative to their own masks — which is the
4249/// textbook joint-stereo criterion. Bits then flow to whichever channel needs
4250/// them, because a near-empty side channel costs almost nothing at any base and
4251/// lets the loop settle on a finer base for the pair.
4252///
4253/// This is a strict generalisation: for two channels of equal demand it lands on
4254/// the same place the independent loops did.
4255#[allow(clippy::too_many_arguments)]
4256fn pair_body_bits(
4257    xp0: &Xpow,
4258    off0: &Offsets,
4259    xp1: &Xpow,
4260    off1: &Offsets,
4261    swb: &[u16],
4262    base: i32,
4263    groups: &[u8],
4264) -> usize {
4265    code_frame_short(xp0, swb, &scalefactors(off0, base), groups).1
4266        + code_frame_short(xp1, swb, &scalefactors(off1, base), groups).1
4267}
4268
4269/// Both channels' quantized spectra of a channel pair.
4270type PairQuant = (Vec<i32>, Vec<i32>);
4271
4272/// Smallest common base whose combined body fits `target_total` bits, and for
4273/// long blocks both channels' quantized spectra at it when the search kept them.
4274#[allow(clippy::too_many_arguments)]
4275fn joint_rate_loop(
4276    xp0: &Xpow,
4277    off0: &Offsets,
4278    xp1: &Xpow,
4279    off1: &Offsets,
4280    swb: &[u16],
4281    target_total: usize,
4282    is_short: bool,
4283    groups: &[u8],
4284) -> (i32, Option<PairQuant>) {
4285    let lo0 = if is_short {
4286        min_base_short(xp0)
4287    } else {
4288        min_base(xp0, swb, off0)
4289    };
4290    let lo1 = if is_short {
4291        min_base_short(xp1)
4292    } else {
4293        min_base(xp1, swb, off1)
4294    };
4295    let mut lo = lo0.max(lo1);
4296    let mut hi = off0.max_level().max(off1.max_level());
4297    if is_short && section_trellis_on() {
4298        let est = |b: i32| {
4299            estimate_bits_short(xp0, swb, off0, b, groups)
4300                + estimate_bits_short(xp1, swb, off1, b, groups)
4301        };
4302        let exact = |b: i32| pair_body_bits(xp0, off0, xp1, off1, swb, b, groups);
4303        return (seeded_level(lo, hi, target_total, est, exact), None);
4304    }
4305    if is_short {
4306        while lo < hi {
4307            let mid = (lo + hi) / 2;
4308            if pair_body_bits(xp0, off0, xp1, off1, swb, mid, groups) <= target_total {
4309                hi = mid;
4310            } else {
4311                lo = mid + 1;
4312            }
4313        }
4314        return (lo, None);
4315    }
4316    if section_trellis_on() {
4317        return joint_rate_loop_seeded(xp0, off0, xp1, off1, swb, target_total, lo, hi);
4318    }
4319    // Long blocks: the same search, keeping both channels' quantized spectra
4320    // from the last fitting level. That level is the answer whenever the search
4321    // evaluated it, so the caller need not quantize the pair again.
4322    let (mut q0, mut q1) = (vec![0i32; xp0.len()], vec![0i32; xp1.len()]);
4323    let mut best: Option<(i32, Vec<i32>, Vec<i32>)> = None;
4324    while lo < hi {
4325        let mid = (lo + hi).div_euclid(2);
4326        let bits = code_core(xp0, swb, &scalefactors(off0, mid), &mut q0).1
4327            + code_core(xp1, swb, &scalefactors(off1, mid), &mut q1).1;
4328        if bits <= target_total {
4329            hi = mid;
4330            let (k0, k1) = (std::mem::take(&mut q0), std::mem::take(&mut q1));
4331            if let Some((_, o0, o1)) = best.take() {
4332                (q0, q1) = (o0, o1);
4333            } else {
4334                (q0, q1) = (vec![0i32; xp0.len()], vec![0i32; xp1.len()]);
4335            }
4336            best = Some((mid, k0, k1));
4337        } else {
4338            lo = mid + 1;
4339        }
4340    }
4341    let kept = best.and_then(|(b, k0, k1)| (b == lo).then_some((k0, k1)));
4342    (lo, kept)
4343}
4344
4345/// The long-block [`joint_rate_loop`] under the section trellis: the search
4346/// shape of [`rate_loop_coded`], a binary search on the cheap estimate that
4347/// seeds a walk with the exact coder to the smallest common level whose pair
4348/// fits. The plain binary search ran the exact coder (now with its trellis) at
4349/// every one of its ~9 steps, for both channels; this runs it two or three
4350/// times. Same answer wherever the exact bits fall monotonically in the level.
4351#[allow(clippy::too_many_arguments)]
4352fn joint_rate_loop_seeded(
4353    xp0: &Xpow,
4354    off0: &Offsets,
4355    xp1: &Xpow,
4356    off1: &Offsets,
4357    swb: &[u16],
4358    target_total: usize,
4359    min_level: i32,
4360    max_level: i32,
4361) -> (i32, Option<PairQuant>) {
4362    let (mut lo, mut hi) = (min_level, max_level);
4363    while lo < hi {
4364        let mid = (lo + hi).div_euclid(2);
4365        if estimate_bits(xp0, swb, off0, mid) + estimate_bits(xp1, swb, off1, mid) <= target_total {
4366            hi = mid;
4367        } else {
4368            lo = mid + 1;
4369        }
4370    }
4371    let (mut q0, mut q1) = (vec![0i32; xp0.len()], vec![0i32; xp1.len()]);
4372    let mut best: Option<(i32, Vec<i32>, Vec<i32>)> = None;
4373    let mut exact = |b: i32| {
4374        let bits = code_core(xp0, swb, &scalefactors(off0, b), &mut q0).1
4375            + code_core(xp1, swb, &scalefactors(off1, b), &mut q1).1;
4376        let fits = bits <= target_total;
4377        if fits {
4378            let (k0, k1) = (std::mem::take(&mut q0), std::mem::take(&mut q1));
4379            (q0, q1) = match best.take() {
4380                Some((_, o0, o1)) => (o0, o1),
4381                None => (vec![0i32; xp0.len()], vec![0i32; xp1.len()]),
4382            };
4383            best = Some((b, k0, k1));
4384        }
4385        fits
4386    };
4387    let mut level = lo;
4388    if exact(level) {
4389        while level > min_level && exact(level - 1) {
4390            level -= 1;
4391        }
4392    } else {
4393        while level < max_level && !exact(level) {
4394            level += 1;
4395        }
4396    }
4397    let kept = best.and_then(|(b, k0, k1)| (b == level).then_some((k0, k1)));
4398    (level, kept)
4399}
4400
4401/// **Arm A7 — intensity stereo.**
4402///
4403/// Above a cutoff the ear localizes by ENVELOPE rather than waveform, so a band
4404/// of the second channel can be sent as a single scale factor applied to the
4405/// first: the decoder reconstructs `s1 = +-0.5^(0.25*is_pos) * s0`
4406/// (`decode::apply_is`). One value replaces a whole band's spectrum.
4407///
4408/// This turns the stereo decision from binary into a **3-arm dispatch** —
4409/// `{L/R, M/S, IS}` — which is why it is applied after `mid_side` and only to
4410/// bands M/S declined: with `ms_used` set the pair is already (M, S), and
4411/// intensity on an S channel means something quite different from intensity on
4412/// an R channel. Restricting to the M/S-declined bands keeps the two tools from
4413/// interpreting each other's output.
4414///
4415/// The anti-class is wide-stereo music, where collapsing a band to a scaled copy
4416/// destroys the image. Hence the correlation gate: only bands where the channels
4417/// genuinely already agree up to a gain.
4418/// **Arm A7 — intensity stereo.**
4419///
4420/// Above a cutoff the ear localizes by ENVELOPE rather than waveform, so a band
4421/// of the right channel can be sent as a single scale factor applied to the left:
4422/// the decoder reconstructs `R = +-0.5^(0.25*is_pos) * L` (`decode::apply_is`).
4423/// One value replaces a whole band's spectrum.
4424///
4425/// # Why this decides BEFORE `mid_side`, not after
4426///
4427/// The first version ran after M/S and only touched bands M/S had declined — on
4428/// the reasoning that intensity on an S channel means something different from
4429/// intensity on an R channel. It never fired once. The bands where `R ~= k*L`
4430/// are exactly the bands where M/S wins (`E_M*E_S << E_L*E_R` for a scaled copy),
4431/// so "M/S declined it" and "intensity wants it" are near-disjoint by
4432/// construction.
4433///
4434/// So intensity is decided on the ORIGINAL L/R spectra and **vetoes M/S** on the
4435/// bands it claims, which also keeps the decoder's sign rule simple: `apply_is`
4436/// flips the intensity sign when `ms_used` is set, and a band that is both is a
4437/// sign error waiting to happen.
4438///
4439/// This makes the stereo decision a genuine **3-arm dispatch** — `{L/R, M/S, IS}`
4440/// — rather than two tools overwriting each other. The anti-class is wide-stereo
4441/// music, where collapsing a band to a scaled copy destroys the image; hence the
4442/// correlation gate.
4443fn intensity_decision(
4444    spec_l: &[f32],
4445    spec_r: &[f32],
4446    swb: &[u16],
4447    sample_rate: u32,
4448) -> Vec<Option<(u8, i32)>> {
4449    /// Below this the ear localizes by waveform and intensity stereo is audible.
4450    const IS_MIN_HZ: f64 = 6000.0;
4451    /// How well `R ~= scale * L` must already hold, as |cos| between the bands.
4452    const IS_MIN_CORR: f64 = 0.85;
4453
4454    let num_swb = swb.len() - 1;
4455    let mut out = vec![None; num_swb];
4456    for sfb in 0..num_swb {
4457        let lo_hz = f64::from(swb[sfb]) * f64::from(sample_rate) * 0.5 / FRAME_LEN as f64;
4458        if lo_hz < IS_MIN_HZ {
4459            continue;
4460        }
4461        let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
4462        let e = e.min(spec_l.len()).min(spec_r.len());
4463        if e <= s {
4464            continue;
4465        }
4466        let (mut dot, mut e0, mut e1) = (0f64, 0f64, 0f64);
4467        for i in s..e {
4468            let (a, b) = (f64::from(spec_l[i]), f64::from(spec_r[i]));
4469            dot += a * b;
4470            e0 += a * a;
4471            e1 += b * b;
4472        }
4473        if e0 <= 1.0 || e1 <= 1.0 {
4474            continue;
4475        }
4476        if (dot / (e0.sqrt() * e1.sqrt())).abs() < IS_MIN_CORR {
4477            continue;
4478        }
4479        // Least-squares gain, then the syntax's log grid:
4480        // scale = 0.5^(0.25*is_pos)  =>  is_pos = -4*log2(|scale|).
4481        let scale = dot / e0;
4482        if scale.abs() < 1e-6 {
4483            continue;
4484        }
4485        let is_pos = (-4.0 * scale.abs().log2()).round() as i32;
4486        if !(-20..=60).contains(&is_pos) {
4487            continue;
4488        }
4489        out[sfb] = Some((
4490            if scale >= 0.0 {
4491                INTENSITY_HCB
4492            } else {
4493                INTENSITY_HCB2
4494            },
4495            is_pos,
4496        ));
4497    }
4498    out
4499}
4500
4501/// Encode a stereo pair as a common-window `channel_pair_element` with per-SFB M/S.
4502#[allow(clippy::too_many_arguments)]
4503fn encode_cpe(
4504    w: &mut BitWriter,
4505    tag: u32,
4506    spec_l: &[f32],
4507    spec_r: &[f32],
4508    swb: &[u16],
4509    seq: WindowSequence,
4510    sample_rate: u32,
4511    target_bits: usize,
4512    cur_kbd: bool,
4513    psy: PsyCfg,
4514) {
4515    let is_short = seq == WindowSequence::EightShort;
4516    // Arm A7 decides first, on the untouched L/R spectra, and vetoes M/S on the
4517    // bands it claims.
4518    let is_bands = if psy.intensity && !is_short {
4519        intensity_decision(spec_l, spec_r, swb, sample_rate)
4520    } else {
4521        vec![None; swb.len() - 1]
4522    };
4523    let is_veto: Vec<bool> = is_bands.iter().map(std::option::Option::is_some).collect();
4524    // Both channels share the ics_info, hence one grouping decided on both.
4525    let groups = if is_short {
4526        short_grouping(&[spec_l, spec_r], psy)
4527    } else {
4528        vec![1]
4529    };
4530    let (ch0, ch1, ms_full) = mid_side(spec_l, spec_r, swb, is_short, &is_veto, &groups);
4531    // Arm A13 ROUTING GATE.
4532    //
4533    // The joint loop is a large win when the pair is CORRELATED and a loss when
4534    // it is not — a per-class sign flip, so it is routed rather than averaged:
4535    //
4536    // | content | 64k | 128k |
4537    // |---|---|---|
4538    // | guitar stereo (correlated) | +0.23 | **+1.15** |
4539    // | piano stereo (correlated)  | +0.01 | +0.26 |
4540    // | wide/decorrelated stereo   | −0.30 | −0.04 |
4541    //
4542    // The signal is already in hand: the fraction of coded bands M/S claimed.
4543    // High means the two channels largely agree, so the side channel is cheap and
4544    // a common base lets the mid channel take the bits it is wasting. Low means
4545    // both channels carry independent content, both genuinely need their half,
4546    // and forcing a common base starves whichever is harder.
4547    //
4548    // The signal is the pair's spectral correlation, measured directly. (The M/S
4549    // flag fraction was tried first and does not separate: M/S still claims most
4550    // bands on wide content because it only needs `E_M·E_S < E_L·E_R`, which a
4551    // shared centre image satisfies.) Measured correlations:
4552    //
4553    //   L == R (ideal)   1.00   -> joint wins hugely
4554    //   guitar stereo    0.84   -> joint wins +1.15 @128k
4555    //   piano stereo     0.47   -> joint wins +0.26 @128k
4556    //   synthetic wide   0.25   -> joint LOSES -0.30 @64k
4557    //
4558    // The threshold sits in the wide gap between 0.25 and 0.47.
4559    let joint_ok = pair_correlation(spec_l, spec_r) >= JOINT_STEREO_MIN_CORR;
4560
4561    let (sf0, quant0, sf1, quant1) = if psy.stereo_bit_split && joint_ok {
4562        let off = |spec: &[f32]| -> Offsets {
4563            if is_short {
4564                short_offsets(spec, swb, sample_rate, psy, &groups)
4565            } else {
4566                perceptual_offsets(spec, swb, sample_rate, psy.tonality_smr, target_bits)
4567            }
4568        };
4569        let (mut o0, mut o1) = (off(&ch0), off(&ch1));
4570        Offsets::join(&mut o0, &mut o1);
4571        let (xp0, xp1) = (Xpow::new(&ch0), Xpow::new(&ch1));
4572        let (base, kept) = joint_rate_loop(
4573            &xp0,
4574            &o0,
4575            &xp1,
4576            &o1,
4577            swb,
4578            target_bits * 2,
4579            is_short,
4580            &groups,
4581        );
4582        let (s0, s1) = (scalefactors(&o0, base), scalefactors(&o1, base));
4583        let (q0, q1) = match kept {
4584            Some(q) => q,
4585            None if is_short => (
4586                code_frame_short(&xp0, swb, &s0, &groups).3,
4587                code_frame_short(&xp1, swb, &s1, &groups).3,
4588            ),
4589            None => (code_frame(&xp0, swb, &s0).3, code_frame(&xp1, swb, &s1).3),
4590        };
4591        (s0, q0, s1, q1)
4592    } else {
4593        let (a, b) = quantize_channel(&ch0, swb, is_short, sample_rate, target_bits, psy, &groups);
4594        let (c, d) = quantize_channel(&ch1, swb, is_short, sample_rate, target_bits, psy, &groups);
4595        (a, b, c, d)
4596    };
4597    let max_sfb = joint_max_sfb(&quant0, &quant1, swb, is_short);
4598    let cbs0 = codebooks(&quant0, swb, is_short, max_sfb, &groups);
4599    let mut cbs1 = codebooks(&quant1, swb, is_short, max_sfb, &groups);
4600    let mut sf1 = sf1;
4601    let mut ms_full = ms_full;
4602
4603    // Arm A7 — stamp the claimed bands into channel 1's codebooks/scalefactors.
4604    for (sfb, band) in is_bands.iter().enumerate().take(max_sfb) {
4605        if let (Some((cb, is_pos)), Some(slot)) = (band, cbs1.get_mut(sfb)) {
4606            *slot = *cb;
4607            sf1[sfb] = *is_pos;
4608            if let Some(m) = ms_full.get_mut(sfb) {
4609                *m = false;
4610            }
4611        }
4612    }
4613
4614    w.write(ID_CPE, 3);
4615    w.write(tag, 4);
4616    w.write(1, 1); // common_window
4617    let info = IcsInfo {
4618        window_sequence: seq,
4619        window_shape_kbd: cur_kbd,
4620        max_sfb: max_sfb as u8,
4621        num_windows: if is_short { 8 } else { 1 },
4622        num_window_groups: groups.len(),
4623        window_group_length: groups.clone(),
4624        num_swb: swb.len() - 1,
4625    };
4626    encode_ics_info(w, &info);
4627    // ms_used is per group, per band below max_sfb, in group order.
4628    let num_swb = swb.len() - 1;
4629    let ms_coded: Vec<bool> = (0..groups.len())
4630        .flat_map(|g| ms_full[g * num_swb..g * num_swb + max_sfb].iter().copied())
4631        .collect();
4632    write_ms_used(w, &ms_coded);
4633    write_channel_data(w, &cbs0, &sf0, &quant0, swb, is_short, &groups, max_sfb);
4634    write_channel_data(w, &cbs1, &sf1, &quant1, swb, is_short, &groups, max_sfb);
4635}
4636
4637// ---------------------------------------------------------------------------
4638// The encoder: buffers input, blocks into 1024-sample long frames, emits raw
4639// access units (add ADTS or MP4 framing around them as needed).
4640// ---------------------------------------------------------------------------
4641
4642/// Window-shape policy — **arm A8, Rung 0** of `docs/finished/codec-aac-great-gate.md`.
4643///
4644/// `window_shape` is a *free syntax element*: one bit already carried in every
4645/// `ics_info`, costing nothing to set either way, with both shapes implemented on
4646/// the decode side since day one. It shipped hardcoded to sine — census category 3.
4647#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
4648pub enum WindowShape {
4649    /// Sine everywhere. **The neutral end**: byte-identical with the encoder as
4650    /// it shipped before Rung 0 (proven by `shape_sine_is_byte_identical`).
4651    #[default]
4652    Sine,
4653    /// KBD everywhere. Not a shipping mode — the *force-on* arm the calculator
4654    /// needs: great-gate §4 requires force-on-everywhere to nearly tie the anchor
4655    /// on the full ladder before a dispatch is built on it, because a big force-on
4656    /// gap predicts a dominated dispatch.
4657    Kbd,
4658    /// **PROVISIONAL** (law 5). Per-frame dispatch on content tonality. Off by
4659    /// default until the calculator banks a threshold from a harvest carrying the
4660    /// full speed pair (law 7's opt-in → default-on ladder).
4661    Auto,
4662}
4663
4664/// Coding bandwidth policy: the highest frequency the encoder codes.
4665///
4666/// Bands that start at or above the cutoff are not coded (`ZERO_HCB`), in long
4667/// and short blocks alike, for every channel except the LFE (which has its own
4668/// band limit).
4669#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
4670#[non_exhaustive]
4671pub enum Bandwidth {
4672    /// Code the whole spectrum at every bitrate: the encoder as it shipped in
4673    /// 2.1.2 (byte-identical).
4674    Full,
4675    /// A cutoff from the bitrate and channel count (see [`auto_bandwidth_hz`]):
4676    /// 17 kHz under 192 kbps, 20 kHz from there to under 160 kbps a channel,
4677    /// the whole spectrum above. The default.
4678    #[default]
4679    Auto,
4680    /// A fixed cutoff in Hz.
4681    Hz(u32),
4682}
4683
4684/// The [`Bandwidth::Auto`] cutoff in Hz for a stream of `bitrate_bps` over
4685/// `channels` at `sample_rate`, or `None` for the whole spectrum.
4686///
4687/// 17 kHz while the stream is under 192 kbps in total and at most 128 kbps a
4688/// channel; the whole spectrum above. Measured (PEAQ, `rusty_aac` 2.1.2 vs the same
4689/// encoder band-limited, decoder FFmpeg 8.1.2):
4690///
4691/// * real music, 64-128 kbps: 17 kHz +0.015 BD-ODG over 6 clips, within
4692///   ±0.04 on every one: the rate loop already leaves little above it;
4693/// * flat-spectrum content (noise, noisy speech), 64-128 kbps: +2.1 and +2.0
4694///   BD-ODG. Coding 17-22 kHz costs a flat spectrum about a quarter of its
4695///   bits, and PEAQ marks the 18-20 kHz region on such content hard: both
4696///   FFmpeg versions lose ~2 ODG between 96 kbps (18 kHz cutoff) and 128 kbps
4697///   (20 kHz) on the same clip;
4698/// * at 256 kbps stereo (128 kbps a channel) real music started to lose
4699///   (-0.06 on one clip, -0.08 on one channel scored alone), hence the
4700///   total-rate ceiling: from 192 kbps up the bandwidth is the 2.1.2 one.
4701///
4702/// Above that, and under [`AUTO_BANDWIDTH_HIGH_MAX_BPS_PER_CHANNEL`] a
4703/// channel (stereo from 192 up to 318 kbps, mono from 129 to 159 kbps), the
4704/// cutoff is [`AUTO_BANDWIDTH_HIGH_HZ`]; from there up, the whole spectrum.
4705///
4706/// Mono and stereo only: no multichannel layout was measured, so 3 or more
4707/// channels keep the whole spectrum, as in 2.1.2.
4708#[must_use]
4709pub fn auto_bandwidth_hz(bitrate_bps: u32, channels: u16, sample_rate: u32) -> Option<u32> {
4710    let per_channel = bitrate_bps / u32::from(channels.max(1));
4711    let hz = if channels > 2 {
4712        None
4713    } else if bitrate_bps < AUTO_BANDWIDTH_MAX_BPS
4714        && per_channel <= AUTO_BANDWIDTH_MAX_BPS_PER_CHANNEL
4715    {
4716        Some(AUTO_BANDWIDTH_HZ)
4717    } else if per_channel < AUTO_BANDWIDTH_HIGH_MAX_BPS_PER_CHANNEL {
4718        Some(AUTO_BANDWIDTH_HIGH_HZ)
4719    } else {
4720        None
4721    };
4722    hz.filter(|&hz| hz < sample_rate / 2)
4723}
4724
4725/// The [`Bandwidth::Auto`] cutoff (see [`auto_bandwidth_hz`]).
4726const AUTO_BANDWIDTH_HZ: u32 = 17_000;
4727/// [`Bandwidth::Auto`] limits only streams under this total rate.
4728const AUTO_BANDWIDTH_MAX_BPS: u32 = 192_000;
4729/// [`Bandwidth::Auto`] limits only streams at or under this rate a channel.
4730const AUTO_BANDWIDTH_MAX_BPS_PER_CHANNEL: u32 = 128_000;
4731
4732/// The [`Bandwidth::Auto`] cutoff from 192 kbps (stereo) up to
4733/// [`AUTO_BANDWIDTH_HIGH_MAX_BPS_PER_CHANNEL`].
4734///
4735/// Coding 20-24 kHz at these rates takes bits the audible band needs: on
4736/// 48 kHz content with energy up there (music recorded to 24 kHz, noise, an
4737/// electronic patch) the noise below 20 kHz drops by 1 to 3 dB and PEAQ's
4738/// noise-to-mask ratio by 0.5 to 3 dB. PEAQ ODG with both signals low-passed
4739/// at 21 kHz (so its bandwidth measure, which reads the reference's bandwidth
4740/// off the decoded signal above 21.6 kHz and gave a 20 kHz cutoff up to +1.9
4741/// ODG on its own, plays no part), 8 such music clips x 4 time offsets:
4742/// +0.017 at 192 kbps stereo, +0.019 at 224 and +0.004 at 256, no clip worse
4743/// than -0.017 +- 0.013; noise-like content +0.12 to +0.17. A lower cutoff
4744/// scores higher still, but this PEAQ hears little above 18 kHz, so the
4745/// sweep has no optimum to read; 20 kHz is the edge of hearing (FFmpeg 9.1
4746/// cuts at 19.4 and 20.9 kHz at 96 and 128 kbps a channel). Waveform SNR on
4747/// content with energy above 20 kHz falls (white noise at 256 kbps 11.6 ->
4748/// 7.2 dB), since that energy is no longer coded.
4749const AUTO_BANDWIDTH_HIGH_HZ: u32 = 20_000;
4750
4751/// [`AUTO_BANDWIDTH_HIGH_HZ`] applies under this rate a channel. At 160 kbps
4752/// a channel (320 kbps stereo) the same cutoff was neutral on music to -0.04
4753/// ODG on three clips, so from there up the whole spectrum is coded, as before.
4754const AUTO_BANDWIDTH_HIGH_MAX_BPS_PER_CHANNEL: u32 = 160_000;
4755
4756/// The first spectral line not coded under `hz` for a window of `n_coeffs`
4757/// lines (`usize::MAX` for no limit): the start of the first band at or above
4758/// the cutoff, so the limit always falls on a band edge.
4759fn cutoff_line(hz: Option<u32>, sample_rate: u32, swb: &[u16], n_coeffs: usize) -> usize {
4760    let Some(hz) = hz else {
4761        return usize::MAX;
4762    };
4763    let line =
4764        (u64::from(hz) * 2 * n_coeffs as u64).div_ceil(u64::from(sample_rate.max(1))) as usize;
4765    swb.iter()
4766        .map(|&s| usize::from(s))
4767        .find(|&s| s >= line)
4768        .unwrap_or(usize::MAX)
4769}
4770
4771/// Bounds on a frame's share of its segment under
4772/// [`AacTuning::frame_demand`], as multiples of the constant-rate share.
4773const DEMAND_MIN_SHARE: f64 = 0.35;
4774const DEMAND_MAX_SHARE: f64 = 2.5;
4775
4776/// Per-frame weights (multiples of the constant-rate share, mean 1) from the
4777/// frames' perceptual entropies `pe`: `(pe / mean)^alpha`, clamped to
4778/// [`DEMAND_MIN_SHARE`, `DEMAND_MAX_SHARE`] and renormalised to mean 1.
4779fn frame_demand_weights(pe: &[f64], alpha: f64) -> Vec<f64> {
4780    let n = pe.len().max(1) as f64;
4781    let mean = pe.iter().sum::<f64>() / n;
4782    if mean <= 0.0 || alpha <= 0.0 {
4783        return vec![1.0; pe.len()];
4784    }
4785    let mut w: Vec<f64> = pe
4786        .iter()
4787        .map(|&p| (p.max(0.0) / mean).powf(alpha))
4788        .collect();
4789    for _ in 0..4 {
4790        let m = w.iter().sum::<f64>() / n;
4791        if m <= 0.0 {
4792            return vec![1.0; pe.len()];
4793        }
4794        for x in &mut w {
4795            *x = (*x / m).clamp(DEMAND_MIN_SHARE, DEMAND_MAX_SHARE);
4796        }
4797    }
4798    let m = w.iter().sum::<f64>() / n;
4799    w.iter().map(|x| x / m).collect()
4800}
4801
4802/// Zero every line at or above `cut` in each of `nwin` windows of `wlen` lines.
4803fn band_limit(spec: &mut [f32], cut: usize, wlen: usize) {
4804    if cut >= wlen {
4805        return;
4806    }
4807    for w in spec.chunks_mut(wlen) {
4808        w[cut..].fill(0.0);
4809    }
4810}
4811
4812/// Encoder options.
4813#[derive(Debug, Clone, Copy)]
4814pub struct AacEncoderConfig {
4815    /// Target bitrate in bits per second. Drives the per-frame rate loop.
4816    /// Default: 128 000 (128 kbps).
4817    pub bitrate_bps: u32,
4818    /// Window-shape policy (arm A8). Default [`WindowShape::Sine`] — the
4819    /// byte-identical neutral end.
4820    pub window_shape: WindowShape,
4821    /// The [`WindowShape::Auto`] gate's threshold, as a **percentile of this
4822    /// clip's own** frame-tonality distribution (great-gate law 1: a
4823    /// population-relative threshold transfers to content the fit never saw; an
4824    /// absolute one does not). Frames above it code with KBD.
4825    ///
4826    /// Default 0.5 is a **placeholder, not a fitted value** — the calculator has
4827    /// not banked this rung yet. `aacharvest` emits the CSV that will decide it.
4828    pub shape_tonality_pct: f32,
4829    /// **Arm A1, Rung 1** — run the psychoacoustic model on short blocks instead
4830    /// of coding them with flat scalefactors. Default `false` (byte-identical).
4831    pub short_block_psy: bool,
4832    /// **Arm 1a, Rung 1** — split each short-block frame into window groups of
4833    /// similar energy and shape scalefactors per group (the short-block psy model
4834    /// run per group, centred jointly so a quiet pre-attack group is coded finer
4835    /// than the attack). Default `false` (byte-identical).
4836    pub window_grouping: bool,
4837    /// **Arm A2, Rung 2** — make the signal-to-mask ratio a function of band
4838    /// tonality instead of a flat 18 dB. Default `false` (byte-identical).
4839    pub tonality_smr: bool,
4840    /// **Arm A3, Rung 3** — emit TNS on long blocks. Default `false`
4841    /// (`tns_data_present = 0`, byte-identical).
4842    pub tns: bool,
4843    /// **Arm A9** — use the level-invariant transient detector. Default `false`
4844    /// (byte-identical). Arm A1 is unmeasurable without this.
4845    pub relative_transients: bool,
4846    /// **Arm A6** — Perceptual Noise Substitution on long blocks. Default `false`
4847    /// (byte-identical).
4848    pub pns: bool,
4849    /// **Arm A7** — intensity stereo on long-block CPEs. Default `false`
4850    /// (byte-identical).
4851    pub intensity: bool,
4852    /// **Arm A13** — split a channel pair's bit budget by perceptual demand
4853    /// rather than evenly. Default `false` (byte-identical).
4854    pub stereo_bit_split: bool,
4855}
4856
4857impl Default for AacEncoderConfig {
4858    fn default() -> Self {
4859        Self {
4860            bitrate_bps: 128_000,
4861            window_shape: WindowShape::Sine,
4862            shape_tonality_pct: 0.5,
4863            short_block_psy: false,
4864            window_grouping: false,
4865            tonality_smr: false,
4866            tns: false,
4867            // DEFAULT ON — measured wins vs the previous default, PEAQ ODG:
4868            //   A9  mean +0.267, worst +0.000 (percussive +1.8, clean speech
4869            //       +1.1..+2.6, exactly 0.00 on every other class)
4870            //   A13 guitar stereo +1.17 @128k, piano stereo +0.22, routed by
4871            //       pair correlation so wide stereo is not harmed
4872            relative_transients: true,
4873            pns: false,
4874            intensity: false,
4875            stereo_bit_split: true,
4876        }
4877    }
4878}
4879
4880/// The low-rate coding tools added in 2.2: the section trellis, the
4881/// high-passed transient detector, the coding bandwidth, frame-demand bit
4882/// allocation and the mask SMR.
4883///
4884/// Kept apart from [`AacEncoderConfig`] so that config keeps the field set it
4885/// had in 2.1 (a struct literal naming every field still compiles). Pass one
4886/// to [`AacEncoder::with_tuning`]; [`AacEncoder::new`] uses
4887/// [`AacTuning::default`], the shipping tools. [`AacTuning::legacy`] is the
4888/// 2.1.2 encoder, bit for bit.
4889///
4890/// `#[non_exhaustive]`: build one from [`Default`] or [`AacTuning::legacy`]
4891/// and set the fields you want.
4892///
4893/// ```
4894/// use rusty_aac::{AacEncoder, AacEncoderConfig, AacTuning};
4895/// let mut tuning = AacTuning::default();
4896/// tuning.frame_demand = 0.0; // every frame at its constant-rate share
4897/// let enc = AacEncoder::with_tuning(AacEncoderConfig::default(), tuning);
4898/// assert_eq!(enc.tuning(), tuning);
4899/// ```
4900#[derive(Debug, Clone, Copy, PartialEq)]
4901#[non_exhaustive]
4902pub struct AacTuning {
4903    /// Coding bandwidth policy. Default [`Bandwidth::Auto`];
4904    /// [`Bandwidth::Full`] is the 2.1.2 encoder.
4905    pub bandwidth: Bandwidth,
4906    /// Inter-frame bit allocation strength: each frame of a 32-frame
4907    /// reservoir segment gets the segment's bits in proportion to its
4908    /// perceptual entropy raised to this power (clamped to 0.35-2.5 times the
4909    /// constant-rate share), so the segment, and the stream, keep their rate.
4910    /// Default `0.5`; `0.0` gives every frame the constant-rate share, the
4911    /// 2.1.2 encoder. Whole-clip encodes only: a streaming encode always uses
4912    /// the constant-rate share.
4913    pub frame_demand: f32,
4914    /// Run the level-invariant transient detector (arm A9) on a high-passed
4915    /// signal (second difference, +12 dB/octave). A plucked or struck note
4916    /// whose attack lives in its high frequencies, over a sustained body that
4917    /// dominates the plain energy, is then switched to short blocks. Default
4918    /// `true`; `false` is the 2.1.2 detector. No effect with
4919    /// `relative_transients` off.
4920    pub transient_highpass: bool,
4921    /// Choose each frame's codebooks by a Viterbi trellis over `section_data`
4922    /// (spectral bits plus section headers, an all-zero band free to ride in
4923    /// a neighbouring section) instead of the cheapest book band by band,
4924    /// which opened a new 9-bit section at nearly every band: 16-17% of a
4925    /// 64 kbps frame, against 3% for FFmpeg. Default `true`; `false` is the
4926    /// 2.1.2 encoder.
4927    pub section_trellis: bool,
4928    /// The psychoacoustic model's flat signal-to-mask ratio, in dB: how far
4929    /// below each band's spread energy its masking threshold sits, before the
4930    /// threshold in quiet and the starved-frame reduction, for mono and stereo
4931    /// streams under 96 kbps a channel (from 96 kbps a channel up, and for 3
4932    /// or more channels, the mask is 18 dB whatever this says).
4933    /// Default `24.0`; `18.0` is the 2.1.2 encoder (bit for bit). A deeper mask makes the
4934    /// rate loop reach the starved-frame reduction sooner, which keeps the
4935    /// precision of a frame's loud, tonal bands and coarsens its quiet ones:
4936    /// at 64 kbps a sung voice's 0-4 kHz went from 16-20 dB SNR to 19-23 dB.
4937    pub mask_smr_db: f32,
4938    /// Spend bits left over far below the masks on the bands that carry the
4939    /// signal, not evenly on every band (for mono and stereo streams from 96
4940    /// kbps a channel; no effect on others). Default `true`; `false` is the
4941    /// 2.1.2 encoder.
4942    pub surplus_shaping: bool,
4943}
4944
4945impl Default for AacTuning {
4946    /// The shipping tools — measured vs 2.1.2, PEAQ BD-ODG over 6 real clips at
4947    /// 64-128 kbps, each tool alone: section trellis +0.223 (every clip and
4948    /// rate better), high-passed transients +0.087, frame demand 0.5 +0.031
4949    /// (synthetic +0.25), bandwidth `Auto` +0.015 (synthetic noise +2.0);
4950    /// together +0.291; mask SMR 24 dB +0.097 on top (stereo vocal +0.41).
4951    fn default() -> Self {
4952        Self {
4953            bandwidth: Bandwidth::Auto,
4954            frame_demand: 0.5,
4955            transient_highpass: true,
4956            section_trellis: true,
4957            mask_smr_db: 24.0,
4958            surplus_shaping: true,
4959        }
4960    }
4961}
4962
4963impl AacTuning {
4964    /// Every 2.2 tool off: the `rusty_aac` 2.1.2 encoder, bit for bit.
4965    #[must_use]
4966    pub const fn legacy() -> Self {
4967        Self {
4968            bandwidth: Bandwidth::Full,
4969            frame_demand: 0.0,
4970            transient_highpass: false,
4971            section_trellis: false,
4972            mask_smr_db: 18.0,
4973            surplus_shaping: false,
4974        }
4975    }
4976}
4977
4978/// One encoded raw access unit (a `raw_data_block`, no ADTS framing).
4979#[derive(Debug, Clone)]
4980pub struct EncodedPacket {
4981    pub data: Vec<u8>,
4982    /// Presentation timestamp in samples (frame index × 1024).
4983    pub pts: i64,
4984    /// Duration in samples (always one AAC frame = 1024).
4985    pub duration: u32,
4986}
4987
4988/// Encoding tables a stream needs, built once from its rate and channels.
4989struct Tables {
4990    swb: &'static [u16],
4991    swb_s: &'static [u16],
4992    sine_s: Vec<f32>,
4993    kbd_s: Vec<f32>,
4994    plan: Vec<Elem>,
4995}
4996
4997/// Frames per bit-reservoir segment. The reservoir restarts empty at every
4998/// multiple of this frame index, so a segment encodes on its own: whole-clip
4999/// encodes fan segments out across threads, streaming encodes walk them in
5000/// order, and both produce the same bytes whatever the thread count.
5001const RESERVOIR_SEGMENT: usize = 32;
5002
5003/// The bit reservoir: bits the stream is ahead of (positive) or behind its
5004/// constant-rate channel.
5005///
5006/// Each frame is coded to the largest budget it fits, and the rate loop's
5007/// steps are coarse (one scalefactor step moves a frame by 5-15% of its bits),
5008/// so frames land short of their budget by half a step on average. With no
5009/// carry that shortfall was simply lost: 2.5-9% under the target bitrate, and
5010/// 13% for mono at 53 kbps (`remade_ffmpeg_rs#129`). Banking it and adding the
5011/// bank to the next frame's budget makes the stream's average land on the
5012/// target (an overshoot banks negative and is taken back the same way), while
5013/// the bank stays about one frame's shortfall, far inside the decoder buffer
5014/// (6144 bits a channel, ISO 14496-3 §4.5.3).
5015#[derive(Debug, Clone, Copy, Default)]
5016struct Reservoir {
5017    bank: i64,
5018}
5019
5020impl Reservoir {
5021    /// Frame `b`'s budget: what the channel delivers for it plus the bank,
5022    /// never past the decoder buffer.
5023    fn budget(&mut self, b: usize, mean: usize, channels: usize) -> usize {
5024        if b % RESERVOIR_SEGMENT == 0 {
5025            self.bank = 0;
5026        }
5027        let cap = (6144 * channels) as i64;
5028        let floor = (mean as i64 / 2).min(cap);
5029        (mean as i64 + self.bank).clamp(floor, cap) as usize
5030    }
5031
5032    /// Settle frame `b` after it coded to `used` bits.
5033    fn spend(&mut self, mean: usize, used: usize, channels: usize) {
5034        let max_bank = (6144 * channels).saturating_sub(mean) as i64;
5035        self.bank = (self.bank + mean as i64 - used as i64).clamp(-(mean as i64) / 2, max_bank);
5036    }
5037}
5038
5039/// The transient detector run a frame at a time, for streaming: the same rule
5040/// as [`detect_transients`] (absolute guard) and [`detect_transients_relative`]
5041/// (floor relative to the signal's mean sub-block energy). A stream does not
5042/// know its whole clip's mean until the end, so the relative floor uses the
5043/// mean of the sub-blocks seen so far, this frame's included. The absolute
5044/// detector needs nothing ahead and gives the whole-clip flags exactly.
5045#[derive(Clone, Default)]
5046struct Detector {
5047    avg: f64,
5048    sum: f64,
5049    count: u64,
5050}
5051
5052impl Detector {
5053    fn frame(&mut self, sub: &[f64; 8], f: usize, relative: bool) -> bool {
5054        if relative {
5055            self.sum += sub.iter().sum::<f64>();
5056            self.count += 8;
5057            let floor = (self.sum / self.count as f64 * 1e-3).max(f64::MIN_POSITIVE);
5058            let mut amax = 1.0f32;
5059            for &e in sub {
5060                amax = amax.max((e / self.avg.max(floor)) as f32);
5061                self.avg = 0.75 * self.avg + 0.25 * e;
5062            }
5063            f > 0 && amax > 10.0
5064        } else {
5065            let mut attack = 1.0f64;
5066            for &e in sub {
5067                if self.avg > 1e-3 {
5068                    attack = attack.max(e / self.avg);
5069                }
5070                self.avg = 0.75 * self.avg + 0.25 * e;
5071            }
5072            f > 0 && attack > 10.0
5073        }
5074    }
5075}
5076
5077/// [`AacEncoder::set_streaming`] state: what has been analysed and encoded.
5078struct Streaming {
5079    tables: Tables,
5080    /// Per channel.
5081    det: Vec<Detector>,
5082    /// Per channel: each analysed frame's raw transient flag.
5083    flags: Vec<Vec<bool>>,
5084    /// Per element: each frame's final window sequence.
5085    seqs: Vec<Vec<WindowSequence>>,
5086    /// Per frame: KBD (true) or sine window shape.
5087    shapes: Vec<bool>,
5088    /// Frames whose transient flags are known.
5089    analysed: usize,
5090    /// The next frame to encode.
5091    next: usize,
5092    /// The bit reservoir, carried from frame to frame.
5093    reservoir: Reservoir,
5094}
5095
5096/// AAC-LC encoder. Push PCM with [`push_pcm`](AacEncoder::push_pcm) (or
5097/// [`push_pcm_planar`](AacEncoder::push_pcm_planar)), call
5098/// [`finish`](AacEncoder::finish), then drain [`next_packet`](AacEncoder::next_packet)
5099/// until it returns [`Error::Eof`].
5100///
5101/// By default every frame is encoded inside `finish`, from a whole-clip
5102/// analysis. [`set_streaming`](AacEncoder::set_streaming) encodes as the PCM
5103/// arrives instead: packets come out of `next_packet` two frames behind the
5104/// input, and memory stays at a few frames however long the stream is. The
5105/// encoder's delay and padding, for an MP4 edit list, are
5106/// [`priming_samples`](AacEncoder::priming_samples) and
5107/// [`padding_samples`](AacEncoder::padding_samples).
5108pub struct AacEncoder {
5109    sample_rate: u32,
5110    channels: usize,
5111    fs_index: u8,
5112    /// Target bitrate (bits/s). Drives the per-frame rate loop.
5113    bitrate: u32,
5114    /// Arm A8 policy and its provisional threshold.
5115    window_shape: WindowShape,
5116    shape_tonality_pct: f32,
5117    short_block_psy: bool,
5118    window_grouping: bool,
5119    tonality_smr: bool,
5120    tns: bool,
5121    relative_transients: bool,
5122    pns: bool,
5123    intensity: bool,
5124    stereo_bit_split: bool,
5125    bandwidth: Bandwidth,
5126    frame_demand: f32,
5127    transient_highpass: bool,
5128    section_trellis: bool,
5129    mask_smr_db: f32,
5130    surplus_shaping: bool,
5131    win: Vec<f32>,
5132    /// The KBD long window (α = 4.0), matching the decoder's. Built once.
5133    win_kbd: Vec<f32>,
5134    chans: Vec<Vec<f32>>,
5135    initialized: bool,
5136    /// Encoded raw access units (`raw_data_block`, no ADTS) awaiting `next_packet`,
5137    /// each with its sample-domain PTS. Filled on `finish` (or as frames
5138    /// complete, when streaming).
5139    queue: VecDeque<(Vec<u8>, i64)>,
5140    flushed: bool,
5141    /// Samples pushed per channel.
5142    total_in: u64,
5143    /// Blocks dropped from the front of `chans` (streaming); `chans[c][0]` is
5144    /// sample `base_block * FRAME_LEN` of the stream. 0 for a whole-clip encode.
5145    base_block: usize,
5146    streaming: bool,
5147    stream: Option<Box<Streaming>>,
5148}
5149
5150impl AacEncoder {
5151    /// An encoder with `config` and the shipping low-rate tools
5152    /// ([`AacTuning::default`]).
5153    #[must_use]
5154    pub fn new(config: AacEncoderConfig) -> Self {
5155        Self::with_tuning(config, AacTuning::default())
5156    }
5157
5158    /// An encoder with `config` and the low-rate tools set by `tuning`
5159    /// ([`AacTuning::legacy`] for the 2.1.2 encoder).
5160    #[must_use]
5161    pub fn with_tuning(config: AacEncoderConfig, tuning: AacTuning) -> Self {
5162        Self {
5163            sample_rate: 0,
5164            channels: 0,
5165            fs_index: 0,
5166            bitrate: config.bitrate_bps.max(1),
5167            window_shape: config.window_shape,
5168            shape_tonality_pct: config.shape_tonality_pct,
5169            short_block_psy: config.short_block_psy,
5170            window_grouping: config.window_grouping,
5171            tonality_smr: config.tonality_smr,
5172            tns: config.tns,
5173            relative_transients: config.relative_transients,
5174            pns: config.pns,
5175            intensity: config.intensity,
5176            stereo_bit_split: config.stereo_bit_split,
5177            bandwidth: tuning.bandwidth,
5178            frame_demand: if tuning.frame_demand.is_finite() {
5179                tuning.frame_demand.clamp(0.0, 4.0)
5180            } else {
5181                0.0
5182            },
5183            transient_highpass: tuning.transient_highpass,
5184            section_trellis: tuning.section_trellis,
5185            mask_smr_db: if tuning.mask_smr_db.is_finite() {
5186                tuning.mask_smr_db.clamp(6.0, 40.0)
5187            } else {
5188                18.0
5189            },
5190            surplus_shaping: tuning.surplus_shaping,
5191            win: Vec::new(),
5192            win_kbd: Vec::new(),
5193            chans: Vec::new(),
5194            initialized: false,
5195            queue: VecDeque::new(),
5196            flushed: false,
5197            total_in: 0,
5198            base_block: 0,
5199            streaming: false,
5200            stream: None,
5201        }
5202    }
5203
5204    /// The low-rate tools this encoder codes with (out-of-range strengths
5205    /// clamped as [`with_tuning`](Self::with_tuning) applied them).
5206    #[must_use]
5207    pub fn tuning(&self) -> AacTuning {
5208        AacTuning {
5209            bandwidth: self.bandwidth,
5210            frame_demand: self.frame_demand,
5211            transient_highpass: self.transient_highpass,
5212            section_trellis: self.section_trellis,
5213            mask_smr_db: self.mask_smr_db,
5214            surplus_shaping: self.surplus_shaping,
5215        }
5216    }
5217
5218    /// Encode as the PCM arrives instead of all at [`finish`](Self::finish):
5219    /// after each push, every frame whose window decisions are final (two
5220    /// frames behind the input) is encoded and queued for
5221    /// [`next_packet`](Self::next_packet), and the samples behind it are
5222    /// dropped. Memory stays at a few frames for a stream of any length.
5223    ///
5224    /// Call it before the first push; later calls are ignored. Differences
5225    /// from the default whole-clip encode, which needs the clip's end:
5226    /// the level-invariant transient detector (on by default) floors its
5227    /// running average at the mean energy seen so far rather than the whole
5228    /// clip's, so quiet openings can switch to short blocks at slightly
5229    /// different frames; [`WindowShape::Auto`] codes every frame with the
5230    /// sine window; and every frame gets its constant-rate share of the bits
5231    /// (frame-demand allocation, [`AacTuning::frame_demand`], needs a
5232    /// whole reservoir segment ahead). With `relative_transients: false` and
5233    /// [`AacTuning::frame_demand`] 0 the packets are byte-identical to the whole-clip
5234    /// encode.
5235    pub fn set_streaming(&mut self, on: bool) {
5236        if self.total_in == 0 && !self.flushed {
5237            self.streaming = on;
5238        }
5239    }
5240
5241    /// Samples of encoder delay at the start of the decoded output: decoded
5242    /// sample `t` is input sample `t - priming_samples()`. 1024 for AAC-LC (one
5243    /// MDCT frame of overlap). The `media_time` of an MP4 edit list, and the
5244    /// first number of an `iTunSMPB`.
5245    #[must_use]
5246    pub fn priming_samples(&self) -> u32 {
5247        FRAME_LEN as u32
5248    }
5249
5250    /// Samples of padding after the last input sample in the decoded output,
5251    /// known once [`finish`](Self::finish) has run: the decoded stream is
5252    /// `priming + input + padding` samples long, a whole number of 1024-sample
5253    /// frames. The last number of an `iTunSMPB`; the edit list's segment
5254    /// duration is the input length.
5255    #[must_use]
5256    pub fn padding_samples(&self) -> Option<u32> {
5257        if !self.flushed || !self.initialized {
5258            return None;
5259        }
5260        let n = self.total_in;
5261        Some((n.div_ceil(FRAME_LEN as u64) * FRAME_LEN as u64 - n) as u32)
5262    }
5263
5264    /// The stream's sample rate (0 until the first PCM is pushed).
5265    #[must_use]
5266    pub fn sample_rate(&self) -> u32 {
5267        self.sample_rate
5268    }
5269
5270    /// The stream's channel count (0 until the first PCM is pushed).
5271    #[must_use]
5272    pub fn channels(&self) -> u16 {
5273        self.channels as u16
5274    }
5275
5276    /// Initialize (or validate) the stream parameters from a PCM push.
5277    fn init(&mut self, channels: u16, sample_rate: u32) -> Result<()> {
5278        if !self.initialized {
5279            self.sample_rate = sample_rate;
5280            self.channels = channels.max(1) as usize;
5281            // Reject counts with no `channel_configuration`. Writing a config the
5282            // element sequence does not match produces a stream that only our own
5283            // decoder accepts — the bug this check exists to make impossible.
5284            if element_plan(self.channels).is_none() {
5285                return Err(Error::unsupported(
5286                    "aac encode: only 1-6 channels are supported (7+ needs a                      program_config_element, which is not implemented)",
5287                ));
5288            }
5289            self.fs_index = crate::sf_index_for_rate(sample_rate)
5290                .ok_or_else(|| Error::invalid("aac encode: unsupported sample rate"))?;
5291            self.win = crate::dsp::sine_window(LONG_N);
5292            // Arm A8's second shape. α = 4.0 for the long window matches the
5293            // decoder's `kbd` exactly — a mismatched α is not a quality choice,
5294            // it breaks TDAC and leaves audible seams at every overlap.
5295            self.win_kbd = crate::dsp::kbd_window(LONG_N, 4.0);
5296            self.chans = vec![Vec::new(); self.channels];
5297            self.initialized = true;
5298        } else if channels.max(1) as usize != self.channels {
5299            return Err(Error::invalid(
5300                "aac encode: channel count changed mid-stream",
5301            ));
5302        }
5303        Ok(())
5304    }
5305
5306    /// Buffer interleaved `f32` PCM in [-1, 1] (`interleaved.len()` must be a
5307    /// multiple of `channels`). The first push fixes the stream's channel count
5308    /// and sample rate. Samples beyond ±[`MAX_INPUT_AMPLITUDE`] are clamped and
5309    /// NaN becomes silence, so no input can push a block past the decoder
5310    /// buffer.
5311    ///
5312    /// # Errors
5313    ///
5314    /// Returns [`Error::Unsupported`] for more than six channels,
5315    /// [`Error::InvalidData`] for a non-standard sample rate, and
5316    /// [`Error::InvalidData`] if `channels` differs from the first push.
5317    pub fn push_pcm(&mut self, interleaved: &[f32], channels: u16, sample_rate: u32) -> Result<()> {
5318        self.init(channels, sample_rate)?;
5319        let ch = self.channels;
5320        let n = interleaved.len() / ch;
5321        // Reserve once, then one pass per channel: a per-sample push grew each
5322        // channel buffer by doubling (a realloc + copy of everything so far, ~log2
5323        // of the stream per channel). Mono is a straight slice copy.
5324        if ch == 1 {
5325            self.chans[0].extend(interleaved[..n].iter().map(|&x| sanitize(x)));
5326        } else {
5327            for (c, dst) in self.chans.iter_mut().enumerate().take(ch) {
5328                dst.reserve(n);
5329                dst.extend(
5330                    interleaved[..n * ch]
5331                        .iter()
5332                        .skip(c)
5333                        .step_by(ch)
5334                        .map(|&x| sanitize(x)),
5335                );
5336            }
5337        }
5338        self.total_in += n as u64;
5339        if self.streaming {
5340            self.stream_advance(false);
5341        }
5342        Ok(())
5343    }
5344
5345    /// Buffer planar `f32` PCM, one slice per channel (`planes.len()` is the
5346    /// channel count; all planes the same length).
5347    ///
5348    /// # Errors
5349    ///
5350    /// As [`push_pcm`](Self::push_pcm).
5351    pub fn push_pcm_planar(&mut self, planes: &[&[f32]], sample_rate: u32) -> Result<()> {
5352        self.init(planes.len() as u16, sample_rate)?;
5353        let n = planes
5354            .iter()
5355            .take(self.channels)
5356            .map(|p| p.len())
5357            .min()
5358            .unwrap_or(0);
5359        for (c, plane) in planes.iter().enumerate().take(self.channels) {
5360            self.chans[c].extend(plane[..n].iter().map(|&x| sanitize(x)));
5361        }
5362        self.total_in += n as u64;
5363        if self.streaming {
5364            self.stream_advance(false);
5365        }
5366        Ok(())
5367    }
5368
5369    /// Encode all buffered samples into per-frame raw access units (`raw_data_block`,
5370    /// no ADTS) with sample-domain PTS. A trailing all-zero block flushes the MDCT
5371    /// overlap so the final audio block decodes. Containers add their own framing
5372    /// (ADTS header for `.aac`, `esds` + raw samples for MP4).
5373    /// Block `b` of channel `ch`, borrowed straight from the buffered input when
5374    /// it lies wholly inside it; only a block running past the end is built
5375    /// (zero-padded). Every frame used to copy four 4 KB blocks this way.
5376    fn block_cow(&self, ch: usize, b: usize) -> std::borrow::Cow<'_, [f32; FRAME_LEN]> {
5377        let s = (b - self.base_block) * FRAME_LEN;
5378        match self.chans[ch].get(s..s + FRAME_LEN) {
5379            Some(x) => std::borrow::Cow::Borrowed(x.try_into().expect("FRAME_LEN samples")),
5380            None => std::borrow::Cow::Owned(self.block(ch, b)),
5381        }
5382    }
5383
5384    /// One block's samples for channel `ch` (zero-padded past the buffered input).
5385    fn block(&self, ch: usize, b: usize) -> [f32; FRAME_LEN] {
5386        let mut cur = [0f32; FRAME_LEN];
5387        let at = (b - self.base_block) * FRAME_LEN;
5388        for (i, s) in cur.iter_mut().enumerate() {
5389            *s = self.chans[ch].get(at + i).copied().unwrap_or(0.0);
5390        }
5391        cur
5392    }
5393
5394    /// Encode one frame `b` to its raw access unit + PTS. A pure function of the
5395    /// buffered input, the window sequences, and `b` — the previous block (for MDCT
5396    /// overlap) is just block `b-1`'s samples — so frames encode **independently**.
5397    #[allow(clippy::too_many_arguments)]
5398    #[allow(clippy::too_many_arguments)]
5399    fn encode_frame(
5400        &self,
5401        b: usize,
5402        swb: &[u16],
5403        swb_s: &[u16],
5404        sine_s: &[f32],
5405        kbd_s: &[f32],
5406        seqs: &[Vec<WindowSequence>],
5407        shapes: &[bool],
5408        frame_budget: usize,
5409        plan: &[Elem],
5410        pre: Option<&[Option<Vec<f32>>]>,
5411    ) -> (Vec<u8>, i64) {
5412        // Per-channel ICS-body budget: the frame less END (3 bits), split
5413        // evenly, less each element's own header (7). Never above the decoder
5414        // input buffer (ISO 14496-3 §4.5.3: 6144 bits per channel) less that
5415        // overhead: an absurd bitrate must not yield a block a conforming
5416        // decoder cannot hold.
5417        let per_channel = (frame_budget.saturating_sub(3) / self.channels.max(1))
5418            .saturating_sub(7)
5419            .min(MAX_CHANNEL_BITS);
5420        let prev = |ch: usize| -> std::borrow::Cow<'_, [f32; FRAME_LEN]> {
5421            if b == 0 {
5422                std::borrow::Cow::Owned([0f32; FRAME_LEN])
5423            } else {
5424                self.block_cow(ch, b - 1)
5425            }
5426        };
5427        // Arm A8. The shape of frame b-1 owns this frame's LEFT overlap half, so
5428        // both are needed; the decoder seeds prev = sine at stream start.
5429        let cur_kbd = shapes.get(b).copied().unwrap_or(false);
5430        let prev_kbd = if b == 0 {
5431            false
5432        } else {
5433            shapes.get(b - 1).copied().unwrap_or(false)
5434        };
5435        let short_win: &[f32] = if cur_kbd { kbd_s } else { sine_s };
5436        // The demand pre-pass's spectrum of channel `ch` (sine window, band
5437        // limited), when this frame codes it with exactly that window.
5438        let cached = |ch: usize, seq: WindowSequence| -> Option<Vec<f32>> {
5439            if seq == WindowSequence::OnlyLong && !prev_kbd && !cur_kbd {
5440                pre.and_then(|p| p.get(ch).cloned().flatten())
5441            } else {
5442                None
5443            }
5444        };
5445        SECTION_TRELLIS.with(|c| c.set(self.section_trellis));
5446        MASK_SMR.with(|c| c.set(smr_ratio(self.effective_smr_db())));
5447        SURPLUS.with(|c| c.set(self.surplus_on()));
5448        let bw_hz = self.bandwidth_hz();
5449        let cut_long = cutoff_line(bw_hz, self.sample_rate, swb, FRAME_LEN);
5450        let cut_short = cutoff_line(bw_hz, self.sample_rate, swb_s, SHORT_HALF);
5451        let psy = PsyCfg {
5452            short_block_psy: self.short_block_psy,
5453            window_grouping: self.window_grouping,
5454            tonality_smr: self.tonality_smr,
5455            tns: self.tns,
5456            pns: self.pns,
5457            intensity: self.intensity,
5458            stereo_bit_split: self.stereo_bit_split,
5459        };
5460
5461        // One pass over the ISO element sequence. `seqs` is indexed by ELEMENT,
5462        // not by channel: a CPE shares one window sequence across its pair, so
5463        // the two channels' transient flags were joined when the plan was built.
5464        // Encode one element into its own writer at `per_channel` bits per
5465        // channel. Elements are independent within a frame (the encoder keeps
5466        // no per-element state between them), so one can be re-encoded at a
5467        // different budget.
5468        let encode_elem = |ei: usize, elem: &Elem, per_channel: usize| -> BitWriter {
5469            let mut wr = BitWriter::new();
5470            let w = &mut wr;
5471            let seq = seqs[ei][b];
5472            let tag = ei as u32;
5473            match *elem {
5474                Elem::Cpe(l, r) => {
5475                    let (p0, c0, p1, c1) =
5476                        (prev(l), self.block_cow(l, b), prev(r), self.block_cow(r, b));
5477                    if seq == WindowSequence::EightShort {
5478                        let mut sl = analyze_short(&p0, &c0, short_win);
5479                        let mut sr_ = analyze_short(&p1, &c1, short_win);
5480                        band_limit(&mut sl, cut_short, SHORT_HALF);
5481                        band_limit(&mut sr_, cut_short, SHORT_HALF);
5482                        encode_cpe(
5483                            w,
5484                            tag,
5485                            &sl,
5486                            &sr_,
5487                            swb_s,
5488                            seq,
5489                            self.sample_rate,
5490                            per_channel,
5491                            cur_kbd,
5492                            psy,
5493                        );
5494                    } else {
5495                        let win = long_window(
5496                            seq,
5497                            prev_kbd,
5498                            cur_kbd,
5499                            &self.win,
5500                            &self.win_kbd,
5501                            sine_s,
5502                            kbd_s,
5503                        );
5504                        let fresh = |p: &[f32; FRAME_LEN], c: &[f32; FRAME_LEN]| {
5505                            let mut x = analyze_long(p, c, &win);
5506                            band_limit(&mut x, cut_long, FRAME_LEN);
5507                            x
5508                        };
5509                        let sl = cached(l, seq).unwrap_or_else(|| fresh(&p0, &c0));
5510                        let sr_ = cached(r, seq).unwrap_or_else(|| fresh(&p1, &c1));
5511                        encode_cpe(
5512                            w,
5513                            tag,
5514                            &sl,
5515                            &sr_,
5516                            swb,
5517                            seq,
5518                            self.sample_rate,
5519                            per_channel,
5520                            cur_kbd,
5521                            psy,
5522                        );
5523                    }
5524                }
5525                Elem::Sce(ch) | Elem::Lfe(ch) => {
5526                    let (p, c) = (prev(ch), self.block_cow(ch, b));
5527                    let id = elem.id();
5528                    if seq == WindowSequence::EightShort {
5529                        let mut spec = analyze_short(&p, &c, short_win);
5530                        band_limit(&mut spec, cut_short, SHORT_HALF);
5531                        encode_channel_element_short(
5532                            w,
5533                            tag,
5534                            &spec,
5535                            swb_s,
5536                            per_channel,
5537                            cur_kbd,
5538                            self.sample_rate,
5539                            psy,
5540                        );
5541                    } else {
5542                        let win = long_window(
5543                            seq,
5544                            prev_kbd,
5545                            cur_kbd,
5546                            &self.win,
5547                            &self.win_kbd,
5548                            sine_s,
5549                            kbd_s,
5550                        );
5551                        let mut spec = match (elem, cached(ch, seq)) {
5552                            (Elem::Sce(_), Some(x)) => x,
5553                            _ => analyze_long(&p, &c, &win),
5554                        };
5555                        if matches!(elem, Elem::Lfe(_)) {
5556                            lfe_band_limit(&mut spec);
5557                        } else {
5558                            band_limit(&mut spec, cut_long, FRAME_LEN);
5559                        }
5560                        encode_channel_element(
5561                            w,
5562                            tag,
5563                            &spec,
5564                            swb,
5565                            seq,
5566                            self.sample_rate,
5567                            per_channel,
5568                            cur_kbd,
5569                            psy,
5570                            id,
5571                        );
5572                    }
5573                }
5574            }
5575            wr
5576        };
5577        let nch = |e: &Elem| if matches!(e, Elem::Cpe(..)) { 2 } else { 1 };
5578        // The LFE first. Band-limited, it seldom needs its share, and what it
5579        // leaves is split among the other channels before they are coded;
5580        // left to the pooling below, it made every element of nearly every 5.1
5581        // frame encode twice.
5582        let mut lfe = None;
5583        let mut lfe_at = usize::MAX;
5584        let mut share = per_channel;
5585        if plan.len() > 1 {
5586            if let Some(li) = plan.iter().position(|e| matches!(e, Elem::Lfe(_))) {
5587                let w = encode_elem(li, &plan[li], per_channel);
5588                let spare = (per_channel + 7).saturating_sub(w.bit_len());
5589                share = (per_channel + spare / (self.channels - 1)).min(MAX_CHANNEL_BITS);
5590                lfe = Some((li, w));
5591                lfe_at = li;
5592            }
5593        }
5594        let budgets: Vec<usize> = plan
5595            .iter()
5596            .map(|e| {
5597                let pc = if matches!(e, Elem::Lfe(_)) {
5598                    per_channel
5599                } else {
5600                    share
5601                };
5602                pc * nch(e)
5603            })
5604            .collect();
5605        let mut writers: Vec<BitWriter> = plan
5606            .iter()
5607            .enumerate()
5608            .map(|(ei, e)| match lfe.take() {
5609                Some((li, w)) if li == ei => w,
5610                other => {
5611                    lfe = other;
5612                    encode_elem(ei, e, budgets[ei] / nch(e))
5613                }
5614            })
5615            .collect();
5616        // Multichannel: hand the bits that some elements leave unused (silence,
5617        // simple content) to the elements that used their whole share, and
5618        // re-encode those. The budget had been split evenly and never pooled,
5619        // so a 5.1 stream with only its centre active coded that centre at a
5620        // sixth of the bitrate (remade_ffmpeg_rs#129). One element (mono,
5621        // stereo) has nothing to pool, so its output is unchanged.
5622        if plan.len() > 1 {
5623            // An element that used half its budget or more was limited by it:
5624            // the rate loop's base steps are coarse at small budgets, so a
5625            // limited element can land well short of its target. Silence uses
5626            // a few dozen bits.
5627            // A pre-coded LFE has already handed on what it left.
5628            let binding = |ei: usize, used: usize| ei != lfe_at && 2 * used >= budgets[ei];
5629            let mut spare = 0usize;
5630            let mut binding_ch = 0usize;
5631            for (ei, (e, w)) in plan.iter().zip(&writers).enumerate() {
5632                if ei == lfe_at {
5633                    continue;
5634                }
5635                if binding(ei, w.bit_len()) {
5636                    binding_ch += nch(e);
5637                } else {
5638                    spare += budgets[ei] - w.bit_len();
5639                }
5640            }
5641            if binding_ch > 0 && spare >= 64 * binding_ch {
5642                let more = (share + spare / binding_ch).min(MAX_CHANNEL_BITS);
5643                if more > share {
5644                    for (ei, e) in plan.iter().enumerate() {
5645                        if binding(ei, writers[ei].bit_len()) {
5646                            writers[ei] = encode_elem(ei, e, more);
5647                        }
5648                    }
5649                }
5650            }
5651        }
5652        let mut rdb = BitWriter::new();
5653        for w in &writers {
5654            rdb.append(w);
5655        }
5656        rdb.write(ID_END, 3);
5657        (rdb.into_bytes(), (b * FRAME_LEN) as i64)
5658    }
5659
5660    /// The mask SMR this stream codes with: [`AacTuning::mask_smr_db`]
5661    /// for mono and stereo under [`MASK_SMR_MAX_BPS_PER_CHANNEL`]; the 2.1.2 18 dB from
5662    /// there up, and for 3 or more channels (no multichannel layout was
5663    /// measured).
5664    fn effective_smr_db(&self) -> f32 {
5665        let per_channel = self.bitrate / self.channels.max(1) as u32;
5666        if per_channel >= MASK_SMR_MAX_BPS_PER_CHANNEL || self.channels > 2 {
5667            18.0
5668        } else {
5669            self.mask_smr_db
5670        }
5671    }
5672
5673    /// Whether this stream runs [`AacTuning::surplus_shaping`].
5674    fn surplus_on(&self) -> bool {
5675        self.surplus_shaping
5676            && self.channels <= 2
5677            && self.bitrate / self.channels.max(1) as u32 >= SURPLUS_MIN_BPS_PER_CHANNEL
5678    }
5679
5680    /// The coding cutoff in Hz under the configured [`Bandwidth`] policy, or
5681    /// `None` for the whole spectrum.
5682    fn bandwidth_hz(&self) -> Option<u32> {
5683        match self.bandwidth {
5684            Bandwidth::Full => None,
5685            Bandwidth::Auto => {
5686                auto_bandwidth_hz(self.bitrate, self.channels as u16, self.sample_rate)
5687            }
5688            Bandwidth::Hz(hz) => Some(hz),
5689        }
5690        .filter(|&hz| hz < self.sample_rate / 2)
5691    }
5692
5693    /// Transient flags for one channel, under the configured detector (arm A9).
5694    fn transients(&self, chan: &[f32], nframes: usize) -> Vec<bool> {
5695        if self.relative_transients {
5696            detect_transients_relative(chan, nframes, self.transient_highpass)
5697        } else {
5698            detect_transients(chan, nframes)
5699        }
5700    }
5701
5702    /// **The Rung 0 gate.** Decide each frame's window shape.
5703    ///
5704    /// Computed as a whole-stream pre-pass, exactly like `detect_transients`, for
5705    /// two reasons: the decision is shared by both channels of a CPE (one common
5706    /// window), and frame b's window depends on frame b−1's shape — so deciding
5707    /// inside the frame-parallel worker would make the output depend on thread
5708    /// scheduling. Deciding up front keeps `encode_frame` independent and the
5709    /// encoder byte-deterministic (asserted by the lab's null arm).
5710    ///
5711    /// Threshold form: **per-clip percentile** of frame tonality (law 1), not an
5712    /// absolute. `Auto` is PROVISIONAL and off by default (law 7).
5713    fn decide_shapes(&self, nblocks: usize) -> Vec<bool> {
5714        match self.window_shape {
5715            WindowShape::Sine => vec![false; nblocks],
5716            WindowShape::Kbd => vec![true; nblocks],
5717            WindowShape::Auto => {
5718                // One reading per frame, from channel 0 (a CPE shares one window,
5719                // so the decision cannot be per-channel).
5720                let ton: Vec<f32> = (0..nblocks)
5721                    .map(|b| time_tonality(&self.block_cow(0, b)[..]))
5722                    .collect();
5723                let atk = frame_attack_ratios(&self.chans[0], nblocks);
5724
5725                let pct = |v: &[f32], q: f32| -> f32 {
5726                    let mut s = v.to_vec();
5727                    s.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
5728                    let i =
5729                        ((s.len().saturating_sub(1)) as f32 * q.clamp(0.0, 1.0)).round() as usize;
5730                    s.get(i).copied().unwrap_or(f32::INFINITY)
5731                };
5732                let ton_thresh = pct(&ton, self.shape_tonality_pct);
5733                let atk_thresh = pct(&atk, SHAPE_ATTACK_VETO_PCT);
5734
5735                // A depth-2 transcribed tree (great-gate law 3: shallow, in plain
5736                // code, one documented feature per node).
5737                //
5738                //   attack  — a frame with a strong onset takes SINE, whatever its
5739                //             tonality. KBD's wider main lobe smears transients in
5740                //             time; the force-on ladder measured +18.6% audible on
5741                //             the percussive class, the largest single effect in
5742                //             the whole Rung 0 harvest.
5743                //   tonality— among the remaining (stationary) frames, KBD's much
5744                //             deeper stopband is worth having.
5745                //
5746                // The veto is why this gate is not simply "tonality > t": ringing
5747                // percussion reads as HIGHLY tonal (a struck resonator is a decaying
5748                // sinusoid), so a tonality-only rule routes exactly the frames that
5749                // KBD hurts most. The first fit did precisely that.
5750                // The veto spans a ±1-frame NEIGHBOURHOOD, not just the frame
5751                // itself. Overlap-add means frame b's window shapes the overlap
5752                // with both b−1 and b+1, so an onset in either neighbour is
5753                // analyzed partly through this frame's window. Vetoing only the
5754                // onset frame left the ring-down frame on KBD and kept the whole
5755                // percussive regression (+10.0% audible, barely half of force-on's
5756                // +18.6%) — the measurement that forced this widening.
5757                let vetoed: Vec<bool> = (0..nblocks)
5758                    .map(|b| {
5759                        let lo = b.saturating_sub(1);
5760                        let hi = (b + 1).min(nblocks.saturating_sub(1));
5761                        (lo..=hi).any(|k| atk.get(k).copied().unwrap_or(1.0) > atk_thresh)
5762                    })
5763                    .collect();
5764
5765                (0..nblocks)
5766                    .map(|b| !vetoed[b] && ton[b] > ton_thresh)
5767                    .collect()
5768            }
5769        }
5770    }
5771
5772    /// Encode all buffered frames to raw access units. Frames are independent, so
5773    /// they fan out across worker threads (ffmpeg's AAC encoder is single-threaded).
5774    fn tables(&self) -> Tables {
5775        Tables {
5776            swb: swb_offsets(true, self.fs_index),
5777            swb_s: swb_offsets(false, self.fs_index),
5778            sine_s: crate::dsp::sine_window(SHORT_N),
5779            kbd_s: crate::dsp::kbd_window(SHORT_N, 6.0),
5780            plan: element_plan(self.channels).expect("channel count validated in init"),
5781        }
5782    }
5783
5784    /// Bits the target bitrate delivers for frame `b`, as whole bits whose
5785    /// running sum never drifts from `bitrate × time` (at 44.1 kHz a frame is
5786    /// not a whole number of bits). The target is the raw access unit, the
5787    /// payload an MP4 stores; an ADTS header (56 bits) comes on top, as with
5788    /// FFmpeg's encoder.
5789    fn frame_bits(&self, b: usize) -> usize {
5790        let per = u64::from(self.bitrate) * FRAME_LEN as u64;
5791        let sr = u64::from(self.sample_rate.max(1));
5792        let b = b as u64;
5793        ((b + 1) * per / sr - b * per / sr) as usize
5794    }
5795
5796    /// One reservoir segment's frame bit targets under
5797    /// [`AacTuning::frame_demand`] (indexed from `seg.start`), and each
5798    /// frame's per-channel sine-window long spectrum the demand was measured
5799    /// on, for `encode_frame` to reuse where it codes a frame with that very
5800    /// window. `None` (every frame its constant-rate share) when the knob is
5801    /// off.
5802    ///
5803    /// The targets sum to the segment's constant-rate bits, so a segment still
5804    /// encodes alone and the stream's rate is unchanged.
5805    #[allow(clippy::type_complexity)]
5806    fn segment_demand(
5807        &self,
5808        seg: std::ops::Range<usize>,
5809        swb: &[u16],
5810        plan: &[Elem],
5811    ) -> Option<(Vec<usize>, Vec<Vec<Option<Vec<f32>>>>)> {
5812        if self.frame_demand <= 0.0 {
5813            return None;
5814        }
5815        MASK_SMR.with(|c| c.set(smr_ratio(self.effective_smr_db())));
5816        let cut = cutoff_line(self.bandwidth_hz(), self.sample_rate, swb, FRAME_LEN);
5817        let cap = (MAX_CHANNEL_BITS + 7) * self.channels;
5818        let means: Vec<usize> = seg.clone().map(|b| self.frame_bits(b)).collect();
5819        let (pe, specs): (Vec<f64>, Vec<_>) = seg.map(|b| self.frame_pe(b, swb, plan, cut)).unzip();
5820        let w = frame_demand_weights(&pe, f64::from(self.frame_demand));
5821        let targets = means
5822            .iter()
5823            .zip(&w)
5824            .map(|(&m, &w)| ((m as f64 * w).round() as usize).min(cap))
5825            .collect();
5826        Some((targets, specs))
5827    }
5828
5829    /// Perceptual entropy of frame `b`, summed over every channel but the LFE:
5830    /// `sum_b n_b * 0.5 * log2(1 + E_b / thr_b)` on a sine-window long MDCT of
5831    /// the frame, against the long-block mask (flat SMR, threshold in quiet),
5832    /// within the coding bandwidth. A demand estimate only: it is computed
5833    /// the same way whatever window sequence the frame is coded with.
5834    /// Also returns each channel's spectrum (LFE: `None`).
5835    fn frame_pe(
5836        &self,
5837        b: usize,
5838        swb: &[u16],
5839        plan: &[Elem],
5840        cut: usize,
5841    ) -> (f64, Vec<Option<Vec<f32>>>) {
5842        let num_swb = swb.len() - 1;
5843        let mut specs = vec![None; self.channels];
5844        let chans = plan.iter().flat_map(|e| match *e {
5845            Elem::Cpe(l, r) => vec![l, r],
5846            Elem::Sce(c) => vec![c],
5847            Elem::Lfe(_) => vec![],
5848        });
5849        let mut pe = 0.0;
5850        for ch in chans {
5851            let prev = if b == 0 {
5852                std::borrow::Cow::Owned([0f32; FRAME_LEN])
5853            } else {
5854                self.block_cow(ch, b - 1)
5855            };
5856            let mut spec = analyze_long(&prev, &self.block_cow(ch, b), &self.win);
5857            band_limit(&mut spec, cut, FRAME_LEN);
5858            let energy: Vec<f64> = (0..num_swb)
5859                .map(|i| {
5860                    let (s, e) = (usize::from(swb[i]), usize::from(swb[i + 1]));
5861                    spec[s..e]
5862                        .iter()
5863                        .map(|&x| f64::from(x).powi(2))
5864                        .sum::<f64>()
5865                        + 1e-3
5866                })
5867                .collect();
5868            let thr = masking_from_energy(&energy, swb, self.sample_rate, FRAME_LEN, None);
5869            for i in 0..num_swb {
5870                let n = f64::from(swb[i + 1] - swb[i]);
5871                pe += n * 0.5 * (1.0 + energy[i] / thr[i].max(1e-30)).log2();
5872            }
5873            specs[ch] = Some(spec);
5874        }
5875        (pe, specs)
5876    }
5877
5878    /// Sub-block energies of frame `f` of channel `ch`, zero past the input.
5879    /// With `highpass`, of the high-passed signal (see [`sub_block_energy`]);
5880    /// its first two samples need the previous block, which is still held
5881    /// (or, at the stream's start, silence, as in the whole-clip detector).
5882    fn sub_energies(&self, ch: usize, f: usize, highpass: bool) -> [f64; 8] {
5883        let chan = &self.chans[ch];
5884        let at = (f - self.base_block) * FRAME_LEN;
5885        if highpass && self.base_block > 0 {
5886            // `chan[0]` is not the stream's first sample: give the filter the
5887            // two samples before `at` from the buffer (held back to block
5888            // `base_block`, so `at >= FRAME_LEN` whenever `f > base_block`).
5889            return std::array::from_fn(|sb| {
5890                let start = at + sb * SHORT_HALF;
5891                if start >= 2 {
5892                    // Past the buffered input (the flush frames) this is an
5893                    // empty slice, and the energy that of silence.
5894                    sub_block_energy(chan.get(start - 2..).unwrap_or(&[]), 2, true)
5895                } else {
5896                    sub_block_energy(chan, start, true)
5897                }
5898            });
5899        }
5900        std::array::from_fn(|sb| sub_block_energy(chan, at + sb * SHORT_HALF, highpass))
5901    }
5902
5903    /// Streaming: analyse the frames now complete, finalise the window
5904    /// sequences two frames behind them, encode those frames, and drop the
5905    /// samples no later frame needs. `last` (from `finish`) analyses and
5906    /// encodes everything, through the flush frame, as the whole-clip encode
5907    /// does.
5908    fn stream_advance(&mut self, last: bool) {
5909        if !self.initialized {
5910            return;
5911        }
5912        if self.stream.is_none() {
5913            self.stream = Some(Box::new(Streaming {
5914                tables: self.tables(),
5915                det: vec![Detector::default(); self.channels],
5916                flags: vec![Vec::new(); self.channels],
5917                seqs: Vec::new(),
5918                shapes: Vec::new(),
5919                analysed: 0,
5920                next: 0,
5921                reservoir: Reservoir::default(),
5922            }));
5923        }
5924        let mut st = self.stream.take().expect("just set");
5925        let mut reservoir = st.reservoir;
5926        if st.seqs.is_empty() {
5927            st.seqs = vec![Vec::new(); st.tables.plan.len()];
5928        }
5929        // Frames whose samples are all here (all of them, padded, at the end).
5930        let held = self.base_block + self.chans[0].len() / FRAME_LEN;
5931        let avail = if last {
5932            (self.total_in as usize).div_ceil(FRAME_LEN) + 1
5933        } else {
5934            held
5935        };
5936        while st.analysed < avail {
5937            let f = st.analysed;
5938            for ch in 0..self.channels {
5939                let sub =
5940                    self.sub_energies(ch, f, self.relative_transients && self.transient_highpass);
5941                let flag = st.det[ch].frame(&sub, f, self.relative_transients);
5942                st.flags[ch].push(flag);
5943            }
5944            st.shapes
5945                .push(matches!(self.window_shape, WindowShape::Kbd));
5946            st.analysed += 1;
5947        }
5948        // A frame's sequence depends on the transient flags up to two frames
5949        // after it (a run's LongStart, a one-frame gap merged into the run).
5950        let ready = if last {
5951            st.analysed
5952        } else {
5953            st.analysed.saturating_sub(2)
5954        };
5955        for (e, elem) in st.tables.plan.iter().enumerate() {
5956            let done = st.seqs[e].len();
5957            if done >= ready {
5958                continue;
5959            }
5960            // Four frames of left context make the window's start effects
5961            // irrelevant to the frames finalised from it.
5962            let w0 = done.saturating_sub(4);
5963            let joint: Vec<bool> = (w0..st.analysed)
5964                .map(|f| match *elem {
5965                    Elem::Cpe(l, r) => st.flags[l][f] || st.flags[r][f],
5966                    Elem::Sce(ch) => st.flags[ch][f],
5967                    Elem::Lfe(_) => false,
5968                })
5969                .collect();
5970            let seq = match *elem {
5971                Elem::Lfe(_) => vec![WindowSequence::OnlyLong; joint.len()],
5972                _ => assign_sequences(&joint),
5973            };
5974            st.seqs[e].extend_from_slice(&seq[done - w0..ready - w0]);
5975        }
5976        // Encode every frame whose sequence is final.
5977        let t = &st.tables;
5978        let out: Vec<(Vec<u8>, i64)> = (st.next..ready)
5979            .map(|b| {
5980                let mean = self.frame_bits(b);
5981                let budget = reservoir.budget(b, mean, self.channels);
5982                let au = self.encode_frame(
5983                    b, t.swb, t.swb_s, &t.sine_s, &t.kbd_s, &st.seqs, &st.shapes, budget, &t.plan,
5984                    None,
5985                );
5986                reservoir.spend(mean, au.0.len() * 8, self.channels);
5987                au
5988            })
5989            .collect();
5990        st.reservoir = reservoir;
5991        st.next = st.next.max(ready);
5992        self.queue.extend(out);
5993        // The next frame needs its previous block for the MDCT overlap.
5994        let keep_from = st.next.saturating_sub(1).max(self.base_block);
5995        let drop = keep_from - self.base_block;
5996        if drop > 0 {
5997            for chan in &mut self.chans {
5998                chan.drain(..(drop * FRAME_LEN).min(chan.len()));
5999            }
6000            self.base_block = keep_from;
6001        }
6002        self.stream = Some(st);
6003    }
6004
6005    fn encode_stream(&self) -> Vec<(Vec<u8>, i64)> {
6006        let swb = swb_offsets(true, self.fs_index);
6007        let swb_s = swb_offsets(false, self.fs_index);
6008        let sine_s = crate::dsp::sine_window(SHORT_N);
6009        // α = 6.0 for the short window, matching the decoder's `kbd_s`.
6010        let kbd_s = crate::dsp::kbd_window(SHORT_N, 6.0);
6011        let n = self.chans.first().map_or(0, std::vec::Vec::len);
6012        let nblocks = n.div_ceil(FRAME_LEN) + 1;
6013
6014        // The ISO element sequence for this channel count (validated at init, so
6015        // the unwrap cannot fire here).
6016        let plan = element_plan(self.channels).expect("channel count validated in init");
6017
6018        // Window sequences, **one per element**. A CPE shares a common window, so
6019        // its two channels' transient flags are joined; an LFE is long-only by
6020        // ISO rule, not by choice.
6021        let seqs: Vec<Vec<WindowSequence>> = plan
6022            .iter()
6023            .map(|e| match *e {
6024                Elem::Cpe(l, r) => {
6025                    let t0 = self.transients(&self.chans[l], nblocks);
6026                    let t1 = self.transients(&self.chans[r], nblocks);
6027                    let joint: Vec<bool> = (0..nblocks).map(|b| t0[b] || t1[b]).collect();
6028                    assign_sequences(&joint)
6029                }
6030                Elem::Sce(ch) => assign_sequences(&self.transients(&self.chans[ch], nblocks)),
6031                // lfe_channel_element carries no window-shape freedom.
6032                Elem::Lfe(_) => vec![WindowSequence::OnlyLong; nblocks],
6033            })
6034            .collect();
6035        // Arm A8: decide every frame's window shape up front, for the same reason
6036        // the sequences are decided up front — frame b's window depends on frame
6037        // b−1's shape, so this cannot live inside the parallel worker.
6038        let shapes = self.decide_shapes(nblocks);
6039
6040        // Slice views the worker threads share (all read-only).
6041        let (swb, swb_s, sine_s, kbd_s, seqs, shapes, plan) = (
6042            swb,
6043            swb_s,
6044            &sine_s[..],
6045            &kbd_s[..],
6046            &seqs[..],
6047            &shapes[..],
6048            &plan[..],
6049        );
6050        // Frames `range` in order, carrying the bit reservoir, which restarts at
6051        // every RESERVOIR_SEGMENT boundary (so any range of whole segments
6052        // encodes the same alone as in sequence).
6053        let frames = |range: std::ops::Range<usize>| {
6054            let mut reservoir = Reservoir::default();
6055            let mut out = Vec::with_capacity(range.len());
6056            let mut s = range.start;
6057            while s < range.end {
6058                let e = ((s / RESERVOIR_SEGMENT + 1) * RESERVOIR_SEGMENT).min(range.end);
6059                let seg = self.segment_demand(s..e, swb, plan);
6060                for b in s..e {
6061                    let (mean, pre) = match &seg {
6062                        Some((t, sp)) => (t[b - s], Some(&sp[b - s][..])),
6063                        None => (self.frame_bits(b), None),
6064                    };
6065                    let budget = reservoir.budget(b, mean, self.channels);
6066                    let au = self.encode_frame(
6067                        b, swb, swb_s, sine_s, kbd_s, seqs, shapes, budget, plan, pre,
6068                    );
6069                    reservoir.spend(mean, au.0.len() * 8, self.channels);
6070                    out.push(au);
6071                }
6072                s = e;
6073            }
6074            out
6075        };
6076
6077        let segments = nblocks.div_ceil(RESERVOIR_SEGMENT);
6078        let nthreads = std::thread::available_parallelism()
6079            .map_or(1, std::num::NonZero::get)
6080            .min(segments);
6081        if nthreads <= 1 || nblocks < 16 {
6082            return frames(0..nblocks); // serial for tiny inputs
6083        }
6084        // Fan out contiguous runs of whole segments; concatenating the parts
6085        // keeps them ordered.
6086        let chunk = segments.div_ceil(nthreads) * RESERVOIR_SEGMENT;
6087        let parts: Vec<Vec<(Vec<u8>, i64)>> = std::thread::scope(|s| {
6088            (0..nthreads)
6089                .map(|t| {
6090                    s.spawn(move || {
6091                        let start = (t * chunk).min(nblocks);
6092                        let end = ((t + 1) * chunk).min(nblocks);
6093                        frames(start..end)
6094                    })
6095                })
6096                .collect::<Vec<_>>()
6097                .into_iter()
6098                .map(|h| h.join().unwrap())
6099                .collect()
6100        });
6101        parts.into_iter().flatten().collect()
6102    }
6103
6104    /// Signal end-of-input: encode all buffered PCM (frame-parallel) so packets
6105    /// can be drained via [`next_packet`](AacEncoder::next_packet). Idempotent.
6106    pub fn finish(&mut self) {
6107        if self.flushed {
6108            return;
6109        }
6110        self.flushed = true;
6111        if self.initialized {
6112            if self.streaming {
6113                self.stream_advance(true);
6114            } else {
6115                self.queue = self.encode_stream().into();
6116            }
6117        }
6118    }
6119
6120    /// Retrieve the next encoded access unit. Returns [`Error::Again`] when
6121    /// none is ready (before [`finish`](AacEncoder::finish), unless
6122    /// streaming), and [`Error::Eof`] once fully drained.
6123    ///
6124    /// # Errors
6125    ///
6126    /// [`Error::Again`] until [`finish`](AacEncoder::finish) is called, then
6127    /// [`Error::Eof`] once every packet has been returned.
6128    pub fn next_packet(&mut self) -> Result<EncodedPacket> {
6129        if let Some((data, pts)) = self.queue.pop_front() {
6130            return Ok(EncodedPacket {
6131                data,
6132                pts,
6133                duration: FRAME_LEN as u32,
6134            });
6135        }
6136        if self.flushed {
6137            Err(Error::Eof)
6138        } else {
6139            Err(Error::Again)
6140        }
6141    }
6142}
6143
6144impl Default for AacEncoder {
6145    fn default() -> Self {
6146        Self::new(AacEncoderConfig::default())
6147    }
6148}
6149
6150#[cfg(test)]
6151mod tests {
6152    use super::*;
6153    use crate::bits::BitReader;
6154    use crate::codebook::decode_tuple;
6155
6156    /// Drain the encoder into a concatenated ADTS elementary stream — the container
6157    /// framing the encoder no longer emits itself — for decoder/ffmpeg validation.
6158    fn encode_to_adts(enc: &mut AacEncoder) -> Vec<u8> {
6159        enc.finish();
6160        let mut out = Vec::new();
6161        while let Ok(p) = enc.next_packet() {
6162            let hdr = AdtsHeader {
6163                object_type: 2,
6164                sample_rate: enc.sample_rate,
6165                channels: enc.channels as u16,
6166                frame_length: 7 + p.data.len(),
6167                header_len: 7,
6168            };
6169            out.extend_from_slice(&write_adts_header(&hdr));
6170            out.extend_from_slice(&p.data);
6171        }
6172        out
6173    }
6174
6175    /// Every `dim`-tuple drawn from `vals`.
6176    fn product(vals: &[i32], dim: usize) -> Vec<Vec<i32>> {
6177        let mut out = vec![vec![]];
6178        for _ in 0..dim {
6179            let mut next = Vec::new();
6180            for prefix in &out {
6181                for &v in vals {
6182                    let mut t = prefix.clone();
6183                    t.push(v);
6184                    next.push(t);
6185                }
6186            }
6187            out = next;
6188        }
6189        out
6190    }
6191
6192    /// Encode every representable tuple of every spectral codebook, then decode it
6193    /// back through the REAL decoder — must match exactly (codeword + sign + escape),
6194    /// and the written bit count must equal `spectral_bits`.
6195    #[test]
6196    #[cfg_attr(miri, ignore = "too slow to interpret: over 2 minutes under Miri")]
6197    fn spectral_encode_roundtrips_through_decoder() {
6198        for cb_num in 1..=11usize {
6199            let cb = &CODEBOOKS[cb_num];
6200            let dim = cb.dim as usize;
6201            let lav = i32::from(cb.lav);
6202
6203            // Signed books offset by lav; unsigned carry a sign, so cover ±lav.
6204            // Book 11 (escape) also probes magnitudes beyond lav, both signs.
6205            let vals: Vec<i32> = if cb.esc {
6206                let mut v: Vec<i32> = (-lav..=lav).collect();
6207                for &m in &[16, 17, 31, 32, 69, 100] {
6208                    v.push(m);
6209                    v.push(-m);
6210                }
6211                v
6212            } else {
6213                (-lav..=lav).collect()
6214            };
6215
6216            for tuple in product(&vals, dim) {
6217                if tuple_index(cb, &tuple).is_none() {
6218                    continue;
6219                }
6220                let mut w = BitWriter::new();
6221                spectral_emit(cb_num, &tuple, &mut w);
6222                assert_eq!(
6223                    w.bit_len(),
6224                    spectral_bits(cb_num, &tuple).unwrap(),
6225                    "cb {cb_num} tuple {tuple:?}: bit count mismatch"
6226                );
6227                let bytes = w.into_bytes();
6228                let mut r = BitReader::new(&bytes);
6229                let mut out = [0i32; 4];
6230                decode_tuple(cb, spectral_book(cb_num as u8), &mut r, &mut out).unwrap();
6231                assert_eq!(
6232                    &out[..dim],
6233                    &tuple[..dim],
6234                    "cb {cb_num} tuple {tuple:?}: round-trip"
6235                );
6236            }
6237        }
6238    }
6239
6240    /// Forward MDCT → decoder synthesis (imdct·window·overlap-add) reconstructs the
6241    /// signal (delayed one frame) — proves the window + overlap + 32768 scaling.
6242    #[test]
6243    #[cfg_attr(miri, ignore = "too slow to interpret: over 2 minutes under Miri")]
6244    fn long_filterbank_reconstructs_via_decoder_math() {
6245        let win = crate::dsp::sine_window(LONG_N);
6246        let nblocks = 6usize;
6247        let signal: Vec<f32> = (0..nblocks * FRAME_LEN)
6248            .map(|i| (0.3 * (i as f64 * 0.017).sin() + 0.2 * (i as f64 * 0.003).cos()) as f32)
6249            .collect();
6250
6251        let mut prev = [0f32; FRAME_LEN];
6252        let mut specs = Vec::new();
6253        for b in 0..nblocks {
6254            let mut cur = [0f32; FRAME_LEN];
6255            cur.copy_from_slice(&signal[b * FRAME_LEN..(b + 1) * FRAME_LEN]);
6256            specs.push(analyze_long(&prev, &cur, &win));
6257            prev = cur;
6258        }
6259
6260        let mut overlap = [0f32; FRAME_LEN];
6261        let mut out = Vec::new();
6262        for spec in &specs {
6263            let time = crate::dsp::imdct(spec);
6264            let frame: Vec<f32> = (0..LONG_N).map(|n| time[n] * win[n] / SPEC_SCALE).collect();
6265            let mut o = [0f32; FRAME_LEN];
6266            for n in 0..FRAME_LEN {
6267                o[n] = frame[n] + overlap[n];
6268                overlap[n] = frame[FRAME_LEN + n];
6269            }
6270            out.extend_from_slice(&o);
6271        }
6272
6273        // Output lags the input by one frame; the interior must reconstruct.
6274        for i in FRAME_LEN..(nblocks - 1) * FRAME_LEN {
6275            assert!(
6276                (out[i] - signal[i - FRAME_LEN]).abs() < 1e-3,
6277                "at {i}: {} vs {}",
6278                out[i],
6279                signal[i - FRAME_LEN]
6280            );
6281        }
6282    }
6283
6284    /// The block-switching sequence `OnlyLong` → `LongStart` → `EightShort` → `LongStop` →
6285    /// `OnlyLong` must reconstruct through the decoder's synthesis math (TDAC across
6286    /// the transition windows) — the decisive check that the short filterbank and
6287    /// transition windows are exact inverses.
6288    #[test]
6289    #[cfg_attr(miri, ignore = "too slow to interpret: over 2 minutes under Miri")]
6290    fn short_block_sequence_reconstructs_via_decoder_math() {
6291        use WindowSequence::*;
6292        let sine_l = crate::dsp::sine_window(LONG_N);
6293        let sine_s = crate::dsp::sine_window(SHORT_N);
6294        // Arm A8's shapes, unused by this test (it exercises the sine arm) but
6295        // required by the shape-aware signature.
6296        let kbd_l_t = crate::dsp::kbd_window(LONG_N, 4.0);
6297        let kbd_s_t = crate::dsp::kbd_window(SHORT_N, 6.0);
6298        let seqs = [
6299            OnlyLong, LongStart, EightShort, LongStop, OnlyLong, OnlyLong,
6300        ];
6301        let nblocks = seqs.len();
6302        let signal: Vec<f32> = (0..nblocks * FRAME_LEN)
6303            .map(|i| (0.3 * (i as f64 * 0.019).sin() + 0.25 * (i as f64 * 0.007).cos()) as f32)
6304            .collect();
6305
6306        // Forward: per-frame filterbank chosen by the window sequence.
6307        let mut prev = [0f32; FRAME_LEN];
6308        let mut specs = Vec::new();
6309        for (b, &seq) in seqs.iter().enumerate() {
6310            let mut cur = [0f32; FRAME_LEN];
6311            cur.copy_from_slice(&signal[b * FRAME_LEN..(b + 1) * FRAME_LEN]);
6312            let spec = if seq == EightShort {
6313                analyze_short(&prev, &cur, &sine_s)
6314            } else {
6315                analyze_long(
6316                    &prev,
6317                    &cur,
6318                    &long_window(seq, false, false, &sine_l, &kbd_l_t, &sine_s, &kbd_s_t),
6319                )
6320            };
6321            specs.push((seq, spec));
6322            prev = cur;
6323        }
6324
6325        // Synthesis: mirror the decoder (short_frame vs imdct·window) + overlap-add.
6326        let mut overlap = [0f32; FRAME_LEN];
6327        let mut out = Vec::new();
6328        for (seq, spec) in &specs {
6329            let frame: Vec<f32> = if *seq == EightShort {
6330                let mut f = vec![0f32; LONG_N];
6331                for w in 0..8 {
6332                    let time = crate::dsp::imdct(&spec[w * SHORT_HALF..(w + 1) * SHORT_HALF]);
6333                    let off = 448 + w * SHORT_HALF;
6334                    for n in 0..SHORT_N {
6335                        f[off + n] += time[n] * sine_s[n] / SPEC_SCALE;
6336                    }
6337                }
6338                f
6339            } else {
6340                let time = crate::dsp::imdct(spec);
6341                let win = long_window(*seq, false, false, &sine_l, &kbd_l_t, &sine_s, &kbd_s_t);
6342                (0..LONG_N).map(|n| time[n] * win[n] / SPEC_SCALE).collect()
6343            };
6344            let mut o = [0f32; FRAME_LEN];
6345            for n in 0..FRAME_LEN {
6346                o[n] = frame[n] + overlap[n];
6347                overlap[n] = frame[FRAME_LEN + n];
6348            }
6349            out.extend_from_slice(&o);
6350        }
6351
6352        // Interior (past the priming frame) must reconstruct across all transitions.
6353        for i in FRAME_LEN..(nblocks - 1) * FRAME_LEN {
6354            assert!(
6355                (out[i] - signal[i - FRAME_LEN]).abs() < 1e-3,
6356                "at {i}: {} vs {}",
6357                out[i],
6358                signal[i - FRAME_LEN]
6359            );
6360        }
6361    }
6362
6363    #[test]
6364    fn window_sequences_are_valid() {
6365        use WindowSequence::*;
6366        // Isolated transient → bracketed by LongStart / LongStop.
6367        assert_eq!(
6368            assign_sequences(&[false, false, false, true, false, false]),
6369            vec![OnlyLong, OnlyLong, LongStart, EightShort, LongStop, OnlyLong]
6370        );
6371        // Adjacent transients → one short run.
6372        assert_eq!(
6373            assign_sequences(&[false, false, true, true, false]),
6374            vec![OnlyLong, LongStart, EightShort, EightShort, LongStop]
6375        );
6376        // A single-frame gap is merged (can't be both a stop and a start).
6377        assert_eq!(
6378            assign_sequences(&[false, true, false, true, false]),
6379            vec![LongStart, EightShort, EightShort, EightShort, LongStop]
6380        );
6381    }
6382
6383    #[test]
6384    fn transient_is_detected() {
6385        let sr = 44100.0f64;
6386        let nframes = 5;
6387        let n = nframes * FRAME_LEN;
6388        let mut s = vec![0f32; n];
6389        for (i, x) in s.iter_mut().enumerate() {
6390            *x = (0.02 * (2.0 * std::f64::consts::PI * 400.0 * i as f64 / sr).sin()) as f32;
6391        }
6392        // A loud burst at the start of frame 2.
6393        for i in 0..600 {
6394            let env = (1.0 - i as f64 / 600.0).max(0.0);
6395            s[2 * FRAME_LEN + i] +=
6396                (0.8 * env * (2.0 * std::f64::consts::PI * 3000.0 * i as f64 / sr).sin()) as f32;
6397        }
6398        let flags = detect_transients(&s, nframes);
6399        assert!(flags[2], "the burst frame must be flagged");
6400        assert!(!flags[0] && !flags[4], "steady frames must not be flagged");
6401    }
6402
6403    /// End-to-end: a signal with a sharp attack must actually emit `EightShort`
6404    /// blocks and still decode cleanly through our decoder.
6405    #[test]
6406    #[cfg_attr(miri, ignore = "too slow to interpret: over 2 minutes under Miri")]
6407    fn transient_encodes_short_and_decodes() {
6408        let sr = 44100u32;
6409        let nframes = 5;
6410        let n = nframes * FRAME_LEN;
6411        let mut interleaved = Vec::new();
6412        for i in 0..n {
6413            let t = i as f64 / f64::from(sr);
6414            let mut v = 0.02 * (2.0 * std::f64::consts::PI * 400.0 * t).sin();
6415            if (2 * FRAME_LEN..2 * FRAME_LEN + 600).contains(&i) {
6416                let k = i - 2 * FRAME_LEN;
6417                let env = (1.0 - k as f64 / 600.0).max(0.0);
6418                v += 0.8
6419                    * env
6420                    * (2.0 * std::f64::consts::PI * 3000.0 * k as f64 / f64::from(sr)).sin();
6421            }
6422            interleaved.push(v as f32);
6423        }
6424
6425        let mut enc = AacEncoder::default();
6426        enc.push_pcm(&interleaved, 1, sr).unwrap();
6427        let adts = encode_to_adts(&mut enc);
6428
6429        // Parse each frame's first SCE window_sequence; EightShort (2) must appear.
6430        let mut saw_short = false;
6431        let mut pos = 0usize;
6432        let mut decoded = 0usize;
6433        let mut dec = crate::decode::Decoder::new(sr);
6434        while pos + 7 <= adts.len() {
6435            let hdr = crate::parse_adts(&adts[pos..]).unwrap();
6436            let au = &adts[pos + hdr.header_len..pos + hdr.frame_length];
6437            let mut r = crate::BitReader::new(au);
6438            assert_eq!(r.read_bits(3).unwrap(), ID_SCE); // mono SCE
6439            let _ = r.read_bits(4).unwrap(); // tag
6440            let _ = r.read_bits(8).unwrap(); // global_gain
6441            let _ = r.read_bit().unwrap(); // ics_reserved
6442            if r.read_bits(2).unwrap() == WindowSequence::EightShort.to_bits() {
6443                saw_short = true;
6444            }
6445            decoded += dec.decode(au, None).unwrap().frames();
6446            pos += hdr.frame_length;
6447        }
6448        assert!(saw_short, "a transient must produce EightShort blocks");
6449        assert!(decoded >= n, "decoded fewer samples than encoded");
6450    }
6451
6452    /// The `ms_mask_present` (2 bits) of the first frame's CPE — 0 = no M/S.
6453    fn first_cpe_ms_mask(adts: &[u8]) -> u32 {
6454        let hdr = crate::parse_adts(adts).unwrap();
6455        let au = &adts[hdr.header_len..hdr.frame_length];
6456        let mut r = crate::BitReader::new(au);
6457        assert_eq!(r.read_bits(3).unwrap(), ID_CPE);
6458        let _tag = r.read_bits(4).unwrap();
6459        assert_eq!(r.read_bit().unwrap(), 1); // common_window
6460        let _reserved = r.read_bit().unwrap();
6461        let ws = r.read_bits(2).unwrap();
6462        let _shape = r.read_bit().unwrap();
6463        if ws == WindowSequence::EightShort.to_bits() {
6464            let _ = r.read_bits(4).unwrap(); // max_sfb
6465            let _ = r.read_bits(7).unwrap(); // grouping
6466        } else {
6467            let _ = r.read_bits(6).unwrap(); // max_sfb
6468            let _ = r.read_bit().unwrap(); // predictor_data_present
6469        }
6470        r.read_bits(2).unwrap()
6471    }
6472
6473    /// Stereo with L = R (fully correlated) must pick M/S and reconstruct the two
6474    /// channels identically — the CPE + mid/side round-trip.
6475    #[test]
6476    #[cfg_attr(miri, ignore = "too slow to interpret: over 2 minutes under Miri")]
6477    fn stereo_ms_roundtrips_mono_content() {
6478        let sr = 44100u32;
6479        let n = 8192usize;
6480        let mut interleaved = Vec::new();
6481        for i in 0..n {
6482            let s = (0.4 * (2.0 * std::f64::consts::PI * 600.0 * i as f64 / f64::from(sr)).sin())
6483                as f32;
6484            interleaved.push(s); // L
6485            interleaved.push(s); // R == L
6486        }
6487        let mut enc = AacEncoder::default();
6488        enc.push_pcm(&interleaved, 2, sr).unwrap();
6489        let adts = encode_to_adts(&mut enc);
6490
6491        assert_ne!(
6492            first_cpe_ms_mask(&adts),
6493            0,
6494            "M/S should be chosen for L=R content"
6495        );
6496
6497        let mut dec = crate::decode::Decoder::new(sr);
6498        let (mut lsum, mut diff) = (0f64, 0f64);
6499        let mut pos = 0usize;
6500        while pos + 7 <= adts.len() {
6501            let hdr = crate::parse_adts(&adts[pos..]).unwrap();
6502            let au = &adts[pos + hdr.header_len..pos + hdr.frame_length];
6503            let a = dec.decode(au, None).unwrap();
6504            for k in 0..a.frames() {
6505                let l = a.samples[k * 2];
6506                let rr = a.samples[k * 2 + 1];
6507                lsum += f64::from(l).powi(2);
6508                diff += f64::from(l - rr).powi(2);
6509            }
6510            pos += hdr.frame_length;
6511        }
6512        assert!(lsum > 0.0, "decoded silence");
6513        // L and R reconstruct identically (mono content preserved through M/S).
6514        assert!(
6515            diff / (lsum + 1e-9) < 1e-3,
6516            "L/R diverged: {}",
6517            diff / (lsum + 1e-9)
6518        );
6519    }
6520
6521    /// The encoder→decoder round-trip is unity gain and length-preserving: decode
6522    /// the raw AUs directly (no container/engine) and check per-channel amplitude
6523    /// (≈0.283 RMS for a 0.4-amp sine) and frame count (~input + a little priming).
6524    #[test]
6525    #[cfg_attr(miri, ignore = "too slow to interpret: over 2 minutes under Miri")]
6526    fn stereo_direct_decode_amplitude() {
6527        let sr = 44100u32;
6528        let n = sr as usize; // 1 s
6529        let mut interleaved = Vec::new();
6530        for i in 0..n {
6531            let t = i as f64 / f64::from(sr);
6532            let l = (0.4 * (2.0 * std::f64::consts::PI * 440.0 * t).sin()) as f32;
6533            let r = (0.4 * (2.0 * std::f64::consts::PI * 660.0 * t).sin()) as f32;
6534            interleaved.push(l);
6535            interleaved.push(r);
6536        }
6537        let mut enc = AacEncoder::default();
6538        enc.push_pcm(&interleaved, 2, sr).unwrap();
6539        enc.finish();
6540        let mut dec = crate::decode::Decoder::new(sr);
6541        let (mut lsq, mut rsq, mut cnt) = (0.0f64, 0.0f64, 0usize);
6542        while let Ok(p) = enc.next_packet() {
6543            let a = dec.decode(&p.data, None).unwrap();
6544            for k in 0..a.frames() {
6545                let l = a.samples[k * 2];
6546                let r = a.samples[k * 2 + 1];
6547                lsq += f64::from(l).powi(2);
6548                rsq += f64::from(r).powi(2);
6549                cnt += 1;
6550            }
6551        }
6552        let (lrms, rrms) = ((lsq / cnt as f64).sqrt(), (rsq / cnt as f64).sqrt());
6553        eprintln!("input {n}/ch; decoded {cnt}/ch; Lrms={lrms:.3} Rrms={rrms:.3} (unity≈0.283)");
6554        // ~1 output frame per input frame (a couple of priming/flush frames extra).
6555        assert!(
6556            cnt >= n && cnt < n + 4 * FRAME_LEN,
6557            "frame count off: {cnt} vs {n}"
6558        );
6559        // Unity gain per channel (lossy tolerance), no doubling.
6560        assert!((0.24..0.32).contains(&lrms), "L amplitude off: {lrms:.3}");
6561        assert!((0.24..0.32).contains(&rrms), "R amplitude off: {rrms:.3}");
6562    }
6563
6564    /// Per-frame hot-path breakdown — which stage dominates encode time.
6565    #[test]
6566    #[ignore = "profiling; run with --ignored --nocapture"]
6567    fn profile_encode_hotpath() {
6568        use std::time::Instant;
6569        let sr = 44100u32;
6570        let fs = crate::sf_index_for_rate(sr).unwrap();
6571        let swb = swb_offsets(true, fs);
6572        let win = crate::dsp::sine_window(LONG_N);
6573        let mut cur = [0f32; FRAME_LEN];
6574        for (i, s) in cur.iter_mut().enumerate() {
6575            let t = i as f64 / f64::from(sr);
6576            *s = (0.3 * (2.0 * std::f64::consts::PI * 440.0 * t).sin()
6577                + 0.1 * (2.0 * std::f64::consts::PI * 3000.0 * t).sin()) as f32;
6578        }
6579        let prev = [0f32; FRAME_LEN];
6580        let iters = 500;
6581        let us = |d: std::time::Duration| d.as_secs_f64() * 1e6 / f64::from(iters);
6582
6583        let t = Instant::now();
6584        let mut spec = Vec::new();
6585        for _ in 0..iters {
6586            spec = analyze_long(&prev, &cur, &win);
6587        }
6588        let mdct = t.elapsed();
6589
6590        let t = Instant::now();
6591        for _ in 0..iters {
6592            let _ = perceptual_offsets(&spec, swb, sr, false, 3000);
6593        }
6594        let psy = t.elapsed();
6595        let offsets = perceptual_offsets(&spec, swb, sr, false, 3000);
6596
6597        let t = Instant::now();
6598        for _ in 0..iters {
6599            let _ = Xpow::new(&spec);
6600        }
6601        let xpow_t = t.elapsed();
6602        let xp = Xpow::new(&spec);
6603
6604        let t = Instant::now();
6605        for _ in 0..iters {
6606            let _ = rate_loop(&xp, swb, &offsets, 3000);
6607        }
6608        let rate = t.elapsed();
6609
6610        let sf = scalefactors(&offsets, 120);
6611        let t = Instant::now();
6612        for _ in 0..iters {
6613            let _ = code_frame(&xp, swb, &sf);
6614        }
6615        let cf = t.elapsed();
6616
6617        eprintln!("per-frame per-channel (avg over {iters}):");
6618        eprintln!("  analyze_long (MDCT): {:>8.1} us", us(mdct));
6619        eprintln!("  Xpow::new (once):    {:>8.1} us", us(xpow_t));
6620        eprintln!("  perceptual_offsets:  {:>8.1} us", us(psy));
6621        eprintln!("  rate_loop (~8x cf):  {:>8.1} us", us(rate));
6622        eprintln!("  one code_frame:      {:>8.1} us", us(cf));
6623        eprintln!(
6624            "  → MDCT is {:.0}% of (MDCT + rate_loop)",
6625            100.0 * mdct.as_secs_f64() / (mdct.as_secs_f64() + rate.as_secs_f64())
6626        );
6627    }
6628
6629    /// The AVX-512 quantize kernel narrows via `trunc(min(v+0.5, MAX+0.5))` instead of
6630    /// the AVX2/scalar `min(round(v), MAX)`. The intrinsics can't run on a non-AVX-512
6631    /// host, but the identity they rely on — for the quantizer's always-nonnegative
6632    /// input — is checkable in scalar, so the untested path's *math* is pinned here.
6633    /// A small deterministic generator for the codebook-cost oracle tests: bands
6634    /// whose peak lands in every book tier (0, 1, 2, 3-4, 5-7, 8-12, 13-15, the
6635    /// escape range up to `MAX_QUANT`), mixed with zeros, at every width the
6636    /// tables use plus odd and non-4-aligned ones.
6637    fn random_band(seed: &mut u64, width: usize) -> Vec<i32> {
6638        let mut next = || {
6639            *seed = seed
6640                .wrapping_mul(6_364_136_223_846_793_005)
6641                .wrapping_add(1_442_695_040_888_963_407);
6642            (*seed >> 33) as u32
6643        };
6644        let peak = [0u32, 1, 2, 4, 7, 12, 15, 16, 40, 300, MAX_QUANT as u32][next() as usize % 11];
6645        (0..width)
6646            .map(|_| {
6647                let r = next();
6648                if r % 3 == 0 || peak == 0 {
6649                    0
6650                } else {
6651                    let m = (r >> 2) % (peak + 1);
6652                    if r & 2 == 0 {
6653                        m as i32
6654                    } else {
6655                        -(m as i32)
6656                    }
6657                }
6658            })
6659            .collect()
6660    }
6661
6662    /// The walk-once codebook cost must pick the same book at the same bit count
6663    /// as the per-book search it replaced, for long bands and for short-window
6664    /// groups.
6665    #[test]
6666    fn codebook_cost_matches_per_book_search() {
6667        let mut seed = 0x5eed_u64;
6668        for width in [2usize, 4, 6, 8, 12, 16, 20, 28, 32, 48, 64, 96, 3] {
6669            for _ in 0..4000 {
6670                let band = random_band(&mut seed, width);
6671                assert_eq!(
6672                    best_codebook_for_band(&band, 0, width),
6673                    best_codebook_for_band_ref(&band, 0, width),
6674                    "width {width} band {band:?}"
6675                );
6676            }
6677        }
6678    }
6679
6680    /// The short-window search over a group of windows (each window's band at its
6681    /// own `SHORT_HALF` stride) against the per-book search it replaced.
6682    #[test]
6683    fn short_codebook_cost_matches_per_book_search() {
6684        let mut seed = 0x5407_u64;
6685        // Long-window and short-window band edges, plus a non-4-aligned and an
6686        // odd band, so the dim-4 and no-book cases are reached too.
6687        let swb: [u16; 10] = [0, 4, 8, 16, 28, 44, 60, 66, 69, 128];
6688        for _ in 0..3000 {
6689            let mut quant = vec![0i32; FRAME_LEN];
6690            for w in 0..8 {
6691                let band = random_band(&mut seed, SHORT_HALF);
6692                quant[w * SHORT_HALF..(w + 1) * SHORT_HALF].copy_from_slice(&band);
6693            }
6694            for sfb in 0..swb.len() - 1 {
6695                for (w0, nwin) in [(0, 8), (0, 1), (2, 3), (5, 3), (7, 1)] {
6696                    assert_eq!(
6697                        best_codebook_short(&quant, &swb, sfb, w0, nwin),
6698                        best_codebook_short_ref(&quant, &swb, sfb, w0, nwin),
6699                        "sfb {sfb} windows {w0}+{nwin}"
6700                    );
6701                }
6702            }
6703        }
6704    }
6705
6706    /// The frame-level quantizer (one dispatch, the band loop inside the AVX2
6707    /// function) equals the scalar per-band quantizer on every band, with
6708    /// scalefactors spanning and exceeding the clamped 0..=255 range.
6709    #[test]
6710    fn quantize_frame_matches_per_band_scalar() {
6711        let swb = swb_offsets(true, 4); // 44.1 kHz long bands
6712        let mut seed = 0x9e37_u64;
6713        let mut next = || {
6714            seed = seed
6715                .wrapping_mul(6_364_136_223_846_793_005)
6716                .wrapping_add(1_442_695_040_888_963_407);
6717            (seed >> 33) as u32
6718        };
6719        for _ in 0..50 {
6720            let spec: Vec<f32> = (0..FRAME_LEN)
6721                .map(|_| (next() as f32 / u32::MAX as f32 - 0.25) * 40_000.0)
6722                .collect();
6723            let xp = Xpow::new(&spec);
6724            let sf: Vec<i32> = (1..swb.len()).map(|_| next() as i32 % 300 - 20).collect();
6725            let mut got = vec![0i32; FRAME_LEN];
6726            quantize_frame(&xp, swb, &sf, &mut got);
6727            let mut want = vec![0i32; FRAME_LEN];
6728            for sfb in 0..swb.len() - 1 {
6729                let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
6730                let sc = scale_table()[sf[sfb].clamp(0, 255) as usize];
6731                quantize_band_scalar(&xp.pow[s..e], &xp.sign[s..e], sc, &mut want[s..e]);
6732            }
6733            assert_eq!(got, want);
6734        }
6735    }
6736
6737    /// The quantize twins must equal the scalar oracle exactly — including at the
6738    /// adversarial rounding points (the double just below each `k + 0.5`, where
6739    /// `v + 0.5` rounds UP in f64 and a naive `floor(v + 0.5)` overshoots), at the
6740    /// `MAX_QUANT` clamp, and with tails that are not a multiple of the lane width.
6741    #[cfg(all(feature = "simd", target_arch = "x86_64"))]
6742    #[test]
6743    fn quantize_simd_matches_scalar() {
6744        let below = |x: f64| f64::from_bits(x.to_bits() - 1);
6745        let mut vals = vec![
6746            0.0f64,
6747            0.25,
6748            0.5,
6749            below(0.5),
6750            1.5,
6751            below(1.5),
6752            2.5,
6753            below(2.5),
6754            1e-300,
6755            1.0 - NEAREST_BIAS,
6756            below(1.0 - NEAREST_BIAS),
6757            NEAREST_T1,
6758            below(NEAREST_T1),
6759        ];
6760        vals.extend([
6761            8190.5,
6762            below(8190.5),
6763            8191.0,
6764            8191.5,
6765            8192.0,
6766            1e9,
6767            4503599627370495.5,
6768        ]);
6769        let mut seed = 0x9e37_79b9u32;
6770        for _ in 0..4000 {
6771            seed = seed.wrapping_mul(1664525).wrapping_add(1013904223);
6772            let k = f64::from(seed >> 20);
6773            vals.push(match seed & 3 {
6774                0 => below(k + 0.5),
6775                1 => k + 0.5,
6776                2 => f64::from(seed) / 1000.0,
6777                _ => k * 1.000_000_1,
6778            });
6779        }
6780        for n in [1usize, 3, 4, 5, 7, 8, 9, 31, vals.len()] {
6781            let pow = &vals[..n];
6782            let sign: Vec<i32> = (0..n).map(|i| if i % 3 == 0 { -1 } else { 1 }).collect();
6783            let mut want = vec![0i32; n];
6784            quantize_band_scalar(pow, &sign, 1.0, &mut want);
6785            if has_avx2() {
6786                let mut got = vec![0i32; n];
6787                // SAFETY: AVX2 detected; all slices are `n` long.
6788                unsafe { quantize_band_avx2(pow, &sign, 1.0, &mut got) };
6789                for i in 0..n {
6790                    assert_eq!(
6791                        got[i],
6792                        want[i],
6793                        "avx2 v={:e} (bits {:x})",
6794                        pow[i],
6795                        pow[i].to_bits()
6796                    );
6797                }
6798            }
6799            #[cfg(feature = "simd-avx512")]
6800            if has_avx512() {
6801                let mut got = vec![0i32; n];
6802                // SAFETY: AVX-512F detected; all slices are `n` long.
6803                unsafe { quantize_band_avx512(pow, &sign, 1.0, &mut got) };
6804                for i in 0..n {
6805                    assert_eq!(got[i], want[i], "avx512 v={:e}", pow[i]);
6806                }
6807            }
6808        }
6809    }
6810
6811    /// `xpow_avx2` must handle a length that is not a multiple of its 4 lanes
6812    /// (its scalar tail once never advanced, an infinite loop masked only because
6813    /// every caller passes 1024 coefficients), and match the scalar formula.
6814    #[cfg(all(feature = "simd", target_arch = "x86_64"))]
6815    #[test]
6816    fn xpow_avx2_matches_scalar_with_tail() {
6817        if !has_avx2() {
6818            return;
6819        }
6820        for n in [0usize, 1, 3, 4, 5, 7, 129, 1023, 1024] {
6821            let spec: Vec<f32> = (0..n)
6822                .map(|i| ((i as f32 * 0.77).sin() * 3000.0) - 0.5)
6823                .collect();
6824            let (mut pow, mut sign) = (vec![0f64; n], vec![0i32; n]);
6825            // SAFETY: AVX2 detected above; the outputs are `n` long.
6826            unsafe { xpow_avx2(&spec, &mut pow, &mut sign) };
6827            for i in 0..n {
6828                let s = f64::from(spec[i].abs()).sqrt();
6829                assert_eq!(pow[i], s * s.sqrt(), "pow[{i}] n={n}");
6830                assert_eq!(
6831                    sign[i],
6832                    if spec[i] < 0.0 { -1 } else { 1 },
6833                    "sign[{i}] n={n}"
6834                );
6835            }
6836        }
6837    }
6838
6839    #[test]
6840    fn avx512_trunc_identity_matches_round_clamp() {
6841        for &v in &[
6842            0.0f64, 0.4, 0.5, 0.6, 1.4, 1.5, 2.5, 100.5, 8190.9, 8191.0, 8191.5, 1e6,
6843        ] {
6844            let round_clamp = (v.round() as i64).min(i64::from(MAX_QUANT));
6845            let trunc_trick = (v + 0.5).min(f64::from(MAX_QUANT) + 0.5) as i64; // `as` truncates
6846            assert_eq!(round_clamp, trunc_trick, "mismatch at v={v}");
6847        }
6848    }
6849
6850    #[test]
6851    fn bitwriter_msb_first() {
6852        let mut w = BitWriter::new();
6853        w.write(0b101, 3);
6854        w.write(0b1, 1);
6855        w.write(0b1111, 4);
6856        assert_eq!(w.bit_len(), 8);
6857        assert_eq!(w.into_bytes(), vec![0b1011_1111]);
6858    }
6859
6860    /// `emit_band` writes exactly the bits of `spectral_emit` tuple by tuple, for
6861    /// every book, with bands whose peak the book can hold (escapes up to
6862    /// `MAX_QUANT` for book 11), at a random starting bit alignment.
6863    #[test]
6864    fn emit_band_matches_spectral_emit() {
6865        let mut seed = 0xe417_u64;
6866        for cb in 1..=11u8 {
6867            let meta = &CODEBOOKS[cb as usize];
6868            let lav = if meta.esc {
6869                MAX_QUANT as u32
6870            } else {
6871                u32::from(meta.lav)
6872            };
6873            let mut done = 0;
6874            while done < 2000 {
6875                let band = random_band(&mut seed, 32);
6876                if band.iter().any(|q| q.unsigned_abs() > lav) {
6877                    continue;
6878                }
6879                done += 1;
6880                let lead = (seed >> 40) as u32 % 32;
6881                let (mut a, mut b) = (BitWriter::new(), BitWriter::new());
6882                a.write(0x5a5a_5a5a, lead);
6883                b.write(0x5a5a_5a5a, lead);
6884                emit_band(&mut a, cb, &band);
6885                for t in band.chunks_exact(meta.dim as usize) {
6886                    spectral_emit(cb as usize, t, &mut b);
6887                }
6888                assert_eq!(a.bit_len(), b.bit_len(), "cb {cb} band {band:?}");
6889                assert_eq!(a.into_bytes(), b.into_bytes(), "cb {cb} band {band:?}");
6890            }
6891        }
6892    }
6893
6894    /// The word-buffered writer against a one-bool-per-bit reference: random
6895    /// widths 0..=32 (with junk above the width), interleaved appends of writers
6896    /// at every alignment, `bit_len` after every step, and the padded bytes.
6897    #[test]
6898    fn bitwriter_matches_bit_vector() {
6899        fn pack(bits: &[bool]) -> Vec<u8> {
6900            bits.chunks(8)
6901                .map(|c| {
6902                    c.iter()
6903                        .enumerate()
6904                        .fold(0u8, |b, (i, &x)| b | (u8::from(x) << (7 - i)))
6905                })
6906                .collect()
6907        }
6908        let mut seed = 0xb17_u64;
6909        let mut next = || {
6910            seed = seed
6911                .wrapping_mul(6_364_136_223_846_793_005)
6912                .wrapping_add(1_442_695_040_888_963_407);
6913            (seed >> 32) as u32
6914        };
6915        for _ in 0..300 {
6916            let (mut w, mut bits) = (BitWriter::new(), Vec::new());
6917            for _ in 0..(next() % 200) {
6918                if next() % 8 == 0 {
6919                    let (mut o, mut obits) = (BitWriter::new(), Vec::new());
6920                    for _ in 0..(next() % 20) {
6921                        let (v, n) = (next(), next() % 33);
6922                        o.write(v, n);
6923                        obits.extend((0..n).rev().map(|i| (v >> i) & 1 == 1));
6924                    }
6925                    w.append(&o);
6926                    bits.extend(obits);
6927                } else {
6928                    let (v, n) = (next(), next() % 33);
6929                    w.write(v, n);
6930                    bits.extend((0..n).rev().map(|i| (v >> i) & 1 == 1));
6931                }
6932                assert_eq!(w.bit_len(), bits.len());
6933            }
6934            assert_eq!(w.into_bytes(), pack(&bits));
6935        }
6936    }
6937
6938    #[test]
6939    fn audio_specific_config_roundtrips() {
6940        for &(sr, ch) in &[(44100u32, 2u16), (48000, 1), (96000, 2), (8000, 1)] {
6941            let cfg = AudioSpecificConfig {
6942                object_type: 2,
6943                sample_rate: sr,
6944                channels: ch,
6945            };
6946            let bytes = write_audio_specific_config(&cfg);
6947            assert_eq!(crate::parse_audio_specific_config(&bytes).unwrap(), cfg);
6948        }
6949    }
6950
6951    #[test]
6952    fn adts_header_roundtrips() {
6953        let hdr = AdtsHeader {
6954            object_type: 2,
6955            sample_rate: 44100,
6956            channels: 2,
6957            frame_length: 512,
6958            header_len: 7,
6959        };
6960        let bytes = write_adts_header(&hdr);
6961        assert_eq!(bytes.len(), 7);
6962        assert!(crate::is_adts(&bytes));
6963        assert_eq!(crate::parse_adts(&bytes).unwrap(), hdr);
6964    }
6965
6966    #[test]
6967    fn ics_info_long_reencodes_bit_exact() {
6968        // The decoder's own long-block test vector.
6969        let orig = [0x0C, 0x40];
6970        let info = crate::ics::parse_ics_info(&mut BitReader::new(&orig), 4).unwrap();
6971        let mut w = BitWriter::new();
6972        encode_ics_info(&mut w, &info);
6973        assert_eq!(w.into_bytes(), orig);
6974    }
6975
6976    #[test]
6977    fn ics_info_short_grouping_roundtrips() {
6978        use crate::ics::{parse_ics_info, IcsInfo, WindowSequence};
6979        let info = IcsInfo {
6980            window_sequence: WindowSequence::EightShort,
6981            window_shape_kbd: false,
6982            max_sfb: 8,
6983            num_windows: 8,
6984            num_window_groups: 2,
6985            window_group_length: vec![3, 5],
6986            num_swb: 0, // encode ignores; the parser re-derives
6987        };
6988        let mut w = BitWriter::new();
6989        encode_ics_info(&mut w, &info);
6990        let parsed = parse_ics_info(&mut BitReader::new(&w.into_bytes()), 4).unwrap();
6991        assert_eq!(parsed.window_sequence, WindowSequence::EightShort);
6992        assert_eq!(parsed.max_sfb, 8);
6993        assert_eq!(parsed.window_group_length, vec![3, 5]);
6994    }
6995
6996    fn rms(sig: &[f32]) -> f64 {
6997        (sig.iter().map(|&s| f64::from(s).powi(2)).sum::<f64>() / sig.len().max(1) as f64).sqrt()
6998    }
6999
7000    /// Magnitude of the `freq`-Hz component (Goertzel-style) — a recognizability probe.
7001    fn tone_energy(sig: &[f32], freq: f64, sr: f64) -> f64 {
7002        let (mut re, mut im) = (0.0f64, 0.0f64);
7003        for (i, &s) in sig.iter().enumerate() {
7004            let ph = 2.0 * std::f64::consts::PI * freq * i as f64 / sr;
7005            re += f64::from(s) * ph.cos();
7006            im += f64::from(s) * ph.sin();
7007        }
7008        (re * re + im * im).sqrt() / sig.len() as f64
7009    }
7010
7011    /// The whole-pipeline gate: encode a 440 Hz tone, decode through the real
7012    /// decoder, and confirm a recognizable 440 Hz tone with preserved energy.
7013    #[test]
7014    #[cfg_attr(miri, ignore = "too slow to interpret: over 2 minutes under Miri")]
7015    fn encodes_and_decodes_recognizable_tone() {
7016        let sr = 44100u32;
7017        let n = 44100usize; // 1 s
7018        let mut samples = Vec::with_capacity(n);
7019        for i in 0..n {
7020            let s = ((i as f64 * 2.0 * std::f64::consts::PI * 440.0 / f64::from(sr)).sin() * 0.5)
7021                as f32;
7022            samples.push(s);
7023        }
7024
7025        let mut enc = AacEncoder::default();
7026        enc.push_pcm(&samples, 1, sr).unwrap();
7027        let adts = encode_to_adts(&mut enc);
7028        assert!(crate::is_adts(&adts), "encoder output is not ADTS");
7029
7030        let mut dec = crate::decode::Decoder::new(sr);
7031        let mut decoded = Vec::new();
7032        let mut pos = 0usize;
7033        while pos + 7 <= adts.len() {
7034            let hdr = crate::parse_adts(&adts[pos..]).unwrap();
7035            let au = &adts[pos + hdr.header_len..pos + hdr.frame_length];
7036            decoded.extend_from_slice(&dec.decode(au, None).unwrap().samples);
7037            pos += hdr.frame_length;
7038        }
7039        assert!(
7040            decoded.len() > n / 2,
7041            "too little decoded audio: {}",
7042            decoded.len()
7043        );
7044
7045        let (ri, ro) = (rms(&samples), rms(&decoded));
7046        assert!(
7047            ro > 0.4 * ri && ro < 2.5 * ri,
7048            "energy off: in {ri:.4} out {ro:.4}"
7049        );
7050        let e440 = tone_energy(&decoded, 440.0, f64::from(sr));
7051        let e1234 = tone_energy(&decoded, 1234.0, f64::from(sr));
7052        assert!(
7053            e440 > 5.0 * e1234,
7054            "not a clean 440 Hz tone: e440 {e440:.5} e1234 {e1234:.5}"
7055        );
7056    }
7057
7058    /// The rate loop must keep a dense signal within (roughly) the target bitrate
7059    /// and still produce decodable audio.
7060    #[test]
7061    #[cfg_attr(miri, ignore = "too slow to interpret: over 2 minutes under Miri")]
7062    fn rate_loop_respects_bitrate() {
7063        let sr = 44100u32;
7064        let secs = 2usize;
7065        let n = sr as usize * secs;
7066        let mut interleaved = Vec::new();
7067        let mut st = 0x0000_2468u32;
7068        for i in 0..n {
7069            let t = i as f64 / f64::from(sr);
7070            let mut s = 0.0;
7071            for h in 1..=8 {
7072                s += (2.0 * std::f64::consts::PI * 300.0 * f64::from(h) * t).sin() / f64::from(h);
7073            }
7074            st ^= st << 13;
7075            st ^= st >> 17;
7076            st ^= st << 5;
7077            let noise = (f64::from(st >> 24) - 128.0) / 128.0 * 0.1;
7078            let v = ((s * 0.2 + noise) * 0.7).clamp(-1.0, 1.0) as f32;
7079            interleaved.push(v);
7080        }
7081
7082        for &kbps in &[64_000u32, 128_000] {
7083            let mut enc = AacEncoder::new(AacEncoderConfig {
7084                bitrate_bps: kbps,
7085                ..Default::default()
7086            });
7087            enc.push_pcm(&interleaved, 1, sr).unwrap();
7088            let adts = encode_to_adts(&mut enc);
7089
7090            let measured = adts.len() as f64 * 8.0 / secs as f64;
7091            assert!(
7092                measured <= f64::from(kbps) * 1.35,
7093                "bitrate {kbps}: measured {measured:.0} b/s exceeds budget"
7094            );
7095
7096            let mut dec = crate::decode::Decoder::new(sr);
7097            let mut pos = 0usize;
7098            let mut got = false;
7099            while pos + 7 <= adts.len() {
7100                let hdr = crate::parse_adts(&adts[pos..]).unwrap();
7101                let au = &adts[pos + hdr.header_len..pos + hdr.frame_length];
7102                got |= !dec.decode(au, None).unwrap().samples.is_empty();
7103                pos += hdr.frame_length;
7104            }
7105            assert!(got, "bitrate {kbps}: no decodable audio");
7106            eprintln!(
7107                "target {kbps} b/s → measured {measured:.0} b/s ({} bytes)",
7108                adts.len()
7109            );
7110        }
7111    }
7112
7113    /// The psychoacoustic model must shape quantization noise toward the masking
7114    /// threshold: at a fixed budget it must not worsen the worst band and must cut
7115    /// the total audible (above-mask) noise vs flat scalefactors.
7116    #[test]
7117    fn psy_model_shapes_noise_below_flat() {
7118        let sr = 44100u32;
7119        let fs = crate::sf_index_for_rate(sr).unwrap();
7120        let swb = swb_offsets(true, fs);
7121        let win = crate::dsp::sine_window(LONG_N);
7122        // A few strong tones with spectral gaps → masking creates real headroom in
7123        // some bands and sensitivity in others.
7124        let mut cur = [0f32; FRAME_LEN];
7125        for (i, s) in cur.iter_mut().enumerate() {
7126            let t = i as f64 / f64::from(sr);
7127            let v = 0.5 * (2.0 * std::f64::consts::PI * 500.0 * t).sin()
7128                + 0.25 * (2.0 * std::f64::consts::PI * 1500.0 * t).sin()
7129                + 0.15 * (2.0 * std::f64::consts::PI * 4000.0 * t).sin();
7130            *s = v as f32;
7131        }
7132        let spec = analyze_long(&[0f32; FRAME_LEN], &cur, &win);
7133        let target = 2500usize; // ~128 kbps — enough that allocation choices matter
7134
7135        // Worst-case NMR (perceptual quality is set by the loudest audible artifact)
7136        // and mean NMR in dB, over the energy-bearing bands.
7137        let xp = Xpow::new(&spec);
7138        let metric = |offsets: &Offsets| -> (f64, f64) {
7139            let base = rate_loop(&xp, swb, offsets, target);
7140            let sf = scalefactors(offsets, base);
7141            let thr = masking_thresholds(&spec, swb, sr);
7142            let (mut max_nmr, mut sum_db, mut n) = (0f64, 0f64, 0usize);
7143            for sfb in 0..swb.len() - 1 {
7144                let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
7145                let en: f64 = spec[s..e].iter().map(|&x| f64::from(x).powi(2)).sum();
7146                if en < 1e6 {
7147                    continue; // near-silent band → quantizes to ZERO, no artifact
7148                }
7149                let mut noise = 0f64;
7150                for &x in &spec[s..e] {
7151                    let q = quantize(x, sf[sfb]);
7152                    let rec = f64::from(q.signum())
7153                        * f64::from(q.unsigned_abs()).powf(4.0 / 3.0)
7154                        * 2f64.powf(0.25 * f64::from(sf[sfb] - 100));
7155                    noise += (f64::from(x) - rec).powi(2);
7156                }
7157                let nmr = (noise / thr[sfb]).max(1e-30);
7158                max_nmr = max_nmr.max(nmr);
7159                sum_db += 10.0 * nmr.log10();
7160                n += 1;
7161            }
7162            (max_nmr, sum_db / n.max(1) as f64)
7163        };
7164
7165        let flat = metric(&Offsets::flat(vec![0i32; swb.len() - 1]));
7166        let psy = metric(&perceptual_offsets(&spec, swb, sr, false, 3000));
7167        eprintln!(
7168            "flat: max_nmr={:.2} mean={:.1}dB | psy: max_nmr={:.2} mean={:.1}dB",
7169            flat.0, flat.1, psy.0, psy.1
7170        );
7171        // The psy model equalizes NMR → the worst audible band is quieter than flat.
7172        assert!(
7173            psy.0 < flat.0,
7174            "psy must reduce the worst-band NMR ({:.2} vs {:.2})",
7175            psy.0,
7176            flat.0
7177        );
7178    }
7179
7180    /// Emit our `.aac` (ADTS) so an external reference decoder (ffmpeg) can confirm
7181    /// the stream is spec-valid, not just self-decodable.
7182    #[test]
7183    #[ignore = "writes an .aac for external ffmpeg validation; run explicitly"]
7184    fn emit_aac_for_external_check() {
7185        let sr = 44100u32;
7186        let n = 44100usize;
7187        let mut interleaved = Vec::new();
7188        for i in 0..n {
7189            let s = ((i as f64 * 2.0 * std::f64::consts::PI * 440.0 / f64::from(sr)).sin() * 0.5)
7190                as f32;
7191            interleaved.push(s);
7192        }
7193        let mut enc = AacEncoder::default();
7194        enc.push_pcm(&interleaved, 1, sr).unwrap();
7195        let adts = encode_to_adts(&mut enc);
7196        let dir = std::env::temp_dir();
7197        std::fs::write(dir.join("rff_aac_tone.aac"), &adts).unwrap();
7198        eprintln!(
7199            "wrote {}/rff_aac_tone.aac ({} bytes)",
7200            dir.display(),
7201            adts.len()
7202        );
7203    }
7204
7205    /// Emit a `.aac` with periodic sharp attacks (drum-like) so ffmpeg can confirm
7206    /// the block-switched (short + transition) stream is spec-valid.
7207    #[test]
7208    #[ignore = "writes an .aac for external ffmpeg validation; run explicitly"]
7209    fn emit_transient_aac_for_external_check() {
7210        let sr = 44100u32;
7211        let n = 44100usize;
7212        let mut interleaved = Vec::new();
7213        for i in 0..n {
7214            let t = i as f64 / f64::from(sr);
7215            let mut v = 0.05 * (2.0 * std::f64::consts::PI * 220.0 * t).sin();
7216            // A sharp click every ~0.25 s.
7217            let k = i % 11025;
7218            if k < 700 {
7219                let env = (1.0 - k as f64 / 700.0).max(0.0);
7220                v += 0.8
7221                    * env
7222                    * (2.0 * std::f64::consts::PI * 3500.0 * k as f64 / f64::from(sr)).sin();
7223            }
7224            interleaved.push(v as f32);
7225        }
7226        let mut enc = AacEncoder::default();
7227        enc.push_pcm(&interleaved, 1, sr).unwrap();
7228        let adts = encode_to_adts(&mut enc);
7229        let dir = std::env::temp_dir();
7230        std::fs::write(dir.join("rff_aac_transient.aac"), &adts).unwrap();
7231        eprintln!(
7232            "wrote {}/rff_aac_transient.aac ({} bytes)",
7233            dir.display(),
7234            adts.len()
7235        );
7236    }
7237
7238    /// Emit a stereo `.aac` (shared bass + divergent highs → mixed per-SFB M/S) so
7239    /// ffmpeg can confirm the CPE stream is spec-valid.
7240    #[test]
7241    #[ignore = "writes an .aac for external ffmpeg validation; run explicitly"]
7242    fn emit_stereo_aac_for_external_check() {
7243        let sr = 44100u32;
7244        let n = 44100usize;
7245        let mut interleaved = Vec::new();
7246        for i in 0..n {
7247            let t = i as f64 / f64::from(sr);
7248            let bass = 0.4 * (2.0 * std::f64::consts::PI * 300.0 * t).sin(); // shared → M/S
7249            let l = bass + 0.2 * (2.0 * std::f64::consts::PI * 1200.0 * t).sin();
7250            let r = bass + 0.2 * (2.0 * std::f64::consts::PI * 1900.0 * t).sin();
7251            interleaved.push(l as f32);
7252            interleaved.push(r as f32);
7253        }
7254        let mut enc = AacEncoder::default();
7255        enc.push_pcm(&interleaved, 2, sr).unwrap();
7256        let adts = encode_to_adts(&mut enc);
7257        let dir = std::env::temp_dir();
7258        std::fs::write(dir.join("rff_aac_stereo.aac"), &adts).unwrap();
7259        eprintln!(
7260            "wrote {}/rff_aac_stereo.aac ({} bytes)",
7261            dir.display(),
7262            adts.len()
7263        );
7264    }
7265}
7266
7267// ---------------------------------------------------------------------------
7268// Rung 0 (arm A8) — window-shape gate tests.
7269//
7270// The rung's contract, in the order great-gate §4 requires it:
7271//   1. the neutral end is BYTE-IDENTICAL (proven against an oracle, not argued),
7272//   2. the routed arm is TDAC-correct (a window mismatch is not a quality
7273//      regression, it is broken audio),
7274//   3. the dispatch decodes on the hardest case — alternating shapes.
7275// ---------------------------------------------------------------------------
7276#[cfg(test)]
7277mod rung0 {
7278    use super::*;
7279
7280    /// The sine-only `long_window` exactly as it stood before arm A8, kept as the
7281    /// oracle for the neutral end.
7282    fn long_window_pre_a8(seq: WindowSequence, sine_l: &[f32], sine_s: &[f32]) -> Vec<f32> {
7283        let mut w = vec![0f32; LONG_N];
7284        if seq == WindowSequence::LongStop {
7285            w[448..448 + SHORT_HALF].copy_from_slice(&sine_s[..SHORT_HALF]);
7286            for s in w.iter_mut().take(FRAME_LEN).skip(576) {
7287                *s = 1.0;
7288            }
7289        } else {
7290            w[..FRAME_LEN].copy_from_slice(&sine_l[..FRAME_LEN]);
7291        }
7292        if seq == WindowSequence::LongStart {
7293            for s in w.iter_mut().take(FRAME_LEN + 448).skip(FRAME_LEN) {
7294                *s = 1.0;
7295            }
7296            w[FRAME_LEN + 448..FRAME_LEN + 448 + SHORT_HALF].copy_from_slice(&sine_s[SHORT_HALF..]);
7297        } else {
7298            w[FRAME_LEN..].copy_from_slice(&sine_l[FRAME_LEN..]);
7299        }
7300        w
7301    }
7302
7303    /// **Law 7 — the neutral end is byte-identical.** With both shape flags false
7304    /// the new shape-aware window must equal the pre-A8 sine-only one, exactly,
7305    /// for every sequence. Every other A8 change is a pass-through of
7306    /// `cur_kbd = false` into a bit that was already 0.
7307    #[test]
7308    fn shape_sine_is_byte_identical() {
7309        let sine_l = crate::dsp::sine_window(LONG_N);
7310        let sine_s = crate::dsp::sine_window(SHORT_N);
7311        let kbd_l = crate::dsp::kbd_window(LONG_N, 4.0);
7312        let kbd_s = crate::dsp::kbd_window(SHORT_N, 6.0);
7313        for seq in [
7314            WindowSequence::OnlyLong,
7315            WindowSequence::LongStart,
7316            WindowSequence::LongStop,
7317        ] {
7318            let new = long_window(seq, false, false, &sine_l, &kbd_l, &sine_s, &kbd_s);
7319            let old = long_window_pre_a8(seq, &sine_l, &sine_s);
7320            assert_eq!(new, old, "{seq:?}: neutral end must be byte-identical");
7321        }
7322    }
7323
7324    /// The whole encoded stream is byte-identical under the default config and an
7325    /// explicit `Sine` — i.e. the default really is the neutral arm.
7326    #[test]
7327    #[cfg_attr(miri, ignore = "too slow to interpret: over 2 minutes under Miri")]
7328    fn default_config_is_the_sine_arm() {
7329        let pcm: Vec<f32> = (0..8 * FRAME_LEN)
7330            .map(|i| {
7331                let t = i as f32 / 44100.0;
7332                0.4 * (2.0 * std::f32::consts::PI * 700.0 * t).sin()
7333            })
7334            .collect();
7335        let enc = |cfg: AacEncoderConfig| {
7336            let mut e = AacEncoder::new(cfg);
7337            e.push_pcm(&pcm, 1, 44100).unwrap();
7338            e.finish();
7339            let mut out = Vec::new();
7340            while let Ok(p) = e.next_packet() {
7341                out.extend_from_slice(&p.data);
7342            }
7343            out
7344        };
7345        let a = enc(AacEncoderConfig::default());
7346        let b = enc(AacEncoderConfig {
7347            window_shape: WindowShape::Sine,
7348            ..Default::default()
7349        });
7350        assert_eq!(a, b, "default must be the Sine arm");
7351    }
7352
7353    /// Windows must satisfy the **Princen-Bradley condition** on every overlap:
7354    /// `w_prev[N+n]^2 + w_cur[n]^2 == 1`. This is what makes overlap-add exact. It
7355    /// must hold for every ordered pair of shapes, which is exactly why the left
7356    /// half follows the previous frame and the right half the current one.
7357    #[test]
7358    fn tdac_holds_across_every_shape_transition() {
7359        let sine_l = crate::dsp::sine_window(LONG_N);
7360        let sine_s = crate::dsp::sine_window(SHORT_N);
7361        let kbd_l = crate::dsp::kbd_window(LONG_N, 4.0);
7362        let kbd_s = crate::dsp::kbd_window(SHORT_N, 6.0);
7363
7364        for (a, b) in [(false, false), (false, true), (true, false), (true, true)] {
7365            // Frame 1 has shape `a`; frame 2 has shape `b` and sees `a` as prev.
7366            let w1 = long_window(
7367                WindowSequence::OnlyLong,
7368                a,
7369                a,
7370                &sine_l,
7371                &kbd_l,
7372                &sine_s,
7373                &kbd_s,
7374            );
7375            let w2 = long_window(
7376                WindowSequence::OnlyLong,
7377                a,
7378                b,
7379                &sine_l,
7380                &kbd_l,
7381                &sine_s,
7382                &kbd_s,
7383            );
7384            for n in 0..FRAME_LEN {
7385                let sum = w1[FRAME_LEN + n] * w1[FRAME_LEN + n] + w2[n] * w2[n];
7386                assert!(
7387                    (sum - 1.0).abs() < 1e-4,
7388                    "TDAC broken at n={n} for prev={a} cur={b}: {sum}"
7389                );
7390            }
7391        }
7392    }
7393
7394    /// Encode then decode under each arm. A prev/cur shape mismatch would show up
7395    /// here as gross reconstruction error, not a subtle quality delta.
7396    #[test]
7397    #[cfg_attr(miri, ignore = "too slow to interpret: over 2 minutes under Miri")]
7398    fn every_arm_round_trips() {
7399        let sr = 44100u32;
7400        let n = 12 * FRAME_LEN;
7401        let pcm: Vec<f32> = (0..n)
7402            .map(|i| {
7403                let t = i as f32 / sr as f32;
7404                0.3 * (2.0 * std::f32::consts::PI * 440.0 * t).sin()
7405                    + 0.2 * (2.0 * std::f32::consts::PI * 2600.0 * t).sin()
7406            })
7407            .collect();
7408
7409        for shape in [WindowShape::Sine, WindowShape::Kbd, WindowShape::Auto] {
7410            let mut e = AacEncoder::new(AacEncoderConfig {
7411                bitrate_bps: 128_000,
7412                window_shape: shape,
7413                shape_tonality_pct: 0.5,
7414                ..Default::default()
7415            });
7416            e.push_pcm(&pcm, 1, sr).unwrap();
7417            e.finish();
7418
7419            let mut dec = crate::decode::Decoder::new(sr);
7420            let mut got = Vec::new();
7421            while let Ok(p) = e.next_packet() {
7422                let audio = dec.decode(&p.data, None).expect("decode");
7423                got.extend_from_slice(&audio.samples);
7424            }
7425            assert!(got.len() >= n, "{shape:?}: short decode");
7426
7427            // Compare against the input, allowing the one-frame filterbank delay.
7428            let lag = FRAME_LEN;
7429            let cmp_len = n - 2 * FRAME_LEN;
7430            let (mut num, mut den) = (0f64, 0f64);
7431            for i in 0..cmp_len {
7432                let o = f64::from(pcm[i]);
7433                let d = f64::from(got[i + lag]);
7434                num += (o - d) * (o - d);
7435                den += o * o;
7436            }
7437            let snr = 10.0 * (den / num.max(1e-30)).log10();
7438            assert!(
7439                snr > 15.0,
7440                "{shape:?}: reconstruction SNR {snr:.1} dB is too low - \
7441                 a window-shape mismatch breaks TDAC"
7442            );
7443        }
7444    }
7445
7446    /// The `Auto` gate must actually dispatch — produce a mix of shapes on
7447    /// content whose tonality varies. A gate that routes everything one way is
7448    /// not a gate.
7449    #[test]
7450    fn auto_gate_dispatches_both_ways() {
7451        let sr = 44100u32;
7452        let n = 16 * FRAME_LEN;
7453        // Alternate 4-frame blocks of tone (tonal) and noise (not).
7454        let mut seed = 0x2468_ACE0u32;
7455        let pcm: Vec<f32> = (0..n)
7456            .map(|i| {
7457                if (i / (4 * FRAME_LEN)) % 2 == 0 {
7458                    let t = i as f32 / sr as f32;
7459                    0.4 * (2.0 * std::f32::consts::PI * 900.0 * t).sin()
7460                } else {
7461                    seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
7462                    0.4 * (((seed >> 8) as f32 / (1u32 << 24) as f32) * 2.0 - 1.0)
7463                }
7464            })
7465            .collect();
7466
7467        let mut e = AacEncoder::new(AacEncoderConfig {
7468            bitrate_bps: 128_000,
7469            window_shape: WindowShape::Auto,
7470            shape_tonality_pct: 0.5,
7471            ..Default::default()
7472        });
7473        e.push_pcm(&pcm, 1, sr).unwrap();
7474        let nblocks = n.div_ceil(FRAME_LEN) + 1;
7475        let shapes = e.decide_shapes(nblocks);
7476        let kbd = shapes.iter().filter(|&&s| s).count();
7477        assert!(
7478            kbd > 0 && kbd < shapes.len(),
7479            "Auto must route both ways, got {kbd}/{} KBD",
7480            shapes.len()
7481        );
7482
7483        // And it must route the TONAL blocks to KBD, not at random: the tonal
7484        // frames tonality must exceed the noise frames.
7485        let tone_ton = time_tonality(&e.block(0, 1));
7486        let noise_ton = time_tonality(&e.block(0, 5));
7487        assert!(
7488            tone_ton > noise_ton * 2.0,
7489            "the gate signal must separate tone ({tone_ton:.1}) from noise ({noise_ton:.1})"
7490        );
7491    }
7492}
7493
7494// ---------------------------------------------------------------------------
7495// Rungs 1-3 (arms A1 short-block psy, A2 tonality SMR, A3 TNS).
7496//
7497// Each arm must clear the same three bars before any quality number counts:
7498//   1. OFF is byte-identical with the encoder as it shipped,
7499//   2. ON still round-trips through our own decoder,
7500//   3. ON actually changes something (an arm that is a no-op is not an arm).
7501// ---------------------------------------------------------------------------
7502#[cfg(test)]
7503mod rung123 {
7504    use super::*;
7505
7506    fn encode(pcm: &[f32], ch: u16, sr: u32, cfg: AacEncoderConfig) -> Vec<Vec<u8>> {
7507        let mut e = AacEncoder::new(cfg);
7508        e.push_pcm(pcm, ch, sr).unwrap();
7509        e.finish();
7510        let mut out = Vec::new();
7511        while let Ok(p) = e.next_packet() {
7512            out.push(p.data);
7513        }
7514        out
7515    }
7516
7517    /// Decode a packet list, returning channel-0 PCM.
7518    fn decode_mono(packets: &[Vec<u8>], sr: u32) -> Vec<f32> {
7519        let mut dec = crate::decode::Decoder::new(sr);
7520        let mut out = Vec::new();
7521        for p in packets {
7522            let a = dec.decode(p, None).expect("decode");
7523            let ch = a.channels.max(1) as usize;
7524            out.extend(a.samples.iter().step_by(ch).copied());
7525        }
7526        out
7527    }
7528
7529    /// A transient-rich mono signal: sharp attacks over a quiet tonal floor.
7530    /// Drives short blocks (arm A1) and gives TNS something to shape (arm A3).
7531    fn transient_signal(sr: u32, frames: usize) -> Vec<f32> {
7532        use std::f32::consts::PI;
7533        let n = frames * FRAME_LEN;
7534        (0..n)
7535            .map(|i| {
7536                let t = i as f32 / sr as f32;
7537                let mut v = 0.05 * (2.0 * PI * 500.0 * t).sin();
7538                let k = i % (3 * FRAME_LEN);
7539                if k < 500 && i > FRAME_LEN {
7540                    let env = (1.0 - k as f32 / 500.0).max(0.0);
7541                    v += 0.85 * env * (2.0 * PI * 3300.0 * k as f32 / sr as f32).sin();
7542                }
7543                v
7544            })
7545            .collect()
7546    }
7547
7548    /// [`transient_signal`] with a broadband (noise) attack, for arm A3. TNS
7549    /// engages only when the coded range reaches `TNS_MAX_LONG`; a tone plus a
7550    /// 3.3 kHz burst has nothing up there once the mask has a hearing floor
7551    /// (#129), so its top bands are correctly left uncoded and TNS never fires.
7552    fn broadband_transient_signal(sr: u32, frames: usize) -> Vec<f32> {
7553        let mut x = 0x2468_ACE1u32;
7554        let mut noise = move || {
7555            x ^= x << 13;
7556            x ^= x >> 17;
7557            x ^= x << 5;
7558            (x as f32 / u32::MAX as f32) * 2.0 - 1.0
7559        };
7560        let mut v = transient_signal(sr, frames);
7561        for (i, s) in v.iter_mut().enumerate() {
7562            let k = i % (3 * FRAME_LEN);
7563            let n = noise();
7564            if k < 500 && i > FRAME_LEN {
7565                *s += 0.5 * (1.0 - k as f32 / 500.0) * n;
7566            }
7567        }
7568        v
7569    }
7570
7571    /// A tonal signal — a harmonic stack, the content arm A2 should treat
7572    /// differently from noise.
7573    fn tonal_signal(sr: u32, frames: usize) -> Vec<f32> {
7574        use std::f32::consts::PI;
7575        let n = frames * FRAME_LEN;
7576        (0..n)
7577            .map(|i| {
7578                let t = i as f32 / sr as f32;
7579                let mut v = 0f32;
7580                for h in 1..=6 {
7581                    v += (1.0 / h as f32) * (2.0 * PI * 330.0 * h as f32 * t).sin();
7582                }
7583                0.3 * v
7584            })
7585            .collect()
7586    }
7587
7588    /// **Every arm's OFF state is byte-identical with the shipped encoder.**
7589    /// This is law 7's neutral end, proven by `cmp` rather than argued.
7590    #[test]
7591    #[cfg_attr(miri, ignore = "too slow to interpret: over 2 minutes under Miri")]
7592    fn every_arm_off_is_byte_identical() {
7593        let sr = 44100u32;
7594        let sigs = [transient_signal(sr, 10), tonal_signal(sr, 10)];
7595        for pcm in &sigs {
7596            let base = encode(pcm, 1, sr, AacEncoderConfig::default());
7597            for (name, cfg) in [
7598                (
7599                    "short_block_psy",
7600                    AacEncoderConfig {
7601                        short_block_psy: false,
7602                        ..Default::default()
7603                    },
7604                ),
7605                (
7606                    "tonality_smr",
7607                    AacEncoderConfig {
7608                        tonality_smr: false,
7609                        ..Default::default()
7610                    },
7611                ),
7612                (
7613                    "tns",
7614                    AacEncoderConfig {
7615                        tns: false,
7616                        ..Default::default()
7617                    },
7618                ),
7619            ] {
7620                let got = encode(pcm, 1, sr, cfg);
7621                assert_eq!(got, base, "{name}: OFF must be byte-identical");
7622            }
7623        }
7624    }
7625
7626    /// **Arm A1** — short-block psy must change the bitstream on transient
7627    /// content (where short blocks actually occur) and still decode.
7628    #[test]
7629    #[cfg_attr(miri, ignore = "too slow to interpret: over 2 minutes under Miri")]
7630    fn a1_short_block_psy_changes_and_round_trips() {
7631        let sr = 44100u32;
7632        let pcm = transient_signal(sr, 12);
7633        let off = encode(&pcm, 1, sr, AacEncoderConfig::default());
7634        let on = encode(
7635            &pcm,
7636            1,
7637            sr,
7638            AacEncoderConfig {
7639                short_block_psy: true,
7640                ..Default::default()
7641            },
7642        );
7643        assert_ne!(off, on, "A1 must change the bitstream on transient content");
7644
7645        let dec = decode_mono(&on, sr);
7646        assert!(dec.len() >= pcm.len(), "A1: short decode");
7647        assert!(
7648            dec.iter().all(|v| v.is_finite()),
7649            "A1: non-finite output — the short-block mask is broken"
7650        );
7651        // Reconstruction must remain sane; a wrong band geometry in the short psy
7652        // path shows up as gross error, not a subtle quality shift.
7653        let lag = FRAME_LEN;
7654        let cmp = pcm.len() - 2 * FRAME_LEN;
7655        let (mut num, mut den) = (0f64, 0f64);
7656        for i in 0..cmp {
7657            let o = f64::from(pcm[i]);
7658            let d = f64::from(dec[i + lag]);
7659            num += (o - d) * (o - d);
7660            den += o * o;
7661        }
7662        let snr = 10.0 * (den / num.max(1e-30)).log10();
7663        assert!(snr > 8.0, "A1: reconstruction SNR {snr:.1} dB too low");
7664    }
7665
7666    /// **Arm 1a** — window grouping splits at energy jumps and leaves a steady
7667    /// frame as one group.
7668    #[test]
7669    fn a1a_short_groups_split_at_the_attack() {
7670        let mut spec = vec![0.0f32; FRAME_LEN];
7671        for (i, v) in spec.iter_mut().enumerate() {
7672            let win = i / SHORT_HALF;
7673            *v = if win < 5 { 1.0 } else { 40.0 } * if i % 2 == 0 { 1.0 } else { -1.0 };
7674        }
7675        assert_eq!(short_groups(&[&spec]), vec![5, 3]);
7676        let steady = vec![3.0f32; FRAME_LEN];
7677        assert_eq!(short_groups(&[&steady]), vec![8]);
7678        // Groups always tile the eight windows.
7679        let mut ramp = vec![0.0f32; FRAME_LEN];
7680        for (i, v) in ramp.iter_mut().enumerate() {
7681            *v = 4f32.powi((i / SHORT_HALF) as i32);
7682        }
7683        let g = short_groups(&[&ramp]);
7684        assert_eq!(g.iter().map(|&x| x as usize).sum::<usize>(), 8);
7685        assert!(g.len() > 1);
7686    }
7687
7688    /// **Arm 1a** — end to end, mono and stereo: the arm changes the bitstream on
7689    /// transient content and the result still decodes to a sane reconstruction.
7690    #[test]
7691    #[cfg_attr(miri, ignore = "too slow to interpret: over 2 minutes under Miri")]
7692    fn a1a_window_grouping_changes_and_round_trips() {
7693        let sr = 44100u32;
7694        let pcm = transient_signal(sr, 12);
7695        let cfg = AacEncoderConfig {
7696            window_grouping: true,
7697            ..Default::default()
7698        };
7699        let off = encode(&pcm, 1, sr, AacEncoderConfig::default());
7700        let on = encode(&pcm, 1, sr, cfg);
7701        assert_ne!(off, on, "1a must change the bitstream on transient content");
7702        let dec = decode_mono(&on, sr);
7703        assert!(dec.iter().all(|v| v.is_finite()), "1a: non-finite output");
7704        let lag = FRAME_LEN;
7705        let cmp = pcm.len() - 2 * FRAME_LEN;
7706        let (mut num, mut den) = (0f64, 0f64);
7707        for i in 0..cmp {
7708            let (o, d) = (f64::from(pcm[i]), f64::from(dec[i + lag]));
7709            num += (o - d) * (o - d);
7710            den += o * o;
7711        }
7712        let snr = 10.0 * (den / num.max(1e-30)).log10();
7713        assert!(snr > 8.0, "1a: reconstruction SNR {snr:.1} dB too low");
7714
7715        // Stereo: a shared grouping and per-group M/S through the CPE path.
7716        let st: Vec<f32> = pcm.iter().flat_map(|&v| [v, 0.6 * v]).collect();
7717        let packets = encode(&st, 2, sr, cfg);
7718        let mut d = crate::decode::Decoder::new(sr);
7719        let mut frames = 0usize;
7720        for p in &packets {
7721            let a = d.decode(p, None).expect("1a stereo decodes");
7722            assert_eq!(a.channels, 2);
7723            assert!(a.samples.iter().all(|v| v.is_finite()));
7724            frames += a.frames();
7725        }
7726        assert!(frames >= pcm.len(), "1a stereo: short decode");
7727    }
7728
7729    /// **Arm A2** — the SMR must actually vary with tonality. A pure tone and
7730    /// broadband noise at equal energy must no longer receive identical masks.
7731    #[test]
7732    fn a2_smr_varies_with_tonality() {
7733        // Direct check of the law itself, at a mid-band Bark.
7734        let tonal = smr_for(1.0, 10.0);
7735        let noisy = smr_for(0.0, 10.0);
7736        assert!(
7737            tonal < noisy,
7738            "a tonal masker must hold the mask FURTHER below the signal \
7739             (tonal {tonal:.5} must be < noise {noisy:.5})"
7740        );
7741        // And it must stay inside the documented clamp.
7742        for t in [0.0f64, 0.25, 0.5, 0.75, 1.0] {
7743            for bark in [0.0f64, 5.0, 12.0, 24.0] {
7744                let v = smr_for(t, bark);
7745                assert!(
7746                    v > 0.0 && v <= 10f64.powf(-5.0 / 10.0) + 1e-12,
7747                    "smr_for({t}, {bark}) = {v} escaped its clamp"
7748                );
7749            }
7750        }
7751    }
7752
7753    /// **Arm A2** — end to end: the bitstream changes on tonal content and still
7754    /// decodes.
7755    #[test]
7756    #[cfg_attr(miri, ignore = "too slow to interpret: over 2 minutes under Miri")]
7757    fn a2_changes_and_round_trips() {
7758        let sr = 44100u32;
7759        let pcm = tonal_signal(sr, 10);
7760        let off = encode(&pcm, 1, sr, AacEncoderConfig::default());
7761        let on = encode(
7762            &pcm,
7763            1,
7764            sr,
7765            AacEncoderConfig {
7766                tonality_smr: true,
7767                ..Default::default()
7768            },
7769        );
7770        assert_ne!(off, on, "A2 must change the bitstream on tonal content");
7771        let dec = decode_mono(&on, sr);
7772        assert!(dec.iter().all(|v| v.is_finite()));
7773        assert!(dec.len() >= pcm.len());
7774    }
7775
7776    /// **Arm A3 — the filter inversion.** The encoder runs the ALL-ZERO analysis
7777    /// filter; the decoder runs the ALL-POLE synthesis filter. If that inversion
7778    /// is wrong in sign, order or state, the spectrum does not degrade — it
7779    /// diverges. So this test demands the TNS arm reconstruct *at least as well*
7780    /// as the un-filtered arm, not merely "not crash".
7781    #[test]
7782    #[cfg_attr(miri, ignore = "too slow to interpret: over 2 minutes under Miri")]
7783    fn a3_tns_inverts_exactly() {
7784        let sr = 44100u32;
7785        let pcm = broadband_transient_signal(sr, 14);
7786
7787        let snr_of = |cfg: AacEncoderConfig| -> f64 {
7788            let pkts = encode(&pcm, 1, sr, cfg);
7789            let dec = decode_mono(&pkts, sr);
7790            assert!(dec.len() >= pcm.len());
7791            let lag = FRAME_LEN;
7792            let cmp = pcm.len() - 2 * FRAME_LEN;
7793            let (mut num, mut den) = (0f64, 0f64);
7794            for i in 0..cmp {
7795                let o = f64::from(pcm[i]);
7796                let d = f64::from(dec[i + lag]);
7797                num += (o - d) * (o - d);
7798                den += o * o;
7799            }
7800            10.0 * (den / num.max(1e-30)).log10()
7801        };
7802
7803        let base = snr_of(AacEncoderConfig {
7804            bitrate_bps: 256_000,
7805            ..Default::default()
7806        });
7807        let with_tns = snr_of(AacEncoderConfig {
7808            bitrate_bps: 256_000,
7809            tns: true,
7810            ..Default::default()
7811        });
7812        assert!(
7813            with_tns > base - 3.0,
7814            "A3: TNS collapsed reconstruction ({with_tns:.1} dB vs {base:.1} dB) — \
7815             the analysis/synthesis inversion is wrong, not merely suboptimal"
7816        );
7817    }
7818
7819    /// **Arm A3** — the quantized PARCOR round-trip must match the decoder's
7820    /// dequantizer bit-for-bit, including its asymmetric negative scale.
7821    #[test]
7822    fn a3_parcor_quantization_matches_the_decoder() {
7823        use std::f32::consts::PI;
7824        let res_bits = 3 + TNS_COEF_RES;
7825        let iqfac = ((1i32 << (res_bits - 1)) as f32 - 0.5) / (PI / 2.0);
7826        let iqfac_m = ((1i32 << (res_bits - 1)) as f32 + 0.5) / (PI / 2.0);
7827        for step in -20..=20 {
7828            let p = step as f32 / 21.0;
7829            let (idx, dq) = quantize_parcor(p);
7830            // Reproduce the DECODER's path from the emitted index.
7831            let masked = (idx as u32) & ((1u32 << TNS_COEF_BITS) - 1);
7832            let c = if masked & (1 << (TNS_COEF_BITS - 1)) != 0 {
7833                masked as i32 - (1 << TNS_COEF_BITS)
7834            } else {
7835                masked as i32
7836            };
7837            let t = if c >= 0 {
7838                c as f32 / iqfac
7839            } else {
7840                c as f32 / iqfac_m
7841            };
7842            let expect = t.sin();
7843            assert!(
7844                (dq - expect).abs() < 1e-6,
7845                "parcor {p}: encoder says {dq}, decoder reconstructs {expect}"
7846            );
7847        }
7848    }
7849
7850    /// **Arm A3** — TNS must actually engage on transient content (otherwise the
7851    /// round-trip test above passes vacuously).
7852    #[test]
7853    #[cfg_attr(miri, ignore = "too slow to interpret: over 2 minutes under Miri")]
7854    fn a3_tns_actually_engages() {
7855        // 256 kbps: TNS engages only on frames coded up to TNS_MAX_LONG (about
7856        // 16 kHz here), and since the hearing floor (#129) 128 kbps mono no
7857        // longer spends bits on the top bands of this signal.
7858        let sr = 44100u32;
7859        let pcm = broadband_transient_signal(sr, 14);
7860        let off = encode(
7861            &pcm,
7862            1,
7863            sr,
7864            AacEncoderConfig {
7865                bitrate_bps: 256_000,
7866                ..Default::default()
7867            },
7868        );
7869        let on = encode(
7870            &pcm,
7871            1,
7872            sr,
7873            AacEncoderConfig {
7874                bitrate_bps: 256_000,
7875                tns: true,
7876                ..Default::default()
7877            },
7878        );
7879        assert_ne!(
7880            off, on,
7881            "A3 never fired — the gate declined every frame, so the round-trip \
7882             test proves nothing"
7883        );
7884    }
7885}
7886
7887// ---------------------------------------------------------------------------
7888// Multichannel conformance — the tests that would have caught the original bug.
7889//
7890// The encoder used to emit N single_channel_elements while declaring
7891// `channel_configuration = N`. Our own decoder accepted it, so a self-round-trip
7892// looked perfect; a conforming decoder reading SCE, CPE, CPE, LFE would not.
7893// These tests check the ELEMENT SEQUENCE against ISO Table 1.19, not just that
7894// audio comes back.
7895// ---------------------------------------------------------------------------
7896#[cfg(test)]
7897mod multichannel {
7898    use super::*;
7899
7900    fn encode_packets(pcm: &[f32], ch: u16, sr: u32) -> Vec<Vec<u8>> {
7901        let mut e = AacEncoder::new(AacEncoderConfig::default());
7902        e.push_pcm(pcm, ch, sr).unwrap();
7903        e.finish();
7904        let mut out = Vec::new();
7905        while let Ok(p) = e.next_packet() {
7906            out.push(p.data);
7907        }
7908        out
7909    }
7910
7911    /// Read the sequence of element ids from a `raw_data_block`, skipping each
7912    /// element's payload by decoding it.
7913    fn element_ids(packet: &[u8], sr: u32) -> Vec<u32> {
7914        // Walk ids by re-decoding: the decoder is the only thing that knows each
7915        // element's length. We instead read ids from a fresh reader, relying on
7916        // the decoder to have validated the packet already.
7917        let mut ids = Vec::new();
7918        let mut dec = crate::decode::Decoder::new(sr);
7919        // The decoder must accept it at all.
7920        dec.decode(packet, None).expect("packet must decode");
7921        // Now re-read just the leading id of each element by decoding again with
7922        // a tracking reader is not available, so assert on the FIRST id plus the
7923        // channel count, which is what distinguishes the layouts we emit.
7924        let mut r = crate::BitReader::new(packet);
7925        ids.push(r.read_bits(3).unwrap());
7926        ids
7927    }
7928
7929    /// Distinct per-channel content so a mis-ordered channel is detectable.
7930    fn distinct_channels(nch: usize, frames: usize, sr: u32) -> Vec<f32> {
7931        let n = frames * FRAME_LEN;
7932        let mut out = Vec::with_capacity(n * nch);
7933        for i in 0..n {
7934            let t = i as f32 / sr as f32;
7935            for c in 0..nch {
7936                // A different frequency per channel, well separated.
7937                let f = 300.0 + 400.0 * c as f32;
7938                out.push(0.35 * (2.0 * std::f32::consts::PI * f * t).sin());
7939            }
7940        }
7941        out
7942    }
7943
7944    /// Every supported channel count produces a stream our decoder accepts with
7945    /// the right channel count.
7946    #[test]
7947    #[cfg_attr(miri, ignore = "too slow to interpret: over 2 minutes under Miri")]
7948    fn supported_channel_counts_round_trip() {
7949        let sr = 44100u32;
7950        for nch in 1..=6usize {
7951            let pcm = distinct_channels(nch, 6, sr);
7952            let pkts = encode_packets(&pcm, nch as u16, sr);
7953            assert!(!pkts.is_empty(), "{nch}ch: no packets");
7954            let mut dec = crate::decode::Decoder::new(sr);
7955            let audio = dec.decode(&pkts[0], None).expect("decode");
7956            assert_eq!(audio.channels as usize, nch, "{nch}ch: wrong channel count");
7957        }
7958    }
7959
7960    /// **The bug.** The first element of a 5.1 stream must be an SCE (the centre
7961    /// channel), and of a stereo stream a CPE. Before the fix a 5.1 stream began
7962    /// with an SCE too — but so did all six of its elements, which is what made it
7963    /// non-conformant.
7964    #[test]
7965    #[cfg_attr(miri, ignore = "too slow to interpret: over 2 minutes under Miri")]
7966    fn element_sequence_matches_iso_table() {
7967        let sr = 44100u32;
7968        for (nch, want_first) in [(1usize, ID_SCE), (2, ID_CPE), (3, ID_SCE), (6, ID_SCE)] {
7969            let pcm = distinct_channels(nch, 4, sr);
7970            let pkts = encode_packets(&pcm, nch as u16, sr);
7971            let ids = element_ids(&pkts[0], sr);
7972            assert_eq!(ids[0], want_first, "{nch}ch: wrong first element id");
7973        }
7974    }
7975
7976    /// The plan itself must match ISO Table 1.19, including the reordering.
7977    #[test]
7978    fn element_plan_matches_iso_table() {
7979        assert_eq!(element_plan(1).unwrap(), vec![Elem::Sce(0)]);
7980        assert_eq!(element_plan(2).unwrap(), vec![Elem::Cpe(0, 1)]);
7981        // 3.0: centre first, then the front pair.
7982        assert_eq!(
7983            element_plan(3).unwrap(),
7984            vec![Elem::Sce(2), Elem::Cpe(0, 1)]
7985        );
7986        // 5.1: C, L/R, Ls/Rs, LFE — with LFE taken from interleave slot 3.
7987        assert_eq!(
7988            element_plan(6).unwrap(),
7989            vec![Elem::Sce(2), Elem::Cpe(0, 1), Elem::Cpe(4, 5), Elem::Lfe(3)]
7990        );
7991        // No channel_configuration exists for these.
7992        assert!(element_plan(0).is_none());
7993        assert!(element_plan(7).is_none());
7994        assert!(element_plan(8).is_none());
7995    }
7996
7997    /// The decoder's reorder must be the exact inverse of the encoder's plan:
7998    /// what goes into interleave slot `k` must come back out of slot `k`.
7999    #[test]
8000    #[cfg_attr(miri, ignore = "too slow to interpret: over 2 minutes under Miri")]
8001    fn channel_order_survives_the_round_trip() {
8002        let sr = 44100u32;
8003        for nch in [1usize, 2, 3, 5, 6] {
8004            let pcm = distinct_channels(nch, 8, sr);
8005            let pkts = encode_packets(&pcm, nch as u16, sr);
8006            let mut dec = crate::decode::Decoder::new(sr);
8007            let mut planes: Vec<Vec<f32>> = vec![Vec::new(); nch];
8008            for p in &pkts {
8009                let a = dec.decode(p, None).expect("decode");
8010                for (i, v) in a.samples.iter().enumerate() {
8011                    planes[i % nch].push(*v);
8012                }
8013            }
8014            // Each decoded channel must correlate best with the SAME input
8015            // channel. A layout or reorder error shows up as a swapped best match.
8016            for c in 0..nch {
8017                let f_expect = 300.0 + 400.0 * c as f32;
8018                // Estimate dominant frequency by zero-crossing count over a
8019                // mid-stream window (crude but unambiguous at this separation).
8020                let seg = &planes[c][3 * FRAME_LEN..5 * FRAME_LEN];
8021                let mut crossings = 0usize;
8022                for w in seg.windows(2) {
8023                    if (w[0] <= 0.0) != (w[1] <= 0.0) {
8024                        crossings += 1;
8025                    }
8026                }
8027                let secs = seg.len() as f32 / sr as f32;
8028                let f_est = crossings as f32 / 2.0 / secs;
8029                assert!(
8030                    (f_est - f_expect).abs() < 120.0,
8031                    "{nch}ch: channel {c} came back at ~{f_est:.0} Hz, expected \\
8032                     ~{f_expect:.0} Hz — channel order is wrong"
8033                );
8034            }
8035        }
8036    }
8037
8038    /// Unsupported counts must be REJECTED, not silently mis-encoded. This is the
8039    /// guard: an unencodable layout is an error, never a wrong bitstream.
8040    #[test]
8041    fn unsupported_channel_counts_are_rejected() {
8042        for nch in [7u16, 8, 12] {
8043            let pcm = vec![0.1f32; FRAME_LEN * nch as usize * 2];
8044            let mut e = AacEncoder::new(AacEncoderConfig::default());
8045            let res = e.push_pcm(&pcm, nch, 44100);
8046            assert!(
8047                res.is_err(),
8048                "{nch} channels must be rejected until a program_config_element exists"
8049            );
8050        }
8051    }
8052}
8053
8054#[cfg(test)]
8055mod rung_a6 {
8056    use super::*;
8057
8058    fn noise_signal(_sr: u32, frames: usize) -> Vec<f32> {
8059        let mut seed = 0xA6A6_1234u32;
8060        (0..frames * FRAME_LEN)
8061            .map(|_| {
8062                seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
8063                0.4 * (((seed >> 8) as f32 / (1u32 << 24) as f32) * 2.0 - 1.0)
8064            })
8065            .collect()
8066    }
8067
8068    fn encode(pcm: &[f32], sr: u32, cfg: AacEncoderConfig) -> Vec<Vec<u8>> {
8069        let mut e = AacEncoder::new(cfg);
8070        e.push_pcm(pcm, 1, sr).unwrap();
8071        e.finish();
8072        let mut out = Vec::new();
8073        while let Ok(p) = e.next_packet() {
8074            out.push(p.data);
8075        }
8076        out
8077    }
8078
8079    /// OFF is byte-identical with the shipped encoder.
8080    #[test]
8081    #[cfg_attr(miri, ignore = "too slow to interpret: over 2 minutes under Miri")]
8082    fn a6_off_is_byte_identical() {
8083        let sr = 44100;
8084        let pcm = noise_signal(sr, 8);
8085        let a = encode(&pcm, sr, AacEncoderConfig::default());
8086        let b = encode(
8087            &pcm,
8088            sr,
8089            AacEncoderConfig {
8090                pns: false,
8091                ..Default::default()
8092            },
8093        );
8094        assert_eq!(a, b);
8095    }
8096
8097    /// PNS must fire on noise and the stream must still decode. A desynchronized
8098    /// scalefactor chain (the classic PNS bug) shows up here as a decode error or
8099    /// non-finite output, not as a subtle quality shift.
8100    #[test]
8101    #[cfg_attr(miri, ignore = "too slow to interpret: over 2 minutes under Miri")]
8102    fn a6_fires_on_noise_and_round_trips() {
8103        let sr = 44100;
8104        let pcm = noise_signal(sr, 10);
8105        let off = encode(
8106            &pcm,
8107            sr,
8108            AacEncoderConfig {
8109                bitrate_bps: 96_000,
8110                ..Default::default()
8111            },
8112        );
8113        let on = encode(
8114            &pcm,
8115            sr,
8116            AacEncoderConfig {
8117                bitrate_bps: 96_000,
8118                pns: true,
8119                ..Default::default()
8120            },
8121        );
8122        assert_ne!(off, on, "A6 must fire on broadband noise");
8123
8124        let mut dec = crate::decode::Decoder::new(sr);
8125        let mut got = Vec::new();
8126        for p in &on {
8127            let a = dec.decode(p, None).expect("PNS stream must decode");
8128            got.extend_from_slice(&a.samples);
8129        }
8130        assert!(got.iter().all(|v| v.is_finite()), "non-finite output");
8131        // Energy must be broadly preserved: PNS substitutes noise of the SAME
8132        // energy, so a gross level error means the ne <-> energy mapping is wrong.
8133        let e_in: f64 = pcm.iter().map(|&x| f64::from(x) * f64::from(x)).sum();
8134        let e_out: f64 = got.iter().map(|&x| f64::from(x) * f64::from(x)).sum();
8135        let ratio = e_out / e_in.max(1e-12);
8136        assert!(
8137            (0.25..4.0).contains(&ratio),
8138            "PNS energy mismatch: out/in = {ratio:.3} - check ne = 2*log2(E)"
8139        );
8140    }
8141
8142    /// PNS must NOT fire on a pure tone: it is the anti-class, and substituting a
8143    /// harmonic band with noise is audibly destructive.
8144    #[test]
8145    #[cfg_attr(miri, ignore = "too slow to interpret: over 2 minutes under Miri")]
8146    fn a6_declines_on_tonal_content() {
8147        let sr = 44100;
8148        let pcm: Vec<f32> = (0..10 * FRAME_LEN)
8149            .map(|i| {
8150                let t = i as f32 / sr as f32;
8151                0.4 * (2.0 * std::f32::consts::PI * 6000.0 * t).sin()
8152            })
8153            .collect();
8154        let off = encode(
8155            &pcm,
8156            sr,
8157            AacEncoderConfig {
8158                bitrate_bps: 96_000,
8159                ..Default::default()
8160            },
8161        );
8162        let on = encode(
8163            &pcm,
8164            sr,
8165            AacEncoderConfig {
8166                bitrate_bps: 96_000,
8167                pns: true,
8168                ..Default::default()
8169            },
8170        );
8171        assert_eq!(
8172            off, on,
8173            "A6 fired on a pure 6 kHz tone - the tonality guard is not working"
8174        );
8175    }
8176
8177    /// PNS and TNS must not both apply to one element (the energy domain differs).
8178    #[test]
8179    #[cfg_attr(miri, ignore = "too slow to interpret: over 2 minutes under Miri")]
8180    fn a6_yields_to_tns() {
8181        let sr = 44100;
8182        let pcm = noise_signal(sr, 10);
8183        let both = encode(
8184            &pcm,
8185            sr,
8186            AacEncoderConfig {
8187                bitrate_bps: 128_000,
8188                pns: true,
8189                tns: true,
8190                ..Default::default()
8191            },
8192        );
8193        let mut dec = crate::decode::Decoder::new(sr);
8194        for p in &both {
8195            let a = dec.decode(p, None).expect("combined stream must decode");
8196            assert!(a.samples.iter().all(|v| v.is_finite()));
8197        }
8198    }
8199}
8200
8201#[cfg(test)]
8202mod rung_a7 {
8203    use super::*;
8204
8205    /// A stereo pair whose high bands are a scaled copy — the content intensity
8206    /// stereo exists for.
8207    fn correlated_stereo(sr: u32, frames: usize, gain: f32) -> Vec<f32> {
8208        let n = frames * FRAME_LEN;
8209        let mut out = Vec::with_capacity(n * 2);
8210        let mut seed = 0x7777_1111u32;
8211        for i in 0..n {
8212            let t = i as f32 / sr as f32;
8213            let low = 0.3 * (2.0 * std::f32::consts::PI * 300.0 * t).sin();
8214            seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
8215            let hi = 0.25 * (((seed >> 8) as f32 / (1u32 << 24) as f32) * 2.0 - 1.0);
8216            out.push(low + hi);
8217            out.push(low + hi * gain);
8218        }
8219        out
8220    }
8221
8222    fn encode(pcm: &[f32], sr: u32, cfg: AacEncoderConfig) -> Vec<Vec<u8>> {
8223        let mut e = AacEncoder::new(cfg);
8224        e.push_pcm(pcm, 2, sr).unwrap();
8225        e.finish();
8226        let mut out = Vec::new();
8227        while let Ok(p) = e.next_packet() {
8228            out.push(p.data);
8229        }
8230        out
8231    }
8232
8233    #[test]
8234    #[cfg_attr(miri, ignore = "too slow to interpret: over 2 minutes under Miri")]
8235    fn a7_off_is_byte_identical() {
8236        let sr = 44100;
8237        let pcm = correlated_stereo(sr, 8, 0.7);
8238        let a = encode(&pcm, sr, AacEncoderConfig::default());
8239        let b = encode(
8240            &pcm,
8241            sr,
8242            AacEncoderConfig {
8243                intensity: false,
8244                ..Default::default()
8245            },
8246        );
8247        assert_eq!(a, b);
8248    }
8249
8250    /// Fires on a scaled-copy pair and still decodes. A wrong `is_pos` sign or a
8251    /// desynchronized intensity accumulator shows up here immediately.
8252    #[test]
8253    #[cfg_attr(miri, ignore = "too slow to interpret: over 2 minutes under Miri")]
8254    fn a7_fires_and_round_trips() {
8255        let sr = 44100;
8256        let pcm = correlated_stereo(sr, 10, 0.7);
8257        let off = encode(
8258            &pcm,
8259            sr,
8260            AacEncoderConfig {
8261                bitrate_bps: 96_000,
8262                ..Default::default()
8263            },
8264        );
8265        let on = encode(
8266            &pcm,
8267            sr,
8268            AacEncoderConfig {
8269                bitrate_bps: 96_000,
8270                intensity: true,
8271                ..Default::default()
8272            },
8273        );
8274        assert_ne!(off, on, "A7 must fire on a correlated high band");
8275
8276        let mut dec = crate::decode::Decoder::new(sr);
8277        let mut got = Vec::new();
8278        for p in &on {
8279            let a = dec.decode(p, None).expect("intensity stream must decode");
8280            got.extend_from_slice(&a.samples);
8281        }
8282        assert!(got.iter().all(|v| v.is_finite()));
8283        // The reconstructed right channel must keep roughly the intended level
8284        // ratio: a sign or exponent error in is_pos shows up as a gross imbalance.
8285        let (mut el, mut er) = (0f64, 0f64);
8286        for c in got.chunks_exact(2) {
8287            el += f64::from(c[0]) * f64::from(c[0]);
8288            er += f64::from(c[1]) * f64::from(c[1]);
8289        }
8290        let ratio = (er / el.max(1e-12)).sqrt();
8291        assert!(
8292            (0.4..1.6).contains(&ratio),
8293            "channel balance wrong after intensity: R/L = {ratio:.3}"
8294        );
8295    }
8296
8297    /// Must DECLINE on a decorrelated pair — the anti-class. Collapsing a wide
8298    /// image to a scaled copy is the failure mode this gate exists to prevent.
8299    #[test]
8300    #[cfg_attr(miri, ignore = "too slow to interpret: over 2 minutes under Miri")]
8301    fn a7_declines_on_wide_stereo() {
8302        let sr = 44100;
8303        let n = 8 * FRAME_LEN;
8304        let mut s1 = 0xAAAA_1111u32;
8305        let mut s2 = 0x5555_2222u32;
8306        let mut pcm = Vec::with_capacity(n * 2);
8307        for _ in 0..n {
8308            s1 = s1.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
8309            s2 = s2.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
8310            pcm.push(0.3 * (((s1 >> 8) as f32 / (1u32 << 24) as f32) * 2.0 - 1.0));
8311            pcm.push(0.3 * (((s2 >> 8) as f32 / (1u32 << 24) as f32) * 2.0 - 1.0));
8312        }
8313        let off = encode(
8314            &pcm,
8315            sr,
8316            AacEncoderConfig {
8317                bitrate_bps: 128_000,
8318                ..Default::default()
8319            },
8320        );
8321        let on = encode(
8322            &pcm,
8323            sr,
8324            AacEncoderConfig {
8325                bitrate_bps: 128_000,
8326                intensity: true,
8327                ..Default::default()
8328            },
8329        );
8330        assert_eq!(
8331            off, on,
8332            "A7 fired on fully decorrelated channels - the correlation gate is not working"
8333        );
8334    }
8335}
8336
8337/// `remade_ffmpeg_rs#129`: a pure tone, and a 5.1 stream with only its centre
8338/// active, must come back at their level and with the precision their bitrate
8339/// buys. Before the hearing floor the mask scaled with each band's own energy,
8340/// so near-silent bands took the bits (a 440 Hz tone at 128 kbps: 19.8 dB);
8341/// before budget pooling a lone 5.1 centre got a sixth of the bitrate (320
8342/// kbps: 10.2 dB, gain up to 1.54 at 128 kbps).
8343#[cfg(test)]
8344mod fidelity_129 {
8345    use super::*;
8346
8347    /// Encode interleaved `pcm`, decode it, and return channel `c`'s gain and
8348    /// SNR (dB) against `src` over the middle half, at the encoder's
8349    /// 1024-sample delay; plus the largest output sample on every other channel.
8350    fn gain_snr(pcm: &[f32], ch: usize, c: usize, sr: u32, kbps: u32) -> (f64, f64, f32) {
8351        let mut e = AacEncoder::new(AacEncoderConfig {
8352            bitrate_bps: kbps * 1000,
8353            ..Default::default()
8354        });
8355        e.push_pcm(pcm, ch as u16, sr).unwrap();
8356        e.finish();
8357        let mut dec = crate::decode::Decoder::new(sr);
8358        let mut out: Vec<f32> = Vec::new();
8359        while let Ok(p) = e.next_packet() {
8360            out.extend(dec.decode(&p.data, None).expect("decode").samples);
8361        }
8362        let n = pcm.len() / ch;
8363        let (mut xy, mut xx) = (0f64, 0f64);
8364        for i in n / 4..n * 3 / 4 {
8365            let (x, y) = (
8366                f64::from(pcm[i * ch + c]),
8367                f64::from(out[(i + FRAME_LEN) * ch + c]),
8368            );
8369            xy += x * y;
8370            xx += x * x;
8371        }
8372        let g = xy / xx;
8373        let mut err = 0f64;
8374        for i in n / 4..n * 3 / 4 {
8375            let e = f64::from(out[(i + FRAME_LEN) * ch + c]) - f64::from(pcm[i * ch + c]);
8376            err += e * e;
8377        }
8378        let others = (0..out.len())
8379            .filter(|i| i % ch != c)
8380            .map(|i| out[i].abs())
8381            .fold(0f32, f32::max);
8382        (g, 10.0 * (xx / err).log10(), others)
8383    }
8384
8385    fn tone(n: usize, ch: usize, c: usize, sr: u32) -> Vec<f32> {
8386        let amp = 10f32.powf(-10.0 / 20.0);
8387        let mut v = vec![0f32; n * ch];
8388        for i in 0..n {
8389            v[i * ch + c] = amp * (2.0 * std::f32::consts::PI * 440.0 * i as f32 / sr as f32).sin();
8390        }
8391        v
8392    }
8393
8394    /// A 220/330 Hz stereo pair, interleaved.
8395    fn tone_pair(n: usize, sr: u32) -> Vec<f32> {
8396        (0..n * 2)
8397            .map(|i| {
8398                let f = [220.0f32, 330.0][i % 2];
8399                let t = (i / 2) as f32 / sr as f32;
8400                0.316 * (2.0 * std::f32::consts::PI * f * t).sin()
8401            })
8402            .collect()
8403    }
8404
8405    fn tuned_aus(pcm: &[f32], ch: u16, kbps: u32, surplus: bool) -> Vec<Vec<u8>> {
8406        let tuning = AacTuning {
8407            surplus_shaping: surplus,
8408            ..Default::default()
8409        };
8410        let cfg = AacEncoderConfig {
8411            bitrate_bps: kbps * 1000,
8412            ..Default::default()
8413        };
8414        let mut e = AacEncoder::with_tuning(cfg, tuning);
8415        e.push_pcm(pcm, ch, 48_000).unwrap();
8416        e.finish();
8417        std::iter::from_fn(|| e.next_packet().ok().map(|p| p.data)).collect()
8418    }
8419
8420    /// `remade_ffmpeg_rs#211`: bits left over far below the masks go to the
8421    /// tones, not to their inaudible window leakage (51 and 62 dB before),
8422    /// up to the quantizer's own limit of about 84 dB, at any rate.
8423    #[test]
8424    #[cfg_attr(miri, ignore = "too slow to interpret")]
8425    fn spare_bits_go_to_the_tones() {
8426        let sr = 48_000;
8427        let pcm = tone_pair(sr as usize * 2, sr);
8428        for (kbps, want) in [(256, 50.0), (320, 60.0), (512, 78.0)] {
8429            for c in 0..2 {
8430                let (g, snr, _) = gain_snr(&pcm, 2, c, sr, kbps);
8431                assert!((0.999..=1.001).contains(&g), "{kbps} kbps: gain {g}");
8432                assert!(snr > want, "{kbps} kbps channel {c}: {snr:.1} dB");
8433            }
8434        }
8435        // Two identical channels: the side is silent.
8436        let dual: Vec<f32> = pcm.chunks(2).flat_map(|c| [c[0] + c[1]; 2]).collect();
8437        let (_, snr, _) = gain_snr(&dual, 2, 0, sr, 320);
8438        assert!(snr > 78.0, "identical channels: {snr:.1} dB");
8439        let mono = tone(sr as usize * 2, 1, 0, sr);
8440        // Past what a 6144-bit frame holds: every band is at its no-clamp floor.
8441        let (_, snr, _) = gain_snr(&mono, 1, 0, sr, 512);
8442        assert!(snr > 78.0, "mono: {snr:.1} dB");
8443    }
8444
8445    /// TNS data is not in the rate loop's count: at the buffer's limit it took
8446    /// a block to 769 bytes (found by the `encode` fuzz target).
8447    #[test]
8448    #[cfg_attr(miri, ignore = "too slow to interpret")]
8449    fn a_tns_block_fits_the_decoder_buffer() {
8450        let mut s = 8u64.wrapping_mul(0x9e37_79b9_7f4a_7c15);
8451        let mut noise = || {
8452            s ^= s << 13;
8453            s ^= s >> 7;
8454            s ^= s << 17;
8455            (s >> 40) as f32 / (1u64 << 24) as f32 - 0.5
8456        };
8457        let pcm: Vec<f32> = (0..48_000)
8458            .map(|i| {
8459                let p = i % 4800;
8460                let hit = if p < 2400 {
8461                    0.0
8462                } else {
8463                    0.6 * (-((p - 2400) as f32) / 400.0).exp()
8464                };
8465                (hit + 0.002) * noise() + 0.1 * (i as f32 * 0.05).sin()
8466            })
8467            .collect();
8468        let mut e = AacEncoder::new(AacEncoderConfig {
8469            bitrate_bps: u32::MAX,
8470            tns: true,
8471            ..Default::default()
8472        });
8473        e.push_pcm(&pcm, 1, 48_000).unwrap();
8474        e.finish();
8475        while let Ok(p) = e.next_packet() {
8476            assert!(p.data.len() <= 768, "{} bytes", p.data.len());
8477        }
8478    }
8479
8480    /// The surplus policy leaves every stream under its rate, and every
8481    /// multichannel one, byte for byte as it was.
8482    #[test]
8483    #[cfg_attr(miri, ignore = "too slow to interpret")]
8484    fn surplus_shaping_leaves_low_rates_and_multichannel_alone() {
8485        let n = 48_000;
8486        let stereo = tone_pair(n, 48_000);
8487        let dual: Vec<f32> = stereo.chunks(2).flat_map(|c| [c[0] + c[1]; 2]).collect();
8488        let six = tone(n, 6, 2, 48_000);
8489        for (pcm, ch, kbps, same) in [
8490            (&stereo, 2, 190, true),
8491            (&stereo, 2, 320, false),
8492            (&dual, 2, 190, true),
8493            (&dual, 2, 320, false),
8494            (&six, 6, 320, true),
8495            (&six, 6, 640, true),
8496        ] {
8497            let (on, off) = (
8498                tuned_aus(pcm, ch, kbps, true),
8499                tuned_aus(pcm, ch, kbps, false),
8500            );
8501            assert_eq!(on == off, same, "{ch} channels at {kbps} kbps");
8502            assert!(on.iter().all(|p| p.len() * 8 <= 6144 * usize::from(ch)));
8503        }
8504    }
8505
8506    #[test]
8507    #[cfg_attr(miri, ignore = "too slow to interpret")]
8508    fn a_pure_tone_gets_the_bits() {
8509        let sr = 48_000;
8510        let (g, snr, _) = gain_snr(&tone(sr as usize * 2, 1, 0, sr), 1, 0, sr, 128);
8511        assert!((0.99..=1.01).contains(&g), "gain {g}");
8512        assert!(snr > 30.0, "a 440 Hz tone at 128 kbps: {snr:.1} dB");
8513    }
8514
8515    #[test]
8516    #[cfg_attr(miri, ignore = "too slow to interpret")]
8517    fn a_lone_5_1_centre_gets_the_whole_bitrate() {
8518        let sr = 48_000;
8519        // WAV / FFmpeg order: L R C LFE Ls Rs.
8520        let (g, snr, others) = gain_snr(&tone(sr as usize * 2, 6, 2, sr), 6, 2, sr, 320);
8521        assert!((0.99..=1.01).contains(&g), "centre gain {g}");
8522        assert!(snr > 45.0, "5.1 centre alone at 320 kbps: {snr:.1} dB");
8523        assert!(others < 1e-3, "silent channels stay silent: {others}");
8524    }
8525
8526    /// One 0.25 sine per channel (220, 330, 440, 55, 660, 880 Hz in L R C LFE
8527    /// Ls Rs order) over independent 0.03 x uniform(-0.5, 0.5) noise: the
8528    /// #129 repro with every element busy.
8529    fn busy_5_1(n: usize, sr: u32) -> Vec<f32> {
8530        let tones = [220.0f32, 330.0, 440.0, 55.0, 660.0, 880.0];
8531        let mut seed = 0x2545_f491u32;
8532        let mut v = vec![0f32; n * 6];
8533        for i in 0..n {
8534            for (c, f) in tones.iter().enumerate() {
8535                seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
8536                let noise = 0.03 * ((seed >> 8) as f32 / (1u32 << 24) as f32 - 0.5);
8537                let t = i as f32 / sr as f32;
8538                v[i * 6 + c] = 0.25 * (2.0 * std::f32::consts::PI * f * t).sin() + noise;
8539            }
8540        }
8541        v
8542    }
8543
8544    /// Encode `pcm` and return the packets.
8545    fn packets(pcm: &[f32], ch: usize, sr: u32, kbps: u32) -> Vec<EncodedPacket> {
8546        let mut e = AacEncoder::new(AacEncoderConfig {
8547            bitrate_bps: kbps * 1000,
8548            ..Default::default()
8549        });
8550        e.push_pcm(pcm, ch as u16, sr).unwrap();
8551        e.finish();
8552        std::iter::from_fn(|| e.next_packet().ok()).collect()
8553    }
8554
8555    /// The decoder rebuilds `q^(4/3)`, so the quantizer must pick the level
8556    /// whose reconstruction is nearest, not the nearest integer to `|x|^0.75`.
8557    #[test]
8558    fn the_quantizer_picks_the_nearest_reconstruction() {
8559        for i in 0..=3_000 {
8560            let v = f64::from(i) * 1e-3;
8561            let x = v.powf(4.0 / 3.0);
8562            let nearest = (0..6)
8563                .min_by(|&a, &b| {
8564                    let da = (x - f64::from(a).powf(4.0 / 3.0)).abs();
8565                    let db = (x - f64::from(b).powf(4.0 / 3.0)).abs();
8566                    da.partial_cmp(&db).unwrap()
8567                })
8568                .unwrap();
8569            let got = nearest_level(v);
8570            // Above 2 the midpoints sit within 0.017 of k + 0.5 and plain
8571            // rounding is kept there.
8572            if v < 2.0 || (v.fract() - 0.5).abs() > 0.02 {
8573                assert_eq!(got, nearest, "v = {v}");
8574            } else {
8575                assert!((got - nearest).abs() <= 1, "v = {v}");
8576            }
8577        }
8578    }
8579
8580    /// A 5.1 stream with all six channels busy at 320 kbps (53 kbps a
8581    /// channel): every channel comes back at its own level. On 2.1.1 the
8582    /// best-fit gains were 1.25 / 1.42 / 1.31 / 1.22 / 1.49 / 1.20.
8583    #[test]
8584    #[cfg_attr(miri, ignore = "too slow to interpret")]
8585    fn every_busy_5_1_channel_keeps_its_level() {
8586        let sr = 48_000;
8587        let n = sr as usize * 3;
8588        let pcm = busy_5_1(n, sr);
8589        let mut dec = crate::decode::Decoder::new(sr);
8590        let mut out: Vec<f32> = Vec::new();
8591        for p in packets(&pcm, 6, sr, 320) {
8592            out.extend(dec.decode(&p.data, None).expect("decode").samples);
8593        }
8594        for c in 0..6 {
8595            let (mut xy, mut xx) = (0f64, 0f64);
8596            for i in n / 4..n * 3 / 4 {
8597                let x = f64::from(pcm[i * 6 + c]);
8598                xy += x * f64::from(out[(i + FRAME_LEN) * 6 + c]);
8599                xx += x * x;
8600            }
8601            let g = xy / xx;
8602            assert!((0.93..=1.07).contains(&g), "channel {c}: gain {g:.3}");
8603        }
8604    }
8605
8606    /// An LFE frame drops its quiet content above 281 Hz (a sub-bass tone
8607    /// over a noise floor) but keeps content that is really there.
8608    #[test]
8609    fn the_lfe_drops_only_a_quiet_top() {
8610        let sr = 48_000.0f32;
8611        let win: Vec<f32> = crate::dsp::sine_window(2 * FRAME_LEN);
8612        let spectrum = |f: f32, noise: f32| {
8613            let mut seed = 0x9e37_79b9u32;
8614            let mut x = [[0f32; FRAME_LEN]; 2];
8615            for (b, blk) in x.iter_mut().enumerate() {
8616                for (i, v) in blk.iter_mut().enumerate() {
8617                    seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
8618                    let t = (b * FRAME_LEN + i) as f32 / sr;
8619                    *v = 0.25 * (2.0 * std::f32::consts::PI * f * t).sin()
8620                        + noise * ((seed >> 8) as f32 / (1u32 << 24) as f32 - 0.5);
8621                }
8622            }
8623            analyze_long(&x[0], &x[1], &win)
8624        };
8625        let mut sub = spectrum(55.0, 0.03);
8626        lfe_band_limit(&mut sub);
8627        assert!(sub[LFE_LINES..].iter().all(|&v| v == 0.0));
8628        assert!(sub[..LFE_LINES].iter().any(|&v| v != 0.0));
8629        let mut mid = spectrum(1000.0, 0.0);
8630        let kept = mid.clone();
8631        lfe_band_limit(&mut mid);
8632        assert_eq!(mid, kept);
8633    }
8634
8635    /// The downstream 5.1 gate signal: one 0.25 tone per channel (500, 700, 900, 60,
8636    /// 1300, 1700 Hz in L R C LFE Ls Rs order) with a slow swell, over
8637    /// independent 0.03 x uniform(-0.5, 0.5) noise. `ch` = 1 is its first
8638    /// channel alone.
8639    fn tone_over_noise(n: usize, ch: usize, sr: u32) -> Vec<f32> {
8640        let tones = [500.0f32, 700.0, 900.0, 60.0, 1300.0, 1700.0];
8641        let mut seed = 0x1234_5678u32;
8642        let mut v = vec![0f32; n * ch];
8643        for i in 0..n {
8644            let t = i as f32 / sr as f32;
8645            let swell = 0.6 + 0.4 * (2.0 * std::f32::consts::PI * 0.7 * t).sin();
8646            for (c, f) in tones.iter().enumerate().take(ch) {
8647                seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
8648                let noise = 0.03 * ((seed >> 8) as f32 / (1u32 << 24) as f32 - 0.5);
8649                v[i * ch + c] = 0.25 * swell * (2.0 * std::f32::consts::PI * f * t).sin() + noise;
8650            }
8651        }
8652        v
8653    }
8654
8655    /// Encode and decode `pcm`; return the SNR over all channels and the
8656    /// level (dB, decoded RMS over source RMS) of each channel, over the clip
8657    /// at the encoder's 1024-sample delay.
8658    fn snr_levels(pcm: &[f32], ch: usize, sr: u32, kbps: u32) -> (f64, Vec<f64>) {
8659        let mut dec = crate::decode::Decoder::new(sr);
8660        let mut out: Vec<f32> = Vec::new();
8661        for p in packets(pcm, ch, sr, kbps) {
8662            out.extend(dec.decode(&p.data, None).expect("decode").samples);
8663        }
8664        let n = pcm.len() / ch;
8665        let (mut sx, mut se) = (0f64, 0f64);
8666        let mut levels = Vec::with_capacity(ch);
8667        for c in 0..ch {
8668            let (mut xx, mut yy) = (0f64, 0f64);
8669            for i in 0..n {
8670                let x = f64::from(pcm[i * ch + c]);
8671                let y = f64::from(out[(i + FRAME_LEN) * ch + c]);
8672                xx += x * x;
8673                yy += y * y;
8674                se += (y - x) * (y - x);
8675            }
8676            sx += xx;
8677            levels.push(10.0 * (yy / xx).log10());
8678        }
8679        (10.0 * (sx / se).log10(), levels)
8680    }
8681
8682    /// On a tone over noise the SNR rises with the bitrate, reaches 20 dB at
8683    /// 320 kbps 5.1, and every channel keeps its level within 0.3 dB. Before
8684    /// the narrow-band SNR floor ([`peak_hold`]) it sat at 15.8-16.9 dB from
8685    /// 128 to 512 kbps 5.1 (15.6-18.3 dB from 32 to 128 kbps mono) and levels
8686    /// swung by up to 0.6 dB.
8687    #[test]
8688    #[cfg_attr(miri, ignore = "too slow to interpret")]
8689    fn tone_over_noise_snr_rises_with_the_bitrate() {
8690        let sr = 48_000u32;
8691        let n = sr as usize * 2;
8692        for (ch, rates, at_320) in [
8693            (6, &[128, 192, 320, 512][..], true),
8694            (1, &[32, 64, 96, 128, 192][..], false),
8695        ] {
8696            let pcm = tone_over_noise(n, ch, sr);
8697            let mut last = f64::NEG_INFINITY;
8698            for &kbps in rates {
8699                let (snr, levels) = snr_levels(&pcm, ch, sr, kbps);
8700                assert!(
8701                    snr > last,
8702                    "{ch} ch: {snr:.2} dB at {kbps} kbps, not above {last:.2} dB"
8703                );
8704                last = snr;
8705                if at_320 && kbps == 320 {
8706                    assert!(snr >= 20.0, "5.1 at 320 kbps: {snr:.2} dB");
8707                }
8708                if ch == 1 {
8709                    assert!(snr >= 19.0, "mono at {kbps} kbps: {snr:.2} dB");
8710                }
8711                for (c, lv) in levels.iter().enumerate() {
8712                    assert!(
8713                        lv.abs() <= 0.3,
8714                        "{ch} ch at {kbps} kbps: channel {c} level {lv:+.2} dB"
8715                    );
8716                }
8717            }
8718        }
8719    }
8720
8721    /// The #129 repro (tones over independent noise, every element busy)
8722    /// keeps every channel within 0.5 dB from 128 to 320 kbps. Before the
8723    /// narrow-band SNR floor Ls drifted by +0.8 to +1.0 dB at 128-192 kbps.
8724    #[test]
8725    #[cfg_attr(miri, ignore = "too slow to interpret")]
8726    fn every_repro_channel_keeps_its_level_at_128_to_320() {
8727        let sr = 48_000u32;
8728        let pcm = busy_5_1(sr as usize * 3, sr);
8729        for kbps in [128, 192, 256, 320] {
8730            let (_, levels) = snr_levels(&pcm, 6, sr, kbps);
8731            for (c, lv) in levels.iter().enumerate() {
8732                assert!(
8733                    lv.abs() <= 0.5,
8734                    "{kbps} kbps: channel {c} level {lv:+.2} dB"
8735                );
8736            }
8737        }
8738    }
8739
8740    /// The raw access units average the target bitrate, within 1%, and no
8741    /// unit outgrows the decoder buffer (6144 bits a channel). On 2.1.1 the
8742    /// streams came out 3-13% short.
8743    #[test]
8744    #[cfg_attr(miri, ignore = "too slow to interpret")]
8745    fn the_stream_lands_on_its_bitrate() {
8746        let sr = 48_000u32;
8747        let n = sr as usize * 3;
8748        let five_one = busy_5_1(n, sr);
8749        let stereo: Vec<f32> = (0..n * 2).map(|i| five_one[(i / 2) * 6 + i % 2]).collect();
8750        let mono: Vec<f32> = (0..n).map(|i| five_one[i * 6 + 2]).collect();
8751        for (pcm, ch, kbps) in [(&mono, 1, 64), (&stereo, 2, 128), (&five_one, 6, 320)] {
8752            let pk = packets(pcm, ch, sr, kbps);
8753            let bits: usize = pk.iter().map(|p| p.data.len() * 8).sum();
8754            let rate = bits as f64 * f64::from(sr) / (pk.len() * FRAME_LEN) as f64;
8755            let err = rate / f64::from(kbps * 1000) - 1.0;
8756            assert!(
8757                err.abs() < 0.01,
8758                "{ch} ch at {kbps} kbps: {:+.2}%",
8759                err * 100.0
8760            );
8761            let most = pk.iter().map(|p| p.data.len() * 8).max().unwrap();
8762            assert!(most <= 6144 * ch, "{ch} ch: a {most}-bit unit");
8763        }
8764    }
8765}
8766
8767/// The low-rate campaign's tools: the section trellis, the frame-demand
8768/// allocation, the coding bandwidth, the high-passed transient detector and
8769/// the mask SMR.
8770#[cfg(test)]
8771mod lowrate {
8772    use super::*;
8773
8774    fn encode(pcm: &[f32], ch: u16, sr: u32, cfg: (AacEncoderConfig, AacTuning)) -> Vec<Vec<u8>> {
8775        let mut e = AacEncoder::with_tuning(cfg.0, cfg.1);
8776        e.push_pcm(pcm, ch, sr).unwrap();
8777        e.finish();
8778        let mut out = Vec::new();
8779        while let Ok(p) = e.next_packet() {
8780            out.push(p.data);
8781        }
8782        out
8783    }
8784
8785    /// Interleaved PCM of a packet list through this crate's decoder, and
8786    /// its channel count.
8787    fn decode(packets: &[Vec<u8>], sr: u32) -> (Vec<f32>, usize) {
8788        let mut dec = crate::decode::Decoder::new(sr);
8789        let mut out = Vec::new();
8790        let mut ch = 1;
8791        for p in packets {
8792            let a = dec.decode(p, None).expect("decode");
8793            ch = a.channels.max(1) as usize;
8794            out.extend_from_slice(&a.samples);
8795        }
8796        (out, ch)
8797    }
8798
8799    /// Music-like stereo: a harmonic tone with plucked attacks, a panned
8800    /// second voice, and broadband noise, so every tool has something to do.
8801    fn music(sr: u32, frames: usize) -> Vec<f32> {
8802        use std::f32::consts::PI;
8803        let n = frames * FRAME_LEN;
8804        let mut seed = 0x1234_5678u32;
8805        let mut noise = move || {
8806            seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
8807            (seed >> 8) as f32 / (1u32 << 24) as f32 - 0.5
8808        };
8809        let mut out = Vec::with_capacity(2 * n);
8810        for i in 0..n {
8811            let t = i as f32 / sr as f32;
8812            let k = i % (3 * FRAME_LEN);
8813            let env = (-(k as f32) / 900.0).exp();
8814            let mut a = 0.0;
8815            for h in 1..=8 {
8816                a += (0.3 / h as f32) * (2.0 * PI * 196.0 * h as f32 * t).sin();
8817            }
8818            let b = 0.2 * (2.0 * PI * 523.0 * t).sin();
8819            let nz = 0.05 * noise();
8820            out.push(a * env + 0.8 * b + nz);
8821            out.push(0.6 * a * env + 0.2 * b + nz);
8822        }
8823        out
8824    }
8825
8826    /// Reconstruction SNR; the decoded stream leads by the 1024-sample priming.
8827    fn snr_db(src: &[f32], dec: &[f32], ch: usize) -> f64 {
8828        let lag = FRAME_LEN * ch;
8829        let n = src.len().min(dec.len().saturating_sub(lag));
8830        let (mut s, mut e) = (0f64, 0f64);
8831        for i in 0..n {
8832            let (x, y) = (f64::from(src[i]), f64::from(dec[i + lag]));
8833            s += x * x;
8834            e += (x - y) * (x - y);
8835        }
8836        10.0 * (s / e.max(1e-30)).log10()
8837    }
8838
8839    /// The trellis is optimal: its choice costs no more than any assignment,
8840    /// checked by brute force over every assignment of small band sets.
8841    #[test]
8842    fn section_trellis_is_optimal() {
8843        let mut seed = 7u32;
8844        let mut rnd = move |m: u32| {
8845            seed = seed.wrapping_mul(1_103_515_245).wrapping_add(12_345);
8846            (seed >> 16) % m
8847        };
8848        let cost = |costs: &[[u32; 12]], cbs: &[u8], hdr: u32| -> u64 {
8849            let mut c = 0u64;
8850            for (b, &cb) in cbs.iter().enumerate() {
8851                if costs[b][cb as usize] == u32::MAX {
8852                    return u64::MAX;
8853                }
8854                c += u64::from(costs[b][cb as usize]);
8855                if b == 0 || cbs[b - 1] != cb {
8856                    c += u64::from(hdr);
8857                }
8858            }
8859            c
8860        };
8861        for _ in 0..40 {
8862            let n = 1 + rnd(4) as usize;
8863            let costs: Vec<[u32; 12]> = (0..n)
8864                .map(|_| {
8865                    let mut k = [u32::MAX; 12];
8866                    for x in k.iter_mut().skip(1) {
8867                        if rnd(3) != 0 {
8868                            *x = rnd(40);
8869                        }
8870                    }
8871                    k[11] = rnd(60); // the escape book always codes
8872                    if rnd(3) == 0 {
8873                        k[0] = 0;
8874                    }
8875                    k
8876                })
8877                .collect();
8878            let got = cost(&costs, &trellis_books(&costs, 9), 9);
8879            let mut best = u64::MAX;
8880            for code in 0..12usize.pow(n as u32) {
8881                let cbs: Vec<u8> = (0..n)
8882                    .map(|b| ((code / 12usize.pow(b as u32)) % 12) as u8)
8883                    .collect();
8884                best = best.min(cost(&costs, &cbs, 9));
8885            }
8886            assert_eq!(got, best, "trellis not optimal for {costs:?}");
8887        }
8888    }
8889
8890    /// The one-walk book pricing the trellis uses gives every book the bits
8891    /// the per-book search does, long and short, across peak magnitudes.
8892    #[test]
8893    fn band_book_costs_match_per_book_search() {
8894        let mut seed = 0x9e37_79b9_u64;
8895        let mut rnd = move |m: u64| {
8896            seed ^= seed << 13;
8897            seed ^= seed >> 7;
8898            seed ^= seed << 17;
8899            seed % m
8900        };
8901        for _ in 0..3000 {
8902            let width = [4usize, 8, 12, 16, 32][rnd(5) as usize];
8903            let (nwin, wlen) = if rnd(2) == 0 {
8904                (1, 1024)
8905            } else {
8906                (1 + rnd(4) as usize, 128)
8907            };
8908            let peak = [1i64, 2, 4, 7, 12, 15, 16, 40, 8191][rnd(9) as usize];
8909            let mut quant = vec![0i32; nwin * wlen];
8910            for w in 0..nwin {
8911                for i in 0..width {
8912                    if rnd(3) != 0 {
8913                        let m = rnd(peak as u64 + 1) as i32;
8914                        quant[w * wlen + 8 + i] = if rnd(2) == 0 { m } else { -m };
8915                    }
8916                }
8917            }
8918            let (s, e) = (8, 8 + width);
8919            if (0..nwin).all(|w| quant[w * wlen + s..w * wlen + e].iter().all(|&q| q == 0)) {
8920                continue;
8921            }
8922            assert_eq!(
8923                band_book_costs(&quant, s, e, 0, nwin, wlen),
8924                band_book_costs_ref(&quant, s, e, 0, nwin, wlen),
8925                "width {width}, nwin {nwin}, peak {peak}"
8926            );
8927        }
8928    }
8929
8930    /// A zero band carried in a section takes the previous coded band's
8931    /// scalefactor (a zero delta); one before any coded band, the first's.
8932    #[test]
8933    fn carried_zero_bands_send_a_zero_delta() {
8934        let cbs = [5u8, 5, 0, 7, 7, 13, 7];
8935        let sf = [120, 99, 140, 110, 30, 40, 112];
8936        let zero = [true, false, true, false, true, false, false];
8937        let got = zero_band_sf(&cbs, &sf, |i| zero[i]);
8938        assert_eq!(got, vec![99, 99, 140, 110, 110, 40, 112]);
8939    }
8940
8941    /// Frame-demand weights keep the segment mean, honour their bounds, and
8942    /// are flat at strength 0.
8943    #[test]
8944    fn demand_weights_preserve_the_segment_rate() {
8945        let pe: Vec<f64> = (0..32)
8946            .map(|i| {
8947                if i % 7 == 0 {
8948                    9000.0
8949                } else {
8950                    100.0 + 30.0 * f64::from(i)
8951                }
8952            })
8953            .collect();
8954        for alpha in [0.0, 0.5, 1.0, 2.0] {
8955            let w = frame_demand_weights(&pe, alpha);
8956            let m = w.iter().sum::<f64>() / w.len() as f64;
8957            assert!((m - 1.0).abs() < 1e-9, "alpha {alpha}: mean {m}");
8958            if alpha == 0.0 {
8959                assert!(w.iter().all(|&x| x == 1.0));
8960            }
8961            assert!(
8962                w.iter().all(|&x| x > 0.2 && x < 3.0),
8963                "alpha {alpha}: {w:?}"
8964            );
8965        }
8966        assert_eq!(frame_demand_weights(&[0.0; 4], 1.0), vec![1.0; 4]);
8967    }
8968
8969    /// The automatic cutoff: 17 kHz under 192 kbps and 128 kbps a channel,
8970    /// 20 kHz from there to under 160 kbps a channel, mono and stereo only,
8971    /// never at or above Nyquist; the cutoff falls on a band edge.
8972    #[test]
8973    fn bandwidth_table_and_cutoff() {
8974        assert_eq!(auto_bandwidth_hz(64_000, 1, 44_100), Some(17_000));
8975        assert_eq!(auto_bandwidth_hz(128_000, 1, 44_100), Some(17_000));
8976        assert_eq!(auto_bandwidth_hz(144_000, 1, 48_000), Some(20_000));
8977        assert_eq!(auto_bandwidth_hz(160_000, 1, 44_100), None);
8978        assert_eq!(auto_bandwidth_hz(160_000, 2, 44_100), Some(17_000));
8979        assert_eq!(auto_bandwidth_hz(192_000, 2, 44_100), Some(20_000));
8980        assert_eq!(auto_bandwidth_hz(256_000, 2, 48_000), Some(20_000));
8981        assert_eq!(auto_bandwidth_hz(318_000, 2, 48_000), Some(20_000));
8982        assert_eq!(auto_bandwidth_hz(320_000, 2, 48_000), None);
8983        assert_eq!(auto_bandwidth_hz(512_000, 2, 48_000), None);
8984        assert_eq!(auto_bandwidth_hz(640_000, 6, 48_000), None);
8985        assert_eq!(auto_bandwidth_hz(256_000, 2, 32_000), None);
8986        assert_eq!(auto_bandwidth_hz(320_000, 6, 48_000), None);
8987        assert_eq!(auto_bandwidth_hz(128_000, 6, 48_000), None);
8988        assert_eq!(auto_bandwidth_hz(64_000, 2, 32_000), None);
8989        let swb = swb_offsets(true, crate::sf_index_for_rate(44_100).unwrap());
8990        let cut = cutoff_line(Some(17_000), 44_100, swb, FRAME_LEN);
8991        assert!(swb.iter().any(|&s| usize::from(s) == cut));
8992        assert!(cut as f64 * 22_050.0 / 1024.0 >= 17_000.0);
8993        assert_eq!(cutoff_line(None, 44_100, swb, FRAME_LEN), usize::MAX);
8994    }
8995
8996    /// Every tool on: decodable at the right length, finite, a faithful copy,
8997    /// on rate, stereo and mono, whole-clip and streaming.
8998    #[test]
8999    #[cfg_attr(miri, ignore = "too slow to interpret")]
9000    fn every_tool_round_trips() {
9001        let sr = 44_100u32;
9002        let st = music(sr, 40);
9003        let mono: Vec<f32> = st.iter().step_by(2).copied().collect();
9004        let cfg = AacEncoderConfig {
9005            bitrate_bps: 64_000,
9006            ..Default::default()
9007        };
9008        let tools = AacTuning {
9009            bandwidth: Bandwidth::Hz(17_000),
9010            ..AacTuning::default()
9011        };
9012        let all = (cfg, tools);
9013        // The 2.1.2 encoder: every tool of this campaign off.
9014        let plain = (cfg, AacTuning::legacy());
9015        for (pcm, ch) in [(&st, 2u16), (&mono, 1)] {
9016            let base = encode(pcm, ch, sr, plain);
9017            let on = encode(pcm, ch, sr, all);
9018            assert_ne!(base, on, "{ch} ch: the tools must change the stream");
9019            let (db, _) = decode(&base, sr);
9020            let (d, dch) = decode(&on, sr);
9021            assert_eq!(dch, usize::from(ch));
9022            assert_eq!(d.len(), db.len(), "{ch} ch: length");
9023            assert!(d.iter().all(|v| v.is_finite()));
9024            let (s0, s1) = (snr_db(pcm, &db, dch), snr_db(pcm, &d, dch));
9025            assert!(
9026                s1 > 3.0 && s1 > s0 - 3.0,
9027                "{ch} ch: snr {s1:.1} dB vs {s0:.1} dB"
9028            );
9029            let bits: usize = on.iter().map(|p| p.len() * 8).sum();
9030            let rate = bits as f64 * f64::from(sr) / (on.len() * FRAME_LEN) as f64;
9031            assert!(
9032                (rate / 64_000.0 - 1.0).abs() < 0.02,
9033                "{ch} ch: rate {rate:.0}"
9034            );
9035            // Streaming: frame demand needs the whole segment and falls back
9036            // to the constant-rate share; everything else applies.
9037            let mut e = AacEncoder::with_tuning(all.0, all.1);
9038            e.set_streaming(true);
9039            e.push_pcm(pcm, ch, sr).unwrap();
9040            e.finish();
9041            let mut sp = Vec::new();
9042            while let Ok(p) = e.next_packet() {
9043                sp.push(p.data);
9044            }
9045            let (ds, _) = decode(&sp, sr);
9046            assert_eq!(ds.len(), db.len());
9047            assert!(snr_db(pcm, &ds, dch) > 3.0);
9048        }
9049    }
9050}