diff --git a/crates/ec-aac/src/lib.rs b/crates/ec-aac/src/lib.rs index cba422c5..3239d955 100644 --- a/crates/ec-aac/src/lib.rs +++ b/crates/ec-aac/src/lib.rs @@ -48,6 +48,10 @@ pub use config::{ pub use decode::{FRAME_LEN, WindowSequence}; pub use ec_core::{Error, Result}; pub use encode::{AacEncoder, AacEncoderConfig, EncodedPacket, WindowShape}; +/// Diagnostic only (round-17 Task 1 conviction check): reads back the +/// per-absolute-QMF-band transmitted signal/noise energy sums +/// `EC_AAC_SBR_NOISE_FRACTION_DEBUG` accumulates during decode. +pub use sbr_env::noise_fraction_table; pub use tables::SAMPLE_RATES; use decode::BlockDecoder; diff --git a/crates/ec-aac/src/sbr_env.rs b/crates/ec-aac/src/sbr_env.rs index 8dfeb862..2c73ba24 100644 --- a/crates/ec-aac/src/sbr_env.rs +++ b/crates/ec-aac/src/sbr_env.rs @@ -144,6 +144,48 @@ impl NoiseGen { const LIMITER_FACTOR: [f64; 4] = [1.4125, 2.0, 4.0, 1.0e6]; // 1.5/3/6 dB, "no limit" +/// (Round-17, Task 1 conviction check) Accumulates transmitted signal vs. +/// noise energy per absolute QMF band across every [`adjust`] call in the +/// process, weighted by how many QMF slots each contributes, when +/// `EC_AAC_SBR_NOISE_FRACTION_DEBUG` is set. [`noise_fraction_table`] reads +/// it back; both are no-ops (empty table) otherwise, so this costs nothing +/// on the normal path. +static NOISE_FRACTION_STATS: std::sync::OnceLock>> = + std::sync::OnceLock::new(); + +fn noise_fraction_debug() -> bool { + std::env::var("EC_AAC_SBR_NOISE_FRACTION_DEBUG").is_ok() +} + +/// `(band, signal_energy_sum, noise_energy_sum)` for every band that +/// accumulated anything, both sums slot-count-weighted. +pub fn noise_fraction_table() -> Vec<(usize, f64, f64)> { + let Some(stats) = NOISE_FRACTION_STATS.get() else { + return Vec::new(); + }; + stats + .lock() + .unwrap() + .iter() + .enumerate() + .filter(|&(_, &(s, n))| s + n > 0.0) + .map(|(b, &(s, n))| (b, s, n)) + .collect() +} + +fn accumulate_noise_fraction(band: usize, slots: usize, signal: f64, noise: f64) { + if slots == 0 { + return; + } + let stats = NOISE_FRACTION_STATS.get_or_init(|| std::sync::Mutex::new(vec![(0.0, 0.0); 256])); + let mut g = stats.lock().unwrap(); + if band >= g.len() { + g.resize(band + 1, (0.0, 0.0)); + } + g[band].0 += signal * slots as f64; + g[band].1 += noise * slots as f64; +} + /// Applies envelope adjustment in place to `hf` (`[target band 0-based /// from kx][slot]`, as [`crate::sbr_hf::generate`] returns it): gain /// toward `env_energy`, the transmitted noise floor from `noise_energy`, @@ -160,6 +202,13 @@ pub fn adjust( ) { let kx = tables.kx as usize; let limiter_max = LIMITER_FACTOR[usize::from(header.limiter_gains).min(3)]; + let track_fraction = noise_fraction_debug(); + // (Round-17, Task 1 corroboration) zeroes our injected noise so the + // sweep's measured correlation can be checked against the + // signal-only ceiling `noise_fraction_table` predicts, without + // touching the transmitted noise ENERGY bookkeeping above (only the + // actual PCM addition is skipped). + let zero_noise = std::env::var("EC_AAC_SBR_NOISE_ZERO").is_ok(); // Gain toward the transmitted envelope, per (envelope, band) cell, // limited relative to that cell's own noise floor. @@ -224,6 +273,15 @@ pub fn adjust( gain = gain.min(limiter_max * ((noise_here + cur) / cur).sqrt()); gain = gain.min(limiter_max * 64.0); // absolute ceiling: never amplify a silent cell to infinity gains.push(gain); + if track_fraction { + let slots = (t1.max(0) - t0.max(0)).max(0) as usize; + for band in lo..hi { + if band < kx { + continue; + } + accumulate_noise_fraction(band, slots, target, 0.0); + } + } } // `bs_interpol_freq` (per-subband linear interpolation of these sfb // gains, Sec 4.6.18.7.6) was tried here: a centre-frequency lerp @@ -307,13 +365,23 @@ pub fn adjust( let hi = tables.f_noise[q + 1] as usize; let energy = noise_energy[ni].get(q).copied().unwrap_or(0.0); let amp = (energy / (hi - lo).max(1) as f64).sqrt(); + if track_fraction { + let slots = (t1.max(0) - t0.max(0)).max(0) as usize; + for band in lo..hi { + if band < kx { + continue; + } + accumulate_noise_fraction(band, slots, 0.0, amp * amp); + } + } for band in lo..hi { if band < kx || band - kx >= hf.len() { continue; } let row = &mut hf[band - kx]; for slot in t0.max(0) as usize..(t1.max(0) as usize).min(row.len()) { - row[slot] = row[slot] + rng.complex_unit().scale(amp); + let n = rng.complex_unit().scale(amp); + row[slot] = row[slot] + if zero_noise { Complex::ZERO } else { n }; } } } diff --git a/crates/ec-aac/tests/sbr_real_library.rs b/crates/ec-aac/tests/sbr_real_library.rs index e1f46475..806fec26 100644 --- a/crates/ec-aac/tests/sbr_real_library.rs +++ b/crates/ec-aac/tests/sbr_real_library.rs @@ -791,6 +791,31 @@ fn sbr_real_library_matches_reference() { } else { 0.0 }; + if ch == 0 && std::env::var("EC_AAC_SBR_NOISE_FRACTION_DEBUG").is_ok() { + // (Round-17, Task 1) the noise-energy-fraction ceiling + // hypothesis: predicted per-band correlation ceiling + // sqrt(1 - noise_energy/(signal_energy+noise_energy)), + // from OUR OWN transmitted (dequantized) envelope/noise + // split -- printed once per file so it can be eyeballed + // against per_band_lag_search's measured |corr| curve + // below. Real QMF band width in output Hz is + // `rate/128` (64-band synthesis over the output Nyquist). + let band_hz = f64::from(rate) / 128.0; + println!( + " NOISE-FRACTION ceiling prediction (band_hz, f_noise, predicted_ceiling):" + ); + for (band, signal, noise) in ec_aac::noise_fraction_table() { + if signal + noise <= 0.0 { + continue; + } + let f = noise / (signal + noise); + println!( + " {:>6.0}Hz band{band:>3}: signal {signal:.3e} noise {noise:.3e} f_noise {f:.6} ceiling {:.4}", + band as f64 * band_hz, + (1.0 - f).max(0.0).sqrt() + ); + } + } if std::env::var("EC_AAC_SBR_BANDS").is_ok() && n >= 4_096 { let spectrum = per_band_correlation(&o[oa..oa + n], &t[ob..ob + n], rate); println!(" ch{ch} per-QMF-band |corr| (band_hz, |corr|, band_index):");