forge
Explore
Log in

Don't you dare go Hollow

Fix the per-band STFT correlation and cross-spectrum diagnostics

Browse files at this commit

80e5af371ee21eccec05466fad5020e5d0d28cdcAhmet Kaan GümüşParent: b768ffa
  • test
    • fix the per-band STFT correlation and cross-spectrum diagnostics
Show full message
test(sbr): fix the per-band STFT correlation and cross-spectrum diagnostics

per_band_correlation was correlating each FFT bin's magnitude series then
averaging |corr| across a band's 8 bins -- a tiny inter-bin energy
redistribution between our filterbank and the reference decorrelates each
bin individually even when the band's total energy tracks closely. Sum the
band's bin magnitudes coherently first, then correlate once.

Added per_band_phase (round-16 Task 2): a cross-spectrum phase/magnitude-
ratio probe over the same aligned window. Its first version complex-summed
a band's bins before forming the cross product, which mixes in O_b*conj(T_b')
cross terms for b != b' -- pure noise between unrelated bin frequencies. Fixed
to accumulate the cross-spectrum per bin across hops, then sum bins.

Neither fix reconciles the STFT-domain reading with per_band_lag_search's
direct PCM bandpass-and-correlate result above the crossover: STFT magnitude
and cross-spectrum phase both go noisy/unstable there (phase swings over
hundreds of degrees band to band, magnitude ratio spans 0.003-8.9), while
per_band_lag_search finds a clean lag-0/-1 peak with correlation declining
smoothly from ~0.999 to ~0.80. Below the crossover both diagnostics agree
cleanly (phase <0.5deg, magnitude ratio ~1.00-1.01), so the below-crossover
0.9989-vs-0.9999 residual is not a phase story. No calibration applied --
the charter's decision tree calls for reporting both curves and stopping
when neither a smooth phase curve nor a stable magnitude curve emerges.
crates/ec-aac/tests/sbr_real_library.rsmodified+113 -12
@@ -440,21 +440,28 @@ fn per_band_correlation(o: &[f32], t: &[f32], rate: u32) -> Vec<(f64, f64, f64)>
440440 if lo >= hi {
441441 continue;
442442 }
443- let mut sum = 0.0f64;
444- let mut cnt = 0usize;
443+ // round-16: correlating bin-by-bin then averaging the |corr| values
444+ // was the bug -- a QMF band's bins share one slowly-varying envelope,
445+ // but a tiny (sub-Hz) frequency offset between our filterbank and the
446+ // reference's shifts energy between adjacent bins hop to hop, so each
447+ // bin's OWN magnitude series decorrelates even though the band's
448+ // total energy (what a QMF band's single subband signal actually
449+ // carries) tracks the reference closely. Summing the bins' magnitudes
450+ // into one band-energy series per side FIRST, then correlating that
451+ // single pair, is robust to that intra-band leakage the way the
452+ // per-bin version wasn't.
453+ let hops_here = o_mag[lo].len().min(t_mag[lo].len());
454+ let mut o_band = vec![0.0f32; hops_here];
455+ let mut t_band = vec![0.0f32; hops_here];
445456 for b in lo..hi {
446- // `correlation`'s 1024-sample floor is sized for raw audio, not
447- // this per-bin magnitude series (one value per STFT hop, ~200
448- // long over the test window) -- use it anyway but on padded
449- // input so the floor doesn't zero every band out.
450- let c = magnitude_series_correlation(&o_mag[b], &t_mag[b]);
451- if c.is_finite() {
452- sum += c.abs();
453- cnt += 1;
457+ for h in 0..hops_here {
458+ o_band[h] += o_mag[b][h];
459+ t_band[h] += t_mag[b][h];
454460 }
455461 }
456- if cnt > 0 {
457- out.push((band as f64 * band_hz, sum / cnt as f64, band as f64));
462+ let c = magnitude_series_correlation(&o_band, &t_band);
463+ if c.is_finite() {
464+ out.push((band as f64 * band_hz, c.abs(), band as f64));
458465 }
459466 }
460467 out
@@ -541,6 +548,90 @@ fn per_band_lag_search(o: &[f32], t: &[f32], rate: u32) -> Vec<(f64, i64, f64)>
541548 out
542549 }
543550
551+/// DIAGNOSTIC (round-16, Task 2): per-band phase offset and magnitude
552+/// transfer between `o` and `t`, over the SAME aligned window
553+/// `per_band_correlation` uses. Reuses the STFT-and-coherent-band-sum
554+/// machinery `per_band_correlation` was just fixed to use (sum the complex
555+/// spectrum, not just its magnitude, across a band's bins first, so a
556+/// per-bin sub-band redistribution doesn't wash out a genuine per-band
557+/// phase relationship) but keeps the complex value: the cross-spectrum
558+/// `sum_h O_band(h) * conj(T_band(h))` accumulated over every hop gives one
559+/// phasor per band whose angle is the (hop-weighted) phase offset between
560+/// `o` and `t` in that band and whose radius, once normalized by each side's
561+/// own energy, gives the magnitude transfer ratio.
562+fn per_band_phase(o: &[f32], t: &[f32], rate: u32) -> Vec<(f64, f64, f64)> {
563+ const FFT_LEN: usize = 2048;
564+ const HOP: usize = 1024;
565+ let win = ec_dsp::Window::<f32>::sine(FFT_LEN);
566+ let mut rfft = ec_dsp::RealFft::<f32>::new(FFT_LEN);
567+ let bins = rfft.spectrum_len();
568+ let n = o.len().min(t.len());
569+ let hops = if n >= FFT_LEN {
570+ (n - FFT_LEN) / HOP + 1
571+ } else {
572+ 0
573+ };
574+ let mut o_spec = vec![Vec::with_capacity(hops); bins];
575+ let mut t_spec = vec![Vec::with_capacity(hops); bins];
576+ let mut spectrum = vec![ec_dsp::Complex::new(0.0f32, 0.0); bins];
577+ for (src, dst) in [(o, &mut o_spec), (t, &mut t_spec)] {
578+ for h in 0..hops {
579+ let mut block = src[h * HOP..h * HOP + FFT_LEN].to_vec();
580+ win.apply(&mut block);
581+ rfft.forward(&block, &mut spectrum);
582+ for (b, c) in spectrum.iter().enumerate() {
583+ dst[b].push(*c);
584+ }
585+ }
586+ }
587+ let band_hz = f64::from(rate) / 256.0;
588+ let bin_hz = f64::from(rate) / FFT_LEN as f64;
589+ let num_bands = (f64::from(rate) / 2.0 / band_hz).ceil() as usize;
590+ let mut out = Vec::with_capacity(num_bands);
591+ for band in 0..num_bands {
592+ let lo = (band as f64 * band_hz / bin_hz).floor() as usize;
593+ let hi = (((band + 1) as f64 * band_hz / bin_hz).ceil() as usize).min(bins);
594+ if lo >= hi || hops == 0 {
595+ continue;
596+ }
597+ // Cross-spectrum accumulated PER BIN over hops, THEN summed across
598+ // the band's bins -- not the reverse. Complex-summing the band's
599+ // bins together at each hop first (as an earlier version of this
600+ // function did) mixes in `O_b * conj(T_b')` cross terms for every
601+ // b != b' pair once the per-hop products are formed; two adjacent
602+ // FFT bins carry unrelated instantaneous phase (they are different
603+ // frequencies), so those cross terms are pure noise that swamped the
604+ // real per-bin coherence and produced an incoherent, near-random
605+ // phase reading across exactly the HF bands `per_band_lag_search`'s
606+ // direct PCM correlation shows are highly correlated at lag 0/-1.
607+ let mut cross_re = 0.0f64;
608+ let mut cross_im = 0.0f64;
609+ let mut o_energy = 0.0f64;
610+ let mut t_energy = 0.0f64;
611+ for b in lo..hi {
612+ for h in 0..hops {
613+ let ob = o_spec[b][h];
614+ let tb = t_spec[b][h];
615+ let cross = ob * tb.conj();
616+ cross_re += f64::from(cross.re);
617+ cross_im += f64::from(cross.im);
618+ o_energy +=
619+ f64::from(ob.re) * f64::from(ob.re) + f64::from(ob.im) * f64::from(ob.im);
620+ t_energy +=
621+ f64::from(tb.re) * f64::from(tb.re) + f64::from(tb.im) * f64::from(tb.im);
622+ }
623+ }
624+ let phase = cross_im.atan2(cross_re);
625+ let mag_ratio = if t_energy > 0.0 {
626+ (o_energy / t_energy).sqrt()
627+ } else {
628+ 0.0
629+ };
630+ out.push((band as f64 * band_hz, phase, mag_ratio));
631+ }
632+ out
633+}
634+
544635 /// A file discovered under the user's own media directories: its path, which
545636 /// AAC stream in it (0-based among AAC streams only) carries HE-AAC, and the
546637 /// core/SBR crossover an ffprobe/ASC inspection already pinned for it -- used
@@ -711,6 +802,16 @@ fn sbr_real_library_matches_reference() {
711802 for (hz, lag, corr) in &lags {
712803 println!(" {hz:>6.0}Hz: lag {lag:>5} corr {corr:.4}");
713804 }
805+ let phases = per_band_phase(&o[oa..oa + n], &t[ob..ob + n], rate);
806+ println!(
807+ " ch{ch} per-band cross-spectrum (band_hz, phase_deg, mag_ratio ours/theirs):"
808+ );
809+ for (hz, phase, ratio) in &phases {
810+ println!(
811+ " {hz:>6.0}Hz: phase {:>7.2}deg ratio {ratio:.4}",
812+ phase.to_degrees()
813+ );
814+ }
714815 }
715816 println!(
716817 " ch{ch}: lag {lag}, full {full:.6}, below {:.0}Hz {low:.6}, above {:.0}Hz {high:.6}",