forge
Explore
Log in

Don't you dare go Hollow

Noise-floor dequant is a signal-relative ratio, not an absolute energy

Browse files at this commit

5537faef9372cf2a408d76c68ac705dc7162b654Ahmet Kaan GümüşParent: 6fea6db
  • fix
    • noise-floor dequant is a signal-relative ratio, not an absolute energy
Show full message
fix(aac-sbr): noise-floor dequant is a signal-relative ratio, not an absolute energy

Round-21 Task 1: a reference-decoder probe (scripts/aac-tables/sbrnoise.py)
sweeping the noise-floor raw value q_q at a fixed envelope target shows
total HF-band output power staying nearly flat across the whole q_q range,
not scaling additively with dequant_noise(q_q) as our own decoder assumed.
That's the signature of the envelope target being split
signal=target/(1+Q_div), noise=target*Q_div/(1+Q_div) with
Q_div=dequant_noise(q_q), not noise added independently on top of the full
target. adjust() now computes that split per (envelope, band) cell and
injects noise there directly, replacing the old separate noise-grid pass
that treated dequant_noise's return value as a standalone absolute energy
comparable to dequant_env's unrelated unit scale.

On the real-file bar (reeln) this moves correlation only slightly
(ch0 0.9726->0.9732, ch1 0.9705->0.9716): real transmitted q_q values
apparently keep Q_div small regardless of interpretation, so the
noise-floor circularity hypothesis still doesn't explain this file's HF
correlation gap -- but the fix itself is now unit-consistent with the
measured reference behavior and is kept as a correctness fix.
crates/ec-aac/src/sbr_env.rsmodified+59 -49
@@ -29,10 +29,14 @@
29 //! # Gain, limiter, noise, sinusoids29 //! # Gain, limiter, noise, sinusoids
30 //!30 //!
31 //! For every `(envelope, band)` cell this measures the HF estimate's own31 //! For every `(envelope, band)` cell this measures the HF estimate's own
32-//! average energy over that time/frequency window and scales it toward32+//! average energy over that time/frequency window; the cell's envelope
33-//! the transmitted target; the limiter then caps how far above the33+//! target is split into a signal share and a noise share via the cell's
34-//! band's own transmitted noise floor that gain is allowed to reach34+//! `Q_div = dequant_noise(q_q)` ratio (`signal = target/(1+Q_div)`,
35-//! (`bs_limiter_gains`), noise is mixed in at the transmitted floor, and35+//! `noise = target*Q_div/(1+Q_div)`, round-21 -- `Q_div` is a ratio
36+//! relative to the envelope target, not a standalone absolute energy), the
37+//! HF estimate is scaled toward the signal share, the limiter caps how far
38+//! above the cell's own noise floor that gain is allowed to reach
39+//! (`bs_limiter_gains`), the noise share is mixed in at that level, and
36 //! flagged bands get an added tone.40 //! flagged bands get an added tone.
37 #![allow(clippy::needless_range_loop)]41 #![allow(clippy::needless_range_loop)]
38 42
@@ -55,7 +59,13 @@ pub fn dequant_env(e_q: i32, amp_res: u8) -> f64 {
55 2f64.powf(alpha(amp_res) * f64::from(e_q))59 2f64.powf(alpha(amp_res) * f64::from(e_q))
56 }60 }
57 61
58-/// Plain noise-floor dequantization.62+/// Plain noise-floor dequantization: `Q_div = 2^(NOISE_FLOOR_OFFSET-q_q)`, a
63+/// ratio relative to the ENVELOPE energy of the same (time, band) cell, not
64+/// an absolute energy on its own (round-21: `adjust` splits each cell's
65+/// envelope target into `signal = target/(1+Q_div)` and
66+/// `noise = target*Q_div/(1+Q_div)`; using this return value as a
67+/// standalone absolute energy, as pre-round-21 code did, compares it
68+/// against `dequant_env`'s unrelated unit scale).
59 pub fn dequant_noise(q_q: i32) -> f64 {69 pub fn dequant_noise(q_q: i32) -> f64 {
60 2f64.powf(NOISE_FLOOR_OFFSET - f64::from(q_q))70 2f64.powf(NOISE_FLOOR_OFFSET - f64::from(q_q))
61 }71 }
@@ -236,6 +246,11 @@ pub fn adjust(
236 // frequencies) so both application modes share the exact same gain246 // frequencies) so both application modes share the exact same gain
237 // values.247 // values.
238 let mut gains = Vec::with_capacity(table.len().saturating_sub(1));248 let mut gains = Vec::with_capacity(table.len().saturating_sub(1));
249+ // (Round-21) Actual per-cell noise energy this envelope/band injects,
250+ // parallel to `gains` -- filled below and consumed by the
251+ // application loop that follows instead of the old separate
252+ // noise-grid pass (see round-21 module doc note).
253+ let mut noise_amps = Vec::with_capacity(table.len().saturating_sub(1));
239 for b in 0..table.len().saturating_sub(1) {254 for b in 0..table.len().saturating_sub(1) {
240 let lo = table[b] as usize;255 let lo = table[b] as usize;
241 let hi = table[b + 1] as usize;256 let hi = table[b + 1] as usize;
@@ -252,12 +267,27 @@ pub fn adjust(
252 }267 }
253 }268 }
254 let current = if count > 0 { sum / count as f64 } else { 0.0 };269 let current = if count > 0 { sum / count as f64 } else { 0.0 };
255- let mut gain = (target / current.max(1e-12)).sqrt();
256 let q = noise_band_for(tables, lo);270 let q = noise_band_for(tables, lo);
257- let noise_here = noise_row271+ // `dequant_noise` returns `Q_div = 2^(NOISE_FLOOR_OFFSET-q_q)`, a
272+ // ratio relative to this cell's OWN envelope target -- not an
273+ // absolute energy in the same units as `target` (round-21 Task
274+ // 1/2: a reference-decoder q_q sweep at a FIXED envelope target
275+ // showed total output power staying nearly flat as q_q swept its
276+ // whole range, the signature of `target` being split
277+ // `signal=target/(1+Q_div)`, `noise=target*Q_div/(1+Q_div)`
278+ // rather than noise being added independently on top of the full
279+ // target -- the previous code used `dequant_noise` as an
280+ // absolute energy standalone, which for real content's near-1e-7
281+ // apparent "fraction" (round-17) was actually comparing two
282+ // energies in unrelated unit scales, not a genuinely near-zero
283+ // noise contribution).
284+ let noise_div = noise_row
258 .and_then(|r| r.get(q).copied())285 .and_then(|r| r.get(q).copied())
259 .unwrap_or(0.0)286 .unwrap_or(0.0)
260- .max(1e-12);287+ .max(0.0);
288+ let signal_target = target / (1.0 + noise_div);
289+ let noise_here = target - signal_target; // = target*noise_div/(1+noise_div)
290+ let mut gain = (signal_target / current.max(1e-12)).sqrt();
261 // Cap gain at `limiter_max` times the cell's own291 // Cap gain at `limiter_max` times the cell's own
262 // noise-plus-signal headroom over its raw HF estimate (Sec292 // noise-plus-signal headroom over its raw HF estimate (Sec
263 // 4.6.18.7.5's `limGain * sqrt((Q_M+E_curr)/E_curr)` shape): a293 // 4.6.18.7.5's `limGain * sqrt((Q_M+E_curr)/E_curr)` shape): a
@@ -273,13 +303,14 @@ pub fn adjust(
273 gain = gain.min(limiter_max * ((noise_here + cur) / cur).sqrt());303 gain = gain.min(limiter_max * ((noise_here + cur) / cur).sqrt());
274 gain = gain.min(limiter_max * 64.0); // absolute ceiling: never amplify a silent cell to infinity304 gain = gain.min(limiter_max * 64.0); // absolute ceiling: never amplify a silent cell to infinity
275 gains.push(gain);305 gains.push(gain);
306+ noise_amps.push((noise_here / (hi - lo).max(1) as f64).sqrt());
276 if track_fraction {307 if track_fraction {
277 let slots = (t1.max(0) - t0.max(0)).max(0) as usize;308 let slots = (t1.max(0) - t0.max(0)).max(0) as usize;
278 for band in lo..hi {309 for band in lo..hi {
279 if band < kx {310 if band < kx {
280 continue;311 continue;
281 }312 }
282- accumulate_noise_fraction(band, slots, target, 0.0);313+ accumulate_noise_fraction(band, slots, signal_target, noise_here);
283 }314 }
284 }315 }
285 }316 }
@@ -300,6 +331,7 @@ pub fn adjust(
300 let lo = table[b] as usize;331 let lo = table[b] as usize;
301 let hi = table[b + 1] as usize;332 let hi = table[b + 1] as usize;
302 let gain = gains[b];333 let gain = gains[b];
334+ let namp = noise_amps[b];
303 for band in lo..hi {335 for band in lo..hi {
304 if band < kx || band - kx >= hf.len() {336 if band < kx || band - kx >= hf.len() {
305 continue;337 continue;
@@ -307,6 +339,11 @@ pub fn adjust(
307 let row = &mut hf[band - kx];339 let row = &mut hf[band - kx];
308 for slot in t0.max(0) as usize..(t1.max(0) as usize).min(row.len()) {340 for slot in t0.max(0) as usize..(t1.max(0) as usize).min(row.len()) {
309 row[slot] = row[slot].scale(gain);341 row[slot] = row[slot].scale(gain);
342+ // Consume the RNG unconditionally (matches the pre-round-21
343+ // stream shape) even under EC_AAC_SBR_NOISE_ZERO, which
344+ // only skips the PCM addition, not the bookkeeping.
345+ let n = rng.complex_unit().scale(namp);
346+ row[slot] = row[slot] + if zero_noise { Complex::ZERO } else { n };
310 }347 }
311 }348 }
312 }349 }
@@ -347,45 +384,14 @@ pub fn adjust(
347 }384 }
348 }385 }
349 386
350- // Noise floor last: every target bin gets the transmitted floor for its387+ // (Round-21) Noise is now injected inside the envelope-gain loop above,
351- // noise-time-segment and noise-frequency-band, independent of the388+ // per (envelope, band) cell using each cell's own `signal_target`/
352- // envelope grid (they are different, coarser grids over the same axes).389+ // `noise_here` split -- the noise grid is coarser than the envelope
353- // This must run after the envelope-gain loop above -- gain is computed390+ // grid but every envelope cell resolves its own noise band via
354- // from the HF-signal-only estimate and must not also rescale the noise391+ // `noise_band_for`/`noise_row`, so this covers the same ground the old
355- // that lands on top of it (injecting noise first made the gain step392+ // separate noise-grid pass did, consistently with the gain that was
356- // measure signal+noise together and rescale both, which distorts the393+ // computed for the same cell (previously the two were split across
357- // noise/signal split by however much noise dominates a given cell -- a394+ // unrelated unit scales; see the comment at `noise_div` above).
358- // content- and channel-dependent error, not a uniform scale bug).
359- for (ni, (t0, t1)) in ch.t_noise.windows(2).map(|w| (w[0], w[1])).enumerate() {
360- if ni >= noise_energy.len() {
361- break;
362- }
363- for q in 0..tables.n_q {
364- let lo = tables.f_noise[q] as usize;
365- let hi = tables.f_noise[q + 1] as usize;
366- let energy = noise_energy[ni].get(q).copied().unwrap_or(0.0);
367- let amp = (energy / (hi - lo).max(1) as f64).sqrt();
368- if track_fraction {
369- let slots = (t1.max(0) - t0.max(0)).max(0) as usize;
370- for band in lo..hi {
371- if band < kx {
372- continue;
373- }
374- accumulate_noise_fraction(band, slots, 0.0, amp * amp);
375- }
376- }
377- for band in lo..hi {
378- if band < kx || band - kx >= hf.len() {
379- continue;
380- }
381- let row = &mut hf[band - kx];
382- for slot in t0.max(0) as usize..(t1.max(0) as usize).min(row.len()) {
383- let n = rng.complex_unit().scale(amp);
384- row[slot] = row[slot] + if zero_noise { Complex::ZERO } else { n };
385- }
386- }
387- }
388- }
389 }395 }
390 396
391 fn noise_band_for(tables: &BandTables, low_band: usize) -> usize {397 fn noise_band_for(tables: &BandTables, low_band: usize) -> usize {
@@ -499,7 +505,11 @@ mod tests {
499 add_harmonic: None,505 add_harmonic: None,
500 };506 };
501 let env_energy = vec![vec![1.0e6f64; tables.n_low]];507 let env_energy = vec![vec![1.0e6f64; tables.n_low]];
502- let noise_energy = vec![vec![1e-3f64; tables.n_q]];508+ // (Round-21) noise_energy is now a Q_div ratio against the cell's
509+ // own envelope target, not a standalone absolute energy -- zero
510+ // keeps this test focused on the signal-gain limiter it names, not
511+ // noise injection.
512+ let noise_energy = vec![vec![0.0f64; tables.n_q]];
503 let mut rng = NoiseGen::new(1);513 let mut rng = NoiseGen::new(1);
504 adjust(514 adjust(
505 &mut hf,515 &mut hf,
scripts/aac-tables/sbrnoise.pyadded+111 -0
@@ -0,0 +1,111 @@
1+#!/usr/bin/env python3
2+"""Black-box measurement of the reference decoder's SBR noise-floor
3+dequantization law (round-21 Task 1).
4+
5+Method: reuse `sbrchirp.py`'s repaired probe shape (SCE, FIXFIX num_env=2,
6+amp_res=1, broadband comb core so the HF-signal envelope target is fixed
7+and non-zero), fix the envelope raw value, and sweep only the noise-floor
8+raw value `q_q` (`noise0`) across its 5-bit range. Noise is spec-additive
9+on top of the gain-adjusted HF signal (module doc in sbr_env.rs), so the
10+total power measured in the target band at each `q_q` is
11+`signal_energy(fixed) + noise_energy(q_q)`; subtracting the high-`q_q`
12+(minimal-noise) baseline isolates `noise_energy(q_q)` and its shape can be
13+fit against `q_q` directly, independent of our own decoder.
14+"""
15+import os
16+import sys
17+
18+import numpy as np
19+
20+HERE = os.path.dirname(os.path.abspath(__file__))
21+sys.path.insert(0, HERE)
22+
23+import sbrchirp as C
24+import sbrpayload_fixtures as F
25+
26+RATE = C.RATE
27+
28+
29+def noise_stream(cfg, tables, n_frames, q, env=40):
30+ """Like `sbrchirp.stream()` but `bs_invf_mode` held at NONE (0, so the
31+ injected noise is not reshaped by the inverse filter) and `noise0`
32+ swept to `[q, q]` instead of `bs_invf_mode`; `env` is the fixed
33+ envelope raw value."""
34+ grid = dict(frame_class=0, num_env=2, freq_res=0)
35+ frames = [C.P.silent(C.SF_INDEX)]
36+ for _ in range(n_frames):
37+ c = dict(cfg, invf=0, header=1, amp_res=1, element="sce", coupling=0,
38+ df_env=[0] * 8, df_noise=[0, 0], env0=[env] * 8, noise0=[q, q])
39+ w = C.P.BitW()
40+ C.broadband_core_bits(w)
41+ body = F.sbr_bits_full(c, tables, grid, [])
42+ w.w(6, 3)
43+ cnt = (len(body.bits) + 4 + 7) // 8
44+ if cnt >= 15:
45+ w.w(15, 4)
46+ w.w(cnt - 15 + 1, 8)
47+ else:
48+ w.w(cnt, 4)
49+ start = len(w)
50+ w.w(13, 4)
51+ w.wbits(body.bits)
52+ while len(w) - start < cnt * 8:
53+ w.w(0, 1)
54+ w.w(7, 3)
55+ frames.append(C.P.adts(w.pack(pad=0), C.SF_INDEX))
56+ frames.append(C.P.silent(C.SF_INDEX))
57+ return frames
58+
59+
60+def band_power(pcm, lo_hz, hi_hz, skip=6, n_fft=8192):
61+ start = skip * 1024
62+ seg = pcm[start : start + n_fft]
63+ if len(seg) < n_fft:
64+ seg = np.pad(seg, (0, n_fft - len(seg)))
65+ spec = np.abs(np.fft.rfft(seg * np.hanning(len(seg)))) ** 2
66+ freqs = np.fft.rfftfreq(n_fft, 1 / RATE)
67+ mask = (freqs >= lo_hz) & (freqs < hi_hz)
68+ return float(np.sum(spec[mask]))
69+
70+
71+if __name__ == "__main__":
72+ cfg0, tables0 = F.one_band_header()
73+ lo, hi = 19 * RATE / 128, 23 * RATE / 128
74+ print(f"target region {lo:.1f}-{hi:.1f} Hz, RAW_NOISE bits={C.T.RAW_NOISE} (q range 0..{2**C.T.RAW_NOISE - 1})")
75+
76+ print("\n== value-engagement check: envelope raw sweep (fixed q_q) must move power by orders ==")
77+ for e in (10, 40, 60):
78+ cfg = dict(cfg0)
79+ frames = noise_stream(cfg, tables0, 20, 30, env=e)
80+ pcm, err = C.decode(frames, f"env_check{e}")
81+ pwr = band_power(pcm, lo, hi)
82+ print(f" env0={e} (q_q=30, minimal noise) pwr={pwr:.4e} err={err.strip()[:60]!r}")
83+
84+ print("\n== Task 1: noise-floor raw (q_q) sweep, fixed envelope ==")
85+ qs = list(range(0, 31, 3))
86+ pwrs = {}
87+ for q in qs:
88+ cfg = dict(cfg0)
89+ frames = noise_stream(cfg, tables0, 20, q)
90+ pcm, err = C.decode(frames, f"q{q}")
91+ pwr = band_power(pcm, lo, hi)
92+ pwrs[q] = pwr
93+ print(f" q_q={q:2d} pwr={pwr:.6e} err={err.strip()[:80]!r}")
94+
95+ baseline = pwrs[qs[-1]]
96+ print(f"\nbaseline (q_q={qs[-1]}, minimal noise) pwr={baseline:.6e}")
97+ print("q_q, noise_energy=pwr-baseline, log2(noise_energy)")
98+ fit_x, fit_y = [], []
99+ for q in qs[:-1]:
100+ n = pwrs[q] - baseline
101+ if n > 0:
102+ l2 = np.log2(n)
103+ print(f" {q:2d} {n:.6e} {l2:.4f}")
104+ fit_x.append(q)
105+ fit_y.append(l2)
106+ else:
107+ print(f" {q:2d} {n:.6e} (non-positive, skipped)")
108+ if len(fit_x) >= 2:
109+ slope, intercept = np.polyfit(fit_x, fit_y, 1)
110+ print(f"\nfit: log2(noise_energy) = {slope:.4f} * q_q + {intercept:.4f}")
111+ print(f"(spec/ours form: log2(noise_energy) = -1*q_q + 6 => slope~-1, intercept~6 expected if law matches)")