forge
Explore
Log in

Don't you dare go Hollow

NoiseGen was DC-biased and under-scaled, realizing ~1/6-1/9 of the transmitted noise split

Browse files at this commit

64cc642ad8a0ad549a03574014782dc7ce16f331Ahmet Kaan GümüşParent: f6d8fb3
  • fix
    • NoiseGen was DC-biased and under-scaled, realizing ~1/6-1/9 of the transmitted noise split
Show full message
fix(aac-sbr): NoiseGen was DC-biased and under-scaled, realizing ~1/6-1/9 of the transmitted noise split

Round-41 Task 1 (instrument anchor): bin_level_conviction reads exactly
1.0 on ours-vs-ours and reference-vs-reference-through-remux, and
0.995+ up to 14.8kHz on a reference-vs-itself 64-sample-offset control
(only degrading in the near-silent >15kHz tail) -- the coherence
instrument is not the story behind reeln's ~0.15-0.25 HF readings.

Round-41 Task 2 (round-24 contradiction): measured actual injected
noise as output energy (decode twice, noise on vs EC_AAC_SBR_NOISE_ZERO,
per-band energy delta) instead of trusting either side. Two real bugs
in NoiseGen found and fixed:
  - next()'s divisor was one bit short (1<<23 instead of 1<<24), so it
    was actually uniform on [-0.5, 1.5) (mean +0.5, DC-biased) rather
    than the intended zero-mean [-0.5, 0.5).
  - complex_unit()'s two components then had E[|z|^2] = 1/6, not 1, so
    adjust()'s namp*z scaling only ever realized ~1/6 of noise_here.
Both fixed; new unit tests pin complex_unit()'s statistics directly.
Measured effect: actual/bookkept noise fraction in noise-covered bands
0.095 -> 0.171 average (bookkept ~0.38, still short -- the limiter/
boost pass's lim_e_orig accumulates the FULL envelope target while its
gain is computed from signal_target alone, a separate pre-existing
mismatch not fixed here). Round-24's "zeroing changes corr by <0.001"
was independently reproduced (0.000957, now 0.001421 post-fix) and
was never in contradiction with the bookkept split once actual
realized energy is measured directly instead of assumed equal to it.

Also gates the O(windows*4001*4096) whole-file drift search in
sbr_real_library_matches_reference behind EC_AAC_SBR_TIMELINE (was
unconditional, ~4min/channel); default path now reuses the established
global lag with no per-window search for the same mean/min summary.
crates/ec-aac/src/sbr_env.rsmodified+43 -2
@@ -148,11 +148,32 @@ impl NoiseGen {
148 148
149 fn next(&mut self) -> f64 {149 fn next(&mut self) -> f64 {
150 self.0 = self.0.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);150 self.0 = self.0.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
151- f64::from(self.0 >> 8) / f64::from(1u32 << 23) - 0.5151+ // (Round-41, Task 2) `self.0 >> 8` keeps 24 bits (range [0, 2^24));
152+ // dividing by `1u32 << 23` (2^23, ONE bit too few) left a range of
153+ // [0, 2) before the `- 0.5`, i.e. actual output was uniform on
154+ // [-0.5, 1.5) with mean +0.5 -- a DC-biased "noise" source, not
155+ // zero-mean. `decode::Noise::next` (same LCG constants) divides by
156+ // the same `1 << 23` but subtracts `1.0`, which correctly centers
157+ // ITS doubled [0,2) range; this generator subtracted the wrong
158+ // constant for its own divisor. Dividing by `1u32 << 24` instead
159+ // fixes the range to [0, 1) so `- 0.5` correctly centers it on
160+ // [-0.5, 0.5), mean 0.
161+ f64::from(self.0 >> 8) / f64::from(1u32 << 24) - 0.5
152 }162 }
153 163
154 fn complex_unit(&mut self) -> Complex<f64> {164 fn complex_unit(&mut self) -> Complex<f64> {
155- Complex::new(self.next(), self.next())165+ // (Round-41, Task 2) `next()` is uniform on [-0.5, 0.5) (Var = 1/12
166+ // per component), so a raw `(re, im)` pair has E[|z|^2] = 1/6, not
167+ // 1 -- `adjust` scales this by `namp = sqrt(noise_here/width)`
168+ // expecting E[|namp*z|^2] = noise_here, so without this correction
169+ // only ~1/6 of the transmitted noise split was ever actually
170+ // realized in the output. Measured directly (decode reeln twice,
171+ // noise on vs `EC_AAC_SBR_NOISE_ZERO`, per-band output energy delta
172+ // in `tests/sbr_real_library.rs`'s `sbr_actual_noise_fraction`):
173+ // bookkept split ~0.37-0.39, actual realized only ~0.10-0.30 in-band
174+ // (whole-HF-weighted ~0.095) before this fix.
175+ const UNIT_SCALE: f64 = 2.449_489_742_783_178; // sqrt(6)
176+ Complex::new(self.next(), self.next()).scale(UNIT_SCALE)
156 }177 }
157 }178 }
158 179
@@ -673,6 +694,26 @@ mod tests {
673 }694 }
674 }695 }
675 696
697+ /// (Round-41, Task 2) `NoiseGen::complex_unit`'s realized expected
698+ /// squared magnitude must be ~1.0 -- `adjust` scales it by
699+ /// `namp = sqrt(noise_here/width)` expecting `E[|namp*z|^2] =
700+ /// noise_here`, so anything but ~1.0 here means the injected noise
701+ /// under- or over-realizes the transmitted split regardless of the
702+ /// limiter/boost interaction (measured separately, at the whole-decode
703+ /// level, in `tests/sbr_real_library.rs`'s `sbr_actual_noise_fraction`).
704+ /// Before the `sqrt(6)` fix this read ~1/6.
705+ #[test]
706+ fn complex_unit_has_unit_expected_squared_magnitude() {
707+ let mut rng = NoiseGen::new(1);
708+ let n = 200_000;
709+ let mean_sq: f64 =
710+ (0..n).map(|_| rng.complex_unit().norm_sqr()).sum::<f64>() / f64::from(n);
711+ assert!(
712+ (mean_sq - 1.0).abs() < 0.02,
713+ "E[|complex_unit()|^2] = {mean_sq}, expected ~1.0"
714+ );
715+ }
716+
676 #[test]717 #[test]
677 fn limiter_stays_finite_on_a_uniformly_starved_band() {718 fn limiter_stays_finite_on_a_uniformly_starved_band() {
678 // (Round-33 semantics change) A UNIFORMLY near-silent HF estimate719 // (Round-33 semantics change) A UNIFORMLY near-silent HF estimate
crates/ec-aac/tests/sbr_real_library.rsmodified+253 -5
@@ -1905,15 +1905,12 @@ fn sbr_real_library_matches_reference() {
1905 // the already-established global `lag` with NO per-window1905 // the already-established global `lag` with NO per-window
1906 // search (O(windows * 4096)), which is cheap and still gives1906 // search (O(windows * 4096)), which is cheap and still gives
1907 // an honest whole-file windowed mean/min at that fixed lag.1907 // an honest whole-file windowed mean/min at that fixed lag.
1908- let timeline: Vec<(i64, f64)> =1908+ let timeline: Vec<(i64, f64)> = if std::env::var("EC_AAC_SBR_TIMELINE").is_ok() {
1909- if std::env::var("EC_AAC_SBR_TIMELINE").is_ok() {
1910 windowed_lag_drift(o, t, oa, ob, windows)1909 windowed_lag_drift(o, t, oa, ob, windows)
1911 } else {1910 } else {
1912 (0..windows)1911 (0..windows)
1913 .filter_map(|w| {1912 .filter_map(|w| {
1914- let base_o = (oa as i64 + lag + (w * 4_096) as i64)1913+ let base_o = (oa as i64 + lag + (w * 4_096) as i64).try_into().ok()?;
1915- .try_into()
1916- .ok()?;
1917 let base_t = ob + w * 4_096;1914 let base_t = ob + w * 4_096;
1918 if base_o + 4_096 > o.len() || base_t + 4_096 > t.len() {1915 if base_o + 4_096 > o.len() || base_t + 4_096 > t.len() {
1919 return None;1916 return None;
@@ -1965,3 +1962,254 @@ fn sbr_real_library_matches_reference() {
1965 "worst below-crossover correlation {worst_low:.6} < 0.9999 -- the core decode itself regressed"1962 "worst below-crossover correlation {worst_low:.6} < 0.9999 -- the core decode itself regressed"
1966 );1963 );
1967 }1964 }
1965+
1966+/// Writes `aus` (raw access units, no ADTS framing) plus `asc` (their own
1967+/// AudioSpecificConfig bytes, unmodified) into a fresh mp4 at `out_path`, so
1968+/// the reference decoder can be pointed at container-native SBR content that
1969+/// is byte-identical to the original stream's access units -- the same
1970+/// `esds`-carries-an-explicit-SBR-config shape `examples/wrap_sbr.rs` proved
1971+/// on synthetic content in round-31, reused here on a REAL file's own AUs as
1972+/// the round-41 Task 1 remux control.
1973+fn write_remux(out_path: &Path, asc: &[u8], aus: &[Vec<u8>]) {
1974+ let cfg = ec_aac::parse_audio_specific_config(asc).expect("real file's own ASC parses");
1975+ let core_rate = cfg.sample_rate;
1976+ let time_base = ec_core::TimeBase::from_rate(core_rate);
1977+ let layout = if cfg.channels == 1 {
1978+ ec_core::ChannelLayout::Mono
1979+ } else {
1980+ ec_core::ChannelLayout::Stereo
1981+ };
1982+ let mut params = ec_core::CodecParameters::new(CodecId::Aac);
1983+ params.extradata = Some(asc.to_vec().into());
1984+ params.media = ec_core::MediaParameters::Audio(ec_core::AudioParameters {
1985+ sample_rate: core_rate,
1986+ layout,
1987+ format: None,
1988+ bits_per_sample: None,
1989+ });
1990+ let mut info = ec_core::StreamInfo::new(0, time_base, params);
1991+ info.default = true;
1992+ let out = File::create(out_path).expect("remux output creatable");
1993+ let mut muxer = ec_mp4::Mp4Muxer::new(out).expect("mp4 muxer opens");
1994+ use ec_core::Muxer as _;
1995+ muxer.add_stream(info).expect("stream declared");
1996+ for (i, au) in aus.iter().enumerate() {
1997+ let pts = i as i64 * 1024;
1998+ let packet = Packet::new(0, time_base, au.as_slice())
1999+ .with_pts(pts)
2000+ .with_duration(1024);
2001+ muxer.write_packet(&packet).expect("packet written");
2002+ }
2003+ muxer.finish().expect("finished");
2004+}
2005+
2006+/// Mean/min of `bin_level_conviction`'s `direct` column, printed as one
2007+/// summary line per control pair.
2008+fn report_conviction(label: &str, rows: &[(f64, f64, f64, f64, f64, f64)]) {
2009+ if rows.is_empty() {
2010+ println!(" {label}: no HF bands measured (window too short)");
2011+ return;
2012+ }
2013+ let vals: Vec<f64> = rows.iter().map(|(_, _, direct, ..)| *direct).collect();
2014+ let mean = vals.iter().sum::<f64>() / vals.len() as f64;
2015+ let min = vals.iter().cloned().fold(f64::MAX, f64::min);
2016+ println!(
2017+ " {label}: direct-coherence mean {mean:.4} min {min:.4} over {} HF bands",
2018+ vals.len()
2019+ );
2020+ for (hz, _, direct, ..) in rows {
2021+ println!(" {hz:>6.0}Hz: direct {direct:.4}");
2022+ }
2023+}
2024+
2025+/// (Round-41, Task 1) Instrument anchor: before trusting `bin_level_conviction`'s
2026+/// low (~0.15-0.25) HF direct-coherence numbers on reeln as evidence the
2027+/// HF content is genuinely different, confirm the measurement itself reads
2028+/// near 1.0 on pairs that are KNOWN to carry the same content. Three
2029+/// controls:
2030+/// A. ours vs ours, decoded independently twice -- a determinism check on
2031+/// our own decode AND the coherence arithmetic's floor.
2032+/// B. the reference's own PCM from the original file vs from a remux of
2033+/// the SAME access units/ASC through a fresh container -- near-1.0
2034+/// expected; anything else would implicate the remux path, not SBR.
2035+/// C. the reference's own PCM vs itself read 64 samples later (one QMF
2036+/// slot) -- sanity that `bin_level_conviction`'s STFT hop/window does
2037+/// not itself destroy coherence for equivalent content at a fixed
2038+/// sample offset, the same shape of offset the real `oa`/`ob` alignment
2039+/// applies above.
2040+/// If any control reads below ~0.9 on the HF bands, the instrument -- not
2041+/// the SBR chain -- is the story; every prior round's coherence number would
2042+/// need to be recalibrated against whatever this control actually measures.
2043+#[test]
2044+fn sbr_instrument_anchor_controls() {
2045+ if std::env::var("EC_AAC_SBR_INSTRUMENT_ANCHOR").is_err() {
2046+ eprintln!("SKIP: set EC_AAC_SBR_INSTRUMENT_ANCHOR=1 to run (round-41 Task 1)");
2047+ return;
2048+ }
2049+ if !have_ffmpeg() {
2050+ eprintln!("SKIP: ffmpeg not on PATH");
2051+ return;
2052+ }
2053+ let home = std::env::var("HOME").unwrap_or_default();
2054+ let path = PathBuf::from(format!("{home}/Music/reeln.mp4"));
2055+ if !path.exists() {
2056+ eprintln!("SKIP: {} not found", path.display());
2057+ return;
2058+ }
2059+ const MIN_BAND: usize = 14;
2060+ const TOP_N: usize = 128; // larger than any real band count -- keeps every HF band
2061+
2062+ // Control A: ours vs ours, decoded independently twice.
2063+ let (ours_a, _, rate) = our_decode(&path, 0).expect("our_decode works");
2064+ let (ours_b, _, _) = our_decode(&path, 0).expect("our_decode works (2nd pass)");
2065+ let n = ours_a[0].len().min(ours_b[0].len()).min(MAX_SAMPLES);
2066+ let rows = bin_level_conviction(&ours_a[0][..n], &ours_b[0][..n], rate, MIN_BAND, TOP_N);
2067+ report_conviction("A: ours-vs-ours (determinism)", &rows);
2068+
2069+ // Control B: reference PCM from the original file vs from a remux of the
2070+ // SAME access units/ASC.
2071+ let (asc, aus) = extract_aac_track(&path, 0).expect("track extracts");
2072+ let remux_path = std::env::temp_dir().join("ec_aac_sbr_instrument_anchor_remux.mp4");
2073+ write_remux(&remux_path, &asc, &aus);
2074+ let theirs_orig = ffmpeg_decode(&path, 0, 2);
2075+ let theirs_remux = ffmpeg_decode(&remux_path, 0, 2);
2076+ let _ = std::fs::remove_file(&remux_path);
2077+ let n = theirs_orig[0]
2078+ .len()
2079+ .min(theirs_remux[0].len())
2080+ .min(MAX_SAMPLES);
2081+ let (lag_b, _) = best_lag_correlation(&theirs_orig[0][..n], &theirs_remux[0][..n]);
2082+ let (oa, ob) = if lag_b >= 0 {
2083+ (0usize, lag_b as usize)
2084+ } else {
2085+ ((-lag_b) as usize, 0usize)
2086+ };
2087+ let win = n.saturating_sub(oa.max(ob));
2088+ let rows = bin_level_conviction(
2089+ &theirs_orig[0][oa..oa + win],
2090+ &theirs_remux[0][ob..ob + win],
2091+ rate,
2092+ MIN_BAND,
2093+ TOP_N,
2094+ );
2095+ report_conviction(
2096+ &format!("B: reference-vs-reference-through-remux (lag {lag_b})"),
2097+ &rows,
2098+ );
2099+
2100+ // Control C: reference PCM vs itself read 64 samples later (one QMF
2101+ // slot) -- both slices are the SAME underlying samples, just offset.
2102+ let t = &theirs_orig[0][..MAX_SAMPLES.min(theirs_orig[0].len())];
2103+ if t.len() > 64 {
2104+ let rows = bin_level_conviction(&t[64..], &t[..t.len() - 64], rate, MIN_BAND, TOP_N);
2105+ report_conviction("C: reference vs reference, 64-sample offset", &rows);
2106+ }
2107+}
2108+
2109+/// (Round-41, Task 2) Actual injected HF noise energy, measured as OUTPUT
2110+/// energy rather than trusted from either side of round-24's contradiction:
2111+/// `noise_fraction_table` bookkept a 0.37-0.39 noise share from the
2112+/// transmitted envelope/noise split, while separately zeroing the injected
2113+/// noise (`EC_AAC_SBR_NOISE_ZERO`, which only skips the PCM addition in
2114+/// `sbr_env::adjust`, not the bookkeeping) was found to change full-band
2115+/// correlation by <0.001 -- both cannot be true of the same signal. This
2116+/// decodes reeln twice (noise on, then off) and reads the per-HF-band
2117+/// `bin_level_conviction` energy delta between them as the fraction noise
2118+/// ACTUALLY realizes in the output, independent of either prior claim.
2119+#[test]
2120+fn sbr_actual_noise_fraction() {
2121+ if std::env::var("EC_AAC_SBR_NOISE_ANCHOR").is_err() {
2122+ eprintln!("SKIP: set EC_AAC_SBR_NOISE_ANCHOR=1 to run (round-41 Task 2)");
2123+ return;
2124+ }
2125+ if !have_ffmpeg() {
2126+ eprintln!("SKIP: ffmpeg not on PATH");
2127+ return;
2128+ }
2129+ let home = std::env::var("HOME").unwrap_or_default();
2130+ let path = PathBuf::from(format!("{home}/Music/reeln.mp4"));
2131+ if !path.exists() {
2132+ eprintln!("SKIP: {} not found", path.display());
2133+ return;
2134+ }
2135+ const MIN_BAND: usize = 14;
2136+ const TOP_N: usize = 128;
2137+
2138+ // SAFETY: this test does not run concurrently with any other test that
2139+ // reads these two vars (both are `ec_aac`-internal SBR debug switches,
2140+ // not read by `sbr_real_library_matches_reference`'s own decode path
2141+ // except through this same `zero_noise`/`track_fraction` plumbing) --
2142+ // invoke this test by name, not as part of a parallel `cargo test` run.
2143+ unsafe {
2144+ std::env::remove_var("EC_AAC_SBR_NOISE_ZERO");
2145+ std::env::set_var("EC_AAC_SBR_NOISE_FRACTION_DEBUG", "1");
2146+ }
2147+ let (ours_on, _, rate) = our_decode(&path, 0).expect("our_decode works (noise on)");
2148+ let bookkept = ec_aac::noise_fraction_table();
2149+ unsafe {
2150+ std::env::remove_var("EC_AAC_SBR_NOISE_FRACTION_DEBUG");
2151+ std::env::set_var("EC_AAC_SBR_NOISE_ZERO", "1");
2152+ }
2153+ let (ours_off, _, _) = our_decode(&path, 0).expect("our_decode works (noise zeroed)");
2154+ unsafe {
2155+ std::env::remove_var("EC_AAC_SBR_NOISE_ZERO");
2156+ }
2157+
2158+ let theirs = ffmpeg_decode(&path, 0, ours_on.len());
2159+ let n = ours_on[0].len().min(ours_off[0].len()).min(MAX_SAMPLES);
2160+ let on = &ours_on[0][..n];
2161+ let off = &ours_off[0][..n];
2162+
2163+ // Per-band actual energy delta: `energy` in `bin_level_conviction`'s row
2164+ // is always the FIRST argument's own band energy, so swap argument order
2165+ // between the two calls to read both sides' energies at the SAME band
2166+ // set (TOP_N kept above any real band count so both calls select every
2167+ // band, not just each side's own top few).
2168+ let rows_on = bin_level_conviction(on, off, rate, MIN_BAND, TOP_N);
2169+ let rows_off = bin_level_conviction(off, on, rate, MIN_BAND, TOP_N);
2170+ let band_hz = f64::from(rate) / 256.0;
2171+ println!(
2172+ " ACTUAL noise fraction (band_hz, energy_on, energy_off, actual_fraction, bookkept_fraction):"
2173+ );
2174+ let mut sum_on = 0.0f64;
2175+ let mut sum_delta = 0.0f64;
2176+ for (hz, e_on, ..) in &rows_on {
2177+ let e_off = rows_off
2178+ .iter()
2179+ .find(|(hz2, ..)| (hz2 - hz).abs() < 1.0)
2180+ .map(|(_, e, ..)| *e)
2181+ .unwrap_or(0.0);
2182+ let actual = if *e_on > 0.0 {
2183+ (e_on - e_off) / e_on
2184+ } else {
2185+ 0.0
2186+ };
2187+ let band = (hz / band_hz).round() as usize;
2188+ let book = bookkept
2189+ .iter()
2190+ .find(|(b, ..)| *b == band)
2191+ .map(|(_, s, n)| if s + n > 0.0 { n / (s + n) } else { 0.0 })
2192+ .unwrap_or(0.0);
2193+ println!(
2194+ " {hz:>6.0}Hz: on {e_on:.3e} off {e_off:.3e} actual {actual:.4} bookkept {book:.4}"
2195+ );
2196+ sum_on += e_on;
2197+ sum_delta += e_on - e_off;
2198+ }
2199+ let actual_total = if sum_on > 0.0 {
2200+ sum_delta / sum_on
2201+ } else {
2202+ 0.0
2203+ };
2204+ println!(" ACTUAL whole-HF noise fraction: {actual_total:.4}");
2205+
2206+ // Corr re-verification: does zeroing the injected noise move full-band
2207+ // correlation against the reference, and by how much (round-24 claimed
2208+ // <0.001).
2209+ let (_, corr_on) = best_lag_correlation(on, &theirs[0][..theirs[0].len().min(MAX_SAMPLES)]);
2210+ let (_, corr_off) = best_lag_correlation(off, &theirs[0][..theirs[0].len().min(MAX_SAMPLES)]);
2211+ println!(
2212+ " full-band corr: noise-on {corr_on:.6} noise-off {corr_off:.6} delta {:.6}",
2213+ corr_off - corr_on
2214+ );
2215+}