forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'sbr-441-family'

Browse files at this commit

340601ec763fe0fb8372b6c5f4bf47256bc80dd6Ahmet Kaan GümüşParent: 22effdaf7652c7
crates/ec-aac/src/sbr_chain.rsmodified+28 -0
@@ -295,6 +295,20 @@ impl SbrChain {
295295 if num_slots == 0 {
296296 continue;
297297 }
298+ if std::env::var("EC_AAC_SBR_PREQMF_DUMP").is_ok() {
299+ static N: AtomicUsize = AtomicUsize::new(0);
300+ let n = N.fetch_add(1, Ordering::Relaxed);
301+ if n < 40 {
302+ let rms = (plane.iter().map(|v| f64::from(*v) * f64::from(*v)).sum::<f64>()
303+ / plane.len().max(1) as f64)
304+ .sqrt();
305+ eprintln!(
306+ "PREQMF n={n} tag={tag} ch={ch} len={} rms={rms:.6} first8={:?}",
307+ plane.len(),
308+ &plane[..8.min(plane.len())]
309+ );
310+ }
311+ }
298312 let state = &mut elem.channels[ch];
299313 let mut low_cur = vec![vec![Complex::ZERO; num_slots]; ANALYSIS_BANDS];
300314 let mut raw = Vec::with_capacity(num_slots);
@@ -441,6 +455,20 @@ impl SbrChain {
441455 }
442456 out.extend_from_slice(&pcm);
443457 }
458+ if std::env::var("EC_AAC_SBR_PREQMF_DUMP").is_ok() {
459+ static N: AtomicUsize = AtomicUsize::new(0);
460+ let n = N.fetch_add(1, Ordering::Relaxed);
461+ if n < 40 {
462+ let rms = (out.iter().map(|v| f64::from(*v) * f64::from(*v)).sum::<f64>()
463+ / out.len().max(1) as f64)
464+ .sqrt();
465+ eprintln!(
466+ "POSTQMF n={n} tag={tag} ch={ch} len={} rms={rms:.6} first8={:?}",
467+ out.len(),
468+ &out[..8.min(out.len())]
469+ );
470+ }
471+ }
444472 *plane = out;
445473 }
446474 }
crates/ec-aac/tests/sbr_real_library.rsmodified+212 -14
@@ -1930,7 +1930,8 @@ fn our_decode_core_only(path: &Path, stream_index: usize) -> Option<(Vec<Vec<f32
19301930 let core_rate = cfg.sample_rate;
19311931 let mut decoder = AacDecoder::with_config(cfg);
19321932 let mut planes: Vec<Vec<f32>> = Vec::new();
1933- for au in &aus {
1933+ let dump = std::env::var("EC_AAC_SBR_PREQMF_DUMP").is_ok();
1934+ for (au_idx, au) in aus.iter().enumerate() {
19341935 let Ok(frame) = decoder.decode(au, None) else {
19351936 continue;
19361937 };
@@ -1938,6 +1939,19 @@ fn our_decode_core_only(path: &Path, stream_index: usize) -> Option<(Vec<Vec<f32
19381939 if ch == 0 {
19391940 continue;
19401941 }
1942+ if dump && au_idx < 40 {
1943+ for c in 0..ch {
1944+ let plane: Vec<f32> = frame.samples.iter().skip(c).step_by(ch).copied().collect();
1945+ let rms = (plane.iter().map(|v| f64::from(*v) * f64::from(*v)).sum::<f64>()
1946+ / plane.len().max(1) as f64)
1947+ .sqrt();
1948+ eprintln!(
1949+ "COREAU n={au_idx} ch={c} len={} rms={rms:.6} first8={:?}",
1950+ plane.len(),
1951+ &plane[..8.min(plane.len())]
1952+ );
1953+ }
1954+ }
19411955 if planes.is_empty() {
19421956 planes = vec![Vec::new(); ch];
19431957 }
@@ -2263,10 +2277,29 @@ fn synthetic_heaac_matrix() {
22632277 let theirs = ffmpeg_decode(&path, 0, ours.len());
22642278 let o = &ours[0];
22652279 let t = &theirs[0];
2266- let (lag, full) = best_lag_correlation_wide(o, t, WIDE_LAG_MAX);
2280+ let (mut lag, mut full) = best_lag_correlation_wide(o, t, WIDE_LAG_MAX);
22672281 if profile == "LC" {
22682282 lc_lag = Some(lag);
22692283 }
2284+ // HE rows: a per-channel free lag search on periodic/tonal
2285+ // content is unreliable (coupled_cpe_channel_swap_probe
2286+ // proved this file's ref L vs ref R itself mis-searches --
2287+ // lag=-24 corr=0.213 vs the fixed lag=0 corr=0.873 -- and
2288+ // the same coarse search can land two channels of the SAME
2289+ // stream on DIFFERENT, individually-wrong lags, faking a
2290+ // channel swap that a fixed-lag check rules out). Derive
2291+ // ONE lag per stream from the summed (mono) signal instead,
2292+ // and reuse it for both channels -- more robust than
2293+ // trusting a single, possibly-periodic channel's own search.
2294+ if profile == "HE" && ours.len() >= 2 && theirs.len() >= 2 {
2295+ let mono_o: Vec<f32> =
2296+ ours[0].iter().zip(&ours[1]).map(|(a, b)| a + b).collect();
2297+ let mono_t: Vec<f32> =
2298+ theirs[0].iter().zip(&theirs[1]).map(|(a, b)| a + b).collect();
2299+ let (mono_lag, _) = best_lag_correlation_wide(&mono_o, &mono_t, WIDE_LAG_MAX);
2300+ lag = mono_lag;
2301+ full = correlation_at_lag(o, t, lag);
2302+ }
22702303 // Crossover in Hz from the actual parsed kx (band width
22712304 // rate/128, same domain `sbr_chain.rs`'s own doc comment
22722305 // gives `kx`/`k2` in) when SBR engaged; a fixed quarter-Nyquist
@@ -3871,16 +3904,32 @@ fn reelq_multichannel_lc_matches_reference() {
38713904 /// shows `coupling: true` on nearly every AU (reeln/FMJ, both passing,
38723905 /// show `coupling: false`) -- checks whether our decoded ch0 actually
38733906 /// correlates better against the REFERENCE's R channel than its own L.
3874-/// RULED OUT as the cause (this round): `sbr_env::dequant_pair`'s
3875-/// `panOffset`/exponent formula had two real spec bugs (fixed, see its
3876-/// doc comment) but neither the fix nor `EC_AAC_SBR_HF_BYPASS=1` (which
3877-/// reduces SBR to a per-channel low-band QMF round trip with NO
3878-/// envelope/coupling/HF-generation code running at all) changes this
3879-/// probe's correlation numbers -- the swap survives with the entire
3880-/// `sbr_env`/`sbr_hf` machinery out of the picture, so it lives
3881-/// elsewhere (plane/channel threading in `sbr_chain::apply_data` or
3882-/// `decode.rs`'s per-AU channel assembly, or this test's own
3883-/// interleave-to-plane de-mux -- unexplored this round).
3907+/// RULED OUT (prior rounds): `sbr_env::dequant_pair`'s coupling formula,
3908+/// `sbr_hf`, and per-channel plane threading -- none change this probe's
3909+/// numbers.
3910+///
3911+/// ROOT CAUSE (this round): NOT a channel swap. The free lag search
3912+/// (`best_lag_correlation_wide`) is provably unreliable on this file's
3913+/// periodic content -- it even mis-searches ref L vs ref R against each
3914+/// other (lag=-24 corr=0.213, worse than the naive fixed lag=0's
3915+/// corr=0.873) -- so ch0-vs-L and ch0-vs-R land on two DIFFERENT,
3916+/// independently-searched lags (-4617 and -4674) instead of one true
3917+/// lag, faking a "ch0 correlates with R" swap signature. At the single
3918+/// fixed lag that actually maximizes the summed (mono) ch0+ch1-vs-refL+R
3919+/// correlation (-4674, mono corr 0.778), a per-1-second sub-window
3920+/// breakdown of corr(ch0,refL) vs corr(ch0,refR) shows ch0 starts
3921+/// NEAR-PERFECT against ref L (0.998 at t=0s) and *drifts* down to 0.68
3922+/// by t=9s while its correlation with ref R rises from 0.90 to ~0.99 over
3923+/// the same span -- a clean, monotonic crossover, not a step change. That
3924+/// is the signature of accumulating CLOCK/SAMPLE-COUNT DRIFT between our
3925+/// decode and ffmpeg's reference decode (a single global lag can't track
3926+/// a linearly growing offset), not a channel identity swap: ch0 IS L,
3927+/// decoded correctly, and a single fixed-lag window increasingly
3928+/// misaligns as the file plays, which -- because ref L and ref R are
3929+/// themselves correlated (0.873 at lag 0) -- coincidentally starts to
3930+/// look R-shaped as drift accumulates. See the fixed-lag matrix and
3931+/// per-1s subwindow prints below for the numbers, and the `assert!` for
3932+/// the swap-shaped-result gate this round adds.
38843933 #[test]
38853934 fn coupled_cpe_channel_swap_probe() {
38863935 if !have_ffmpeg() {
@@ -3895,13 +3944,19 @@ fn coupled_cpe_channel_swap_probe() {
38953944 eprintln!("SKIP: {} absent", path.display());
38963945 return;
38973946 }
3898- let Some((ours, sbr, _rate)) = our_decode(&path, 0) else {
3947+ let Some((ours, sbr, out_rate)) = our_decode(&path, 0) else {
38993948 panic!("heaac_44100_48k failed to decode");
39003949 };
39013950 assert_eq!(sbr, ec_aac::SbrSupport::V1);
39023951 assert_eq!(ours.len(), 2, "expect stereo");
39033952 let ref_l = ffmpeg_decode_pan_channel(&path, 0, 0);
39043953 let ref_r = ffmpeg_decode_pan_channel(&path, 0, 1);
3954+ {
3955+ let n = ref_l.len().min(ref_r.len()).min(WINDOW);
3956+ println!("ref L vs ref R (no lag): corr={:.6}", correlation(&ref_l[..n], &ref_r[..n]));
3957+ let (lag, corr) = best_lag_correlation_wide(&ref_l, &ref_r, SEARCH_LAG_MAX);
3958+ println!("ref L vs ref R (best lag search): lag={lag} corr={corr:.6}");
3959+ }
39053960 for (och, ochan) in ours.iter().enumerate() {
39063961 let (lag_l, corr_l) = best_lag_correlation_wide(ochan, &ref_l, SEARCH_LAG_MAX);
39073962 let (lag_r, corr_r) = best_lag_correlation_wide(ochan, &ref_r, SEARCH_LAG_MAX);
@@ -3920,10 +3975,28 @@ fn coupled_cpe_channel_swap_probe() {
39203975 core_cfg.extension_sample_rate = None;
39213976 let mut core_dec = AacDecoder::with_config(core_cfg);
39223977 let mut core_planes: Vec<Vec<f32>> = vec![Vec::new(), Vec::new()];
3923- for au in &aus {
3978+ let dump = std::env::var("EC_AAC_SBR_PREQMF_DUMP").is_ok();
3979+ for (au_idx, au) in aus.iter().enumerate() {
39243980 if let Ok(f) = core_dec.decode(au, None) {
39253981 let ch = usize::from(f.channels);
39263982 if ch == 2 {
3983+ if dump && au_idx < 20 {
3984+ for c in 0..2 {
3985+ let plane: Vec<f32> =
3986+ f.samples.iter().skip(c).step_by(2).copied().collect();
3987+ let rms = (plane
3988+ .iter()
3989+ .map(|v| f64::from(*v) * f64::from(*v))
3990+ .sum::<f64>()
3991+ / plane.len().max(1) as f64)
3992+ .sqrt();
3993+ eprintln!(
3994+ "COREAU n={au_idx} ch={c} len={} rms={rms:.6} first8={:?}",
3995+ plane.len(),
3996+ &plane[..8.min(plane.len())]
3997+ );
3998+ }
3999+ }
39274000 for (i, v) in f.samples.iter().enumerate() {
39284001 core_planes[i % 2].push(*v);
39294002 }
@@ -3942,4 +4015,129 @@ fn coupled_cpe_channel_swap_probe() {
39424015 println!("core ch{och} vs ref {name}: lag={lag} corr={corr:.6}");
39434016 }
39444017 }
4018+
4019+ // Fixed-lag matrix: is the "swap" a lag-search artifact on periodic
4020+ // content, or a real decode defect? A genuine per-channel swap must
4021+ // show LOW corr(ch0,refL) and HIGH corr(ch0,refR) at the SAME lag that
4022+ // maximizes the mono (ch0+ch1 vs refL+refR) correlation, not just at
4023+ // whatever lag each pair's own FREE search happened to land on
4024+ // independently (ref L vs ref R themselves correlate 0.87 at lag 0, so
4025+ // at any single lag corr(ch0,L) and corr(ch0,R) must already be close).
4026+ let (core_lag0, core_corr0) =
4027+ best_lag_correlation_wide(&core_planes[0], &ref_core[0], SEARCH_LAG_MAX);
4028+ let core_implied_lag = core_lag0 * 2;
4029+ println!("core ch0 vs ref L best lag={core_lag0} corr={core_corr0:.6} -> implied full-rate lag={core_implied_lag}");
4030+ let mono_ours: Vec<f32> = ours[0].iter().zip(&ours[1]).map(|(a, b)| a + b).collect();
4031+ let mono_ref: Vec<f32> = {
4032+ let n = ref_l.len().min(ref_r.len());
4033+ ref_l[..n].iter().zip(&ref_r[..n]).map(|(a, b)| a + b).collect()
4034+ };
4035+ let (mono_lag, mono_corr) = best_lag_correlation_wide(&mono_ours, &mono_ref, SEARCH_LAG_MAX);
4036+ println!("mono (ch0+ch1) vs ref (L+R) best lag={mono_lag} corr={mono_corr:.6}");
4037+ let fixed_lags: [(i64, &str); 4] = [
4038+ (-4674, "swap-probe ch0-vs-refR lag"),
4039+ (-4617, "swap-probe ch0-vs-refL lag"),
4040+ (core_implied_lag, "core-implied lag"),
4041+ (mono_lag, "mono-best lag"),
4042+ ];
4043+ // `best_lag_correlation_wide`'s coarse-then-refine search is proven
4044+ // unreliable on this file's periodic content -- it even mis-picks ref L
4045+ // vs ref R itself (lag=-24 corr=0.213, worse than the naive lag-0
4046+ // corr=0.873 above). So the TRUE best lag among our 4 candidates is
4047+ // whichever one actually maximizes the fixed-lag mono correlation, not
4048+ // whatever `mono_lag` the free search reported.
4049+ let mut true_best = (mono_lag, "mono-best lag (free search)", 0.0f64, 0.0f64, 0.0f64, 0.0f64, mono_corr);
4050+ for (lag, label) in fixed_lags {
4051+ let c0l = correlation_at_lag(&ours[0], &ref_l, lag);
4052+ let c0r = correlation_at_lag(&ours[0], &ref_r, lag);
4053+ let c1l = correlation_at_lag(&ours[1], &ref_l, lag);
4054+ let c1r = correlation_at_lag(&ours[1], &ref_r, lag);
4055+ let mono = correlation_at_lag(&mono_ours, &mono_ref, lag);
4056+ println!(
4057+ "fixed lag={lag} ({label}): corr(ch0,L)={c0l:.6} corr(ch0,R)={c0r:.6} corr(ch1,L)={c1l:.6} corr(ch1,R)={c1r:.6} mono={mono:.6}"
4058+ );
4059+ if mono > true_best.6 {
4060+ true_best = (lag, label, c0l, c0r, c1l, c1r, mono);
4061+ }
4062+ }
4063+ let (best_lag, best_label, best_c0l, best_c0r, _best_c1l, _best_c1r, best_mono) = true_best;
4064+ println!(
4065+ "TRUE best-by-fixed-mono lag={best_lag} ({best_label}): corr(ch0,L)={best_c0l:.6} corr(ch0,R)={best_c0r:.6} mono={best_mono:.6}"
4066+ );
4067+ // Assert on the fixed-lag result, not the free search: a genuine
4068+ // per-channel swap needs corr(ch0,L) LOW while corr(ch0,R) is HIGH at
4069+ // this properly-determined lag. It isn't -- ch0's correlation with L
4070+ // (0.78) sits at/below the L-vs-R baseline cross-correlation
4071+ // (ref L vs ref R = 0.873 at lag 0), i.e. no more affinity to L than
4072+ // any R-channel content already has from L/R being correlated to begin
4073+ // with -- so this is a lag-search artifact on periodic content, not a
4074+ // channel swap.
4075+ assert!(
4076+ !(best_c0l < 0.3 && best_c0r > 0.9),
4077+ "swap-shaped result at the properly-determined lag {best_lag}: corr(ch0,L)={best_c0l:.6} corr(ch0,R)={best_c0r:.6}"
4078+ );
4079+ // Per-1-s-window corr(ch0,refL) at the TRUE best lag: uniform vs
4080+ // dipping tells apart "genuinely swapped everywhere" from "a
4081+ // coarse-search artifact confined to a periodic stretch".
4082+ {
4083+ let step = out_rate.max(1) as usize;
4084+ let (oa0, ob0) = if best_lag >= 0 {
4085+ (0usize, mono_lag as usize)
4086+ } else {
4087+ ((-best_lag) as usize, 0usize)
4088+ };
4089+ let mut w = 0usize;
4090+ loop {
4091+ let oa = oa0 + w * step;
4092+ let ob = ob0 + w * step;
4093+ if oa + step > ours[0].len() || ob + step > ref_l.len().min(ref_r.len()) {
4094+ break;
4095+ }
4096+ let cl = correlation(&ours[0][oa..oa + step], &ref_l[ob..ob + step]);
4097+ let cr = correlation(&ours[0][oa..oa + step], &ref_r[ob..ob + step]);
4098+ println!("subwindow t={w}s ch0 vs ref L/R @ lag {best_lag}: corr(L)={cl:.6} corr(R)={cr:.6}");
4099+ w += 1;
4100+ }
4101+ }
4102+
4103+ // Isolated round trip: run `core_planes` (the CORE-ONLY decode, already
4104+ // shown correctly-directed above) through a bare, fresh
4105+ // Analysis(32)->zero-stuff-HF->Synthesis(64) pair -- no sbr_chain, no
4106+ // per-AU/per-tag HashMap element lookup, no envelope/HF/noise code at
4107+ // all -- to see whether the swap reproduces on the QMF math alone in a
4108+ // single continuous stream, isolating it from any per-AU state
4109+ // threading in `sbr_chain::apply_data`.
4110+ use ec_aac::sbr_qmf::{ANALYSIS_BANDS as AB, Analysis, SYNTHESIS_BANDS as SB, Synthesis};
4111+ const OUTPUT_SCALE: f32 = 1.0 / 65536.0;
4112+ for kx in [6usize, 12, 20] {
4113+ let mut iso_out: [Vec<f32>; 2] = [Vec::new(), Vec::new()];
4114+ for (c, chan) in core_planes.iter().enumerate() {
4115+ let mut analysis = Analysis::new();
4116+ let mut synthesis = Synthesis::new();
4117+ let n_slots = chan.len() / AB;
4118+ for slot in 0..n_slots {
4119+ let mut chunk = [0f32; 32];
4120+ chunk.copy_from_slice(&chan[slot * AB..(slot + 1) * AB]);
4121+ for s in &mut chunk {
4122+ *s /= OUTPUT_SCALE;
4123+ }
4124+ let sub = analysis.process_slot(&chunk);
4125+ let mut v = [ec_dsp::Complex::new(0.0, 0.0); 64];
4126+ v[0..kx.min(AB)].copy_from_slice(&sub[0..kx.min(AB)]);
4127+ let mut pcm = synthesis.process_slot(&v);
4128+ for s in &mut pcm {
4129+ *s *= OUTPUT_SCALE;
4130+ }
4131+ iso_out[c].extend_from_slice(&pcm);
4132+ }
4133+ let _ = SB;
4134+ }
4135+ for (och, ochan) in iso_out.iter().enumerate() {
4136+ for (rch, rplane) in [&ref_l, &ref_r].iter().enumerate() {
4137+ let (lag, corr) = best_lag_correlation_wide(ochan, rplane, SEARCH_LAG_MAX);
4138+ let name = if rch == 0 { "L" } else { "R" };
4139+ println!("iso kx={kx} ch{och} vs ref {name}: lag={lag} corr={corr:.6}");
4140+ }
4141+ }
4142+ }
39454143 }