forge
Explore
Log in

Don't you dare go Hollow

diag(aac-sbr): add a header/frame-feature discriminator table; fix two self-check instruments' stale/wrong lag conventions

Browse files at this commit

2b4d6911648b2d36c107858e26958b9df3fbf018Ahmet Kaan GümüşParent: 03a1069
Task A: sbr_header_feature_table (tests/sbr_real_library.rs) prints one row
per stream (reeln, FMJ, all 8 synthetic HE fixtures) of sbr_header()/
frame-level features (kx/k2, xover/start/stop freq, freq_scale, alter_scale,
noise_bands, limiter_bands/gains, interpol_freq, smoothing_mode, per-frame
num_env histogram, invf modes seen, add_harmonic usage, df_env/df_noise
delta-coding rate, patch geometry) next to each stream's pass/fail
correlation. Needed df_env/df_noise plumbed through SbrChannel and header
params + patch lengths added to SbrSideInfoRow (src change, no behaviour
change).

Key finding: FMJ (fail, corr 0.036) and synth-48000-64k (pass, corr 1.000)
share IDENTICAL kx/k2 (27/59), IDENTICAL header config, and IDENTICAL patch
geometry [26,1,5] -- the only differences in the table are per-frame entropy
(envelope-count histogram, invf-mode diversity), which is exactly what
differing real-vs-synthetic CONTENT should produce on its own. This directly
refutes "a per-stream SBR header/config feature separates pass from fail"
(the standing hypothesis this task was chartered to test): no such feature
exists in what sbr_header()/sbr_data() actually carries. Whatever breaks FMJ
must be in the payload's numeric content or the container/extraction path,
not the SBR sideinfo shape.

Task B: full_chain_low_band_matches_own_core no longer hardcodes a stale
QMF delay (-897); it now runs the same wide lag search
`synthetic_heaac_matrix` uses and asserts corr >= 0.99 at the MEASURED lag.
Confirms reeln's true lag is -576 (matches the ledger) at corr 0.997,
and turns FMJ's already-known low-band self-inconsistency (round-51) into a
real failing assertion instead of a silent print.

synthetic_heaac_matrix's `ours_v_core`/`core_v_ref` columns: replaced the
naive 2x-nearest-neighbor-upsample-then-lowpass-at-full-rate convention
(which read a flat ~-0.12 regardless of file) with the native-core-rate
decimate/`ffmpeg_decode_at_rate` convention `core_only_matches_reference`
already trusts. This measurably fixed the 44100 family (core_v_ref now
0.44-0.995, proving the core decode itself is correct there even though the
full chain fails at 0.07) but the 48000 family's core_v_ref is still flat/
negative despite `full`/`below` proving near-perfect correctness at native
rate -- left open, most likely a remaining artifact in this resampling-
domain comparison itself (ffmpeg's -ar downsample phase vs the wide-lag
search), not a real SBR defect, since `below` already disproves it at the
rate that matters. Correcting the charter's premise: core_v_ref did NOT
read 0.9999 before this fix (measured 0.22-0.40 on 48000, near 0 on
44100) -- both self-check columns were broken, not one healthy one to copy.
crates/ec-aac/src/sbr_chain.rsmodified+36 -0
@@ -91,6 +91,26 @@ pub struct SbrSideInfoRow {
91 pub add_harmonic: Option<Vec<u8>>,91 pub add_harmonic: Option<Vec<u8>>,
92 pub e_q_means: Vec<f64>,92 pub e_q_means: Vec<f64>,
93 pub q_q_means: Vec<f64>,93 pub q_q_means: Vec<f64>,
94+ /// Header fields held for the frame's duration (§4.6.18.3.2), added for
95+ /// the FMJ-vs-reeln feature-table hunt: `sbr_header()`'s own coding
96+ /// choices, not per-envelope grid data.
97+ pub freq_scale: u8,
98+ pub alter_scale: u8,
99+ pub noise_bands: u8,
100+ pub limiter_bands: u8,
101+ pub limiter_gains: u8,
102+ pub interpol_freq: u8,
103+ pub smoothing_mode: u8,
104+ pub start_freq: u8,
105+ pub stop_freq: u8,
106+ pub xover_band: u8,
107+ /// `t_noise.len() - 1`, i.e. `numNoiseFloors` this frame.
108+ pub num_noise: usize,
109+ /// One entry per HF patch, each the patch's band count (from
110+ /// `sbr_hf::build_patches`), so patch geometry is visible per frame.
111+ pub patch_lengths: Vec<usize>,
112+ pub df_env: Vec<u8>,
113+ pub df_noise: Vec<u8>,
94 }114 }
95 115
96 static SIDEINFO_LOG: std::sync::OnceLock<std::sync::Mutex<Vec<SbrSideInfoRow>>> =116 static SIDEINFO_LOG: std::sync::OnceLock<std::sync::Mutex<Vec<SbrSideInfoRow>>> =
@@ -325,6 +345,20 @@ impl SbrChain {
325 add_harmonic: sbr_ch.add_harmonic.clone(),345 add_harmonic: sbr_ch.add_harmonic.clone(),
326 e_q_means: mean(&sbr_ch.e_q),346 e_q_means: mean(&sbr_ch.e_q),
327 q_q_means: mean(&sbr_ch.q_q),347 q_q_means: mean(&sbr_ch.q_q),
348+ freq_scale: header.freq_scale,
349+ alter_scale: header.alter_scale,
350+ noise_bands: header.noise_bands,
351+ limiter_bands: header.limiter_bands,
352+ limiter_gains: header.limiter_gains,
353+ interpol_freq: header.interpol_freq,
354+ smoothing_mode: header.smoothing_mode,
355+ start_freq: header.start_freq,
356+ stop_freq: header.stop_freq,
357+ xover_band: header.xover_band,
358+ num_noise: sbr_ch.t_noise.len().saturating_sub(1),
359+ patch_lengths: sbr_hf::build_patches(&tables).iter().map(|p| p.width).collect(),
360+ df_env: sbr_ch.df_env.clone(),
361+ df_noise: sbr_ch.df_noise.clone(),
328 };362 };
329 let log = SIDEINFO_LOG.get_or_init(|| std::sync::Mutex::new(Vec::new()));363 let log = SIDEINFO_LOG.get_or_init(|| std::sync::Mutex::new(Vec::new()));
330 if let Ok(mut l) = log.lock() {364 if let Ok(mut l) = log.lock() {
@@ -436,6 +470,8 @@ mod tests {
436 q_q: vec![vec![2i32; n_q]],470 q_q: vec![vec![2i32; n_q]],
437 invf_mode: vec![0; n_q],471 invf_mode: vec![0; n_q],
438 add_harmonic: None,472 add_harmonic: None,
473+ df_env: vec![],
474+ df_noise: vec![],
439 }475 }
440 }476 }
441 477
crates/ec-aac/src/sbr_env.rsmodified+6 -0
@@ -848,6 +848,8 @@ mod tests {
848 q_q: vec![vec![]],848 q_q: vec![vec![]],
849 invf_mode: vec![],849 invf_mode: vec![],
850 add_harmonic: None,850 add_harmonic: None,
851+ df_env: vec![],
852+ df_noise: vec![],
851 };853 };
852 let target = 4.0f64;854 let target = 4.0f64;
853 let env_energy = vec![vec![target; tables.n_low]];855 let env_energy = vec![vec![target; tables.n_low]];
@@ -940,6 +942,8 @@ mod tests {
940 q_q: vec![vec![]],942 q_q: vec![vec![]],
941 invf_mode: vec![],943 invf_mode: vec![],
942 add_harmonic: None,944 add_harmonic: None,
945+ df_env: vec![],
946+ df_noise: vec![],
943 };947 };
944 let env_energy = vec![vec![1.0e6f64; tables.n_low]];948 let env_energy = vec![vec![1.0e6f64; tables.n_low]];
945 // (Round-21) noise_energy is now a Q_div ratio against the cell's949 // (Round-21) noise_energy is now a Q_div ratio against the cell's
@@ -1001,6 +1005,8 @@ mod tests {
1001 q_q: vec![vec![]],1005 q_q: vec![vec![]],
1002 invf_mode: vec![],1006 invf_mode: vec![],
1003 add_harmonic: None,1007 add_harmonic: None,
1008+ df_env: vec![],
1009+ df_noise: vec![],
1004 };1010 };
1005 let target = 4.0f64;1011 let target = 4.0f64;
1006 let env_energy = vec![vec![target; tables.n_low]];1012 let env_energy = vec![vec![target; tables.n_low]];
crates/ec-aac/src/sbr_payload.rsmodified+7 -0
@@ -55,6 +55,11 @@ pub struct SbrChannel {
55 pub invf_mode: Vec<u8>,55 pub invf_mode: Vec<u8>,
56 /// `bs_add_harmonic` per high-resolution band, when the flag is set.56 /// `bs_add_harmonic` per high-resolution band, when the flag is set.
57 pub add_harmonic: Option<Vec<u8>>,57 pub add_harmonic: Option<Vec<u8>>,
58+ /// `bs_df_env` per envelope: `1` selects delta-time coding over
59+ /// delta-frequency (diagnostic only, not consumed by the DSP stage).
60+ pub df_env: Vec<u8>,
61+ /// `bs_df_noise` per noise floor, same convention as `df_env`.
62+ pub df_noise: Vec<u8>,
58 }63 }
59 64
60 /// One `sbr_data()` frame: one channel for an SCE, two for a CPE.65 /// One `sbr_data()` frame: one channel for an SCE, two for a CPE.
@@ -621,6 +626,8 @@ impl SbrParser {
621 q_q,626 q_q,
622 invf_mode: invf[ch].clone(),627 invf_mode: invf[ch].clone(),
623 add_harmonic: None,628 add_harmonic: None,
629+ df_env: df_env[ch].iter().map(|&b| u8::from(b)).collect(),
630+ df_noise: df_noise[ch].iter().map(|&b| u8::from(b)).collect(),
624 });631 });
625 }632 }
626 633
crates/ec-aac/tests/sbr_real_library.rsmodified+192 -23
@@ -2097,11 +2097,21 @@ fn full_chain_low_band_matches_own_core() {
2097 let cutoff = f64::from(core_rate) * 0.4;2097 let cutoff = f64::from(core_rate) * 0.4;
2098 let ol = lowpass(&full[ch], full_rate, cutoff);2098 let ol = lowpass(&full[ch], full_rate, cutoff);
2099 let ul = lowpass(&up, full_rate, cutoff);2099 let ul = lowpass(&up, full_rate, cutoff);
2100- let (lag, corr) = best_lag_correlation(&ol, &ul);2100+ // Wide search, not the plain `best_lag_correlation`'s
2101- println!(" ch{ch}: lag {lag}, corr {corr:.6}");2101+ // `LAG_MAX=4000` -- the QMF-chain delay this measures is not a
2102- println!(2102+ // fixed constant across files/rates (measured -576 on reeln
2103- " ch{ch} @ rate-independent QMF delay -897: corr {:.6}",2103+ // vs the stale -897 this test used to assert against), so the
2104- correlation_at_lag(&ol, &ul, -897)2104+ // lag itself is part of what's measured here, not assumed.
2105+ const WIDE_LAG_MAX: i64 = 20_000;
2106+ let (lag, corr) = best_lag_correlation_wide(&ol, &ul, WIDE_LAG_MAX);
2107+ println!(" ch{ch}: measured best lag {lag}, corr {corr:.6}");
2108+ assert!(
2109+ corr >= 0.99,
2110+ "{} ch{ch}: full-chain low band vs our own core-only decode \
2111+ corr {corr:.6} at measured lag {lag} < 0.99 -- the \
2112+ synthesis/gain-adjust stage is corrupting even the untouched \
2113+ low-band region copied straight from core analysis",
2114+ c.path.display()
2105 );2115 );
2106 }2116 }
2107 }2117 }
@@ -2273,35 +2283,66 @@ fn synthetic_heaac_matrix() {
2273 0.02283 0.0
2274 };2284 };
2275 // Round-51's self-consistency probe (our full chain's low2285 // Round-51's self-consistency probe (our full chain's low
2276- // band vs our own core-only decode, 2x upsampled), run2286+ // band vs our own core-only decode), run per-row so a
2277- // per-row so a rate/kx-specific self-inconsistency shows in2287+ // rate/kx-specific self-inconsistency shows in the same
2278- // the same table instead of needing a second pass.2288+ // table instead of needing a second pass.
2289+ //
2290+ // Fixed (this round): the original convention naively
2291+ // nearest-neighbor UPSAMPLED the core 2x and compared it
2292+ // against the full-rate signal, low-passed at
2293+ // `core_rate*0.4` -- that stairstep-and-lowpass round trip
2294+ // is lossy enough on its own to sink a genuinely-correct
2295+ // pair's correlation (measured flat ~-0.12 here even on
2296+ // rows whose `full`/`below` columns read 0.999+ against the
2297+ // real reference). `core_only_matches_reference` already
2298+ // proved a clean pattern for this exact comparison: stay in
2299+ // the CORE's own native rate (DECIMATE the full/reference
2300+ // signal down instead of upsampling the core up) and use a
2301+ // wide lag search there. `decimate` below is a lowpass
2302+ // (well under the core Nyquist) followed by a plain
2303+ // every-other-sample drop -- the inverse of the old
2304+ // `[s, s]` upsample, at the same information cost but
2305+ // without its stairstep artifact.
2306+ let decimate = |s: &[f32], from_rate: u32, to_rate: u32| -> Vec<f32> {
2307+ let cutoff = f64::from(to_rate) * 0.45;
2308+ lowpass(s, from_rate, cutoff)
2309+ .iter()
2310+ .step_by((from_rate / to_rate.max(1)).max(1) as usize)
2311+ .copied()
2312+ .collect()
2313+ };
2314+ let core_lag_max = WIDE_LAG_MAX / 2;
2279 let ours_v_core = if kx > 0 {2315 let ours_v_core = if kx > 0 {
2280 our_decode_core_only(&path, 0).map(|(core, core_rate)| {2316 our_decode_core_only(&path, 0).map(|(core, core_rate)| {
2281- let up: Vec<f32> = core[0].iter().flat_map(|&s| [s, s]).collect();2317+ let full_at_core_rate = decimate(o, our_rate, core_rate);
2282- let cutoff = f64::from(core_rate) * 0.4;2318+ best_lag_correlation_wide(&full_at_core_rate, &core[0], core_lag_max)
2283- let ol = lowpass(o, our_rate, cutoff);
2284- let ul = lowpass(&up, our_rate, cutoff);
2285- best_lag_correlation_wide(&ol, &ul, WIDE_LAG_MAX)
2286 })2319 })
2287 } else {2320 } else {
2288 None2321 None
2289 };2322 };
2290 // Coordinator follow-up 2: splits "our core decode of THIS2323 // Coordinator follow-up 2: splits "our core decode of THIS
2291 // fixture is wrong" (core_v_ref ~0) from "the SBR chain2324 // fixture is wrong" (core_v_ref ~0) from "the SBR chain
2292- // scrambles a good core" (core_v_ref >= ~0.99 while `below`2325+ // scrambles a good core" (core_v_ref >= ~0.99 while `below`/
2293- // above stays ~0/negative) -- OUR core-only decode (2x2326+ // `above` stays ~0/negative) -- OUR core-only decode, same
2294- // upsampled, same convention `ours_v_core` uses) against the2327+ // native-core-rate convention `ours_v_core` now uses, against
2295- // REFERENCE decoder's own decode, below the crossover only,2328+ // the REFERENCE decoder's own decode resampled to that same
2296- // wide lag search since this is an independent alignment2329+ // core rate (`ffmpeg_decode_at_rate`, the same helper
2297- // from `full`/`below`'s (core-only carries no SBR delay).2330+ // `core_only_matches_reference` already trusts) -- wide lag
2331+ // search since this is an independent alignment from
2332+ // `full`/`below`'s (core-only carries no SBR delay).
2298 let (core_v_ref, core_rate_str) = if kx > 0 {2333 let (core_v_ref, core_rate_str) = if kx > 0 {
2299 match our_decode_core_only(&path, 0) {2334 match our_decode_core_only(&path, 0) {
2300 Some((core, core_rate)) => {2335 Some((core, core_rate)) => {
2301- let up: Vec<f32> = core[0].iter().flat_map(|&s| [s, s]).collect();2336+ let ref_at_core_rate =
2302- let tl = lowpass(t, our_rate, crossover_hz);2337+ ffmpeg_decode_at_rate(&path, 0, core.len(), core_rate);
2303- let ul = lowpass(&up, our_rate, crossover_hz);2338+ (
2304- (Some(best_lag_correlation_wide(&ul, &tl, WIDE_LAG_MAX)), core_rate.to_string())2339+ Some(best_lag_correlation_wide(
2340+ &core[0],
2341+ &ref_at_core_rate[0],
2342+ core_lag_max,
2343+ )),
2344+ core_rate.to_string(),
2345+ )
2305 }2346 }
2306 None => (None, "n/a".into()),2347 None => (None, "n/a".into()),
2307 }2348 }
@@ -3262,3 +3303,131 @@ fn sbr_actual_noise_fraction() {
3262 0.1787 pre-fix -- shape does not move this metric, see doc above)"3303 0.1787 pre-fix -- shape does not move this metric, see doc above)"
3263 );3304 );
3264 }3305 }
3306+
3307+/// Discriminator instrument: one row per stream of the SBR header/frame
3308+/// features actually parsed from its first ~20 `sbr_data()` frames, next to
3309+/// that stream's own pass/fail correlation vs the reference decoder --
3310+/// looking for which feature(s) separate the two known-PASS streams
3311+/// (reeln, synthetic 48k HE) from the two known-FAIL families (FMJ,
3312+/// synthetic 44.1k HE). Gated on the real files / fixture directory being
3313+/// present, same as the tests it borrows machinery from; skips loudly,
3314+/// generates nothing.
3315+#[test]
3316+fn sbr_header_feature_table() {
3317+ if !have_ffmpeg() {
3318+ eprintln!("SKIP: ffmpeg not on PATH");
3319+ return;
3320+ }
3321+ struct Row {
3322+ label: String,
3323+ path: PathBuf,
3324+ aac_stream: usize,
3325+ ffmpeg_stream: usize,
3326+ }
3327+ let mut rows: Vec<Row> = candidates()
3328+ .into_iter()
3329+ .map(|c| Row {
3330+ label: c
3331+ .path
3332+ .file_stem()
3333+ .map(|s| s.to_string_lossy().into_owned())
3334+ .unwrap_or_default(),
3335+ path: c.path,
3336+ aac_stream: c.aac_stream,
3337+ ffmpeg_stream: c.ffmpeg_stream,
3338+ })
3339+ .collect();
3340+ let fixtures = std::env::var("EC_AAC_HEAAC_FIXTURES").unwrap_or_else(|_| {
3341+ format!("{}/../../.cache/heaac-fixtures", env!("CARGO_MANIFEST_DIR"))
3342+ });
3343+ let fixtures = PathBuf::from(fixtures);
3344+ if fixtures.is_dir() {
3345+ for rate in [48_000u32, 44_100] {
3346+ for br in ["32k", "48k", "64k", "96k"] {
3347+ let p = fixtures.join(format!("heaac_{rate}_{br}.m4a"));
3348+ if p.exists() {
3349+ rows.push(Row {
3350+ label: format!("synth-{rate}-{br}"),
3351+ path: p,
3352+ aac_stream: 0,
3353+ ffmpeg_stream: 0,
3354+ });
3355+ }
3356+ }
3357+ }
3358+ } else {
3359+ eprintln!(
3360+ "SKIP synthetic rows: {} absent -- run scripts/aac-tables/make-heaac-fixtures.sh first",
3361+ fixtures.display()
3362+ );
3363+ }
3364+ if rows.is_empty() {
3365+ eprintln!("SKIP: no real HE-AAC files and no synthetic fixtures found");
3366+ return;
3367+ }
3368+ unsafe {
3369+ std::env::set_var("EC_AAC_SBR_SIDEINFO_DEBUG", "1");
3370+ }
3371+ const WIDE_LAG_MAX: i64 = 20_000;
3372+ println!(
3373+ "{:<20} {:>6} {:>4} {:>4} {:>4} {:>4} {:>4} {:>4} {:>4} {:>4} {:>4} {:>4} {:>5} {:>10} {:>10} {:>8} {:>8} {:>10} {:>6}",
3374+ "stream", "rate", "kx", "k2", "xovr", "sfrq", "efrq", "fscl", "ascl", "nbnd", "lbnd", "lgn",
3375+ "ifrq", "smooth", "envs", "invf", "harm", "df%", "corr"
3376+ );
3377+ for r in &rows {
3378+ let before = ec_aac::sbr_sideinfo_log().len();
3379+ let Some((ours, sbr, our_rate)) = our_decode(&r.path, r.aac_stream) else {
3380+ eprintln!("SKIP {}: could not decode", r.label);
3381+ continue;
3382+ };
3383+ if sbr != ec_aac::SbrSupport::V1 {
3384+ eprintln!("SKIP {}: not SBR v1", r.label);
3385+ continue;
3386+ }
3387+ let log = ec_aac::sbr_sideinfo_log();
3388+ let frames: Vec<_> = log[before..].iter().filter(|row| row.ch == 0).take(20).collect();
3389+ if frames.is_empty() {
3390+ eprintln!("SKIP {}: no sideinfo rows captured", r.label);
3391+ continue;
3392+ }
3393+ let f0 = &frames[0];
3394+ let mut env_counts: std::collections::BTreeMap<usize, usize> = Default::default();
3395+ let mut invf_seen: std::collections::BTreeSet<u8> = Default::default();
3396+ let mut any_harmonic = false;
3397+ let mut df_total = 0usize;
3398+ let mut df_ones = 0usize;
3399+ for row in &frames {
3400+ *env_counts.entry(row.t_env.len().saturating_sub(1)).or_default() += 1;
3401+ invf_seen.extend(&row.invf_mode);
3402+ if row.add_harmonic.as_ref().is_some_and(|h| h.iter().any(|&v| v != 0)) {
3403+ any_harmonic = true;
3404+ }
3405+ df_total += row.df_env.len() + row.df_noise.len();
3406+ df_ones += row.df_env.iter().chain(&row.df_noise).filter(|&&b| b != 0).count();
3407+ }
3408+ let df_pct = if df_total > 0 {
3409+ 100.0 * df_ones as f64 / df_total as f64
3410+ } else {
3411+ 0.0
3412+ };
3413+ let envs_hist: String = env_counts
3414+ .iter()
3415+ .map(|(k, v)| format!("{k}x{v}"))
3416+ .collect::<Vec<_>>()
3417+ .join(",");
3418+ let invf_str: String = invf_seen.iter().map(|v| v.to_string()).collect::<Vec<_>>().join("");
3419+ let theirs = ffmpeg_decode(&r.path, r.ffmpeg_stream, ours.len());
3420+ let (_, corr) = best_lag_correlation_wide(&ours[0], &theirs[0], WIDE_LAG_MAX);
3421+ println!(
3422+ "{:<20} {:>6} {:>4} {:>4} {:>4} {:>4} {:>4} {:>4} {:>4} {:>4} {:>4} {:>4} {:>5} {:>10} {:>10} {:>8} {:>8} {:>10.1} {:>6.3}",
3423+ r.label, our_rate, f0.kx, f0.k2, f0.xover_band, f0.start_freq, f0.stop_freq,
3424+ f0.freq_scale, f0.alter_scale, f0.noise_bands, f0.limiter_bands, f0.limiter_gains,
3425+ f0.interpol_freq, f0.smoothing_mode, envs_hist, invf_str,
3426+ any_harmonic, df_pct, corr
3427+ );
3428+ println!(
3429+ " patches (frame0): {:?}",
3430+ f0.patch_lengths
3431+ );
3432+ }
3433+}