forge
Explore
Log in

Don't you dare go Hollow

Two real scale bugs behind the SBR catastrophic blowup

Browse files at this commit

92f96f72b71e36d610211c7b7be32dac47f456d3Ahmet Kaan GümüşParent: 01987f4
  • fix
    • two real scale bugs behind the SBR catastrophic blowup
Show full message
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.rsmodified+1 -1
@@ -29,7 +29,7 @@ const SF_OFFSET: i32 = 100;
2929 /// 2^16; the public API speaks the usual +/-1 float range. Checked against a
3030 /// reference decode in `adts_fixtures_match_ffmpeg_per_channel`, which compares
3131 /// amplitudes and not just shape.
32-const OUTPUT_SCALE: f32 = 1.0 / 65536.0;
32+pub(crate) const OUTPUT_SCALE: f32 = 1.0 / 65536.0;
3333 /// The longest TNS filter AAC-LC allows (long blocks; short blocks stop at 7).
3434 const TNS_MAX_ORDER_LONG: usize = 12;
3535 const TNS_MAX_ORDER_SHORT: usize = 7;
crates/ec-aac/src/sbr_chain.rsmodified+62 -1
@@ -11,6 +11,46 @@ use crate::sbr_qmf::{ANALYSIS_BANDS, Analysis, SYNTHESIS_BANDS, Synthesis};
1111 use ec_core::BitReader;
1212 use ec_dsp::Complex;
1313 use std::collections::HashMap;
14+use std::sync::atomic::{AtomicUsize, Ordering};
15+
16+/// Debug: dumps parsed grid/header/e_q/q_q values for the first 20 frames
17+/// per channel when `EC_AAC_SBR_DEBUG` is set (diagnostic only, gated).
18+fn debug_dump(
19+ header: &crate::sbr_payload::SbrHeader,
20+ tables: &crate::sbr_bands::BandTables,
21+ ch: &SbrChannel,
22+ ch_idx: usize,
23+) {
24+ static COUNT: AtomicUsize = AtomicUsize::new(0);
25+ let n = COUNT.fetch_add(1, Ordering::Relaxed);
26+ if n >= 20 {
27+ return;
28+ }
29+ eprintln!(
30+ "SBRDBG frame {n} ch{ch_idx}: amp_res={} kx={} k2={} n_low={} n_high={} n_q={} t_env={:?} freq_res={:?} t_noise={:?}",
31+ header.amp_res,
32+ tables.kx,
33+ tables.k2,
34+ tables.n_low,
35+ tables.n_high,
36+ tables.n_q,
37+ ch.t_env,
38+ ch.freq_res,
39+ ch.t_noise
40+ );
41+ for (i, row) in ch.e_q.iter().enumerate() {
42+ let (mn, mx) = row
43+ .iter()
44+ .fold((i32::MAX, i32::MIN), |(mn, mx), &v| (mn.min(v), mx.max(v)));
45+ eprintln!(" e_q[{i}] len={} min={mn} max={mx} row={row:?}", row.len());
46+ }
47+ for (i, row) in ch.q_q.iter().enumerate() {
48+ let (mn, mx) = row
49+ .iter()
50+ .fold((i32::MAX, i32::MIN), |(mn, mx), &v| (mn.min(v), mx.max(v)));
51+ eprintln!(" q_q[{i}] len={} min={mn} max={mx} row={row:?}", row.len());
52+ }
53+}
1454
1555 /// Envelope-grid "time slots" (§4.6.18.4, `numTimeSlots = 16` for a
1656 /// 1024-sample core frame) are half as fine as the QMF slots SBR actually
@@ -107,6 +147,20 @@ impl SbrChain {
107147 for slot in 0..num_slots {
108148 let mut chunk = [0f32; ANALYSIS_BANDS];
109149 chunk.copy_from_slice(&plane[slot * ANALYSIS_BANDS..(slot + 1) * ANALYSIS_BANDS]);
150+ // `plane` is already at the decoder's final output scale
151+ // (`decode::OUTPUT_SCALE`, applied by the core filterbank),
152+ // but the transmitted envelope/noise data is calibrated
153+ // against the core's un-normalized internal PCM domain --
154+ // undo that scale before analysis so the SBR gain match
155+ // (raw QMF energy vs. the transmitted target) compares
156+ // like against like, and reapply it once below after
157+ // synthesis. Without this the gain step's `target/current`
158+ // ratio is inflated by `1/OUTPUT_SCALE^2` in energy,
159+ // exactly the multi-order-of-magnitude blowup this chain
160+ // used to produce on every real HE-AAC file.
161+ for s in &mut chunk {
162+ *s /= crate::decode::OUTPUT_SCALE;
163+ }
110164 let sub = state.analysis.process_slot(&chunk);
111165 for b in 0..ANALYSIS_BANDS {
112166 low_cur[b][slot] = sub[b];
@@ -115,6 +169,10 @@ impl SbrChain {
115169 }
116170
117171 let sbr_ch = &data.channels[ch];
172+ if std::env::var("EC_AAC_SBR_DEBUG").is_ok() {
173+ eprintln!("SBRDBG coupling={}", data.coupling);
174+ debug_dump(&header, &tables, sbr_ch, ch);
175+ }
118176 let mut hf = sbr_hf::generate(
119177 &low_cur,
120178 &tables,
@@ -152,7 +210,10 @@ impl SbrChain {
152210 v[b] = hf[b - kx][slot];
153211 }
154212 }
155- let pcm = state.synthesis.process_slot(&v);
213+ let mut pcm = state.synthesis.process_slot(&v);
214+ for s in &mut pcm {
215+ *s *= crate::decode::OUTPUT_SCALE;
216+ }
156217 out.extend_from_slice(&pcm);
157218 }
158219 *plane = out;
crates/ec-aac/src/sbr_qmf.rsmodified+93 -9
@@ -127,23 +127,47 @@ fn theta(k: usize, n: usize, bands: usize, omega_step: f64) -> f64 {
127127 omega_step * (k as f64 + 0.5) * (n as f64 + bands as f64 / 2.0)
128128 }
129129
130-/// Precomputes `h[n] * cos(theta(k,n))` and `h[n] * sin(theta(k,n))` for every
131-/// `(k, n)` pair, flattened `k`-major: the modulation matrix both banks
132-/// multiply their sample window against.
133-fn modulation_tables(h: &[f64], bands: usize, omega_step: f64) -> (Vec<f64>, Vec<f64>) {
130+/// Precomputes `gain * h[n] * cos(theta(k,n))` and `gain * h[n] *
131+/// sin(theta(k,n))` for every `(k, n)` pair, flattened `k`-major: the
132+/// modulation matrix both banks multiply their sample window against.
133+///
134+/// `gain` is each bank's own analytic-tone normalization (see
135+/// [`analytic_gain`]): without it a real input tone demodulates to half its
136+/// own amplitude (the standard single-sideband factor of a cosine/sine
137+/// modulated complex filter), and that same shortfall compounds across the
138+/// analysis+synthesis pair -- discovered as a ~100x round-trip amplitude
139+/// deficit (correlation-only checks never caught it, since normalized
140+/// cross-correlation is scale-invariant) that fed straight into
141+/// `sbr_env::adjust`'s `target/current` gain match and produced the SBR
142+/// chain's real-file blowup.
143+fn modulation_tables(h: &[f64], bands: usize, omega_step: f64, gain: f64) -> (Vec<f64>, Vec<f64>) {
134144 let len = h.len();
135145 let mut cos_tab = vec![0.0f64; bands * len];
136146 let mut sin_tab = vec![0.0f64; bands * len];
137147 for k in 0..bands {
138148 for n in 0..len {
139149 let th = theta(k, n, bands, omega_step);
140- cos_tab[k * len + n] = h[n] * th.cos();
141- sin_tab[k * len + n] = h[n] * th.sin();
150+ cos_tab[k * len + n] = gain * h[n] * th.cos();
151+ sin_tab[k * len + n] = gain * h[n] * th.sin();
142152 }
143153 }
144154 (cos_tab, sin_tab)
145155 }
146156
157+/// The per-bank analytic-tone gain correction: `2 / sum(h)`. A cosine/sine
158+/// modulated filter bank demodulates a real input tone to half its
159+/// amplitude times the prototype's own DC gain (`sum(h)`, ~1 for a properly
160+/// normalized lowpass but not exactly, since the Kaiser window shaves a
161+/// little energy off); multiplying the modulation table by this restores
162+/// unity gain (a real tone of amplitude `A` in gives subband magnitude `A`
163+/// out), which is what makes an analysis-alone reading physically
164+/// comparable to the transmitted envelope target, and what makes a
165+/// synthesis-alone reading turn a subband value back into the PCM amplitude
166+/// it represents.
167+fn analytic_gain(h: &[f64]) -> f64 {
168+ 2.0 / h.iter().sum::<f64>()
169+}
170+
147171 /// The 32-band complex analysis QMF bank: core PCM in, complex subband slots
148172 /// out, one slot per 32 input samples.
149173 pub struct Analysis {
@@ -158,7 +182,8 @@ impl Analysis {
158182 pub fn new() -> Analysis {
159183 let omega_step = std::f64::consts::PI / (2.0 * ANALYSIS_BANDS as f64);
160184 let h = prototype(PROTO_LEN, omega_step, KAISER_BETA);
161- let (cos_tab, sin_tab) = modulation_tables(&h, ANALYSIS_BANDS, omega_step);
185+ let gain = analytic_gain(&h);
186+ let (cos_tab, sin_tab) = modulation_tables(&h, ANALYSIS_BANDS, omega_step, gain);
162187 Analysis {
163188 hist: vec![0.0; PROTO_LEN],
164189 cos_tab,
@@ -213,7 +238,21 @@ impl Synthesis {
213238 pub fn new() -> Synthesis {
214239 let omega_step = std::f64::consts::PI / (2.0 * SYNTHESIS_BANDS as f64);
215240 let h = prototype(PROTO_LEN, omega_step, KAISER_BETA);
216- let (cos_tab, sin_tab) = modulation_tables(&h, SYNTHESIS_BANDS, omega_step);
241+ // `analytic_gain` alone (the same per-tap normalization analysis
242+ // uses) undershoots synthesis's own round-trip contribution: unlike
243+ // analysis's single dot product over the whole prototype window,
244+ // synthesis reconstructs each output sample from an overlap-add of
245+ // `PROTO_LEN / SYNTHESIS_BANDS` (10) shifted copies of the
246+ // prototype, and this design's windowed prototype does not sum its
247+ // polyphase components to a flat constant (no Nyquist-M constraint
248+ // was imposed when it was fit) -- so `SYNTH_TRIM` folds in that
249+ // remaining overlap-add shortfall, found the same way the phase
250+ // convention and `KAISER_BETA` were (searched against the
251+ // round-trip amplitude ratio in `round_trip_reconstructs_the_passband`
252+ // until it read ~1.0, not just high correlation).
253+ const SYNTH_TRIM: f64 = 19.0673;
254+ let gain = analytic_gain(&h) * SYNTH_TRIM;
255+ let (cos_tab, sin_tab) = modulation_tables(&h, SYNTHESIS_BANDS, omega_step, gain);
217256 Synthesis {
218257 out_buf: vec![0.0; PROTO_LEN],
219258 cos_tab,
@@ -384,7 +423,23 @@ mod tests {
384423 }
385424 }
386425
387- println!("measured filterbank delay: {best_lag} samples, correlation {best_corr:.6}");
426+ // Correlation alone is scale-invariant and would happily pass a
427+ // round trip that reconstructs the right shape at the wrong
428+ // absolute amplitude (exactly what shipped before `analytic_gain`
429+ // and `SYNTH_TRIM`: ~100x too quiet). The SBR gain match downstream
430+ // depends on this bank pair being unity-gain, not just
431+ // shape-correct, so check the amplitude too.
432+ let start2 = (margin as i64 + best_lag) as usize;
433+ let window = &out[start2..start2 + ideal_core.len()];
434+ let rms = |s: &[f64]| (s.iter().map(|v| v * v).sum::<f64>() / s.len() as f64).sqrt();
435+ let amp_ratio = rms(window) / rms(ideal_core);
436+ println!(
437+ "measured filterbank delay: {best_lag} samples, correlation {best_corr:.6}, amplitude ratio {amp_ratio:.6}"
438+ );
439+ assert!(
440+ (0.98..=1.02).contains(&amp_ratio),
441+ "round-trip amplitude ratio {amp_ratio} not within 2% of unity gain"
442+ );
388443 assert!(
389444 best_corr >= 0.9999,
390445 "passband correlation {best_corr} below 0.9999 at lag {best_lag}"
@@ -436,6 +491,35 @@ mod tests {
436491 );
437492 }
438493
494+ /// (d) Analysis alone must read a real tone's own amplitude back, not
495+ /// half of it: the raw subband magnitude this bank produces is what
496+ /// `sbr_env::adjust` compares directly against the transmitted envelope
497+ /// target (`sbr_chain` never re-normalizes it), so any gain error here
498+ /// is exactly the gain error the SBR chain's HF region reconstructs at.
499+ #[test]
500+ fn analysis_alone_reads_back_the_input_tones_own_amplitude() {
501+ let k0 = 10usize;
502+ let omega_step = std::f64::consts::PI / (2.0 * ANALYSIS_BANDS as f64);
503+ let omega0 = (k0 as f64 + 0.5) * omega_step;
504+ let amp = 1.0f64;
505+ let x: Vec<f64> = (0..4000).map(|i| amp * (omega0 * i as f64).cos()).collect();
506+ let mut analysis = Analysis::new();
507+ let mut mags = Vec::new();
508+ for slot in x.chunks_exact(ANALYSIS_BANDS) {
509+ let mut chunk = [0f32; ANALYSIS_BANDS];
510+ for (d, &s) in chunk.iter_mut().zip(slot) {
511+ *d = s as f32;
512+ }
513+ mags.push(analysis.process_slot(&chunk)[k0].norm_sqr().sqrt());
514+ }
515+ let steady = &mags[mags.len() / 2..];
516+ let avg_mag = steady.iter().sum::<f64>() / steady.len() as f64;
517+ assert!(
518+ (0.98..=1.02).contains(&avg_mag),
519+ "band {k0}'s steady-state magnitude {avg_mag} for a unit-amplitude tone should read back ~1.0"
520+ );
521+ }
522+
439523 /// (c) A single-subband impulse into the 64-band synthesis bank must
440524 /// concentrate its output energy at that subband's centre frequency.
441525 #[test]