diff --git a/crates/ec-aac/src/sbr_env.rs b/crates/ec-aac/src/sbr_env.rs index 3ce44fc9..51ce923a 100644 --- a/crates/ec-aac/src/sbr_env.rs +++ b/crates/ec-aac/src/sbr_env.rs @@ -139,15 +139,40 @@ pub fn dequantize_frame( /// A small deterministic PRNG for the injected noise floor -- the same /// generator shape `decode::Noise` uses, kept local so this module has no /// dependency on the core decoder's internals. -pub struct NoiseGen(u32); +pub struct NoiseGen { + lcg: u32, + // (Round-44, Task 1/2) The last `LOWPASS_TAPS - 1` raw (pre-scale) draws, + // oldest first -- `complex_unit` boxcar-averages the current draw against + // these before scaling, so consecutive calls (one QMF slot apart, same + // band -- see `adjust`'s band-outer/slot-inner loop) are correlated + // instead of independent. + history: std::collections::VecDeque>, +} + +/// (Round-44, Task 1) `sbr_qmf::Synthesis`'s prototype passband is HALF the +/// decimated slot-rate Nyquist a per-slot i.i.d. draw spans (see +/// `sbr_qmf.rs`'s module doc and `synthesis_energy_gain_for_...` harness): +/// an unfiltered draw already survives Synthesis' overlap-add reasonably +/// (in-band fraction ~0.49 of a 20000-slot excitation, once the harness's own +/// band-index math was corrected -- see round-44 ledger), but a short boxcar +/// across consecutive slots pulls more of that draw's own spectral energy +/// into the passband without collapsing it into a near-tone (a wider boxcar +/// keeps raising in-band fraction but concentrates it into the passband's +/// own DC edge, losing the noise-like spread across the band the acceptance +/// bar requires -- taps=2 was the harness's best fraction/spread balance: +/// 0.6083 in-band, quarter-bin energy spread [0.257,0.293,0.251,0.199]). +const LOWPASS_TAPS: usize = 2; impl NoiseGen { pub fn new(seed: u32) -> NoiseGen { - NoiseGen(seed | 1) + NoiseGen { + lcg: seed | 1, + history: std::collections::VecDeque::with_capacity(LOWPASS_TAPS), + } } fn next(&mut self) -> f64 { - self.0 = self.0.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + self.lcg = self.lcg.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); // (Round-41, Task 2) `self.0 >> 8` keeps 24 bits (range [0, 2^24)); // dividing by `1u32 << 23` (2^23, ONE bit too few) left a range of // [0, 2) before the `- 0.5`, i.e. actual output was uniform on @@ -158,7 +183,7 @@ impl NoiseGen { // constant for its own divisor. Dividing by `1u32 << 24` instead // fixes the range to [0, 1) so `- 0.5` correctly centers it on // [-0.5, 0.5), mean 0. - f64::from(self.0 >> 8) / f64::from(1u32 << 24) - 0.5 + f64::from(self.lcg >> 8) / f64::from(1u32 << 24) - 0.5 } fn complex_unit(&mut self) -> Complex { @@ -173,8 +198,31 @@ impl NoiseGen { // in `tests/sbr_real_library.rs`'s `sbr_actual_noise_fraction`): // bookkept split ~0.37-0.39, actual realized only ~0.10-0.30 in-band // (whole-HF-weighted ~0.095) before this fix. + // + // (Round-44, Task 2) The raw i.i.d. draw is boxcar-averaged over the + // last `LOWPASS_TAPS` calls (see the constant's own doc) before this + // scale: a boxcar of `taps` independent Uniform(-0.5,0.5) draws has + // per-component variance `(1/12)/taps`, `taps`-fold smaller than a + // single draw's, so the unit-energy scale grows by `sqrt(taps)` on + // top of the original `sqrt(6)` to still land at E[|z|^2] = 1 -- this + // is a SHAPE change (which spectral slice of the subband's own + // baseband the energy sits in), not an energy change; the boxcar's + // first `taps - 1` calls average fewer draws than nominal (history + // still filling), a startup transient too short to matter against a + // whole envelope segment's slot count. const UNIT_SCALE: f64 = 2.449_489_742_783_178; // sqrt(6) - Complex::new(self.next(), self.next()).scale(UNIT_SCALE) + let lowpass_scale: f64 = UNIT_SCALE * (LOWPASS_TAPS as f64).sqrt(); + let raw = Complex::new(self.next(), self.next()); + self.history.push_back(raw); + if self.history.len() > LOWPASS_TAPS { + self.history.pop_front(); + } + let n = self.history.len() as f64; + let sum = self + .history + .iter() + .fold(Complex::new(0.0, 0.0), |a, &b| a + b); + sum.scale(lowpass_scale / n) } } diff --git a/crates/ec-aac/src/sbr_qmf.rs b/crates/ec-aac/src/sbr_qmf.rs index be9cc51f..7223fc56 100644 --- a/crates/ec-aac/src/sbr_qmf.rs +++ b/crates/ec-aac/src/sbr_qmf.rs @@ -996,8 +996,14 @@ mod tests { let mut spectrum = vec![ec_dsp::Complex::new(0.0f32, 0.0); bins]; let mut in_band = 0.0f64; let mut total = 0.0f64; - let band_lo = (k0 as f64 / SYNTHESIS_BANDS as f64 * bins as f64) as usize; - let band_hi = ((k0 + 1) as f64 / SYNTHESIS_BANDS as f64 * bins as f64) as usize; + // Band k's passband is centred at `(k+0.5)*omega_step` with + // half-width `omega_step` (the prototype's own lowpass cutoff, see + // the module doc), and `omega_step = pi/(2*SYNTHESIS_BANDS)` here -- + // NOT `pi/SYNTHESIS_BANDS`. A frequency fraction of Nyquist (`pi`) + // is therefore `k/(2*SYNTHESIS_BANDS)` to `(k+1)/(2*SYNTHESIS_BANDS)`, + // half of what a naive `k/bands` split would give. + let band_lo = (k0 as f64 / (2.0 * SYNTHESIS_BANDS as f64) * bins as f64) as usize; + let band_hi = ((k0 + 1) as f64 / (2.0 * SYNTHESIS_BANDS as f64) * bins as f64) as usize; let win = ec_dsp::Window::::sine(FFT_LEN); let hops = (steady.len() - FFT_LEN) / FFT_LEN; for h in 0..hops { @@ -1017,4 +1023,114 @@ mod tests { in_band / total ); } + + /// (Round-44, Task 1, shape 1) The i.i.d.-per-slot draw above is white + /// across the SUBBAND'S OWN full baseband Nyquist (the hop rate), while + /// the prototype's own passband only covers a narrow slice of that range + /// (see the module doc: cutoff `omega_step = pi/(2*bands)`, vs. the + /// slot-domain signal's own Nyquist of `pi`). Slot-lowpassing the i.i.d. + /// draw (a short moving average across consecutive slots, independently + /// on real/imag, renormalized back to the same per-draw energy) should + /// concentrate its content inside that passband slice instead of + /// aliasing across the whole synthesis band. Swept tap count to find + /// where in-band fraction stops improving. + #[test] + fn synthesis_energy_gain_for_lowpassed_noise_excitation() { + fn xorshift(seed: u64) -> impl FnMut() -> f64 { + let mut state = seed | 1; + move || { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + (state >> 11) as f64 / (1u64 << 53) as f64 - 0.5 + } + } + let k0 = SYNTHESIS_BANDS / 2; + let slots = 20_000usize; + + for taps in [2usize, 3, 4, 6, 8, 12, 16, 24, 32] { + let mut rng = xorshift(0xdead_beef); + let raw: Vec> = (0..slots).map(|_| Complex::new(rng(), rng())).collect(); + + // Moving-average lowpass across the slot index, then renormalize + // each output draw back to the raw draws' own mean energy so the + // comparison isolates the SHAPE change, not an energy change. + let raw_energy: f64 = raw.iter().map(|c| c.norm_sqr()).sum::() / slots as f64; + let mut lp = vec![Complex::new(0.0, 0.0); slots]; + for (i, out) in lp.iter_mut().enumerate() { + let lo = i.saturating_sub(taps - 1); + let mut re = 0.0; + let mut im = 0.0; + let mut n = 0.0; + for c in &raw[lo..=i] { + re += c.re; + im += c.im; + n += 1.0; + } + *out = Complex::new(re / n, im / n); + } + let lp_energy: f64 = lp.iter().map(|c| c.norm_sqr()).sum::() / slots as f64; + let scale = (raw_energy / lp_energy).sqrt(); + + let mut synthesis = Synthesis::new(); + let mut in_energy = 0.0f64; + let mut out = Vec::with_capacity(slots * SYNTHESIS_BANDS); + for &c0 in &lp { + let c = c0.scale(scale); + let mut v = [Complex::new(0.0, 0.0); SYNTHESIS_BANDS]; + v[k0] = c; + in_energy += c.norm_sqr(); + out.extend(synthesis.process_slot(&v)); + } + let steady = &out[out.len() / 2..]; + let mut out_energy = 0.0f64; + for &s in steady { + out_energy += f64::from(s) * f64::from(s); + } + let steady_slots = steady.len() / SYNTHESIS_BANDS; + let steady_in_energy = in_energy * steady_slots as f64 / slots as f64; + let energy_gain = out_energy / steady_in_energy; + + const FFT_LEN: usize = 2048; + let mut rfft = ec_dsp::RealFft::::new(FFT_LEN); + let bins = rfft.spectrum_len(); + let mut spectrum = vec![ec_dsp::Complex::new(0.0f32, 0.0); bins]; + let mut in_band = 0.0f64; + let mut total = 0.0f64; + let band_lo = (k0 as f64 / (2.0 * SYNTHESIS_BANDS as f64) * bins as f64) as usize; + let band_hi = ((k0 + 1) as f64 / (2.0 * SYNTHESIS_BANDS as f64) * bins as f64) as usize; + // Also bucket the in-band bins into quarters, to check the + // surviving content is spread across the band (noise-like), not + // piled into one edge (which would look more like a residual + // tone than usable noise). + let quarter = (band_hi - band_lo).max(4) / 4; + let mut quarters = [0.0f64; 4]; + let win = ec_dsp::Window::::sine(FFT_LEN); + let hops = (steady.len() - FFT_LEN) / FFT_LEN; + for h in 0..hops { + let mut block = steady[h * FFT_LEN..h * FFT_LEN + FFT_LEN].to_vec(); + win.apply(&mut block); + rfft.forward(&block, &mut spectrum); + for (i, c) in spectrum.iter().enumerate() { + let e = f64::from(c.norm_sqr()); + total += e; + if i >= band_lo && i < band_hi { + in_band += e; + let q = ((i - band_lo) / quarter.max(1)).min(3); + quarters[q] += e; + } + } + } + let qsum: f64 = quarters.iter().sum(); + println!( + "taps={taps:2}: energy gain {energy_gain:.4}, in-band fraction {:.4}, \ + quarter spread [{:.3},{:.3},{:.3},{:.3}]", + in_band / total, + if qsum > 0.0 { quarters[0] / qsum } else { 0.0 }, + if qsum > 0.0 { quarters[1] / qsum } else { 0.0 }, + if qsum > 0.0 { quarters[2] / qsum } else { 0.0 }, + if qsum > 0.0 { quarters[3] / qsum } else { 0.0 }, + ); + } + } } diff --git a/crates/ec-aac/tests/sbr_real_library.rs b/crates/ec-aac/tests/sbr_real_library.rs index 74a4f824..d937edfc 100644 --- a/crates/ec-aac/tests/sbr_real_library.rs +++ b/crates/ec-aac/tests/sbr_real_library.rs @@ -2242,31 +2242,44 @@ fn sbr_actual_noise_fraction() { // mislabeled by a factor of two, this file's true SBR band spacing is // `rate/128` = 344.5Hz not the 172.3Hz FFT-analysis spacing those Hz // labels come from) show `adjust` injecting 40-85% noise share in the - // QMF domain, at or ABOVE the ~0.37 bookkept split, not starved. The - // real defect is downstream, in `sbr_qmf::Synthesis`: - // `synthesis_energy_gain_for_white_noise_excitation` (round-43) drives - // ONE subband with an independent-per-slot random complex value (what - // `adjust`'s noise injection actually looks like) through the same - // overlap-add prototype `synthesis_gain_is_flat_across_bands` - // calibrated against a slowly-rotating TONE phasor, and finds - // essentially 0% of that injected energy lands back in the source - // subband's own frequency range (vs. a tone's clean in-band - // reconstruction) -- an i.i.d.-per-slot draw is not a legitimate - // "bandlimited content in this subband" input to this filterbank's - // complex-modulation convention, so it aliases out almost entirely - // rather than reconstructing as audible noise near the intended - // frequency. This is exactly the charter's Task 3 "noise SEQUENCE is - // the last mile" scenario -- fixing it needs the round-17 noise-stream - // derivation (per-slot values shaped to actually decode as noise - // through THIS synthesis convention), not another `adjust()` accounting - // pass. Deferred: round-17 derivation, budget did not reach it this - // round (open, see ledger). This assertion remains a regression floor - // against the two round-42 accounting bugs re-appearing, not a claim of - // bookkept parity -- NOT tightened, since the actual gating defect - // (synthesis-stage noise-sequence shape) is still unfixed. + // QMF domain, at or ABOVE the ~0.37 bookkept split, not starved. + // + // (Round-44) Round-43's "essentially 0% of injected energy lands back + // in the source subband" reading of + // `synthesis_energy_gain_for_white_noise_excitation` was itself a test + // bug, not a `Synthesis` defect: that harness measured its in-band FFT + // window at `k0/SYNTHESIS_BANDS`, but band k's passband is centred at + // `(k+0.5)*omega_step` with `omega_step = pi/(2*SYNTHESIS_BANDS)` -- + // HALF that fraction of Nyquist -- so the window sat on the image + // region, not the signal. Corrected, a raw i.i.d.-per-slot draw already + // lands ~0.49 of its own energy in its home subband's own frequency + // range (not 0%), and a short slot-domain boxcar (`sbr_env::NoiseGen`'s + // new `LOWPASS_TAPS = 2`) raises that to ~0.61 while staying spread + // across the band (not collapsing to a residual tone) -- see the + // harness's `synthesis_energy_gain_for_lowpassed_noise_excitation`. + // That shape fix is real (an i.i.d. draw genuinely was less + // band-faithful than it needed to be, and now is not), but re-measuring + // THIS whole-HF metric after shipping it moved `actual_total` by <0.002 + // (0.1787 -> 0.1770, i.e. flat) -- because this metric sums the noise + // energy DELTA across the whole swept HF spectrum, and energy an + // i.i.d. draw aliased to a NEIGHBOURING QMF band still lands somewhere + // inside that same swept HF range, so it was never actually excluded + // from this particular sum. The ~0.38 bookkept vs ~0.18 actual gap is + // therefore NOT a spectral-shape/aliasing defect (refuting round-43's + // framing) -- it is a genuine energy shortfall, and per-band coherence + // sits well below even the ACTUAL-fraction ceiling + // (`sqrt(1 - f)`; ~0.15-0.20 measured vs. ~0.90 predicted at + // `f ~= 0.177`, see `EC_AAC_SBR_PARITY_SPLIT`), meaning most of the + // remaining HF correlation shortfall is a content defect independent of + // noise level. Deferred: locating that energy shortfall and the + // content defect, budget did not reach either this round (open, see + // ledger). Floor tightened from round-42's 0.15 to the level this + // fix's shape change actually lands at (0.177, both before and after), + // with margin for run-to-run FFT/decode jitter. assert!( - actual_total > 0.15, + actual_total > 0.17, "whole-HF realized noise fraction regressed to {actual_total:.4} \ - (round-42 fix floor is 0.15; pre-fix was ~0.13, post-fix ~0.18)" + (round-44 fix floor is 0.17; measured 0.1770 post-shape-fix, \ + 0.1787 pre-fix -- shape does not move this metric, see doc above)" ); }