forge
Explore
Log in

Don't you dare go Hollow

Correct the QMF in-band measurement bug, box-car the injected noise draw

Browse files at this commit

3b6045472f1a7f952a53728418e1f8f4f41e6b4bAhmet Kaan GümüşParent: 30721a2
  • fix
    • correct the QMF in-band measurement bug, box-car the injected noise draw
Show full message
fix(sbr): correct the QMF in-band measurement bug, box-car the injected noise draw

sbr_qmf's synthesis_energy_gain_for_white_noise_excitation measured its
in-band FFT window at k0/SYNTHESIS_BANDS; band k's passband is actually
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 alias image, not
the signal -- the round-43 "~0% in-band survival" reading was this bug,
not a Synthesis defect. Corrected, a raw i.i.d.-per-slot draw already
lands ~0.49 of its own energy in-band; a 2-slot boxcar (sbr_env::NoiseGen)
raises that to ~0.61 while staying noise-like (spread across the band,
not a residual tone).

Re-measuring the real-file whole-HF realized noise fraction after
shipping the boxcar shows it barely moves (0.1787 -> 0.1770): that metric
sums energy across the whole swept HF spectrum, and energy an i.i.d. draw
aliases to a neighbouring QMF band still lands inside that same sweep, so
it was never actually excluded. The ~0.38 bookkept vs ~0.18 actual gap is
therefore a genuine energy shortfall plus a content defect (measured
coherence sits well below even the actual-fraction ceiling), not the
noise-sequence-shape problem round-43 diagnosed. Tightens
sbr_actual_noise_fraction's regression floor from 0.15 to 0.17, the level
both before and after this fix.
crates/ec-aac/src/sbr_env.rsmodified+53 -5
@@ -139,15 +139,40 @@ pub fn dequantize_frame(
139 /// A small deterministic PRNG for the injected noise floor -- the same139 /// A small deterministic PRNG for the injected noise floor -- the same
140 /// generator shape `decode::Noise` uses, kept local so this module has no140 /// generator shape `decode::Noise` uses, kept local so this module has no
141 /// dependency on the core decoder's internals.141 /// dependency on the core decoder's internals.
142-pub struct NoiseGen(u32);142+pub struct NoiseGen {
143+ lcg: u32,
144+ // (Round-44, Task 1/2) The last `LOWPASS_TAPS - 1` raw (pre-scale) draws,
145+ // oldest first -- `complex_unit` boxcar-averages the current draw against
146+ // these before scaling, so consecutive calls (one QMF slot apart, same
147+ // band -- see `adjust`'s band-outer/slot-inner loop) are correlated
148+ // instead of independent.
149+ history: std::collections::VecDeque<Complex<f64>>,
150+}
151+
152+/// (Round-44, Task 1) `sbr_qmf::Synthesis`'s prototype passband is HALF the
153+/// decimated slot-rate Nyquist a per-slot i.i.d. draw spans (see
154+/// `sbr_qmf.rs`'s module doc and `synthesis_energy_gain_for_...` harness):
155+/// an unfiltered draw already survives Synthesis' overlap-add reasonably
156+/// (in-band fraction ~0.49 of a 20000-slot excitation, once the harness's own
157+/// band-index math was corrected -- see round-44 ledger), but a short boxcar
158+/// across consecutive slots pulls more of that draw's own spectral energy
159+/// into the passband without collapsing it into a near-tone (a wider boxcar
160+/// keeps raising in-band fraction but concentrates it into the passband's
161+/// own DC edge, losing the noise-like spread across the band the acceptance
162+/// bar requires -- taps=2 was the harness's best fraction/spread balance:
163+/// 0.6083 in-band, quarter-bin energy spread [0.257,0.293,0.251,0.199]).
164+const LOWPASS_TAPS: usize = 2;
143 165
144 impl NoiseGen {166 impl NoiseGen {
145 pub fn new(seed: u32) -> NoiseGen {167 pub fn new(seed: u32) -> NoiseGen {
146- NoiseGen(seed | 1)168+ NoiseGen {
169+ lcg: seed | 1,
170+ history: std::collections::VecDeque::with_capacity(LOWPASS_TAPS),
171+ }
147 }172 }
148 173
149 fn next(&mut self) -> f64 {174 fn next(&mut self) -> f64 {
150- self.0 = self.0.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);175+ self.lcg = self.lcg.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
151 // (Round-41, Task 2) `self.0 >> 8` keeps 24 bits (range [0, 2^24));176 // (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 of177 // 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 on178 // [0, 2) before the `- 0.5`, i.e. actual output was uniform on
@@ -158,7 +183,7 @@ impl NoiseGen {
158 // constant for its own divisor. Dividing by `1u32 << 24` instead183 // constant for its own divisor. Dividing by `1u32 << 24` instead
159 // fixes the range to [0, 1) so `- 0.5` correctly centers it on184 // fixes the range to [0, 1) so `- 0.5` correctly centers it on
160 // [-0.5, 0.5), mean 0.185 // [-0.5, 0.5), mean 0.
161- f64::from(self.0 >> 8) / f64::from(1u32 << 24) - 0.5186+ f64::from(self.lcg >> 8) / f64::from(1u32 << 24) - 0.5
162 }187 }
163 188
164 fn complex_unit(&mut self) -> Complex<f64> {189 fn complex_unit(&mut self) -> Complex<f64> {
@@ -173,8 +198,31 @@ impl NoiseGen {
173 // in `tests/sbr_real_library.rs`'s `sbr_actual_noise_fraction`):198 // in `tests/sbr_real_library.rs`'s `sbr_actual_noise_fraction`):
174 // bookkept split ~0.37-0.39, actual realized only ~0.10-0.30 in-band199 // bookkept split ~0.37-0.39, actual realized only ~0.10-0.30 in-band
175 // (whole-HF-weighted ~0.095) before this fix.200 // (whole-HF-weighted ~0.095) before this fix.
201+ //
202+ // (Round-44, Task 2) The raw i.i.d. draw is boxcar-averaged over the
203+ // last `LOWPASS_TAPS` calls (see the constant's own doc) before this
204+ // scale: a boxcar of `taps` independent Uniform(-0.5,0.5) draws has
205+ // per-component variance `(1/12)/taps`, `taps`-fold smaller than a
206+ // single draw's, so the unit-energy scale grows by `sqrt(taps)` on
207+ // top of the original `sqrt(6)` to still land at E[|z|^2] = 1 -- this
208+ // is a SHAPE change (which spectral slice of the subband's own
209+ // baseband the energy sits in), not an energy change; the boxcar's
210+ // first `taps - 1` calls average fewer draws than nominal (history
211+ // still filling), a startup transient too short to matter against a
212+ // whole envelope segment's slot count.
176 const UNIT_SCALE: f64 = 2.449_489_742_783_178; // sqrt(6)213 const UNIT_SCALE: f64 = 2.449_489_742_783_178; // sqrt(6)
177- Complex::new(self.next(), self.next()).scale(UNIT_SCALE)214+ let lowpass_scale: f64 = UNIT_SCALE * (LOWPASS_TAPS as f64).sqrt();
215+ let raw = Complex::new(self.next(), self.next());
216+ self.history.push_back(raw);
217+ if self.history.len() > LOWPASS_TAPS {
218+ self.history.pop_front();
219+ }
220+ let n = self.history.len() as f64;
221+ let sum = self
222+ .history
223+ .iter()
224+ .fold(Complex::new(0.0, 0.0), |a, &b| a + b);
225+ sum.scale(lowpass_scale / n)
178 }226 }
179 }227 }
180 228
crates/ec-aac/src/sbr_qmf.rsmodified+118 -2
@@ -996,8 +996,14 @@ mod tests {
996 let mut spectrum = vec![ec_dsp::Complex::new(0.0f32, 0.0); bins];996 let mut spectrum = vec![ec_dsp::Complex::new(0.0f32, 0.0); bins];
997 let mut in_band = 0.0f64;997 let mut in_band = 0.0f64;
998 let mut total = 0.0f64;998 let mut total = 0.0f64;
999- let band_lo = (k0 as f64 / SYNTHESIS_BANDS as f64 * bins as f64) as usize;999+ // Band k's passband is centred at `(k+0.5)*omega_step` with
1000- let band_hi = ((k0 + 1) as f64 / SYNTHESIS_BANDS as f64 * bins as f64) as usize;1000+ // half-width `omega_step` (the prototype's own lowpass cutoff, see
1001+ // the module doc), and `omega_step = pi/(2*SYNTHESIS_BANDS)` here --
1002+ // NOT `pi/SYNTHESIS_BANDS`. A frequency fraction of Nyquist (`pi`)
1003+ // is therefore `k/(2*SYNTHESIS_BANDS)` to `(k+1)/(2*SYNTHESIS_BANDS)`,
1004+ // half of what a naive `k/bands` split would give.
1005+ let band_lo = (k0 as f64 / (2.0 * SYNTHESIS_BANDS as f64) * bins as f64) as usize;
1006+ let band_hi = ((k0 + 1) as f64 / (2.0 * SYNTHESIS_BANDS as f64) * bins as f64) as usize;
1001 let win = ec_dsp::Window::<f32>::sine(FFT_LEN);1007 let win = ec_dsp::Window::<f32>::sine(FFT_LEN);
1002 let hops = (steady.len() - FFT_LEN) / FFT_LEN;1008 let hops = (steady.len() - FFT_LEN) / FFT_LEN;
1003 for h in 0..hops {1009 for h in 0..hops {
@@ -1017,4 +1023,114 @@ mod tests {
1017 in_band / total1023 in_band / total
1018 );1024 );
1019 }1025 }
1026+
1027+ /// (Round-44, Task 1, shape 1) The i.i.d.-per-slot draw above is white
1028+ /// across the SUBBAND'S OWN full baseband Nyquist (the hop rate), while
1029+ /// the prototype's own passband only covers a narrow slice of that range
1030+ /// (see the module doc: cutoff `omega_step = pi/(2*bands)`, vs. the
1031+ /// slot-domain signal's own Nyquist of `pi`). Slot-lowpassing the i.i.d.
1032+ /// draw (a short moving average across consecutive slots, independently
1033+ /// on real/imag, renormalized back to the same per-draw energy) should
1034+ /// concentrate its content inside that passband slice instead of
1035+ /// aliasing across the whole synthesis band. Swept tap count to find
1036+ /// where in-band fraction stops improving.
1037+ #[test]
1038+ fn synthesis_energy_gain_for_lowpassed_noise_excitation() {
1039+ fn xorshift(seed: u64) -> impl FnMut() -> f64 {
1040+ let mut state = seed | 1;
1041+ move || {
1042+ state ^= state << 13;
1043+ state ^= state >> 7;
1044+ state ^= state << 17;
1045+ (state >> 11) as f64 / (1u64 << 53) as f64 - 0.5
1046+ }
1047+ }
1048+ let k0 = SYNTHESIS_BANDS / 2;
1049+ let slots = 20_000usize;
1050+
1051+ for taps in [2usize, 3, 4, 6, 8, 12, 16, 24, 32] {
1052+ let mut rng = xorshift(0xdead_beef);
1053+ let raw: Vec<Complex<f64>> = (0..slots).map(|_| Complex::new(rng(), rng())).collect();
1054+
1055+ // Moving-average lowpass across the slot index, then renormalize
1056+ // each output draw back to the raw draws' own mean energy so the
1057+ // comparison isolates the SHAPE change, not an energy change.
1058+ let raw_energy: f64 = raw.iter().map(|c| c.norm_sqr()).sum::<f64>() / slots as f64;
1059+ let mut lp = vec![Complex::new(0.0, 0.0); slots];
1060+ for (i, out) in lp.iter_mut().enumerate() {
1061+ let lo = i.saturating_sub(taps - 1);
1062+ let mut re = 0.0;
1063+ let mut im = 0.0;
1064+ let mut n = 0.0;
1065+ for c in &raw[lo..=i] {
1066+ re += c.re;
1067+ im += c.im;
1068+ n += 1.0;
1069+ }
1070+ *out = Complex::new(re / n, im / n);
1071+ }
1072+ let lp_energy: f64 = lp.iter().map(|c| c.norm_sqr()).sum::<f64>() / slots as f64;
1073+ let scale = (raw_energy / lp_energy).sqrt();
1074+
1075+ let mut synthesis = Synthesis::new();
1076+ let mut in_energy = 0.0f64;
1077+ let mut out = Vec::with_capacity(slots * SYNTHESIS_BANDS);
1078+ for &c0 in &lp {
1079+ let c = c0.scale(scale);
1080+ let mut v = [Complex::new(0.0, 0.0); SYNTHESIS_BANDS];
1081+ v[k0] = c;
1082+ in_energy += c.norm_sqr();
1083+ out.extend(synthesis.process_slot(&v));
1084+ }
1085+ let steady = &out[out.len() / 2..];
1086+ let mut out_energy = 0.0f64;
1087+ for &s in steady {
1088+ out_energy += f64::from(s) * f64::from(s);
1089+ }
1090+ let steady_slots = steady.len() / SYNTHESIS_BANDS;
1091+ let steady_in_energy = in_energy * steady_slots as f64 / slots as f64;
1092+ let energy_gain = out_energy / steady_in_energy;
1093+
1094+ const FFT_LEN: usize = 2048;
1095+ let mut rfft = ec_dsp::RealFft::<f32>::new(FFT_LEN);
1096+ let bins = rfft.spectrum_len();
1097+ let mut spectrum = vec![ec_dsp::Complex::new(0.0f32, 0.0); bins];
1098+ let mut in_band = 0.0f64;
1099+ let mut total = 0.0f64;
1100+ let band_lo = (k0 as f64 / (2.0 * SYNTHESIS_BANDS as f64) * bins as f64) as usize;
1101+ let band_hi = ((k0 + 1) as f64 / (2.0 * SYNTHESIS_BANDS as f64) * bins as f64) as usize;
1102+ // Also bucket the in-band bins into quarters, to check the
1103+ // surviving content is spread across the band (noise-like), not
1104+ // piled into one edge (which would look more like a residual
1105+ // tone than usable noise).
1106+ let quarter = (band_hi - band_lo).max(4) / 4;
1107+ let mut quarters = [0.0f64; 4];
1108+ let win = ec_dsp::Window::<f32>::sine(FFT_LEN);
1109+ let hops = (steady.len() - FFT_LEN) / FFT_LEN;
1110+ for h in 0..hops {
1111+ let mut block = steady[h * FFT_LEN..h * FFT_LEN + FFT_LEN].to_vec();
1112+ win.apply(&mut block);
1113+ rfft.forward(&block, &mut spectrum);
1114+ for (i, c) in spectrum.iter().enumerate() {
1115+ let e = f64::from(c.norm_sqr());
1116+ total += e;
1117+ if i >= band_lo && i < band_hi {
1118+ in_band += e;
1119+ let q = ((i - band_lo) / quarter.max(1)).min(3);
1120+ quarters[q] += e;
1121+ }
1122+ }
1123+ }
1124+ let qsum: f64 = quarters.iter().sum();
1125+ println!(
1126+ "taps={taps:2}: energy gain {energy_gain:.4}, in-band fraction {:.4}, \
1127+ quarter spread [{:.3},{:.3},{:.3},{:.3}]",
1128+ in_band / total,
1129+ if qsum > 0.0 { quarters[0] / qsum } else { 0.0 },
1130+ if qsum > 0.0 { quarters[1] / qsum } else { 0.0 },
1131+ if qsum > 0.0 { quarters[2] / qsum } else { 0.0 },
1132+ if qsum > 0.0 { quarters[3] / qsum } else { 0.0 },
1133+ );
1134+ }
1135+ }
1020 }1136 }
crates/ec-aac/tests/sbr_real_library.rsmodified+37 -24
@@ -2242,31 +2242,44 @@ fn sbr_actual_noise_fraction() {
2242 // mislabeled by a factor of two, this file's true SBR band spacing is2242 // mislabeled by a factor of two, this file's true SBR band spacing is
2243 // `rate/128` = 344.5Hz not the 172.3Hz FFT-analysis spacing those Hz2243 // `rate/128` = 344.5Hz not the 172.3Hz FFT-analysis spacing those Hz
2244 // labels come from) show `adjust` injecting 40-85% noise share in the2244 // labels come from) show `adjust` injecting 40-85% noise share in the
2245- // QMF domain, at or ABOVE the ~0.37 bookkept split, not starved. The2245+ // QMF domain, at or ABOVE the ~0.37 bookkept split, not starved.
2246- // real defect is downstream, in `sbr_qmf::Synthesis`:2246+ //
2247- // `synthesis_energy_gain_for_white_noise_excitation` (round-43) drives2247+ // (Round-44) Round-43's "essentially 0% of injected energy lands back
2248- // ONE subband with an independent-per-slot random complex value (what2248+ // in the source subband" reading of
2249- // `adjust`'s noise injection actually looks like) through the same2249+ // `synthesis_energy_gain_for_white_noise_excitation` was itself a test
2250- // overlap-add prototype `synthesis_gain_is_flat_across_bands`2250+ // bug, not a `Synthesis` defect: that harness measured its in-band FFT
2251- // calibrated against a slowly-rotating TONE phasor, and finds2251+ // window at `k0/SYNTHESIS_BANDS`, but band k's passband is centred at
2252- // essentially 0% of that injected energy lands back in the source2252+ // `(k+0.5)*omega_step` with `omega_step = pi/(2*SYNTHESIS_BANDS)` --
2253- // subband's own frequency range (vs. a tone's clean in-band2253+ // HALF that fraction of Nyquist -- so the window sat on the image
2254- // reconstruction) -- an i.i.d.-per-slot draw is not a legitimate2254+ // region, not the signal. Corrected, a raw i.i.d.-per-slot draw already
2255- // "bandlimited content in this subband" input to this filterbank's2255+ // lands ~0.49 of its own energy in its home subband's own frequency
2256- // complex-modulation convention, so it aliases out almost entirely2256+ // range (not 0%), and a short slot-domain boxcar (`sbr_env::NoiseGen`'s
2257- // rather than reconstructing as audible noise near the intended2257+ // new `LOWPASS_TAPS = 2`) raises that to ~0.61 while staying spread
2258- // frequency. This is exactly the charter's Task 3 "noise SEQUENCE is2258+ // across the band (not collapsing to a residual tone) -- see the
2259- // the last mile" scenario -- fixing it needs the round-17 noise-stream2259+ // harness's `synthesis_energy_gain_for_lowpassed_noise_excitation`.
2260- // derivation (per-slot values shaped to actually decode as noise2260+ // That shape fix is real (an i.i.d. draw genuinely was less
2261- // through THIS synthesis convention), not another `adjust()` accounting2261+ // band-faithful than it needed to be, and now is not), but re-measuring
2262- // pass. Deferred: round-17 derivation, budget did not reach it this2262+ // THIS whole-HF metric after shipping it moved `actual_total` by <0.002
2263- // round (open, see ledger). This assertion remains a regression floor2263+ // (0.1787 -> 0.1770, i.e. flat) -- because this metric sums the noise
2264- // against the two round-42 accounting bugs re-appearing, not a claim of2264+ // energy DELTA across the whole swept HF spectrum, and energy an
2265- // bookkept parity -- NOT tightened, since the actual gating defect2265+ // i.i.d. draw aliased to a NEIGHBOURING QMF band still lands somewhere
2266- // (synthesis-stage noise-sequence shape) is still unfixed.2266+ // inside that same swept HF range, so it was never actually excluded
2267+ // from this particular sum. The ~0.38 bookkept vs ~0.18 actual gap is
2268+ // therefore NOT a spectral-shape/aliasing defect (refuting round-43's
2269+ // framing) -- it is a genuine energy shortfall, and per-band coherence
2270+ // sits well below even the ACTUAL-fraction ceiling
2271+ // (`sqrt(1 - f)`; ~0.15-0.20 measured vs. ~0.90 predicted at
2272+ // `f ~= 0.177`, see `EC_AAC_SBR_PARITY_SPLIT`), meaning most of the
2273+ // remaining HF correlation shortfall is a content defect independent of
2274+ // noise level. Deferred: locating that energy shortfall and the
2275+ // content defect, budget did not reach either this round (open, see
2276+ // ledger). Floor tightened from round-42's 0.15 to the level this
2277+ // fix's shape change actually lands at (0.177, both before and after),
2278+ // with margin for run-to-run FFT/decode jitter.
2267 assert!(2279 assert!(
2268- actual_total > 0.15,2280+ actual_total > 0.17,
2269 "whole-HF realized noise fraction regressed to {actual_total:.4} \2281 "whole-HF realized noise fraction regressed to {actual_total:.4} \
2270- (round-42 fix floor is 0.15; pre-fix was ~0.13, post-fix ~0.18)"2282+ (round-44 fix floor is 0.17; measured 0.1770 post-shape-fix, \
2283+ 0.1787 pre-fix -- shape does not move this metric, see doc above)"
2271 );2284 );
2272 }2285 }