forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB03dc6e9Tahinli3 months ago178 commits

sbr_env.rs1068 lines, 48.2 KiBHistoryRawDownload
1//! SBR envelope adjustment (ISO/IEC 14496-3 §4.6.18.7): scales the raw HF
2//! QMF estimate [`crate::sbr_hf::generate`] produced so each transmitted
3//! (envelope, band) cell carries the energy the encoder actually measured,
4//! injects the transmitted noise floor, and adds sinusoids at the bands
5//! `bs_add_harmonic` flags.
6//!
7//! # Dequantization
8//!
9//! A plain (non-coupled) envelope's linear energy is `2^(alpha * e_q)`
10//! with `alpha = 1.0` at `bs_amp_res = 1` (3 dB steps) and `0.5` at
11//! `bs_amp_res = 0` (1.5 dB steps); the noise floor is `2^(6 - q_q)`
12//! (`NOISE_FLOOR_OFFSET = 6`). A coupled CPE's balance channel (`e_q`'s
13//! second channel) carries a log-ratio rather than an absolute
14//! scalefactor; `dequant_pair` de-mixes it against channel 0's raw value
15//! into left/right energies that are equal (and sum to `2 * channel 0's
16//! energy`) when the ratio is centred. The ratio's exponent is
17//! `2 * alpha * balance_raw - 12`: pinned empirically (not from spec
18//! text) by writing coupled CPE payloads with known asymmetric
19//! `(channel 0 raw, balance raw)` pairs through a decodable HE-AAC
20//! stream, decoding both channels' PCM with the reference decoder, and
21//! fitting the left/right energy ratio against the balance raw value --
22//! done separately for `bs_amp_res=0` (offset 12 in raw units, one
23//! exponent step per raw unit) and `bs_amp_res=1` (offset 6, two
24//! exponent steps per raw unit); both collapse to the same
25//! `2*alpha*raw - 12` form (`scripts/aac-tables/sbrpayload_fixtures.py`
26//! carries no permanent copy of the probe -- the fit is recorded here
27//! and in the project ledger).
28//!
29//! # Gain, limiter, noise, sinusoids
30//!
31//! For every `(envelope, band)` cell this measures the HF estimate's own
32//! average energy over that time/frequency window; the cell's envelope
33//! target is split into a signal share and a noise share via the cell's
34//! `Q_div = dequant_noise(q_q)` ratio (`signal = target/(1+Q_div)`,
35//! `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 then caps
38//! every cell's gain against its LIMITER BAND's aggregate headroom (Sec
39//! 4.6.18.7.2/.7.5, `bs_limiter_gains`, `crate::sbr_hf::limiter_band_table`)
40//! rather than each cell's own -- a content-empty cell has zero raw energy,
41//! so a per-cell cap is infinite exactly where it should bite; the
42//! aggregate cap and its gain-boost compensation (Sec 4.6.18.7.4) are
43//! applied to gains, injected noise and sinusoids alike. The noise share is
44//! mixed in at that level, and flagged bands get an added tone.
45#![allow(clippy::needless_range_loop)]
46
47use crate::sbr_bands::BandTables;
48use crate::sbr_payload::{SbrChannel, SbrHeader};
49use ec_dsp::Complex;
50
51const NOISE_FLOOR_OFFSET: f64 = 6.0;
52
53/// Envelope amp-resolution exponent: `2.0` (`bs_amp_res=1`, 3 dB) or `1.0`
54/// (`bs_amp_res=0`, 1.5 dB) -- expressed as the multiplier on `e_q/2` so
55/// callers can write `2f64.powf(alpha * e_q as f64 / 2.0)` uniformly, or
56/// just use [`dequant_env`] directly.
57fn alpha(amp_res: u8) -> f64 {
58 if amp_res != 0 { 1.0 } else { 0.5 }
59}
60
61/// Plain (non-coupled) envelope dequantization.
62pub fn dequant_env(e_q: i32, amp_res: u8) -> f64 {
63 2f64.powf(alpha(amp_res) * f64::from(e_q))
64}
65
66/// Plain noise-floor dequantization: `Q_div = 2^(NOISE_FLOOR_OFFSET-q_q)`, a
67/// ratio relative to the ENVELOPE energy of the same (time, band) cell, not
68/// an absolute energy on its own (round-21: `adjust` splits each cell's
69/// envelope target into `signal = target/(1+Q_div)` and
70/// `noise = target*Q_div/(1+Q_div)`; using this return value as a
71/// standalone absolute energy, as pre-round-21 code did, compares it
72/// against `dequant_env`'s unrelated unit scale).
73pub fn dequant_noise(q_q: i32) -> f64 {
74 2f64.powf(NOISE_FLOOR_OFFSET - f64::from(q_q))
75}
76
77/// De-mixes a coupled CPE's `(channel 0 raw, balance raw)` pair into
78/// `(left, right)` linear energies. See the module doc for the convention.
79pub fn dequant_pair(e0_raw: i32, e1_raw: i32, amp_res: u8) -> (f64, f64) {
80 let e0 = dequant_env(e0_raw, amp_res);
81 let ratio = 2f64.powf(2.0 * alpha(amp_res) * f64::from(e1_raw) - 12.0);
82 let left = 2.0 * e0 * ratio / (1.0 + ratio);
83 let right = 2.0 * e0 / (1.0 + ratio);
84 (left, right)
85}
86
87/// Dequantizes one channel's envelopes and noise floors for one frame,
88/// de-mixing through [`dequant_pair`] when `coupling` makes `channels[1]`
89/// a balance channel against `channels[0]`.
90pub fn dequantize_frame(
91 header: &SbrHeader,
92 channels: &[SbrChannel],
93 ch: usize,
94 coupling: bool,
95) -> (Vec<Vec<f64>>, Vec<Vec<f64>>) {
96 let c = &channels[ch];
97 // A single-envelope frame forces 1.5 dB resolution regardless of
98 // bs_amp_res, mirroring sbr_payload's own `amp_res_of`.
99 let amp_res = if c.e_q.len() == 1 { 0 } else { header.amp_res };
100 let mut env = Vec::with_capacity(c.e_q.len());
101 if coupling && channels.len() == 2 {
102 let (row0_src, row1_src, want_left) = if ch == 0 {
103 (0usize, 1usize, true)
104 } else {
105 (0usize, 1usize, false)
106 };
107 for i in 0..c.e_q.len() {
108 let row0 = channels[row0_src].e_q.get(i);
109 let row1 = channels[row1_src].e_q.get(i);
110 let len = c.e_q[i].len();
111 let mut r = Vec::with_capacity(len);
112 for b in 0..len {
113 let e0 = row0.and_then(|r| r.get(b)).copied().unwrap_or(0);
114 let e1 = row1.and_then(|r| r.get(b)).copied().unwrap_or(0);
115 let (left, right) = dequant_pair(e0, e1, amp_res);
116 r.push(if want_left { left } else { right });
117 }
118 env.push(r);
119 }
120 } else {
121 for row in &c.e_q {
122 env.push(row.iter().map(|&v| dequant_env(v, amp_res)).collect());
123 }
124 }
125 // corner-cut: noise floors dequantize independently per channel
126 // regardless of coupling. A mirrored dequant_noise_pair() demix (see
127 // git history) was tried and measured ZERO effect on the real-file
128 // ch1 RMS blow-up (identical output to printed precision), so the
129 // energy dequantization below is the live suspect, not this; reverted
130 // rather than keeping an unverified formula with no measured benefit.
131 let noise = c
132 .q_q
133 .iter()
134 .map(|row| row.iter().map(|&v| dequant_noise(v)).collect())
135 .collect();
136 (env, noise)
137}
138
139/// A small deterministic PRNG for the injected noise floor -- the same
140/// generator shape `decode::Noise` uses, kept local so this module has no
141/// dependency on the core decoder's internals.
142pub 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]).
164const LOWPASS_TAPS: usize = 2;
165
166impl NoiseGen {
167 pub fn new(seed: u32) -> NoiseGen {
168 NoiseGen {
169 lcg: seed | 1,
170 history: std::collections::VecDeque::with_capacity(LOWPASS_TAPS),
171 }
172 }
173
174 fn next(&mut self) -> f64 {
175 self.lcg = self.lcg.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
176 // (Round-41, Task 2) `self.0 >> 8` keeps 24 bits (range [0, 2^24));
177 // dividing by `1u32 << 23` (2^23, ONE bit too few) left a range of
178 // [0, 2) before the `- 0.5`, i.e. actual output was uniform on
179 // [-0.5, 1.5) with mean +0.5 -- a DC-biased "noise" source, not
180 // zero-mean. `decode::Noise::next` (same LCG constants) divides by
181 // the same `1 << 23` but subtracts `1.0`, which correctly centers
182 // ITS doubled [0,2) range; this generator subtracted the wrong
183 // constant for its own divisor. Dividing by `1u32 << 24` instead
184 // fixes the range to [0, 1) so `- 0.5` correctly centers it on
185 // [-0.5, 0.5), mean 0.
186 f64::from(self.lcg >> 8) / f64::from(1u32 << 24) - 0.5
187 }
188
189 fn complex_unit(&mut self) -> Complex<f64> {
190 // (Round-41, Task 2) `next()` is uniform on [-0.5, 0.5) (Var = 1/12
191 // per component), so a raw `(re, im)` pair has E[|z|^2] = 1/6, not
192 // 1 -- `adjust` scales this by `namp = sqrt(noise_here)` (round-42:
193 // no `/width`, `noise_here` is already a per-sample average)
194 // expecting E[|namp*z|^2] = noise_here, so without this correction
195 // only ~1/6 of the transmitted noise split was ever actually
196 // realized in the output. Measured directly (decode reeln twice,
197 // noise on vs `EC_AAC_SBR_NOISE_ZERO`, per-band output energy delta
198 // in `tests/sbr_real_library.rs`'s `sbr_actual_noise_fraction`):
199 // bookkept split ~0.37-0.39, actual realized only ~0.10-0.30 in-band
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.
213 const UNIT_SCALE: f64 = 2.449_489_742_783_178; // sqrt(6)
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)
226 }
227}
228
229// (Round-33) Per-limiter-band aggregate gain factor, ISO/IEC 14496-3
230// §4.6.18.7.2's `bs_limiter_gains` table: -3/0/+3 dB, and index 3
231// ("no limiting") given a very large but finite ceiling so a limiter band
232// with zero measured HF energy still can't blow up to a literal infinity.
233const LIMITER_FACTOR: [f64; 4] = [0.707_945_78, 1.0, 1.412_537_5, 1.0e10];
234
235/// Gain-boost compensation ceiling (+4 dB, §4.6.18.7.4): after the
236/// per-limiter-band cap, a band whose achieved energy fell short of its
237/// transmitted envelope total is boosted back up, capped here so a band
238/// that was capped hard doesn't get fully "un-capped" by the boost step.
239const BOOST_MAX: f64 = 1.584_893_2;
240
241/// (Round-17, Task 1 conviction check) Accumulates transmitted signal vs.
242/// noise energy per absolute QMF band across every [`adjust`] call in the
243/// process, weighted by how many QMF slots each contributes, when
244/// `EC_AAC_SBR_NOISE_FRACTION_DEBUG` is set. [`noise_fraction_table`] reads
245/// it back; both are no-ops (empty table) otherwise, so this costs nothing
246/// on the normal path.
247static NOISE_FRACTION_STATS: std::sync::OnceLock<std::sync::Mutex<Vec<(f64, f64)>>> =
248 std::sync::OnceLock::new();
249
250fn noise_fraction_debug() -> bool {
251 std::env::var("EC_AAC_SBR_NOISE_FRACTION_DEBUG").is_ok()
252}
253
254/// `(band, signal_energy_sum, noise_energy_sum)` for every band that
255/// accumulated anything, both sums slot-count-weighted.
256pub fn noise_fraction_table() -> Vec<(usize, f64, f64)> {
257 let Some(stats) = NOISE_FRACTION_STATS.get() else {
258 return Vec::new();
259 };
260 stats
261 .lock()
262 .unwrap()
263 .iter()
264 .enumerate()
265 .filter(|&(_, &(s, n))| s + n > 0.0)
266 .map(|(b, &(s, n))| (b, s, n))
267 .collect()
268}
269
270fn accumulate_noise_fraction(band: usize, slots: usize, signal: f64, noise: f64) {
271 if slots == 0 {
272 return;
273 }
274 let stats = NOISE_FRACTION_STATS.get_or_init(|| std::sync::Mutex::new(vec![(0.0, 0.0); 256]));
275 let mut g = stats.lock().unwrap();
276 if band >= g.len() {
277 g.resize(band + 1, (0.0, 0.0));
278 }
279 g[band].0 += signal * slots as f64;
280 g[band].1 += noise * slots as f64;
281}
282
283/// Applies envelope adjustment in place to `hf` (`[target band 0-based
284/// from kx][slot]`, as [`crate::sbr_hf::generate`] returns it): gain
285/// toward `env_energy`, the transmitted noise floor from `noise_energy`,
286/// and sinusoids at `ch.add_harmonic`'s flagged high-resolution bands.
287#[allow(clippy::too_many_arguments)]
288pub fn adjust(
289 hf: &mut [Vec<Complex<f64>>],
290 tables: &BandTables,
291 header: &SbrHeader,
292 ch: &SbrChannel,
293 env_energy: &[Vec<f64>],
294 noise_energy: &[Vec<f64>],
295 rng: &mut NoiseGen,
296 limiter_table: &[i64],
297) {
298 let kx = tables.kx as usize;
299 let n_lim = limiter_table.len().saturating_sub(1).max(1);
300 // (Round-22 sweep instrumentation, zero cost unset) `EC_AAC_SBR_LIMITER_OFF`
301 // forces the "no limit" factor regardless of the transmitted
302 // `bs_limiter_gains`, to probe whether the limiter itself is clipping
303 // correlation on real content.
304 let limiter_max = if std::env::var("EC_AAC_SBR_LIMITER_OFF").is_ok() {
305 LIMITER_FACTOR[3]
306 } else {
307 LIMITER_FACTOR[usize::from(header.limiter_gains).min(3)]
308 };
309 let track_fraction = noise_fraction_debug();
310 // (Round-17, Task 1 corroboration) zeroes our injected noise so the
311 // sweep's measured correlation can be checked against the
312 // signal-only ceiling `noise_fraction_table` predicts, without
313 // touching the transmitted noise ENERGY bookkeeping above (only the
314 // actual PCM addition is skipped).
315 let zero_noise = std::env::var("EC_AAC_SBR_NOISE_ZERO").is_ok();
316 // (Round-22 sweep instrumentation, zero cost unset) `EC_AAC_SBR_GAIN_LERP`
317 // linearly interpolates each envelope's per-band gain toward the NEXT
318 // envelope's gain across the current envelope's time slots, instead of
319 // holding it flat -- probing whether our constant-per-cell gain shape
320 // (vs. the spec's smoother per-slot shape) is a live suspect.
321 let gain_lerp = std::env::var("EC_AAC_SBR_GAIN_LERP").is_ok();
322 // (Round-43, Task 1) `EC_AAC_SBR_CELLDUMP=band[,band...]` -- comma list
323 // of ABSOLUTE QMF band indices (same units as `kx`/`k2`/`f_high`,
324 // `band_hz = rate/128`, per round-42's fixed test-side mapping) -- dumps
325 // every (envelope, band) cell whose `[lo,hi)` range covers a listed
326 // band: target/signal_target/noise_here/measured cur/raw+capped gain/
327 // boost/namp/sinusoid amp, and the actually-injected noise energy that
328 // frame, to stderr.
329 let celldump: Vec<usize> = std::env::var("EC_AAC_SBR_CELLDUMP")
330 .ok()
331 .map(|s| s.split(',').filter_map(|t| t.trim().parse().ok()).collect())
332 .unwrap_or_default();
333
334 // Gain toward the transmitted envelope, per (envelope, band) cell,
335 // limited relative to that cell's own noise floor.
336 for (ei, (t0, t1)) in ch.t_env.windows(2).map(|w| (w[0], w[1])).enumerate() {
337 if ei >= env_energy.len() {
338 break;
339 }
340 let high_res = ch.freq_res.get(ei).copied().unwrap_or(0) != 0;
341 let table = if high_res {
342 &tables.f_high
343 } else {
344 &tables.f_low
345 };
346 // The noise segment covering this envelope's time range (noise
347 // borders are a coarser subset of the envelope borders sharing the
348 // same start/end points).
349 let noise_row: Option<&Vec<f64>> = ch
350 .t_noise
351 .windows(2)
352 .position(|w| t0 >= w[0] && t0 < w[1])
353 .and_then(|ni| noise_energy.get(ni));
354 // Per-sfb gain, computed first and applied afterward (as either a
355 // flat step per band, or -- Sec 4.6.18.7.6, `bs_interpol_freq` --
356 // linearly interpolated across subbands between sfb centre
357 // frequencies) so both application modes share the exact same gain
358 // values.
359 //
360 // (Round-33) The limiter no longer caps each cell against its OWN
361 // near-zero raw HF estimate (that cap is infinite exactly where a
362 // patch left a target band content-empty, Sec 4.6.18.7.5's known
363 // failure mode for cell-local caps). Instead this is a two-pass
364 // per-LIMITER-BAND aggregate: pass 1 computes each cell's raw
365 // (uncapped) gain and accumulates that cell's transmitted/measured
366 // energy into its limiter band (`limiter_table`, built from
367 // f_low/patch borders in sbr_hf::limiter_band_table); pass 2 caps
368 // every cell in a limiter band at that band's AGGREGATE
369 // `sqrt(E_orig/E_curr)*limgain` ratio, so an empty cell inherits its
370 // band's cap rather than blowing up alone, then boosts the whole
371 // band back up (capped at `BOOST_MAX`) to still meet the band's
372 // transmitted total.
373 let mut gains = Vec::with_capacity(table.len().saturating_sub(1));
374 // (Round-21) Actual per-cell noise energy this envelope/band injects,
375 // parallel to `gains` -- filled below and consumed by the
376 // application loop that follows instead of the old separate
377 // noise-grid pass (see round-21 module doc note).
378 let mut noise_amps = Vec::with_capacity(table.len().saturating_sub(1));
379 let mut cell_current = Vec::with_capacity(table.len().saturating_sub(1));
380 let mut cell_noise_here = Vec::with_capacity(table.len().saturating_sub(1));
381 let mut cell_lim = Vec::with_capacity(table.len().saturating_sub(1));
382 let mut lim_e_orig = vec![0.0f64; n_lim];
383 let mut lim_e_curr = vec![0.0f64; n_lim];
384 for b in 0..table.len().saturating_sub(1) {
385 let lo = table[b] as usize;
386 let hi = table[b + 1] as usize;
387 let target = env_energy[ei].get(b).copied().unwrap_or(0.0);
388 let (mut sum, mut count) = (0.0f64, 0usize);
389 for band in lo..hi {
390 if band < kx || band - kx >= hf.len() {
391 continue;
392 }
393 let row = &hf[band - kx];
394 for slot in t0.max(0) as usize..(t1.max(0) as usize).min(row.len()) {
395 sum += row[slot].norm_sqr();
396 count += 1;
397 }
398 }
399 let current = if count > 0 { sum / count as f64 } else { 0.0 };
400 let q = noise_band_for(tables, lo);
401 // `dequant_noise` returns `Q_div = 2^(NOISE_FLOOR_OFFSET-q_q)`, a
402 // ratio relative to this cell's OWN envelope target -- not an
403 // absolute energy in the same units as `target` (round-21 Task
404 // 1/2: a reference-decoder q_q sweep at a FIXED envelope target
405 // showed total output power staying nearly flat as q_q swept its
406 // whole range, the signature of `target` being split
407 // `signal=target/(1+Q_div)`, `noise=target*Q_div/(1+Q_div)`
408 // rather than noise being added independently on top of the full
409 // target -- the previous code used `dequant_noise` as an
410 // absolute energy standalone, which for real content's near-1e-7
411 // apparent "fraction" (round-17) was actually comparing two
412 // energies in unrelated unit scales, not a genuinely near-zero
413 // noise contribution).
414 let noise_div = noise_row
415 .and_then(|r| r.get(q).copied())
416 .unwrap_or(0.0)
417 .max(0.0);
418 let signal_target = target / (1.0 + noise_div);
419 let noise_here = target - signal_target; // = target*noise_div/(1+noise_div)
420 let cur = current.max(1e-12);
421 let raw_gain = (signal_target / cur).sqrt();
422 let lim_idx = limiter_band_index(limiter_table, lo, hi).min(n_lim - 1);
423 let width = (hi - lo).max(1) as f64;
424 // (Round-42, Task 1) `lim_e_orig` conserves the cell's FULL
425 // transmitted `target` (signal+noise), matching the limiter cap
426 // and boost pass to the TOTAL energy budget rather than the
427 // signal share alone -- `lim_e_actual` below is widened to
428 // match (adds `cell_noise_here` alongside the capped signal
429 // energy) so the boost's `lim_e_orig/lim_e_actual` ratio
430 // compares total-to-total. Measured signal-target-only variant
431 // (both sides restricted to `signal_target`) FIRST and it made
432 // the realized noise fraction anchor WORSE (0.1325 -> 0.1233
433 // whole-HF, moving further from the ~0.38 bookkept split) --
434 // this total-conserving variant is the one that holds.
435 lim_e_orig[lim_idx] += target * width;
436 lim_e_curr[lim_idx] += cur * width;
437 cell_current.push(cur);
438 cell_noise_here.push(noise_here);
439 cell_lim.push(lim_idx);
440 gains.push(raw_gain);
441 if track_fraction {
442 let slots = (t1.max(0) - t0.max(0)).max(0) as usize;
443 for band in lo..hi {
444 if band < kx {
445 continue;
446 }
447 accumulate_noise_fraction(band, slots, signal_target, noise_here);
448 }
449 }
450 }
451 // (Round-43, Task 1) `raw_gain` (pre-cap) is about to be overwritten
452 // in place inside `gains` below; keep an uncapped copy for the
453 // celldump so its "cap applied?" column can compare against it.
454 let raw_gains: Vec<f64> = if celldump.is_empty() {
455 Vec::new()
456 } else {
457 gains.clone()
458 };
459 // Pass 2: per-limiter-band aggregate cap, then per-band boost
460 // compensation so the band still meets its transmitted total.
461 let lim_cap: Vec<f64> = (0..n_lim)
462 .map(|j| limiter_max * (lim_e_orig[j] / lim_e_curr[j].max(1e-12)).sqrt())
463 .collect();
464 let mut lim_e_actual = vec![0.0f64; n_lim];
465 for b in 0..gains.len() {
466 let j = cell_lim[b];
467 gains[b] = gains[b].min(lim_cap[j]);
468 let lo = table[b] as usize;
469 let hi = table[b + 1] as usize;
470 let width = (hi - lo).max(1) as f64;
471 // Total realized energy this cell will carry: the capped
472 // signal gain applied to the raw HF estimate, PLUS the noise
473 // share `target` already budgeted for this cell (noise is
474 // injected independently of `gains`, at `noise_amps` below) --
475 // matches `lim_e_orig`'s total-target accounting above.
476 lim_e_actual[j] +=
477 cell_current[b] * gains[b] * gains[b] * width + cell_noise_here[b] * width;
478 }
479 let lim_boost: Vec<f64> = (0..n_lim)
480 .map(|j| {
481 if lim_e_actual[j] > 1e-12 {
482 (lim_e_orig[j] / lim_e_actual[j])
483 .sqrt()
484 .clamp(1.0, BOOST_MAX)
485 } else {
486 1.0
487 }
488 })
489 .collect();
490 for b in 0..gains.len() {
491 let j = cell_lim[b];
492 gains[b] *= lim_boost[j];
493 // (Round-42, Task 1 corollary) `cell_noise_here[b]` is already a
494 // PER-SAMPLE average energy (same units as `target`/`current` --
495 // see `raw_gain = sqrt(signal_target / cur)` just above, which
496 // treats both sides as per-sample averages without any width
497 // normalization). Dividing by the cell's QMF-band width here
498 // (as the pre-round-42 code did) additionally shrank the
499 // per-sample injected noise variance by `1/width`, on top of
500 // whatever the sample count already contributes when this same
501 // amplitude is applied once per (band, slot) below -- worse at
502 // wider high-frequency sfb cells, matching the measured
503 // realized-noise-fraction shortfall growing toward the top of
504 // the band in `EC_AAC_SBR_NOISE_ANCHOR`.
505 noise_amps.push(cell_noise_here[b].sqrt() * lim_boost[j]);
506 }
507 // (Round-43, Task 1) per-cell diagnostic dump for `EC_AAC_SBR_CELLDUMP`
508 // -- printed before the application loop below so it reflects the
509 // gain/noise-amplitude values that loop is about to use; the
510 // actually-injected sample energy (which depends on the RNG draws
511 // that loop consumes) is measured separately and printed right
512 // after it, tagged with the same `ei`/band range so the two lines
513 // pair up by eye.
514 if !celldump.is_empty() {
515 for b in 0..table.len().saturating_sub(1) {
516 let lo = table[b] as usize;
517 let hi = table[b + 1] as usize;
518 if !celldump.iter().any(|&cb| cb >= lo && cb < hi) {
519 continue;
520 }
521 let target = env_energy[ei].get(b).copied().unwrap_or(0.0);
522 let noise_here = cell_noise_here[b];
523 let signal_target = target - noise_here;
524 let cur = cell_current[b];
525 let raw_gain = raw_gains[b];
526 let lim_idx = cell_lim[b];
527 let capped = raw_gain > lim_cap[lim_idx] + 1e-12;
528 let boost = lim_boost[lim_idx];
529 let namp = noise_amps[b];
530 // Harmonic flag/amp for any listed band this cell covers
531 // (checked against the high-res `f_high` grid the sinusoid
532 // block below uses, regardless of this cell's own
533 // resolution).
534 let mut harmonic = None;
535 if let Some(flags) = &ch.add_harmonic {
536 for (hb, &on) in flags.iter().enumerate() {
537 if on == 0 || hb + 1 >= tables.f_high.len() {
538 continue;
539 }
540 let hlo = tables.f_high[hb] as usize;
541 let hhi = tables.f_high[hb + 1] as usize;
542 if celldump
543 .iter()
544 .any(|&cb| cb >= hlo && cb < hhi && cb >= lo && cb < hi)
545 {
546 let e = if high_res {
547 env_energy[ei].get(hb).copied().unwrap_or(0.0)
548 } else {
549 target
550 };
551 let hboost = lim_boost
552 [limiter_band_index(limiter_table, hlo, hhi).min(n_lim - 1)];
553 harmonic = Some((2.0 * e).sqrt() * hboost);
554 }
555 }
556 }
557 eprintln!(
558 "CELLDUMP ei={ei} band[{lo},{hi}) target={target:.6e} \
559 signal_target={signal_target:.6e} noise_here={noise_here:.6e} \
560 cur={cur:.6e} raw_gain={raw_gain:.6} capped={capped} boost={boost:.6} \
561 namp={namp:.6} harmonic_amp={harmonic:?}"
562 );
563 }
564 }
565 // (Round-22 sweep instrumentation) the next envelope's gains, only
566 // when `EC_AAC_SBR_GAIN_LERP` is set and the band layouts match --
567 // `hf` in the next envelope's time range is still untouched at this
568 // point (envelopes are processed and applied in time order), so
569 // this reads the same raw HF estimate the next iteration would.
570 let next_gains: Option<Vec<f64>> =
571 if gain_lerp && ei + 1 < env_energy.len() && ei + 2 < ch.t_env.len() {
572 let (t0n, t1n) = (ch.t_env[ei + 1], ch.t_env[ei + 2]);
573 let high_res_n = ch.freq_res.get(ei + 1).copied().unwrap_or(0) != 0;
574 let table_n: &[i64] = if high_res_n {
575 &tables.f_high
576 } else {
577 &tables.f_low
578 };
579 if table_n.len() == table.len() {
580 let noise_row_n: Option<&Vec<f64>> = ch
581 .t_noise
582 .windows(2)
583 .position(|w| t0n >= w[0] && t0n < w[1])
584 .and_then(|ni| noise_energy.get(ni));
585 Some(compute_gains_only(
586 hf,
587 tables,
588 kx,
589 table_n,
590 t0n,
591 t1n,
592 &env_energy[ei + 1],
593 noise_row_n,
594 limiter_max,
595 ))
596 } else {
597 None
598 }
599 } else {
600 None
601 };
602 // `bs_interpol_freq` (per-subband linear interpolation of these sfb
603 // gains, Sec 4.6.18.7.6) was tried here: a centre-frequency lerp
604 // between neighbouring sfbs' flat gain values, applied whenever
605 // `header.interpol_freq != 0`. Measured effect on the real-file
606 // sweep was NEGATIVE (reeln ch0 full-band 0.972756 -> 0.960561)
607 // -- the reference decoder's actual interpolation shape (weighting,
608 // node placement, or which quantity gets interpolated) differs from
609 // this naive lerp, so it was reverted rather than shipped as a
610 // regression; `header.interpol_freq`/`smoothing_mode` remain parsed
611 // but unapplied. corner-cut: real bs_interpol_freq/smoothing_mode
612 // support, ceiling ~0.999 full-band bar; needs the reference
613 // decoder's exact per-subband gain-interpolation formula, not a
614 // plausible reconstruction of it.
615 let span = (t1 - t0.max(0)).max(1) as f64;
616 // (Round-43, Task 1) actual injected-noise-sample energy for the
617 // celldump, summed per listed absolute band (the RNG draws it from
618 // are only realized inside this loop, unlike everything the print
619 // block above already knows).
620 let mut celldump_injected: std::collections::HashMap<usize, (f64, f64, usize)> =
621 std::collections::HashMap::new();
622 let mut celldump_post: std::collections::HashMap<usize, (f64, usize)> =
623 std::collections::HashMap::new();
624 for b in 0..table.len().saturating_sub(1) {
625 let lo = table[b] as usize;
626 let hi = table[b + 1] as usize;
627 let base_gain = gains[b];
628 let end_gain = next_gains.as_ref().and_then(|ng| ng.get(b).copied());
629 let namp = noise_amps[b];
630 for band in lo..hi {
631 if band < kx || band - kx >= hf.len() {
632 continue;
633 }
634 let row = &mut hf[band - kx];
635 for slot in t0.max(0) as usize..(t1.max(0) as usize).min(row.len()) {
636 let gain = if let Some(end) = end_gain {
637 let w = (slot as f64 - t0.max(0) as f64) / span;
638 base_gain + (end - base_gain) * w.clamp(0.0, 1.0)
639 } else {
640 base_gain
641 };
642 row[slot] = row[slot].scale(gain);
643 if !celldump.is_empty() && celldump.contains(&band) {
644 let e = celldump_injected.entry(band).or_insert((0.0, 0.0, 0));
645 e.1 += row[slot].norm_sqr(); // signal alone, pre-noise
646 e.2 += 1;
647 }
648 // Consume the RNG unconditionally (matches the pre-round-21
649 // stream shape) even under EC_AAC_SBR_NOISE_ZERO, which
650 // only skips the PCM addition, not the bookkeeping.
651 let n = rng.complex_unit().scale(namp);
652 if !celldump.is_empty() && celldump.contains(&band) {
653 let e = celldump_injected.entry(band).or_insert((0.0, 0.0, 0));
654 e.0 += n.norm_sqr();
655 }
656 row[slot] = row[slot] + if zero_noise { Complex::ZERO } else { n };
657 if !celldump.is_empty() && celldump.contains(&band) {
658 celldump_post.entry(band).or_insert((0.0, 0)).0 += row[slot].norm_sqr();
659 celldump_post.entry(band).or_insert((0.0, 0)).1 += 1;
660 }
661 }
662 }
663 }
664 if !celldump.is_empty() {
665 for (&band, &(noise_sum, signal_sum, count)) in &celldump_injected {
666 let (post_sum, post_count) = celldump_post.get(&band).copied().unwrap_or((0.0, 0));
667 eprintln!(
668 "CELLDUMP ei={ei} band={band} actually_injected_noise_energy={:.6e} \
669 actual_signal_only_energy={:.6e} post_addition_energy={:.6e} (n={count})",
670 if count > 0 {
671 noise_sum / count as f64
672 } else {
673 0.0
674 },
675 if count > 0 {
676 signal_sum / count as f64
677 } else {
678 0.0
679 },
680 if post_count > 0 {
681 post_sum / post_count as f64
682 } else {
683 0.0
684 },
685 );
686 }
687 }
688
689 // Sinusoids: one extra tone per flagged high-resolution band,
690 // added after gain so its amplitude is exact regardless of the
691 // cell's measured HF energy.
692 if let Some(flags) = &ch.add_harmonic {
693 for (b, &on) in flags.iter().enumerate() {
694 if on == 0 || b + 1 >= tables.f_high.len() {
695 continue;
696 }
697 let lo = tables.f_high[b] as usize;
698 let hi = tables.f_high[b + 1] as usize;
699 let e = if high_res {
700 env_energy[ei].get(b).copied().unwrap_or(0.0)
701 } else {
702 // The envelope grid was low-res this frame; approximate
703 // the harmonic band's share of its low-res parent cell.
704 let lb = table
705 .iter()
706 .position(|&x| x as usize > lo)
707 .map(|i| i.saturating_sub(1))
708 .unwrap_or(0);
709 env_energy[ei].get(lb).copied().unwrap_or(0.0)
710 };
711 let boost = lim_boost[limiter_band_index(limiter_table, lo, hi).min(n_lim - 1)];
712 let amp = (2.0 * e).sqrt() * boost;
713 for band in lo..hi {
714 if band < kx || band - kx >= hf.len() {
715 continue;
716 }
717 let row = &mut hf[band - kx];
718 for slot in t0.max(0) as usize..(t1.max(0) as usize).min(row.len()) {
719 row[slot] = row[slot] + Complex::new(amp, 0.0);
720 }
721 }
722 }
723 }
724 }
725
726 // (Round-21) Noise is now injected inside the envelope-gain loop above,
727 // per (envelope, band) cell using each cell's own `signal_target`/
728 // `noise_here` split -- the noise grid is coarser than the envelope
729 // grid but every envelope cell resolves its own noise band via
730 // `noise_band_for`/`noise_row`, so this covers the same ground the old
731 // separate noise-grid pass did, consistently with the gain that was
732 // computed for the same cell (previously the two were split across
733 // unrelated unit scales; see the comment at `noise_div` above).
734}
735
736/// (Round-22 sweep instrumentation) The same gain math the main loop in
737/// [`adjust`] computes, minus the tracking/noise-amplitude side effects --
738/// used to look ahead at the NEXT envelope's gain for `EC_AAC_SBR_GAIN_LERP`.
739#[allow(clippy::too_many_arguments)]
740fn compute_gains_only(
741 hf: &[Vec<Complex<f64>>],
742 tables: &BandTables,
743 kx: usize,
744 table: &[i64],
745 t0: i64,
746 t1: i64,
747 env_row: &[f64],
748 noise_row: Option<&Vec<f64>>,
749 limiter_max: f64,
750) -> Vec<f64> {
751 let mut gains = Vec::with_capacity(table.len().saturating_sub(1));
752 for b in 0..table.len().saturating_sub(1) {
753 let lo = table[b] as usize;
754 let hi = table[b + 1] as usize;
755 let target = env_row.get(b).copied().unwrap_or(0.0);
756 let (mut sum, mut count) = (0.0f64, 0usize);
757 for band in lo..hi {
758 if band < kx || band - kx >= hf.len() {
759 continue;
760 }
761 let row = &hf[band - kx];
762 for slot in t0.max(0) as usize..(t1.max(0) as usize).min(row.len()) {
763 sum += row[slot].norm_sqr();
764 count += 1;
765 }
766 }
767 let current = if count > 0 { sum / count as f64 } else { 0.0 };
768 let q = noise_band_for(tables, lo);
769 let noise_div = noise_row
770 .and_then(|r| r.get(q).copied())
771 .unwrap_or(0.0)
772 .max(0.0);
773 let signal_target = target / (1.0 + noise_div);
774 let noise_here = target - signal_target;
775 let cur = current.max(1e-12);
776 let mut gain = (signal_target / cur).sqrt();
777 gain = gain.min(limiter_max * ((noise_here + cur) / cur).sqrt());
778 gain = gain.min(limiter_max * 64.0);
779 gains.push(gain);
780 }
781 gains
782}
783
784/// Finds which limiter band (from [`crate::sbr_hf::limiter_band_table`])
785/// a `[lo, hi)` QMF-band cell falls into, by its midpoint.
786fn limiter_band_index(limiter_table: &[i64], lo: usize, hi: usize) -> usize {
787 if limiter_table.len() < 2 {
788 return 0;
789 }
790 let mid = (lo + hi) as i64 / 2;
791 for j in 0..limiter_table.len() - 1 {
792 if mid < limiter_table[j + 1] {
793 return j;
794 }
795 }
796 limiter_table.len() - 2
797}
798
799fn noise_band_for(tables: &BandTables, low_band: usize) -> usize {
800 let mut q = 0usize;
801 for i in 0..tables.n_q {
802 if (low_band as i64) >= tables.f_noise[i] {
803 q = i;
804 }
805 }
806 q
807}
808
809#[cfg(test)]
810mod tests {
811 use super::*;
812 use crate::sbr_bands::freq_tables;
813 use crate::sbr_hf::{build_patches, limiter_band_table};
814 use crate::sbr_payload::SbrChannel;
815
816 fn flat_tables() -> BandTables {
817 freq_tables(44100, 5, 3, 2, 1, 2, 2).unwrap()
818 }
819
820 fn header(amp_res: u8, limiter_gains: u8) -> SbrHeader {
821 SbrHeader {
822 amp_res,
823 start_freq: 5,
824 stop_freq: 3,
825 xover_band: 2,
826 freq_scale: 2,
827 alter_scale: 1,
828 noise_bands: 2,
829 limiter_bands: 2,
830 limiter_gains,
831 interpol_freq: 1,
832 smoothing_mode: 1,
833 }
834 }
835
836 #[test]
837 fn flat_hf_region_reaches_the_stated_envelope_energy() {
838 let tables = flat_tables();
839 let kx = tables.kx as usize;
840 let k2 = tables.k2 as usize;
841 let slots = 16usize;
842 let mut hf = vec![vec![Complex::new(0.1, 0.0); slots]; k2 - kx];
843 let ch = SbrChannel {
844 t_env: vec![0, 16],
845 freq_res: vec![0],
846 t_noise: vec![0, 16],
847 e_q: vec![vec![]],
848 q_q: vec![vec![]],
849 invf_mode: vec![],
850 add_harmonic: None,
851 };
852 let target = 4.0f64;
853 let env_energy = vec![vec![target; tables.n_low]];
854 let noise_energy = vec![vec![0.0f64; tables.n_q]];
855 let mut rng = NoiseGen::new(1);
856 let lim_table =
857 limiter_band_table(&tables, &build_patches(&tables), header(1, 3).limiter_bands);
858 adjust(
859 &mut hf,
860 &tables,
861 &header(1, 3),
862 &ch,
863 &env_energy,
864 &noise_energy,
865 &mut rng,
866 &lim_table,
867 );
868
869 // Every low-res band's average energy should land close to target.
870 for b in 0..tables.n_low {
871 let lo = tables.f_low[b] as usize;
872 let hi = tables.f_low[b + 1] as usize;
873 let mut sum = 0.0;
874 let mut n = 0usize;
875 for band in lo..hi {
876 if band < kx {
877 continue;
878 }
879 for slot in 0..slots {
880 sum += hf[band - kx][slot].norm_sqr();
881 n += 1;
882 }
883 }
884 if n == 0 {
885 continue;
886 }
887 let avg = sum / n as f64;
888 assert!(
889 (avg - target).abs() / target < 0.05,
890 "band {b}: avg {avg} vs target {target}"
891 );
892 }
893 }
894
895 /// (Round-41, Task 2) `NoiseGen::complex_unit`'s realized expected
896 /// squared magnitude must be ~1.0 -- `adjust` scales it by
897 /// `namp = sqrt(noise_here)` expecting `E[|namp*z|^2] =
898 /// noise_here`, so anything but ~1.0 here means the injected noise
899 /// under- or over-realizes the transmitted split regardless of the
900 /// limiter/boost interaction (measured separately, at the whole-decode
901 /// level, in `tests/sbr_real_library.rs`'s `sbr_actual_noise_fraction`).
902 /// Before the `sqrt(6)` fix this read ~1/6.
903 #[test]
904 fn complex_unit_has_unit_expected_squared_magnitude() {
905 let mut rng = NoiseGen::new(1);
906 let n = 200_000;
907 let mean_sq: f64 =
908 (0..n).map(|_| rng.complex_unit().norm_sqr()).sum::<f64>() / f64::from(n);
909 assert!(
910 (mean_sq - 1.0).abs() < 0.02,
911 "E[|complex_unit()|^2] = {mean_sq}, expected ~1.0"
912 );
913 }
914
915 #[test]
916 fn limiter_stays_finite_on_a_uniformly_starved_band() {
917 // (Round-33 semantics change) A UNIFORMLY near-silent HF estimate
918 // against a huge uniform target is no longer expected to be capped
919 // down near the raw HF amplitude -- the aggregate cap and its
920 // gain-boost compensation are computed from the SAME population, so
921 // when every cell in a limiter band is equally starved (no
922 // disproportion for the limiter to actually correct), full recovery
923 // toward the transmitted target is the spec-correct outcome (boost
924 // undoes exactly what the cap took away, as long as the needed
925 // `1/limiter_max` stays under `BOOST_MAX`). What must NOT happen
926 // (the actual pre-fix bug) is a literal unbounded/non-finite blow-up
927 // -- this asserts finiteness and a generous bound around the target
928 // amplitude, not the old (now-wrong) "stays near the raw estimate"
929 // shape.
930 let tables = flat_tables();
931 let kx = tables.kx as usize;
932 let k2 = tables.k2 as usize;
933 let slots = 16usize;
934 let mut hf = vec![vec![Complex::new(1e-9, 0.0); slots]; k2 - kx];
935 let ch = SbrChannel {
936 t_env: vec![0, 16],
937 freq_res: vec![0],
938 t_noise: vec![0, 16],
939 e_q: vec![vec![]],
940 q_q: vec![vec![]],
941 invf_mode: vec![],
942 add_harmonic: None,
943 };
944 let env_energy = vec![vec![1.0e6f64; tables.n_low]];
945 // (Round-21) noise_energy is now a Q_div ratio against the cell's
946 // own envelope target, not a standalone absolute energy -- zero
947 // keeps this test focused on the signal-gain limiter it names, not
948 // noise injection.
949 let noise_energy = vec![vec![0.0f64; tables.n_q]];
950 let mut rng = NoiseGen::new(1);
951 let lim_table =
952 limiter_band_table(&tables, &build_patches(&tables), header(1, 0).limiter_bands);
953 adjust(
954 &mut hf,
955 &tables,
956 &header(1, 0),
957 &ch,
958 &env_energy,
959 &noise_energy,
960 &mut rng,
961 &lim_table,
962 );
963 let target_amp = 1.0e6f64.sqrt(); // ~1000, the envelope's own amplitude scale
964 for band in 0..hf.len() {
965 for slot in 0..slots {
966 let amp = hf[band][slot].norm_sqr().sqrt();
967 assert!(
968 amp.is_finite() && amp < 10.0 * target_amp,
969 "gain escaped to a non-finite/unbounded value at band {band} slot {slot}: {:?}",
970 hf[band][slot]
971 );
972 }
973 }
974 }
975
976 #[test]
977 fn a_content_empty_cell_inherits_its_limiter_bands_aggregate_cap() {
978 // (Round-33) One low-res band has real HF content, its neighbour is
979 // perfectly silent (current=0, the exact case a per-cell cap makes
980 // infinite -- round-33's convicted mechanism). Both fall in the
981 // same limiter_bands=0 (single aggregate band) table here, so the
982 // silent cell must be capped by the AGGREGATE ratio (dominated by
983 // the loud cell's huge current), not blown up on its own.
984 let tables = flat_tables();
985 let kx = tables.kx as usize;
986 let k2 = tables.k2 as usize;
987 let slots = 16usize;
988 let mut hf = vec![vec![Complex::new(0.1, 0.0); slots]; k2 - kx];
989 // Silence the top half of the HF region (the empty target cell).
990 let mid = hf.len() / 2;
991 for row in &mut hf[mid..] {
992 for c in row.iter_mut() {
993 *c = Complex::ZERO;
994 }
995 }
996 let ch = SbrChannel {
997 t_env: vec![0, 16],
998 freq_res: vec![0],
999 t_noise: vec![0, 16],
1000 e_q: vec![vec![]],
1001 q_q: vec![vec![]],
1002 invf_mode: vec![],
1003 add_harmonic: None,
1004 };
1005 let target = 4.0f64;
1006 let env_energy = vec![vec![target; tables.n_low]];
1007 let noise_energy = vec![vec![0.0f64; tables.n_q]];
1008 let mut rng = NoiseGen::new(1);
1009 let mut h = header(1, 1);
1010 h.limiter_bands = 0; // single aggregate band spanning the whole HF region
1011 let lim_table = limiter_band_table(&tables, &build_patches(&tables), h.limiter_bands);
1012 assert_eq!(lim_table, vec![tables.kx, tables.k2]);
1013 adjust(
1014 &mut hf,
1015 &tables,
1016 &h,
1017 &ch,
1018 &env_energy,
1019 &noise_energy,
1020 &mut rng,
1021 &lim_table,
1022 );
1023 // The previously-silent cells must stay bounded (not blown up to
1024 // the old per-cell `limiter_max*64` absolute ceiling on a target of
1025 // 4.0 -- they should land well under it, inheriting the band's
1026 // aggregate cap instead).
1027 for row in &hf[mid..] {
1028 for c in row {
1029 assert!(
1030 c.norm_sqr() < target * 4.0,
1031 "empty cell escaped its limiter band's aggregate cap: {c:?}"
1032 );
1033 }
1034 }
1035 }
1036
1037 #[test]
1038 fn coupled_balance_round_trips_at_a_centred_ratio() {
1039 // The ratio's exponent is `2*alpha*balance_raw - 12` (pinned against
1040 // a reference decoder, see the module doc): it's centred at
1041 // balance_raw=6 for amp_res=1 (alpha=1) and balance_raw=12 for
1042 // amp_res=0 (alpha=0.5).
1043 let (l, r) = dequant_pair(10, 6, 1);
1044 let e0 = dequant_env(10, 1);
1045 assert!(
1046 (l - e0).abs() < 1e-6 && (r - e0).abs() < 1e-6,
1047 "{l} {r} vs {e0}"
1048 );
1049 let (l0, r0) = dequant_pair(10, 12, 0);
1050 let e00 = dequant_env(10, 0);
1051 assert!(
1052 (l0 - e00).abs() < 1e-6 && (r0 - e00).abs() < 1e-6,
1053 "{l0} {r0} vs {e00}"
1054 );
1055 }
1056
1057 #[test]
1058 fn coupled_balance_shifts_energy_toward_the_channel_with_a_higher_raw_value() {
1059 // Fit against the reference decoder's own PCM output (not spec
1060 // text): as balance_raw grows past the centre, left grows toward
1061 // `2*e0` and right shrinks toward 0, matching the measured PCM
1062 // energy split for a real coupled CPE.
1063 let (l_low, r_low) = dequant_pair(10, 0, 1);
1064 let (l_high, r_high) = dequant_pair(10, 20, 1);
1065 assert!(l_low < r_low, "{l_low} vs {r_low}");
1066 assert!(l_high > r_high, "{l_high} vs {r_high}");
1067 }
1068}