From 1b74ecaff39e2375c181dbd502b221c2d7912eea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Thu, 20 Aug 2026 06:55:56 +0300 Subject: [PATCH] revert(aac-sbr): the patch copy stays unrotated -- the reference matches the raw convention The round-35 quarter-turn correction is frequency-pure by unit measurement, and wrong by the bar: a 4-way A/B on the real file (off / as-is / sign flipped / half rate) has the uncorrected copy winning decisively in the very bands the correction targeted (odd-gap direct coherence 0.19 vs 0.07). The reference reproduces the same cross-band convention, so matching it means leaving the copy raw. band_shift_correction stays as documentation of the characterized convention, pinned by its own tests; the production-path test now exercises generate() itself and pins the raw-copy placement. --- crates/ec-aac/src/sbr_hf.rs | 87 +++++++++++++++-------------- crates/ec-aac/src/sbr_qmf.rs | 105 +++++++++++++++++++++++++++++++++++ 2 files changed, 150 insertions(+), 42 deletions(-) diff --git a/crates/ec-aac/src/sbr_hf.rs b/crates/ec-aac/src/sbr_hf.rs index 1fea008b..11c881a9 100644 --- a/crates/ec-aac/src/sbr_hf.rs +++ b/crates/ec-aac/src/sbr_hf.rs @@ -36,27 +36,37 @@ use crate::sbr_bands::BandTables; use ec_dsp::Complex; -/// Compensates a QMF-bank convention gap `sbr_qmf`'s round-trip tuning never -/// exercised: replaying a source band's raw complex series into a -/// *different* synthesis band (exactly what patch copying does) lands the -/// content at the wrong absolute frequency by exactly one synthesis-band -/// width whenever `target_band - source_band` is odd, with the sign flipping -/// every other odd step -- i.e. a period-4 pattern in `target - source` -/// (even difference: no error; `+1 mod 4`: content lands one band flat; -/// `+3 mod 4`: one band sharp). `sbr_qmf::Synthesis`'s modulation kernel -/// centres band `k` at `(k+0.5) * pi/(2*SYNTHESIS_BANDS)` via a phase -/// intercept that is itself `(k+0.5) * pi/4` -- exactly the odd-stacked -/// cosine-modulated-bank convention the round-trip test tuned for -/// same-band replay, where this intercept cancels against the receiving -/// band's own reconstruction. For an odd `target - source` that intercept -/// difference is an odd multiple of `pi/4`, which this design's finite, -/// hop-discretised overlap-add can't represent without a full extra -/// `pi/2 * (target - source)`-quarter snap; `generate` cancels it here by -/// counter-rotating the patched series at the same quarter-turn rate before -/// it reaches `Synthesis`, rather than reworking the tuned bank convention -/// (which round-trip/gain-flatness tests already hold to a hard-won bound). -/// Returns the signed number of `pi/2` quarter-turns per QMF slot to rotate -/// the copied series by. +/// Characterizes (but, as of round-37, is deliberately NOT applied to) a QMF +/// bank convention gap `sbr_qmf`'s round-trip tuning never exercised: +/// replaying a source band's raw complex series into a *different* synthesis +/// band (exactly what patch copying does) lands the content at the "wrong" +/// absolute frequency by exactly one synthesis-band width whenever +/// `target_band - source_band` is odd, with the sign flipping every other +/// odd step -- i.e. a period-4 pattern in `target - source` (even +/// difference: no error; `+1 mod 4`: content lands one band flat; `+3 mod +/// 4`: one band sharp). `sbr_qmf::Synthesis`'s modulation kernel centres +/// band `k` at `(k+0.5) * pi/(2*SYNTHESIS_BANDS)` via a phase intercept that +/// is itself `(k+0.5) * pi/4` -- exactly the odd-stacked cosine-modulated- +/// bank convention the round-trip test tuned for same-band replay, where +/// this intercept cancels against the receiving band's own reconstruction. +/// +/// Round-35 had `generate` counter-rotate the patched series by this amount +/// before it reaches `Synthesis`, and proved (in isolation, via a +/// stationary-tone FFT probe through the actual production call site -- +/// `sbr_qmf::tests::patch_replay_through_generate_preserves_absolute_frequency_mapping`) +/// that doing so restores textbook-coherent absolute-frequency placement. +/// Round-36/37's real-file mechanical A/B (`EC_AAC_SBR_PARITY_SPLIT`) +/// showed applying that correction REGRESSES odd-gap coherence against the +/// reference decoder (ch0 0.1907->0.0714, ch1 0.2461->0.0741; a +/// sign-flipped variant and a half-rate variant both regress it too, to +/// 0.0757 and 0.1449 respectively on ch0) -- the reference apparently +/// reproduces this same "wrong" convention itself, so leaving the raw copy +/// unrotated is what actually matches it. This function is kept (and +/// pinned by its own unit tests) purely to document that convention as +/// intentional, not to be called from `generate`'s patch-copy site. +/// Returns the signed number of `pi/2` quarter-turns per QMF slot that +/// *would* need to be applied to restore frequency-pure placement. +#[allow(dead_code)] // documentation of the characterized convention; tests call it pub(crate) fn band_shift_correction(target_band: usize, source_band: usize) -> i64 { match (target_band as i64 - source_band as i64).rem_euclid(4) { 1 => 1, @@ -328,11 +338,6 @@ fn stabilize(coeffs: (Complex, Complex)) -> (Complex, Complex; 2]>, y: Vec<[Complex; 2]>, - /// Running QMF-slot counter mod 4, since stream start -- carries the - /// patch-band-shift phase correction's own period across frame calls - /// (see `band_shift_correction` in `generate`). Only the value mod 4 - /// matters (the correction's period), so this never grows unbounded. - slot_phase: usize, } impl HfHistory { @@ -340,7 +345,6 @@ impl HfHistory { HfHistory { x: vec![[Complex::ZERO; 2]; bands], y: vec![[Complex::ZERO; 2]; bands], - slot_phase: 0, } } } @@ -408,24 +412,24 @@ pub fn generate( } else { (Complex::ZERO, Complex::ZERO) }; - let k = band_shift_correction(target_band, source_band); let dst = &mut out[target_band - kx]; for (n, &x) in series.iter().enumerate() { let residual = x - a1 * x_prev1 - a2 * x_prev2; let y = residual + ca1 * y_prev1 + ca2 * y_prev2; - // The filter's own recursion continues on the unrotated - // `y` (its whitening state belongs to the source band, not - // the target placement); only what lands in `dst` -- the - // value `Synthesis` will actually see at `target_band` -- - // gets the placement correction. - dst[n] = if k == 0 { - y - } else { - let t_mod4 = (history.slot_phase + n) % 4; - let angle = k as f64 * std::f64::consts::FRAC_PI_2 * t_mod4 as f64; - let rot = Complex::new(angle.cos(), angle.sin()); - Complex::new(y.re * rot.re - y.im * rot.im, y.re * rot.im + y.im * rot.re) - }; + // Round-37 (Task 2): `band_shift_correction` is proven exact + // in isolation (a stationary tone replayed through this + // patch-copy site lands within a couple of FFT bins of its + // corrected absolute frequency -- see + // `sbr_qmf::tests::patch_replay_through_generate_preserves_absolute_frequency_mapping`) + // but a real-file mechanical A/B (round-36/37, + // `EC_AAC_SBR_PARITY_SPLIT`) shows applying it REGRESSES + // odd-gap coherence against the reference decoder (ch0 + // 0.1907->0.0714, ch1 0.2461->0.0741; sign-flipped and + // half-rate variants both regress it too, 0.0757/0.1449 resp. + // on ch0). The reference apparently exhibits this bank's own + // "wrong" cross-band placement convention, so matching it is + // the bar: `dst` stays the plain, uncorrected copy. + dst[n] = y; x_prev2 = x_prev1; x_prev1 = x; y_prev2 = y_prev1; @@ -433,7 +437,6 @@ pub fn generate( } } } - history.slot_phase = (history.slot_phase + num_slots) % 4; // Every source subband's history advances regardless of whether a // patch used it this frame: the low-band QMF stream is continuous. diff --git a/crates/ec-aac/src/sbr_qmf.rs b/crates/ec-aac/src/sbr_qmf.rs index 5e7fac80..d467ff35 100644 --- a/crates/ec-aac/src/sbr_qmf.rs +++ b/crates/ec-aac/src/sbr_qmf.rs @@ -775,6 +775,111 @@ mod tests { ); } + /// Round-37 Task 1 audit: `patch_replay_preserves_absolute_frequency_mapping` + /// above re-derives the correction formula inline rather than calling + /// `sbr_hf::generate`, so it only ever proved the *formula* right, not + /// that `generate`'s own application of it was. Driving the actual + /// production path (a two-band `BandTables` built so + /// `sbr_hf::build_patches` emits exactly one patch with an odd + /// `target - source` gap: source 3..8, target 8..13, gap 5, `5 mod 4 == + /// 1`) showed the production application WAS correct when it was + /// applied -- but round-36/37's real-file A/B then showed applying it + /// regresses reference-decoder coherence (see `sbr_hf::generate`'s own + /// doc comment at its patch-copy site). Round-37 reverted the + /// application, so this test now pins the opposite: `generate`'s raw, + /// UNROTATED patch replay lands the tone exactly where + /// `band_shift_correction` predicts the uncorrected bank convention + /// would put it (one synthesis-band-width off for this odd gap) -- i.e. + /// `generate` no longer calls `band_shift_correction` at all, and this + /// is the intentional (reference-matching) behaviour, not a residual bug. + #[test] + fn patch_replay_through_generate_matches_the_uncorrected_bank_convention() { + use crate::sbr_bands::BandTables; + use crate::sbr_hf::{ChirpState, HfHistory, generate}; + + let tables = BandTables { + n_master: 0, + n_high: 0, + n_low: 0, + n_q: 1, + f_high: vec![8, 13], + f_low: vec![8, 13], + f_noise: vec![8, 13], + kx: 8, + k2: 13, + }; + let source_band = 3usize; + let target_band = 8usize; // build_patches' only patch: source 3..8 -> target 8..13, gap 5 + + let omega_step_a = std::f64::consts::PI / (2.0 * ANALYSIS_BANDS as f64); + let omega_step_s = std::f64::consts::PI / (2.0 * SYNTHESIS_BANDS as f64); + let band_spacing_s = omega_step_s / std::f64::consts::TAU; + let slots = 128; + let core_samples = slots * ANALYSIS_BANDS; + let fft_len = 4096; + let centre = (source_band as f64 + 0.5) * omega_step_a; + + let analyse = |delta: f64| -> Vec> { + let omega0 = centre + delta * omega_step_a; + let x: Vec = (0..core_samples) + .map(|i| (omega0 * i as f64).cos()) + .collect(); + let mut analysis = Analysis::new(); + let mut sub = Vec::with_capacity(slots); + for chunk in x.chunks_exact(ANALYSIS_BANDS) { + let mut c = [0f32; ANALYSIS_BANDS]; + for (d, &s) in c.iter_mut().zip(chunk) { + *d = s as f32; + } + sub.push(analysis.process_slot(&c)[source_band]); + } + sub + }; + let synth_direct = |band: usize, sub: &[Complex]| -> f64 { + let mut synthesis = Synthesis::new(); + let mut out = Vec::with_capacity(slots * SYNTHESIS_BANDS); + for &s in sub { + let mut v = [Complex::new(0.0, 0.0); SYNTHESIS_BANDS]; + v[band] = s; + out.extend(synthesis.process_slot(&v).iter().map(|&s| f64::from(s))); + } + dominant_freq(&out[out.len() - fft_len..]) + }; + + println!("delta\tf_calib\tf_measured\texpected\terr(bins)"); + let mut worst_err_bins = 0.0f64; + for &delta in &[-0.3f64, 0.0, 0.3] { + let sub = analyse(delta); + let f_calib = synth_direct(source_band, &sub); + + let mut low_cur = vec![vec![Complex::ZERO; slots]; ANALYSIS_BANDS]; + low_cur[source_band] = sub; + let mut chirp = ChirpState::new(1); + let mut history = HfHistory::new(ANALYSIS_BANDS); + let hf = generate(&low_cur, &tables, &[0u8], &mut chirp, &mut history); + let row = &hf[target_band - tables.kx as usize]; + let f_measured = synth_direct(target_band, row); + + // Frequency-pure placement (what `band_shift_correction` would + // restore, were it applied) minus the one-band-width shift the + // uncorrected bank convention actually leaves in place. + let k = crate::sbr_hf::band_shift_correction(target_band, source_band); + let expected = f_calib + + (target_band as i64 - source_band as i64) as f64 * band_spacing_s + - k as f64 * band_spacing_s; + let bin_width = 1.0 / fft_len as f64; + let err_bins = (f_measured - expected).abs() / bin_width; + worst_err_bins = f64::max(worst_err_bins, err_bins); + println!("{delta:+.2}\t{f_calib:.6}\t{f_measured:.6}\t{expected:.6}\t{err_bins:.2}"); + } + assert!( + worst_err_bins <= 3.0, + "worst production-path prediction error {worst_err_bins} bins exceeds 3 -- \ + sbr_hf::generate's raw (uncorrected) patch replay no longer matches the \ + uncorrected bank convention's own predicted placement" + ); + } + /// Round-13 (queue item 2, "gain-level issue" bucket): per-band /// steady-state synthesis amplitude gain for a PHYSICALLY REAL tone at /// each synthesis band's own centre frequency -- unlike a naive