From 0fb1dc203ca0700b187f9b722122a288d51d3687 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Thu, 20 Aug 2026 01:15:17 +0300 Subject: [PATCH] sbr: env-gated parameter-sensitivity sweep instruments (round-22) EC_AAC_SBR_BW_SCALE (chirp/inverse-filter target scale, clamped <1), EC_AAC_SBR_CHIRP_SMOOTH=none|swap (attack/release curve), EC_AAC_SBR_GAIN_LERP (per-slot gain interpolation toward the next envelope), and EC_AAC_SBR_LIMITER_OFF probe whether real-content correlation is sensitive to these knobs. All zero-cost when unset; default behavior unchanged (40/40 lib tests, reeln baseline bit-identical). EC_AAC_SBR_SWEEP_SEGMENT=1 lets the real-file test measure the second half of a file for stability checks. Sweep result: BW_SCALE shows a small monotonic response (best at scale=0, i.e. no chirp resonance at all -- ch1 delta 0.0023, just past the 0.002 material bar) but a two-segment stability check was inconclusive (the file's second half has near-zero baseline correlation for both candidate and default, invalidating the comparison), so the default is NOT changed. Chirp-smoothing curve and limiter are flat (eliminated). Gain-lerp catastrophically regresses (full-band 0.97->0.07) and is eliminated. --- crates/ec-aac/src/sbr_env.rs | 111 +++++++++++++++++++++++- crates/ec-aac/src/sbr_hf.rs | 58 +++++++++++-- crates/ec-aac/tests/sbr_real_library.rs | 12 ++- 3 files changed, 173 insertions(+), 8 deletions(-) diff --git a/crates/ec-aac/src/sbr_env.rs b/crates/ec-aac/src/sbr_env.rs index 4f329bdd..3ba24ada 100644 --- a/crates/ec-aac/src/sbr_env.rs +++ b/crates/ec-aac/src/sbr_env.rs @@ -211,7 +211,15 @@ pub fn adjust( rng: &mut NoiseGen, ) { let kx = tables.kx as usize; - let limiter_max = LIMITER_FACTOR[usize::from(header.limiter_gains).min(3)]; + // (Round-22 sweep instrumentation, zero cost unset) `EC_AAC_SBR_LIMITER_OFF` + // forces the "no limit" factor regardless of the transmitted + // `bs_limiter_gains`, to probe whether the limiter itself is clipping + // correlation on real content. + let limiter_max = if std::env::var("EC_AAC_SBR_LIMITER_OFF").is_ok() { + LIMITER_FACTOR[3] + } else { + LIMITER_FACTOR[usize::from(header.limiter_gains).min(3)] + }; let track_fraction = noise_fraction_debug(); // (Round-17, Task 1 corroboration) zeroes our injected noise so the // sweep's measured correlation can be checked against the @@ -219,6 +227,12 @@ pub fn adjust( // touching the transmitted noise ENERGY bookkeeping above (only the // actual PCM addition is skipped). let zero_noise = std::env::var("EC_AAC_SBR_NOISE_ZERO").is_ok(); + // (Round-22 sweep instrumentation, zero cost unset) `EC_AAC_SBR_GAIN_LERP` + // linearly interpolates each envelope's per-band gain toward the NEXT + // envelope's gain across the current envelope's time slots, instead of + // holding it flat -- probing whether our constant-per-cell gain shape + // (vs. the spec's smoother per-slot shape) is a live suspect. + let gain_lerp = std::env::var("EC_AAC_SBR_GAIN_LERP").is_ok(); // Gain toward the transmitted envelope, per (envelope, band) cell, // limited relative to that cell's own noise floor. @@ -314,6 +328,43 @@ pub fn adjust( } } } + // (Round-22 sweep instrumentation) the next envelope's gains, only + // when `EC_AAC_SBR_GAIN_LERP` is set and the band layouts match -- + // `hf` in the next envelope's time range is still untouched at this + // point (envelopes are processed and applied in time order), so + // this reads the same raw HF estimate the next iteration would. + let next_gains: Option> = + if gain_lerp && ei + 1 < env_energy.len() && ei + 2 < ch.t_env.len() { + let (t0n, t1n) = (ch.t_env[ei + 1], ch.t_env[ei + 2]); + let high_res_n = ch.freq_res.get(ei + 1).copied().unwrap_or(0) != 0; + let table_n: &[i64] = if high_res_n { + &tables.f_high + } else { + &tables.f_low + }; + if table_n.len() == table.len() { + let noise_row_n: Option<&Vec> = ch + .t_noise + .windows(2) + .position(|w| t0n >= w[0] && t0n < w[1]) + .and_then(|ni| noise_energy.get(ni)); + Some(compute_gains_only( + hf, + tables, + kx, + table_n, + t0n, + t1n, + &env_energy[ei + 1], + noise_row_n, + limiter_max, + )) + } else { + None + } + } else { + None + }; // `bs_interpol_freq` (per-subband linear interpolation of these sfb // gains, Sec 4.6.18.7.6) was tried here: a centre-frequency lerp // between neighbouring sfbs' flat gain values, applied whenever @@ -327,10 +378,12 @@ pub fn adjust( // support, ceiling ~0.999 full-band bar; needs the reference // decoder's exact per-subband gain-interpolation formula, not a // plausible reconstruction of it. + let span = (t1 - t0.max(0)).max(1) as f64; for b in 0..table.len().saturating_sub(1) { let lo = table[b] as usize; let hi = table[b + 1] as usize; - let gain = gains[b]; + let base_gain = gains[b]; + let end_gain = next_gains.as_ref().and_then(|ng| ng.get(b).copied()); let namp = noise_amps[b]; for band in lo..hi { if band < kx || band - kx >= hf.len() { @@ -338,6 +391,12 @@ pub fn adjust( } let row = &mut hf[band - kx]; for slot in t0.max(0) as usize..(t1.max(0) as usize).min(row.len()) { + let gain = if let Some(end) = end_gain { + let w = (slot as f64 - t0.max(0) as f64) / span; + base_gain + (end - base_gain) * w.clamp(0.0, 1.0) + } else { + base_gain + }; row[slot] = row[slot].scale(gain); // Consume the RNG unconditionally (matches the pre-round-21 // stream shape) even under EC_AAC_SBR_NOISE_ZERO, which @@ -394,6 +453,54 @@ pub fn adjust( // unrelated unit scales; see the comment at `noise_div` above). } +/// (Round-22 sweep instrumentation) The same gain math the main loop in +/// [`adjust`] computes, minus the tracking/noise-amplitude side effects -- +/// used to look ahead at the NEXT envelope's gain for `EC_AAC_SBR_GAIN_LERP`. +#[allow(clippy::too_many_arguments)] +fn compute_gains_only( + hf: &[Vec>], + tables: &BandTables, + kx: usize, + table: &[i64], + t0: i64, + t1: i64, + env_row: &[f64], + noise_row: Option<&Vec>, + limiter_max: f64, +) -> Vec { + let mut gains = Vec::with_capacity(table.len().saturating_sub(1)); + for b in 0..table.len().saturating_sub(1) { + let lo = table[b] as usize; + let hi = table[b + 1] as usize; + let target = env_row.get(b).copied().unwrap_or(0.0); + let (mut sum, mut count) = (0.0f64, 0usize); + for band in lo..hi { + if band < kx || band - kx >= hf.len() { + continue; + } + let row = &hf[band - kx]; + for slot in t0.max(0) as usize..(t1.max(0) as usize).min(row.len()) { + sum += row[slot].norm_sqr(); + count += 1; + } + } + let current = if count > 0 { sum / count as f64 } else { 0.0 }; + let q = noise_band_for(tables, lo); + let noise_div = noise_row + .and_then(|r| r.get(q).copied()) + .unwrap_or(0.0) + .max(0.0); + let signal_target = target / (1.0 + noise_div); + let noise_here = target - signal_target; + let cur = current.max(1e-12); + let mut gain = (signal_target / cur).sqrt(); + gain = gain.min(limiter_max * ((noise_here + cur) / cur).sqrt()); + gain = gain.min(limiter_max * 64.0); + gains.push(gain); + } + gains +} + fn noise_band_for(tables: &BandTables, low_band: usize) -> usize { let mut q = 0usize; for i in 0..tables.n_q { diff --git a/crates/ec-aac/src/sbr_hf.rs b/crates/ec-aac/src/sbr_hf.rs index 54a2642c..12f48f52 100644 --- a/crates/ec-aac/src/sbr_hf.rs +++ b/crates/ec-aac/src/sbr_hf.rs @@ -107,19 +107,67 @@ impl ChirpState { /// Advances the state one frame given this frame's `bs_invf_mode` per /// noise band, returning the smoothed bw to use for HF generation. + /// + /// (Round-22 sweep instrumentation, zero cost unset) `EC_AAC_SBR_BW_SCALE` + /// scales `BW_TABLE`'s target globally (clamped below 1.0) before + /// smoothing, to probe whether the chirp/inverse-filter strength is + /// miscalibrated on real content. `EC_AAC_SBR_CHIRP_SMOOTH=none` skips + /// the attack/release smoothing entirely (target used immediately); + /// `=swap` swaps which curve (0.75/0.25 vs 0.90625/0.09375) applies to + /// rising vs falling bw, to probe whether the asymmetry is backwards. pub fn update(&mut self, invf_mode: &[u8]) -> &[f64] { + let scale = bw_scale_override(); + let smooth = chirp_smooth_mode(); for (slot, &mode) in self.bw.iter_mut().zip(invf_mode) { - let target = BW_TABLE[usize::from(mode).min(3)]; - *slot = if target < *slot { - 0.75 * target + 0.25 * *slot - } else { - 0.90625 * *slot + 0.09375 * target + let target = (BW_TABLE[usize::from(mode).min(3)] * scale).min(0.999_999); + *slot = match smooth { + ChirpSmooth::None => target, + ChirpSmooth::Current => { + if target < *slot { + 0.75 * target + 0.25 * *slot + } else { + 0.90625 * *slot + 0.09375 * target + } + } + ChirpSmooth::Swap => { + if target < *slot { + 0.90625 * target + 0.09375 * *slot + } else { + 0.75 * *slot + 0.25 * target + } + } }; } &self.bw } } +/// `EC_AAC_SBR_BW_SCALE` global multiplier on `BW_TABLE`, clamped below 1.0 +/// (a chirp target at or past 1.0 is an undamped all-pole resonance, not a +/// meaningful "stronger" whitening). `1.0` (no-op) when unset or unparsable. +fn bw_scale_override() -> f64 { + std::env::var("EC_AAC_SBR_BW_SCALE") + .ok() + .and_then(|s| s.parse::().ok()) + .map(|s| s.max(0.0)) + .unwrap_or(1.0) +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum ChirpSmooth { + None, + Current, + Swap, +} + +fn chirp_smooth_mode() -> ChirpSmooth { + match std::env::var("EC_AAC_SBR_CHIRP_SMOOTH").as_deref() { + Ok("none") => ChirpSmooth::None, + Ok("swap") => ChirpSmooth::Swap, + _ => ChirpSmooth::Current, + } +} + /// Order-2 covariance-method LPC over `x` (index 0 is the oldest sample): /// solves the 2x2 normal equations minimizing `sum |x[n] - a1*x[n-1] - /// a2*x[n-2]|^2` over `n = 2..x.len()`. Returns `(a1, a2)`; `(0, 0)` if `x` diff --git a/crates/ec-aac/tests/sbr_real_library.rs b/crates/ec-aac/tests/sbr_real_library.rs index 15a9562a..1a8f98f2 100644 --- a/crates/ec-aac/tests/sbr_real_library.rs +++ b/crates/ec-aac/tests/sbr_real_library.rs @@ -1053,7 +1053,17 @@ fn sbr_real_library_matches_reference() { correlation_at_lag(&ours[0], &ours[1], 0), ); } - for (ch, (o, t)) in ours.iter().zip(&theirs).enumerate() { + for (ch, (o_full, t_full)) in ours.iter().zip(&theirs).enumerate() { + // (Round-22 stability check) EC_AAC_SBR_SWEEP_SEGMENT=1 measures + // the second half of the file instead of the first, so a + // calibration candidate can be checked on two disjoint segments + // rather than just the file's start. + let (o, t): (&[f32], &[f32]) = + if std::env::var("EC_AAC_SBR_SWEEP_SEGMENT").as_deref() == Ok("1") { + (&o_full[o_full.len() / 2..], &t_full[t_full.len() / 2..]) + } else { + (&o_full[..], &t_full[..]) + }; let rms = |s: &[f32]| { (s.iter().map(|v| f64::from(*v) * f64::from(*v)).sum::() / s.len().max(1) as f64)