forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB7f487c1Tahinli3 months ago659 commits

encode.rs4940 lines, 196.2 KiBHistoryRawDownload
1//! In-house **AAC-LC encoder** (see `docs/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/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
24#![allow(dead_code)]
25
26use crate::codebook::{Codebook, CODEBOOKS, INTENSITY_HCB, INTENSITY_HCB2, NOISE_HCB};
27use crate::ics::{IcsInfo, WindowSequence};
28use crate::swb::swb_offsets;
29use crate::tables::spectral_book;
30use crate::{AdtsHeader, AudioSpecificConfig, Error, Result};
31use std::collections::{HashMap, VecDeque};
32use std::sync::{Arc, Mutex, OnceLock};
33
34// ---------------------------------------------------------------------------
35// Bit writer — MSB-first, the mirror of the decoder's `BitReader`.
36// ---------------------------------------------------------------------------
37pub struct BitWriter {
38 buf: Vec<u8>,
39 cur: u8,
40 nbits: u8,
41}
42
43impl BitWriter {
44 pub fn new() -> Self {
45 BitWriter {
46 buf: Vec::new(),
47 cur: 0,
48 nbits: 0,
49 }
50 }
51
52 /// Append the low `n` bits of `val`, most-significant bit first.
53 pub fn write(&mut self, val: u32, n: u32) {
54 for i in (0..n).rev() {
55 self.cur = (self.cur << 1) | ((val >> i) & 1) as u8;
56 self.nbits += 1;
57 if self.nbits == 8 {
58 self.buf.push(self.cur);
59 self.cur = 0;
60 self.nbits = 0;
61 }
62 }
63 }
64
65 pub fn write_bool(&mut self, b: bool) {
66 self.write(b as u32, 1);
67 }
68
69 /// Total bits written so far.
70 pub fn bit_len(&self) -> usize {
71 self.buf.len() * 8 + self.nbits as usize
72 }
73
74 /// Pad to a byte boundary with zero bits and return the bytes.
75 pub fn into_bytes(mut self) -> Vec<u8> {
76 if self.nbits != 0 {
77 self.cur <<= 8 - self.nbits;
78 self.buf.push(self.cur);
79 }
80 self.buf
81 }
82}
83
84impl Default for BitWriter {
85 fn default() -> Self {
86 Self::new()
87 }
88}
89
90// ---------------------------------------------------------------------------
91// Spectral codebook encoding — the inverse of `codebook::apply_index`.
92// ---------------------------------------------------------------------------
93
94/// Pack a `dim`-tuple of quantized coefficients into codebook `cb`'s base-`modulo`
95/// Huffman index, or None if the tuple isn't representable by that codebook.
96fn tuple_index(cb: &Codebook, tuple: &[i32]) -> Option<u32> {
97 let dim = cb.dim as usize;
98 let lav = cb.lav as u32;
99 let modulo = if cb.unsigned { lav + 1 } else { 2 * lav + 1 };
100 let mut index = 0u32;
101 for &c in &tuple[..dim] {
102 let mag = c.unsigned_abs();
103 let digit = if cb.unsigned {
104 if cb.esc {
105 mag.min(lav) // book 11: a magnitude ≥ lav clamps to lav and escapes
106 } else if mag <= lav {
107 mag
108 } else {
109 return None;
110 }
111 } else if mag <= lav {
112 (c + lav as i32) as u32
113 } else {
114 return None;
115 };
116 index = index * modulo + digit;
117 }
118 Some(index)
119}
120
121/// Bits to code `tuple` with codebook `cb_num`, or None if unrepresentable.
122pub fn spectral_bits(cb_num: usize, tuple: &[i32]) -> Option<usize> {
123 let cb = &CODEBOOKS[cb_num];
124 let idx = tuple_index(cb, tuple)?;
125 let (_, len) = spectral_book(cb_num as u8).code(idx as usize);
126 let dim = cb.dim as usize;
127 let mut bits = len as usize;
128 if cb.unsigned {
129 bits += tuple[..dim].iter().filter(|&&c| c != 0).count(); // one sign bit each
130 }
131 if cb.esc {
132 for &c in &tuple[..dim] {
133 if c.unsigned_abs() >= cb.lav as u32 {
134 bits += escape_bits(c.unsigned_abs());
135 }
136 }
137 }
138 Some(bits)
139}
140
141/// Emit `tuple` with codebook `cb_num`: codeword, then sign bits (unsigned books),
142/// then escape sequences (book 11). Caller ensures `spectral_bits` is Some.
143pub fn spectral_emit(cb_num: usize, tuple: &[i32], w: &mut BitWriter) {
144 let cb = &CODEBOOKS[cb_num];
145 let dim = cb.dim as usize;
146 let idx = tuple_index(cb, tuple).expect("representable tuple");
147 let (code, len) = spectral_book(cb_num as u8).code(idx as usize);
148 w.write(code, len as u32);
149 if cb.unsigned {
150 for &c in &tuple[..dim] {
151 if c != 0 {
152 w.write_bool(c < 0);
153 }
154 }
155 }
156 if cb.esc {
157 for &c in &tuple[..dim] {
158 if c.unsigned_abs() >= cb.lav as u32 {
159 emit_escape(c.unsigned_abs(), w);
160 }
161 }
162 }
163}
164
165/// Escape length for magnitude `m` (≥ 16): `2N+5` bits, `2^(N+4) ≤ m < 2^(N+5)`.
166fn escape_bits(m: u32) -> usize {
167 let n = (31 - m.leading_zeros()) - 4;
168 2 * n as usize + 5
169}
170
171/// Escape sequence (ISO §4.6.3.3): N leading 1-bits, a 0, then N+4 bits of
172/// `m - 2^(N+4)`.
173fn emit_escape(m: u32, w: &mut BitWriter) {
174 let n = (31 - m.leading_zeros()) - 4;
175 for _ in 0..n {
176 w.write_bool(true);
177 }
178 w.write_bool(false);
179 let bits = n + 4;
180 w.write(m - (1 << bits), bits);
181}
182
183// ---------------------------------------------------------------------------
184// Header / config serializers — inverses of the decoder's parsers.
185// ---------------------------------------------------------------------------
186
187/// The `AudioSpecificConfig` bytes for an AAC-LC stream — the MP4 `esds`
188/// DecoderSpecificInfo the muxer needs (2 bytes for standard rates).
189pub fn audio_specific_config_bytes(sample_rate: u32, channels: u16) -> Vec<u8> {
190 write_audio_specific_config(&AudioSpecificConfig {
191 object_type: 2, // AAC-LC
192 sample_rate,
193 channels,
194 })
195}
196
197/// Serialize an `AudioSpecificConfig` (ISO §1.6.2.1) — the `esds`/`stsd` config
198/// bytes the MP4 muxer needs. Inverse of `parse_audio_specific_config`.
199pub fn write_audio_specific_config(cfg: &AudioSpecificConfig) -> Vec<u8> {
200 let mut w = BitWriter::new();
201 if cfg.object_type >= 31 {
202 w.write(31, 5);
203 w.write((cfg.object_type - 32) as u32, 6);
204 } else {
205 w.write(cfg.object_type as u32, 5);
206 }
207 match crate::sf_index_for_rate(cfg.sample_rate) {
208 Some(i) => w.write(i as u32, 4),
209 None => {
210 w.write(0x0F, 4);
211 w.write(cfg.sample_rate, 24);
212 }
213 }
214 w.write(cfg.channels as u32, 4);
215 w.into_bytes()
216}
217
218/// Serialize a 7-byte ADTS frame header (no CRC) — inverse of `parse_adts`.
219/// `hdr.frame_length` must include this 7-byte header.
220pub fn write_adts_header(hdr: &AdtsHeader) -> Vec<u8> {
221 let sf = crate::sf_index_for_rate(hdr.sample_rate).expect("standard rate for ADTS");
222 let mut w = BitWriter::new();
223 w.write(0xFFF, 12); // syncword
224 w.write(0, 1); // MPEG-4
225 w.write(0, 2); // layer (00)
226 w.write_bool(true); // protection_absent → 7-byte header, no CRC
227 w.write((hdr.object_type - 1) as u32, 2); // profile
228 w.write(sf as u32, 4);
229 w.write(0, 1); // private
230 w.write(hdr.channels as u32, 3); // channel config
231 w.write(0, 4); // orig/home/copyright id+start
232 w.write(hdr.frame_length as u32, 13);
233 w.write(0x7FF, 11); // buffer fullness (VBR marker)
234 w.write(0, 2); // num_raw_data_blocks - 1
235 w.into_bytes()
236}
237
238/// Serialize `ics_info` for AAC-LC — inverse of `parse_ics_info`.
239pub fn encode_ics_info(w: &mut BitWriter, info: &IcsInfo) {
240 w.write(0, 1); // ics_reserved
241 w.write(info.window_sequence.to_bits(), 2);
242 w.write_bool(info.window_shape_kbd);
243 if info.window_sequence.is_short() {
244 w.write(info.max_sfb as u32, 4);
245 w.write(grouping_bits(&info.window_group_length), 7);
246 } else {
247 w.write(info.max_sfb as u32, 6);
248 w.write(0, 1); // predictor_data_present (AAC-LC = 0)
249 }
250}
251
252/// The 7 `scale_factor_grouping` bits from window-group lengths (inverse of the
253/// parser's grouping walk): the bit for window i+1 is 1 if it continues the
254/// current group, 0 if it starts a new one.
255fn grouping_bits(group_lengths: &[u8]) -> u32 {
256 let mut is_start = [false; 8];
257 let mut w = 0usize;
258 for &len in group_lengths {
259 if w < 8 {
260 is_start[w] = true;
261 }
262 w += len as usize;
263 }
264 let mut sfg = 0u32;
265 for i in 0..7 {
266 if !is_start[i + 1] {
267 sfg |= 1 << (6 - i);
268 }
269 }
270 sfg
271}
272
273// ---------------------------------------------------------------------------
274// Filterbank — forward long-block MDCT (inverse of the decoder's synthesis).
275// ---------------------------------------------------------------------------
276pub const FRAME_LEN: usize = 1024;
277pub const LONG_N: usize = 2048;
278const SHORT_N: usize = 256;
279const SHORT_HALF: usize = 128;
280/// 1 / OUTPUT_NORM: the decoder scales its output by 1/32768, so the encoder
281/// scales the spectrum up by 32768 to land in the AAC coefficient domain.
282const SPEC_SCALE: f32 = 32768.0;
283
284/// Forward long-block filterbank: window the overlapping 2048 input samples
285/// (previous frame's 1024 ++ current 1024) and forward-MDCT to 1024 coefficients,
286/// scaled so the decoder's `imdct · window · (1/32768) + overlap-add` reconstructs
287/// the input (TDAC). `win` is the 2048-length window (sine or KBD).
288pub fn analyze_long(prev: &[f32; FRAME_LEN], cur: &[f32; FRAME_LEN], win: &[f32]) -> Vec<f32> {
289 let mut windowed = vec![0f32; LONG_N];
290 for n in 0..FRAME_LEN {
291 windowed[n] = prev[n] * win[n] * SPEC_SCALE;
292 windowed[FRAME_LEN + n] = cur[n] * win[FRAME_LEN + n] * SPEC_SCALE;
293 }
294 crate::dsp::mdct_fast(&windowed)
295}
296
297/// Forward short-block filterbank: eight 256-sample windows (128-hop) tiled across
298/// [448, 1600) of the prev++cur 2048 buffer, each windowed + MDCT'd to 128 coeffs,
299/// laid out window-major (the exact inverse of the decoder's `short_frame`). The
300/// uncovered [0,448)/[1600,2048) regions are bridged by the LongStart/LongStop
301/// neighbours — which is why EightShort must sit between transition blocks.
302pub fn analyze_short(prev: &[f32; FRAME_LEN], cur: &[f32; FRAME_LEN], sw: &[f32]) -> Vec<f32> {
303 let mut buf = [0f32; LONG_N];
304 buf[..FRAME_LEN].copy_from_slice(prev);
305 buf[FRAME_LEN..].copy_from_slice(cur);
306 let mut spec = vec![0f32; FRAME_LEN];
307 for w in 0..8 {
308 let off = 448 + w * SHORT_HALF;
309 let mut windowed = [0f32; SHORT_N];
310 for (n, s) in windowed.iter_mut().enumerate() {
311 *s = buf[off + n] * sw[n] * SPEC_SCALE;
312 }
313 let coeffs = crate::dsp::mdct_fast(&windowed);
314 spec[w * SHORT_HALF..(w + 1) * SHORT_HALF].copy_from_slice(&coeffs);
315 }
316 spec
317}
318
319/// The 2048-sample analysis window for a long or transition block — the exact
320/// encode-side twin of the decoder's `long_window`.
321///
322/// **The left half follows the PREVIOUS block's shape, the right half the
323/// current's** (`prev_kbd` / `cur_kbd`), because that is what the decoder does:
324/// each overlap region must be windowed identically on both sides or TDAC fails
325/// and the overlap-add leaves audible seams. LongStart/LongStop taper one side to
326/// a short window so the sequence stays TDAC-exact.
327///
328/// The decoder seeds `prev_kbd = false` for the first frame of a stream
329/// (`decode.rs`), so the encoder must too.
330#[allow(clippy::too_many_arguments)]
331fn long_window(
332 seq: WindowSequence,
333 prev_kbd: bool,
334 cur_kbd: bool,
335 sine_l: &[f32],
336 kbd_l: &[f32],
337 sine_s: &[f32],
338 kbd_s: &[f32],
339) -> Vec<f32> {
340 let long_prev = if prev_kbd { kbd_l } else { sine_l };
341 let long_cur = if cur_kbd { kbd_l } else { sine_l };
342 let short_prev = if prev_kbd { kbd_s } else { sine_s };
343 let short_cur = if cur_kbd { kbd_s } else { sine_s };
344
345 let mut w = vec![0f32; LONG_N];
346 if seq == WindowSequence::LongStop {
347 w[448..448 + SHORT_HALF].copy_from_slice(&short_prev[..SHORT_HALF]);
348 for s in w.iter_mut().take(FRAME_LEN).skip(576) {
349 *s = 1.0;
350 }
351 } else {
352 w[..FRAME_LEN].copy_from_slice(&long_prev[..FRAME_LEN]);
353 }
354 if seq == WindowSequence::LongStart {
355 for s in w.iter_mut().take(FRAME_LEN + 448).skip(FRAME_LEN) {
356 *s = 1.0;
357 }
358 w[FRAME_LEN + 448..FRAME_LEN + 448 + SHORT_HALF].copy_from_slice(&short_cur[SHORT_HALF..]);
359 } else {
360 w[FRAME_LEN..].copy_from_slice(&long_cur[FRAME_LEN..]);
361 }
362 w
363}
364
365/// **The Rung 0 gate signal**: order-2 LPC prediction gain over the frame's time
366/// samples — a cheap tonality proxy.
367///
368/// Chosen over the spectral flatness measure the lab validates because SFM needs
369/// a spectrum, and the window shape must be decided *before* the spectrum exists
370/// (the shape determines the window that produces it). Computing a probe MDCT per
371/// frame just to pick a window would roughly double filterbank cost for a
372/// small-by-design win — dominated on `bits-per-op` grounds before it started.
373///
374/// This is O(3n) multiply-adds and needs no transform. Tonal signals are strongly
375/// predictable from two past samples; noise is not. Validated against the
376/// per-class truth table in `lab::signals` before being wired here.
377///
378/// Returns `R[0] / E₂ ≥ 1`.
379pub(crate) fn time_tonality(x: &[f32]) -> f32 {
380 let n = x.len();
381 if n < 8 {
382 return 1.0;
383 }
384 let mut r = [0f64; 3];
385 for (lag, slot) in r.iter_mut().enumerate() {
386 let mut acc = 0f64;
387 for i in 0..n - lag {
388 acc += x[i] as f64 * x[i + lag] as f64;
389 }
390 *slot = acc;
391 }
392 if r[0] <= 1e-12 {
393 return 1.0;
394 }
395 let r0 = r[0] * 1.0001; // white-noise correction — keeps Levinson stable
396 let k1 = r[1] / r0;
397 let e1 = r0 * (1.0 - k1 * k1);
398 if e1 <= 1e-12 {
399 return 1.0;
400 }
401 let k2 = (r[2] - k1 * r[1]) / e1;
402 let e2 = e1 * (1.0 - k2 * k2);
403 ((r0 / e2.max(1e-12)) as f32).max(1.0)
404}
405
406// ---------------------------------------------------------------------------
407// Psychoacoustic model (brick 4) — per-SFB masking thresholds drive per-band
408// scalefactor allocation, so quantization noise is shaped to the audible floor.
409// ---------------------------------------------------------------------------
410
411/// Traunmüller's Hz→Bark (critical-band rate).
412fn hz_to_bark(f: f64) -> f64 {
413 let f = f.max(1.0);
414 26.81 * f / (1960.0 + f) - 0.53
415}
416
417/// Spreading of a masker's energy to a maskee `dz` Bark away (`dz` = maskee −
418/// masker): steep ~27 dB/Bark toward lower bands, gentle ~10 dB/Bark upward.
419fn spreading(dz: f64) -> f64 {
420 let slope_db = if dz >= 0.0 { -10.0 } else { -27.0 };
421 10f64.powf(slope_db * dz.abs() / 10.0)
422}
423
424/// The Bark-spreading matrix `S[i·n+j] = spreading(bark[i]-bark[j])` for one band
425/// geometry — fixed per (sample_rate, band count), so it's built once and cached,
426/// turning each frame's masking into a matrix-vector product (no runtime powf).
427/// `n_coeffs` is the number of spectral coefficients the band table spans — 1024
428/// for a long block, 128 for one short window. It sets the coefficient→Hz
429/// mapping, so passing the long value for a short block would place every band
430/// eight octaves too low and spread the mask against the wrong neighbours.
431fn spreading_matrix(swb: &[u16], sample_rate: u32, n_coeffs: usize) -> Arc<Vec<f64>> {
432 type Cache = Mutex<HashMap<(u32, usize, usize), Arc<Vec<f64>>>>;
433 static CACHE: OnceLock<Cache> = OnceLock::new();
434 let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new()));
435 let key = (sample_rate, swb.len(), n_coeffs);
436 let mut c = cache.lock().unwrap();
437 if let Some(m) = c.get(&key) {
438 return m.clone();
439 }
440 let num_swb = swb.len() - 1;
441 let bark: Vec<f64> = (0..num_swb)
442 .map(|sfb| {
443 let center = (swb[sfb] as f64 + swb[sfb + 1] as f64) / 2.0;
444 // n_coeffs coefficients span 0..sr/2.
445 hz_to_bark(center * sample_rate as f64 * 0.5 / n_coeffs as f64)
446 })
447 .collect();
448 let mut mat = vec![0f64; num_swb * num_swb];
449 for i in 0..num_swb {
450 for j in 0..num_swb {
451 mat[i * num_swb + j] = spreading(bark[i] - bark[j]);
452 }
453 }
454 let arc = Arc::new(mat);
455 c.insert(key, arc.clone());
456 arc
457}
458
459/// Per-SFB masking threshold (energy units): spread the band energies on the
460/// Bark scale, then sit the mask a fixed ratio below the spread signal.
461///
462/// `pub(crate)` so [`crate::lab::quality`] can score coding noise against the
463/// encoder's own mask (the NMR metric), in the same band geometry and energy
464/// domain the encoder allocates in.
465pub(crate) fn masking_thresholds(spec: &[f32], swb: &[u16], sample_rate: u32) -> Vec<f64> {
466 let num_swb = swb.len() - 1;
467 let mut energy = vec![0.0f64; num_swb];
468 for sfb in 0..num_swb {
469 let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
470 energy[sfb] = spec[s..e].iter().map(|&x| (x as f64).powi(2)).sum::<f64>() + 1e-3;
471 }
472 masking_from_energy(&energy, swb, sample_rate, FRAME_LEN, None)
473}
474
475/// The default signal-to-mask ratio: the mask sits 18 dB below the spread signal,
476/// for every band and every kind of content.
477///
478/// **Arm A2** replaces this constant with a function of tonality. It is census
479/// category 4 — a knob whose own doc-comment names the physical signal it tracks,
480/// shipping as a constant. Kept as the byte-identical fallback.
481const SMR_FLAT: f64 = 0.0158; // 10^(-18/10)
482
483/// The psychoacoustic arms in flight, threaded down to every coding path.
484///
485/// A struct rather than loose bools because these arms compose: A1 decides
486/// *whether* short blocks get a mask at all, A2 decides *what* that mask is, and
487/// both must reach the CPE path and the SCE path identically or the two paths
488/// silently encode to different models — the inconsistency great-gate's P0.9
489/// hygiene batch exists to prevent.
490///
491/// `PsyCfg::default()` is all-off = the encoder exactly as it shipped.
492#[derive(Debug, Clone, Copy, Default)]
493pub(crate) struct PsyCfg {
494 /// Arm A1 — psy model on short blocks (else flat scalefactors).
495 pub short_block_psy: bool,
496 /// Arm A2 — tonality-adaptive SMR (else flat 18 dB).
497 pub tonality_smr: bool,
498 /// Arm A3 — emit TNS on long blocks.
499 pub tns: bool,
500 /// Arm A6 — Perceptual Noise Substitution.
501 pub pns: bool,
502 /// Arm A7 — intensity stereo.
503 pub intensity: bool,
504 /// Arm A13 — demand-proportional stereo bit split.
505 pub stereo_bit_split: bool,
506}
507
508/// Per-band masking threshold from precomputed band energies.
509///
510/// Split out from [`masking_thresholds`] so short blocks (whose band energies are
511/// summed across the eight windows of a group) and long blocks share one masking
512/// model — great-gate P1: consolidate duplicated probe skeletons into one path,
513/// or a fit spanning both learns the inconsistency rather than the content.
514///
515/// `tonality` is **arm A2**: `None` uses the flat 18 dB [`SMR_FLAT`] (the shipped
516/// behavior, byte-identical); `Some(t)` interpolates the classic tonal/noise
517/// masker offsets per band.
518fn masking_from_energy(
519 energy: &[f64],
520 swb: &[u16],
521 sample_rate: u32,
522 n_coeffs: usize,
523 tonality: Option<&[f32]>,
524) -> Vec<f64> {
525 let num_swb = swb.len() - 1;
526 let mat = spreading_matrix(swb, sample_rate, n_coeffs);
527 (0..num_swb)
528 .map(|i| {
529 let row = &mat[i * num_swb..(i + 1) * num_swb];
530 let spread: f64 = (0..num_swb).map(|j| energy[j] * row[j]).sum();
531 let smr = match tonality {
532 None => SMR_FLAT,
533 Some(t) => {
534 let center = (swb[i] as f64 + swb[i + 1] as f64) / 2.0;
535 let bark = hz_to_bark(center * sample_rate as f64 * 0.5 / n_coeffs as f64);
536 smr_for(t[i] as f64, bark)
537 }
538 };
539 spread * smr
540 })
541 .collect()
542}
543
544/// **Arm A2.** Signal-to-mask ratio as a function of band tonality and Bark.
545///
546/// The classic asymmetry: a *tonal* masker hides noise poorly, so the mask must
547/// sit far below it (≈ 14.5 + bark dB); a *noise-like* masker hides noise well
548/// (≈ 5.5 dB). Interpolating on the tonality index is the standard MPEG form.
549///
550/// Today's encoder applies 18 dB to everything, so a pure tone and band-limited
551/// noise at equal energy get identical treatment — which is what this replaces.
552///
553/// Returned as a linear energy ratio (`10^(−dB/10)`), matching [`SMR_FLAT`].
554///
555/// # The noise end is 5.5 dB — and pinning it to 18 dB was measured and REFUTED
556///
557/// The obvious-looking "safety" tweak is to pin the noise end to the shipped flat
558/// 18 dB, so arm A2 can only ever give a band *more* protection than today and
559/// never less. Measured on the corpus, that made things **worse**, not safer:
560///
561/// | noise end | mean Δaudible% | worst class |
562/// |---|---|---|
563/// | 5.5 dB (textbook) | **−0.312** | +0.720 |
564/// | 18.0 dB (pinned) | −0.006 | **+2.185** |
565///
566/// The reason is that an SMR pair is a **bit-allocation balance, not two
567/// independent protections**. Raising the tonal end buys precision only because
568/// lowering the noise end frees the bits to pay for it. Pin the noise end and the
569/// tonal end becomes pure extra demand against a fixed budget — the rate loop
570/// answers by lifting the global base, and *every* band gets coarser. The
571/// "conservative" variant regressed three times as hard as the one it was meant
572/// to protect against.
573///
574/// Keep the textbook pair. A2's remaining per-class failures are a **dispatch**
575/// problem (route the arm by content class), not a constant to retune.
576const SMR_NOISE_DB: f64 = 5.5;
577fn smr_for(tonality: f64, bark: f64) -> f64 {
578 let t = tonality.clamp(0.0, 1.0);
579 let db = t * (14.5 + bark) + (1.0 - t) * SMR_NOISE_DB;
580 // Clamp to a sane band: below ~5 dB the mask stops protecting anything, and
581 // above ~30 dB the rate loop is asked for precision no bitrate can buy.
582 let db = db.clamp(5.0, 30.0);
583 10f64.powf(-db / 10.0)
584}
585
586/// Per-SFB scalefactor offsets (relative to a common base the rate loop sets):
587/// higher where masking is generous, lower where noise would be audible. From
588/// `noise ∝ 2^(0.375·sf)·Σ√|X|`, the sf hitting `noise = threshold` is
589/// `log2(threshold/Σ√|X|)/0.375`; we normalize + clamp so deltas stay codeable.
590/// Per-SFB tonality index in `[0, 1]` from the spectral flatness measure — **arm
591/// A2's signal**. 0 = noise-like, 1 = pure tone.
592///
593/// `SFM = geometric_mean(|X|²) / arithmetic_mean(|X|²)`, in dB, through the
594/// classic `min(SFM_dB / −60, 1)`.
595pub(crate) fn band_tonality(spec: &[f32], swb: &[u16], nwin: usize, wlen: usize) -> Vec<f32> {
596 let n = swb.len() - 1;
597 let mut out = vec![0f32; n];
598 for b in 0..n {
599 let (s, e) = (swb[b] as usize, swb[b + 1] as usize);
600 let (mut log_sum, mut lin_sum, mut cnt) = (0f64, 0f64, 0usize);
601 for w in 0..nwin {
602 let base = w * wlen;
603 for k in s..e {
604 let Some(&x) = spec.get(base + k) else { continue };
605 // Floored well below any audible coefficient so a single exact
606 // zero cannot drag the geometric mean to 0 and fake a pure tone.
607 let p = ((x as f64) * (x as f64)).max(1e-10);
608 log_sum += p.ln();
609 lin_sum += p;
610 cnt += 1;
611 }
612 }
613 if cnt == 0 {
614 continue;
615 }
616 let gm = (log_sum / cnt as f64).exp();
617 let am = lin_sum / cnt as f64;
618 let sfm_db = 10.0 * (gm / am.max(1e-30)).log10();
619 out[b] = ((sfm_db / -60.0) as f32).clamp(0.0, 1.0);
620 }
621 out
622}
623
624fn perceptual_offsets(
625 spec: &[f32],
626 swb: &[u16],
627 sample_rate: u32,
628 tonality_smr: bool,
629) -> Vec<i32> {
630 let num_swb = swb.len() - 1;
631 let mut energy = vec![0.0f64; num_swb];
632 for sfb in 0..num_swb {
633 let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
634 energy[sfb] = spec[s..e].iter().map(|&x| (x as f64).powi(2)).sum::<f64>() + 1e-3;
635 }
636 let ton = tonality_smr.then(|| band_tonality(spec, swb, 1, FRAME_LEN));
637 let thr = masking_from_energy(&energy, swb, sample_rate, FRAME_LEN, ton.as_deref());
638
639 let mut raw = vec![0.0f64; num_swb];
640 for sfb in 0..num_swb {
641 let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
642 energy[sfb] = spec[s..e].iter().map(|&x| (x as f64).powi(2)).sum();
643 let noise_scale: f64 = spec[s..e]
644 .iter()
645 .map(|&x| (x.abs() as f64).sqrt())
646 .sum::<f64>()
647 + 1e-6;
648 raw[sfb] = (thr[sfb] / noise_scale).log2() / 0.375;
649 }
650 // Center on the energy-bearing bands — empty bands have huge `thr/noise_scale`
651 // (they quantize to ZERO anyway) and would otherwise skew a plain mean.
652 let etot: f64 = energy.iter().sum::<f64>() + 1e-9;
653 let center: f64 = (0..num_swb).map(|i| raw[i] * energy[i]).sum::<f64>() / etot;
654 raw.iter()
655 .map(|&r| ((r - center).round() as i32).clamp(-60, 60))
656 .collect()
657}
658
659// ---------------------------------------------------------------------------
660// Quantization + coding — brick 4: per-band scalefactors (psy-driven), cheapest
661// codebook per band, rate loop over the common base, raw_data_block assembly.
662// ---------------------------------------------------------------------------
663
664/// The Rung 0 gate's transient-veto threshold, as a percentile of the clip's own
665/// frame-attack distribution. Frames above it always take the sine window.
666///
667/// PROVISIONAL. 0.75 is a placeholder pending a calculator fit; it is set high
668/// (veto only the top quartile) so the veto is conservative — it gives up KBD on
669/// some stationary frames rather than risk smearing an onset.
670const SHAPE_ATTACK_VETO_PCT: f32 = 0.75;
671
672/// Arm A13's routing threshold: how correlated a channel pair must be before the
673/// joint rate loop replaces the even per-channel split. Sits in the measured gap
674/// between wide content (0.25, where joint loses) and real stereo music
675/// (0.47-0.84, where it wins).
676const JOINT_STEREO_MIN_CORR: f32 = 0.35;
677
678/// Spectral correlation of a channel pair, `|<L,R>| / sqrt(<L,L><R,R>)`.
679/// 1 = identical, 0 = orthogonal. O(n) over the spectra the caller already has.
680fn pair_correlation(l: &[f32], r: &[f32]) -> f32 {
681 let n = l.len().min(r.len());
682 let (mut dot, mut el, mut er) = (0f64, 0f64, 0f64);
683 for i in 0..n {
684 let (a, b) = (l[i] as f64, r[i] as f64);
685 dot += a * b;
686 el += a * a;
687 er += b * b;
688 }
689 if el <= 1e-9 || er <= 1e-9 {
690 return 1.0; // a silent channel is trivially "agreeable"
691 }
692 (dot.abs() / (el.sqrt() * er.sqrt())) as f32
693}
694
695const ID_SCE: u32 = 0;
696const ID_CPE: u32 = 1;
697const ID_LFE: u32 = 3;
698const ID_END: u32 = 7;
699const ZERO_HCB: u8 = 0;
700const ESC_HCB: u8 = 11;
701
702// ---------------------------------------------------------------------------
703// Channel element layout (ISO 14496-3 Table 1.19).
704//
705// `channel_configuration` in the ADTS header / AudioSpecificConfig does not just
706// count channels — it *names the element sequence a decoder will expect*. Writing
707// `channel_config = 6` and then emitting six SCEs is not "6 channels", it is a
708// non-conformant stream: a conforming decoder reads SCE, CPE, CPE, LFE.
709//
710// Our own decoder happened to tolerate it (it appends elements in order), which
711// is exactly how the bug survived — self-round-trip is not conformance.
712// ---------------------------------------------------------------------------
713
714/// One channel element to emit, naming its source channels **in input order**.
715#[derive(Debug, Clone, Copy, PartialEq, Eq)]
716pub(crate) enum Elem {
717 /// single_channel_element carrying input channel `.0`.
718 Sce(usize),
719 /// channel_pair_element carrying input channels `.0` (left) and `.1` (right).
720 Cpe(usize, usize),
721 /// lfe_channel_element carrying input channel `.0`. Long blocks only.
722 Lfe(usize),
723}
724
725impl Elem {
726 /// The 3-bit element id written to the bitstream.
727 fn id(self) -> u32 {
728 match self {
729 Elem::Sce(_) => ID_SCE,
730 Elem::Cpe(_, _) => ID_CPE,
731 Elem::Lfe(_) => ID_LFE,
732 }
733 }
734}
735
736/// The element sequence for `channels`, with source indices in the **standard
737/// interleave order** the caller pushes (WAVE_FORMAT_EXTENSIBLE / FFmpeg order:
738/// FL, FR, FC, LFE, BL, BR).
739///
740/// The reordering is the substance here. AAC orders a 5.1 stream
741/// `C, L, R, Ls, Rs, LFE`; interleaved PCM arrives `L, R, C, LFE, Ls, Rs`. Emitting
742/// them in arrival order would put the centre channel in the left speaker.
743///
744/// Returns `None` for channel counts with no defined `channel_configuration`
745/// (0, or > 6): those need a program_config_element, which we do not yet write.
746pub(crate) fn element_plan(channels: usize) -> Option<Vec<Elem>> {
747 Some(match channels {
748 // config 1 — mono.
749 1 => vec![Elem::Sce(0)],
750 // config 2 — stereo.
751 2 => vec![Elem::Cpe(0, 1)],
752 // config 3 — 3.0: C, L/R.
753 3 => vec![Elem::Sce(2), Elem::Cpe(0, 1)],
754 // config 4 — 4.0: C, L/R, rear centre.
755 4 => vec![Elem::Sce(2), Elem::Cpe(0, 1), Elem::Sce(3)],
756 // config 5 — 5.0: C, L/R, Ls/Rs.
757 5 => vec![Elem::Sce(2), Elem::Cpe(0, 1), Elem::Cpe(3, 4)],
758 // config 6 — 5.1: C, L/R, Ls/Rs, LFE.
759 6 => vec![
760 Elem::Sce(2),
761 Elem::Cpe(0, 1),
762 Elem::Cpe(4, 5),
763 Elem::Lfe(3),
764 ],
765 _ => return None,
766 })
767}
768
769/// Inverse of [`element_plan`]'s ordering: for each **output** slot in standard
770/// interleave order, which decoded element-order channel supplies it.
771///
772/// The decoder emits channels in element order (AAC order); this maps them back
773/// so a 5.1 decode interleaves as FL, FR, FC, LFE, BL, BR like every other
774/// decoder in the workspace.
775pub(crate) fn aac_to_interleave_order(channels: usize) -> Option<Vec<usize>> {
776 Some(match channels {
777 1 => vec![0],
778 2 => vec![0, 1],
779 // AAC order C,L,R -> interleave L,R,C
780 3 => vec![1, 2, 0],
781 // AAC order C,L,R,Cs -> interleave L,R,C,Cs
782 4 => vec![1, 2, 0, 3],
783 // AAC order C,L,R,Ls,Rs -> interleave L,R,C,Ls,Rs
784 5 => vec![1, 2, 0, 3, 4],
785 // AAC order C,L,R,Ls,Rs,LFE -> interleave L,R,C,LFE,Ls,Rs
786 6 => vec![1, 2, 0, 5, 3, 4],
787 _ => return None,
788 })
789}
790
791const MAX_QUANT: i32 = 8191;
792
793/// Quantize one coefficient at global gain `gg` (used by tests / the noise metric).
794fn quantize(x: f32, gg: i32) -> i32 {
795 if x == 0.0 {
796 return 0;
797 }
798 let scale = 2f64.powf(-0.1875 * (gg - 100) as f64);
799 let q = (((x.abs() as f64).powf(0.75) * scale).round() as i32).min(MAX_QUANT);
800 if x < 0.0 {
801 -q
802 } else {
803 q
804 }
805}
806
807/// `2^(-0.1875·(sf-100))`, the quantizer scale, tabulated once over all 256 gains
808/// so the rate loop never repeats the exponent.
809fn scale_table() -> &'static [f64; 256] {
810 static T: OnceLock<[f64; 256]> = OnceLock::new();
811 T.get_or_init(|| {
812 let mut t = [0f64; 256];
813 for (sf, e) in t.iter_mut().enumerate() {
814 *e = 2f64.powf(-0.1875 * (sf as f64 - 100.0));
815 }
816 t
817 })
818}
819
820/// Per-magnitude coefficient bit cost (half a book-11 pair), tabulated so the rate
821/// loop's *search* can price a frame in O(n) without the full codebook selection —
822/// only the exact refinement does the real search.
823fn coef_bits() -> &'static [u16] {
824 static T: OnceLock<Vec<u16>> = OnceLock::new();
825 T.get_or_init(|| {
826 (0..=MAX_QUANT)
827 .map(|m| (spectral_bits(ESC_HCB as usize, &[m, m]).unwrap_or(64) / 2) as u16)
828 .collect()
829 })
830}
831
832/// Per-coefficient `|x|^0.75` and sign, precomputed once per frame so the rate
833/// loop can re-quantize at each candidate gain without repeating the 0.75-power
834/// (the single hottest op after the MDCT). Bit-exact with [`quantize`].
835struct Xpow {
836 pow: Vec<f64>,
837 sign: Vec<i32>,
838}
839
840impl Xpow {
841 fn new(spec: &[f32]) -> Xpow {
842 let mut pow = vec![0f64; spec.len()];
843 let mut sign = vec![0i32; spec.len()];
844 #[cfg(all(feature = "simd", target_arch = "x86_64"))]
845 {
846 if has_avx2() {
847 // SAFETY: runtime AVX2 check; `pow`/`sign` are `spec.len()` long.
848 unsafe { xpow_avx2(spec, &mut pow, &mut sign) };
849 return Xpow { pow, sign };
850 }
851 }
852 for (i, &x) in spec.iter().enumerate() {
853 // |x|^0.75 = |x|^½·|x|^¼ = √|x|·√√|x| — two sqrts vectorize; `powf` doesn't.
854 // (For x=0, pow=0 so the sign is irrelevant — the quant is 0 either way.)
855 let s = (x.abs() as f64).sqrt();
856 pow[i] = s * s.sqrt();
857 sign[i] = if x < 0.0 { -1 } else { 1 };
858 }
859 Xpow { pow, sign }
860 }
861
862 /// Max `|x|^0.75` over `[s, e)` — the no-clamp-floor input (= `(max|x|)^0.75`).
863 fn max_pow(&self, s: usize, e: usize) -> f64 {
864 self.pow[s..e].iter().copied().fold(0.0, f64::max)
865 }
866
867 fn len(&self) -> usize {
868 self.pow.len()
869 }
870}
871
872/// The cheapest representable spectral codebook for one SFB's coefficients, and
873/// its bit cost. ZERO for a silent band; dim-4 books only for 4-aligned bands.
874/// Books whose LAV can't hold the band's peak are skipped up front (only the
875/// escape book covers arbitrarily large values).
876fn best_codebook_for_band(quant: &[i32], s: usize, e: usize) -> (u8, usize) {
877 let maxq = quant[s..e]
878 .iter()
879 .map(|&q| q.unsigned_abs())
880 .max()
881 .unwrap_or(0);
882 if maxq == 0 {
883 return (ZERO_HCB, 0);
884 }
885 let mut best = (ESC_HCB, usize::MAX);
886 for cb in 1..=11u8 {
887 let meta = &CODEBOOKS[cb as usize];
888 let dim = meta.dim as usize;
889 if (e - s) % dim != 0 || (!meta.esc && (meta.lav as u32) < maxq) {
890 continue;
891 }
892 let mut bits = 0usize;
893 let mut ok = true;
894 let mut i = s;
895 while i < e {
896 match spectral_bits(cb as usize, &quant[i..i + dim]) {
897 Some(b) => bits += b,
898 None => {
899 ok = false;
900 break;
901 }
902 }
903 i += dim;
904 }
905 if ok && bits < best.1 {
906 best = (cb, bits);
907 }
908 }
909 best
910}
911
912/// Bits for section_data given per-SFB codebooks (adjacent equal cbs merge into
913/// one 4-bit codebook + 5-bit run-length increments).
914fn section_bits(cbs: &[u8]) -> usize {
915 let esc = 31usize;
916 let mut bits = 0usize;
917 let mut k = 0usize;
918 while k < cbs.len() {
919 let cb = cbs[k];
920 let mut len = 1usize;
921 while k + len < cbs.len() && cbs[k + len] == cb {
922 len += 1;
923 }
924 bits += 4;
925 let mut l = len;
926 while l >= esc {
927 bits += 5;
928 l -= esc;
929 }
930 bits += 5;
931 k += len;
932 }
933 bits
934}
935
936/// Per-band scalefactors from a common `base` plus the psy offsets, each clamped
937/// to the codeable range. Offsets span ≤48, so band-to-band deltas stay < 60.
938fn scalefactors(offsets: &[i32], base: i32) -> Vec<i32> {
939 offsets.iter().map(|&o| (base + o).clamp(0, 255)).collect()
940}
941
942/// global_gain = the first coded band's scalefactor (the differential reference);
943/// 100 for a silent frame with no coded bands.
944fn global_gain(cbs: &[u8], sf: &[i32]) -> i32 {
945 // Only a REGULAR band seeds the differential chain. A PNS band's `sf` is a
946 // noise-energy value on its own accumulator and an intensity band's is a
947 // stereo position — seeding global_gain from either desynchronizes every
948 // scalefactor that follows.
949 cbs.iter()
950 .position(|&cb| cb != ZERO_HCB && cb < NOISE_HCB)
951 .map(|sfb| sf[sfb])
952 .unwrap_or(100)
953}
954
955/// Bits to code the per-band scalefactors as `SCALEFACTOR_BOOK` deltas from a
956/// running accumulator seeded at `gg`.
957fn scalefactor_bits(cbs: &[u8], sf: &[i32], gg: i32) -> usize {
958 let mut acc = gg;
959 let mut noise = gg - 90;
960 let mut noise_pcm = true;
961 let mut is_pos = 0i32;
962 let mut bits = 0usize;
963 for (sfb, &cb) in cbs.iter().enumerate() {
964 if cb == ZERO_HCB {
965 continue;
966 } else if cb >= crate::codebook::INTENSITY_HCB2 {
967 let d = (sf[sfb] - is_pos).clamp(-60, 60);
968 bits += crate::tables::SCALEFACTOR_BOOK.code((d + 60) as usize).1 as usize;
969 is_pos += d;
970 } else if cb == NOISE_HCB {
971 if noise_pcm {
972 noise_pcm = false;
973 let d = (sf[sfb] - noise).clamp(-256, 255);
974 bits += 9;
975 noise += d;
976 } else {
977 let d = (sf[sfb] - noise).clamp(-60, 60);
978 bits += crate::tables::SCALEFACTOR_BOOK.code((d + 60) as usize).1 as usize;
979 noise += d;
980 }
981 } else {
982 let d = (sf[sfb] - acc).clamp(-60, 60);
983 bits += crate::tables::SCALEFACTOR_BOOK.code((d + 60) as usize).1 as usize;
984 acc += d;
985 }
986 }
987 bits
988}
989
990/// Runtime AVX2 availability (detected once).
991#[cfg(all(feature = "simd", target_arch = "x86_64"))]
992fn has_avx2() -> bool {
993 static AVX2: OnceLock<bool> = OnceLock::new();
994 *AVX2.get_or_init(|| std::is_x86_feature_detected!("avx2"))
995}
996
997#[cfg(all(feature = "simd-avx512", target_arch = "x86_64"))]
998fn has_avx512() -> bool {
999 static AVX512: OnceLock<bool> = OnceLock::new();
1000 *AVX512.get_or_init(|| std::is_x86_feature_detected!("avx512f"))
1001}
1002
1003/// Quantize one band into `out`: `out[k] = sign[k]·min(round(pow[k]·scale), MAX_QUANT)`.
1004/// This is the encoder's hottest kernel — the rate loop runs it ~11× per frame — so it
1005/// has an AVX2 path. `pow·scale ≥ 0`, so `floor(v+0.5)` equals `round(v)`, making the
1006/// vector path **bit-exact** with the scalar reference (verified by every gate test).
1007fn quantize_band(pow: &[f64], sign: &[i32], scale: f64, out: &mut [i32]) {
1008 // SAFETY (all SIMD branches): entered only when the ISA is detected at runtime; the
1009 // three slices share a length and vector bodies touch full lane-chunks, the remainder
1010 // falling to the scalar tail. Every path is bit-exact with the scalar reference.
1011 #[cfg(all(feature = "simd-avx512", target_arch = "x86_64"))]
1012 if has_avx512() {
1013 unsafe { quantize_band_avx512(pow, sign, scale, out) };
1014 return;
1015 }
1016 #[cfg(all(feature = "simd", target_arch = "x86_64"))]
1017 if has_avx2() {
1018 unsafe { quantize_band_avx2(pow, sign, scale, out) };
1019 return;
1020 }
1021 quantize_band_scalar(pow, sign, scale, out);
1022}
1023
1024fn quantize_band_scalar(pow: &[f64], sign: &[i32], scale: f64, out: &mut [i32]) {
1025 for k in 0..out.len() {
1026 let q = ((pow[k] * scale).round() as i32).min(MAX_QUANT);
1027 out[k] = sign[k] * q;
1028 }
1029}
1030
1031/// AVX2 quantize — four coefficients per iteration. Bit-exact with the scalar path
1032/// (`floor(v+0.5) == round(v)` for `v ≥ 0`, and the clamp is applied before the
1033/// f64→i32 narrowing so nothing overflows).
1034#[cfg(all(feature = "simd", target_arch = "x86_64"))]
1035#[target_feature(enable = "avx2")]
1036unsafe fn quantize_band_avx2(pow: &[f64], sign: &[i32], scale: f64, out: &mut [i32]) {
1037 use std::arch::x86_64::*;
1038 let n = out.len();
1039 let vscale = _mm256_set1_pd(scale);
1040 let vhalf = _mm256_set1_pd(0.5);
1041 let vmax = _mm256_set1_pd(MAX_QUANT as f64);
1042 let mut i = 0;
1043 while i + 4 <= n {
1044 let v = _mm256_mul_pd(_mm256_loadu_pd(pow.as_ptr().add(i)), vscale);
1045 let r = _mm256_floor_pd(_mm256_add_pd(v, vhalf)); // = round(v), v ≥ 0
1046 let qabs = _mm256_cvttpd_epi32(_mm256_min_pd(r, vmax)); // clamp then f64→i32
1047 let s = _mm_loadu_si128(sign.as_ptr().add(i) as *const __m128i);
1048 _mm_storeu_si128(
1049 out.as_mut_ptr().add(i) as *mut __m128i,
1050 _mm_mullo_epi32(qabs, s),
1051 );
1052 i += 4;
1053 }
1054 while i < n {
1055 let q = ((pow[i] * scale).round() as i32).min(MAX_QUANT);
1056 out[i] = sign[i] * q;
1057 i += 1;
1058 }
1059}
1060
1061/// AVX-512 quantize — eight coefficients per iteration (2× the AVX2 width). Bit-exact:
1062/// for the quantizer's always-nonnegative input, `trunc(min(v+0.5, MAX+0.5))` equals
1063/// `min(round(v), MAX)`, so a single truncating narrow does round+clamp in one step.
1064/// Runtime-gated above AVX2; on AVX2-only hosts this path never runs (untested there —
1065/// the math mirrors the AVX2 kernel exactly, and its tail is the shared scalar reference).
1066#[cfg(all(feature = "simd-avx512", target_arch = "x86_64"))]
1067#[target_feature(enable = "avx512f,avx2")]
1068unsafe fn quantize_band_avx512(pow: &[f64], sign: &[i32], scale: f64, out: &mut [i32]) {
1069 use std::arch::x86_64::*;
1070 let n = out.len();
1071 let vscale = _mm512_set1_pd(scale);
1072 let vhalf = _mm512_set1_pd(0.5);
1073 let vmaxph = _mm512_set1_pd(MAX_QUANT as f64 + 0.5); // clamp v+0.5 so trunc yields MAX
1074 let mut i = 0;
1075 while i + 8 <= n {
1076 let v = _mm512_mul_pd(_mm512_loadu_pd(pow.as_ptr().add(i)), vscale);
1077 let c = _mm512_min_pd(_mm512_add_pd(v, vhalf), vmaxph);
1078 let qabs = _mm512_cvttpd_epi32(c); // 8 f64 → 8 i32; trunc = floor for c ≥ 0
1079 let s = _mm256_loadu_si256(sign.as_ptr().add(i) as *const __m256i);
1080 _mm256_storeu_si256(
1081 out.as_mut_ptr().add(i) as *mut __m256i,
1082 _mm256_mullo_epi32(qabs, s),
1083 );
1084 i += 8;
1085 }
1086 while i < n {
1087 let q = ((pow[i] * scale).round() as i32).min(MAX_QUANT);
1088 out[i] = sign[i] * q;
1089 i += 1;
1090 }
1091}
1092
1093/// AVX2 `Xpow` builder: `pow[i] = |x|^0.75` via `√|x|·√√|x|` (two vector sqrts), and
1094/// `sign[i] = ±1` from the sign bit — four coefficients per iteration.
1095#[cfg(all(feature = "simd", target_arch = "x86_64"))]
1096#[target_feature(enable = "avx2")]
1097unsafe fn xpow_avx2(spec: &[f32], pow: &mut [f64], sign: &mut [i32]) {
1098 use std::arch::x86_64::*;
1099 let n = spec.len();
1100 let absmask = _mm256_castsi256_pd(_mm256_set1_epi64x(0x7fff_ffff_ffff_ffffu64 as i64));
1101 let one = _mm256_set1_pd(1.0);
1102 let mut i = 0;
1103 while i + 4 <= n {
1104 let x = _mm256_cvtps_pd(_mm_loadu_ps(spec.as_ptr().add(i))); // 4 f32 → 4 f64
1105 let a = _mm256_and_pd(x, absmask); // |x|
1106 let s = _mm256_sqrt_pd(a); // |x|^½
1107 _mm256_storeu_pd(pow.as_mut_ptr().add(i), _mm256_mul_pd(s, _mm256_sqrt_pd(s)));
1108 // ±1.0 carrying x's sign bit → i32 (x=0 gives +1; harmless, pow is 0).
1109 let signed = _mm256_or_pd(one, _mm256_andnot_pd(absmask, x));
1110 _mm_storeu_si128(
1111 sign.as_mut_ptr().add(i) as *mut __m128i,
1112 _mm256_cvttpd_epi32(signed),
1113 );
1114 i += 4;
1115 }
1116 while i < n {
1117 let s = (spec[i].abs() as f64).sqrt();
1118 pow[i] = s * s.sqrt();
1119 sign[i] = if spec[i] < 0.0 { -1 } else { 1 };
1120 }
1121}
1122
1123/// **Deterministic work counters** (feature `lab`) — the PRIMARY evidence for any
1124/// gate's speed half, per `codec-measurement` §15.
1125///
1126/// A counter is immune to scheduler drift, needs one run, and SIZES the effect;
1127/// a clock at these magnitudes cannot be promoted to a verdict no matter how many
1128/// pairs it gets. The gate-calculator's `work` column is fed from here.
1129///
1130/// Counts the rate loop's exact-coder evaluations — the encoder's dominant inner
1131/// cost and precisely the quantity a psy arm moves, because changing the offsets
1132/// changes how many bases the loop must try.
1133#[cfg(feature = "lab")]
1134pub mod work {
1135 use std::sync::atomic::{AtomicU64, Ordering};
1136
1137 // GLOBAL, not thread-local. `encode_stream` fans frames out across worker
1138 // threads, so a thread-local counter is drained on the main thread AFTER the
1139 // workers have exited and reads **zero** — which is exactly what the first
1140 // harvest reported (`WORK NULL: 0 vs 0`). A counter that reads flat is a
1141 // defect report, not reassurance (`codec-measurement`, order of instruments).
1142 static CODE_FRAME_EVALS: AtomicU64 = AtomicU64::new(0);
1143 static QUANT_BANDS: AtomicU64 = AtomicU64::new(0);
1144
1145 #[inline]
1146 pub(crate) fn bump_code_frame() {
1147 CODE_FRAME_EVALS.fetch_add(1, Ordering::Relaxed);
1148 }
1149
1150 #[inline]
1151 pub(crate) fn bump_quant_bands(n: u64) {
1152 QUANT_BANDS.fetch_add(n, Ordering::Relaxed);
1153 }
1154
1155 /// Read and clear both counters.
1156 ///
1157 /// `Relaxed` is sufficient: these are pure counters, never used to order
1158 /// other memory, and the harvest reads them only after `finish()` has joined
1159 /// every worker — so the joins provide the happens-before edge.
1160 pub fn take() -> (u64, u64) {
1161 (
1162 CODE_FRAME_EVALS.swap(0, Ordering::Relaxed),
1163 QUANT_BANDS.swap(0, Ordering::Relaxed),
1164 )
1165 }
1166}
1167
1168#[cfg(not(feature = "lab"))]
1169mod work {
1170 #[inline]
1171 pub(crate) fn bump_code_frame() {}
1172 #[inline]
1173 pub(crate) fn bump_quant_bands(_: u64) {}
1174}
1175
1176/// Shared coder body: quantize the frame into the caller-owned `quant` (per-band
1177/// scalefactors `sf`, which cover the whole spectrum so no pre-zeroing is needed),
1178/// pick per-band codebooks, and return (codebooks, ICS body bits, max_sfb). Splitting
1179/// this out lets the rate loop reuse one buffer instead of allocating per candidate.
1180fn code_core(xp: &Xpow, swb: &[u16], sf: &[i32], quant: &mut [i32]) -> (Vec<u8>, usize, usize) {
1181 work::bump_code_frame();
1182 let num_swb = swb.len() - 1;
1183 work::bump_quant_bands((swb.len() - 1) as u64);
1184 let scale = scale_table();
1185 for sfb in 0..num_swb {
1186 let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
1187 let sc = scale[sf[sfb].clamp(0, 255) as usize];
1188 quantize_band(&xp.pow[s..e], &xp.sign[s..e], sc, &mut quant[s..e]);
1189 }
1190 let mut max_sfb = 0usize;
1191 for sfb in 0..num_swb {
1192 let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
1193 if quant[s..e].iter().any(|&q| q != 0) {
1194 max_sfb = sfb + 1;
1195 }
1196 }
1197 let mut cbs = Vec::with_capacity(max_sfb);
1198 let mut spec_bits = 0usize;
1199 for sfb in 0..max_sfb {
1200 let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
1201 let (cb, bits) = best_codebook_for_band(quant, s, e);
1202 cbs.push(cb);
1203 spec_bits += bits;
1204 }
1205 let gg = global_gain(&cbs, sf);
1206 // global_gain(8) + ics_info(~11) + 3 flag bits + sections + scalefactors + spectrum.
1207 let body = 8 + 11 + 3 + section_bits(&cbs) + scalefactor_bits(&cbs, sf, gg) + spec_bits;
1208 (cbs, body, max_sfb)
1209}
1210
1211/// Owned-buffer wrapper over [`code_core`] for the one-shot callers (final coding).
1212fn code_frame(xp: &Xpow, swb: &[u16], sf: &[i32]) -> (Vec<u8>, usize, usize, Vec<i32>) {
1213 let mut quant = vec![0i32; xp.len()];
1214 let (cbs, body, max_sfb) = code_core(xp, swb, sf, &mut quant);
1215 (cbs, body, max_sfb, quant)
1216}
1217
1218/// The smallest common `base` such that no band clamps its loudest coefficient
1219/// past `MAX_QUANT` (each band's own no-clamp floor, minus that band's offset).
1220fn min_base(xp: &Xpow, swb: &[u16], offsets: &[i32]) -> i32 {
1221 let num_swb = swb.len() - 1;
1222 let mut floor = 0i32;
1223 for sfb in 0..num_swb {
1224 let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
1225 let maxp = xp.max_pow(s, e); // = (max|x|)^0.75
1226 if maxp <= 1e-9 {
1227 continue;
1228 }
1229 let min_sf = (100.0 - (MAX_QUANT as f64 / maxp).log2() / 0.1875).ceil() as i32;
1230 floor = floor.max(min_sf - offsets[sfb]);
1231 }
1232 floor.clamp(0, 255)
1233}
1234
1235/// Fast body-bit estimate at a candidate `base`: quantize (cheap) and price each
1236/// coefficient from the `coef_bits` table — no codebook search. Monotone in `base`,
1237/// so it seeds the search; the exact refinement corrects it.
1238fn estimate_bits(xp: &Xpow, swb: &[u16], offsets: &[i32], base: i32) -> usize {
1239 let scale = scale_table();
1240 let ct = coef_bits();
1241 let num_swb = swb.len() - 1;
1242 let mut bits = 22usize; // global_gain + ics_info + flags, approx
1243 let mut qbuf = [0i32; 128]; // one band (max long SWB width is 96)
1244 for sfb in 0..num_swb {
1245 let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
1246 let w = e - s;
1247 let sc = scale[(base + offsets[sfb]).clamp(0, 255) as usize];
1248 quantize_band(&xp.pow[s..e], &xp.sign[s..e], sc, &mut qbuf[..w]);
1249 let mut band = 0usize;
1250 let mut nonzero = false;
1251 for &q in &qbuf[..w] {
1252 let m = q.unsigned_abs() as usize;
1253 if m != 0 {
1254 nonzero = true;
1255 band += ct[m] as usize;
1256 }
1257 }
1258 if nonzero {
1259 bits += 9 + band; // ~section + scalefactor + spectrum for the band
1260 }
1261 }
1262 bits
1263}
1264
1265/// The smallest common `base` (≥ the no-clamp floor) whose ICS body fits
1266/// `target_bits` — finest quality within budget. A fast estimate seeds the search;
1267/// the exact coder then walks to the true boundary (identical to a full search, but
1268/// only a couple of exact evaluations instead of eight). Body bits fall as `base`
1269/// rises.
1270fn rate_loop(xp: &Xpow, swb: &[u16], offsets: &[i32], target_bits: usize) -> i32 {
1271 let min_b = min_base(xp, swb, offsets);
1272 // Phase 1: binary-search the cheap estimate.
1273 let (mut lo, mut hi) = (min_b, 255i32);
1274 while lo < hi {
1275 let mid = (lo + hi) / 2;
1276 if estimate_bits(xp, swb, offsets, mid) <= target_bits {
1277 hi = mid;
1278 } else {
1279 lo = mid + 1;
1280 }
1281 }
1282 // Phase 2: refine to the exact smallest fitting base with the real coder, reusing
1283 // one quant buffer across the (few) exact evaluations.
1284 let mut quant = vec![0i32; xp.len()];
1285 let mut exact =
1286 |b: i32| code_core(xp, swb, &scalefactors(offsets, b), &mut quant).1 <= target_bits;
1287 let mut base = lo;
1288 if exact(base) {
1289 while base > min_b && exact(base - 1) {
1290 base -= 1;
1291 }
1292 } else {
1293 while base < 255 && !exact(base) {
1294 base += 1;
1295 }
1296 }
1297 base
1298}
1299
1300/// section_data (single group, long block): 4-bit codebook + 5-bit run-length
1301/// increments (esc = 31 continues the run).
1302fn write_sections(w: &mut BitWriter, cbs: &[u8]) {
1303 let esc = 31u32;
1304 let mut k = 0usize;
1305 while k < cbs.len() {
1306 let cb = cbs[k];
1307 let mut len = 1usize;
1308 while k + len < cbs.len() && cbs[k + len] == cb {
1309 len += 1;
1310 }
1311 w.write(cb as u32, 4);
1312 let mut l = len as u32;
1313 while l >= esc {
1314 w.write(esc, 5);
1315 l -= esc;
1316 }
1317 w.write(l, 5);
1318 k += len;
1319 }
1320}
1321
1322/// scale_factor_data: each coded band's scalefactor as a `SCALEFACTOR_BOOK` delta
1323/// from a running accumulator seeded at `gg` (matching the decoder).
1324fn write_scalefactors(w: &mut BitWriter, cbs: &[u8], sf: &[i32], gg: i32) {
1325 // THREE independent accumulators, exactly as `decode::read_scalefactors`
1326 // maintains them. Folding PNS or intensity values into the regular chain
1327 // desynchronizes every later band, which decodes as garbage rather than as a
1328 // slightly wrong gain.
1329 let mut acc = gg;
1330 let mut noise = gg - 90;
1331 let mut noise_pcm = true;
1332 let mut is_pos = 0i32;
1333 for (sfb, &cb) in cbs.iter().enumerate() {
1334 if cb == ZERO_HCB {
1335 continue;
1336 } else if cb >= crate::codebook::INTENSITY_HCB2 {
1337 let d = (sf[sfb] - is_pos).clamp(-60, 60);
1338 let (code, len) = crate::tables::SCALEFACTOR_BOOK.code((d + 60) as usize);
1339 w.write(code, len as u32);
1340 is_pos += d;
1341 } else if cb == NOISE_HCB {
1342 if noise_pcm {
1343 // The first PNS band is a 9-bit PCM delta, not a Huffman one.
1344 noise_pcm = false;
1345 let d = (sf[sfb] - noise).clamp(-256, 255);
1346 w.write((d + 256) as u32, 9);
1347 noise += d;
1348 } else {
1349 let d = (sf[sfb] - noise).clamp(-60, 60);
1350 let (code, len) = crate::tables::SCALEFACTOR_BOOK.code((d + 60) as usize);
1351 w.write(code, len as u32);
1352 noise += d;
1353 }
1354 } else {
1355 let d = (sf[sfb] - acc).clamp(-60, 60);
1356 let (code, len) = crate::tables::SCALEFACTOR_BOOK.code((d + 60) as usize);
1357 w.write(code, len as u32);
1358 acc += d;
1359 }
1360 }
1361}
1362
1363/// **Arm A6 — Perceptual Noise Substitution.**
1364///
1365/// Replace a noise-like band's coefficients with a single transmitted *energy*;
1366/// the decoder refills it with scaled random noise (`decode::fill_noise`). The
1367/// band costs a scalefactor instead of a spectrum, which at low rates is the
1368/// difference between coding a band and zeroing it.
1369///
1370/// The P0 baseline is the motivation: `speech-noisy` and `noise-like` sit at
1371/// 99%+ audible from 64-128k and only clear at 192k — broadband noise has no
1372/// maskers to hide under and is unaffordable, which is exactly the problem PNS
1373/// exists to solve.
1374///
1375/// The gate is deliberately conservative on all three axes, because PNS destroys
1376/// phase and is audibly destructive on a harmonic band (the `music-tonal`
1377/// anti-class):
1378///
1379/// * **frequency** — only above `PNS_MIN_HZ`; PNS on the bass is never right,
1380/// * **tonality** — only bands the SFM calls noise-like,
1381/// * **energy** — only bands actually carrying signal.
1382///
1383/// Returns the noise-energy value to transmit for each substituted band.
1384/// `fill_noise` produces band energy `2^(ne/2)`, so `ne = 2*log2(E)`.
1385fn pns_bands(
1386 spec: &[f32],
1387 swb: &[u16],
1388 sample_rate: u32,
1389 tonality: &[f32],
1390 max_sfb: usize,
1391) -> Vec<Option<i32>> {
1392 const PNS_MIN_HZ: f64 = 4000.0;
1393 const PNS_MAX_TONALITY: f32 = 0.10;
1394 /// A frame this tonal overall gets NO PNS at all, whatever individual bands
1395 /// say. See the band-level trap below.
1396 const PNS_MAX_FRAME_TONALITY: f32 = 0.15;
1397 /// A band must carry at least this fraction of the frame's MEAN band energy
1398 /// to be worth substituting — population-relative (law 1), not absolute.
1399 const PNS_MIN_ENERGY_FRAC: f64 = 0.5;
1400
1401 let num_swb = swb.len() - 1;
1402 let mut out = vec![None; num_swb];
1403
1404 // Band energies once, and the frame's energy-weighted tonality.
1405 let mut energies = vec![0f64; num_swb];
1406 for sfb in 0..num_swb {
1407 let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
1408 energies[sfb] = spec[s..e.min(spec.len())]
1409 .iter()
1410 .map(|&x| (x as f64) * (x as f64))
1411 .sum();
1412 }
1413 let total: f64 = energies.iter().sum::<f64>() + 1e-9;
1414 let frame_tonality =
1415 (0..num_swb).map(|i| energies[i] * tonality[i] as f64).sum::<f64>() / total;
1416
1417 // **The band-level trap, measured.** A near-EMPTY band has a flat spectrum,
1418 // so its spectral flatness measure reads as maximally *noise-like* — SFM
1419 // cannot distinguish "broadband noise" from "almost nothing". A band-only
1420 // gate therefore substitutes noise into the empty bands surrounding a pure
1421 // tone, which is how the first version of this fired on a 6 kHz sine.
1422 //
1423 // Two guards, because they fail in different directions: the frame-level veto
1424 // refuses tonal CONTENT outright, and the relative energy floor refuses
1425 // individual bands with nothing in them.
1426 if frame_tonality as f32 > PNS_MAX_FRAME_TONALITY {
1427 return out;
1428 }
1429 let mean_band = total / num_swb as f64;
1430
1431 for sfb in 0..num_swb.min(max_sfb) {
1432 let lo_hz = swb[sfb] as f64 * sample_rate as f64 * 0.5 / FRAME_LEN as f64;
1433 if lo_hz < PNS_MIN_HZ || tonality[sfb] > PNS_MAX_TONALITY {
1434 continue;
1435 }
1436 let energy = energies[sfb];
1437 if energy <= 1.0 || energy < mean_band * PNS_MIN_ENERGY_FRAC {
1438 continue; // nothing meaningful there to substitute
1439 }
1440 let ne = (2.0 * energy.log2()).round() as i32;
1441 out[sfb] = Some(ne.clamp(-100, 255));
1442 }
1443 out
1444}
1445
1446/// spectral_data: per regular SFB, code coefficient tuples with the band's book.
1447fn write_spectrum(w: &mut BitWriter, quant: &[i32], cbs: &[u8], swb: &[u16]) {
1448 for (sfb, &cb) in cbs.iter().enumerate() {
1449 // ZERO, NOISE (PNS) and intensity bands carry no spectral data — their
1450 // whole point is that the coefficients are not transmitted.
1451 if cb == ZERO_HCB || cb >= NOISE_HCB {
1452 continue;
1453 }
1454 let dim = CODEBOOKS[cb as usize].dim as usize;
1455 let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
1456 let mut i = s;
1457 while i + dim <= e {
1458 spectral_emit(cb as usize, &quant[i..i + dim], w);
1459 i += dim;
1460 }
1461 }
1462}
1463
1464/// Encode one channel as a single_channel_element for a long or transition block
1465/// (`seq` ∈ {OnlyLong, LongStart, LongStop}): psy offsets → rate loop over the
1466/// common base → per-band scalefactors → coded ICS.
1467#[allow(clippy::too_many_arguments)]
1468fn encode_channel_element(
1469 w: &mut BitWriter,
1470 tag: u32,
1471 spec: &[f32],
1472 swb: &[u16],
1473 seq: WindowSequence,
1474 sample_rate: u32,
1475 target_bits: usize,
1476 cur_kbd: bool,
1477 psy: PsyCfg,
1478 elem_id: u32,
1479) {
1480 // Pass 1, un-filtered: the TNS span depends on max_sfb, which only exists
1481 // after quantization. This pass exists to learn it.
1482 let offsets0 = perceptual_offsets(spec, swb, sample_rate, psy.tonality_smr);
1483 let xp0 = Xpow::new(spec);
1484 let base0 = rate_loop(&xp0, swb, &offsets0, target_bits);
1485 let sf0 = scalefactors(&offsets0, base0);
1486 let (cbs0, _, max_sfb0, quant0) = code_frame(&xp0, swb, &sf0);
1487
1488 // Arm A3. Only engage when the coded range already reaches TNS_MAX_LONG, so
1489 // the decoder's span `min(TNS_MAX_LONG, max_sfb)` is pinned to TNS_MAX_LONG
1490 // on BOTH sides regardless of what the re-quantization does to max_sfb. The
1491 // alternative (span depending on a max_sfb that pass 2 can move) is a
1492 // bitstream desync waiting to happen.
1493 let fs_index = crate::sf_index_for_rate(sample_rate).unwrap_or(4);
1494 let tns_max = crate::decode::TNS_MAX_LONG[fs_index as usize] as usize;
1495 let mut tns: Option<TnsEnc> = None;
1496 // ARM A3 ROUTING GATE. Spectral LPC prediction gain alone is NOT a transient
1497 // detector: a peaky TONAL spectrum predicts just as well as an impulsive one,
1498 // so a gain-only gate fires on sustained content, where temporal noise
1499 // shaping has nothing to shape and simply costs bits. Measured (PEAQ, vs the
1500 // previous default): tonal -1.02, mixed -1.14, quiet -1.05, while percussive
1501 // moved only -0.01. It was firing almost exclusively on the wrong content.
1502 //
1503 // The fix is to require the frame to be transient-ADJACENT: only the
1504 // LongStart / LongStop frames that bracket a detected attack. Those are
1505 // exactly the long blocks that carry pre-echo, and the window sequence
1506 // already names them, so the gate is free.
1507 let tns_frame_ok = seq != WindowSequence::OnlyLong;
1508 let (cbs, sf, max_sfb, quant) = if psy.tns && tns_frame_ok && max_sfb0 >= tns_max {
1509 let mut filtered = spec.to_vec();
1510 match tns_analyze_long(&mut filtered, swb, fs_index, max_sfb0) {
1511 Some(t) => {
1512 let offsets = perceptual_offsets(&filtered, swb, sample_rate, psy.tonality_smr);
1513 let xp = Xpow::new(&filtered);
1514 let base = rate_loop(&xp, swb, &offsets, target_bits);
1515 let sf = scalefactors(&offsets, base);
1516 let (mut cbs, _, msfb, quant) = code_frame(&xp, swb, &sf);
1517 // Hold max_sfb at or above tns_max, padding with ZERO bands, so
1518 // the decoder's TNS span is exactly the one we filtered.
1519 let msfb = msfb.max(tns_max);
1520 cbs.resize(msfb, ZERO_HCB);
1521 tns = Some(t);
1522 (cbs, sf, msfb, quant)
1523 }
1524 None => (cbs0, sf0, max_sfb0, quant0),
1525 }
1526 } else {
1527 (cbs0, sf0, max_sfb0, quant0)
1528 };
1529 // Arm A6 — PNS. Substituted bands trade their spectrum for one energy value.
1530 //
1531 // Skipped when TNS fired: the decoder fills noise BEFORE inverse-filtering,
1532 // so with TNS active the transmitted energy would have to be expressed in the
1533 // filtered domain. That combination is not yet validated, and a wrong energy
1534 // there is not a small error - it is a band of noise at the wrong level.
1535 let (mut cbs, mut sf) = (cbs, sf);
1536 if psy.pns && tns.is_none() {
1537 let ton = band_tonality(spec, swb, 1, FRAME_LEN);
1538 for (b, ne) in pns_bands(spec, swb, sample_rate, &ton, max_sfb)
1539 .into_iter()
1540 .enumerate()
1541 {
1542 if let (Some(ne), Some(cb)) = (ne, cbs.get_mut(b)) {
1543 if *cb != ZERO_HCB && *cb < NOISE_HCB {
1544 *cb = NOISE_HCB;
1545 sf[b] = ne;
1546 }
1547 }
1548 }
1549 }
1550 let gg = global_gain(&cbs, &sf);
1551
1552 w.write(elem_id, 3);
1553 w.write(tag, 4);
1554 w.write(gg as u32, 8);
1555 let info = IcsInfo {
1556 window_sequence: seq,
1557 window_shape_kbd: cur_kbd,
1558 max_sfb: max_sfb as u8,
1559 num_windows: 1,
1560 num_window_groups: 1,
1561 window_group_length: vec![1],
1562 num_swb: swb.len() - 1,
1563 };
1564 encode_ics_info(w, &info);
1565 write_sections(w, &cbs);
1566 write_scalefactors(w, &cbs, &sf, gg);
1567 w.write(0, 1); // pulse_data_present
1568 match &tns {
1569 Some(t) => {
1570 w.write(1, 1); // tns_data_present
1571 write_tns_long(w, t);
1572 }
1573 None => w.write(0, 1),
1574 }
1575 w.write(0, 1); // gain_control_data_present
1576 write_spectrum(w, &quant, &cbs, swb);
1577}
1578
1579
1580// ---------------------------------------------------------------------------
1581// Arm A3 (Rung 3) — Temporal Noise Shaping.
1582//
1583// The AAC tool for pre-echo, and a large part of why AAC beats MP3 on speech.
1584// The decoder has implemented it since day one (`decode::apply_tns`); the encoder
1585// emitted `tns_data_present = 0` at all three sites.
1586//
1587// The decoder runs an ALL-POLE (synthesis) filter over the spectrum:
1588// orig[n] = resid[n] - SUM_k lpc[k] * orig[n-k]
1589// so the encoder must run the matching ALL-ZERO (analysis) filter:
1590// resid[n] = orig[n] + SUM_k lpc[k] * orig[n-k]
1591// with the state holding past *inputs* (the original spectrum), not past outputs.
1592// Getting that inversion backwards does not sound slightly worse; it diverges.
1593// ---------------------------------------------------------------------------
1594
1595/// One TNS filter the encoder decided to apply, in emit form.
1596#[derive(Debug, Clone)]
1597pub(crate) struct TnsEnc {
1598 /// Span in scalefactor bands, counted down from the top.
1599 pub length: usize,
1600 pub order: usize,
1601 /// Quantized PARCOR indices (4-bit two's complement, `coef_res = 1`).
1602 pub idx: Vec<i32>,
1603 /// The de-quantized PARCOR values the decoder will reconstruct — the encoder
1604 /// must filter with *these*, not with the unquantized ones, or encoder and
1605 /// decoder run different filters.
1606 pub parcor: Vec<f32>,
1607}
1608
1609/// Coefficient resolution we emit: `coef_res = 1` (4-bit), `coef_compress = 0`.
1610/// The widest grid AAC-LC offers, so quantization error in the filter itself is
1611/// as small as the syntax allows.
1612const TNS_COEF_RES: u32 = 1;
1613const TNS_COEF_BITS: u32 = 4;
1614/// Max order for AAC-LC long blocks (the syntax allows 5 bits; 12 is the ISO cap).
1615const TNS_MAX_ORDER: usize = 12;
1616/// Prediction gain below which TNS is not worth its bits. PROVISIONAL — the
1617/// classic value; the calculator has not fitted it.
1618const TNS_MIN_GAIN: f64 = 1.4;
1619
1620/// Quantize one PARCOR value to the 4-bit grid and return `(index, dequantized)`.
1621///
1622/// Exact inverse of the decoder's dequantizer, including its **asymmetric**
1623/// scale factors (`iqfac` for non-negative, `iqfac_m` for negative) — a single
1624/// shared factor would round half the coefficients to the wrong index.
1625fn quantize_parcor(p: f32) -> (i32, f32) {
1626 use std::f32::consts::PI;
1627 let res_bits = 3 + TNS_COEF_RES;
1628 let iqfac = ((1i32 << (res_bits - 1)) as f32 - 0.5) / (PI / 2.0);
1629 let iqfac_m = ((1i32 << (res_bits - 1)) as f32 + 0.5) / (PI / 2.0);
1630 let t = p.clamp(-0.999, 0.999).asin();
1631 let lo = -(1i32 << (TNS_COEF_BITS - 1));
1632 let hi = (1i32 << (TNS_COEF_BITS - 1)) - 1;
1633 let c = if t >= 0.0 {
1634 (t * iqfac).round() as i32
1635 } else {
1636 (t * iqfac_m).round() as i32
1637 }
1638 .clamp(lo, hi);
1639 // Reconstruct exactly as the decoder will.
1640 let t_back = if c >= 0 {
1641 c as f32 / iqfac
1642 } else {
1643 c as f32 / iqfac_m
1644 };
1645 (c, t_back.sin())
1646}
1647
1648/// PARCOR (reflection coefficients) -> LPC, matching `decode::parcor_to_lpc`.
1649fn parcor_to_lpc_enc(parcor: &[f32]) -> Vec<f32> {
1650 let order = parcor.len();
1651 let mut lpc = vec![0f32; order + 1];
1652 lpc[0] = 1.0;
1653 for m in 1..=order {
1654 let mut tmp = lpc.clone();
1655 for i in 1..m {
1656 tmp[i] = lpc[i] + parcor[m - 1] * lpc[m - i];
1657 }
1658 lpc[..m].copy_from_slice(&tmp[..m]);
1659 lpc[m] = parcor[m - 1];
1660 }
1661 lpc
1662}
1663
1664/// Levinson-Durbin over `spec[start..end]`, returning `(parcor, prediction_gain)`.
1665fn spectral_parcor(spec: &[f32], start: usize, end: usize, order: usize) -> (Vec<f32>, f64) {
1666 let n = end.saturating_sub(start);
1667 if n <= order + 1 {
1668 return (Vec::new(), 1.0);
1669 }
1670 let x = &spec[start..end];
1671 let mut r = vec![0f64; order + 1];
1672 for (lag, slot) in r.iter_mut().enumerate() {
1673 let mut acc = 0f64;
1674 for i in 0..n - lag {
1675 acc += x[i] as f64 * x[i + lag] as f64;
1676 }
1677 *slot = acc;
1678 }
1679 if r[0] <= 1e-12 {
1680 return (Vec::new(), 1.0);
1681 }
1682 let r0 = r[0] * 1.0001; // white-noise correction
1683 r[0] = r0;
1684 let mut a = vec![0f64; order + 1];
1685 let mut parcor = Vec::with_capacity(order);
1686 let mut err = r0;
1687 for i in 1..=order {
1688 let mut acc = r[i];
1689 for j in 1..i {
1690 acc -= a[j] * r[i - j];
1691 }
1692 let k = acc / err;
1693 if !k.is_finite() || k.abs() >= 0.999 {
1694 break;
1695 }
1696 let prev: Vec<f64> = a[1..i].to_vec();
1697 for j in 1..i {
1698 a[j] = prev[j - 1] - k * prev[i - j - 1];
1699 }
1700 a[i] = k;
1701 parcor.push(k as f32);
1702 err *= 1.0 - k * k;
1703 if err <= 1e-12 {
1704 break;
1705 }
1706 }
1707 (parcor, r0 / err.max(1e-12))
1708}
1709
1710/// **The Rung 3 gate + arm.** Decide whether to apply TNS to a long block and, if
1711/// so, filter `spec` in place and return the data to emit.
1712///
1713/// `max_sfb_hint` must be the `max_sfb` that will be written, because the decoder
1714/// filters over `min(TNS_MAX_LONG, max_sfb)` bands — encoder and decoder must
1715/// agree on the span exactly or the inverse filter runs over the wrong region.
1716///
1717/// Returns `None` when the gate declines (prediction gain below threshold, span
1718/// too short, or a degenerate fit), in which case `spec` is untouched and the
1719/// caller emits `tns_data_present = 0` — the byte-identical fallback.
1720pub(crate) fn tns_analyze_long(
1721 spec: &mut [f32],
1722 swb: &[u16],
1723 fs_index: u8,
1724 max_sfb: usize,
1725) -> Option<TnsEnc> {
1726 let num_swb = swb.len() - 1;
1727 let tns_max = crate::decode::TNS_MAX_LONG[fs_index as usize] as usize;
1728 let mmm = tns_max.min(max_sfb);
1729 if mmm < 4 {
1730 return None;
1731 }
1732 // One filter spanning the top of the coded range down to band `bottom`. The
1733 // decoder derives `start`/`end` from `length` the same way.
1734 let bottom = mmm / 4; // skip the lowest quarter: TNS on the bass is harmful
1735 let length = num_swb.saturating_sub(bottom);
1736 let start = swb[bottom.min(mmm)] as usize;
1737 let end = swb[mmm] as usize;
1738 if end <= start + TNS_MAX_ORDER + 1 {
1739 return None;
1740 }
1741
1742 let (parcor_raw, gain) = spectral_parcor(spec, start, end, TNS_MAX_ORDER);
1743 if parcor_raw.is_empty() || gain < TNS_MIN_GAIN {
1744 return None; // the gate: not worth its bits
1745 }
1746
1747 // Quantize to the shipping 4-bit grid, and keep the DEQUANTIZED values —
1748 // filtering with the unquantized ones would leave the decoder running a
1749 // slightly different filter, which shows up as drift across the band.
1750 let mut idx = Vec::with_capacity(parcor_raw.len());
1751 let mut parcor = Vec::with_capacity(parcor_raw.len());
1752 for &p in &parcor_raw {
1753 let (c, dq) = quantize_parcor(p);
1754 idx.push(c);
1755 parcor.push(dq);
1756 }
1757 // Drop trailing zero-index coefficients: they cost 4 bits each and do nothing.
1758 while idx.len() > 1 && *idx.last().unwrap() == 0 {
1759 idx.pop();
1760 parcor.pop();
1761 }
1762 let order = idx.len();
1763 if order == 0 {
1764 return None;
1765 }
1766
1767 let lpc = parcor_to_lpc_enc(&parcor);
1768
1769 // The ANALYSIS filter (all-zero), upward direction, state = past inputs.
1770 // Indexed rather than iterated: the filter reads and writes the same slice
1771 // element each step, which an iterator form cannot express without a copy.
1772 #[allow(clippy::needless_range_loop)]
1773 let mut state = vec![0f32; order];
1774 #[allow(clippy::needless_range_loop)]
1775 for p in start..end {
1776 let xn = spec[p];
1777 let mut y = xn;
1778 for j in 0..order {
1779 y += state[j] * lpc[j + 1];
1780 }
1781 for j in (1..order).rev() {
1782 state[j] = state[j - 1];
1783 }
1784 state[0] = xn;
1785 spec[p] = y;
1786 }
1787
1788 Some(TnsEnc {
1789 length,
1790 order,
1791 idx,
1792 parcor,
1793 })
1794}
1795
1796/// Emit `tns_data` for a long block (`n_filt` 2 bits, `length` 6, `order` 5).
1797/// Mirrors `decode::parse_tns` exactly.
1798pub(crate) fn write_tns_long(w: &mut BitWriter, tns: &TnsEnc) {
1799 w.write(1, 2); // n_filt = 1
1800 w.write(TNS_COEF_RES, 1); // coef_res
1801 w.write(tns.length as u32, 6);
1802 w.write(tns.order as u32, 5);
1803 if tns.order > 0 {
1804 w.write(0, 1); // direction: upward (low -> high)
1805 w.write(0, 1); // coef_compress = 0
1806 for &c in &tns.idx {
1807 let masked = (c as u32) & ((1u32 << TNS_COEF_BITS) - 1);
1808 w.write(masked, TNS_COEF_BITS);
1809 }
1810 }
1811}
1812
1813// ---------------------------------------------------------------------------
1814// Block switching (brick 5) — transient detection, window-sequence assignment,
1815// and the short-block coding path (eight 128-bin windows, one group).
1816// ---------------------------------------------------------------------------
1817
1818/// Flag each 1024-sample frame that contains a transient: a 128-sample sub-block
1819/// whose energy leaps above the recent running average (an attack). Frame 0 is
1820/// never flagged — nothing precedes it to open a LongStart transition from.
1821///
1822/// `pub(crate)` so [`crate::lab::signals`] can record what the *shipping*
1823/// detector decides alongside the campaign's replacement signal — the
1824/// gate-calculator's `shipped` column (arm A9).
1825pub(crate) fn detect_transients(chan: &[f32], nframes: usize) -> Vec<bool> {
1826 const RATIO: f64 = 10.0;
1827 // (arm A9 replaces the guard below; see `detect_transients_relative`)
1828 let mut flags = vec![false; nframes];
1829 let mut avg = 0.0f64;
1830 for (f, flag) in flags.iter_mut().enumerate() {
1831 let mut attack = 1.0f64;
1832 for sb in 0..8 {
1833 let start = f * FRAME_LEN + sb * SHORT_HALF;
1834 let e: f64 = (0..SHORT_HALF)
1835 .map(|i| {
1836 let x = chan.get(start + i).copied().unwrap_or(0.0) as f64;
1837 x * x
1838 })
1839 .sum();
1840 if avg > 1e-3 {
1841 attack = attack.max(e / avg);
1842 }
1843 avg = 0.75 * avg + 0.25 * e;
1844 }
1845 if f > 0 && attack > RATIO {
1846 *flag = true;
1847 }
1848 }
1849 flags
1850}
1851
1852/// Per-frame **population-relative** max attack ratio — the level-invariant
1853/// replacement for [`detect_transients`]'s absolute `avg > 1e-3` guard (arm A9).
1854///
1855/// The running average is floored at a fraction of *this clip's own* mean
1856/// sub-block energy, so both numerator and floor scale with level and the ratio
1857/// is unchanged by a gain change. The shipping detector's absolute floor makes it
1858/// blind on quiet content and, because the average decays 0.75× per sub-block, on
1859/// sparse attacks over a quiet floor at *any* level.
1860///
1861/// Used by the Rung 0 shape gate as a transient veto; it is also the signal arm
1862/// A9 will replace the detector's threshold with.
1863pub(crate) fn frame_attack_ratios(chan: &[f32], nframes: usize) -> Vec<f32> {
1864 let mut sub: Vec<f64> = Vec::with_capacity(nframes * 8);
1865 for f in 0..nframes {
1866 for sb in 0..8 {
1867 let start = f * FRAME_LEN + sb * SHORT_HALF;
1868 let e: f64 = (0..SHORT_HALF)
1869 .map(|i| {
1870 let x = chan.get(start + i).copied().unwrap_or(0.0) as f64;
1871 x * x
1872 })
1873 .sum();
1874 sub.push(e);
1875 }
1876 }
1877 let mean_e = sub.iter().sum::<f64>() / sub.len().max(1) as f64;
1878 let floor = (mean_e * 1e-3).max(f64::MIN_POSITIVE);
1879
1880 let mut avg = 0.0f64;
1881 let mut out = Vec::with_capacity(nframes);
1882 for f in 0..nframes {
1883 let mut amax = 1.0f32;
1884 for sb in 0..8 {
1885 let e = sub[f * 8 + sb];
1886 amax = amax.max((e / avg.max(floor)) as f32);
1887 avg = 0.75 * avg + 0.25 * e;
1888 }
1889 out.push(amax);
1890 }
1891 out
1892}
1893
1894/// **Arm A9 — the level-invariant transient detector.**
1895///
1896/// Same decision rule as [`detect_transients`] (`attack ratio > 10`), on a signal
1897/// that is actually defined. The shipped detector guards its ratio with
1898/// `avg > 1e-3` — an **absolute** energy floor — which has two consequences the
1899/// P1 truth table pinned:
1900///
1901/// * the identical waveform 40 dB quieter stops being detected at all, and
1902/// * because the running average decays 0.75x per sub-block, it falls under the
1903/// floor across the quiet stretch between sparse attacks, so castanet-like
1904/// content is missed **at any level** — measured: zero frames flagged on the
1905/// percussive corpus class whose p95 attack ratio is ~30000x.
1906///
1907/// The ratio itself is already scale-invariant; only the guard was not. This
1908/// version floors the running average relative to the clip's own mean sub-block
1909/// energy instead, which is the law-1 form and leaves the threshold meaning what
1910/// it says.
1911///
1912/// This is not merely a quality knob: arm A1 (short-block psy) can only reach
1913/// frames that are coded as short blocks, so a detector that never fires makes A1
1914/// unmeasurable. A9 is A1's prerequisite.
1915pub(crate) fn detect_transients_relative(chan: &[f32], nframes: usize) -> Vec<bool> {
1916 const RATIO: f32 = 10.0;
1917 let ratios = frame_attack_ratios(chan, nframes);
1918 (0..nframes)
1919 .map(|f| f > 0 && ratios.get(f).copied().unwrap_or(1.0) > RATIO)
1920 .collect()
1921}
1922
1923/// Assign a valid AAC window sequence to each frame from the transient flags. A
1924/// short run is bracketed by LongStart/LongStop; runs a single frame apart are
1925/// merged (a lone gap can't be both a stop and a start).
1926fn assign_sequences(transient: &[bool]) -> Vec<WindowSequence> {
1927 use WindowSequence::*;
1928 let n = transient.len();
1929 let mut short = transient.to_vec();
1930 for i in 1..n.saturating_sub(1) {
1931 if !short[i] && short[i - 1] && short[i + 1] {
1932 short[i] = true;
1933 }
1934 }
1935 let mut seq = vec![OnlyLong; n];
1936 let mut i = 0;
1937 while i < n {
1938 if short[i] {
1939 let a = i;
1940 while i < n && short[i] {
1941 seq[i] = EightShort;
1942 i += 1;
1943 }
1944 if a > 0 {
1945 seq[a - 1] = LongStart;
1946 }
1947 if i < n {
1948 seq[i] = LongStop;
1949 }
1950 } else {
1951 i += 1;
1952 }
1953 }
1954 seq
1955}
1956
1957/// Cheapest codebook (and its bit cost) for one SFB across all short windows of a
1958/// single group, matched to how the decoder reads it (per-SFB codebook, per-window
1959/// coefficients).
1960fn best_codebook_short(quant: &[i32], swb: &[u16], sfb: usize, nwin: usize) -> (u8, usize) {
1961 let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
1962 let mut maxq = 0u32;
1963 for win in 0..nwin {
1964 let base = win * SHORT_HALF;
1965 for &q in &quant[base + s..base + e] {
1966 maxq = maxq.max(q.unsigned_abs());
1967 }
1968 }
1969 if maxq == 0 {
1970 return (ZERO_HCB, 0);
1971 }
1972 let mut best = (ESC_HCB, usize::MAX);
1973 for cb in 1..=11u8 {
1974 let meta = &CODEBOOKS[cb as usize];
1975 let dim = meta.dim as usize;
1976 if (e - s) % dim != 0 || (!meta.esc && (meta.lav as u32) < maxq) {
1977 continue;
1978 }
1979 let mut bits = 0usize;
1980 let mut ok = true;
1981 'windows: for win in 0..nwin {
1982 let base = win * SHORT_HALF;
1983 let mut i = s;
1984 while i < e {
1985 match spectral_bits(cb as usize, &quant[base + i..base + i + dim]) {
1986 Some(b) => bits += b,
1987 None => {
1988 ok = false;
1989 break 'windows;
1990 }
1991 }
1992 i += dim;
1993 }
1994 }
1995 if ok && bits < best.1 {
1996 best = (cb, bits);
1997 }
1998 }
1999 best
2000}
2001
2002/// Bits for short-block section_data (3-bit run-length increments, esc = 7).
2003fn section_bits_short(cbs: &[u8]) -> usize {
2004 let esc = 7usize;
2005 let mut bits = 0usize;
2006 let mut k = 0usize;
2007 while k < cbs.len() {
2008 let cb = cbs[k];
2009 let mut len = 1usize;
2010 while k + len < cbs.len() && cbs[k + len] == cb {
2011 len += 1;
2012 }
2013 bits += 4;
2014 let mut l = len;
2015 while l >= esc {
2016 bits += 3;
2017 l -= esc;
2018 }
2019 bits += 3;
2020 k += len;
2021 }
2022 bits
2023}
2024
2025/// Quantize all eight short windows with a per-SFB scalefactor (one group; flat
2026/// this brick), pick per-SFB codebooks, and return (codebooks, body bits, max_sfb,
2027/// window-major quantized spectrum).
2028fn code_frame_short(xp: &Xpow, swb: &[u16], sf: &[i32]) -> (Vec<u8>, usize, usize, Vec<i32>) {
2029 work::bump_code_frame();
2030 let num_swb = swb.len() - 1;
2031 work::bump_quant_bands(((swb.len() - 1) * 8) as u64);
2032 let scale = scale_table();
2033 let mut quant = vec![0i32; FRAME_LEN];
2034 for win in 0..8 {
2035 let base = win * SHORT_HALF;
2036 for sfb in 0..num_swb {
2037 let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
2038 let sc = scale[sf[sfb].clamp(0, 255) as usize];
2039 quantize_band(
2040 &xp.pow[base + s..base + e],
2041 &xp.sign[base + s..base + e],
2042 sc,
2043 &mut quant[base + s..base + e],
2044 );
2045 }
2046 }
2047 let mut max_sfb = 0usize;
2048 for sfb in 0..num_swb {
2049 let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
2050 if (0..8).any(|win| {
2051 let base = win * SHORT_HALF;
2052 quant[base + s..base + e].iter().any(|&q| q != 0)
2053 }) {
2054 max_sfb = sfb + 1;
2055 }
2056 }
2057 let mut cbs = Vec::with_capacity(max_sfb);
2058 let mut spec_bits = 0usize;
2059 for sfb in 0..max_sfb {
2060 let (cb, bits) = best_codebook_short(&quant, swb, sfb, 8);
2061 cbs.push(cb);
2062 spec_bits += bits;
2063 }
2064 let gg = global_gain(&cbs, sf);
2065 // global_gain(8) + ics_info(short ~18) + 3 flags + sections + scalefactors + spectrum.
2066 let body = 8 + 18 + 3 + section_bits_short(&cbs) + scalefactor_bits(&cbs, sf, gg) + spec_bits;
2067 (cbs, body, max_sfb, quant)
2068}
2069
2070/// The smallest flat scalefactor that avoids clamping the loudest short coefficient
2071/// past `MAX_QUANT`.
2072fn min_base_short(xp: &Xpow) -> i32 {
2073 let maxp = xp.max_pow(0, xp.len());
2074 if maxp <= 1e-9 {
2075 return 0;
2076 }
2077 (100.0 - (MAX_QUANT as f64 / maxp).log2() / 0.1875)
2078 .ceil()
2079 .clamp(0.0, 255.0) as i32
2080}
2081
2082/// **Arm A1 — the short-block psychoacoustic model.**
2083///
2084/// Per-SFB scalefactor offsets for an EightShort frame. The band energies are
2085/// summed **across the eight windows** of the group, because with one window group
2086/// a scalefactor covers band `b` of all eight windows — so the mask must be
2087/// computed over exactly the coefficients that scalefactor governs.
2088///
2089/// The band geometry is the short SWB table over a 128-coefficient window, hence
2090/// `n_coeffs = SHORT_HALF`: reusing the long block's 1024 here would place every
2091/// band three octaves too low and spread the mask against the wrong neighbours.
2092///
2093/// Before this arm, short blocks coded with **flat** scalefactors — no noise
2094/// shaping at all on precisely the content where masking matters most.
2095///
2096/// # MEASURED REFUTATION (2026-08-08): this is harmful WITHOUT window grouping
2097///
2098/// Once arm A9 made short blocks actually occur, A1 became measurable — and it
2099/// made things **worse**, on both the class it was built for and the one it was
2100/// meant to be neutral on:
2101///
2102/// | arm | percussive 64k/128k | speech-clean 64k/128k |
2103/// |---|---|---|
2104/// | A9 alone | −2.81 / −6.10 | +1.56 / +1.18 |
2105/// | A9 + A1 | −1.18 / −5.50 | +2.33 / +1.46 |
2106///
2107/// The cause is the group-summed energy above. With **one** window group a single
2108/// scalefactor governs band `b` of all eight windows, so the mask must be derived
2109/// from their sum — which hands the quiet pre-attack windows a mask sized by the
2110/// attack. That is precisely the pre-echo the tool was supposed to suppress: a
2111/// flat scalefactor at least errs uniformly, whereas an attack-sized mask
2112/// actively licenses noise where the ear is most sensitive.
2113///
2114/// **This overturns a plan correction I made earlier.** Reading the emit path, I
2115/// argued grouping was a follow-up rather than a prerequisite, because per-SFB
2116/// shaping is available with one group. That is true and irrelevant: the shaping
2117/// available with one group is shaping in the *wrong domain*. Arm 1a (window
2118/// grouping) is a genuine prerequisite for A1, exactly as the original plan said.
2119/// Do not enable `short_block_psy` before grouping exists.
2120fn perceptual_offsets_short(spec: &[f32], swb: &[u16], sample_rate: u32, tonality_smr: bool) -> Vec<i32> {
2121 let num_swb = swb.len() - 1;
2122 let mut energy = vec![0.0f64; num_swb];
2123 let mut noise_scale = vec![0.0f64; num_swb];
2124 for sfb in 0..num_swb {
2125 let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
2126 for win in 0..8 {
2127 let base = win * SHORT_HALF;
2128 for k in s..e {
2129 let Some(&x) = spec.get(base + k) else { continue };
2130 energy[sfb] += (x as f64) * (x as f64);
2131 noise_scale[sfb] += (x.abs() as f64).sqrt();
2132 }
2133 }
2134 }
2135 let mut e_masked: Vec<f64> = energy.iter().map(|&e| e + 1e-3).collect();
2136 let ton = tonality_smr.then(|| band_tonality(spec, swb, 8, SHORT_HALF));
2137 let thr = masking_from_energy(&e_masked, swb, sample_rate, SHORT_HALF, ton.as_deref());
2138 e_masked.clear();
2139
2140 let raw: Vec<f64> = (0..num_swb)
2141 .map(|sfb| (thr[sfb] / (noise_scale[sfb] + 1e-6)).log2() / 0.375)
2142 .collect();
2143 // Centre on the energy-bearing bands, exactly as the long-block path does.
2144 let etot: f64 = energy.iter().sum::<f64>() + 1e-9;
2145 let center: f64 = (0..num_swb).map(|i| raw[i] * energy[i]).sum::<f64>() / etot;
2146 raw.iter()
2147 .map(|&r| ((r - center).round() as i32).clamp(-60, 60))
2148 .collect()
2149}
2150
2151/// Rate loop for a short block: smallest common base (≥ no-clamp floor) whose body
2152/// fits `target_bits`. `offsets` is arm A1's per-band shape (all zeros reproduces
2153/// the flat-scalefactor behavior byte-identically).
2154fn rate_loop_short(xp: &Xpow, swb: &[u16], offsets: &[i32], target_bits: usize) -> i32 {
2155 let mut lo = min_base_short(xp);
2156 let mut hi = 255i32;
2157 while lo < hi {
2158 let mid = (lo + hi) / 2;
2159 let sf = scalefactors(offsets, mid);
2160 if code_frame_short(xp, swb, &sf).1 <= target_bits {
2161 hi = mid;
2162 } else {
2163 lo = mid + 1;
2164 }
2165 }
2166 lo
2167}
2168
2169/// short_block section_data (4-bit codebook + 3-bit run increments, esc = 7).
2170fn write_sections_short(w: &mut BitWriter, cbs: &[u8]) {
2171 let esc = 7u32;
2172 let mut k = 0usize;
2173 while k < cbs.len() {
2174 let cb = cbs[k];
2175 let mut len = 1usize;
2176 while k + len < cbs.len() && cbs[k + len] == cb {
2177 len += 1;
2178 }
2179 w.write(cb as u32, 4);
2180 let mut l = len as u32;
2181 while l >= esc {
2182 w.write(esc, 3);
2183 l -= esc;
2184 }
2185 w.write(l, 3);
2186 k += len;
2187 }
2188}
2189
2190/// short_block spectral_data: per SFB, per window (one group), coefficient tuples.
2191fn write_spectrum_short(w: &mut BitWriter, quant: &[i32], cbs: &[u8], swb: &[u16]) {
2192 for (sfb, &cb) in cbs.iter().enumerate() {
2193 if cb == ZERO_HCB {
2194 continue;
2195 }
2196 let dim = CODEBOOKS[cb as usize].dim as usize;
2197 let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
2198 for win in 0..8 {
2199 let base = win * SHORT_HALF;
2200 let mut i = s;
2201 while i + dim <= e {
2202 spectral_emit(cb as usize, &quant[base + i..base + i + dim], w);
2203 i += dim;
2204 }
2205 }
2206 }
2207}
2208
2209/// Encode one channel as an EightShort single_channel_element (one group of 8
2210/// windows). Scalefactors are flat unless arm A1 (`psy.short_block_psy`) supplies
2211/// a per-band shape.
2212#[allow(clippy::too_many_arguments)]
2213fn encode_channel_element_short(
2214 w: &mut BitWriter,
2215 tag: u32,
2216 spec: &[f32],
2217 swb: &[u16],
2218 target_bits: usize,
2219 cur_kbd: bool,
2220 sample_rate: u32,
2221 psy: PsyCfg,
2222) {
2223 let xp = Xpow::new(spec);
2224 // Arm A1: a real per-band mask, or the flat fallback (all-zero offsets
2225 // reproduce the shipped behavior byte-identically).
2226 let offsets = if psy.short_block_psy {
2227 perceptual_offsets_short(spec, swb, sample_rate, psy.tonality_smr)
2228 } else {
2229 vec![0i32; swb.len() - 1]
2230 };
2231 let base = rate_loop_short(&xp, swb, &offsets, target_bits);
2232 let sf = scalefactors(&offsets, base);
2233 let (cbs, _, max_sfb, quant) = code_frame_short(&xp, swb, &sf);
2234 let gg = global_gain(&cbs, &sf);
2235
2236 w.write(ID_SCE, 3);
2237 w.write(tag, 4);
2238 w.write(gg as u32, 8);
2239 let info = IcsInfo {
2240 window_sequence: WindowSequence::EightShort,
2241 window_shape_kbd: cur_kbd,
2242 max_sfb: max_sfb as u8,
2243 num_windows: 8,
2244 num_window_groups: 1,
2245 window_group_length: vec![8],
2246 num_swb: swb.len() - 1,
2247 };
2248 encode_ics_info(w, &info);
2249 write_sections_short(w, &cbs);
2250 write_scalefactors(w, &cbs, &sf, gg);
2251 w.write(0, 1); // pulse_data_present
2252 w.write(0, 1); // tns_data_present
2253 w.write(0, 1); // gain_control_data_present
2254 write_spectrum_short(w, &quant, &cbs, swb);
2255}
2256
2257// ---------------------------------------------------------------------------
2258// Stereo (brick 6) — a channel_pair_element with a common window and per-SFB M/S
2259// (mid/side) coding where the channels are correlated enough to pay off.
2260// ---------------------------------------------------------------------------
2261
2262/// Per-SFB M/S decision + mixed spectra. M/S wins when `E_M·E_S < E_L·E_R` (the
2263/// correlation criterion — raw energy always halves under the ½ scaling, so the
2264/// *product* is what predicts bit savings). Returns (ch0 = M or L, ch1 = S or R,
2265/// per-SFB ms_used).
2266fn mid_side(
2267 l: &[f32],
2268 r: &[f32],
2269 swb: &[u16],
2270 is_short: bool,
2271 is_veto: &[bool],
2272) -> (Vec<f32>, Vec<f32>, Vec<bool>) {
2273 let num_swb = swb.len() - 1;
2274 let nwin = if is_short { 8 } else { 1 };
2275 let wlen = if is_short { SHORT_HALF } else { FRAME_LEN };
2276 let mut ch0 = l.to_vec();
2277 let mut ch1 = r.to_vec();
2278 let mut ms = vec![false; num_swb];
2279 for sfb in 0..num_swb {
2280 let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
2281 let (mut el, mut er, mut em, mut es) = (0.0f64, 0.0, 0.0, 0.0);
2282 for win in 0..nwin {
2283 let base = win * wlen;
2284 for i in s..e {
2285 let (lv, rv) = (l[base + i] as f64, r[base + i] as f64);
2286 let (m, sd) = ((lv + rv) * 0.5, (lv - rv) * 0.5);
2287 el += lv * lv;
2288 er += rv * rv;
2289 em += m * m;
2290 es += sd * sd;
2291 }
2292 }
2293 // A band claimed by intensity stereo (arm A7) must stay L/R.
2294 if em * es < el * er && !is_veto.get(sfb).copied().unwrap_or(false) {
2295 ms[sfb] = true;
2296 for win in 0..nwin {
2297 let base = win * wlen;
2298 for i in s..e {
2299 let (lv, rv) = (l[base + i], r[base + i]);
2300 ch0[base + i] = (lv + rv) * 0.5;
2301 ch1[base + i] = (lv - rv) * 0.5;
2302 }
2303 }
2304 }
2305 }
2306 (ch0, ch1, ms)
2307}
2308
2309/// Quantize one CPE channel to a target: psy per-band scalefactors (long) or flat
2310/// (short). Returns (per-SFB scalefactors, quantized spectrum).
2311fn quantize_channel(
2312 spec: &[f32],
2313 swb: &[u16],
2314 is_short: bool,
2315 sample_rate: u32,
2316 target_bits: usize,
2317 psy: PsyCfg,
2318) -> (Vec<i32>, Vec<i32>) {
2319 let xp = Xpow::new(spec);
2320 if is_short {
2321 let offsets = if psy.short_block_psy {
2322 perceptual_offsets_short(spec, swb, sample_rate, psy.tonality_smr)
2323 } else {
2324 vec![0i32; swb.len() - 1]
2325 };
2326 let base = rate_loop_short(&xp, swb, &offsets, target_bits);
2327 let sf = scalefactors(&offsets, base);
2328 let (_, _, _, quant) = code_frame_short(&xp, swb, &sf);
2329 (sf, quant)
2330 } else {
2331 let offsets = perceptual_offsets(spec, swb, sample_rate, psy.tonality_smr);
2332 let base = rate_loop(&xp, swb, &offsets, target_bits);
2333 let sf = scalefactors(&offsets, base);
2334 let (_, _, _, quant) = code_frame(&xp, swb, &sf);
2335 (sf, quant)
2336 }
2337}
2338
2339/// The highest SFB with a non-zero coefficient in either channel (both channels of
2340/// a common-window CPE share `max_sfb`).
2341fn joint_max_sfb(q0: &[i32], q1: &[i32], swb: &[u16], is_short: bool) -> usize {
2342 let num_swb = swb.len() - 1;
2343 let nwin = if is_short { 8 } else { 1 };
2344 let wlen = if is_short { SHORT_HALF } else { FRAME_LEN };
2345 let nz = |q: &[i32], s: usize, e: usize| {
2346 (0..nwin).any(|win| {
2347 let b = win * wlen;
2348 q[b + s..b + e].iter().any(|&x| x != 0)
2349 })
2350 };
2351 let mut m = 0;
2352 for sfb in 0..num_swb {
2353 let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
2354 if nz(q0, s, e) || nz(q1, s, e) {
2355 m = sfb + 1;
2356 }
2357 }
2358 m
2359}
2360
2361/// Per-SFB codebooks for one channel over `0..max_sfb`.
2362fn codebooks(quant: &[i32], swb: &[u16], is_short: bool, max_sfb: usize) -> Vec<u8> {
2363 (0..max_sfb)
2364 .map(|sfb| {
2365 if is_short {
2366 best_codebook_short(quant, swb, sfb, 8).0
2367 } else {
2368 let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
2369 best_codebook_for_band(quant, s, e).0
2370 }
2371 })
2372 .collect()
2373}
2374
2375/// ms_mask_present (2 bits) + the per-SFB mask when mixed.
2376fn write_ms_used(w: &mut BitWriter, ms_used: &[bool]) {
2377 if ms_used.iter().all(|&b| !b) {
2378 w.write(0, 2);
2379 } else if ms_used.iter().all(|&b| b) {
2380 w.write(2, 2);
2381 } else {
2382 w.write(1, 2);
2383 for &b in ms_used {
2384 w.write_bool(b);
2385 }
2386 }
2387}
2388
2389/// One channel's individual_channel_stream body inside a common-window CPE:
2390/// global_gain, section_data, scale_factor_data, the three flag bits, spectral_data
2391/// (no ics_info — it is shared).
2392fn write_channel_data(
2393 w: &mut BitWriter,
2394 cbs: &[u8],
2395 sf: &[i32],
2396 quant: &[i32],
2397 swb: &[u16],
2398 is_short: bool,
2399) {
2400 let gg = global_gain(cbs, sf);
2401 w.write(gg as u32, 8);
2402 if is_short {
2403 write_sections_short(w, cbs);
2404 } else {
2405 write_sections(w, cbs);
2406 }
2407 write_scalefactors(w, cbs, sf, gg);
2408 w.write(0, 1); // pulse_data_present
2409 w.write(0, 1); // tns_data_present
2410 w.write(0, 1); // gain_control_data_present
2411 if is_short {
2412 write_spectrum_short(w, quant, cbs, swb);
2413 } else {
2414 write_spectrum(w, quant, cbs, swb);
2415 }
2416}
2417
2418/// **Arm A13 — joint rate loop over a channel pair.**
2419///
2420/// # The defect this fixes
2421///
2422/// A CPE's two channels were each given `frame_budget / channel_count` bits and
2423/// run through **independent** rate loops. That is a fixed 50/50 split, so when
2424/// M/S makes the side channel nearly empty its bits are simply wasted — the mid
2425/// channel, which is what the listener hears, still gets only half the frame.
2426///
2427/// Measured on perfectly-correlated stereo (`L == R`, so `S ≡ 0`) at 128 kbps,
2428/// per-channel reconstruction SNR:
2429///
2430/// | encoder | SNR |
2431/// |---|---|
2432/// | independent per-channel loops | **10.6 dB** |
2433/// | ffmpeg native AAC | **38.8 dB** |
2434///
2435/// # Why the obvious fix did not work
2436///
2437/// The first attempt split the budget by each channel's perceptual entropy. It
2438/// made things *worse* (8.5 dB), because PE is degenerate under a purely
2439/// relative masking model: the mask is `SMR × spread(signal)`, so `E/thr ≈
2440/// 1/SMR` for **any** non-silent channel regardless of its level. Both channels
2441/// report near-identical "demand" whatever they contain. A level-blind demand
2442/// estimate cannot allocate between levels.
2443///
2444/// # What actually works
2445///
2446/// Run **one** rate loop over the pair and give both channels a **common base**
2447/// scalefactor. A common base means a common quantizer step, i.e. both channels
2448/// are coded to the same noise floor relative to their own masks — which is the
2449/// textbook joint-stereo criterion. Bits then flow to whichever channel needs
2450/// them, because a near-empty side channel costs almost nothing at any base and
2451/// lets the loop settle on a finer base for the pair.
2452///
2453/// This is a strict generalisation: for two channels of equal demand it lands on
2454/// the same place the independent loops did.
2455fn pair_body_bits(
2456 xp0: &Xpow,
2457 off0: &[i32],
2458 xp1: &Xpow,
2459 off1: &[i32],
2460 swb: &[u16],
2461 base: i32,
2462 is_short: bool,
2463 quant: &mut [i32],
2464) -> usize {
2465 let (b0, b1) = if is_short {
2466 (
2467 code_frame_short(xp0, swb, &scalefactors(off0, base)).1,
2468 code_frame_short(xp1, swb, &scalefactors(off1, base)).1,
2469 )
2470 } else {
2471 (
2472 code_core(xp0, swb, &scalefactors(off0, base), quant).1,
2473 code_core(xp1, swb, &scalefactors(off1, base), quant).1,
2474 )
2475 };
2476 b0 + b1
2477}
2478
2479/// Smallest common base whose combined body fits `target_total` bits.
2480#[allow(clippy::too_many_arguments)]
2481fn joint_rate_loop(
2482 xp0: &Xpow,
2483 off0: &[i32],
2484 xp1: &Xpow,
2485 off1: &[i32],
2486 swb: &[u16],
2487 target_total: usize,
2488 is_short: bool,
2489) -> i32 {
2490 let lo0 = if is_short { min_base_short(xp0) } else { min_base(xp0, swb, off0) };
2491 let lo1 = if is_short { min_base_short(xp1) } else { min_base(xp1, swb, off1) };
2492 let mut lo = lo0.max(lo1);
2493 let mut hi = 255i32;
2494 let mut quant = vec![0i32; xp0.len().max(xp1.len())];
2495 while lo < hi {
2496 let mid = (lo + hi) / 2;
2497 if pair_body_bits(xp0, off0, xp1, off1, swb, mid, is_short, &mut quant) <= target_total {
2498 hi = mid;
2499 } else {
2500 lo = mid + 1;
2501 }
2502 }
2503 lo
2504}
2505
2506/// **Arm A7 — intensity stereo.**
2507///
2508/// Above a cutoff the ear localizes by ENVELOPE rather than waveform, so a band
2509/// of the second channel can be sent as a single scale factor applied to the
2510/// first: the decoder reconstructs `s1 = +-0.5^(0.25*is_pos) * s0`
2511/// (`decode::apply_is`). One value replaces a whole band's spectrum.
2512///
2513/// This turns the stereo decision from binary into a **3-arm dispatch** —
2514/// `{L/R, M/S, IS}` — which is why it is applied after `mid_side` and only to
2515/// bands M/S declined: with `ms_used` set the pair is already (M, S), and
2516/// intensity on an S channel means something quite different from intensity on
2517/// an R channel. Restricting to the M/S-declined bands keeps the two tools from
2518/// interpreting each other's output.
2519///
2520/// The anti-class is wide-stereo music, where collapsing a band to a scaled copy
2521/// destroys the image. Hence the correlation gate: only bands where the channels
2522/// genuinely already agree up to a gain.
2523/// **Arm A7 — intensity stereo.**
2524///
2525/// Above a cutoff the ear localizes by ENVELOPE rather than waveform, so a band
2526/// of the right channel can be sent as a single scale factor applied to the left:
2527/// the decoder reconstructs `R = +-0.5^(0.25*is_pos) * L` (`decode::apply_is`).
2528/// One value replaces a whole band's spectrum.
2529///
2530/// # Why this decides BEFORE `mid_side`, not after
2531///
2532/// The first version ran after M/S and only touched bands M/S had declined — on
2533/// the reasoning that intensity on an S channel means something different from
2534/// intensity on an R channel. It never fired once. The bands where `R ~= k*L`
2535/// are exactly the bands where M/S wins (`E_M*E_S << E_L*E_R` for a scaled copy),
2536/// so "M/S declined it" and "intensity wants it" are near-disjoint by
2537/// construction.
2538///
2539/// So intensity is decided on the ORIGINAL L/R spectra and **vetoes M/S** on the
2540/// bands it claims, which also keeps the decoder's sign rule simple: `apply_is`
2541/// flips the intensity sign when `ms_used` is set, and a band that is both is a
2542/// sign error waiting to happen.
2543///
2544/// This makes the stereo decision a genuine **3-arm dispatch** — `{L/R, M/S, IS}`
2545/// — rather than two tools overwriting each other. The anti-class is wide-stereo
2546/// music, where collapsing a band to a scaled copy destroys the image; hence the
2547/// correlation gate.
2548fn intensity_decision(
2549 spec_l: &[f32],
2550 spec_r: &[f32],
2551 swb: &[u16],
2552 sample_rate: u32,
2553) -> Vec<Option<(u8, i32)>> {
2554 /// Below this the ear localizes by waveform and intensity stereo is audible.
2555 const IS_MIN_HZ: f64 = 6000.0;
2556 /// How well `R ~= scale * L` must already hold, as |cos| between the bands.
2557 const IS_MIN_CORR: f64 = 0.85;
2558
2559 let num_swb = swb.len() - 1;
2560 let mut out = vec![None; num_swb];
2561 for sfb in 0..num_swb {
2562 let lo_hz = swb[sfb] as f64 * sample_rate as f64 * 0.5 / FRAME_LEN as f64;
2563 if lo_hz < IS_MIN_HZ {
2564 continue;
2565 }
2566 let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
2567 let e = e.min(spec_l.len()).min(spec_r.len());
2568 if e <= s {
2569 continue;
2570 }
2571 let (mut dot, mut e0, mut e1) = (0f64, 0f64, 0f64);
2572 for i in s..e {
2573 let (a, b) = (spec_l[i] as f64, spec_r[i] as f64);
2574 dot += a * b;
2575 e0 += a * a;
2576 e1 += b * b;
2577 }
2578 if e0 <= 1.0 || e1 <= 1.0 {
2579 continue;
2580 }
2581 if (dot / (e0.sqrt() * e1.sqrt())).abs() < IS_MIN_CORR {
2582 continue;
2583 }
2584 // Least-squares gain, then the syntax's log grid:
2585 // scale = 0.5^(0.25*is_pos) => is_pos = -4*log2(|scale|).
2586 let scale = dot / e0;
2587 if scale.abs() < 1e-6 {
2588 continue;
2589 }
2590 let is_pos = (-4.0 * scale.abs().log2()).round() as i32;
2591 if !(-20..=60).contains(&is_pos) {
2592 continue;
2593 }
2594 out[sfb] = Some((
2595 if scale >= 0.0 {
2596 INTENSITY_HCB
2597 } else {
2598 INTENSITY_HCB2
2599 },
2600 is_pos,
2601 ));
2602 }
2603 out
2604}
2605
2606/// Encode a stereo pair as a common-window channel_pair_element with per-SFB M/S.
2607#[allow(clippy::too_many_arguments)]
2608fn encode_cpe(
2609 w: &mut BitWriter,
2610 tag: u32,
2611 spec_l: &[f32],
2612 spec_r: &[f32],
2613 swb: &[u16],
2614 seq: WindowSequence,
2615 sample_rate: u32,
2616 target_bits: usize,
2617 cur_kbd: bool,
2618 psy: PsyCfg,
2619) {
2620 let is_short = seq == WindowSequence::EightShort;
2621 // Arm A7 decides first, on the untouched L/R spectra, and vetoes M/S on the
2622 // bands it claims.
2623 let is_bands = if psy.intensity && !is_short {
2624 intensity_decision(spec_l, spec_r, swb, sample_rate)
2625 } else {
2626 vec![None; swb.len() - 1]
2627 };
2628 let is_veto: Vec<bool> = is_bands.iter().map(|b| b.is_some()).collect();
2629 let (ch0, ch1, ms_full) = mid_side(spec_l, spec_r, swb, is_short, &is_veto);
2630 // Arm A13 ROUTING GATE.
2631 //
2632 // The joint loop is a large win when the pair is CORRELATED and a loss when
2633 // it is not — a per-class sign flip, so it is routed rather than averaged:
2634 //
2635 // | content | 64k | 128k |
2636 // |---|---|---|
2637 // | guitar stereo (correlated) | +0.23 | **+1.15** |
2638 // | piano stereo (correlated) | +0.01 | +0.26 |
2639 // | wide/decorrelated stereo | −0.30 | −0.04 |
2640 //
2641 // The signal is already in hand: the fraction of coded bands M/S claimed.
2642 // High means the two channels largely agree, so the side channel is cheap and
2643 // a common base lets the mid channel take the bits it is wasting. Low means
2644 // both channels carry independent content, both genuinely need their half,
2645 // and forcing a common base starves whichever is harder.
2646 //
2647 // The signal is the pair's spectral correlation, measured directly. (The M/S
2648 // flag fraction was tried first and does not separate: M/S still claims most
2649 // bands on wide content because it only needs `E_M·E_S < E_L·E_R`, which a
2650 // shared centre image satisfies.) Measured correlations:
2651 //
2652 // L == R (ideal) 1.00 -> joint wins hugely
2653 // guitar stereo 0.84 -> joint wins +1.15 @128k
2654 // piano stereo 0.47 -> joint wins +0.26 @128k
2655 // synthetic wide 0.25 -> joint LOSES -0.30 @64k
2656 //
2657 // The threshold sits in the wide gap between 0.25 and 0.47.
2658 let joint_ok = pair_correlation(spec_l, spec_r) >= JOINT_STEREO_MIN_CORR;
2659
2660 let (sf0, quant0, sf1, quant1) = if psy.stereo_bit_split && joint_ok {
2661 let off = |spec: &[f32]| -> Vec<i32> {
2662 if is_short {
2663 if psy.short_block_psy {
2664 perceptual_offsets_short(spec, swb, sample_rate, psy.tonality_smr)
2665 } else {
2666 vec![0i32; swb.len() - 1]
2667 }
2668 } else {
2669 perceptual_offsets(spec, swb, sample_rate, psy.tonality_smr)
2670 }
2671 };
2672 let (o0, o1) = (off(&ch0), off(&ch1));
2673 let (xp0, xp1) = (Xpow::new(&ch0), Xpow::new(&ch1));
2674 let base = joint_rate_loop(&xp0, &o0, &xp1, &o1, swb, target_bits * 2, is_short);
2675 let (s0, s1) = (scalefactors(&o0, base), scalefactors(&o1, base));
2676 let q0 = if is_short {
2677 code_frame_short(&xp0, swb, &s0).3
2678 } else {
2679 code_frame(&xp0, swb, &s0).3
2680 };
2681 let q1 = if is_short {
2682 code_frame_short(&xp1, swb, &s1).3
2683 } else {
2684 code_frame(&xp1, swb, &s1).3
2685 };
2686 (s0, q0, s1, q1)
2687 } else {
2688 let (a, b) = quantize_channel(&ch0, swb, is_short, sample_rate, target_bits, psy);
2689 let (c, d) = quantize_channel(&ch1, swb, is_short, sample_rate, target_bits, psy);
2690 (a, b, c, d)
2691 };
2692 let max_sfb = joint_max_sfb(&quant0, &quant1, swb, is_short);
2693 let cbs0 = codebooks(&quant0, swb, is_short, max_sfb);
2694 let mut cbs1 = codebooks(&quant1, swb, is_short, max_sfb);
2695 let mut sf1 = sf1;
2696 let mut ms_full = ms_full;
2697
2698 // Arm A7 — stamp the claimed bands into channel 1's codebooks/scalefactors.
2699 for (sfb, band) in is_bands.iter().enumerate().take(max_sfb) {
2700 if let (Some((cb, is_pos)), Some(slot)) = (band, cbs1.get_mut(sfb)) {
2701 *slot = *cb;
2702 sf1[sfb] = *is_pos;
2703 if let Some(m) = ms_full.get_mut(sfb) {
2704 *m = false;
2705 }
2706 }
2707 }
2708
2709 w.write(ID_CPE, 3);
2710 w.write(tag, 4);
2711 w.write(1, 1); // common_window
2712 let info = IcsInfo {
2713 window_sequence: seq,
2714 window_shape_kbd: cur_kbd,
2715 max_sfb: max_sfb as u8,
2716 num_windows: if is_short { 8 } else { 1 },
2717 num_window_groups: 1,
2718 window_group_length: vec![if is_short { 8 } else { 1 }],
2719 num_swb: swb.len() - 1,
2720 };
2721 encode_ics_info(w, &info);
2722 write_ms_used(w, &ms_full[..max_sfb]);
2723 write_channel_data(w, &cbs0, &sf0, &quant0, swb, is_short);
2724 write_channel_data(w, &cbs1, &sf1, &quant1, swb, is_short);
2725}
2726
2727// ---------------------------------------------------------------------------
2728// The encoder: buffers input, blocks into 1024-sample long frames, emits raw
2729// access units (add ADTS or MP4 framing around them as needed).
2730// ---------------------------------------------------------------------------
2731
2732/// Window-shape policy — **arm A8, Rung 0** of `docs/codec-aac-great-gate.md`.
2733///
2734/// `window_shape` is a *free syntax element*: one bit already carried in every
2735/// `ics_info`, costing nothing to set either way, with both shapes implemented on
2736/// the decode side since day one. It shipped hardcoded to sine — census category 3.
2737#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
2738pub enum WindowShape {
2739 /// Sine everywhere. **The neutral end**: byte-identical with the encoder as
2740 /// it shipped before Rung 0 (proven by `shape_sine_is_byte_identical`).
2741 #[default]
2742 Sine,
2743 /// KBD everywhere. Not a shipping mode — the *force-on* arm the calculator
2744 /// needs: great-gate §4 requires force-on-everywhere to nearly tie the anchor
2745 /// on the full ladder before a dispatch is built on it, because a big force-on
2746 /// gap predicts a dominated dispatch.
2747 Kbd,
2748 /// **PROVISIONAL** (law 5). Per-frame dispatch on content tonality. Off by
2749 /// default until the calculator banks a threshold from a harvest carrying the
2750 /// full speed pair (law 7's opt-in → default-on ladder).
2751 Auto,
2752}
2753
2754/// Encoder options.
2755#[derive(Debug, Clone, Copy)]
2756pub struct AacEncoderConfig {
2757 /// Target bitrate in bits per second. Drives the per-frame rate loop.
2758 /// Default: 128 000 (128 kbps).
2759 pub bitrate_bps: u32,
2760 /// Window-shape policy (arm A8). Default [`WindowShape::Sine`] — the
2761 /// byte-identical neutral end.
2762 pub window_shape: WindowShape,
2763 /// The [`WindowShape::Auto`] gate's threshold, as a **percentile of this
2764 /// clip's own** frame-tonality distribution (great-gate law 1: a
2765 /// population-relative threshold transfers to content the fit never saw; an
2766 /// absolute one does not). Frames above it code with KBD.
2767 ///
2768 /// Default 0.5 is a **placeholder, not a fitted value** — the calculator has
2769 /// not banked this rung yet. `aacharvest` emits the CSV that will decide it.
2770 pub shape_tonality_pct: f32,
2771 /// **Arm A1, Rung 1** — run the psychoacoustic model on short blocks instead
2772 /// of coding them with flat scalefactors. Default `false` (byte-identical).
2773 pub short_block_psy: bool,
2774 /// **Arm A2, Rung 2** — make the signal-to-mask ratio a function of band
2775 /// tonality instead of a flat 18 dB. Default `false` (byte-identical).
2776 pub tonality_smr: bool,
2777 /// **Arm A3, Rung 3** — emit TNS on long blocks. Default `false`
2778 /// (`tns_data_present = 0`, byte-identical).
2779 pub tns: bool,
2780 /// **Arm A9** — use the level-invariant transient detector. Default `false`
2781 /// (byte-identical). Arm A1 is unmeasurable without this.
2782 pub relative_transients: bool,
2783 /// **Arm A6** — Perceptual Noise Substitution on long blocks. Default `false`
2784 /// (byte-identical).
2785 pub pns: bool,
2786 /// **Arm A7** — intensity stereo on long-block CPEs. Default `false`
2787 /// (byte-identical).
2788 pub intensity: bool,
2789 /// **Arm A13** — split a channel pair's bit budget by perceptual demand
2790 /// rather than evenly. Default `false` (byte-identical).
2791 pub stereo_bit_split: bool,
2792}
2793
2794impl Default for AacEncoderConfig {
2795 fn default() -> Self {
2796 AacEncoderConfig {
2797 bitrate_bps: 128_000,
2798 window_shape: WindowShape::Sine,
2799 shape_tonality_pct: 0.5,
2800 short_block_psy: false,
2801 tonality_smr: false,
2802 tns: false,
2803 // DEFAULT ON — measured wins vs the previous default, PEAQ ODG:
2804 // A9 mean +0.267, worst +0.000 (percussive +1.8, clean speech
2805 // +1.1..+2.6, exactly 0.00 on every other class)
2806 // A13 guitar stereo +1.17 @128k, piano stereo +0.22, routed by
2807 // pair correlation so wide stereo is not harmed
2808 relative_transients: true,
2809 pns: false,
2810 intensity: false,
2811 stereo_bit_split: true,
2812 }
2813 }
2814}
2815
2816/// One encoded raw access unit (a `raw_data_block`, no ADTS framing).
2817#[derive(Debug, Clone)]
2818pub struct EncodedPacket {
2819 pub data: Vec<u8>,
2820 /// Presentation timestamp in samples (frame index × 1024).
2821 pub pts: i64,
2822 /// Duration in samples (always one AAC frame = 1024).
2823 pub duration: u32,
2824}
2825
2826/// AAC-LC encoder. Push PCM with [`push_pcm`](AacEncoder::push_pcm) (or
2827/// [`push_pcm_planar`](AacEncoder::push_pcm_planar)), call
2828/// [`finish`](AacEncoder::finish), then drain [`next_packet`](AacEncoder::next_packet)
2829/// until it returns [`Error::Eof`].
2830pub struct AacEncoder {
2831 sample_rate: u32,
2832 channels: usize,
2833 fs_index: u8,
2834 /// Target bitrate (bits/s). Drives the per-frame rate loop.
2835 bitrate: u32,
2836 /// Arm A8 policy and its provisional threshold.
2837 window_shape: WindowShape,
2838 shape_tonality_pct: f32,
2839 short_block_psy: bool,
2840 tonality_smr: bool,
2841 tns: bool,
2842 relative_transients: bool,
2843 pns: bool,
2844 intensity: bool,
2845 stereo_bit_split: bool,
2846 win: Vec<f32>,
2847 /// The KBD long window (α = 4.0), matching the decoder's. Built once.
2848 win_kbd: Vec<f32>,
2849 chans: Vec<Vec<f32>>,
2850 initialized: bool,
2851 /// Encoded raw access units (raw_data_block, no ADTS) awaiting `next_packet`,
2852 /// each with its sample-domain PTS. Filled on `finish`.
2853 queue: VecDeque<(Vec<u8>, i64)>,
2854 flushed: bool,
2855}
2856
2857impl AacEncoder {
2858 pub fn new(config: AacEncoderConfig) -> Self {
2859 AacEncoder {
2860 sample_rate: 0,
2861 channels: 0,
2862 fs_index: 0,
2863 bitrate: config.bitrate_bps.max(1),
2864 window_shape: config.window_shape,
2865 shape_tonality_pct: config.shape_tonality_pct,
2866 short_block_psy: config.short_block_psy,
2867 tonality_smr: config.tonality_smr,
2868 tns: config.tns,
2869 relative_transients: config.relative_transients,
2870 pns: config.pns,
2871 intensity: config.intensity,
2872 stereo_bit_split: config.stereo_bit_split,
2873 win: Vec::new(),
2874 win_kbd: Vec::new(),
2875 chans: Vec::new(),
2876 initialized: false,
2877 queue: VecDeque::new(),
2878 flushed: false,
2879 }
2880 }
2881
2882 /// The stream's sample rate (0 until the first PCM is pushed).
2883 pub fn sample_rate(&self) -> u32 {
2884 self.sample_rate
2885 }
2886
2887 /// The stream's channel count (0 until the first PCM is pushed).
2888 pub fn channels(&self) -> u16 {
2889 self.channels as u16
2890 }
2891
2892 /// Initialize (or validate) the stream parameters from a PCM push.
2893 fn init(&mut self, channels: u16, sample_rate: u32) -> Result<()> {
2894 if !self.initialized {
2895 self.sample_rate = sample_rate;
2896 self.channels = channels.max(1) as usize;
2897 // Reject counts with no `channel_configuration`. Writing a config the
2898 // element sequence does not match produces a stream that only our own
2899 // decoder accepts — the bug this check exists to make impossible.
2900 if element_plan(self.channels).is_none() {
2901 return Err(Error::unsupported(
2902 "aac encode: only 1-6 channels are supported (7+ needs a program_config_element, which is not implemented)",
2903 ));
2904 }
2905 self.fs_index = crate::sf_index_for_rate(sample_rate)
2906 .ok_or_else(|| Error::invalid("aac encode: unsupported sample rate"))?;
2907 self.win = crate::dsp::sine_window(LONG_N);
2908 // Arm A8's second shape. α = 4.0 for the long window matches the
2909 // decoder's `kbd` exactly — a mismatched α is not a quality choice,
2910 // it breaks TDAC and leaves audible seams at every overlap.
2911 self.win_kbd = crate::dsp::kbd_window(LONG_N, 4.0);
2912 self.chans = vec![Vec::new(); self.channels];
2913 self.initialized = true;
2914 } else if channels.max(1) as usize != self.channels {
2915 return Err(Error::invalid(
2916 "aac encode: channel count changed mid-stream",
2917 ));
2918 }
2919 Ok(())
2920 }
2921
2922 /// Buffer interleaved `f32` PCM in [-1, 1] (`interleaved.len()` must be a
2923 /// multiple of `channels`). The first push fixes the stream's channel count
2924 /// and sample rate.
2925 pub fn push_pcm(&mut self, interleaved: &[f32], channels: u16, sample_rate: u32) -> Result<()> {
2926 self.init(channels, sample_rate)?;
2927 let ch = self.channels;
2928 let n = interleaved.len() / ch;
2929 for i in 0..n {
2930 for c in 0..ch {
2931 self.chans[c].push(interleaved[i * ch + c]);
2932 }
2933 }
2934 Ok(())
2935 }
2936
2937 /// Buffer planar `f32` PCM, one slice per channel (`planes.len()` is the
2938 /// channel count; all planes the same length).
2939 pub fn push_pcm_planar(&mut self, planes: &[&[f32]], sample_rate: u32) -> Result<()> {
2940 self.init(planes.len() as u16, sample_rate)?;
2941 for (c, plane) in planes.iter().enumerate().take(self.channels) {
2942 self.chans[c].extend_from_slice(plane);
2943 }
2944 Ok(())
2945 }
2946
2947 /// Encode all buffered samples into per-frame raw access units (raw_data_block,
2948 /// no ADTS) with sample-domain PTS. A trailing all-zero block flushes the MDCT
2949 /// overlap so the final audio block decodes. Containers add their own framing
2950 /// (ADTS header for `.aac`, `esds` + raw samples for MP4).
2951 /// One block's samples for channel `ch` (zero-padded past the buffered input).
2952 fn block(&self, ch: usize, b: usize) -> [f32; FRAME_LEN] {
2953 let mut cur = [0f32; FRAME_LEN];
2954 for (i, s) in cur.iter_mut().enumerate() {
2955 *s = self.chans[ch]
2956 .get(b * FRAME_LEN + i)
2957 .copied()
2958 .unwrap_or(0.0);
2959 }
2960 cur
2961 }
2962
2963 /// Encode one frame `b` to its raw access unit + PTS. A pure function of the
2964 /// buffered input, the window sequences, and `b` — the previous block (for MDCT
2965 /// overlap) is just block `b-1`'s samples — so frames encode **independently**.
2966 #[allow(clippy::too_many_arguments)]
2967 #[allow(clippy::too_many_arguments)]
2968 fn encode_frame(
2969 &self,
2970 b: usize,
2971 swb: &[u16],
2972 swb_s: &[u16],
2973 sine_s: &[f32],
2974 kbd_s: &[f32],
2975 seqs: &[Vec<WindowSequence>],
2976 shapes: &[bool],
2977 per_channel: usize,
2978 plan: &[Elem],
2979 ) -> (Vec<u8>, i64) {
2980 let prev = |ch: usize| -> [f32; FRAME_LEN] {
2981 if b == 0 {
2982 [0f32; FRAME_LEN]
2983 } else {
2984 self.block(ch, b - 1)
2985 }
2986 };
2987 // Arm A8. The shape of frame b-1 owns this frame's LEFT overlap half, so
2988 // both are needed; the decoder seeds prev = sine at stream start.
2989 let cur_kbd = shapes.get(b).copied().unwrap_or(false);
2990 let prev_kbd = if b == 0 {
2991 false
2992 } else {
2993 shapes.get(b - 1).copied().unwrap_or(false)
2994 };
2995 let short_win: &[f32] = if cur_kbd { kbd_s } else { sine_s };
2996 let psy = PsyCfg {
2997 short_block_psy: self.short_block_psy,
2998 tonality_smr: self.tonality_smr,
2999 tns: self.tns,
3000 pns: self.pns,
3001 intensity: self.intensity,
3002 stereo_bit_split: self.stereo_bit_split,
3003 };
3004
3005 let mut rdb = BitWriter::new();
3006 // One pass over the ISO element sequence. `seqs` is indexed by ELEMENT,
3007 // not by channel: a CPE shares one window sequence across its pair, so
3008 // the two channels' transient flags were joined when the plan was built.
3009 for (ei, elem) in plan.iter().enumerate() {
3010 let seq = seqs[ei][b];
3011 let tag = ei as u32;
3012 match *elem {
3013 Elem::Cpe(l, r) => {
3014 let (p0, c0, p1, c1) = (prev(l), self.block(l, b), prev(r), self.block(r, b));
3015 if seq == WindowSequence::EightShort {
3016 let sl = analyze_short(&p0, &c0, short_win);
3017 let sr_ = analyze_short(&p1, &c1, short_win);
3018 encode_cpe(
3019 &mut rdb, tag, &sl, &sr_, swb_s, seq, self.sample_rate, per_channel,
3020 cur_kbd, psy,
3021 );
3022 } else {
3023 let win = long_window(
3024 seq, prev_kbd, cur_kbd, &self.win, &self.win_kbd, sine_s, kbd_s,
3025 );
3026 let sl = analyze_long(&p0, &c0, &win);
3027 let sr_ = analyze_long(&p1, &c1, &win);
3028 encode_cpe(
3029 &mut rdb, tag, &sl, &sr_, swb, seq, self.sample_rate, per_channel,
3030 cur_kbd, psy,
3031 );
3032 }
3033 }
3034 Elem::Sce(ch) | Elem::Lfe(ch) => {
3035 let (p, c) = (prev(ch), self.block(ch, b));
3036 let id = elem.id();
3037 if seq == WindowSequence::EightShort {
3038 let spec = analyze_short(&p, &c, short_win);
3039 encode_channel_element_short(
3040 &mut rdb,
3041 tag,
3042 &spec,
3043 swb_s,
3044 per_channel,
3045 cur_kbd,
3046 self.sample_rate,
3047 psy,
3048 );
3049 } else {
3050 let win = long_window(
3051 seq, prev_kbd, cur_kbd, &self.win, &self.win_kbd, sine_s, kbd_s,
3052 );
3053 let spec = analyze_long(&p, &c, &win);
3054 encode_channel_element(
3055 &mut rdb,
3056 tag,
3057 &spec,
3058 swb,
3059 seq,
3060 self.sample_rate,
3061 per_channel,
3062 cur_kbd,
3063 psy,
3064 id,
3065 );
3066 }
3067 }
3068 }
3069 }
3070 rdb.write(ID_END, 3);
3071 (rdb.into_bytes(), (b * FRAME_LEN) as i64)
3072 }
3073
3074 /// Transient flags for one channel, under the configured detector (arm A9).
3075 fn transients(&self, chan: &[f32], nframes: usize) -> Vec<bool> {
3076 if self.relative_transients {
3077 detect_transients_relative(chan, nframes)
3078 } else {
3079 detect_transients(chan, nframes)
3080 }
3081 }
3082
3083 /// **The Rung 0 gate.** Decide each frame's window shape.
3084 ///
3085 /// Computed as a whole-stream pre-pass, exactly like `detect_transients`, for
3086 /// two reasons: the decision is shared by both channels of a CPE (one common
3087 /// window), and frame b's window depends on frame b−1's shape — so deciding
3088 /// inside the frame-parallel worker would make the output depend on thread
3089 /// scheduling. Deciding up front keeps `encode_frame` independent and the
3090 /// encoder byte-deterministic (asserted by the lab's null arm).
3091 ///
3092 /// Threshold form: **per-clip percentile** of frame tonality (law 1), not an
3093 /// absolute. `Auto` is PROVISIONAL and off by default (law 7).
3094 fn decide_shapes(&self, nblocks: usize) -> Vec<bool> {
3095 match self.window_shape {
3096 WindowShape::Sine => vec![false; nblocks],
3097 WindowShape::Kbd => vec![true; nblocks],
3098 WindowShape::Auto => {
3099 // One reading per frame, from channel 0 (a CPE shares one window,
3100 // so the decision cannot be per-channel).
3101 let ton: Vec<f32> = (0..nblocks)
3102 .map(|b| time_tonality(&self.block(0, b)))
3103 .collect();
3104 let atk = frame_attack_ratios(&self.chans[0], nblocks);
3105
3106 let pct = |v: &[f32], q: f32| -> f32 {
3107 let mut s = v.to_vec();
3108 s.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
3109 let i = ((s.len().saturating_sub(1)) as f32 * q.clamp(0.0, 1.0)).round() as usize;
3110 s.get(i).copied().unwrap_or(f32::INFINITY)
3111 };
3112 let ton_thresh = pct(&ton, self.shape_tonality_pct);
3113 let atk_thresh = pct(&atk, SHAPE_ATTACK_VETO_PCT);
3114
3115 // A depth-2 transcribed tree (great-gate law 3: shallow, in plain
3116 // code, one documented feature per node).
3117 //
3118 // attack — a frame with a strong onset takes SINE, whatever its
3119 // tonality. KBD's wider main lobe smears transients in
3120 // time; the force-on ladder measured +18.6% audible on
3121 // the percussive class, the largest single effect in
3122 // the whole Rung 0 harvest.
3123 // tonality— among the remaining (stationary) frames, KBD's much
3124 // deeper stopband is worth having.
3125 //
3126 // The veto is why this gate is not simply "tonality > t": ringing
3127 // percussion reads as HIGHLY tonal (a struck resonator is a decaying
3128 // sinusoid), so a tonality-only rule routes exactly the frames that
3129 // KBD hurts most. The first fit did precisely that.
3130 // The veto spans a ±1-frame NEIGHBOURHOOD, not just the frame
3131 // itself. Overlap-add means frame b's window shapes the overlap
3132 // with both b−1 and b+1, so an onset in either neighbour is
3133 // analyzed partly through this frame's window. Vetoing only the
3134 // onset frame left the ring-down frame on KBD and kept the whole
3135 // percussive regression (+10.0% audible, barely half of force-on's
3136 // +18.6%) — the measurement that forced this widening.
3137 let vetoed: Vec<bool> = (0..nblocks)
3138 .map(|b| {
3139 let lo = b.saturating_sub(1);
3140 let hi = (b + 1).min(nblocks.saturating_sub(1));
3141 (lo..=hi).any(|k| atk.get(k).copied().unwrap_or(1.0) > atk_thresh)
3142 })
3143 .collect();
3144
3145 (0..nblocks)
3146 .map(|b| !vetoed[b] && ton[b] > ton_thresh)
3147 .collect()
3148 }
3149 }
3150 }
3151
3152 /// Encode all buffered frames to raw access units. Frames are independent, so
3153 /// they fan out across worker threads (ffmpeg's AAC encoder is single-threaded).
3154 fn encode_stream(&self) -> Vec<(Vec<u8>, i64)> {
3155 let swb = swb_offsets(true, self.fs_index);
3156 let swb_s = swb_offsets(false, self.fs_index);
3157 let sine_s = crate::dsp::sine_window(SHORT_N);
3158 // α = 6.0 for the short window, matching the decoder's `kbd_s`.
3159 let kbd_s = crate::dsp::kbd_window(SHORT_N, 6.0);
3160 let n = self.chans.first().map_or(0, |c| c.len());
3161 let nblocks = n.div_ceil(FRAME_LEN) + 1;
3162 // Per-channel ICS-body budget from the target bitrate (minus framing).
3163 let frame_budget = (self.bitrate as usize * FRAME_LEN / self.sample_rate.max(1) as usize)
3164 .saturating_sub(59); // ADTS header (56) + END (3)
3165 let per_channel = (frame_budget / self.channels.max(1)).saturating_sub(7); // element overhead
3166
3167 // The ISO element sequence for this channel count (validated at init, so
3168 // the unwrap cannot fire here).
3169 let plan = element_plan(self.channels).expect("channel count validated in init");
3170
3171 // Window sequences, **one per element**. A CPE shares a common window, so
3172 // its two channels' transient flags are joined; an LFE is long-only by
3173 // ISO rule, not by choice.
3174 let seqs: Vec<Vec<WindowSequence>> = plan
3175 .iter()
3176 .map(|e| match *e {
3177 Elem::Cpe(l, r) => {
3178 let t0 = self.transients(&self.chans[l], nblocks);
3179 let t1 = self.transients(&self.chans[r], nblocks);
3180 let joint: Vec<bool> = (0..nblocks).map(|b| t0[b] || t1[b]).collect();
3181 assign_sequences(&joint)
3182 }
3183 Elem::Sce(ch) => assign_sequences(&self.transients(&self.chans[ch], nblocks)),
3184 // lfe_channel_element carries no window-shape freedom.
3185 Elem::Lfe(_) => vec![WindowSequence::OnlyLong; nblocks],
3186 })
3187 .collect();
3188 // Arm A8: decide every frame's window shape up front, for the same reason
3189 // the sequences are decided up front — frame b's window depends on frame
3190 // b−1's shape, so this cannot live inside the parallel worker.
3191 let shapes = self.decide_shapes(nblocks);
3192
3193 // Slice views the worker threads share (all read-only).
3194 let (swb, swb_s, sine_s, kbd_s, seqs, shapes, plan) = (
3195 &swb[..],
3196 &swb_s[..],
3197 &sine_s[..],
3198 &kbd_s[..],
3199 &seqs[..],
3200 &shapes[..],
3201 &plan[..],
3202 );
3203 let frame = |b: usize| {
3204 self.encode_frame(b, swb, swb_s, sine_s, kbd_s, seqs, shapes, per_channel, plan)
3205 };
3206
3207 let nthreads = std::thread::available_parallelism()
3208 .map_or(1, |p| p.get())
3209 .min(nblocks.max(1));
3210 if nthreads <= 1 || nblocks < 16 {
3211 return (0..nblocks).map(frame).collect(); // serial for tiny inputs
3212 }
3213 // Fan out contiguous frame ranges; concatenating the parts keeps them ordered.
3214 let chunk = nblocks.div_ceil(nthreads);
3215 let parts: Vec<Vec<(Vec<u8>, i64)>> = std::thread::scope(|s| {
3216 (0..nthreads)
3217 .map(|t| {
3218 s.spawn(move || {
3219 let end = ((t + 1) * chunk).min(nblocks);
3220 (t * chunk..end).map(frame).collect::<Vec<_>>()
3221 })
3222 })
3223 .collect::<Vec<_>>()
3224 .into_iter()
3225 .map(|h| h.join().unwrap())
3226 .collect()
3227 });
3228 parts.into_iter().flatten().collect()
3229 }
3230
3231 /// Signal end-of-input: encode all buffered PCM (frame-parallel) so packets
3232 /// can be drained via [`next_packet`](AacEncoder::next_packet). Idempotent.
3233 pub fn finish(&mut self) {
3234 if self.flushed {
3235 return;
3236 }
3237 self.flushed = true;
3238 if self.initialized {
3239 self.queue = self.encode_stream().into();
3240 }
3241 }
3242
3243 /// Retrieve the next encoded access unit. Returns [`Error::Again`] before
3244 /// [`finish`](AacEncoder::finish) has been called, and [`Error::Eof`] once
3245 /// fully drained.
3246 pub fn next_packet(&mut self) -> Result<EncodedPacket> {
3247 if let Some((data, pts)) = self.queue.pop_front() {
3248 return Ok(EncodedPacket {
3249 data,
3250 pts,
3251 duration: FRAME_LEN as u32,
3252 });
3253 }
3254 if self.flushed {
3255 Err(Error::Eof)
3256 } else {
3257 Err(Error::Again)
3258 }
3259 }
3260}
3261
3262impl Default for AacEncoder {
3263 fn default() -> Self {
3264 Self::new(AacEncoderConfig::default())
3265 }
3266}
3267
3268#[cfg(test)]
3269mod tests {
3270 use super::*;
3271 use crate::bits::BitReader;
3272 use crate::codebook::decode_tuple;
3273
3274 /// Drain the encoder into a concatenated ADTS elementary stream — the container
3275 /// framing the encoder no longer emits itself — for decoder/ffmpeg validation.
3276 fn encode_to_adts(enc: &mut AacEncoder) -> Vec<u8> {
3277 enc.finish();
3278 let mut out = Vec::new();
3279 while let Ok(p) = enc.next_packet() {
3280 let hdr = AdtsHeader {
3281 object_type: 2,
3282 sample_rate: enc.sample_rate,
3283 channels: enc.channels as u16,
3284 frame_length: 7 + p.data.len(),
3285 header_len: 7,
3286 };
3287 out.extend_from_slice(&write_adts_header(&hdr));
3288 out.extend_from_slice(&p.data);
3289 }
3290 out
3291 }
3292
3293 /// Every `dim`-tuple drawn from `vals`.
3294 fn product(vals: &[i32], dim: usize) -> Vec<Vec<i32>> {
3295 let mut out = vec![vec![]];
3296 for _ in 0..dim {
3297 let mut next = Vec::new();
3298 for prefix in &out {
3299 for &v in vals {
3300 let mut t = prefix.clone();
3301 t.push(v);
3302 next.push(t);
3303 }
3304 }
3305 out = next;
3306 }
3307 out
3308 }
3309
3310 /// Encode every representable tuple of every spectral codebook, then decode it
3311 /// back through the REAL decoder — must match exactly (codeword + sign + escape),
3312 /// and the written bit count must equal `spectral_bits`.
3313 #[test]
3314 fn spectral_encode_roundtrips_through_decoder() {
3315 for cb_num in 1..=11usize {
3316 let cb = &CODEBOOKS[cb_num];
3317 let dim = cb.dim as usize;
3318 let lav = cb.lav as i32;
3319
3320 // Signed books offset by lav; unsigned carry a sign, so cover ±lav.
3321 // Book 11 (escape) also probes magnitudes beyond lav, both signs.
3322 let vals: Vec<i32> = if cb.esc {
3323 let mut v: Vec<i32> = (-lav..=lav).collect();
3324 for &m in &[16, 17, 31, 32, 69, 100] {
3325 v.push(m);
3326 v.push(-m);
3327 }
3328 v
3329 } else {
3330 (-lav..=lav).collect()
3331 };
3332
3333 for tuple in product(&vals, dim) {
3334 if tuple_index(cb, &tuple).is_none() {
3335 continue;
3336 }
3337 let mut w = BitWriter::new();
3338 spectral_emit(cb_num, &tuple, &mut w);
3339 assert_eq!(
3340 w.bit_len(),
3341 spectral_bits(cb_num, &tuple).unwrap(),
3342 "cb {cb_num} tuple {tuple:?}: bit count mismatch"
3343 );
3344 let bytes = w.into_bytes();
3345 let mut r = BitReader::new(&bytes);
3346 let mut out = [0i32; 4];
3347 decode_tuple(cb, spectral_book(cb_num as u8), &mut r, &mut out).unwrap();
3348 assert_eq!(
3349 &out[..dim],
3350 &tuple[..dim],
3351 "cb {cb_num} tuple {tuple:?}: round-trip"
3352 );
3353 }
3354 }
3355 }
3356
3357 /// Forward MDCT → decoder synthesis (imdct·window·overlap-add) reconstructs the
3358 /// signal (delayed one frame) — proves the window + overlap + 32768 scaling.
3359 #[test]
3360 fn long_filterbank_reconstructs_via_decoder_math() {
3361 let win = crate::dsp::sine_window(LONG_N);
3362 let nblocks = 6usize;
3363 let signal: Vec<f32> = (0..nblocks * FRAME_LEN)
3364 .map(|i| (0.3 * (i as f64 * 0.017).sin() + 0.2 * (i as f64 * 0.003).cos()) as f32)
3365 .collect();
3366
3367 let mut prev = [0f32; FRAME_LEN];
3368 let mut specs = Vec::new();
3369 for b in 0..nblocks {
3370 let mut cur = [0f32; FRAME_LEN];
3371 cur.copy_from_slice(&signal[b * FRAME_LEN..(b + 1) * FRAME_LEN]);
3372 specs.push(analyze_long(&prev, &cur, &win));
3373 prev = cur;
3374 }
3375
3376 let mut overlap = [0f32; FRAME_LEN];
3377 let mut out = Vec::new();
3378 for spec in &specs {
3379 let time = crate::dsp::imdct(spec);
3380 let frame: Vec<f32> = (0..LONG_N).map(|n| time[n] * win[n] / SPEC_SCALE).collect();
3381 let mut o = [0f32; FRAME_LEN];
3382 for n in 0..FRAME_LEN {
3383 o[n] = frame[n] + overlap[n];
3384 overlap[n] = frame[FRAME_LEN + n];
3385 }
3386 out.extend_from_slice(&o);
3387 }
3388
3389 // Output lags the input by one frame; the interior must reconstruct.
3390 for i in FRAME_LEN..(nblocks - 1) * FRAME_LEN {
3391 assert!(
3392 (out[i] - signal[i - FRAME_LEN]).abs() < 1e-3,
3393 "at {i}: {} vs {}",
3394 out[i],
3395 signal[i - FRAME_LEN]
3396 );
3397 }
3398 }
3399
3400 /// The block-switching sequence OnlyLong → LongStart → EightShort → LongStop →
3401 /// OnlyLong must reconstruct through the decoder's synthesis math (TDAC across
3402 /// the transition windows) — the decisive check that the short filterbank and
3403 /// transition windows are exact inverses.
3404 #[test]
3405 fn short_block_sequence_reconstructs_via_decoder_math() {
3406 use WindowSequence::*;
3407 let sine_l = crate::dsp::sine_window(LONG_N);
3408 let sine_s = crate::dsp::sine_window(SHORT_N);
3409 // Arm A8's shapes, unused by this test (it exercises the sine arm) but
3410 // required by the shape-aware signature.
3411 let kbd_l_t = crate::dsp::kbd_window(LONG_N, 4.0);
3412 let kbd_s_t = crate::dsp::kbd_window(SHORT_N, 6.0);
3413 let seqs = [
3414 OnlyLong, LongStart, EightShort, LongStop, OnlyLong, OnlyLong,
3415 ];
3416 let nblocks = seqs.len();
3417 let signal: Vec<f32> = (0..nblocks * FRAME_LEN)
3418 .map(|i| (0.3 * (i as f64 * 0.019).sin() + 0.25 * (i as f64 * 0.007).cos()) as f32)
3419 .collect();
3420
3421 // Forward: per-frame filterbank chosen by the window sequence.
3422 let mut prev = [0f32; FRAME_LEN];
3423 let mut specs = Vec::new();
3424 for (b, &seq) in seqs.iter().enumerate() {
3425 let mut cur = [0f32; FRAME_LEN];
3426 cur.copy_from_slice(&signal[b * FRAME_LEN..(b + 1) * FRAME_LEN]);
3427 let spec = if seq == EightShort {
3428 analyze_short(&prev, &cur, &sine_s)
3429 } else {
3430 analyze_long(&prev, &cur, &long_window(seq, false, false, &sine_l, &kbd_l_t, &sine_s, &kbd_s_t))
3431 };
3432 specs.push((seq, spec));
3433 prev = cur;
3434 }
3435
3436 // Synthesis: mirror the decoder (short_frame vs imdct·window) + overlap-add.
3437 let mut overlap = [0f32; FRAME_LEN];
3438 let mut out = Vec::new();
3439 for (seq, spec) in &specs {
3440 let frame: Vec<f32> = if *seq == EightShort {
3441 let mut f = vec![0f32; LONG_N];
3442 for w in 0..8 {
3443 let time = crate::dsp::imdct(&spec[w * SHORT_HALF..(w + 1) * SHORT_HALF]);
3444 let off = 448 + w * SHORT_HALF;
3445 for n in 0..SHORT_N {
3446 f[off + n] += time[n] * sine_s[n] / SPEC_SCALE;
3447 }
3448 }
3449 f
3450 } else {
3451 let time = crate::dsp::imdct(spec);
3452 let win = long_window(*seq, false, false, &sine_l, &kbd_l_t, &sine_s, &kbd_s_t);
3453 (0..LONG_N).map(|n| time[n] * win[n] / SPEC_SCALE).collect()
3454 };
3455 let mut o = [0f32; FRAME_LEN];
3456 for n in 0..FRAME_LEN {
3457 o[n] = frame[n] + overlap[n];
3458 overlap[n] = frame[FRAME_LEN + n];
3459 }
3460 out.extend_from_slice(&o);
3461 }
3462
3463 // Interior (past the priming frame) must reconstruct across all transitions.
3464 for i in FRAME_LEN..(nblocks - 1) * FRAME_LEN {
3465 assert!(
3466 (out[i] - signal[i - FRAME_LEN]).abs() < 1e-3,
3467 "at {i}: {} vs {}",
3468 out[i],
3469 signal[i - FRAME_LEN]
3470 );
3471 }
3472 }
3473
3474 #[test]
3475 fn window_sequences_are_valid() {
3476 use WindowSequence::*;
3477 // Isolated transient → bracketed by LongStart / LongStop.
3478 assert_eq!(
3479 assign_sequences(&[false, false, false, true, false, false]),
3480 vec![OnlyLong, OnlyLong, LongStart, EightShort, LongStop, OnlyLong]
3481 );
3482 // Adjacent transients → one short run.
3483 assert_eq!(
3484 assign_sequences(&[false, false, true, true, false]),
3485 vec![OnlyLong, LongStart, EightShort, EightShort, LongStop]
3486 );
3487 // A single-frame gap is merged (can't be both a stop and a start).
3488 assert_eq!(
3489 assign_sequences(&[false, true, false, true, false]),
3490 vec![LongStart, EightShort, EightShort, EightShort, LongStop]
3491 );
3492 }
3493
3494 #[test]
3495 fn transient_is_detected() {
3496 let sr = 44100.0f64;
3497 let nframes = 5;
3498 let n = nframes * FRAME_LEN;
3499 let mut s = vec![0f32; n];
3500 for (i, x) in s.iter_mut().enumerate() {
3501 *x = (0.02 * (2.0 * std::f64::consts::PI * 400.0 * i as f64 / sr).sin()) as f32;
3502 }
3503 // A loud burst at the start of frame 2.
3504 for i in 0..600 {
3505 let env = (1.0 - i as f64 / 600.0).max(0.0);
3506 s[2 * FRAME_LEN + i] +=
3507 (0.8 * env * (2.0 * std::f64::consts::PI * 3000.0 * i as f64 / sr).sin()) as f32;
3508 }
3509 let flags = detect_transients(&s, nframes);
3510 assert!(flags[2], "the burst frame must be flagged");
3511 assert!(!flags[0] && !flags[4], "steady frames must not be flagged");
3512 }
3513
3514 /// End-to-end: a signal with a sharp attack must actually emit EightShort
3515 /// blocks and still decode cleanly through our decoder.
3516 #[test]
3517 fn transient_encodes_short_and_decodes() {
3518 let sr = 44100u32;
3519 let nframes = 5;
3520 let n = nframes * FRAME_LEN;
3521 let mut interleaved = Vec::new();
3522 for i in 0..n {
3523 let t = i as f64 / sr as f64;
3524 let mut v = 0.02 * (2.0 * std::f64::consts::PI * 400.0 * t).sin();
3525 if (2 * FRAME_LEN..2 * FRAME_LEN + 600).contains(&i) {
3526 let k = i - 2 * FRAME_LEN;
3527 let env = (1.0 - k as f64 / 600.0).max(0.0);
3528 v += 0.8 * env * (2.0 * std::f64::consts::PI * 3000.0 * k as f64 / sr as f64).sin();
3529 }
3530 interleaved.push(v as f32);
3531 }
3532
3533 let mut enc = AacEncoder::default();
3534 enc.push_pcm(&interleaved, 1, sr).unwrap();
3535 let adts = encode_to_adts(&mut enc);
3536
3537 // Parse each frame's first SCE window_sequence; EightShort (2) must appear.
3538 let mut saw_short = false;
3539 let mut pos = 0usize;
3540 let mut decoded = 0usize;
3541 let mut dec = crate::decode::Decoder::new(sr);
3542 while pos + 7 <= adts.len() {
3543 let hdr = crate::parse_adts(&adts[pos..]).unwrap();
3544 let au = &adts[pos + hdr.header_len..pos + hdr.frame_length];
3545 let mut r = crate::BitReader::new(au);
3546 assert_eq!(r.read_bits(3).unwrap(), ID_SCE); // mono SCE
3547 let _ = r.read_bits(4).unwrap(); // tag
3548 let _ = r.read_bits(8).unwrap(); // global_gain
3549 let _ = r.read_bit().unwrap(); // ics_reserved
3550 if r.read_bits(2).unwrap() == WindowSequence::EightShort.to_bits() {
3551 saw_short = true;
3552 }
3553 decoded += dec.decode(au, None).unwrap().frames();
3554 pos += hdr.frame_length;
3555 }
3556 assert!(saw_short, "a transient must produce EightShort blocks");
3557 assert!(decoded >= n, "decoded fewer samples than encoded");
3558 }
3559
3560 /// The `ms_mask_present` (2 bits) of the first frame's CPE — 0 = no M/S.
3561 fn first_cpe_ms_mask(adts: &[u8]) -> u32 {
3562 let hdr = crate::parse_adts(adts).unwrap();
3563 let au = &adts[hdr.header_len..hdr.frame_length];
3564 let mut r = crate::BitReader::new(au);
3565 assert_eq!(r.read_bits(3).unwrap(), ID_CPE);
3566 let _tag = r.read_bits(4).unwrap();
3567 assert_eq!(r.read_bit().unwrap(), 1); // common_window
3568 let _reserved = r.read_bit().unwrap();
3569 let ws = r.read_bits(2).unwrap();
3570 let _shape = r.read_bit().unwrap();
3571 if ws == WindowSequence::EightShort.to_bits() {
3572 let _ = r.read_bits(4).unwrap(); // max_sfb
3573 let _ = r.read_bits(7).unwrap(); // grouping
3574 } else {
3575 let _ = r.read_bits(6).unwrap(); // max_sfb
3576 let _ = r.read_bit().unwrap(); // predictor_data_present
3577 }
3578 r.read_bits(2).unwrap()
3579 }
3580
3581 /// Stereo with L = R (fully correlated) must pick M/S and reconstruct the two
3582 /// channels identically — the CPE + mid/side round-trip.
3583 #[test]
3584 fn stereo_ms_roundtrips_mono_content() {
3585 let sr = 44100u32;
3586 let n = 8192usize;
3587 let mut interleaved = Vec::new();
3588 for i in 0..n {
3589 let s =
3590 (0.4 * (2.0 * std::f64::consts::PI * 600.0 * i as f64 / sr as f64).sin()) as f32;
3591 interleaved.push(s); // L
3592 interleaved.push(s); // R == L
3593 }
3594 let mut enc = AacEncoder::default();
3595 enc.push_pcm(&interleaved, 2, sr).unwrap();
3596 let adts = encode_to_adts(&mut enc);
3597
3598 assert_ne!(
3599 first_cpe_ms_mask(&adts),
3600 0,
3601 "M/S should be chosen for L=R content"
3602 );
3603
3604 let mut dec = crate::decode::Decoder::new(sr);
3605 let (mut lsum, mut diff) = (0f64, 0f64);
3606 let mut pos = 0usize;
3607 while pos + 7 <= adts.len() {
3608 let hdr = crate::parse_adts(&adts[pos..]).unwrap();
3609 let au = &adts[pos + hdr.header_len..pos + hdr.frame_length];
3610 let a = dec.decode(au, None).unwrap();
3611 for k in 0..a.frames() {
3612 let l = a.samples[k * 2];
3613 let rr = a.samples[k * 2 + 1];
3614 lsum += (l as f64).powi(2);
3615 diff += ((l - rr) as f64).powi(2);
3616 }
3617 pos += hdr.frame_length;
3618 }
3619 assert!(lsum > 0.0, "decoded silence");
3620 // L and R reconstruct identically (mono content preserved through M/S).
3621 assert!(
3622 diff / (lsum + 1e-9) < 1e-3,
3623 "L/R diverged: {}",
3624 diff / (lsum + 1e-9)
3625 );
3626 }
3627
3628 /// The encoder→decoder round-trip is unity gain and length-preserving: decode
3629 /// the raw AUs directly (no container/engine) and check per-channel amplitude
3630 /// (≈0.283 RMS for a 0.4-amp sine) and frame count (~input + a little priming).
3631 #[test]
3632 fn stereo_direct_decode_amplitude() {
3633 let sr = 44100u32;
3634 let n = sr as usize; // 1 s
3635 let mut interleaved = Vec::new();
3636 for i in 0..n {
3637 let t = i as f64 / sr as f64;
3638 let l = (0.4 * (2.0 * std::f64::consts::PI * 440.0 * t).sin()) as f32;
3639 let r = (0.4 * (2.0 * std::f64::consts::PI * 660.0 * t).sin()) as f32;
3640 interleaved.push(l);
3641 interleaved.push(r);
3642 }
3643 let mut enc = AacEncoder::default();
3644 enc.push_pcm(&interleaved, 2, sr).unwrap();
3645 enc.finish();
3646 let mut dec = crate::decode::Decoder::new(sr);
3647 let (mut lsq, mut rsq, mut cnt) = (0.0f64, 0.0f64, 0usize);
3648 while let Ok(p) = enc.next_packet() {
3649 let a = dec.decode(&p.data, None).unwrap();
3650 for k in 0..a.frames() {
3651 let l = a.samples[k * 2];
3652 let r = a.samples[k * 2 + 1];
3653 lsq += (l as f64).powi(2);
3654 rsq += (r as f64).powi(2);
3655 cnt += 1;
3656 }
3657 }
3658 let (lrms, rrms) = ((lsq / cnt as f64).sqrt(), (rsq / cnt as f64).sqrt());
3659 eprintln!("input {n}/ch; decoded {cnt}/ch; Lrms={lrms:.3} Rrms={rrms:.3} (unity≈0.283)");
3660 // ~1 output frame per input frame (a couple of priming/flush frames extra).
3661 assert!(
3662 cnt >= n && cnt < n + 4 * FRAME_LEN,
3663 "frame count off: {cnt} vs {n}"
3664 );
3665 // Unity gain per channel (lossy tolerance), no doubling.
3666 assert!((0.24..0.32).contains(&lrms), "L amplitude off: {lrms:.3}");
3667 assert!((0.24..0.32).contains(&rrms), "R amplitude off: {rrms:.3}");
3668 }
3669
3670 /// Per-frame hot-path breakdown — which stage dominates encode time.
3671 #[test]
3672 #[ignore = "profiling; run with --ignored --nocapture"]
3673 fn profile_encode_hotpath() {
3674 use std::time::Instant;
3675 let sr = 44100u32;
3676 let fs = crate::sf_index_for_rate(sr).unwrap();
3677 let swb = swb_offsets(true, fs);
3678 let win = crate::dsp::sine_window(LONG_N);
3679 let mut cur = [0f32; FRAME_LEN];
3680 for (i, s) in cur.iter_mut().enumerate() {
3681 let t = i as f64 / sr as f64;
3682 *s = (0.3 * (2.0 * std::f64::consts::PI * 440.0 * t).sin()
3683 + 0.1 * (2.0 * std::f64::consts::PI * 3000.0 * t).sin()) as f32;
3684 }
3685 let prev = [0f32; FRAME_LEN];
3686 let iters = 500;
3687 let us = |d: std::time::Duration| d.as_secs_f64() * 1e6 / iters as f64;
3688
3689 let t = Instant::now();
3690 let mut spec = Vec::new();
3691 for _ in 0..iters {
3692 spec = analyze_long(&prev, &cur, &win);
3693 }
3694 let mdct = t.elapsed();
3695
3696 let t = Instant::now();
3697 for _ in 0..iters {
3698 let _ = perceptual_offsets(&spec, swb, sr, false);
3699 }
3700 let psy = t.elapsed();
3701 let offsets = perceptual_offsets(&spec, swb, sr, false);
3702
3703 let t = Instant::now();
3704 for _ in 0..iters {
3705 let _ = Xpow::new(&spec);
3706 }
3707 let xpow_t = t.elapsed();
3708 let xp = Xpow::new(&spec);
3709
3710 let t = Instant::now();
3711 for _ in 0..iters {
3712 let _ = rate_loop(&xp, swb, &offsets, 3000);
3713 }
3714 let rate = t.elapsed();
3715
3716 let sf = scalefactors(&offsets, 120);
3717 let t = Instant::now();
3718 for _ in 0..iters {
3719 let _ = code_frame(&xp, swb, &sf);
3720 }
3721 let cf = t.elapsed();
3722
3723 eprintln!("per-frame per-channel (avg over {iters}):");
3724 eprintln!(" analyze_long (MDCT): {:>8.1} us", us(mdct));
3725 eprintln!(" Xpow::new (once): {:>8.1} us", us(xpow_t));
3726 eprintln!(" perceptual_offsets: {:>8.1} us", us(psy));
3727 eprintln!(" rate_loop (~8x cf): {:>8.1} us", us(rate));
3728 eprintln!(" one code_frame: {:>8.1} us", us(cf));
3729 eprintln!(
3730 " → MDCT is {:.0}% of (MDCT + rate_loop)",
3731 100.0 * mdct.as_secs_f64() / (mdct.as_secs_f64() + rate.as_secs_f64())
3732 );
3733 }
3734
3735 /// The AVX-512 quantize kernel narrows via `trunc(min(v+0.5, MAX+0.5))` instead of
3736 /// the AVX2/scalar `min(round(v), MAX)`. The intrinsics can't run on a non-AVX-512
3737 /// host, but the identity they rely on — for the quantizer's always-nonnegative
3738 /// input — is checkable in scalar, so the untested path's *math* is pinned here.
3739 #[test]
3740 fn avx512_trunc_identity_matches_round_clamp() {
3741 for &v in &[
3742 0.0f64, 0.4, 0.5, 0.6, 1.4, 1.5, 2.5, 100.5, 8190.9, 8191.0, 8191.5, 1e6,
3743 ] {
3744 let round_clamp = (v.round() as i64).min(MAX_QUANT as i64);
3745 let trunc_trick = (v + 0.5).min(MAX_QUANT as f64 + 0.5) as i64; // `as` truncates
3746 assert_eq!(round_clamp, trunc_trick, "mismatch at v={v}");
3747 }
3748 }
3749
3750 #[test]
3751 fn bitwriter_msb_first() {
3752 let mut w = BitWriter::new();
3753 w.write(0b101, 3);
3754 w.write(0b1, 1);
3755 w.write(0b1111, 4);
3756 assert_eq!(w.bit_len(), 8);
3757 assert_eq!(w.into_bytes(), vec![0b1011_1111]);
3758 }
3759
3760 #[test]
3761 fn audio_specific_config_roundtrips() {
3762 for &(sr, ch) in &[(44100u32, 2u16), (48000, 1), (96000, 2), (8000, 1)] {
3763 let cfg = AudioSpecificConfig {
3764 object_type: 2,
3765 sample_rate: sr,
3766 channels: ch,
3767 };
3768 let bytes = write_audio_specific_config(&cfg);
3769 assert_eq!(crate::parse_audio_specific_config(&bytes).unwrap(), cfg);
3770 }
3771 }
3772
3773 #[test]
3774 fn adts_header_roundtrips() {
3775 let hdr = AdtsHeader {
3776 object_type: 2,
3777 sample_rate: 44100,
3778 channels: 2,
3779 frame_length: 512,
3780 header_len: 7,
3781 };
3782 let bytes = write_adts_header(&hdr);
3783 assert_eq!(bytes.len(), 7);
3784 assert!(crate::is_adts(&bytes));
3785 assert_eq!(crate::parse_adts(&bytes).unwrap(), hdr);
3786 }
3787
3788 #[test]
3789 fn ics_info_long_reencodes_bit_exact() {
3790 // The decoder's own long-block test vector.
3791 let orig = [0x0C, 0x40];
3792 let info = crate::ics::parse_ics_info(&mut BitReader::new(&orig), 4).unwrap();
3793 let mut w = BitWriter::new();
3794 encode_ics_info(&mut w, &info);
3795 assert_eq!(w.into_bytes(), orig);
3796 }
3797
3798 #[test]
3799 fn ics_info_short_grouping_roundtrips() {
3800 use crate::ics::{parse_ics_info, IcsInfo, WindowSequence};
3801 let info = IcsInfo {
3802 window_sequence: WindowSequence::EightShort,
3803 window_shape_kbd: false,
3804 max_sfb: 8,
3805 num_windows: 8,
3806 num_window_groups: 2,
3807 window_group_length: vec![3, 5],
3808 num_swb: 0, // encode ignores; the parser re-derives
3809 };
3810 let mut w = BitWriter::new();
3811 encode_ics_info(&mut w, &info);
3812 let parsed = parse_ics_info(&mut BitReader::new(&w.into_bytes()), 4).unwrap();
3813 assert_eq!(parsed.window_sequence, WindowSequence::EightShort);
3814 assert_eq!(parsed.max_sfb, 8);
3815 assert_eq!(parsed.window_group_length, vec![3, 5]);
3816 }
3817
3818 fn rms(sig: &[f32]) -> f64 {
3819 (sig.iter().map(|&s| (s as f64).powi(2)).sum::<f64>() / sig.len().max(1) as f64).sqrt()
3820 }
3821
3822 /// Magnitude of the `freq`-Hz component (Goertzel-style) — a recognizability probe.
3823 fn tone_energy(sig: &[f32], freq: f64, sr: f64) -> f64 {
3824 let (mut re, mut im) = (0.0f64, 0.0f64);
3825 for (i, &s) in sig.iter().enumerate() {
3826 let ph = 2.0 * std::f64::consts::PI * freq * i as f64 / sr;
3827 re += s as f64 * ph.cos();
3828 im += s as f64 * ph.sin();
3829 }
3830 (re * re + im * im).sqrt() / sig.len() as f64
3831 }
3832
3833 /// The whole-pipeline gate: encode a 440 Hz tone, decode through the real
3834 /// decoder, and confirm a recognizable 440 Hz tone with preserved energy.
3835 #[test]
3836 fn encodes_and_decodes_recognizable_tone() {
3837 let sr = 44100u32;
3838 let n = 44100usize; // 1 s
3839 let mut samples = Vec::with_capacity(n);
3840 for i in 0..n {
3841 let s =
3842 ((i as f64 * 2.0 * std::f64::consts::PI * 440.0 / sr as f64).sin() * 0.5) as f32;
3843 samples.push(s);
3844 }
3845
3846 let mut enc = AacEncoder::default();
3847 enc.push_pcm(&samples, 1, sr).unwrap();
3848 let adts = encode_to_adts(&mut enc);
3849 assert!(crate::is_adts(&adts), "encoder output is not ADTS");
3850
3851 let mut dec = crate::decode::Decoder::new(sr);
3852 let mut decoded = Vec::new();
3853 let mut pos = 0usize;
3854 while pos + 7 <= adts.len() {
3855 let hdr = crate::parse_adts(&adts[pos..]).unwrap();
3856 let au = &adts[pos + hdr.header_len..pos + hdr.frame_length];
3857 decoded.extend_from_slice(&dec.decode(au, None).unwrap().samples);
3858 pos += hdr.frame_length;
3859 }
3860 assert!(
3861 decoded.len() > n / 2,
3862 "too little decoded audio: {}",
3863 decoded.len()
3864 );
3865
3866 let (ri, ro) = (rms(&samples), rms(&decoded));
3867 assert!(
3868 ro > 0.4 * ri && ro < 2.5 * ri,
3869 "energy off: in {ri:.4} out {ro:.4}"
3870 );
3871 let e440 = tone_energy(&decoded, 440.0, sr as f64);
3872 let e1234 = tone_energy(&decoded, 1234.0, sr as f64);
3873 assert!(
3874 e440 > 5.0 * e1234,
3875 "not a clean 440 Hz tone: e440 {e440:.5} e1234 {e1234:.5}"
3876 );
3877 }
3878
3879 /// The rate loop must keep a dense signal within (roughly) the target bitrate
3880 /// and still produce decodable audio.
3881 #[test]
3882 fn rate_loop_respects_bitrate() {
3883 let sr = 44100u32;
3884 let secs = 2usize;
3885 let n = sr as usize * secs;
3886 let mut interleaved = Vec::new();
3887 let mut st = 0x0000_2468u32;
3888 for i in 0..n {
3889 let t = i as f64 / sr as f64;
3890 let mut s = 0.0;
3891 for h in 1..=8 {
3892 s += (2.0 * std::f64::consts::PI * 300.0 * h as f64 * t).sin() / h as f64;
3893 }
3894 st ^= st << 13;
3895 st ^= st >> 17;
3896 st ^= st << 5;
3897 let noise = ((st >> 24) as f64 - 128.0) / 128.0 * 0.1;
3898 let v = ((s * 0.2 + noise) * 0.7).clamp(-1.0, 1.0) as f32;
3899 interleaved.push(v);
3900 }
3901
3902 for &kbps in &[64_000u32, 128_000] {
3903 let mut enc = AacEncoder::new(AacEncoderConfig { bitrate_bps: kbps, ..Default::default() });
3904 enc.push_pcm(&interleaved, 1, sr).unwrap();
3905 let adts = encode_to_adts(&mut enc);
3906
3907 let measured = adts.len() as f64 * 8.0 / secs as f64;
3908 assert!(
3909 measured <= kbps as f64 * 1.35,
3910 "bitrate {kbps}: measured {measured:.0} b/s exceeds budget"
3911 );
3912
3913 let mut dec = crate::decode::Decoder::new(sr);
3914 let mut pos = 0usize;
3915 let mut got = false;
3916 while pos + 7 <= adts.len() {
3917 let hdr = crate::parse_adts(&adts[pos..]).unwrap();
3918 let au = &adts[pos + hdr.header_len..pos + hdr.frame_length];
3919 got |= !dec.decode(au, None).unwrap().samples.is_empty();
3920 pos += hdr.frame_length;
3921 }
3922 assert!(got, "bitrate {kbps}: no decodable audio");
3923 eprintln!(
3924 "target {kbps} b/s → measured {measured:.0} b/s ({} bytes)",
3925 adts.len()
3926 );
3927 }
3928 }
3929
3930 /// The psychoacoustic model must shape quantization noise toward the masking
3931 /// threshold: at a fixed budget it must not worsen the worst band and must cut
3932 /// the total audible (above-mask) noise vs flat scalefactors.
3933 #[test]
3934 fn psy_model_shapes_noise_below_flat() {
3935 let sr = 44100u32;
3936 let fs = crate::sf_index_for_rate(sr).unwrap();
3937 let swb = swb_offsets(true, fs);
3938 let win = crate::dsp::sine_window(LONG_N);
3939 // A few strong tones with spectral gaps → masking creates real headroom in
3940 // some bands and sensitivity in others.
3941 let mut cur = [0f32; FRAME_LEN];
3942 for (i, s) in cur.iter_mut().enumerate() {
3943 let t = i as f64 / sr as f64;
3944 let v = 0.5 * (2.0 * std::f64::consts::PI * 500.0 * t).sin()
3945 + 0.25 * (2.0 * std::f64::consts::PI * 1500.0 * t).sin()
3946 + 0.15 * (2.0 * std::f64::consts::PI * 4000.0 * t).sin();
3947 *s = v as f32;
3948 }
3949 let spec = analyze_long(&[0f32; FRAME_LEN], &cur, &win);
3950 let target = 2500usize; // ~128 kbps — enough that allocation choices matter
3951
3952 // Worst-case NMR (perceptual quality is set by the loudest audible artifact)
3953 // and mean NMR in dB, over the energy-bearing bands.
3954 let xp = Xpow::new(&spec);
3955 let metric = |offsets: &[i32]| -> (f64, f64) {
3956 let base = rate_loop(&xp, swb, offsets, target);
3957 let sf = scalefactors(offsets, base);
3958 let thr = masking_thresholds(&spec, swb, sr);
3959 let (mut max_nmr, mut sum_db, mut n) = (0f64, 0f64, 0usize);
3960 for sfb in 0..swb.len() - 1 {
3961 let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
3962 let en: f64 = spec[s..e].iter().map(|&x| (x as f64).powi(2)).sum();
3963 if en < 1e6 {
3964 continue; // near-silent band → quantizes to ZERO, no artifact
3965 }
3966 let mut noise = 0f64;
3967 for &x in &spec[s..e] {
3968 let q = quantize(x, sf[sfb]);
3969 let rec = q.signum() as f64
3970 * (q.unsigned_abs() as f64).powf(4.0 / 3.0)
3971 * 2f64.powf(0.25 * (sf[sfb] - 100) as f64);
3972 noise += (x as f64 - rec).powi(2);
3973 }
3974 let nmr = (noise / thr[sfb]).max(1e-30);
3975 max_nmr = max_nmr.max(nmr);
3976 sum_db += 10.0 * nmr.log10();
3977 n += 1;
3978 }
3979 (max_nmr, sum_db / n.max(1) as f64)
3980 };
3981
3982 let flat = metric(&vec![0i32; swb.len() - 1]);
3983 let psy = metric(&perceptual_offsets(&spec, swb, sr, false));
3984 eprintln!(
3985 "flat: max_nmr={:.2} mean={:.1}dB | psy: max_nmr={:.2} mean={:.1}dB",
3986 flat.0, flat.1, psy.0, psy.1
3987 );
3988 // The psy model equalizes NMR → the worst audible band is quieter than flat.
3989 assert!(
3990 psy.0 < flat.0,
3991 "psy must reduce the worst-band NMR ({:.2} vs {:.2})",
3992 psy.0,
3993 flat.0
3994 );
3995 }
3996
3997 /// Emit our `.aac` (ADTS) so an external reference decoder (ffmpeg) can confirm
3998 /// the stream is spec-valid, not just self-decodable.
3999 #[test]
4000 #[ignore = "writes an .aac for external ffmpeg validation; run explicitly"]
4001 fn emit_aac_for_external_check() {
4002 let sr = 44100u32;
4003 let n = 44100usize;
4004 let mut interleaved = Vec::new();
4005 for i in 0..n {
4006 let s =
4007 ((i as f64 * 2.0 * std::f64::consts::PI * 440.0 / sr as f64).sin() * 0.5) as f32;
4008 interleaved.push(s);
4009 }
4010 let mut enc = AacEncoder::default();
4011 enc.push_pcm(&interleaved, 1, sr).unwrap();
4012 let adts = encode_to_adts(&mut enc);
4013 let dir = std::env::temp_dir();
4014 std::fs::write(dir.join("rff_aac_tone.aac"), &adts).unwrap();
4015 eprintln!(
4016 "wrote {}/rff_aac_tone.aac ({} bytes)",
4017 dir.display(),
4018 adts.len()
4019 );
4020 }
4021
4022 /// Emit a `.aac` with periodic sharp attacks (drum-like) so ffmpeg can confirm
4023 /// the block-switched (short + transition) stream is spec-valid.
4024 #[test]
4025 #[ignore = "writes an .aac for external ffmpeg validation; run explicitly"]
4026 fn emit_transient_aac_for_external_check() {
4027 let sr = 44100u32;
4028 let n = 44100usize;
4029 let mut interleaved = Vec::new();
4030 for i in 0..n {
4031 let t = i as f64 / sr as f64;
4032 let mut v = 0.05 * (2.0 * std::f64::consts::PI * 220.0 * t).sin();
4033 // A sharp click every ~0.25 s.
4034 let k = i % 11025;
4035 if k < 700 {
4036 let env = (1.0 - k as f64 / 700.0).max(0.0);
4037 v += 0.8 * env * (2.0 * std::f64::consts::PI * 3500.0 * k as f64 / sr as f64).sin();
4038 }
4039 interleaved.push(v as f32);
4040 }
4041 let mut enc = AacEncoder::default();
4042 enc.push_pcm(&interleaved, 1, sr).unwrap();
4043 let adts = encode_to_adts(&mut enc);
4044 let dir = std::env::temp_dir();
4045 std::fs::write(dir.join("rff_aac_transient.aac"), &adts).unwrap();
4046 eprintln!(
4047 "wrote {}/rff_aac_transient.aac ({} bytes)",
4048 dir.display(),
4049 adts.len()
4050 );
4051 }
4052
4053 /// Emit a stereo `.aac` (shared bass + divergent highs → mixed per-SFB M/S) so
4054 /// ffmpeg can confirm the CPE stream is spec-valid.
4055 #[test]
4056 #[ignore = "writes an .aac for external ffmpeg validation; run explicitly"]
4057 fn emit_stereo_aac_for_external_check() {
4058 let sr = 44100u32;
4059 let n = 44100usize;
4060 let mut interleaved = Vec::new();
4061 for i in 0..n {
4062 let t = i as f64 / sr as f64;
4063 let bass = 0.4 * (2.0 * std::f64::consts::PI * 300.0 * t).sin(); // shared → M/S
4064 let l = bass + 0.2 * (2.0 * std::f64::consts::PI * 1200.0 * t).sin();
4065 let r = bass + 0.2 * (2.0 * std::f64::consts::PI * 1900.0 * t).sin();
4066 interleaved.push(l as f32);
4067 interleaved.push(r as f32);
4068 }
4069 let mut enc = AacEncoder::default();
4070 enc.push_pcm(&interleaved, 2, sr).unwrap();
4071 let adts = encode_to_adts(&mut enc);
4072 let dir = std::env::temp_dir();
4073 std::fs::write(dir.join("rff_aac_stereo.aac"), &adts).unwrap();
4074 eprintln!(
4075 "wrote {}/rff_aac_stereo.aac ({} bytes)",
4076 dir.display(),
4077 adts.len()
4078 );
4079 }
4080}
4081
4082// ---------------------------------------------------------------------------
4083// Rung 0 (arm A8) — window-shape gate tests.
4084//
4085// The rung's contract, in the order great-gate §4 requires it:
4086// 1. the neutral end is BYTE-IDENTICAL (proven against an oracle, not argued),
4087// 2. the routed arm is TDAC-correct (a window mismatch is not a quality
4088// regression, it is broken audio),
4089// 3. the dispatch decodes on the hardest case — alternating shapes.
4090// ---------------------------------------------------------------------------
4091#[cfg(test)]
4092mod rung0 {
4093 use super::*;
4094
4095 /// The sine-only `long_window` exactly as it stood before arm A8, kept as the
4096 /// oracle for the neutral end.
4097 fn long_window_pre_a8(seq: WindowSequence, sine_l: &[f32], sine_s: &[f32]) -> Vec<f32> {
4098 let mut w = vec![0f32; LONG_N];
4099 if seq == WindowSequence::LongStop {
4100 w[448..448 + SHORT_HALF].copy_from_slice(&sine_s[..SHORT_HALF]);
4101 for s in w.iter_mut().take(FRAME_LEN).skip(576) {
4102 *s = 1.0;
4103 }
4104 } else {
4105 w[..FRAME_LEN].copy_from_slice(&sine_l[..FRAME_LEN]);
4106 }
4107 if seq == WindowSequence::LongStart {
4108 for s in w.iter_mut().take(FRAME_LEN + 448).skip(FRAME_LEN) {
4109 *s = 1.0;
4110 }
4111 w[FRAME_LEN + 448..FRAME_LEN + 448 + SHORT_HALF].copy_from_slice(&sine_s[SHORT_HALF..]);
4112 } else {
4113 w[FRAME_LEN..].copy_from_slice(&sine_l[FRAME_LEN..]);
4114 }
4115 w
4116 }
4117
4118 /// **Law 7 — the neutral end is byte-identical.** With both shape flags false
4119 /// the new shape-aware window must equal the pre-A8 sine-only one, exactly,
4120 /// for every sequence. Every other A8 change is a pass-through of
4121 /// `cur_kbd = false` into a bit that was already 0.
4122 #[test]
4123 fn shape_sine_is_byte_identical() {
4124 let sine_l = crate::dsp::sine_window(LONG_N);
4125 let sine_s = crate::dsp::sine_window(SHORT_N);
4126 let kbd_l = crate::dsp::kbd_window(LONG_N, 4.0);
4127 let kbd_s = crate::dsp::kbd_window(SHORT_N, 6.0);
4128 for seq in [
4129 WindowSequence::OnlyLong,
4130 WindowSequence::LongStart,
4131 WindowSequence::LongStop,
4132 ] {
4133 let new = long_window(seq, false, false, &sine_l, &kbd_l, &sine_s, &kbd_s);
4134 let old = long_window_pre_a8(seq, &sine_l, &sine_s);
4135 assert_eq!(new, old, "{seq:?}: neutral end must be byte-identical");
4136 }
4137 }
4138
4139 /// The whole encoded stream is byte-identical under the default config and an
4140 /// explicit `Sine` — i.e. the default really is the neutral arm.
4141 #[test]
4142 fn default_config_is_the_sine_arm() {
4143 let pcm: Vec<f32> = (0..8 * FRAME_LEN)
4144 .map(|i| {
4145 let t = i as f32 / 44100.0;
4146 0.4 * (2.0 * std::f32::consts::PI * 700.0 * t).sin()
4147 })
4148 .collect();
4149 let enc = |cfg: AacEncoderConfig| {
4150 let mut e = AacEncoder::new(cfg);
4151 e.push_pcm(&pcm, 1, 44100).unwrap();
4152 e.finish();
4153 let mut out = Vec::new();
4154 while let Ok(p) = e.next_packet() {
4155 out.extend_from_slice(&p.data);
4156 }
4157 out
4158 };
4159 let a = enc(AacEncoderConfig::default());
4160 let b = enc(AacEncoderConfig {
4161 window_shape: WindowShape::Sine,
4162 ..Default::default()
4163 });
4164 assert_eq!(a, b, "default must be the Sine arm");
4165 }
4166
4167 /// Windows must satisfy the **Princen-Bradley condition** on every overlap:
4168 /// `w_prev[N+n]^2 + w_cur[n]^2 == 1`. This is what makes overlap-add exact. It
4169 /// must hold for every ordered pair of shapes, which is exactly why the left
4170 /// half follows the previous frame and the right half the current one.
4171 #[test]
4172 fn tdac_holds_across_every_shape_transition() {
4173 let sine_l = crate::dsp::sine_window(LONG_N);
4174 let sine_s = crate::dsp::sine_window(SHORT_N);
4175 let kbd_l = crate::dsp::kbd_window(LONG_N, 4.0);
4176 let kbd_s = crate::dsp::kbd_window(SHORT_N, 6.0);
4177
4178 for (a, b) in [(false, false), (false, true), (true, false), (true, true)] {
4179 // Frame 1 has shape `a`; frame 2 has shape `b` and sees `a` as prev.
4180 let w1 = long_window(WindowSequence::OnlyLong, a, a, &sine_l, &kbd_l, &sine_s, &kbd_s);
4181 let w2 = long_window(WindowSequence::OnlyLong, a, b, &sine_l, &kbd_l, &sine_s, &kbd_s);
4182 for n in 0..FRAME_LEN {
4183 let sum = w1[FRAME_LEN + n] * w1[FRAME_LEN + n] + w2[n] * w2[n];
4184 assert!(
4185 (sum - 1.0).abs() < 1e-4,
4186 "TDAC broken at n={n} for prev={a} cur={b}: {sum}"
4187 );
4188 }
4189 }
4190 }
4191
4192 /// Encode then decode under each arm. A prev/cur shape mismatch would show up
4193 /// here as gross reconstruction error, not a subtle quality delta.
4194 #[test]
4195 fn every_arm_round_trips() {
4196 let sr = 44100u32;
4197 let n = 12 * FRAME_LEN;
4198 let pcm: Vec<f32> = (0..n)
4199 .map(|i| {
4200 let t = i as f32 / sr as f32;
4201 0.3 * (2.0 * std::f32::consts::PI * 440.0 * t).sin()
4202 + 0.2 * (2.0 * std::f32::consts::PI * 2600.0 * t).sin()
4203 })
4204 .collect();
4205
4206 for shape in [WindowShape::Sine, WindowShape::Kbd, WindowShape::Auto] {
4207 let mut e = AacEncoder::new(AacEncoderConfig {
4208 bitrate_bps: 128_000,
4209 window_shape: shape,
4210 shape_tonality_pct: 0.5,
4211 ..Default::default()
4212 });
4213 e.push_pcm(&pcm, 1, sr).unwrap();
4214 e.finish();
4215
4216 let mut dec = crate::decode::Decoder::new(sr);
4217 let mut got = Vec::new();
4218 while let Ok(p) = e.next_packet() {
4219 let audio = dec.decode(&p.data, None).expect("decode");
4220 got.extend_from_slice(&audio.samples);
4221 }
4222 assert!(got.len() >= n, "{shape:?}: short decode");
4223
4224 // Compare against the input, allowing the one-frame filterbank delay.
4225 let lag = FRAME_LEN;
4226 let cmp_len = n - 2 * FRAME_LEN;
4227 let (mut num, mut den) = (0f64, 0f64);
4228 for i in 0..cmp_len {
4229 let o = pcm[i] as f64;
4230 let d = got[i + lag] as f64;
4231 num += (o - d) * (o - d);
4232 den += o * o;
4233 }
4234 let snr = 10.0 * (den / num.max(1e-30)).log10();
4235 assert!(
4236 snr > 15.0,
4237 "{shape:?}: reconstruction SNR {snr:.1} dB is too low - \
4238 a window-shape mismatch breaks TDAC"
4239 );
4240 }
4241 }
4242
4243 /// The `Auto` gate must actually dispatch — produce a mix of shapes on
4244 /// content whose tonality varies. A gate that routes everything one way is
4245 /// not a gate.
4246 #[test]
4247 fn auto_gate_dispatches_both_ways() {
4248 let sr = 44100u32;
4249 let n = 16 * FRAME_LEN;
4250 // Alternate 4-frame blocks of tone (tonal) and noise (not).
4251 let mut seed = 0x2468_ACE0u32;
4252 let pcm: Vec<f32> = (0..n)
4253 .map(|i| {
4254 if (i / (4 * FRAME_LEN)) % 2 == 0 {
4255 let t = i as f32 / sr as f32;
4256 0.4 * (2.0 * std::f32::consts::PI * 900.0 * t).sin()
4257 } else {
4258 seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
4259 0.4 * (((seed >> 8) as f32 / (1u32 << 24) as f32) * 2.0 - 1.0)
4260 }
4261 })
4262 .collect();
4263
4264 let mut e = AacEncoder::new(AacEncoderConfig {
4265 bitrate_bps: 128_000,
4266 window_shape: WindowShape::Auto,
4267 shape_tonality_pct: 0.5,
4268 ..Default::default()
4269 });
4270 e.push_pcm(&pcm, 1, sr).unwrap();
4271 let nblocks = n.div_ceil(FRAME_LEN) + 1;
4272 let shapes = e.decide_shapes(nblocks);
4273 let kbd = shapes.iter().filter(|&&s| s).count();
4274 assert!(
4275 kbd > 0 && kbd < shapes.len(),
4276 "Auto must route both ways, got {kbd}/{} KBD",
4277 shapes.len()
4278 );
4279
4280 // And it must route the TONAL blocks to KBD, not at random: the tonal
4281 // frames tonality must exceed the noise frames.
4282 let tone_ton = time_tonality(&e.block(0, 1));
4283 let noise_ton = time_tonality(&e.block(0, 5));
4284 assert!(
4285 tone_ton > noise_ton * 2.0,
4286 "the gate signal must separate tone ({tone_ton:.1}) from noise ({noise_ton:.1})"
4287 );
4288 }
4289}
4290
4291// ---------------------------------------------------------------------------
4292// Rungs 1-3 (arms A1 short-block psy, A2 tonality SMR, A3 TNS).
4293//
4294// Each arm must clear the same three bars before any quality number counts:
4295// 1. OFF is byte-identical with the encoder as it shipped,
4296// 2. ON still round-trips through our own decoder,
4297// 3. ON actually changes something (an arm that is a no-op is not an arm).
4298// ---------------------------------------------------------------------------
4299#[cfg(test)]
4300mod rung123 {
4301 use super::*;
4302
4303 fn encode(pcm: &[f32], ch: u16, sr: u32, cfg: AacEncoderConfig) -> Vec<Vec<u8>> {
4304 let mut e = AacEncoder::new(cfg);
4305 e.push_pcm(pcm, ch, sr).unwrap();
4306 e.finish();
4307 let mut out = Vec::new();
4308 while let Ok(p) = e.next_packet() {
4309 out.push(p.data);
4310 }
4311 out
4312 }
4313
4314 /// Decode a packet list, returning channel-0 PCM.
4315 fn decode_mono(packets: &[Vec<u8>], sr: u32) -> Vec<f32> {
4316 let mut dec = crate::decode::Decoder::new(sr);
4317 let mut out = Vec::new();
4318 for p in packets {
4319 let a = dec.decode(p, None).expect("decode");
4320 let ch = a.channels.max(1) as usize;
4321 out.extend(a.samples.iter().step_by(ch).copied());
4322 }
4323 out
4324 }
4325
4326 /// A transient-rich mono signal: sharp attacks over a quiet tonal floor.
4327 /// Drives short blocks (arm A1) and gives TNS something to shape (arm A3).
4328 fn transient_signal(sr: u32, frames: usize) -> Vec<f32> {
4329 use std::f32::consts::PI;
4330 let n = frames * FRAME_LEN;
4331 (0..n)
4332 .map(|i| {
4333 let t = i as f32 / sr as f32;
4334 let mut v = 0.05 * (2.0 * PI * 500.0 * t).sin();
4335 let k = i % (3 * FRAME_LEN);
4336 if k < 500 && i > FRAME_LEN {
4337 let env = (1.0 - k as f32 / 500.0).max(0.0);
4338 v += 0.85 * env * (2.0 * PI * 3300.0 * k as f32 / sr as f32).sin();
4339 }
4340 v
4341 })
4342 .collect()
4343 }
4344
4345 /// A tonal signal — a harmonic stack, the content arm A2 should treat
4346 /// differently from noise.
4347 fn tonal_signal(sr: u32, frames: usize) -> Vec<f32> {
4348 use std::f32::consts::PI;
4349 let n = frames * FRAME_LEN;
4350 (0..n)
4351 .map(|i| {
4352 let t = i as f32 / sr as f32;
4353 let mut v = 0f32;
4354 for h in 1..=6 {
4355 v += (1.0 / h as f32) * (2.0 * PI * 330.0 * h as f32 * t).sin();
4356 }
4357 0.3 * v
4358 })
4359 .collect()
4360 }
4361
4362 /// **Every arm's OFF state is byte-identical with the shipped encoder.**
4363 /// This is law 7's neutral end, proven by `cmp` rather than argued.
4364 #[test]
4365 fn every_arm_off_is_byte_identical() {
4366 let sr = 44100u32;
4367 let sigs = [transient_signal(sr, 10), tonal_signal(sr, 10)];
4368 for pcm in &sigs {
4369 let base = encode(pcm, 1, sr, AacEncoderConfig::default());
4370 for (name, cfg) in [
4371 (
4372 "short_block_psy",
4373 AacEncoderConfig {
4374 short_block_psy: false,
4375 ..Default::default()
4376 },
4377 ),
4378 (
4379 "tonality_smr",
4380 AacEncoderConfig {
4381 tonality_smr: false,
4382 ..Default::default()
4383 },
4384 ),
4385 (
4386 "tns",
4387 AacEncoderConfig {
4388 tns: false,
4389 ..Default::default()
4390 },
4391 ),
4392 ] {
4393 let got = encode(pcm, 1, sr, cfg);
4394 assert_eq!(got, base, "{name}: OFF must be byte-identical");
4395 }
4396 }
4397 }
4398
4399 /// **Arm A1** — short-block psy must change the bitstream on transient
4400 /// content (where short blocks actually occur) and still decode.
4401 #[test]
4402 fn a1_short_block_psy_changes_and_round_trips() {
4403 let sr = 44100u32;
4404 let pcm = transient_signal(sr, 12);
4405 let off = encode(&pcm, 1, sr, AacEncoderConfig::default());
4406 let on = encode(
4407 &pcm,
4408 1,
4409 sr,
4410 AacEncoderConfig {
4411 short_block_psy: true,
4412 ..Default::default()
4413 },
4414 );
4415 assert_ne!(off, on, "A1 must change the bitstream on transient content");
4416
4417 let dec = decode_mono(&on, sr);
4418 assert!(dec.len() >= pcm.len(), "A1: short decode");
4419 assert!(
4420 dec.iter().all(|v| v.is_finite()),
4421 "A1: non-finite output — the short-block mask is broken"
4422 );
4423 // Reconstruction must remain sane; a wrong band geometry in the short psy
4424 // path shows up as gross error, not a subtle quality shift.
4425 let lag = FRAME_LEN;
4426 let cmp = pcm.len() - 2 * FRAME_LEN;
4427 let (mut num, mut den) = (0f64, 0f64);
4428 for i in 0..cmp {
4429 let o = pcm[i] as f64;
4430 let d = dec[i + lag] as f64;
4431 num += (o - d) * (o - d);
4432 den += o * o;
4433 }
4434 let snr = 10.0 * (den / num.max(1e-30)).log10();
4435 assert!(snr > 8.0, "A1: reconstruction SNR {snr:.1} dB too low");
4436 }
4437
4438 /// **Arm A2** — the SMR must actually vary with tonality. A pure tone and
4439 /// broadband noise at equal energy must no longer receive identical masks.
4440 #[test]
4441 fn a2_smr_varies_with_tonality() {
4442 // Direct check of the law itself, at a mid-band Bark.
4443 let tonal = smr_for(1.0, 10.0);
4444 let noisy = smr_for(0.0, 10.0);
4445 assert!(
4446 tonal < noisy,
4447 "a tonal masker must hold the mask FURTHER below the signal \
4448 (tonal {tonal:.5} must be < noise {noisy:.5})"
4449 );
4450 // And it must stay inside the documented clamp.
4451 for t in [0.0f64, 0.25, 0.5, 0.75, 1.0] {
4452 for bark in [0.0f64, 5.0, 12.0, 24.0] {
4453 let v = smr_for(t, bark);
4454 assert!(
4455 v > 0.0 && v <= 10f64.powf(-5.0 / 10.0) + 1e-12,
4456 "smr_for({t}, {bark}) = {v} escaped its clamp"
4457 );
4458 }
4459 }
4460 }
4461
4462 /// **Arm A2** — end to end: the bitstream changes on tonal content and still
4463 /// decodes.
4464 #[test]
4465 fn a2_changes_and_round_trips() {
4466 let sr = 44100u32;
4467 let pcm = tonal_signal(sr, 10);
4468 let off = encode(&pcm, 1, sr, AacEncoderConfig::default());
4469 let on = encode(
4470 &pcm,
4471 1,
4472 sr,
4473 AacEncoderConfig {
4474 tonality_smr: true,
4475 ..Default::default()
4476 },
4477 );
4478 assert_ne!(off, on, "A2 must change the bitstream on tonal content");
4479 let dec = decode_mono(&on, sr);
4480 assert!(dec.iter().all(|v| v.is_finite()));
4481 assert!(dec.len() >= pcm.len());
4482 }
4483
4484 /// **Arm A3 — the filter inversion.** The encoder runs the ALL-ZERO analysis
4485 /// filter; the decoder runs the ALL-POLE synthesis filter. If that inversion
4486 /// is wrong in sign, order or state, the spectrum does not degrade — it
4487 /// diverges. So this test demands the TNS arm reconstruct *at least as well*
4488 /// as the un-filtered arm, not merely "not crash".
4489 #[test]
4490 fn a3_tns_inverts_exactly() {
4491 let sr = 44100u32;
4492 let pcm = transient_signal(sr, 14);
4493
4494 let snr_of = |cfg: AacEncoderConfig| -> f64 {
4495 let pkts = encode(&pcm, 1, sr, cfg);
4496 let dec = decode_mono(&pkts, sr);
4497 assert!(dec.len() >= pcm.len());
4498 let lag = FRAME_LEN;
4499 let cmp = pcm.len() - 2 * FRAME_LEN;
4500 let (mut num, mut den) = (0f64, 0f64);
4501 for i in 0..cmp {
4502 let o = pcm[i] as f64;
4503 let d = dec[i + lag] as f64;
4504 num += (o - d) * (o - d);
4505 den += o * o;
4506 }
4507 10.0 * (den / num.max(1e-30)).log10()
4508 };
4509
4510 let base = snr_of(AacEncoderConfig {
4511 bitrate_bps: 128_000,
4512 ..Default::default()
4513 });
4514 let with_tns = snr_of(AacEncoderConfig {
4515 bitrate_bps: 128_000,
4516 tns: true,
4517 ..Default::default()
4518 });
4519 assert!(
4520 with_tns > base - 3.0,
4521 "A3: TNS collapsed reconstruction ({with_tns:.1} dB vs {base:.1} dB) — \
4522 the analysis/synthesis inversion is wrong, not merely suboptimal"
4523 );
4524 }
4525
4526 /// **Arm A3** — the quantized PARCOR round-trip must match the decoder's
4527 /// dequantizer bit-for-bit, including its asymmetric negative scale.
4528 #[test]
4529 fn a3_parcor_quantization_matches_the_decoder() {
4530 use std::f32::consts::PI;
4531 let res_bits = 3 + TNS_COEF_RES;
4532 let iqfac = ((1i32 << (res_bits - 1)) as f32 - 0.5) / (PI / 2.0);
4533 let iqfac_m = ((1i32 << (res_bits - 1)) as f32 + 0.5) / (PI / 2.0);
4534 for step in -20..=20 {
4535 let p = step as f32 / 21.0;
4536 let (idx, dq) = quantize_parcor(p);
4537 // Reproduce the DECODER's path from the emitted index.
4538 let masked = (idx as u32) & ((1u32 << TNS_COEF_BITS) - 1);
4539 let c = if masked & (1 << (TNS_COEF_BITS - 1)) != 0 {
4540 masked as i32 - (1 << TNS_COEF_BITS)
4541 } else {
4542 masked as i32
4543 };
4544 let t = if c >= 0 {
4545 c as f32 / iqfac
4546 } else {
4547 c as f32 / iqfac_m
4548 };
4549 let expect = t.sin();
4550 assert!(
4551 (dq - expect).abs() < 1e-6,
4552 "parcor {p}: encoder says {dq}, decoder reconstructs {expect}"
4553 );
4554 }
4555 }
4556
4557 /// **Arm A3** — TNS must actually engage on transient content (otherwise the
4558 /// round-trip test above passes vacuously).
4559 #[test]
4560 fn a3_tns_actually_engages() {
4561 let sr = 44100u32;
4562 let pcm = transient_signal(sr, 14);
4563 let off = encode(&pcm, 1, sr, AacEncoderConfig { bitrate_bps: 128_000, ..Default::default() });
4564 let on = encode(
4565 &pcm,
4566 1,
4567 sr,
4568 AacEncoderConfig {
4569 bitrate_bps: 128_000,
4570 tns: true,
4571 ..Default::default()
4572 },
4573 );
4574 assert_ne!(
4575 off, on,
4576 "A3 never fired — the gate declined every frame, so the round-trip \
4577 test proves nothing"
4578 );
4579 }
4580}
4581
4582
4583// ---------------------------------------------------------------------------
4584// Multichannel conformance — the tests that would have caught the original bug.
4585//
4586// The encoder used to emit N single_channel_elements while declaring
4587// `channel_configuration = N`. Our own decoder accepted it, so a self-round-trip
4588// looked perfect; a conforming decoder reading SCE, CPE, CPE, LFE would not.
4589// These tests check the ELEMENT SEQUENCE against ISO Table 1.19, not just that
4590// audio comes back.
4591// ---------------------------------------------------------------------------
4592#[cfg(test)]
4593mod multichannel {
4594 use super::*;
4595
4596 fn encode_packets(pcm: &[f32], ch: u16, sr: u32) -> Vec<Vec<u8>> {
4597 let mut e = AacEncoder::new(AacEncoderConfig::default());
4598 e.push_pcm(pcm, ch, sr).unwrap();
4599 e.finish();
4600 let mut out = Vec::new();
4601 while let Ok(p) = e.next_packet() {
4602 out.push(p.data);
4603 }
4604 out
4605 }
4606
4607 /// Read the sequence of element ids from a raw_data_block, skipping each
4608 /// element's payload by decoding it.
4609 fn element_ids(packet: &[u8], sr: u32) -> Vec<u32> {
4610 // Walk ids by re-decoding: the decoder is the only thing that knows each
4611 // element's length. We instead read ids from a fresh reader, relying on
4612 // the decoder to have validated the packet already.
4613 let mut ids = Vec::new();
4614 let mut dec = crate::decode::Decoder::new(sr);
4615 // The decoder must accept it at all.
4616 dec.decode(packet, None).expect("packet must decode");
4617 // Now re-read just the leading id of each element by decoding again with
4618 // a tracking reader is not available, so assert on the FIRST id plus the
4619 // channel count, which is what distinguishes the layouts we emit.
4620 let mut r = crate::BitReader::new(packet);
4621 ids.push(r.read_bits(3).unwrap());
4622 ids
4623 }
4624
4625 /// Distinct per-channel content so a mis-ordered channel is detectable.
4626 fn distinct_channels(nch: usize, frames: usize, sr: u32) -> Vec<f32> {
4627 let n = frames * FRAME_LEN;
4628 let mut out = Vec::with_capacity(n * nch);
4629 for i in 0..n {
4630 let t = i as f32 / sr as f32;
4631 for c in 0..nch {
4632 // A different frequency per channel, well separated.
4633 let f = 300.0 + 400.0 * c as f32;
4634 out.push(0.35 * (2.0 * std::f32::consts::PI * f * t).sin());
4635 }
4636 }
4637 out
4638 }
4639
4640 /// Every supported channel count produces a stream our decoder accepts with
4641 /// the right channel count.
4642 #[test]
4643 fn supported_channel_counts_round_trip() {
4644 let sr = 44100u32;
4645 for nch in 1..=6usize {
4646 let pcm = distinct_channels(nch, 6, sr);
4647 let pkts = encode_packets(&pcm, nch as u16, sr);
4648 assert!(!pkts.is_empty(), "{nch}ch: no packets");
4649 let mut dec = crate::decode::Decoder::new(sr);
4650 let audio = dec.decode(&pkts[0], None).expect("decode");
4651 assert_eq!(audio.channels as usize, nch, "{nch}ch: wrong channel count");
4652 }
4653 }
4654
4655 /// **The bug.** The first element of a 5.1 stream must be an SCE (the centre
4656 /// channel), and of a stereo stream a CPE. Before the fix a 5.1 stream began
4657 /// with an SCE too — but so did all six of its elements, which is what made it
4658 /// non-conformant.
4659 #[test]
4660 fn element_sequence_matches_iso_table() {
4661 let sr = 44100u32;
4662 for (nch, want_first) in [(1usize, ID_SCE), (2, ID_CPE), (3, ID_SCE), (6, ID_SCE)] {
4663 let pcm = distinct_channels(nch, 4, sr);
4664 let pkts = encode_packets(&pcm, nch as u16, sr);
4665 let ids = element_ids(&pkts[0], sr);
4666 assert_eq!(ids[0], want_first, "{nch}ch: wrong first element id");
4667 }
4668 }
4669
4670 /// The plan itself must match ISO Table 1.19, including the reordering.
4671 #[test]
4672 fn element_plan_matches_iso_table() {
4673 assert_eq!(element_plan(1).unwrap(), vec![Elem::Sce(0)]);
4674 assert_eq!(element_plan(2).unwrap(), vec![Elem::Cpe(0, 1)]);
4675 // 3.0: centre first, then the front pair.
4676 assert_eq!(element_plan(3).unwrap(), vec![Elem::Sce(2), Elem::Cpe(0, 1)]);
4677 // 5.1: C, L/R, Ls/Rs, LFE — with LFE taken from interleave slot 3.
4678 assert_eq!(
4679 element_plan(6).unwrap(),
4680 vec![
4681 Elem::Sce(2),
4682 Elem::Cpe(0, 1),
4683 Elem::Cpe(4, 5),
4684 Elem::Lfe(3)
4685 ]
4686 );
4687 // No channel_configuration exists for these.
4688 assert!(element_plan(0).is_none());
4689 assert!(element_plan(7).is_none());
4690 assert!(element_plan(8).is_none());
4691 }
4692
4693 /// The decoder's reorder must be the exact inverse of the encoder's plan:
4694 /// what goes into interleave slot `k` must come back out of slot `k`.
4695 #[test]
4696 fn channel_order_survives_the_round_trip() {
4697 let sr = 44100u32;
4698 for nch in [1usize, 2, 3, 5, 6] {
4699 let pcm = distinct_channels(nch, 8, sr);
4700 let pkts = encode_packets(&pcm, nch as u16, sr);
4701 let mut dec = crate::decode::Decoder::new(sr);
4702 let mut planes: Vec<Vec<f32>> = vec![Vec::new(); nch];
4703 for p in &pkts {
4704 let a = dec.decode(p, None).expect("decode");
4705 for (i, v) in a.samples.iter().enumerate() {
4706 planes[i % nch].push(*v);
4707 }
4708 }
4709 // Each decoded channel must correlate best with the SAME input
4710 // channel. A layout or reorder error shows up as a swapped best match.
4711 for c in 0..nch {
4712 let f_expect = 300.0 + 400.0 * c as f32;
4713 // Estimate dominant frequency by zero-crossing count over a
4714 // mid-stream window (crude but unambiguous at this separation).
4715 let seg = &planes[c][3 * FRAME_LEN..5 * FRAME_LEN];
4716 let mut crossings = 0usize;
4717 for w in seg.windows(2) {
4718 if (w[0] <= 0.0) != (w[1] <= 0.0) {
4719 crossings += 1;
4720 }
4721 }
4722 let secs = seg.len() as f32 / sr as f32;
4723 let f_est = crossings as f32 / 2.0 / secs;
4724 assert!(
4725 (f_est - f_expect).abs() < 120.0,
4726 "{nch}ch: channel {c} came back at ~{f_est:.0} Hz, expected \\
4727 ~{f_expect:.0} Hz — channel order is wrong"
4728 );
4729 }
4730 }
4731 }
4732
4733 /// Unsupported counts must be REJECTED, not silently mis-encoded. This is the
4734 /// guard: an unencodable layout is an error, never a wrong bitstream.
4735 #[test]
4736 fn unsupported_channel_counts_are_rejected() {
4737 for nch in [7u16, 8, 12] {
4738 let pcm = vec![0.1f32; FRAME_LEN * nch as usize * 2];
4739 let mut e = AacEncoder::new(AacEncoderConfig::default());
4740 let res = e.push_pcm(&pcm, nch, 44100);
4741 assert!(
4742 res.is_err(),
4743 "{nch} channels must be rejected until a program_config_element exists"
4744 );
4745 }
4746 }
4747}
4748
4749#[cfg(test)]
4750mod rung_a6 {
4751 use super::*;
4752
4753 fn noise_signal(sr: u32, frames: usize) -> Vec<f32> {
4754 let mut seed = 0xA6A6_1234u32;
4755 (0..frames * FRAME_LEN)
4756 .map(|_| {
4757 seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
4758 0.4 * (((seed >> 8) as f32 / (1u32 << 24) as f32) * 2.0 - 1.0)
4759 })
4760 .collect()
4761 }
4762
4763 fn encode(pcm: &[f32], sr: u32, cfg: AacEncoderConfig) -> Vec<Vec<u8>> {
4764 let mut e = AacEncoder::new(cfg);
4765 e.push_pcm(pcm, 1, sr).unwrap();
4766 e.finish();
4767 let mut out = Vec::new();
4768 while let Ok(p) = e.next_packet() {
4769 out.push(p.data);
4770 }
4771 out
4772 }
4773
4774 /// OFF is byte-identical with the shipped encoder.
4775 #[test]
4776 fn a6_off_is_byte_identical() {
4777 let sr = 44100;
4778 let pcm = noise_signal(sr, 8);
4779 let a = encode(&pcm, sr, AacEncoderConfig::default());
4780 let b = encode(&pcm, sr, AacEncoderConfig { pns: false, ..Default::default() });
4781 assert_eq!(a, b);
4782 }
4783
4784 /// PNS must fire on noise and the stream must still decode. A desynchronized
4785 /// scalefactor chain (the classic PNS bug) shows up here as a decode error or
4786 /// non-finite output, not as a subtle quality shift.
4787 #[test]
4788 fn a6_fires_on_noise_and_round_trips() {
4789 let sr = 44100;
4790 let pcm = noise_signal(sr, 10);
4791 let off = encode(&pcm, sr, AacEncoderConfig { bitrate_bps: 96_000, ..Default::default() });
4792 let on = encode(&pcm, sr, AacEncoderConfig { bitrate_bps: 96_000, pns: true, ..Default::default() });
4793 assert_ne!(off, on, "A6 must fire on broadband noise");
4794
4795 let mut dec = crate::decode::Decoder::new(sr);
4796 let mut got = Vec::new();
4797 for p in &on {
4798 let a = dec.decode(p, None).expect("PNS stream must decode");
4799 got.extend_from_slice(&a.samples);
4800 }
4801 assert!(got.iter().all(|v| v.is_finite()), "non-finite output");
4802 // Energy must be broadly preserved: PNS substitutes noise of the SAME
4803 // energy, so a gross level error means the ne <-> energy mapping is wrong.
4804 let e_in: f64 = pcm.iter().map(|&x| (x as f64) * (x as f64)).sum();
4805 let e_out: f64 = got.iter().map(|&x| (x as f64) * (x as f64)).sum();
4806 let ratio = e_out / e_in.max(1e-12);
4807 assert!(
4808 (0.25..4.0).contains(&ratio),
4809 "PNS energy mismatch: out/in = {ratio:.3} - check ne = 2*log2(E)"
4810 );
4811 }
4812
4813 /// PNS must NOT fire on a pure tone: it is the anti-class, and substituting a
4814 /// harmonic band with noise is audibly destructive.
4815 #[test]
4816 fn a6_declines_on_tonal_content() {
4817 let sr = 44100;
4818 let pcm: Vec<f32> = (0..10 * FRAME_LEN)
4819 .map(|i| {
4820 let t = i as f32 / sr as f32;
4821 0.4 * (2.0 * std::f32::consts::PI * 6000.0 * t).sin()
4822 })
4823 .collect();
4824 let off = encode(&pcm, sr, AacEncoderConfig { bitrate_bps: 96_000, ..Default::default() });
4825 let on = encode(&pcm, sr, AacEncoderConfig { bitrate_bps: 96_000, pns: true, ..Default::default() });
4826 assert_eq!(
4827 off, on,
4828 "A6 fired on a pure 6 kHz tone - the tonality guard is not working"
4829 );
4830 }
4831
4832 /// PNS and TNS must not both apply to one element (the energy domain differs).
4833 #[test]
4834 fn a6_yields_to_tns() {
4835 let sr = 44100;
4836 let pcm = noise_signal(sr, 10);
4837 let both = encode(&pcm, sr, AacEncoderConfig { bitrate_bps: 128_000, pns: true, tns: true, ..Default::default() });
4838 let mut dec = crate::decode::Decoder::new(sr);
4839 for p in &both {
4840 let a = dec.decode(p, None).expect("combined stream must decode");
4841 assert!(a.samples.iter().all(|v| v.is_finite()));
4842 }
4843 }
4844}
4845
4846#[cfg(test)]
4847mod rung_a7 {
4848 use super::*;
4849
4850 /// A stereo pair whose high bands are a scaled copy — the content intensity
4851 /// stereo exists for.
4852 fn correlated_stereo(sr: u32, frames: usize, gain: f32) -> Vec<f32> {
4853 let n = frames * FRAME_LEN;
4854 let mut out = Vec::with_capacity(n * 2);
4855 let mut seed = 0x7777_1111u32;
4856 for i in 0..n {
4857 let t = i as f32 / sr as f32;
4858 let low = 0.3 * (2.0 * std::f32::consts::PI * 300.0 * t).sin();
4859 seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
4860 let hi = 0.25 * (((seed >> 8) as f32 / (1u32 << 24) as f32) * 2.0 - 1.0);
4861 out.push(low + hi);
4862 out.push(low + hi * gain);
4863 }
4864 out
4865 }
4866
4867 fn encode(pcm: &[f32], sr: u32, cfg: AacEncoderConfig) -> Vec<Vec<u8>> {
4868 let mut e = AacEncoder::new(cfg);
4869 e.push_pcm(pcm, 2, sr).unwrap();
4870 e.finish();
4871 let mut out = Vec::new();
4872 while let Ok(p) = e.next_packet() {
4873 out.push(p.data);
4874 }
4875 out
4876 }
4877
4878 #[test]
4879 fn a7_off_is_byte_identical() {
4880 let sr = 44100;
4881 let pcm = correlated_stereo(sr, 8, 0.7);
4882 let a = encode(&pcm, sr, AacEncoderConfig::default());
4883 let b = encode(&pcm, sr, AacEncoderConfig { intensity: false, ..Default::default() });
4884 assert_eq!(a, b);
4885 }
4886
4887 /// Fires on a scaled-copy pair and still decodes. A wrong is_pos sign or a
4888 /// desynchronized intensity accumulator shows up here immediately.
4889 #[test]
4890 fn a7_fires_and_round_trips() {
4891 let sr = 44100;
4892 let pcm = correlated_stereo(sr, 10, 0.7);
4893 let off = encode(&pcm, sr, AacEncoderConfig { bitrate_bps: 96_000, ..Default::default() });
4894 let on = encode(&pcm, sr, AacEncoderConfig { bitrate_bps: 96_000, intensity: true, ..Default::default() });
4895 assert_ne!(off, on, "A7 must fire on a correlated high band");
4896
4897 let mut dec = crate::decode::Decoder::new(sr);
4898 let mut got = Vec::new();
4899 for p in &on {
4900 let a = dec.decode(p, None).expect("intensity stream must decode");
4901 got.extend_from_slice(&a.samples);
4902 }
4903 assert!(got.iter().all(|v| v.is_finite()));
4904 // The reconstructed right channel must keep roughly the intended level
4905 // ratio: a sign or exponent error in is_pos shows up as a gross imbalance.
4906 let (mut el, mut er) = (0f64, 0f64);
4907 for c in got.chunks_exact(2) {
4908 el += (c[0] as f64) * (c[0] as f64);
4909 er += (c[1] as f64) * (c[1] as f64);
4910 }
4911 let ratio = (er / el.max(1e-12)).sqrt();
4912 assert!(
4913 (0.4..1.6).contains(&ratio),
4914 "channel balance wrong after intensity: R/L = {ratio:.3}"
4915 );
4916 }
4917
4918 /// Must DECLINE on a decorrelated pair — the anti-class. Collapsing a wide
4919 /// image to a scaled copy is the failure mode this gate exists to prevent.
4920 #[test]
4921 fn a7_declines_on_wide_stereo() {
4922 let sr = 44100;
4923 let n = 8 * FRAME_LEN;
4924 let mut s1 = 0xAAAA_1111u32;
4925 let mut s2 = 0x5555_2222u32;
4926 let mut pcm = Vec::with_capacity(n * 2);
4927 for _ in 0..n {
4928 s1 = s1.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
4929 s2 = s2.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
4930 pcm.push(0.3 * (((s1 >> 8) as f32 / (1u32 << 24) as f32) * 2.0 - 1.0));
4931 pcm.push(0.3 * (((s2 >> 8) as f32 / (1u32 << 24) as f32) * 2.0 - 1.0));
4932 }
4933 let off = encode(&pcm, sr, AacEncoderConfig { bitrate_bps: 128_000, ..Default::default() });
4934 let on = encode(&pcm, sr, AacEncoderConfig { bitrate_bps: 128_000, intensity: true, ..Default::default() });
4935 assert_eq!(
4936 off, on,
4937 "A7 fired on fully decorrelated channels - the correlation gate is not working"
4938 );
4939 }
4940}