forge
Explore
Log in

Don't you dare go Hollow

Round-40 fine-bin spectral shift scan + complex-gain fingerprint

Browse files at this commit

3a953423c008d8f20680aab5ee1342d4187ada81Ahmet Kaan GümüşParent: cc56143
  • test
    • round-40 fine-bin spectral shift scan + complex-gain fingerprint
Show full message
test(sbr): round-40 fine-bin spectral shift scan + complex-gain fingerprint

Task 1 (EC_AAC_SBR_BIN_SHIFT): scans HF bin-coherence with ours-vs-reference
paired at a b-bin offset (b=-7..=7), split even/odd patch-gap regions --
reeln ch0 peaks cleanly at b=0 in BOTH regions (0.1526 even-gap,
0.1983 odd-gap; every other b lower, no secondary peak), refuting the
half-QMF-band frequency-offset hypothesis.

Task 2 (EC_AAC_SBR_COMPLEX_GAIN): per-STFT-frame complex ratio O/T on each
top-energy band's dominant bin -- magnitude and phase both swing randomly
frame to frame with no steady rotation rate, consistent with the Task 1
refutation (a real carrier offset would show a fixed dphase/frame).

Both diagnostics are additive, gated behind their own env vars (default
off), no existing assertion touched.
crates/ec-aac/tests/sbr_real_library.rsmodified+268 -0
@@ -949,6 +949,213 @@ fn hf_lag_sweep(
949 out949 out
950 }950 }
951 951
952+/// Round-40, Task 1: fine spectral-BIN shift scan on patched HF content.
953+/// `hf_lag_sweep` (round-38) only tested whole-QMF-slot SAMPLE-domain lags and
954+/// round-26's `bin_level_conviction` shift columns only tested whole
955+/// `BINS_PER_SBR_BAND` (8-bin) band shifts; neither ever tried a FEW-bin
956+/// spectral offset, which is what a half-QMF-band (~4-bin, ~86Hz at this
957+/// 2048-window scale) carrier convention mismatch on patched content would
958+/// look like -- it would leave envelope/magnitude tracking (and therefore
959+/// `hf_lag_sweep`'s k=0 peak) intact while destroying bin-level phase
960+/// coherence via linear phase drift across the band. The audio itself is
961+/// never shifted; only the bin INDEX used to pair `o` against `t` moves, by
962+/// `b` in -7..=+7 (deliberately short of the 8-bin whole-band-shift case
963+/// round-26 already ruled out). Reports mean direct coherence
964+/// (`bin_level_conviction`'s same `|sum_h O(h)*conj(T(h))| /
965+/// sqrt(sum|O|^2*sum|T|^2)` measure) separately over the even-gap [14,28) and
966+/// odd-gap [28,43) SBR-band regions -- the offset, if real, could differ by
967+/// patch parity given round-35/36's convention-fix history. A clear peak at
968+/// `b != 0` (region-dependent sign allowed) convicts a constant sub-band
969+/// frequency offset; a flat/0-peaked curve refutes it.
970+fn hf_bin_shift_sweep(
971+ o: &[f32],
972+ t: &[f32],
973+ _rate: u32,
974+ region_lo_band: usize,
975+ region_hi_band: usize,
976+) -> Vec<(i64, f64)> {
977+ const FFT_LEN: usize = 2048;
978+ const HOP: usize = 1024;
979+ const BINS_PER_SBR_BAND: usize = FFT_LEN / 256;
980+ const MAX_B: i64 = 7;
981+ let win = ec_dsp::Window::<f32>::sine(FFT_LEN);
982+ let mut rfft = ec_dsp::RealFft::<f32>::new(FFT_LEN);
983+ let bins = rfft.spectrum_len();
984+ let n = o.len().min(t.len());
985+ let hops = if n >= FFT_LEN {
986+ (n - FFT_LEN) / HOP + 1
987+ } else {
988+ 0
989+ };
990+ if hops == 0 {
991+ return Vec::new();
992+ }
993+ let mut o_spec = vec![Vec::with_capacity(hops); bins];
994+ let mut t_spec = vec![Vec::with_capacity(hops); bins];
995+ let mut spectrum = vec![ec_dsp::Complex::new(0.0f32, 0.0); bins];
996+ for (src, dst) in [(o, &mut o_spec), (t, &mut t_spec)] {
997+ for h in 0..hops {
998+ let mut block = src[h * HOP..h * HOP + FFT_LEN].to_vec();
999+ win.apply(&mut block);
1000+ rfft.forward(&block, &mut spectrum);
1001+ for (b, c) in spectrum.iter().enumerate() {
1002+ dst[b].push(*c);
1003+ }
1004+ }
1005+ }
1006+ let lo_bin = region_lo_band * BINS_PER_SBR_BAND;
1007+ let hi_bin = (region_hi_band * BINS_PER_SBR_BAND).min(bins);
1008+ let coh = |ob: usize, tb: usize| -> f64 {
1009+ if ob >= bins || tb >= bins {
1010+ return 0.0;
1011+ }
1012+ let mut cross_re = 0.0f64;
1013+ let mut cross_im = 0.0f64;
1014+ let mut o_e = 0.0f64;
1015+ let mut t_e = 0.0f64;
1016+ for h in 0..hops {
1017+ let oc = o_spec[ob][h];
1018+ let tc = t_spec[tb][h];
1019+ let cross = oc * tc.conj();
1020+ cross_re += f64::from(cross.re);
1021+ cross_im += f64::from(cross.im);
1022+ o_e += f64::from(oc.norm_sqr());
1023+ t_e += f64::from(tc.norm_sqr());
1024+ }
1025+ let den = (o_e * t_e).sqrt();
1026+ if den > 0.0 {
1027+ (cross_re * cross_re + cross_im * cross_im).sqrt() / den
1028+ } else {
1029+ 0.0
1030+ }
1031+ };
1032+ let mut out = Vec::with_capacity((2 * MAX_B + 1) as usize);
1033+ if lo_bin >= hi_bin {
1034+ return out;
1035+ }
1036+ for b in -MAX_B..=MAX_B {
1037+ let mut sum = 0.0f64;
1038+ let mut count = 0usize;
1039+ for i in lo_bin..hi_bin {
1040+ let oi = i as i64 + b;
1041+ if oi < 0 || oi as usize >= bins {
1042+ continue;
1043+ }
1044+ sum += coh(oi as usize, i);
1045+ count += 1;
1046+ }
1047+ out.push((b, if count > 0 { sum / count as f64 } else { 0.0 }));
1048+ }
1049+ out
1050+}
1051+
1052+/// Round-40, Task 2: per-STFT-frame complex-gain fingerprint. For the same
1053+/// top-energy HF bands `bin_level_conviction` picks (ranked by `o`'s own
1054+/// energy), takes each band's single dominant bin (highest total `|O(h)|^2`
1055+/// across hops) and reports the per-hop complex ratio `O(h)/T(h)` trajectory
1056+/// -- `(magnitude, phase_radians)` per STFT frame -- for that bin across
1057+/// every frame. Read afterward, not here: constant magnitude+phase is a pure
1058+/// gain (would predict HIGH coherence, contradicting the low bin-coherence
1059+/// measured elsewhere -- flags a measurement issue, not a real
1060+/// transformation); phase advancing at a roughly fixed per-frame rate is a
1061+/// genuine carrier frequency offset (the rate converts directly to Hz and
1062+/// cross-checks `hf_bin_shift_sweep`'s peak); phase jumping specifically at
1063+/// hop indices lining up with SBR envelope borders is a per-envelope
1064+/// gain/phase re-seed; anything else (magnitude and phase both wandering with
1065+/// no fixed rate) is genuinely uncorrelated content frame to frame.
1066+fn hf_complex_ratio_trajectory(
1067+ o: &[f32],
1068+ t: &[f32],
1069+ rate: u32,
1070+ min_band: usize,
1071+ top_n: usize,
1072+) -> Vec<(f64, Vec<(f64, f64)>)> {
1073+ const FFT_LEN: usize = 2048;
1074+ const HOP: usize = 1024;
1075+ const BINS_PER_SBR_BAND: usize = FFT_LEN / 256;
1076+ let win = ec_dsp::Window::<f32>::sine(FFT_LEN);
1077+ let mut rfft = ec_dsp::RealFft::<f32>::new(FFT_LEN);
1078+ let bins = rfft.spectrum_len();
1079+ let n = o.len().min(t.len());
1080+ let hops = if n >= FFT_LEN {
1081+ (n - FFT_LEN) / HOP + 1
1082+ } else {
1083+ 0
1084+ };
1085+ if hops == 0 {
1086+ return Vec::new();
1087+ }
1088+ let mut o_spec = vec![Vec::with_capacity(hops); bins];
1089+ let mut t_spec = vec![Vec::with_capacity(hops); bins];
1090+ let mut spectrum = vec![ec_dsp::Complex::new(0.0f32, 0.0); bins];
1091+ for (src, dst) in [(o, &mut o_spec), (t, &mut t_spec)] {
1092+ for h in 0..hops {
1093+ let mut block = src[h * HOP..h * HOP + FFT_LEN].to_vec();
1094+ win.apply(&mut block);
1095+ rfft.forward(&block, &mut spectrum);
1096+ for (b, c) in spectrum.iter().enumerate() {
1097+ dst[b].push(*c);
1098+ }
1099+ }
1100+ }
1101+ let band_hz = f64::from(rate) / 256.0;
1102+ let num_bands = bins / BINS_PER_SBR_BAND;
1103+ if min_band >= num_bands {
1104+ return Vec::new();
1105+ }
1106+ let mut ranked: Vec<(usize, f64)> = (min_band..num_bands)
1107+ .map(|band| {
1108+ let lo = band * BINS_PER_SBR_BAND;
1109+ let hi = (lo + BINS_PER_SBR_BAND).min(bins);
1110+ let e: f64 = (lo..hi)
1111+ .flat_map(|b| o_spec[b].iter())
1112+ .map(|c| f64::from(c.norm_sqr()))
1113+ .sum();
1114+ (band, e)
1115+ })
1116+ .collect();
1117+ ranked.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap());
1118+ let mut selected: Vec<usize> = ranked.into_iter().take(top_n).map(|(b, _)| b).collect();
1119+ selected.sort_unstable();
1120+
1121+ let mut out = Vec::with_capacity(selected.len());
1122+ for band in selected {
1123+ let lo = band * BINS_PER_SBR_BAND;
1124+ let hi = (lo + BINS_PER_SBR_BAND).min(bins);
1125+ if lo >= hi {
1126+ continue;
1127+ }
1128+ let dom = (lo..hi)
1129+ .max_by(|&a, &b| {
1130+ let ea: f64 = o_spec[a].iter().map(|c| f64::from(c.norm_sqr())).sum();
1131+ let eb: f64 = o_spec[b].iter().map(|c| f64::from(c.norm_sqr())).sum();
1132+ ea.partial_cmp(&eb).unwrap()
1133+ })
1134+ .unwrap();
1135+ // Complex division `O/T` done by hand (`ec_dsp::Complex` carries no
1136+ // `Div` impl -- it is a from-scratch minimal type, see fft.rs): `O *
1137+ // conj(T) / |T|^2`.
1138+ let traj: Vec<(f64, f64)> = (0..hops)
1139+ .map(|h| {
1140+ let oc = o_spec[dom][h];
1141+ let tc = t_spec[dom][h];
1142+ let t_e = f64::from(tc.norm_sqr());
1143+ if t_e > 1e-12 {
1144+ let (or, oi) = (f64::from(oc.re), f64::from(oc.im));
1145+ let (tr, ti) = (f64::from(tc.re), f64::from(tc.im));
1146+ let rr = (or * tr + oi * ti) / t_e;
1147+ let ri = (oi * tr - or * ti) / t_e;
1148+ ((rr * rr + ri * ri).sqrt(), ri.atan2(rr))
1149+ } else {
1150+ (0.0, 0.0)
1151+ }
1152+ })
1153+ .collect();
1154+ out.push((band as f64 * band_hz, traj));
1155+ }
1156+ out
1157+}
1158+
952 /// A file discovered under the user's own media directories: its path, which1159 /// A file discovered under the user's own media directories: its path, which
953 /// AAC stream in it (0-based among AAC streams only) carries HE-AAC, and the1160 /// AAC stream in it (0-based among AAC streams only) carries HE-AAC, and the
954 /// core/SBR crossover an ffprobe/ASC inspection already pinned for it -- used1161 /// core/SBR crossover an ffprobe/ASC inspection already pinned for it -- used
@@ -1600,6 +1807,67 @@ fn sbr_real_library_matches_reference() {
1600 println!(" ch{ch} HF lag sweep peak: k={peak_k} coherence {peak_c:.4}");1807 println!(" ch{ch} HF lag sweep peak: k={peak_k} coherence {peak_c:.4}");
1601 }1808 }
1602 }1809 }
1810+ // (Round-40, Task 1) fine spectral-bin shift scan -- see
1811+ // `hf_bin_shift_sweep`'s doc comment.
1812+ if std::env::var("EC_AAC_SBR_BIN_SHIFT").is_ok() && n >= 4_096 {
1813+ let win = &o[oa..oa + n];
1814+ let twin = &t[ob..ob + n];
1815+ for (region_name, lo, hi) in
1816+ [("even-gap[14,28)", 14, 28), ("odd-gap[28,43)", 28, 43)]
1817+ {
1818+ let sweep = hf_bin_shift_sweep(win, twin, rate, lo, hi);
1819+ println!(
1820+ " ch{ch} TASK1 BIN-SHIFT {region_name} (b = FFT bins, mean direct HF-bin coherence):"
1821+ );
1822+ for (b, coh) in &sweep {
1823+ println!(" b={b:>3}: coherence {coh:.4}");
1824+ }
1825+ if let Some((peak_b, peak_c)) =
1826+ sweep.iter().max_by(|a, b| a.1.partial_cmp(&b.1).unwrap())
1827+ {
1828+ println!(
1829+ " ch{ch} {region_name} bin-shift peak: b={peak_b} coherence {peak_c:.4}"
1830+ );
1831+ }
1832+ }
1833+ }
1834+ // (Round-40, Task 2) complex-gain fingerprint -- see
1835+ // `hf_complex_ratio_trajectory`'s doc comment.
1836+ if std::env::var("EC_AAC_SBR_COMPLEX_GAIN").is_ok() && n >= 4_096 {
1837+ let band_hz = f64::from(rate) / 256.0;
1838+ let min_band = (2_500.0 / band_hz).ceil() as usize;
1839+ let win = &o[oa..oa + n];
1840+ let twin = &t[ob..ob + n];
1841+ for (hz, traj) in hf_complex_ratio_trajectory(win, twin, rate, min_band, 4) {
1842+ println!(
1843+ " ch{ch} TASK2 COMPLEX-GAIN {hz:.0}Hz dominant-bin O/T trajectory (frame: mag, phase_deg, dphase_deg):"
1844+ );
1845+ let mut prev_phase: Option<f64> = None;
1846+ for (h, (mag, phase)) in traj.iter().enumerate() {
1847+ let dphase = prev_phase.map(|p| {
1848+ let mut d = phase.to_degrees() - p;
1849+ while d > 180.0 {
1850+ d -= 360.0;
1851+ }
1852+ while d < -180.0 {
1853+ d += 360.0;
1854+ }
1855+ d
1856+ });
1857+ prev_phase = Some(phase.to_degrees());
1858+ match dphase {
1859+ Some(d) => println!(
1860+ " frame{h:>3}: mag {mag:.4} phase {:>7.2}deg dphase {d:>7.2}deg",
1861+ phase.to_degrees()
1862+ ),
1863+ None => println!(
1864+ " frame{h:>3}: mag {mag:.4} phase {:>7.2}deg dphase n/a",
1865+ phase.to_degrees()
1866+ ),
1867+ }
1868+ }
1869+ }
1870+ }
1603 println!(1871 println!(
1604 " ch{ch}: lag {lag}, full {full:.6}, below {:.0}Hz {low:.6}, above {:.0}Hz {high:.6}",1872 " ch{ch}: lag {lag}, full {full:.6}, below {:.0}Hz {low:.6}, above {:.0}Hz {high:.6}",
1605 c.crossover_hz, c.crossover_hz1873 c.crossover_hz, c.crossover_hz