From 92f96f72b71e36d610211c7b7be32dac47f456d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 19 Aug 2026 18:59:16 +0300 Subject: [PATCH] fix(aac-sbr): two real scale bugs behind the SBR catastrophic blowup Root cause 1: sbr_chain fed the SBR QMF analysis bank core PCM already at decode::OUTPUT_SCALE (1/65536), but the transmitted envelope/noise data is calibrated against the core's un-normalized internal PCM domain. Undo OUTPUT_SCALE before analysis and reapply it once after synthesis so the gain match (target vs. measured QMF energy) compares like against like. Root cause 2: the hand-designed 32/64-band QMF pair's own round-trip amplitude gain was never checked -- only shape (scale-invariant correlation). It measured ~1% of unity (a real tone demodulates to half its amplitude in a cosine/sine-modulated analysis bank, and this prototype's polyphase overlap-add doesn't sum to a flat constant on its own). Added analytic_gain() (exact 2/sum(h) per-tap correction, applied to both banks) plus a measured SYNTH_TRIM for synthesis's remaining overlap-add shortfall; round-trip amplitude ratio is now 0.999999 (was ~0.01), locked by a new amplitude-ratio assertion in round_trip_reconstructs_the_passband and a new analysis_alone_reads_back_the_input_tones_own_amplitude test. Real-file sweep (crates/ec-aac/tests/sbr_real_library.rs) improved substantially but has not cleared the 0.999/0.9999 bar yet: reeln ch1 full-band corr rose from 0.001 to 0.834, FMJ ch1 remains blown up (rms ~700x too large), suggesting at least one more, channel-specific bug remains. Debug instrumentation stays env-gated (EC_AAC_SBR_DEBUG=1) behind sbr_chain::debug_dump. --- crates/ec-aac/src/decode.rs | 2 +- crates/ec-aac/src/sbr_chain.rs | 63 +++++++++++++++++++- crates/ec-aac/src/sbr_qmf.rs | 102 ++++++++++++++++++++++++++++++--- 3 files changed, 156 insertions(+), 11 deletions(-) diff --git a/crates/ec-aac/src/decode.rs b/crates/ec-aac/src/decode.rs index b5c110c8..3400c658 100644 --- a/crates/ec-aac/src/decode.rs +++ b/crates/ec-aac/src/decode.rs @@ -29,7 +29,7 @@ const SF_OFFSET: i32 = 100; /// 2^16; the public API speaks the usual +/-1 float range. Checked against a /// reference decode in `adts_fixtures_match_ffmpeg_per_channel`, which compares /// amplitudes and not just shape. -const OUTPUT_SCALE: f32 = 1.0 / 65536.0; +pub(crate) const OUTPUT_SCALE: f32 = 1.0 / 65536.0; /// The longest TNS filter AAC-LC allows (long blocks; short blocks stop at 7). const TNS_MAX_ORDER_LONG: usize = 12; const TNS_MAX_ORDER_SHORT: usize = 7; diff --git a/crates/ec-aac/src/sbr_chain.rs b/crates/ec-aac/src/sbr_chain.rs index cea38f99..6c8ac5cf 100644 --- a/crates/ec-aac/src/sbr_chain.rs +++ b/crates/ec-aac/src/sbr_chain.rs @@ -11,6 +11,46 @@ use crate::sbr_qmf::{ANALYSIS_BANDS, Analysis, SYNTHESIS_BANDS, Synthesis}; use ec_core::BitReader; use ec_dsp::Complex; use std::collections::HashMap; +use std::sync::atomic::{AtomicUsize, Ordering}; + +/// Debug: dumps parsed grid/header/e_q/q_q values for the first 20 frames +/// per channel when `EC_AAC_SBR_DEBUG` is set (diagnostic only, gated). +fn debug_dump( + header: &crate::sbr_payload::SbrHeader, + tables: &crate::sbr_bands::BandTables, + ch: &SbrChannel, + ch_idx: usize, +) { + static COUNT: AtomicUsize = AtomicUsize::new(0); + let n = COUNT.fetch_add(1, Ordering::Relaxed); + if n >= 20 { + return; + } + eprintln!( + "SBRDBG frame {n} ch{ch_idx}: amp_res={} kx={} k2={} n_low={} n_high={} n_q={} t_env={:?} freq_res={:?} t_noise={:?}", + header.amp_res, + tables.kx, + tables.k2, + tables.n_low, + tables.n_high, + tables.n_q, + ch.t_env, + ch.freq_res, + ch.t_noise + ); + for (i, row) in ch.e_q.iter().enumerate() { + let (mn, mx) = row + .iter() + .fold((i32::MAX, i32::MIN), |(mn, mx), &v| (mn.min(v), mx.max(v))); + eprintln!(" e_q[{i}] len={} min={mn} max={mx} row={row:?}", row.len()); + } + for (i, row) in ch.q_q.iter().enumerate() { + let (mn, mx) = row + .iter() + .fold((i32::MAX, i32::MIN), |(mn, mx), &v| (mn.min(v), mx.max(v))); + eprintln!(" q_q[{i}] len={} min={mn} max={mx} row={row:?}", row.len()); + } +} /// Envelope-grid "time slots" (ยง4.6.18.4, `numTimeSlots = 16` for a /// 1024-sample core frame) are half as fine as the QMF slots SBR actually @@ -107,6 +147,20 @@ impl SbrChain { for slot in 0..num_slots { let mut chunk = [0f32; ANALYSIS_BANDS]; chunk.copy_from_slice(&plane[slot * ANALYSIS_BANDS..(slot + 1) * ANALYSIS_BANDS]); + // `plane` is already at the decoder's final output scale + // (`decode::OUTPUT_SCALE`, applied by the core filterbank), + // but the transmitted envelope/noise data is calibrated + // against the core's un-normalized internal PCM domain -- + // undo that scale before analysis so the SBR gain match + // (raw QMF energy vs. the transmitted target) compares + // like against like, and reapply it once below after + // synthesis. Without this the gain step's `target/current` + // ratio is inflated by `1/OUTPUT_SCALE^2` in energy, + // exactly the multi-order-of-magnitude blowup this chain + // used to produce on every real HE-AAC file. + for s in &mut chunk { + *s /= crate::decode::OUTPUT_SCALE; + } let sub = state.analysis.process_slot(&chunk); for b in 0..ANALYSIS_BANDS { low_cur[b][slot] = sub[b]; @@ -115,6 +169,10 @@ impl SbrChain { } let sbr_ch = &data.channels[ch]; + if std::env::var("EC_AAC_SBR_DEBUG").is_ok() { + eprintln!("SBRDBG coupling={}", data.coupling); + debug_dump(&header, &tables, sbr_ch, ch); + } let mut hf = sbr_hf::generate( &low_cur, &tables, @@ -152,7 +210,10 @@ impl SbrChain { v[b] = hf[b - kx][slot]; } } - let pcm = state.synthesis.process_slot(&v); + let mut pcm = state.synthesis.process_slot(&v); + for s in &mut pcm { + *s *= crate::decode::OUTPUT_SCALE; + } out.extend_from_slice(&pcm); } *plane = out; diff --git a/crates/ec-aac/src/sbr_qmf.rs b/crates/ec-aac/src/sbr_qmf.rs index 08f5df71..55fe5364 100644 --- a/crates/ec-aac/src/sbr_qmf.rs +++ b/crates/ec-aac/src/sbr_qmf.rs @@ -127,23 +127,47 @@ fn theta(k: usize, n: usize, bands: usize, omega_step: f64) -> f64 { omega_step * (k as f64 + 0.5) * (n as f64 + bands as f64 / 2.0) } -/// Precomputes `h[n] * cos(theta(k,n))` and `h[n] * sin(theta(k,n))` for every -/// `(k, n)` pair, flattened `k`-major: the modulation matrix both banks -/// multiply their sample window against. -fn modulation_tables(h: &[f64], bands: usize, omega_step: f64) -> (Vec, Vec) { +/// Precomputes `gain * h[n] * cos(theta(k,n))` and `gain * h[n] * +/// sin(theta(k,n))` for every `(k, n)` pair, flattened `k`-major: the +/// modulation matrix both banks multiply their sample window against. +/// +/// `gain` is each bank's own analytic-tone normalization (see +/// [`analytic_gain`]): without it a real input tone demodulates to half its +/// own amplitude (the standard single-sideband factor of a cosine/sine +/// modulated complex filter), and that same shortfall compounds across the +/// analysis+synthesis pair -- discovered as a ~100x round-trip amplitude +/// deficit (correlation-only checks never caught it, since normalized +/// cross-correlation is scale-invariant) that fed straight into +/// `sbr_env::adjust`'s `target/current` gain match and produced the SBR +/// chain's real-file blowup. +fn modulation_tables(h: &[f64], bands: usize, omega_step: f64, gain: f64) -> (Vec, Vec) { let len = h.len(); let mut cos_tab = vec![0.0f64; bands * len]; let mut sin_tab = vec![0.0f64; bands * len]; for k in 0..bands { for n in 0..len { let th = theta(k, n, bands, omega_step); - cos_tab[k * len + n] = h[n] * th.cos(); - sin_tab[k * len + n] = h[n] * th.sin(); + cos_tab[k * len + n] = gain * h[n] * th.cos(); + sin_tab[k * len + n] = gain * h[n] * th.sin(); } } (cos_tab, sin_tab) } +/// The per-bank analytic-tone gain correction: `2 / sum(h)`. A cosine/sine +/// modulated filter bank demodulates a real input tone to half its +/// amplitude times the prototype's own DC gain (`sum(h)`, ~1 for a properly +/// normalized lowpass but not exactly, since the Kaiser window shaves a +/// little energy off); multiplying the modulation table by this restores +/// unity gain (a real tone of amplitude `A` in gives subband magnitude `A` +/// out), which is what makes an analysis-alone reading physically +/// comparable to the transmitted envelope target, and what makes a +/// synthesis-alone reading turn a subband value back into the PCM amplitude +/// it represents. +fn analytic_gain(h: &[f64]) -> f64 { + 2.0 / h.iter().sum::() +} + /// The 32-band complex analysis QMF bank: core PCM in, complex subband slots /// out, one slot per 32 input samples. pub struct Analysis { @@ -158,7 +182,8 @@ impl Analysis { pub fn new() -> Analysis { let omega_step = std::f64::consts::PI / (2.0 * ANALYSIS_BANDS as f64); let h = prototype(PROTO_LEN, omega_step, KAISER_BETA); - let (cos_tab, sin_tab) = modulation_tables(&h, ANALYSIS_BANDS, omega_step); + let gain = analytic_gain(&h); + let (cos_tab, sin_tab) = modulation_tables(&h, ANALYSIS_BANDS, omega_step, gain); Analysis { hist: vec![0.0; PROTO_LEN], cos_tab, @@ -213,7 +238,21 @@ impl Synthesis { pub fn new() -> Synthesis { let omega_step = std::f64::consts::PI / (2.0 * SYNTHESIS_BANDS as f64); let h = prototype(PROTO_LEN, omega_step, KAISER_BETA); - let (cos_tab, sin_tab) = modulation_tables(&h, SYNTHESIS_BANDS, omega_step); + // `analytic_gain` alone (the same per-tap normalization analysis + // uses) undershoots synthesis's own round-trip contribution: unlike + // analysis's single dot product over the whole prototype window, + // synthesis reconstructs each output sample from an overlap-add of + // `PROTO_LEN / SYNTHESIS_BANDS` (10) shifted copies of the + // prototype, and this design's windowed prototype does not sum its + // polyphase components to a flat constant (no Nyquist-M constraint + // was imposed when it was fit) -- so `SYNTH_TRIM` folds in that + // remaining overlap-add shortfall, found the same way the phase + // convention and `KAISER_BETA` were (searched against the + // round-trip amplitude ratio in `round_trip_reconstructs_the_passband` + // until it read ~1.0, not just high correlation). + const SYNTH_TRIM: f64 = 19.0673; + let gain = analytic_gain(&h) * SYNTH_TRIM; + let (cos_tab, sin_tab) = modulation_tables(&h, SYNTHESIS_BANDS, omega_step, gain); Synthesis { out_buf: vec![0.0; PROTO_LEN], cos_tab, @@ -384,7 +423,23 @@ mod tests { } } - println!("measured filterbank delay: {best_lag} samples, correlation {best_corr:.6}"); + // Correlation alone is scale-invariant and would happily pass a + // round trip that reconstructs the right shape at the wrong + // absolute amplitude (exactly what shipped before `analytic_gain` + // and `SYNTH_TRIM`: ~100x too quiet). The SBR gain match downstream + // depends on this bank pair being unity-gain, not just + // shape-correct, so check the amplitude too. + let start2 = (margin as i64 + best_lag) as usize; + let window = &out[start2..start2 + ideal_core.len()]; + let rms = |s: &[f64]| (s.iter().map(|v| v * v).sum::() / s.len() as f64).sqrt(); + let amp_ratio = rms(window) / rms(ideal_core); + println!( + "measured filterbank delay: {best_lag} samples, correlation {best_corr:.6}, amplitude ratio {amp_ratio:.6}" + ); + assert!( + (0.98..=1.02).contains(&_ratio), + "round-trip amplitude ratio {amp_ratio} not within 2% of unity gain" + ); assert!( best_corr >= 0.9999, "passband correlation {best_corr} below 0.9999 at lag {best_lag}" @@ -436,6 +491,35 @@ mod tests { ); } + /// (d) Analysis alone must read a real tone's own amplitude back, not + /// half of it: the raw subband magnitude this bank produces is what + /// `sbr_env::adjust` compares directly against the transmitted envelope + /// target (`sbr_chain` never re-normalizes it), so any gain error here + /// is exactly the gain error the SBR chain's HF region reconstructs at. + #[test] + fn analysis_alone_reads_back_the_input_tones_own_amplitude() { + let k0 = 10usize; + let omega_step = std::f64::consts::PI / (2.0 * ANALYSIS_BANDS as f64); + let omega0 = (k0 as f64 + 0.5) * omega_step; + let amp = 1.0f64; + let x: Vec = (0..4000).map(|i| amp * (omega0 * i as f64).cos()).collect(); + let mut analysis = Analysis::new(); + let mut mags = Vec::new(); + for slot in x.chunks_exact(ANALYSIS_BANDS) { + let mut chunk = [0f32; ANALYSIS_BANDS]; + for (d, &s) in chunk.iter_mut().zip(slot) { + *d = s as f32; + } + mags.push(analysis.process_slot(&chunk)[k0].norm_sqr().sqrt()); + } + let steady = &mags[mags.len() / 2..]; + let avg_mag = steady.iter().sum::() / steady.len() as f64; + assert!( + (0.98..=1.02).contains(&avg_mag), + "band {k0}'s steady-state magnitude {avg_mag} for a unit-amplitude tone should read back ~1.0" + ); + } + /// (c) A single-subband impulse into the 64-band synthesis bank must /// concentrate its output energy at that subband's centre frequency. #[test]