diff --git a/crates/ec-aac/src/sbr_chain.rs b/crates/ec-aac/src/sbr_chain.rs index ae4800fc..76cecb61 100644 --- a/crates/ec-aac/src/sbr_chain.rs +++ b/crates/ec-aac/src/sbr_chain.rs @@ -27,7 +27,7 @@ fn debug_dump( return; } eprintln!( - "SBRDBG frame {n} ch{ch_idx}: amp_res={} kx={} k2={} n_low={} n_high={} n_q={} t_env={:?} freq_res={:?} t_noise={:?}", + "SBRDBG frame {n} ch{ch_idx}: amp_res={} kx={} k2={} n_low={} n_high={} n_q={} t_env={:?} freq_res={:?} t_noise={:?} f_high={:?} patches={:?}", header.amp_res, tables.kx, tables.k2, @@ -36,7 +36,9 @@ fn debug_dump( tables.n_q, ch.t_env, ch.freq_res, - ch.t_noise + ch.t_noise, + tables.f_high, + crate::sbr_hf::build_patches(tables), ); for (i, row) in ch.e_q.iter().enumerate() { let (mn, mx) = row @@ -379,4 +381,83 @@ mod tests { ); } } + + /// Round-13 stitching verdict (queue item 1): the QMF filterbank pair + /// underneath the low band (`0..kx`, `apply_data` copies + /// `raw[slot][0..kx]` straight from `Analysis` into `Synthesis`, no + /// envelope/HF touch) must give BIT-IDENTICAL output whether its + /// `process_slot` calls arrive chunked AU-by-AU (32 slots per call, + /// matching a real 1024-sample core frame) or as one continuous run -- + /// `Analysis`/`Synthesis`'s own history/overlap-add state carries + /// between calls regardless of how the caller groups them, so the + /// SAME sample sequence fed either way must produce the SAME output. + /// (An earlier version of this test drove it through `SbrChain::apply` + /// with one AU-sized `SbrData` grid reused for a 10-AU-long "continuous" + /// call; that showed a large divergence, but the divergence was a test + /// bug, not a real one: `sbr_env::adjust`'s envelope gain is grid-scoped + /// to `ch.t_env`'s own 32-slot range, so a 320-slot call only gain- + /// adjusted its first AU's worth and left the other nine raw -- + /// `apply_data` is inherently one-AU-per-call by design, so the + /// meaningful comparison is at the QMF layer these AU-sized calls sit + /// on top of, not by force-feeding it a multi-AU span it was never + /// meant to take in one call.) + #[test] + fn ten_aus_worth_of_qmf_slots_chained_per_au_are_bit_identical_to_one_continuous_pass() { + let mut rng = 0x02f6_e2b1_u64; + let mut next = || { + rng ^= rng << 13; + rng ^= rng >> 7; + rng ^= rng << 17; + (rng >> 11) as f64 / (1u64 << 53) as f64 - 0.5 + }; + let all_samples: Vec = (0..10 * 1024).map(|_| next() as f32 * 0.3).collect(); + + // (a) Per-AU: a fresh 32-slot chunk fed to the SAME persistent + // Analysis/Synthesis pair per call, as `apply_data` drives it once + // per access unit. + let mut analysis_a = Analysis::new(); + let mut synthesis_a = Synthesis::new(); + let mut per_au_out: Vec = Vec::new(); + for au in all_samples.chunks(1024) { + for slot in au.chunks_exact(ANALYSIS_BANDS) { + let mut chunk = [0f32; ANALYSIS_BANDS]; + chunk.copy_from_slice(slot); + let sub = analysis_a.process_slot(&chunk); + let mut v = [Complex::ZERO; SYNTHESIS_BANDS]; + v[0..ANALYSIS_BANDS].copy_from_slice(&sub); + per_au_out.extend(synthesis_a.process_slot(&v)); + } + } + + // (b) One continuous pass over the same samples, same bank pair, + // just not grouped into per-AU calls. + let mut analysis_b = Analysis::new(); + let mut synthesis_b = Synthesis::new(); + let mut continuous_out: Vec = Vec::new(); + for slot in all_samples.chunks_exact(ANALYSIS_BANDS) { + let mut chunk = [0f32; ANALYSIS_BANDS]; + chunk.copy_from_slice(slot); + let sub = analysis_b.process_slot(&chunk); + let mut v = [Complex::ZERO; SYNTHESIS_BANDS]; + v[0..ANALYSIS_BANDS].copy_from_slice(&sub); + continuous_out.extend(synthesis_b.process_slot(&v)); + } + + assert_eq!(per_au_out.len(), continuous_out.len()); + let mut max_diff = 0.0f32; + let mut diverging = 0usize; + for (a, b) in per_au_out.iter().zip(&continuous_out) { + let d = (a - b).abs(); + if d != 0.0 { + diverging += 1; + } + max_diff = max_diff.max(d); + } + let total = per_au_out.len(); + println!("stitching check: {diverging}/{total} samples differ, max abs diff {max_diff:e}"); + assert!( + max_diff < 1e-5, + "per-AU chaining and one continuous pass diverge by {max_diff:e} -- a real QMF stitching bug" + ); + } } diff --git a/crates/ec-aac/src/sbr_qmf.rs b/crates/ec-aac/src/sbr_qmf.rs index 55fe5364..d6e3c166 100644 --- a/crates/ec-aac/src/sbr_qmf.rs +++ b/crates/ec-aac/src/sbr_qmf.rs @@ -573,4 +573,61 @@ mod tests { "only {fraction} of impulse energy landed in the fed subband's band" ); } + + /// 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 + /// constant-complex-value-per-slot excitation (which does not + /// correspond to any real Analysis output, since a stationary tone's + /// subband phasor rotates hop to hop), this drives `Synthesis` with a + /// genuine cosine tone's own [`SYNTHESIS_BANDS`]-wide complex spectrum + /// at each hop (only band `k0` populated, the rest zero -- an isolated + /// tone has negligible energy in neighbouring bands at these + /// crossover widths) and measures the reconstructed PCM tone's own + /// amplitude against the input's. Verdict: FLAT to six decimal places + /// across every band tried (0.595853 everywhere, not the isolated + /// band's own round-trip unity -- the shortfall from 1.0 is the + /// expected single-subband-vs-adjacent-alias-cancellation factor, not a + /// per-band defect), so `SYNTH_TRIM` as a single global scalar is NOT + /// masking a band-dependent overlap-add ripple; the above-crossover + /// residual (ch1 0.72) is not a synthesis-gain-flatness bug. + #[test] + fn synthesis_gain_is_flat_across_bands() { + let omega_step = std::f64::consts::PI / (2.0 * SYNTHESIS_BANDS as f64); + let mut min_amp = f64::MAX; + let mut max_amp = f64::MIN; + for k0 in 5..SYNTHESIS_BANDS - 5 { + let omega0 = (k0 as f64 + 0.5) * omega_step; + let mut synthesis = Synthesis::new(); + let mut out = Vec::new(); + let slots = 40; + for slot in 0..slots { + let mut v = [Complex::new(0.0, 0.0); SYNTHESIS_BANDS]; + // Analytic-signal phasor at this band's own hop rate, phase + // referenced the same way `theta` references analysis's + // sliding window: exp(i*omega0*(slot*SYNTHESIS_BANDS)). + let ph = omega0 * (slot * SYNTHESIS_BANDS) as f64; + v[k0] = Complex::new(ph.cos(), ph.sin()); + out.extend(synthesis.process_slot(&v)); + } + let steady = &out[out.len() / 2..]; + let rms = (steady + .iter() + .map(|&s| f64::from(s) * f64::from(s)) + .sum::() + / steady.len() as f64) + .sqrt(); + // A real cosine tone of amplitude A has RMS A/sqrt(2). + let amp = rms * std::f64::consts::SQRT_2; + println!("band {k0}: reconstructed amplitude {amp:.6}"); + min_amp = min_amp.min(amp); + max_amp = max_amp.max(amp); + } + let ripple = (max_amp - min_amp) / min_amp; + println!("band amplitude range [{min_amp:.6}, {max_amp:.6}], ripple {ripple:e}"); + assert!( + ripple < 1e-4, + "per-band synthesis gain ripple {ripple:e} exceeds 1e-4 -- SYNTH_TRIM's flat-scalar assumption is wrong" + ); + } } diff --git a/crates/ec-aac/tests/sbr_real_library.rs b/crates/ec-aac/tests/sbr_real_library.rs index 7781fbad..e85562c9 100644 --- a/crates/ec-aac/tests/sbr_real_library.rs +++ b/crates/ec-aac/tests/sbr_real_library.rs @@ -322,6 +322,17 @@ fn highpass(samples: &[f32], rate: u32, cutoff_hz: f64) -> Vec { samples.iter().zip(&low).map(|(a, b)| a - b).collect() } +/// DIAGNOSTIC (round-13): cascades `lowpass` three times for a much sharper +/// stopband than the single first-order zero-phase filter the real +/// assertion uses -- checking whether the below-crossover bar is actually +/// being missed because of above-crossover energy leaking through the +/// gentle single-pass rolloff, not because the low band itself is wrong. +fn sharp_lowpass(samples: &[f32], rate: u32, cutoff_hz: f64) -> Vec { + let a = lowpass(samples, rate, cutoff_hz); + let b = lowpass(&a, rate, cutoff_hz); + lowpass(&b, rate, cutoff_hz) +} + /// Decisive-experiment diagnostic: correlates consecutive short (`WIN`) /// windows of `o` against `t` (already coarsely aligned at `oa`/`ob`, e.g. /// the winning full-file lag from `best_lag_correlation`), searching a small @@ -505,6 +516,14 @@ fn sbr_real_library_matches_reference() { " ch{ch} below-crossover band's own best lag {low_lag} differs from full-band lag {lag}" ); } + if std::env::var("EC_AAC_SBR_DRIFT").is_ok() { + let ol_sharp = sharp_lowpass(o, rate, c.crossover_hz); + let tl_sharp = sharp_lowpass(t, rate, c.crossover_hz); + let (_, sharp_corr) = best_lag_correlation(&ol_sharp, &tl_sharp); + println!( + " ch{ch} below-crossover SHARP (3x cascaded) filter: {sharp_corr:.6}" + ); + } low_corr }; let high = if n >= 1024 {