diag(aac-sbr): add a header/frame-feature discriminator table; fix two self-check instruments' stale/wrong lag conventions
Browse files at this commit2b4d6911648b2d36c107858e26958b9df3fbf018Parent: 03a10694 changed files +241 -23
- crates/ec-aac/src/sbr_chain.rs +36 -0
- crates/ec-aac/src/sbr_env.rs +6 -0
- crates/ec-aac/src/sbr_payload.rs +7 -0
- crates/ec-aac/tests/sbr_real_library.rs +192 -23
crates/ec-aac/src/sbr_chain.rsmodified+36 -0
| @@ -91,6 +91,26 @@ pub struct SbrSideInfoRow { | ||
| 91 | 91 | pub add_harmonic: Option<Vec<u8>>, |
| 92 | 92 | pub e_q_means: Vec<f64>, |
| 93 | 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 | 116 | static SIDEINFO_LOG: std::sync::OnceLock<std::sync::Mutex<Vec<SbrSideInfoRow>>> = |
| @@ -325,6 +345,20 @@ impl SbrChain { | ||
| 325 | 345 | add_harmonic: sbr_ch.add_harmonic.clone(), |
| 326 | 346 | e_q_means: mean(&sbr_ch.e_q), |
| 327 | 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 | 363 | let log = SIDEINFO_LOG.get_or_init(|| std::sync::Mutex::new(Vec::new())); |
| 330 | 364 | if let Ok(mut l) = log.lock() { |
| @@ -436,6 +470,8 @@ mod tests { | ||
| 436 | 470 | q_q: vec![vec![2i32; n_q]], |
| 437 | 471 | invf_mode: vec![0; n_q], |
| 438 | 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 | 848 | q_q: vec![vec![]], |
| 849 | 849 | invf_mode: vec![], |
| 850 | 850 | add_harmonic: None, |
| 851 | + df_env: vec![], | |
| 852 | + df_noise: vec![], | |
| 851 | 853 | }; |
| 852 | 854 | let target = 4.0f64; |
| 853 | 855 | let env_energy = vec![vec![target; tables.n_low]]; |
| @@ -940,6 +942,8 @@ mod tests { | ||
| 940 | 942 | q_q: vec![vec![]], |
| 941 | 943 | invf_mode: vec![], |
| 942 | 944 | add_harmonic: None, |
| 945 | + df_env: vec![], | |
| 946 | + df_noise: vec![], | |
| 943 | 947 | }; |
| 944 | 948 | let env_energy = vec![vec![1.0e6f64; tables.n_low]]; |
| 945 | 949 | // (Round-21) noise_energy is now a Q_div ratio against the cell's |
| @@ -1001,6 +1005,8 @@ mod tests { | ||
| 1001 | 1005 | q_q: vec![vec![]], |
| 1002 | 1006 | invf_mode: vec![], |
| 1003 | 1007 | add_harmonic: None, |
| 1008 | + df_env: vec![], | |
| 1009 | + df_noise: vec![], | |
| 1004 | 1010 | }; |
| 1005 | 1011 | let target = 4.0f64; |
| 1006 | 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 | 55 | pub invf_mode: Vec<u8>, |
| 56 | 56 | /// `bs_add_harmonic` per high-resolution band, when the flag is set. |
| 57 | 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 | 65 | /// One `sbr_data()` frame: one channel for an SCE, two for a CPE. |
| @@ -621,6 +626,8 @@ impl SbrParser { | ||
| 621 | 626 | q_q, |
| 622 | 627 | invf_mode: invf[ch].clone(), |
| 623 | 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 | 2097 | let cutoff = f64::from(core_rate) * 0.4; |
| 2098 | 2098 | let ol = lowpass(&full[ch], full_rate, cutoff); |
| 2099 | 2099 | let ul = lowpass(&up, full_rate, cutoff); |
| 2100 | - let (lag, corr) = best_lag_correlation(&ol, &ul); | |
| 2101 | - println!(" ch{ch}: lag {lag}, corr {corr:.6}"); | |
| 2102 | - println!( | |
| 2103 | - " ch{ch} @ rate-independent QMF delay -897: corr {:.6}", | |
| 2104 | - correlation_at_lag(&ol, &ul, -897) | |
| 2100 | + // Wide search, not the plain `best_lag_correlation`'s | |
| 2101 | + // `LAG_MAX=4000` -- the QMF-chain delay this measures is not a | |
| 2102 | + // fixed constant across files/rates (measured -576 on reeln | |
| 2103 | + // vs the stale -897 this test used to assert against), so the | |
| 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 | 2283 | 0.0 |
| 2274 | 2284 | }; |
| 2275 | 2285 | // Round-51's self-consistency probe (our full chain's low |
| 2276 | - // band vs our own core-only decode, 2x upsampled), run | |
| 2277 | - // per-row so a rate/kx-specific self-inconsistency shows in | |
| 2278 | - // the same table instead of needing a second pass. | |
| 2286 | + // band vs our own core-only decode), run per-row so a | |
| 2287 | + // rate/kx-specific self-inconsistency shows in the same | |
| 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 | 2315 | let ours_v_core = if kx > 0 { |
| 2280 | 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(); | |
| 2282 | - let cutoff = f64::from(core_rate) * 0.4; | |
| 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) | |
| 2317 | + let full_at_core_rate = decimate(o, our_rate, core_rate); | |
| 2318 | + best_lag_correlation_wide(&full_at_core_rate, &core[0], core_lag_max) | |
| 2286 | 2319 | }) |
| 2287 | 2320 | } else { |
| 2288 | 2321 | None |
| 2289 | 2322 | }; |
| 2290 | 2323 | // Coordinator follow-up 2: splits "our core decode of THIS |
| 2291 | 2324 | // fixture is wrong" (core_v_ref ~0) from "the SBR chain |
| 2292 | - // scrambles a good core" (core_v_ref >= ~0.99 while `below` | |
| 2293 | - // above stays ~0/negative) -- OUR core-only decode (2x | |
| 2294 | - // upsampled, same convention `ours_v_core` uses) against the | |
| 2295 | - // REFERENCE decoder's own decode, below the crossover only, | |
| 2296 | - // wide lag search since this is an independent alignment | |
| 2297 | - // from `full`/`below`'s (core-only carries no SBR delay). | |
| 2325 | + // scrambles a good core" (core_v_ref >= ~0.99 while `below`/ | |
| 2326 | + // `above` stays ~0/negative) -- OUR core-only decode, same | |
| 2327 | + // native-core-rate convention `ours_v_core` now uses, against | |
| 2328 | + // the REFERENCE decoder's own decode resampled to that same | |
| 2329 | + // core rate (`ffmpeg_decode_at_rate`, the same helper | |
| 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 | 2333 | let (core_v_ref, core_rate_str) = if kx > 0 { |
| 2299 | 2334 | match our_decode_core_only(&path, 0) { |
| 2300 | 2335 | Some((core, core_rate)) => { |
| 2301 | - let up: Vec<f32> = core[0].iter().flat_map(|&s| [s, s]).collect(); | |
| 2302 | - let tl = lowpass(t, our_rate, crossover_hz); | |
| 2303 | - let ul = lowpass(&up, our_rate, crossover_hz); | |
| 2304 | - (Some(best_lag_correlation_wide(&ul, &tl, WIDE_LAG_MAX)), core_rate.to_string()) | |
| 2336 | + let ref_at_core_rate = | |
| 2337 | + ffmpeg_decode_at_rate(&path, 0, core.len(), core_rate); | |
| 2338 | + ( | |
| 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 | 2347 | None => (None, "n/a".into()), |
| 2307 | 2348 | } |
| @@ -3262,3 +3303,131 @@ fn sbr_actual_noise_fraction() { | ||
| 3262 | 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 | +} |