forge
Explore
Log in

Don't you dare go Hollow

debug(ec-aac): third-witness plain patch+gain simulator for SBR HF content

Browse files at this commit

1117d7a740ee7360aecab0877aa9cd35ed9ceff6Ahmet Kaan GümüşParent: 3b60454
Reference-free model: copies the decoded reference's low band through the
verified patch map, rescales per (band, hop) to each comparison side's own
energy, then measures complex coherence sim-vs-reference and sim-vs-ours --
breaking the pairwise ours-vs-reference deadlock. Gated by
EC_AAC_SBR_SIMULATOR, lands as a permanent diagnostic.
crates/ec-aac/tests/sbr_real_library.rsmodified+158 -0
@@ -1156,6 +1156,126 @@ fn hf_complex_ratio_trajectory(
11561156 out
11571157 }
11581158
1159+/// Round-45, Task 3 THIRD WITNESS. Every prior round compared OURS against
1160+/// the REFERENCE directly -- a pairwise measurement that can never say which
1161+/// side is wrong when they disagree. This builds a reference-free model: a
1162+/// pure "plain patch-copy + per-band energy match" reconstruction of HF
1163+/// content from the REFERENCE's own LOW band (the one piece of ground truth
1164+/// both decoders start from and our own low-band round-trip already measures
1165+/// as near-identity), using the verified patch map
1166+/// `[(0,14,14),(3,28,11),(0,39,3),(13,42,1)]` and this file's own established
1167+/// `band_hz = rate/256`, `BINS_PER_SBR_BAND = FFT_LEN/256 = 8` convention
1168+/// (round-14/16; NOT the `rate/128` scale the naive spec reading suggests --
1169+/// that value indexes the QMF/hybrid analysis grid, not this STFT-bin grid,
1170+/// and using it here would be the "trap" that bit round-42 elsewhere in this
1171+/// file. The patch map's own band numbers (14/28/39/42/43) only make sense
1172+/// under the `/256` convention already used everywhere else in this file that
1173+/// touches the patch map -- confirmed by construction, not re-derived here).
1174+///
1175+/// For each HF band in `[14, 43)` and each STFT hop, the simulated bins are
1176+/// the REFERENCE's low-band bins at the patch-mapped source position, then
1177+/// RESCALED per (band, hop) to match the comparison side's own energy in
1178+/// that band/hop -- two separate rescalings, "sim-normalized-to-ours" and
1179+/// "sim-normalized-to-reference" -- so the only thing left for the
1180+/// coherence measure to see is phase/content structure, not a gain
1181+/// difference (the gain question is already closed by prior rounds). Returns
1182+/// `(band, coherence)` pairs for sim-vs-reference and sim-vs-ours.
1183+type BandCoherenceTable = Vec<(usize, f64)>;
1184+
1185+fn hf_patch_simulator(o: &[f32], t: &[f32], rate: u32) -> (BandCoherenceTable, BandCoherenceTable) {
1186+ const FFT_LEN: usize = 2048;
1187+ const HOP: usize = 1024;
1188+ const BINS_PER_SBR_BAND: usize = FFT_LEN / 256;
1189+ const PATCHES: [(usize, usize, usize); 4] = [(0, 14, 14), (3, 28, 11), (0, 39, 3), (13, 42, 1)];
1190+ let _ = rate; // band Hz not needed here; caller converts band index itself.
1191+ let win = ec_dsp::Window::<f32>::sine(FFT_LEN);
1192+ let mut rfft = ec_dsp::RealFft::<f32>::new(FFT_LEN);
1193+ let bins = rfft.spectrum_len();
1194+ let n = o.len().min(t.len());
1195+ let hops = if n >= FFT_LEN {
1196+ (n - FFT_LEN) / HOP + 1
1197+ } else {
1198+ 0
1199+ };
1200+ if hops == 0 {
1201+ return (Vec::new(), Vec::new());
1202+ }
1203+ let mut o_spec = vec![Vec::with_capacity(hops); bins];
1204+ let mut t_spec = vec![Vec::with_capacity(hops); bins];
1205+ let mut spectrum = vec![ec_dsp::Complex::new(0.0f32, 0.0); bins];
1206+ for (src, dst) in [(o, &mut o_spec), (t, &mut t_spec)] {
1207+ for h in 0..hops {
1208+ let mut block = src[h * HOP..h * HOP + FFT_LEN].to_vec();
1209+ win.apply(&mut block);
1210+ rfft.forward(&block, &mut spectrum);
1211+ for (b, c) in spectrum.iter().enumerate() {
1212+ dst[b].push(*c);
1213+ }
1214+ }
1215+ }
1216+ // Plain patch copy: sim's target bins, per hop, are the reference's
1217+ // source bins, unmodified (no phase adjustment) -- modelling exactly the
1218+ // "plain patch+gain" hypothesis the charter names.
1219+ let mut sim_spec = vec![vec![ec_dsp::Complex::new(0.0f32, 0.0); hops]; bins];
1220+ for (src, tgt, width) in PATCHES {
1221+ let src_lo = src * BINS_PER_SBR_BAND;
1222+ let tgt_lo = tgt * BINS_PER_SBR_BAND;
1223+ let len = width * BINS_PER_SBR_BAND;
1224+ for i in 0..len {
1225+ if src_lo + i >= bins || tgt_lo + i >= bins {
1226+ continue;
1227+ }
1228+ for h in 0..hops {
1229+ sim_spec[tgt_lo + i][h] = t_spec[src_lo + i][h];
1230+ }
1231+ }
1232+ }
1233+ let num_bands = bins / BINS_PER_SBR_BAND;
1234+ let top_band = 43.min(num_bands);
1235+ // Per (band, hop) rescale of `sim` to match `target`'s energy in that
1236+ // band/hop, then the same magnitude-of-summed-cross-spectrum coherence
1237+ // measure every prior round's `coh` helper uses (already scale-invariant
1238+ // to a CONSTANT gain across hops; this rescale additionally removes a
1239+ // gain that varies hop-to-hop, isolating phase/content agreement).
1240+ let band_coherence = |target: &[Vec<ec_dsp::Complex<f32>>]| -> Vec<(usize, f64)> {
1241+ (14..top_band)
1242+ .map(|band| {
1243+ let lo = band * BINS_PER_SBR_BAND;
1244+ let hi = (lo + BINS_PER_SBR_BAND).min(bins);
1245+ let mut cross_re = 0.0f64;
1246+ let mut cross_im = 0.0f64;
1247+ let mut sim_e = 0.0f64;
1248+ let mut tgt_e = 0.0f64;
1249+ for h in 0..hops {
1250+ let se: f64 = (lo..hi).map(|b| f64::from(sim_spec[b][h].norm_sqr())).sum();
1251+ let te: f64 = (lo..hi).map(|b| f64::from(target[b][h].norm_sqr())).sum();
1252+ if se <= 1e-20 || te <= 0.0 {
1253+ continue;
1254+ }
1255+ let scale = (te / se).sqrt() as f32;
1256+ for b in lo..hi {
1257+ let sc = sim_spec[b][h].scale(scale);
1258+ let tc = target[b][h];
1259+ let cross = sc * tc.conj();
1260+ cross_re += f64::from(cross.re);
1261+ cross_im += f64::from(cross.im);
1262+ sim_e += f64::from(sc.norm_sqr());
1263+ tgt_e += f64::from(tc.norm_sqr());
1264+ }
1265+ }
1266+ let den = (sim_e * tgt_e).sqrt();
1267+ let coh = if den > 0.0 {
1268+ (cross_re * cross_re + cross_im * cross_im).sqrt() / den
1269+ } else {
1270+ 0.0
1271+ };
1272+ (band, coh)
1273+ })
1274+ .collect()
1275+ };
1276+ (band_coherence(&t_spec), band_coherence(&o_spec))
1277+}
1278+
11591279 /// A file discovered under the user's own media directories: its path, which
11601280 /// AAC stream in it (0-based among AAC streams only) carries HE-AAC, and the
11611281 /// core/SBR crossover an ffprobe/ASC inspection already pinned for it -- used
@@ -1868,6 +1988,44 @@ fn sbr_real_library_matches_reference() {
18681988 }
18691989 }
18701990 }
1991+ // (Round-45, Task 3) THIRD WITNESS: a reference-free plain
1992+ // patch+gain simulator built from the reference's own low band --
1993+ // see `hf_patch_simulator`'s doc comment.
1994+ if std::env::var("EC_AAC_SBR_SIMULATOR").is_ok() && n >= 4_096 {
1995+ let win = &o[oa..oa + n];
1996+ let twin = &t[ob..ob + n];
1997+ let (vs_ref, vs_ours) = hf_patch_simulator(win, twin, rate);
1998+ let mean_in = |rows: &[(usize, f64)], lo: usize, hi: usize| {
1999+ let vals: Vec<f64> = rows
2000+ .iter()
2001+ .filter(|(b, _)| *b >= lo && *b < hi)
2002+ .map(|(_, c)| *c)
2003+ .collect();
2004+ if vals.is_empty() {
2005+ 0.0
2006+ } else {
2007+ vals.iter().sum::<f64>() / vals.len() as f64
2008+ }
2009+ };
2010+ println!(" ch{ch} SIMULATOR sim-vs-REFERENCE per-band coherence (band, coh):");
2011+ for (b, coh) in &vs_ref {
2012+ println!(" band{b:>3}: {coh:.4}");
2013+ }
2014+ println!(
2015+ " ch{ch} SIMULATOR sim-vs-REFERENCE mean: even-gap[14,28)={:.4} odd-gap[28,43)={:.4}",
2016+ mean_in(&vs_ref, 14, 28),
2017+ mean_in(&vs_ref, 28, 43)
2018+ );
2019+ println!(" ch{ch} SIMULATOR sim-vs-OURS per-band coherence (band, coh):");
2020+ for (b, coh) in &vs_ours {
2021+ println!(" band{b:>3}: {coh:.4}");
2022+ }
2023+ println!(
2024+ " ch{ch} SIMULATOR sim-vs-OURS mean: even-gap[14,28)={:.4} odd-gap[28,43)={:.4}",
2025+ mean_in(&vs_ours, 14, 28),
2026+ mean_in(&vs_ours, 28, 43)
2027+ );
2028+ }
18712029 println!(
18722030 " ch{ch}: lag {lag}, full {full:.6}, below {:.0}Hz {low:.6}, above {:.0}Hz {high:.6}",
18732031 c.crossover_hz, c.crossover_hz