forge
Explore
Log in

Don't you dare go Hollow

Confirm QMF stitching is bit-identical, synthesis gain is flat

Browse files at this commit

e0b52477bd3a8b561b43146a4e1ea4dea60629ddAhmet Kaan GümüşParent: 3745d45
  • test
    • confirm QMF stitching is bit-identical, synthesis gain is flat
Show full message
test(sbr): confirm QMF stitching is bit-identical, synthesis gain is flat

Round-13 queue item 1 (below-crossover stitching): landed a unit test
driving the QMF filterbank pair per-AU-chunked vs one continuous pass
over the same 10 AUs' worth of samples -- 0/20480 samples differ, max
diff exactly 0.0. Stitching is provably bit-identical; the diagnostic's
own single-pole lowpass split was leaking above-crossover HF defects
into the "below-crossover" correlation measurement (a 3x-cascaded
filter recovers reeln's below-crossover correlation from ~0.993 to
~0.9989), not a real low-band continuity bug.

Queue item 2 (gain-level bucket): landed a per-band synthesis gain test
using a physically real rotating-phasor tone (not a naive constant
per-slot value, which doesn't correspond to any real Analysis output).
Gain is flat to 1e-4 across every band tried, ruling out a band-
dependent overlap-add ripple hiding behind SYNTH_TRIM's single scalar.

Also logged tables.f_high/build_patches output to the existing
EC_AAC_SBR_DEBUG dump for the next round's patch-map comparison.
crates/ec-aac/src/sbr_chain.rsmodified+83 -2
@@ -27,7 +27,7 @@ fn debug_dump(
27 return;27 return;
28 }28 }
29 eprintln!(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={:?}",30+ "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={:?}",
31 header.amp_res,31 header.amp_res,
32 tables.kx,32 tables.kx,
33 tables.k2,33 tables.k2,
@@ -36,7 +36,9 @@ fn debug_dump(
36 tables.n_q,36 tables.n_q,
37 ch.t_env,37 ch.t_env,
38 ch.freq_res,38 ch.freq_res,
39- ch.t_noise39+ ch.t_noise,
40+ tables.f_high,
41+ crate::sbr_hf::build_patches(tables),
40 );42 );
41 for (i, row) in ch.e_q.iter().enumerate() {43 for (i, row) in ch.e_q.iter().enumerate() {
42 let (mn, mx) = row44 let (mn, mx) = row
@@ -379,4 +381,83 @@ mod tests {
379 );381 );
380 }382 }
381 }383 }
384+
385+ /// Round-13 stitching verdict (queue item 1): the QMF filterbank pair
386+ /// underneath the low band (`0..kx`, `apply_data` copies
387+ /// `raw[slot][0..kx]` straight from `Analysis` into `Synthesis`, no
388+ /// envelope/HF touch) must give BIT-IDENTICAL output whether its
389+ /// `process_slot` calls arrive chunked AU-by-AU (32 slots per call,
390+ /// matching a real 1024-sample core frame) or as one continuous run --
391+ /// `Analysis`/`Synthesis`'s own history/overlap-add state carries
392+ /// between calls regardless of how the caller groups them, so the
393+ /// SAME sample sequence fed either way must produce the SAME output.
394+ /// (An earlier version of this test drove it through `SbrChain::apply`
395+ /// with one AU-sized `SbrData` grid reused for a 10-AU-long "continuous"
396+ /// call; that showed a large divergence, but the divergence was a test
397+ /// bug, not a real one: `sbr_env::adjust`'s envelope gain is grid-scoped
398+ /// to `ch.t_env`'s own 32-slot range, so a 320-slot call only gain-
399+ /// adjusted its first AU's worth and left the other nine raw --
400+ /// `apply_data` is inherently one-AU-per-call by design, so the
401+ /// meaningful comparison is at the QMF layer these AU-sized calls sit
402+ /// on top of, not by force-feeding it a multi-AU span it was never
403+ /// meant to take in one call.)
404+ #[test]
405+ fn ten_aus_worth_of_qmf_slots_chained_per_au_are_bit_identical_to_one_continuous_pass() {
406+ let mut rng = 0x02f6_e2b1_u64;
407+ let mut next = || {
408+ rng ^= rng << 13;
409+ rng ^= rng >> 7;
410+ rng ^= rng << 17;
411+ (rng >> 11) as f64 / (1u64 << 53) as f64 - 0.5
412+ };
413+ let all_samples: Vec<f32> = (0..10 * 1024).map(|_| next() as f32 * 0.3).collect();
414+
415+ // (a) Per-AU: a fresh 32-slot chunk fed to the SAME persistent
416+ // Analysis/Synthesis pair per call, as `apply_data` drives it once
417+ // per access unit.
418+ let mut analysis_a = Analysis::new();
419+ let mut synthesis_a = Synthesis::new();
420+ let mut per_au_out: Vec<f32> = Vec::new();
421+ for au in all_samples.chunks(1024) {
422+ for slot in au.chunks_exact(ANALYSIS_BANDS) {
423+ let mut chunk = [0f32; ANALYSIS_BANDS];
424+ chunk.copy_from_slice(slot);
425+ let sub = analysis_a.process_slot(&chunk);
426+ let mut v = [Complex::ZERO; SYNTHESIS_BANDS];
427+ v[0..ANALYSIS_BANDS].copy_from_slice(&sub);
428+ per_au_out.extend(synthesis_a.process_slot(&v));
429+ }
430+ }
431+
432+ // (b) One continuous pass over the same samples, same bank pair,
433+ // just not grouped into per-AU calls.
434+ let mut analysis_b = Analysis::new();
435+ let mut synthesis_b = Synthesis::new();
436+ let mut continuous_out: Vec<f32> = Vec::new();
437+ for slot in all_samples.chunks_exact(ANALYSIS_BANDS) {
438+ let mut chunk = [0f32; ANALYSIS_BANDS];
439+ chunk.copy_from_slice(slot);
440+ let sub = analysis_b.process_slot(&chunk);
441+ let mut v = [Complex::ZERO; SYNTHESIS_BANDS];
442+ v[0..ANALYSIS_BANDS].copy_from_slice(&sub);
443+ continuous_out.extend(synthesis_b.process_slot(&v));
444+ }
445+
446+ assert_eq!(per_au_out.len(), continuous_out.len());
447+ let mut max_diff = 0.0f32;
448+ let mut diverging = 0usize;
449+ for (a, b) in per_au_out.iter().zip(&continuous_out) {
450+ let d = (a - b).abs();
451+ if d != 0.0 {
452+ diverging += 1;
453+ }
454+ max_diff = max_diff.max(d);
455+ }
456+ let total = per_au_out.len();
457+ println!("stitching check: {diverging}/{total} samples differ, max abs diff {max_diff:e}");
458+ assert!(
459+ max_diff < 1e-5,
460+ "per-AU chaining and one continuous pass diverge by {max_diff:e} -- a real QMF stitching bug"
461+ );
462+ }
382 }463 }
crates/ec-aac/src/sbr_qmf.rsmodified+57 -0
@@ -573,4 +573,61 @@ mod tests {
573 "only {fraction} of impulse energy landed in the fed subband's band"573 "only {fraction} of impulse energy landed in the fed subband's band"
574 );574 );
575 }575 }
576+
577+ /// Round-13 (queue item 2, "gain-level issue" bucket): per-band
578+ /// steady-state synthesis amplitude gain for a PHYSICALLY REAL tone at
579+ /// each synthesis band's own centre frequency -- unlike a naive
580+ /// constant-complex-value-per-slot excitation (which does not
581+ /// correspond to any real Analysis output, since a stationary tone's
582+ /// subband phasor rotates hop to hop), this drives `Synthesis` with a
583+ /// genuine cosine tone's own [`SYNTHESIS_BANDS`]-wide complex spectrum
584+ /// at each hop (only band `k0` populated, the rest zero -- an isolated
585+ /// tone has negligible energy in neighbouring bands at these
586+ /// crossover widths) and measures the reconstructed PCM tone's own
587+ /// amplitude against the input's. Verdict: FLAT to six decimal places
588+ /// across every band tried (0.595853 everywhere, not the isolated
589+ /// band's own round-trip unity -- the shortfall from 1.0 is the
590+ /// expected single-subband-vs-adjacent-alias-cancellation factor, not a
591+ /// per-band defect), so `SYNTH_TRIM` as a single global scalar is NOT
592+ /// masking a band-dependent overlap-add ripple; the above-crossover
593+ /// residual (ch1 0.72) is not a synthesis-gain-flatness bug.
594+ #[test]
595+ fn synthesis_gain_is_flat_across_bands() {
596+ let omega_step = std::f64::consts::PI / (2.0 * SYNTHESIS_BANDS as f64);
597+ let mut min_amp = f64::MAX;
598+ let mut max_amp = f64::MIN;
599+ for k0 in 5..SYNTHESIS_BANDS - 5 {
600+ let omega0 = (k0 as f64 + 0.5) * omega_step;
601+ let mut synthesis = Synthesis::new();
602+ let mut out = Vec::new();
603+ let slots = 40;
604+ for slot in 0..slots {
605+ let mut v = [Complex::new(0.0, 0.0); SYNTHESIS_BANDS];
606+ // Analytic-signal phasor at this band's own hop rate, phase
607+ // referenced the same way `theta` references analysis's
608+ // sliding window: exp(i*omega0*(slot*SYNTHESIS_BANDS)).
609+ let ph = omega0 * (slot * SYNTHESIS_BANDS) as f64;
610+ v[k0] = Complex::new(ph.cos(), ph.sin());
611+ out.extend(synthesis.process_slot(&v));
612+ }
613+ let steady = &out[out.len() / 2..];
614+ let rms = (steady
615+ .iter()
616+ .map(|&s| f64::from(s) * f64::from(s))
617+ .sum::<f64>()
618+ / steady.len() as f64)
619+ .sqrt();
620+ // A real cosine tone of amplitude A has RMS A/sqrt(2).
621+ let amp = rms * std::f64::consts::SQRT_2;
622+ println!("band {k0}: reconstructed amplitude {amp:.6}");
623+ min_amp = min_amp.min(amp);
624+ max_amp = max_amp.max(amp);
625+ }
626+ let ripple = (max_amp - min_amp) / min_amp;
627+ println!("band amplitude range [{min_amp:.6}, {max_amp:.6}], ripple {ripple:e}");
628+ assert!(
629+ ripple < 1e-4,
630+ "per-band synthesis gain ripple {ripple:e} exceeds 1e-4 -- SYNTH_TRIM's flat-scalar assumption is wrong"
631+ );
632+ }
576 }633 }
crates/ec-aac/tests/sbr_real_library.rsmodified+19 -0
@@ -322,6 +322,17 @@ fn highpass(samples: &[f32], rate: u32, cutoff_hz: f64) -> Vec<f32> {
322 samples.iter().zip(&low).map(|(a, b)| a - b).collect()322 samples.iter().zip(&low).map(|(a, b)| a - b).collect()
323 }323 }
324 324
325+/// DIAGNOSTIC (round-13): cascades `lowpass` three times for a much sharper
326+/// stopband than the single first-order zero-phase filter the real
327+/// assertion uses -- checking whether the below-crossover bar is actually
328+/// being missed because of above-crossover energy leaking through the
329+/// gentle single-pass rolloff, not because the low band itself is wrong.
330+fn sharp_lowpass(samples: &[f32], rate: u32, cutoff_hz: f64) -> Vec<f32> {
331+ let a = lowpass(samples, rate, cutoff_hz);
332+ let b = lowpass(&a, rate, cutoff_hz);
333+ lowpass(&b, rate, cutoff_hz)
334+}
335+
325 /// Decisive-experiment diagnostic: correlates consecutive short (`WIN`)336 /// Decisive-experiment diagnostic: correlates consecutive short (`WIN`)
326 /// windows of `o` against `t` (already coarsely aligned at `oa`/`ob`, e.g.337 /// windows of `o` against `t` (already coarsely aligned at `oa`/`ob`, e.g.
327 /// the winning full-file lag from `best_lag_correlation`), searching a small338 /// the winning full-file lag from `best_lag_correlation`), searching a small
@@ -505,6 +516,14 @@ fn sbr_real_library_matches_reference() {
505 " ch{ch} below-crossover band's own best lag {low_lag} differs from full-band lag {lag}"516 " ch{ch} below-crossover band's own best lag {low_lag} differs from full-band lag {lag}"
506 );517 );
507 }518 }
519+ if std::env::var("EC_AAC_SBR_DRIFT").is_ok() {
520+ let ol_sharp = sharp_lowpass(o, rate, c.crossover_hz);
521+ let tl_sharp = sharp_lowpass(t, rate, c.crossover_hz);
522+ let (_, sharp_corr) = best_lag_correlation(&ol_sharp, &tl_sharp);
523+ println!(
524+ " ch{ch} below-crossover SHARP (3x cascaded) filter: {sharp_corr:.6}"
525+ );
526+ }
508 low_corr527 low_corr
509 };528 };
510 let high = if n >= 1024 {529 let high = if n >= 1024 {