Two real scale bugs behind the SBR catastrophic blowup
Browse files at this commit92f96f72b71e36d610211c7b7be32dac47f456d3Parent: 01987f4- fix
- two real scale bugs behind the SBR catastrophic blowup
3 changed files +156 -11
- crates/ec-aac/src/decode.rs +1 -1
- crates/ec-aac/src/sbr_chain.rs +62 -1
- crates/ec-aac/src/sbr_qmf.rs +93 -9
crates/ec-aac/src/decode.rsmodified+1 -1
| @@ -29,7 +29,7 @@ const SF_OFFSET: i32 = 100; | |||
| 29 | /// 2^16; the public API speaks the usual +/-1 float range. Checked against a | 29 | /// 2^16; the public API speaks the usual +/-1 float range. Checked against a |
| 30 | /// reference decode in `adts_fixtures_match_ffmpeg_per_channel`, which compares | 30 | /// reference decode in `adts_fixtures_match_ffmpeg_per_channel`, which compares |
| 31 | /// amplitudes and not just shape. | 31 | /// 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; |
| 33 | /// The longest TNS filter AAC-LC allows (long blocks; short blocks stop at 7). | 33 | /// The longest TNS filter AAC-LC allows (long blocks; short blocks stop at 7). |
| 34 | const TNS_MAX_ORDER_LONG: usize = 12; | 34 | const TNS_MAX_ORDER_LONG: usize = 12; |
| 35 | const TNS_MAX_ORDER_SHORT: usize = 7; | 35 | 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}; | |||
| 11 | use ec_core::BitReader; | 11 | use ec_core::BitReader; |
| 12 | use ec_dsp::Complex; | 12 | use ec_dsp::Complex; |
| 13 | use std::collections::HashMap; | 13 | 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 | +} | ||
| 14 | 54 | ||
| 15 | /// Envelope-grid "time slots" (§4.6.18.4, `numTimeSlots = 16` for a | 55 | /// Envelope-grid "time slots" (§4.6.18.4, `numTimeSlots = 16` for a |
| 16 | /// 1024-sample core frame) are half as fine as the QMF slots SBR actually | 56 | /// 1024-sample core frame) are half as fine as the QMF slots SBR actually |
| @@ -107,6 +147,20 @@ impl SbrChain { | |||
| 107 | for slot in 0..num_slots { | 147 | for slot in 0..num_slots { |
| 108 | let mut chunk = [0f32; ANALYSIS_BANDS]; | 148 | let mut chunk = [0f32; ANALYSIS_BANDS]; |
| 109 | chunk.copy_from_slice(&plane[slot * ANALYSIS_BANDS..(slot + 1) * ANALYSIS_BANDS]); | 149 | 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 | + } | ||
| 110 | let sub = state.analysis.process_slot(&chunk); | 164 | let sub = state.analysis.process_slot(&chunk); |
| 111 | for b in 0..ANALYSIS_BANDS { | 165 | for b in 0..ANALYSIS_BANDS { |
| 112 | low_cur[b][slot] = sub[b]; | 166 | low_cur[b][slot] = sub[b]; |
| @@ -115,6 +169,10 @@ impl SbrChain { | |||
| 115 | } | 169 | } |
| 116 | 170 | ||
| 117 | let sbr_ch = &data.channels[ch]; | 171 | 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 | + } | ||
| 118 | let mut hf = sbr_hf::generate( | 176 | let mut hf = sbr_hf::generate( |
| 119 | &low_cur, | 177 | &low_cur, |
| 120 | &tables, | 178 | &tables, |
| @@ -152,7 +210,10 @@ impl SbrChain { | |||
| 152 | v[b] = hf[b - kx][slot]; | 210 | v[b] = hf[b - kx][slot]; |
| 153 | } | 211 | } |
| 154 | } | 212 | } |
| 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 | + } | ||
| 156 | out.extend_from_slice(&pcm); | 217 | out.extend_from_slice(&pcm); |
| 157 | } | 218 | } |
| 158 | *plane = out; | 219 | *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 { | |||
| 127 | omega_step * (k as f64 + 0.5) * (n as f64 + bands as f64 / 2.0) | 127 | omega_step * (k as f64 + 0.5) * (n as f64 + bands as f64 / 2.0) |
| 128 | } | 128 | } |
| 129 | 129 | ||
| 130 | -/// Precomputes `h[n] * cos(theta(k,n))` and `h[n] * sin(theta(k,n))` for every | 130 | +/// Precomputes `gain * h[n] * cos(theta(k,n))` and `gain * h[n] * |
| 131 | -/// `(k, n)` pair, flattened `k`-major: the modulation matrix both banks | 131 | +/// sin(theta(k,n))` for every `(k, n)` pair, flattened `k`-major: the |
| 132 | -/// multiply their sample window against. | 132 | +/// modulation matrix both banks multiply their sample window against. |
| 133 | -fn modulation_tables(h: &[f64], bands: usize, omega_step: f64) -> (Vec<f64>, Vec<f64>) { | 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>) { | ||
| 134 | let len = h.len(); | 144 | let len = h.len(); |
| 135 | let mut cos_tab = vec![0.0f64; bands * len]; | 145 | let mut cos_tab = vec![0.0f64; bands * len]; |
| 136 | let mut sin_tab = vec![0.0f64; bands * len]; | 146 | let mut sin_tab = vec![0.0f64; bands * len]; |
| 137 | for k in 0..bands { | 147 | for k in 0..bands { |
| 138 | for n in 0..len { | 148 | for n in 0..len { |
| 139 | let th = theta(k, n, bands, omega_step); | 149 | let th = theta(k, n, bands, omega_step); |
| 140 | - cos_tab[k * len + n] = h[n] * th.cos(); | 150 | + cos_tab[k * len + n] = gain * h[n] * th.cos(); |
| 141 | - sin_tab[k * len + n] = h[n] * th.sin(); | 151 | + sin_tab[k * len + n] = gain * h[n] * th.sin(); |
| 142 | } | 152 | } |
| 143 | } | 153 | } |
| 144 | (cos_tab, sin_tab) | 154 | (cos_tab, sin_tab) |
| 145 | } | 155 | } |
| 146 | 156 | ||
| 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 | + | ||
| 147 | /// The 32-band complex analysis QMF bank: core PCM in, complex subband slots | 171 | /// The 32-band complex analysis QMF bank: core PCM in, complex subband slots |
| 148 | /// out, one slot per 32 input samples. | 172 | /// out, one slot per 32 input samples. |
| 149 | pub struct Analysis { | 173 | pub struct Analysis { |
| @@ -158,7 +182,8 @@ impl Analysis { | |||
| 158 | pub fn new() -> Analysis { | 182 | pub fn new() -> Analysis { |
| 159 | let omega_step = std::f64::consts::PI / (2.0 * ANALYSIS_BANDS as f64); | 183 | let omega_step = std::f64::consts::PI / (2.0 * ANALYSIS_BANDS as f64); |
| 160 | let h = prototype(PROTO_LEN, omega_step, KAISER_BETA); | 184 | 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); | ||
| 162 | Analysis { | 187 | Analysis { |
| 163 | hist: vec![0.0; PROTO_LEN], | 188 | hist: vec![0.0; PROTO_LEN], |
| 164 | cos_tab, | 189 | cos_tab, |
| @@ -213,7 +238,21 @@ impl Synthesis { | |||
| 213 | pub fn new() -> Synthesis { | 238 | pub fn new() -> Synthesis { |
| 214 | let omega_step = std::f64::consts::PI / (2.0 * SYNTHESIS_BANDS as f64); | 239 | let omega_step = std::f64::consts::PI / (2.0 * SYNTHESIS_BANDS as f64); |
| 215 | let h = prototype(PROTO_LEN, omega_step, KAISER_BETA); | 240 | 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); | ||
| 217 | Synthesis { | 256 | Synthesis { |
| 218 | out_buf: vec![0.0; PROTO_LEN], | 257 | out_buf: vec![0.0; PROTO_LEN], |
| 219 | cos_tab, | 258 | cos_tab, |
| @@ -384,7 +423,23 @@ mod tests { | |||
| 384 | } | 423 | } |
| 385 | } | 424 | } |
| 386 | 425 | ||
| 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(&_ratio), | ||
| 441 | + "round-trip amplitude ratio {amp_ratio} not within 2% of unity gain" | ||
| 442 | + ); | ||
| 388 | assert!( | 443 | assert!( |
| 389 | best_corr >= 0.9999, | 444 | best_corr >= 0.9999, |
| 390 | "passband correlation {best_corr} below 0.9999 at lag {best_lag}" | 445 | "passband correlation {best_corr} below 0.9999 at lag {best_lag}" |
| @@ -436,6 +491,35 @@ mod tests { | |||
| 436 | ); | 491 | ); |
| 437 | } | 492 | } |
| 438 | 493 | ||
| 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 | + | ||
| 439 | /// (c) A single-subband impulse into the 64-band synthesis bank must | 523 | /// (c) A single-subband impulse into the 64-band synthesis bank must |
| 440 | /// concentrate its output energy at that subband's centre frequency. | 524 | /// concentrate its output energy at that subband's centre frequency. |
| 441 | #[test] | 525 | #[test] |