forge
Explore
Log in

Don't you dare go Hollow

diag(aac-sbr): root-cause a real-file HE-AAC v1 decorrelation to the SBR QMF chain, not the LC core

Browse files at this commit

87b805ddf2c7e64c2cb59f3acdc6d4575810f1f3Ahmet Kaan GümüşParent: fee35a8
Round-51 triage on a real-file HE-AAC v1 stereo commentary track (24kHz
core / 48kHz SBR, kx=27/k2=59 -- a materially wider low-band crossover than
the other tracked real file's 22.05k/44.1k kx=14/k2=43 family):

- ASC hand-parsed and cross-checked against parse_audio_specific_config's
  bit-for-bit walk: object=AAC-LC, sf_index=6 (24000), channel_config=2,
  backward-compatible SBR sync extension (0x2B7) correctly found,
  extensionAudioObjectType=5, extensionSamplingFrequencyIndex=3 (48000).
  Config parsing is correct; TRIAGE item 1 (mis-parsed ASC / rate family)
  is refuted.

- New `core_only_matches_reference` test (SBR forced off at the
  AudioSpecificConfig level, so decode.rs's FIL branch never touches
  sbr_chain at all): this track's LC core alone correlates
  0.999977/0.999974 against the reference decoder at the core rate. The
  LC core is not the defect.

- New `wide_lag_search_full_chain` test: the full SBR-reconstructed output
  finds no usable alignment against the reference anywhere in a +-4.16s
  window (vs. the normal +-4000-sample LAG_MAX) -- this is not a missed
  alignment lag, the content itself has decorrelated.

- New `full_chain_low_band_matches_own_core` test: compares our own
  full-chain output against our own core-only decode of the SAME stream,
  no reference decoder involved. The 22.05k-family file's self-consistency
  is 0.99. This 24k-family file's self-consistency is -0.02/0.01 -- the
  SBR chain does not even reproduce its own untouched low-band passthrough
  (`v[0..kx]`, a literal copy of the same core analysis data) once it
  goes through the SBR QMF chain.

- EC_AAC_SBR_HF_BYPASS=1 (new, sbr_chain.rs, default off): skips filling
  v[kx..k2] from the HF generator entirely. This file's self-consistency
  is UNCHANGED (-0.02/0.01) with HF fully bypassed, while the other
  file's improves slightly (0.99->0.99) as expected from removing HF
  leakage. This refutes the entire HF-generation/envelope-adjust/noise
  axis (the subject of every prior round's dead-ends) as this file's
  cause: the defect survives with the HF generator entirely out of the
  loop.

Conviction: the break is in the SBR chain's QMF analysis->synthesis
round-trip itself (sbr_qmf.rs Analysis/Synthesis, or the raw-band copy
feeding it) for this kx/k2 (near-32, wide-crossover) configuration, not in
HF generation, not in the LC core, and not in reference alignment/test
methodology. A rate-independent constant-delay hypothesis was also
checked and refuted (this file does not correlate at the other file's own-
core delay of -897 samples either). No fix in this diff -- root-cause
LOCATION only; see ledger for the next round's starting point.

cargo test -p ec-aac --lib: 50/50 green. fmt clean. clippy -D warnings clean.
crates/ec-aac/src/sbr_chain.rsmodified+2 -0
@@ -383,11 +383,13 @@ impl SbrChain {
383 for slot in 0..num_slots {383 for slot in 0..num_slots {
384 let mut v = [Complex::ZERO; SYNTHESIS_BANDS];384 let mut v = [Complex::ZERO; SYNTHESIS_BANDS];
385 v[0..kx].copy_from_slice(&raw[slot][0..kx]);385 v[0..kx].copy_from_slice(&raw[slot][0..kx]);
386+ if std::env::var("EC_AAC_SBR_HF_BYPASS").is_err() {
386 for b in kx..k2 {387 for b in kx..k2 {
387 if b - kx < hf.len() {388 if b - kx < hf.len() {
388 v[b] = hf[b - kx][slot];389 v[b] = hf[b - kx][slot];
389 }390 }
390 }391 }
392+ }
391 let mut pcm = state.synthesis.process_slot(&v);393 let mut pcm = state.synthesis.process_slot(&v);
392 for s in &mut pcm {394 for s in &mut pcm {
393 *s *= crate::decode::OUTPUT_SCALE;395 *s *= crate::decode::OUTPUT_SCALE;
crates/ec-aac/tests/sbr_real_library.rsmodified+244 -1
@@ -11,7 +11,7 @@ use std::io::{BufReader, Read};
11 use std::path::{Path, PathBuf};11 use std::path::{Path, PathBuf};
12 use std::process::Command;12 use std::process::Command;
13 13
14-use ec_aac::AacDecoder;14+use ec_aac::{AacDecoder, parse_audio_specific_config};
15 use ec_core::{CodecId, Demuxer, Packet};15 use ec_core::{CodecId, Demuxer, Packet};
16 use ec_matroska::MatroskaDemuxer;16 use ec_matroska::MatroskaDemuxer;
17 use ec_mp4::Mp4Demuxer;17 use ec_mp4::Mp4Demuxer;
@@ -1864,6 +1864,249 @@ fn residual_sideinfo_analysis(o: &[f32], t: &[f32], oa: usize, ob: usize, rate:
1864 );1864 );
1865 }1865 }
1866 1866
1867+/// Decodes one stream's core (AAC-LC) layer only, with SBR forced off at the
1868+/// `AudioSpecificConfig` level -- `sbr_present: false` never arms
1869+/// `BlockDecoder::sbr`, so `decode.rs`'s FIL-element branch never calls into
1870+/// `sbr_chain` at all and `out` (the raw core `channel_stream` decode) is
1871+/// handed back untouched, at the core rate. This isolates whether a
1872+/// real-file break lives in the LC core or in the SBR chain bolted onto it.
1873+fn our_decode_core_only(path: &Path, stream_index: usize) -> Option<(Vec<Vec<f32>>, u32)> {
1874+ let (asc, aus) = extract_aac_track(path, stream_index)?;
1875+ let mut cfg = parse_audio_specific_config(&asc).ok()?;
1876+ cfg.sbr_present = false;
1877+ cfg.ps_present = false;
1878+ cfg.extension_sample_rate = None;
1879+ let core_rate = cfg.sample_rate;
1880+ let mut decoder = AacDecoder::with_config(cfg);
1881+ let mut planes: Vec<Vec<f32>> = Vec::new();
1882+ for au in &aus {
1883+ let Ok(frame) = decoder.decode(au, None) else {
1884+ continue;
1885+ };
1886+ let ch = usize::from(frame.channels);
1887+ if ch == 0 {
1888+ continue;
1889+ }
1890+ if planes.is_empty() {
1891+ planes = vec![Vec::new(); ch];
1892+ }
1893+ for (i, v) in frame.samples.iter().enumerate() {
1894+ planes[i % ch].push(*v);
1895+ }
1896+ if planes[0].len() >= MAX_SAMPLES {
1897+ break;
1898+ }
1899+ }
1900+ if planes.is_empty() {
1901+ return None;
1902+ }
1903+ Some((planes, core_rate))
1904+}
1905+
1906+/// The reference decoder's decode of `absolute_stream`, resampled to
1907+/// `target_rate` -- used to compare against `our_decode_core_only`'s
1908+/// core-rate PCM directly instead of at the doubled SBR rate.
1909+fn ffmpeg_decode_at_rate(
1910+ path: &Path,
1911+ absolute_stream: usize,
1912+ channels: usize,
1913+ target_rate: u32,
1914+) -> Vec<Vec<f32>> {
1915+ let out = Command::new("ffmpeg")
1916+ .args(["-v", "error", "-i"])
1917+ .arg(path)
1918+ .args([
1919+ "-map",
1920+ &format!("0:{absolute_stream}"),
1921+ "-t",
1922+ "30",
1923+ "-ar",
1924+ &target_rate.to_string(),
1925+ "-f",
1926+ "f32le",
1927+ "-acodec",
1928+ "pcm_f32le",
1929+ "-",
1930+ ])
1931+ .output()
1932+ .expect("ffmpeg runs");
1933+ assert!(
1934+ out.status.success(),
1935+ "ffmpeg decode failed: {}",
1936+ String::from_utf8_lossy(&out.stderr)
1937+ );
1938+ let samples: Vec<f32> = out
1939+ .stdout
1940+ .chunks_exact(4)
1941+ .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
1942+ .collect();
1943+ let mut planes = vec![Vec::with_capacity(samples.len() / channels.max(1)); channels];
1944+ for (i, &v) in samples.iter().enumerate() {
1945+ planes[i % channels].push(v);
1946+ }
1947+ planes
1948+}
1949+
1950+/// Root-cause triage (round-51): is a real file's SBR-chain break actually
1951+/// downstream of a broken LC core, or does the core decode cleanly and the
1952+/// break lives only in the SBR chain layered on top of it? Prints a
1953+/// core-rate correlation per channel; not asserted on, this is a diagnostic,
1954+/// not a regression gate (the asserted gate is
1955+/// `sbr_real_library_matches_reference`, which already covers the full-band
1956+/// SBR-reconstructed output).
1957+#[test]
1958+fn core_only_matches_reference() {
1959+ if !have_ffmpeg() {
1960+ eprintln!("SKIP: ffmpeg not on PATH");
1961+ return;
1962+ }
1963+ for c in &candidates() {
1964+ let Some((ours, core_rate)) = our_decode_core_only(&c.path, c.aac_stream) else {
1965+ eprintln!("SKIP {}: could not core-decode", c.path.display());
1966+ continue;
1967+ };
1968+ let theirs = ffmpeg_decode_at_rate(&c.path, c.ffmpeg_stream, ours.len(), core_rate);
1969+ println!(
1970+ "{} core-only ({} ch, {} Hz):",
1971+ c.path.display(),
1972+ ours.len(),
1973+ core_rate
1974+ );
1975+ for (ch, (o, t)) in ours.iter().zip(&theirs).enumerate() {
1976+ let (lag, corr) = best_lag_correlation(o, t);
1977+ println!(" ch{ch}: lag {lag}, corr {corr:.6}");
1978+ }
1979+ }
1980+}
1981+
1982+/// Round-51 triage: dumps `kx`/`k2` (the SBR crossover/top band) for the
1983+/// first several frames of every candidate, unconditionally (no ffmpeg
1984+/// needed) -- a wrong `kx` would corrupt bands BELOW the crossover too, not
1985+/// just the HF-generated ones, since `adjust()` gain-scales everything from
1986+/// `kx` up, and `kx` computed too low would pull real core content into
1987+/// that scaling.
1988+#[test]
1989+fn dump_sideinfo_kx() {
1990+ unsafe {
1991+ std::env::set_var("EC_AAC_SBR_SIDEINFO_DEBUG", "1");
1992+ }
1993+ for c in &candidates() {
1994+ let Some((asc, aus)) = extract_aac_track(&c.path, c.aac_stream) else {
1995+ continue;
1996+ };
1997+ let Ok(mut decoder) = AacDecoder::with_config_bytes(&asc) else {
1998+ continue;
1999+ };
2000+ let before = ec_aac::sbr_sideinfo_log().len();
2001+ for au in aus.iter().take(50) {
2002+ let _ = decoder.decode(au, None);
2003+ }
2004+ let rows = ec_aac::sbr_sideinfo_log();
2005+ println!("{}:", c.path.display());
2006+ for row in rows[before..].iter().filter(|r| r.ch == 0).take(6) {
2007+ println!(
2008+ " frame={} source={} kx={} k2={} t_env={:?} f_high={:?}",
2009+ row.frame, row.source, row.kx, row.k2, row.t_env, row.f_high
2010+ );
2011+ }
2012+ }
2013+}
2014+
2015+/// Round-51 triage: FMJ's full-chain best-lag search (`LAG_MAX` = 4000)
2016+/// finds no usable alignment (|corr| ~0.02) even though the core-only
2017+/// decode matches almost exactly -- this widens the search far past
2018+/// `LAG_MAX` to see whether the true alignment just lies outside the normal
2019+/// bound (a large, rate-family-specific extra delay) rather than the SBR
2020+/// content itself being wrong.
2021+#[test]
2022+fn wide_lag_search_full_chain() {
2023+ if !have_ffmpeg() {
2024+ eprintln!("SKIP: ffmpeg not on PATH");
2025+ return;
2026+ }
2027+ for c in &candidates() {
2028+ let Some((ours, sbr, rate)) = our_decode(&c.path, c.aac_stream) else {
2029+ continue;
2030+ };
2031+ if sbr != ec_aac::SbrSupport::V1 {
2032+ continue;
2033+ }
2034+ let theirs = ffmpeg_decode(&c.path, c.ffmpeg_stream, ours.len());
2035+ let o = &ours[0];
2036+ let t = &theirs[0];
2037+ println!(
2038+ "{} ({} Hz): ours len={} theirs len={}",
2039+ c.path.display(),
2040+ rate,
2041+ o.len(),
2042+ t.len()
2043+ );
2044+ const COARSE: usize = 4096;
2045+ const WIDE_LAG_MAX: i64 = 200_000;
2046+ let mut best = (0i64, -1.0f64);
2047+ let mut lag = -WIDE_LAG_MAX;
2048+ while lag <= WIDE_LAG_MAX {
2049+ let (oa, ob) = if lag >= 0 {
2050+ (0usize, lag as usize)
2051+ } else {
2052+ ((-lag) as usize, 0usize)
2053+ };
2054+ if oa + COARSE <= o.len() && ob + COARSE <= t.len() {
2055+ let c = correlation(&o[oa..oa + COARSE], &t[ob..ob + COARSE]).abs();
2056+ if c > best.1 {
2057+ best = (lag, c);
2058+ }
2059+ }
2060+ lag += 97; // odd stride so it doesn't alias against 2048-sample AU boundaries
2061+ }
2062+ println!(" widest coarse best: lag={} |corr|={:.4}", best.0, best.1);
2063+ }
2064+}
2065+
2066+/// Round-51 triage: compares OUR full-chain (SBR-reconstructed) output's
2067+/// low band directly against OUR OWN core-only decode of the same stream --
2068+/// no reference decoder involved. `v[0..kx]` in `sbr_chain.rs` is a literal
2069+/// copy of the same core analysis QMF data the core-only path also
2070+/// produces, so if the synthesis/gain-adjust stage is corrupting even that
2071+/// untouched region, this shows a real self-inconsistency with no external
2072+/// factor (alignment against a reference, different tool, etc.) to blame.
2073+#[test]
2074+fn full_chain_low_band_matches_own_core() {
2075+ for c in &candidates() {
2076+ let Some((core, core_rate)) = our_decode_core_only(&c.path, c.aac_stream) else {
2077+ continue;
2078+ };
2079+ let Some((full, sbr, full_rate)) = our_decode(&c.path, c.aac_stream) else {
2080+ continue;
2081+ };
2082+ if sbr != ec_aac::SbrSupport::V1 {
2083+ continue;
2084+ }
2085+ println!(
2086+ "{} (core {} Hz, full {} Hz):",
2087+ c.path.display(),
2088+ core_rate,
2089+ full_rate
2090+ );
2091+ for ch in 0..core.len().min(full.len()) {
2092+ // Naive nearest-neighbor 2x upsample of the core so it lines up
2093+ // sample-for-sample with the full-chain output's rate --
2094+ // crude, but a low-pass well below the core Nyquist erases the
2095+ // stairstep artifacts this introduces.
2096+ let up: Vec<f32> = core[ch].iter().flat_map(|&s| [s, s]).collect();
2097+ let cutoff = f64::from(core_rate) * 0.4;
2098+ let ol = lowpass(&full[ch], full_rate, cutoff);
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)
2105+ );
2106+ }
2107+ }
2108+}
2109+
1867 fn candidates() -> Vec<Candidate> {2110 fn candidates() -> Vec<Candidate> {
1868 let home = std::env::var("HOME").unwrap_or_default();2111 let home = std::env::var("HOME").unwrap_or_default();
1869 [2112 [