diff --git a/crates/ec-aac/src/sbr_bands.rs b/crates/ec-aac/src/sbr_bands.rs index 739fe1d2..ef2181a1 100644 --- a/crates/ec-aac/src/sbr_bands.rs +++ b/crates/ec-aac/src/sbr_bands.rs @@ -180,6 +180,10 @@ pub struct BandTables { pub f_noise: Vec, pub kx: i64, pub k2: i64, + /// Master table borders (`k0 = f_master[0]`), needed by the patch builder. + pub f_master: Vec, + /// SBR (output) sample rate, the patch builder's `goalSb` input. + pub rate: u32, } /// `rate` is the SBR rate: twice the AAC-LC core's. @@ -236,6 +240,8 @@ pub fn freq_tables( f_noise, kx, k2, + f_master: master.clone(), + rate, }) } diff --git a/crates/ec-aac/src/sbr_chain.rs b/crates/ec-aac/src/sbr_chain.rs index e06b73b3..44fb7d29 100644 --- a/crates/ec-aac/src/sbr_chain.rs +++ b/crates/ec-aac/src/sbr_chain.rs @@ -4,7 +4,7 @@ //! PCM through 32-band analysis, generate and adjust the HF region, and //! resynthesize through the 64-band bank to double-rate PCM in place. -use crate::sbr_env::{self, NoiseGen}; +use crate::sbr_env::{self, AdjustState}; use crate::sbr_hf::{self, ChirpState, HfHistory}; use crate::sbr_payload::{SbrChannel, SbrData, SbrParser}; use crate::sbr_qmf::{ANALYSIS_BANDS, Analysis, SYNTHESIS_BANDS, Synthesis}; @@ -181,17 +181,32 @@ struct ChannelState { synthesis: Synthesis, hf_hist: HfHistory, chirp: ChirpState, - noise: NoiseGen, + adj: AdjustState, + /// §4.6.18.7.6 `tHFAdj`/overlap buffers: the SBR output lags the raw + /// analysis by `HF_ADJ` slots, so the previous frame's last `HF_ADJ` + /// raw low-band and raw HF slots are kept, plus the already-adjusted HF + /// slots past the frame end that a variable-border envelope produced + /// (`Y` of slots `32..2*t_E(L_E)`), which lead the next frame's output. + low_tail: Vec<[Complex; ANALYSIS_BANDS]>, + hf_tail: Vec>>, + y_carry: Vec>>, } +/// Slots by which the HF adjuster's envelope grid lags the raw QMF frame +/// (`tHFAdj` + the 6-slot overlap, §4.6.18.7.6 / Figure 4.32). +const HF_ADJ: usize = 6; + impl ChannelState { - fn new(n_q: usize, seed: u32) -> ChannelState { + fn new(n_q: usize, _seed: u32) -> ChannelState { ChannelState { analysis: Analysis::new(), synthesis: Synthesis::new(), hf_hist: HfHistory::new(ANALYSIS_BANDS), chirp: ChirpState::new(n_q.max(1)), - noise: NoiseGen::new(seed), + adj: AdjustState::new(), + low_tail: vec![[Complex::ZERO; ANALYSIS_BANDS]; HF_ADJ], + hf_tail: Vec::new(), + y_carry: Vec::new(), } } } @@ -209,6 +224,8 @@ struct Element { /// half length -- which otherwise permanently shifts every sample after /// it out of alignment with a reference that stayed at full rate. last_data: Option, + /// Header of the previous applied frame: a change is the spec's reset. + last_header: Option, } /// Every configured SBR element in a stream, keyed by @@ -240,6 +257,7 @@ impl SbrChain { parser: SbrParser::new(self.rate), channels: Vec::new(), last_data: None, + last_header: None, }); let data = elem.parser.parse(r, is_cpe).ok()?; let n_q = elem.parser.tables().map(|t| t.n_q).unwrap_or(1); @@ -294,6 +312,8 @@ impl SbrChain { let Some(tables) = elem.parser.tables().cloned() else { return; }; + let reset = elem.last_header.as_ref() != elem.parser.header(); + elem.last_header = elem.parser.header().cloned(); let Some(header) = elem.parser.header().cloned() else { return; }; @@ -411,7 +431,7 @@ impl SbrChain { if qmfdump_on { qmfdump_energies("analysis", 0, &low_cur); } - let mut hf = sbr_hf::generate( + let hf = sbr_hf::generate( &low_cur, &tables, &sbr_ch.invf_mode, @@ -430,25 +450,64 @@ impl SbrChain { t_noise: sbr_ch.t_noise.iter().map(|&t| t * RATE).collect(), ..sbr_ch.clone() }; - // Same deterministic `build_patches(&tables)` call `generate` - // makes internally -- cheap to recompute here so the limiter - // band table (patch boundaries + f_low, Sec 4.6.18.7.2) can be - // built without threading patches out of `generate`'s signature. let limiter_table = sbr_hf::limiter_band_table( &tables, &sbr_hf::build_patches(&tables), header.limiter_bands, ); + // Envelope slot i is raw slot i - HF_ADJ: prepend the previous + // frame's raw HF tail so the grid (up to 2*t_E(L_E) <= 38) lines + // up with the content it was measured on (§4.6.18.7.6). + let m_max = hf.len(); + if state.hf_tail.len() != m_max || reset { + state.hf_tail = vec![vec![Complex::ZERO; HF_ADJ]; m_max]; + state.y_carry.clear(); + } + let mut xh: Vec>> = (0..m_max) + .map(|m| { + let mut v = state.hf_tail[m].clone(); + v.extend_from_slice(&hf[m]); + v + }) + .collect(); + for m in 0..m_max { + state.hf_tail[m] = hf[m][num_slots.saturating_sub(HF_ADJ)..].to_vec(); + } sbr_env::adjust( - &mut hf, + &mut xh, &tables, &header, &scaled, &env_energy, &noise_energy, - &mut state.noise, &limiter_table, + &mut state.adj, + reset, ); + // Output slot i: low band from the delayed raw analysis, HF from + // the previous frame's carried-over adjusted slots first, then + // this frame's; slots past the frame end are carried forward. + let i_temp = state.y_carry.first().map(Vec::len).unwrap_or(0).min(num_slots); + let t_end = (scaled.t_env.last().copied().unwrap_or(0).max(0) as usize).min(xh[0].len()); + let mut hf: Vec>> = vec![vec![Complex::ZERO; num_slots]; m_max]; + for m in 0..m_max { + for i in 0..i_temp { + hf[m][i] = state.y_carry[m][i]; + } + for i in i_temp..num_slots { + hf[m][i] = xh[m][i]; + } + } + state.y_carry = (0..m_max) + .map(|m| xh[m][num_slots.min(t_end)..t_end].to_vec()) + .collect(); + let raw: Vec<[Complex; ANALYSIS_BANDS]> = { + let mut d = state.low_tail.clone(); + d.extend_from_slice(&raw); + state.low_tail = d[d.len() - HF_ADJ..].to_vec(); + d.truncate(num_slots); + d + }; if qmfdump_on { qmfdump_energies("post_adjust", tables.kx as usize, &hf); } @@ -468,7 +527,10 @@ impl SbrChain { } let mut pcm = state.synthesis.process_slot(&v); for s in &mut pcm { - *s *= crate::decode::OUTPUT_SCALE; + // The spec 32-analysis/64-synthesis pair (4.6.18.4.1 + + // 4.6.18.8.2, literal equations) reads back at half the + // core's amplitude; the 2x is the upsampler's gain. + *s *= 2.0 * crate::decode::OUTPUT_SCALE; } out.extend_from_slice(&pcm); } @@ -528,6 +590,8 @@ mod tests { add_harmonic: None, df_env: vec![], df_noise: vec![], + l_a: -1, + amp_res: 1, } } @@ -551,6 +615,7 @@ mod tests { parser: SbrParser::new(44100), channels: vec![ChannelState::new(n_q, 1), ChannelState::new(n_q, 2)], last_data: None, + last_header: None, }, ); chain @@ -650,6 +715,7 @@ mod tests { .map(|i| ChannelState::new(n_q, 10 + i as u32)) .collect(), last_data: None, + last_header: None, }, ); chain @@ -694,6 +760,7 @@ mod tests { parser: SbrParser::new(44100), channels: vec![ChannelState::new(n_q, 10)], last_data: None, + last_header: None, }, ); reference diff --git a/crates/ec-aac/src/sbr_env.rs b/crates/ec-aac/src/sbr_env.rs index 11dd4a8b..0f01f483 100644 --- a/crates/ec-aac/src/sbr_env.rs +++ b/crates/ec-aac/src/sbr_env.rs @@ -1,50 +1,23 @@ -//! SBR envelope adjustment (ISO/IEC 14496-3 §4.6.18.7): scales the raw HF -//! QMF estimate [`crate::sbr_hf::generate`] produced so each transmitted -//! (envelope, band) cell carries the energy the encoder actually measured, -//! injects the transmitted noise floor, and adds sinusoids at the bands -//! `bs_add_harmonic` flags. +//! SBR envelope adjustment (ISO/IEC 14496-3 §4.6.18.7): dequantisation, +//! mapping, E_curr estimation, gain/limiter/boost calculation and HF +//! assembly, written formula-for-formula against §4.6.18.7.2-7.6. //! -//! # Dequantization +//! Everything below `adjust` works per QMF subband `m = k - kx` +//! (`0..m_max`) and per QMF slot, as the spec does: envelope/noise data is +//! mapped onto subbands first (`E_origMapped`, `Q_mapped`, `S_mapped`, +//! `S_indexMapped`), gains are computed per subband, the limiter works on +//! subband sums per limiter band, and the smoothing filter runs over the +//! previous four QMF SLOTS' gain vectors (carried across frames). //! -//! A plain (non-coupled) envelope's linear energy is `2^(alpha * e_q)` -//! with `alpha = 1.0` at `bs_amp_res = 1` (3 dB steps) and `0.5` at -//! `bs_amp_res = 0` (1.5 dB steps); the noise floor is `2^(6 - q_q)` -//! (`NOISE_FLOOR_OFFSET = 6`). A coupled CPE's balance channel (`e_q`'s -//! second channel) carries a log-ratio (`pan`) rather than an absolute -//! scalefactor; `dequant_pair` de-mixes it against channel 0's raw value -//! into `(env0, env1)` energies that are equal (and each equal to channel -//! 0's plain energy) when the ratio is centred (ISO/IEC 14496-3 -//! §4.6.18.7.2): `ratio = 2^(pan - panOffset)`, `panOffset = 24` at -//! `bs_amp_res=0` and `12` at `bs_amp_res=1`, `env0 = 2*Ecurr/(1+ratio)`, -//! `env1 = 2*Ecurr*ratio/(1+ratio)`. A real coupled-CPE fixture -//! (`heaac_44100_48k.m4a`, `coupled_cpe_channel_swap_probe`) settled this: -//! its transmitted balance raw values cluster at 12 under `bs_amp_res=1`, -//! matching a centred pan at `panOffset=12` exactly, and only this -//! `ratio` shape (not the previous `2*alpha*raw - 12` exponent) plus -//! keeping `env0`/`env1` on their own physical channel (not swapped -//! into a `left`/`right` naming) reproduces the reference decoder's L/R -//! assignment on that file. -//! -//! # Gain, limiter, noise, sinusoids -//! -//! For every `(envelope, band)` cell this measures the HF estimate's own -//! average energy over that time/frequency window; the cell's envelope -//! target is split into a signal share and a noise share via the cell's -//! `Q_div = dequant_noise(q_q)` ratio (`signal = target/(1+Q_div)`, -//! `noise = target*Q_div/(1+Q_div)`, round-21 -- `Q_div` is a ratio -//! relative to the envelope target, not a standalone absolute energy), the -//! HF estimate is scaled toward the signal share; the limiter then caps -//! every cell's gain against its LIMITER BAND's aggregate headroom (Sec -//! 4.6.18.7.2/.7.5, `bs_limiter_gains`, `crate::sbr_hf::limiter_band_table`) -//! rather than each cell's own -- a content-empty cell has zero raw energy, -//! so a per-cell cap is infinite exactly where it should bite; the -//! aggregate cap and its gain-boost compensation (Sec 4.6.18.7.4) are -//! applied to gains, injected noise and sinusoids alike. The noise share is -//! mixed in at that level, and flagged bands get an added tone. +//! Slot indexing: `hf[m][i]` is `X_high(k, i + tHFAdj)`, i.e. slot `i` is the +//! one envelope border `2*t_E` counts -- the caller supplies a buffer long +//! enough for `2*t_E(L_E)` (up to 38 slots: 32 of this frame plus the +//! 6-slot overlap the variable frame classes may reach into). #![allow(clippy::needless_range_loop)] use crate::sbr_bands::BandTables; use crate::sbr_payload::{SbrChannel, SbrHeader}; +use crate::sbr_tables::SBR_NOISE; use ec_dsp::Complex; const NOISE_FLOOR_OFFSET: f64 = 6.0; @@ -57,55 +30,50 @@ fn alpha(amp_res: u8) -> f64 { if amp_res != 0 { 1.0 } else { 0.5 } } -/// Plain (non-coupled) envelope dequantization. +/// Plain (non-coupled) envelope dequantization: `E_Orig = 2^(E_Q * a) * 64` +/// (§4.6.18.7.2), in the spec 32-band analysis domain `sbr_qmf::Analysis` +/// now produces directly. pub fn dequant_env(e_q: i32, amp_res: u8) -> f64 { - 2f64.powf(alpha(amp_res) * f64::from(e_q)) + 2f64.powf(alpha(amp_res) * f64::from(e_q)) * 64.0 } -/// Plain noise-floor dequantization: `Q_div = 2^(NOISE_FLOOR_OFFSET-q_q)`, a -/// ratio relative to the ENVELOPE energy of the same (time, band) cell, not -/// an absolute energy on its own (round-21: `adjust` splits each cell's -/// envelope target into `signal = target/(1+Q_div)` and -/// `noise = target*Q_div/(1+Q_div)`; using this return value as a -/// standalone absolute energy, as pre-round-21 code did, compares it -/// against `dequant_env`'s unrelated unit scale). +/// Plain noise-floor dequantization: `Q_Orig = 2^(NOISE_FLOOR_OFFSET - Q_Q)`, +/// a ratio against the same cell's envelope energy (§4.6.18.7.2). pub fn dequant_noise(q_q: i32) -> f64 { 2f64.powf(NOISE_FLOOR_OFFSET - f64::from(q_q)) } /// De-mixes a coupled CPE's `(channel 0 raw, balance raw)` pair into /// `(env0, env1)` linear energies (ISO/IEC 14496-3 §4.6.18.7.2, -/// `bs_coupling`): `Ecurr = dequant_env(e0_raw, amp_res)`, -/// `ratio = 2^(pan - panOffset)` where `pan` is the RAW balance value -/// (channels[1]'s `e_q`, not run through `alpha`/`amp_res` scaling) and -/// `panOffset` is 24 at `bs_amp_res=0` (1.5 dB steps) or 12 at -/// `bs_amp_res=1` (3 dB steps); `env0 = 2*Ecurr/(1+ratio)`, -/// `env1 = 2*Ecurr*ratio/(1+ratio)`. The previous `2*alpha*raw - 12` -/// exponent (doubling the step at `amp_res=1` and using the wrong offset -/// at `amp_res=0`), combined with a `left`/`right` naming below that -/// handed physical channel 0 the `env1` shape and channel 1 the `env0` -/// shape, together produced a real-file coupled-CPE L/R swap -/// (`coupled_cpe_channel_swap_probe`, ch0 correlated 0.98 against the -/// REFERENCE's right channel, not its left). This stream's live balance -/// raw values cluster at 12 (`amp_res=1`), matching a centred pan at -/// `panOffset=12` exactly, confirming the offset direction empirically. -/// `env_amp_res` scales `e0_raw` (forced to 0/1.5 dB on a single-envelope -/// frame, mirroring `sbr_payload`'s own `amp_res_of`); `header_amp_res` is -/// the SBR header's transmitted `bs_amp_res` field UNCONDITIONALLY, which -/// governs `panOffset` regardless of the single-envelope override -- the -/// two diverge on single-envelope coupled frames. -pub fn dequant_pair(e0_raw: i32, pan_raw: i32, env_amp_res: u8, header_amp_res: u8) -> (f64, f64) { - let e_curr = dequant_env(e0_raw, env_amp_res); - let pan_offset = if header_amp_res != 0 { 12.0 } else { 24.0 }; - let ratio = 2f64.powf(f64::from(pan_raw) - pan_offset); - let env0 = 2.0 * e_curr / (1.0 + ratio); - let env1 = 2.0 * e_curr * ratio / (1.0 + ratio); - (env0, env1) +/// `bs_coupling`): `E = 2^(a*e0_raw + 7)`, `r = 2^(a*(panOffset - 2*pan))` +/// with `a` = 1 (3 dB) or 0.5 (1.5 dB) and `panOffset` = 12 / 24 for the +/// FRAME's amp_res (the FIXFIX single-envelope override included); +/// `env0 = E/(1+r)`, `env1 = env0*r`. The balance channel's raw values +/// (and its Huffman deltas) count in DOUBLE steps -- `bs_data_env` is one +/// bit narrower than the level field -- so its centre is 6 (3 dB) / 12 +/// (1.5 dB) in raw units; measured on a real coupled stream, where 88% of +/// the raw balance values sit exactly on that centre. +pub fn dequant_pair(e0_raw: i32, pan_raw: i32, amp_res: u8) -> (f64, f64) { + let a = alpha(amp_res); + let pan_offset = if amp_res != 0 { 12.0 } else { 24.0 }; + let ratio = 2f64.powf(a * (pan_offset - 2.0 * f64::from(pan_raw))); + let env0 = 2.0 * dequant_env(e0_raw, amp_res) / (1.0 + ratio); + (env0, env0 * ratio) +} + +/// Coupled noise-floor pair (§4.6.18.7.2): `Q0 = 2^(NOISE_FLOOR_OFFSET - q0 + 1) +/// / (1 + 2^(12 - 2*q1))`, `Q1 = Q0 * 2^(12 - 2*q1)` -- the raw balance +/// value counts in double steps, as for the envelope. +pub fn dequant_noise_pair(q0_raw: i32, pan_raw: i32) -> (f64, f64) { + let temp1 = 2f64.powf(NOISE_FLOOR_OFFSET - f64::from(q0_raw) + 1.0); + let temp2 = 2f64.powf(12.0 - 2.0 * f64::from(pan_raw)); + let q0 = temp1 / (1.0 + temp2); + (q0, q0 * temp2) } /// Dequantizes one channel's envelopes and noise floors for one frame, -/// de-mixing through [`dequant_pair`] when `coupling` makes `channels[1]` -/// a balance channel against `channels[0]`. +/// de-mixing through [`dequant_pair`]/[`dequant_noise_pair`] when +/// `coupling` makes `channels[1]` a balance channel against `channels[0]`. pub fn dequantize_frame( header: &SbrHeader, channels: &[SbrChannel], @@ -113,191 +81,119 @@ pub fn dequantize_frame( coupling: bool, ) -> (Vec>, Vec>) { let c = &channels[ch]; - // A single-envelope frame forces 1.5 dB resolution regardless of - // bs_amp_res, mirroring sbr_payload's own `amp_res_of`. - let amp_res = if c.e_q.len() == 1 { 0 } else { header.amp_res }; - let mut env = Vec::with_capacity(c.e_q.len()); - if coupling && channels.len() == 2 { - for i in 0..c.e_q.len() { - let row0 = channels[0].e_q.get(i); - let row1 = channels[1].e_q.get(i); - let len = c.e_q[i].len(); - let mut r = Vec::with_capacity(len); - for b in 0..len { - let e0 = row0.and_then(|r| r.get(b)).copied().unwrap_or(0); - let pan = row1.and_then(|r| r.get(b)).copied().unwrap_or(0); - let (env0, env1) = dequant_pair(e0, pan, amp_res, header.amp_res); - r.push(if ch == 0 { env0 } else { env1 }); - } - env.push(r); - } + let amp_res = c.amp_res; + let coupled = coupling && channels.len() == 2; + let pick = |pair: (f64, f64)| if ch == 0 { pair.0 } else { pair.1 }; + let env = if coupled { + (0..c.e_q.len()) + .map(|i| { + (0..c.e_q[i].len()) + .map(|b| { + let e0 = channels[0].e_q.get(i).and_then(|r| r.get(b)).copied().unwrap_or(0); + let pan = channels[1].e_q.get(i).and_then(|r| r.get(b)).copied().unwrap_or(0); + pick(dequant_pair(e0, pan, amp_res)) + }) + .collect() + }) + .collect() } else { - for row in &c.e_q { - env.push(row.iter().map(|&v| dequant_env(v, amp_res)).collect()); - } - } - // corner-cut: noise floors dequantize independently per channel - // regardless of coupling. A mirrored dequant_noise_pair() demix (see - // git history) was tried and measured ZERO effect on the real-file - // ch1 RMS blow-up (identical output to printed precision), so the - // energy dequantization below is the live suspect, not this; reverted - // rather than keeping an unverified formula with no measured benefit. - let noise = c - .q_q - .iter() - .map(|row| row.iter().map(|&v| dequant_noise(v)).collect()) - .collect(); + c.e_q.iter().map(|row| row.iter().map(|&v| dequant_env(v, amp_res)).collect()).collect() + }; + let noise = if coupled { + (0..c.q_q.len()) + .map(|i| { + (0..c.q_q[i].len()) + .map(|b| { + let q0 = channels[0].q_q.get(i).and_then(|r| r.get(b)).copied().unwrap_or(0); + let pan = channels[1].q_q.get(i).and_then(|r| r.get(b)).copied().unwrap_or(0); + pick(dequant_noise_pair(q0, pan)) + }) + .collect() + }) + .collect() + } else { + c.q_q.iter().map(|row| row.iter().map(|&v| dequant_noise(v)).collect()).collect() + }; (env, noise) } -/// 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 { - 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>, +/// Limiter gain ceilings, `bs_limiter_gains` 0..3 (§4.6.18.7.5, Table 4.150): +/// -3 dB, 0 dB, +3 dB, off. +const LIMITER_FACTOR: [f64; 4] = [0.70795, 1.0, 1.41254, 1.0e10]; +const GAIN_MAX_CLIP: f64 = 1.0e5; +const BOOST_MAX: f64 = 1.584_893_192; +const H_SMOOTH: [f64; 5] = [ + 0.333_333_333_333_33, + 0.301_502_832_395_82, + 0.218_169_499_062_49, + 0.115_163_834_270_84, + 0.031_830_500_937_51, +]; +const H_SL: usize = 4; +const EPS: f64 = 1.192_092_9e-7; + +/// Per-channel adjuster state carried across frames (§4.6.18.7.6's +/// `G_Temp`/`Q_Temp` slot history, `f_IndexNoise`, `f_IndexSine`, the +/// previous frame's `S_indexMapped` and its `l_A`). +#[derive(Clone, Debug)] +pub struct AdjustState { + s_index_prev: Vec, + /// Gain/noise vectors of the last `H_SL` slots, oldest first. + g_hist: std::collections::VecDeque>, + q_hist: std::collections::VecDeque>, + index_noise: usize, + index_sine: usize, + /// Previous frame's `l_A == L_E` (the transient envelope continues into + /// this frame's envelope 0 -- `l_Aprev`). + la_prev_at_end: bool, + pub fresh: bool, } -/// (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 { - lcg: seed | 1, - history: std::collections::VecDeque::with_capacity(LOWPASS_TAPS), +impl AdjustState { + pub fn new() -> AdjustState { + AdjustState { + s_index_prev: Vec::new(), + g_hist: std::collections::VecDeque::new(), + q_hist: std::collections::VecDeque::new(), + index_noise: 0, + index_sine: 0, + la_prev_at_end: false, + fresh: true, } } +} - fn next(&mut self) -> f64 { - 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 - // [-0.5, 1.5) with mean +0.5 -- a DC-biased "noise" source, not - // zero-mean. `decode::Noise::next` (same LCG constants) divides by - // the same `1 << 23` but subtracts `1.0`, which correctly centers - // ITS doubled [0,2) range; this generator subtracted the wrong - // 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.lcg >> 8) / f64::from(1u32 << 24) - 0.5 - } - - fn complex_unit(&mut self) -> Complex { - // (Round-41, Task 2) `next()` is uniform on [-0.5, 0.5) (Var = 1/12 - // per component), so a raw `(re, im)` pair has E[|z|^2] = 1/6, not - // 1 -- `adjust` scales this by `namp = sqrt(noise_here)` (round-42: - // no `/width`, `noise_here` is already a per-sample average) - // expecting E[|namp*z|^2] = noise_here, so without this correction - // only ~1/6 of the transmitted noise split was ever actually - // realized in the output. Measured directly (decode reeln twice, - // noise on vs `EC_AAC_SBR_NOISE_ZERO`, per-band output energy delta - // 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) - 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) +impl Default for AdjustState { + fn default() -> Self { + Self::new() } } -// (Round-33) Per-limiter-band aggregate gain factor, ISO/IEC 14496-3 -// §4.6.18.7.2's `bs_limiter_gains` table: -3/0/+3 dB, and index 3 -// ("no limiting") given a very large but finite ceiling so a limiter band -// with zero measured HF energy still can't blow up to a literal infinity. -const LIMITER_FACTOR: [f64; 4] = [0.707_945_78, 1.0, 1.412_537_5, 1.0e10]; - -/// Gain-boost compensation ceiling (+4 dB, §4.6.18.7.4): after the -/// per-limiter-band cap, a band whose achieved energy fell short of its -/// transmitted envelope total is boosted back up, capped here so a band -/// that was capped hard doesn't get fully "un-capped" by the boost step. -const BOOST_MAX: f64 = 1.584_893_2; - -/// (Round-17, Task 1 conviction check) Accumulates transmitted signal vs. -/// noise energy per absolute QMF band across every [`adjust`] call in the -/// process, weighted by how many QMF slots each contributes, when -/// `EC_AAC_SBR_NOISE_FRACTION_DEBUG` is set. [`noise_fraction_table`] reads -/// it back; both are no-ops (empty table) otherwise, so this costs nothing -/// on the normal path. -static NOISE_FRACTION_STATS: std::sync::OnceLock>> = - std::sync::OnceLock::new(); - fn noise_fraction_debug() -> bool { - std::env::var("EC_AAC_SBR_NOISE_FRACTION_DEBUG").is_ok() + std::env::var("EC_AAC_SBR_NOISE_FRACTION").is_ok() } -/// `(band, signal_energy_sum, noise_energy_sum)` for every band that -/// accumulated anything, both sums slot-count-weighted. -pub fn noise_fraction_table() -> Vec<(usize, f64, f64)> { - let Some(stats) = NOISE_FRACTION_STATS.get() else { - return Vec::new(); - }; - stats - .lock() - .unwrap() - .iter() - .enumerate() - .filter(|&(_, &(s, n))| s + n > 0.0) - .map(|(b, &(s, n))| (b, s, n)) - .collect() -} +static NOISE_FRACTION: std::sync::OnceLock>> = + std::sync::OnceLock::new(); -fn accumulate_noise_fraction(band: usize, slots: usize, signal: f64, noise: f64) { - if slots == 0 { - return; - } - let stats = NOISE_FRACTION_STATS.get_or_init(|| std::sync::Mutex::new(vec![(0.0, 0.0); 256])); - let mut g = stats.lock().unwrap(); - if band >= g.len() { - g.resize(band + 1, (0.0, 0.0)); - } - g[band].0 += signal * slots as f64; - g[band].1 += noise * slots as f64; +/// Diagnostic (`EC_AAC_SBR_NOISE_FRACTION`): per absolute QMF band, +/// bookkept `(band, Σ signal energy·slots, Σ noise energy·slots, Σ |Y|² +/// post-adjust)` -- the last column against the first two's sum is the +/// per-subband realised/target energy ratio. +pub fn noise_fraction_table() -> Vec<(usize, f64, f64, f64)> { + let mut out: Vec<(usize, f64, f64, f64)> = NOISE_FRACTION + .get() + .and_then(|m| m.lock().ok()) + .map(|g| g.clone()) + .unwrap_or_default(); + out.sort_by_key(|e| e.0); + out } -/// Applies envelope adjustment in place to `hf` (`[target band 0-based -/// from kx][slot]`, as [`crate::sbr_hf::generate`] returns it): gain -/// toward `env_energy`, the transmitted noise floor from `noise_energy`, -/// and sinusoids at `ch.add_harmonic`'s flagged high-resolution bands. +/// Adjusts `hf` (`[m][slot]`, `m = k - kx`) in place: envelope gains, +/// noise floor and added sinusoids per §4.6.18.7.3-7.6. `ch.t_env`/`t_noise` +/// are in QMF slots (already ×2). `reset` mirrors the spec's header-reset +/// flag (smoothing history primed from the first envelope, indices zeroed). #[allow(clippy::too_many_arguments)] pub fn adjust( hf: &mut [Vec>], @@ -306,549 +202,277 @@ pub fn adjust( ch: &SbrChannel, env_energy: &[Vec], noise_energy: &[Vec], - rng: &mut NoiseGen, limiter_table: &[i64], + state: &mut AdjustState, + reset: bool, ) { let kx = tables.kx as usize; - let n_lim = limiter_table.len().saturating_sub(1).max(1); - // (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 m_max = hf.len(); + let num_env = ch.t_env.len().saturating_sub(1).min(env_energy.len()); + if m_max == 0 || num_env == 0 { + return; + } + let reset = reset || state.fresh || state.s_index_prev.len() != m_max; + state.fresh = false; + if reset { + state.s_index_prev = vec![0; m_max]; + state.index_noise = 0; + state.index_sine = 0; + state.g_hist.clear(); + state.q_hist.clear(); + } 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 - // signal-only ceiling `noise_fraction_table` predicts, without - // 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(); - // (Round-43, Task 1) `EC_AAC_SBR_CELLDUMP=band[,band...]` -- comma list - // of ABSOLUTE QMF band indices (same units as `kx`/`k2`/`f_high`, - // `band_hz = rate/128`, per round-42's fixed test-side mapping) -- dumps - // every (envelope, band) cell whose `[lo,hi)` range covers a listed - // band: target/signal_target/noise_here/measured cur/raw+capped gain/ - // boost/namp/sinusoid amp, and the actually-injected noise energy that - // frame, to stderr. - let celldump: Vec = std::env::var("EC_AAC_SBR_CELLDUMP") - .ok() - .map(|s| s.split(',').filter_map(|t| t.trim().parse().ok()).collect()) - .unwrap_or_default(); - - // Gain toward the transmitted envelope, per (envelope, band) cell, - // limited relative to that cell's own noise floor. - for (ei, (t0, t1)) in ch.t_env.windows(2).map(|w| (w[0], w[1])).enumerate() { - if ei >= env_energy.len() { - break; - } - let high_res = ch.freq_res.get(ei).copied().unwrap_or(0) != 0; - let table = if high_res { - &tables.f_high - } else { - &tables.f_low - }; - // The noise segment covering this envelope's time range (noise - // borders are a coarser subset of the envelope borders sharing the - // same start/end points). - let noise_row: Option<&Vec> = ch - .t_noise - .windows(2) - .position(|w| t0 >= w[0] && t0 < w[1]) - .and_then(|ni| noise_energy.get(ni)); - // Per-sfb gain, computed first and applied afterward (as either a - // flat step per band, or -- Sec 4.6.18.7.6, `bs_interpol_freq` -- - // linearly interpolated across subbands between sfb centre - // frequencies) so both application modes share the exact same gain - // values. - // - // (Round-33) The limiter no longer caps each cell against its OWN - // near-zero raw HF estimate (that cap is infinite exactly where a - // patch left a target band content-empty, Sec 4.6.18.7.5's known - // failure mode for cell-local caps). Instead this is a two-pass - // per-LIMITER-BAND aggregate: pass 1 computes each cell's raw - // (uncapped) gain and accumulates that cell's transmitted/measured - // energy into its limiter band (`limiter_table`, built from - // f_low/patch borders in sbr_hf::limiter_band_table); pass 2 caps - // every cell in a limiter band at that band's AGGREGATE - // `sqrt(E_orig/E_curr)*limgain` ratio, so an empty cell inherits its - // band's cap rather than blowing up alone, then boosts the whole - // band back up (capped at `BOOST_MAX`) to still meet the band's - // transmitted total. - let mut gains = Vec::with_capacity(table.len().saturating_sub(1)); - // (Round-21) Actual per-cell noise energy this envelope/band injects, - // parallel to `gains` -- filled below and consumed by the - // application loop that follows instead of the old separate - // noise-grid pass (see round-21 module doc note). - let mut noise_amps = Vec::with_capacity(table.len().saturating_sub(1)); - let mut cell_current = Vec::with_capacity(table.len().saturating_sub(1)); - let mut cell_noise_here = Vec::with_capacity(table.len().saturating_sub(1)); - let mut cell_lim = Vec::with_capacity(table.len().saturating_sub(1)); - let mut lim_e_orig = vec![0.0f64; n_lim]; - let mut lim_e_curr = vec![0.0f64; n_lim]; - 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_energy[ei].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 limdump = std::env::var("EC_AAC_SBR_CELLDUMP").is_ok(); + let track_fraction = noise_fraction_debug(); + let h_sl = if header.smoothing_mode == 0 { H_SL } else { 0 }; + let l_a = ch.l_a; + let l_a_prev: i64 = if state.la_prev_at_end { 0 } else { -1 }; + let n_lim = limiter_table.len().saturating_sub(1); + + // §4.6.18.7.2 mapping + §4.6.18.7.3 E_curr + §4.6.18.7.5 gains, per env. + let mut gain = vec![vec![0.0f64; m_max]; num_env]; + let mut q_m = vec![vec![0.0f64; m_max]; num_env]; + let mut s_m = vec![vec![0.0f64; m_max]; num_env]; + let mut s_index_prev = state.s_index_prev.clone(); + for e in 0..num_env { + let (t0, t1) = (ch.t_env[e].max(0) as usize, ch.t_env[e + 1].max(0) as usize); + let high_res = ch.freq_res.get(e).copied().unwrap_or(0) != 0; + let table: &[i64] = if high_res { &tables.f_high } else { &tables.f_low }; + let n_bands = table.len().saturating_sub(1); + // E_origMapped + let mut e_orig = vec![0.0f64; m_max]; + for i in 0..n_bands { + let v = env_energy[e].get(i).copied().unwrap_or(0.0); + for k in table[i]..table[i + 1] { + let m = k as usize - kx.min(k as usize); + if k as usize >= kx && m < m_max { + e_orig[m] = v; } } - let current = if count > 0 { sum / count as f64 } else { 0.0 }; - let q = noise_band_for(tables, lo); - // `dequant_noise` returns `Q_div = 2^(NOISE_FLOOR_OFFSET-q_q)`, a - // ratio relative to this cell's OWN envelope target -- not an - // absolute energy in the same units as `target` (round-21 Task - // 1/2: a reference-decoder q_q sweep at a FIXED envelope target - // showed total output power staying nearly flat as q_q swept its - // whole range, the signature of `target` being split - // `signal=target/(1+Q_div)`, `noise=target*Q_div/(1+Q_div)` - // rather than noise being added independently on top of the full - // target -- the previous code used `dequant_noise` as an - // absolute energy standalone, which for real content's near-1e-7 - // apparent "fraction" (round-17) was actually comparing two - // energies in unrelated unit scales, not a genuinely near-zero - // noise contribution). - 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; // = target*noise_div/(1+noise_div) - let cur = current.max(1e-12); - let raw_gain = (signal_target / cur).sqrt(); - let lim_idx = limiter_band_index(limiter_table, lo, hi).min(n_lim - 1); - let width = (hi - lo).max(1) as f64; - // (Round-42, Task 1) `lim_e_orig` conserves the cell's FULL - // transmitted `target` (signal+noise), matching the limiter cap - // and boost pass to the TOTAL energy budget rather than the - // signal share alone -- `lim_e_actual` below is widened to - // match (adds `cell_noise_here` alongside the capped signal - // energy) so the boost's `lim_e_orig/lim_e_actual` ratio - // compares total-to-total. Measured signal-target-only variant - // (both sides restricted to `signal_target`) FIRST and it made - // the realized noise fraction anchor WORSE (0.1325 -> 0.1233 - // whole-HF, moving further from the ~0.38 bookkept split) -- - // this total-conserving variant is the one that holds. - lim_e_orig[lim_idx] += target * width; - lim_e_curr[lim_idx] += cur * width; - cell_current.push(cur); - cell_noise_here.push(noise_here); - cell_lim.push(lim_idx); - gains.push(raw_gain); - if track_fraction { - let slots = (t1.max(0) - t0.max(0)).max(0) as usize; - for band in lo..hi { - if band < kx { - continue; + } + // Q_mapped: noise floor covering this envelope's start. + let nf = usize::from(ch.t_noise.len() > 2 && ch.t_env[e] >= ch.t_noise[1]); + let mut q_mapped = vec![0.0f64; m_max]; + if let Some(row) = noise_energy.get(nf.min(noise_energy.len().saturating_sub(1))) { + for i in 0..tables.n_q.min(tables.f_noise.len().saturating_sub(1)) { + let v = row.get(i).copied().unwrap_or(0.0); + for k in tables.f_noise[i]..tables.f_noise[i + 1] { + if k as usize >= kx && (k as usize - kx) < m_max { + q_mapped[k as usize - kx] = v; } - accumulate_noise_fraction(band, slots, signal_target, noise_here); } } } - // (Round-43, Task 1) `raw_gain` (pre-cap) is about to be overwritten - // in place inside `gains` below; keep an uncapped copy for the - // celldump so its "cap applied?" column can compare against it. - let raw_gains: Vec = if celldump.is_empty() { - Vec::new() + // S_indexMapped (centre subband of each flagged high-res band, from + // l_A on, or carried over from the previous frame) and S_mapped. + let mut s_index = vec![0u8; m_max]; + if let Some(flags) = &ch.add_harmonic { + for i in 0..tables.f_high.len().saturating_sub(1) { + let mid = ((tables.f_high[i] + tables.f_high[i + 1]) >> 1) as usize; + if mid < kx || mid - kx >= m_max { + continue; + } + let on = flags.get(i).copied().unwrap_or(0) != 0; + s_index[mid - kx] = + u8::from(on && ((e as i64) >= l_a || s_index_prev[mid - kx] == 1)); + } + } + let mut s_mapped = vec![false; m_max]; + for i in 0..n_bands { + let lo = (table[i] as usize).max(kx) - kx; + let hi = ((table[i + 1] as usize).max(kx) - kx).min(m_max); + let any = (lo..hi).any(|m| s_index[m] != 0); + for m in lo..hi { + s_mapped[m] = any; + } + } + s_index_prev = s_index.clone(); + // E_curr (§4.6.18.7.3), bs_interpol_freq 1 per subband / 0 per band. + let mut e_curr = vec![0.0f64; m_max]; + let slots = (t1.saturating_sub(t0)).max(1) as f64; + if header.interpol_freq != 0 { + for m in 0..m_max { + let row = &hf[m]; + let sum: f64 = + (t0..t1.min(row.len())).map(|i| row[i].norm_sqr()).sum(); + e_curr[m] = sum / slots; + } } else { - gains.clone() - }; - // Pass 2: per-limiter-band aggregate cap, then per-band boost - // compensation so the band still meets its transmitted total. - let lim_cap: Vec = (0..n_lim) - .map(|j| limiter_max * (lim_e_orig[j] / lim_e_curr[j].max(1e-12)).sqrt()) - .collect(); - let mut lim_e_actual = vec![0.0f64; n_lim]; - let mut lim_capped_count = vec![0usize; n_lim]; - let mut lim_total_count = vec![0usize; n_lim]; - for b in 0..gains.len() { - let j = cell_lim[b]; - lim_total_count[j] += 1; - if gains[b] > lim_cap[j] + 1e-12 { - lim_capped_count[j] += 1; + for i in 0..n_bands { + let lo = (table[i] as usize).max(kx) - kx; + let hi = ((table[i + 1] as usize).max(kx) - kx).min(m_max); + let mut sum = 0.0; + for m in lo..hi { + let row = &hf[m]; + sum += (t0..t1.min(row.len())).map(|i| row[i].norm_sqr()).sum::(); + } + let v = sum / (slots * (hi.saturating_sub(lo)).max(1) as f64); + for m in lo..hi { + e_curr[m] = v; + } } - gains[b] = gains[b].min(lim_cap[j]); - let lo = table[b] as usize; - let hi = table[b + 1] as usize; - let width = (hi - lo).max(1) as f64; - // Total realized energy this cell will carry: the capped - // signal gain applied to the raw HF estimate, PLUS the noise - // share `target` already budgeted for this cell (noise is - // injected independently of `gains`, at `noise_amps` below) -- - // matches `lim_e_orig`'s total-target accounting above. - lim_e_actual[j] += - cell_current[b] * gains[b] * gains[b] * width + cell_noise_here[b] * width; } - let lim_boost: Vec = (0..n_lim) - .map(|j| { - if lim_e_actual[j] > 1e-12 { - (lim_e_orig[j] / lim_e_actual[j]) - .sqrt() - .clamp(1.0, BOOST_MAX) + // Gains, limiter and boost (§4.6.18.7.5), per limiter band. + let delta = !((e as i64) == l_a || (e as i64) == l_a_prev); + let deltaf = if delta { 1.0 } else { 0.0 }; + for j in 0..n_lim { + let lo = (limiter_table[j] as usize).max(kx) - kx; + let hi = ((limiter_table[j + 1] as usize).max(kx) - kx).min(m_max); + if lo >= hi { + continue; + } + for m in lo..hi { + let temp = e_orig[m] / (1.0 + q_mapped[m]); + q_m[e][m] = (temp * q_mapped[m]).sqrt(); + s_m[e][m] = (temp * f64::from(s_index[m])).sqrt(); + gain[e][m] = if !s_mapped[m] { + (e_orig[m] / ((1.0 + e_curr[m]) * (1.0 + q_mapped[m] * deltaf))).sqrt() } else { - 1.0 + (e_orig[m] * q_mapped[m] / ((1.0 + e_curr[m]) * (1.0 + q_mapped[m]))).sqrt() + } + f64::MIN_POSITIVE; + } + let sum_orig: f64 = (lo..hi).map(|m| e_orig[m]).sum(); + let sum_curr: f64 = (lo..hi).map(|m| e_curr[m]).sum(); + let g_max = (limiter_max * ((EPS + sum_orig) / (EPS + sum_curr)).sqrt()).min(GAIN_MAX_CLIP); + let mut capped = 0usize; + for m in lo..hi { + let q_max = q_m[e][m] * g_max / gain[e][m]; + q_m[e][m] = q_m[e][m].min(q_max); + if gain[e][m] > g_max { + capped += 1; } - }) - .collect(); - // (Round-57 audit, ISO/IEC 14496-3 4.6.18.7.5/.7.6) Per-limiter-band - // aggregate dump under `EC_AAC_SBR_CELLDUMP`: the exact quantities - // the spec's two equations operate on (E_orig,mapped/E_curr sums, - // G_max=limGain*sqrt(ratio), capped-cell count, G_boost), one line - // per limiter band per envelope, so the aggregate math can be - // checked directly rather than inferred from individual cells. - if !celldump.is_empty() { - for j in 0..n_lim { + gain[e][m] = gain[e][m].min(g_max); + } + let sum_act: f64 = (lo..hi) + .map(|m| { + e_curr[m] * gain[e][m] * gain[e][m] + + s_m[e][m] * s_m[e][m] + + if delta && s_m[e][m] == 0.0 { q_m[e][m] * q_m[e][m] } else { 0.0 } + }) + .sum(); + let boost = ((EPS + sum_orig) / (EPS + sum_act)).sqrt().min(BOOST_MAX); + for m in lo..hi { + gain[e][m] *= boost; + q_m[e][m] *= boost; + s_m[e][m] *= boost; + } + if limdump { eprintln!( - "LIMDUMP ei={ei} band=[{},{}) limiter_bands={} j={j}/{n_lim} \ - E_orig_mapped={:.6e} E_curr={:.6e} G_max={:.6} capped_cells={}/{} \ - E_actual={:.6e} G_boost={:.6}", - limiter_table.get(j).copied().unwrap_or(-1), - limiter_table.get(j + 1).copied().unwrap_or(-1), + "LIMDUMP ei={e} band=[{},{}) limiter_bands={} j={j}/{n_lim} \ + E_orig_mapped={sum_orig:.6e} E_curr={sum_curr:.6e} G_max={g_max:.6} \ + capped_cells={capped}/{} E_actual={sum_act:.6e} G_boost={boost:.6}", + limiter_table[j], + limiter_table[j + 1], header.limiter_bands, - lim_e_orig[j], - lim_e_curr[j], - lim_cap[j], - lim_capped_count[j], - lim_total_count[j], - lim_e_actual[j], - lim_boost[j], + hi - lo, ); } } - for b in 0..gains.len() { - let j = cell_lim[b]; - gains[b] *= lim_boost[j]; - // (Round-42, Task 1 corollary) `cell_noise_here[b]` is already a - // PER-SAMPLE average energy (same units as `target`/`current` -- - // see `raw_gain = sqrt(signal_target / cur)` just above, which - // treats both sides as per-sample averages without any width - // normalization). Dividing by the cell's QMF-band width here - // (as the pre-round-42 code did) additionally shrank the - // per-sample injected noise variance by `1/width`, on top of - // whatever the sample count already contributes when this same - // amplitude is applied once per (band, slot) below -- worse at - // wider high-frequency sfb cells, matching the measured - // realized-noise-fraction shortfall growing toward the top of - // the band in `EC_AAC_SBR_NOISE_ANCHOR`. - noise_amps.push(cell_noise_here[b].sqrt() * lim_boost[j]); - } - // (Round-43, Task 1) per-cell diagnostic dump for `EC_AAC_SBR_CELLDUMP` - // -- printed before the application loop below so it reflects the - // gain/noise-amplitude values that loop is about to use; the - // actually-injected sample energy (which depends on the RNG draws - // that loop consumes) is measured separately and printed right - // after it, tagged with the same `ei`/band range so the two lines - // pair up by eye. - if !celldump.is_empty() { - for b in 0..table.len().saturating_sub(1) { - let lo = table[b] as usize; - let hi = table[b + 1] as usize; - if !celldump.iter().any(|&cb| cb >= lo && cb < hi) { - continue; - } - let target = env_energy[ei].get(b).copied().unwrap_or(0.0); - let noise_here = cell_noise_here[b]; - let signal_target = target - noise_here; - let cur = cell_current[b]; - let raw_gain = raw_gains[b]; - let lim_idx = cell_lim[b]; - let capped = raw_gain > lim_cap[lim_idx] + 1e-12; - let boost = lim_boost[lim_idx]; - let namp = noise_amps[b]; - // Harmonic flag/amp for any listed band this cell covers - // (checked against the high-res `f_high` grid the sinusoid - // block below uses, regardless of this cell's own - // resolution). - let mut harmonic = None; - if let Some(flags) = &ch.add_harmonic { - for (hb, &on) in flags.iter().enumerate() { - if on == 0 || hb + 1 >= tables.f_high.len() { - continue; - } - let hlo = tables.f_high[hb] as usize; - let hhi = tables.f_high[hb + 1] as usize; - if celldump - .iter() - .any(|&cb| cb >= hlo && cb < hhi && cb >= lo && cb < hi) - { - let e = if high_res { - env_energy[ei].get(hb).copied().unwrap_or(0.0) - } else { - target - }; - let hboost = lim_boost - [limiter_band_index(limiter_table, hlo, hhi).min(n_lim - 1)]; - harmonic = Some((2.0 * e).sqrt() * hboost); - } + if track_fraction { + let tab = NOISE_FRACTION.get_or_init(|| std::sync::Mutex::new(Vec::new())); + if let Ok(mut t) = tab.lock() { + for m in 0..m_max { + let sig = e_orig[m] / (1.0 + q_mapped[m]) * slots; + let noi = e_orig[m] * q_mapped[m] / (1.0 + q_mapped[m]) * slots; + if let Some(row) = t.iter_mut().find(|r| r.0 == m + kx) { + row.1 += sig; + row.2 += noi; + } else { + t.push((m + kx, sig, noi, 0.0)); } } - eprintln!( - "CELLDUMP ei={ei} band[{lo},{hi}) target={target:.6e} \ - signal_target={signal_target:.6e} noise_here={noise_here:.6e} \ - cur={cur:.6e} raw_gain={raw_gain:.6} capped={capped} boost={boost:.6} \ - namp={namp:.6} harmonic_amp={harmonic:?}" - ); } } - // (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 + } + state.s_index_prev = s_index_prev; + state.la_prev_at_end = l_a == num_env as i64; + + // §4.6.18.7.6 assembly: smoothing over the previous H_SL slots, noise + // from the V table, sinusoids with the (-1)^k phase alternation. + if reset || state.g_hist.len() != h_sl { + state.g_hist.clear(); + state.q_hist.clear(); + for _ in 0..h_sl { + state.g_hist.push_back(gain[0].clone()); + state.q_hist.push_back(q_m[0].clone()); + } + } + let phi_sign = if kx & 1 == 1 { -1.0 } else { 1.0 }; + let mut g_filt = vec![0.0f64; m_max]; + let mut q_filt = vec![0.0f64; m_max]; + for e in 0..num_env { + let (t0, t1) = (ch.t_env[e].max(0) as usize, ch.t_env[e + 1].max(0) as usize); + let transient = (e as i64) == l_a || (e as i64) == l_a_prev; + for i in t0..t1 { + if h_sl > 0 && !transient { + for m in 0..m_max { + let mut g = gain[e][m] * H_SMOOTH[0]; + let mut q = q_m[e][m] * H_SMOOTH[0]; + for j in 1..=h_sl { + // g_hist is oldest-first; j=1 is the most recent slot. + g += state.g_hist[h_sl - j][m] * H_SMOOTH[j]; + q += state.q_hist[h_sl - j][m] * H_SMOOTH[j]; + } + g_filt[m] = g; + q_filt[m] = q; } } else { - None + g_filt.copy_from_slice(&gain[e]); + q_filt.copy_from_slice(&q_m[e]); + } + if h_sl > 0 { + state.g_hist.pop_front(); + state.q_hist.pop_front(); + state.g_hist.push_back(gain[e].clone()); + state.q_hist.push_back(q_m[e].clone()); + } + // Sinusoid phase for this slot: f_IndexSine 0..3 -> + // (1,0), (0,phi), (-1,0), (0,-phi), phi alternating per subband. + let (p_re, p_im0) = match state.index_sine { + 0 => (1.0, 0.0), + 1 => (0.0, phi_sign), + 2 => (-1.0, 0.0), + _ => (0.0, -phi_sign), }; - // `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 - // `header.interpol_freq != 0`. Measured effect on the real-file - // sweep was NEGATIVE (reeln ch0 full-band 0.972756 -> 0.960561) - // -- the reference decoder's actual interpolation shape (weighting, - // node placement, or which quantity gets interpolated) differs from - // this naive lerp, so it was reverted rather than shipped as a - // regression; `header.interpol_freq`/`smoothing_mode` remain parsed - // but unapplied. corner-cut: real bs_interpol_freq/smoothing_mode - // 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; - // (Round-43, Task 1) actual injected-noise-sample energy for the - // celldump, summed per listed absolute band (the RNG draws it from - // are only realized inside this loop, unlike everything the print - // block above already knows). - let mut celldump_injected: std::collections::HashMap = - std::collections::HashMap::new(); - let mut celldump_post: std::collections::HashMap = - std::collections::HashMap::new(); - for b in 0..table.len().saturating_sub(1) { - let lo = table[b] as usize; - let hi = table[b + 1] as usize; - 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() { - continue; + let mut p_im = p_im0; + let mut noise_idx = state.index_noise; + for m in 0..m_max { + let row = &mut hf[m]; + if i >= row.len() { + break; } - 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); - if !celldump.is_empty() && celldump.contains(&band) { - let e = celldump_injected.entry(band).or_insert((0.0, 0.0, 0)); - e.1 += row[slot].norm_sqr(); // signal alone, pre-noise - e.2 += 1; - } - // Consume the RNG unconditionally (matches the pre-round-21 - // stream shape) even under EC_AAC_SBR_NOISE_ZERO, which - // only skips the PCM addition, not the bookkeeping. - let n = rng.complex_unit().scale(namp); - if !celldump.is_empty() && celldump.contains(&band) { - let e = celldump_injected.entry(band).or_insert((0.0, 0.0, 0)); - e.0 += n.norm_sqr(); - } - row[slot] = row[slot] + if zero_noise { Complex::ZERO } else { n }; - if !celldump.is_empty() && celldump.contains(&band) { - celldump_post.entry(band).or_insert((0.0, 0)).0 += row[slot].norm_sqr(); - celldump_post.entry(band).or_insert((0.0, 0)).1 += 1; - } + let mut y = row[i].scale(g_filt[m]); + noise_idx = (noise_idx + 1) & 0x1ff; + if s_m[e][m] != 0.0 { + y = y + Complex::new(s_m[e][m] * p_re, s_m[e][m] * p_im); + } else if !transient && !zero_noise { + let (vr, vi) = SBR_NOISE[noise_idx]; + y = y + Complex::new(q_filt[m] * vr, q_filt[m] * vi); } + row[i] = y; + p_im = -p_im; } - } - if !celldump.is_empty() { - for (&band, &(noise_sum, signal_sum, count)) in &celldump_injected { - let (post_sum, post_count) = celldump_post.get(&band).copied().unwrap_or((0.0, 0)); - eprintln!( - "CELLDUMP ei={ei} band={band} actually_injected_noise_energy={:.6e} \ - actual_signal_only_energy={:.6e} post_addition_energy={:.6e} (n={count})", - if count > 0 { - noise_sum / count as f64 - } else { - 0.0 - }, - if count > 0 { - signal_sum / count as f64 - } else { - 0.0 - }, - if post_count > 0 { - post_sum / post_count as f64 - } else { - 0.0 - }, - ); - } - } - - // Sinusoids: one extra tone per flagged high-resolution band, - // added after gain so its amplitude is exact regardless of the - // cell's measured HF energy. - if let Some(flags) = &ch.add_harmonic { - for (b, &on) in flags.iter().enumerate() { - if on == 0 || b + 1 >= tables.f_high.len() { - continue; - } - let lo = tables.f_high[b] as usize; - let hi = tables.f_high[b + 1] as usize; - let e = if high_res { - env_energy[ei].get(b).copied().unwrap_or(0.0) - } else { - // The envelope grid was low-res this frame; approximate - // the harmonic band's share of its low-res parent cell. - let lb = table - .iter() - .position(|&x| x as usize > lo) - .map(|i| i.saturating_sub(1)) - .unwrap_or(0); - env_energy[ei].get(lb).copied().unwrap_or(0.0) - }; - let boost = lim_boost[limiter_band_index(limiter_table, lo, hi).min(n_lim - 1)]; - let amp = (2.0 * e).sqrt() * boost; - for band in lo..hi { - if band < kx || band - kx >= hf.len() { - continue; - } - let row = &mut hf[band - kx]; - for slot in t0.max(0) as usize..(t1.max(0) as usize).min(row.len()) { - row[slot] = row[slot] + Complex::new(amp, 0.0); + if track_fraction { + let tab = NOISE_FRACTION.get_or_init(|| std::sync::Mutex::new(Vec::new())); + if let Ok(mut t) = tab.lock() { + for m in 0..m_max { + if let (Some(row), Some(y)) = + (t.iter_mut().find(|r| r.0 == m + kx), hf[m].get(i)) + { + row.3 += y.norm_sqr(); + } } } } + state.index_noise = (state.index_noise + m_max) & 0x1ff; + state.index_sine = (state.index_sine + 1) & 3; } } - - // (Round-21) Noise is now injected inside the envelope-gain loop above, - // per (envelope, band) cell using each cell's own `signal_target`/ - // `noise_here` split -- the noise grid is coarser than the envelope - // grid but every envelope cell resolves its own noise band via - // `noise_band_for`/`noise_row`, so this covers the same ground the old - // separate noise-grid pass did, consistently with the gain that was - // computed for the same cell (previously the two were split across - // 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 -} - -/// Finds which limiter band (from [`crate::sbr_hf::limiter_band_table`]) -/// a `[lo, hi)` QMF-band cell falls into, by its midpoint. -fn limiter_band_index(limiter_table: &[i64], lo: usize, hi: usize) -> usize { - if limiter_table.len() < 2 { - return 0; - } - let mid = (lo + hi) as i64 / 2; - for j in 0..limiter_table.len() - 1 { - if mid < limiter_table[j + 1] { - return j; - } - } - limiter_table.len() - 2 -} - -fn noise_band_for(tables: &BandTables, low_band: usize) -> usize { - let mut q = 0usize; - for i in 0..tables.n_q { - if (low_band as i64) >= tables.f_noise[i] { - q = i; - } - } - q } #[cfg(test)] @@ -878,240 +502,94 @@ mod tests { } } - #[test] - fn flat_hf_region_reaches_the_stated_envelope_energy() { - let tables = flat_tables(); - let kx = tables.kx as usize; - let k2 = tables.k2 as usize; - let slots = 16usize; - let mut hf = vec![vec![Complex::new(0.1, 0.0); slots]; k2 - kx]; - let ch = SbrChannel { + fn channel(tables: &BandTables, add_harmonic: Option>) -> SbrChannel { + SbrChannel { t_env: vec![0, 16], - freq_res: vec![0], + freq_res: vec![1], t_noise: vec![0, 16], - e_q: vec![vec![]], - q_q: vec![vec![]], + e_q: vec![vec![0; tables.n_high]], + q_q: vec![vec![0; tables.n_q]], invf_mode: vec![], - add_harmonic: None, + add_harmonic, df_env: vec![], df_noise: vec![], - }; - let target = 4.0f64; - let env_energy = vec![vec![target; tables.n_low]]; - let noise_energy = vec![vec![0.0f64; tables.n_q]]; - let mut rng = NoiseGen::new(1); - let lim_table = - limiter_band_table(&tables, &build_patches(&tables), header(1, 3).limiter_bands); - adjust( - &mut hf, - &tables, - &header(1, 3), - &ch, - &env_energy, - &noise_energy, - &mut rng, - &lim_table, - ); - - // Every low-res band's average energy should land close to target. - for b in 0..tables.n_low { - let lo = tables.f_low[b] as usize; - let hi = tables.f_low[b + 1] as usize; - let mut sum = 0.0; - let mut n = 0usize; - for band in lo..hi { - if band < kx { - continue; - } - for slot in 0..slots { - sum += hf[band - kx][slot].norm_sqr(); - n += 1; - } - } - if n == 0 { - continue; - } - let avg = sum / n as f64; - assert!( - (avg - target).abs() / target < 0.05, - "band {b}: avg {avg} vs target {target}" - ); + l_a: -1, + amp_res: 1, } } - /// (Round-41, Task 2) `NoiseGen::complex_unit`'s realized expected - /// squared magnitude must be ~1.0 -- `adjust` scales it by - /// `namp = sqrt(noise_here)` expecting `E[|namp*z|^2] = - /// noise_here`, so anything but ~1.0 here means the injected noise - /// under- or over-realizes the transmitted split regardless of the - /// limiter/boost interaction (measured separately, at the whole-decode - /// level, in `tests/sbr_real_library.rs`'s `sbr_actual_noise_fraction`). - /// Before the `sqrt(6)` fix this read ~1/6. #[test] - fn complex_unit_has_unit_expected_squared_magnitude() { - let mut rng = NoiseGen::new(1); - let n = 200_000; - let mean_sq: f64 = - (0..n).map(|_| rng.complex_unit().norm_sqr()).sum::() / f64::from(n); - assert!( - (mean_sq - 1.0).abs() < 0.02, - "E[|complex_unit()|^2] = {mean_sq}, expected ~1.0" - ); - } - - #[test] - fn limiter_stays_finite_on_a_uniformly_starved_band() { - // (Round-33 semantics change) A UNIFORMLY near-silent HF estimate - // against a huge uniform target is no longer expected to be capped - // down near the raw HF amplitude -- the aggregate cap and its - // gain-boost compensation are computed from the SAME population, so - // when every cell in a limiter band is equally starved (no - // disproportion for the limiter to actually correct), full recovery - // toward the transmitted target is the spec-correct outcome (boost - // undoes exactly what the cap took away, as long as the needed - // `1/limiter_max` stays under `BOOST_MAX`). What must NOT happen - // (the actual pre-fix bug) is a literal unbounded/non-finite blow-up - // -- this asserts finiteness and a generous bound around the target - // amplitude, not the old (now-wrong) "stays near the raw estimate" - // shape. + fn flat_hf_region_reaches_the_stated_envelope_energy() { let tables = flat_tables(); - let kx = tables.kx as usize; - let k2 = tables.k2 as usize; + let (kx, k2) = (tables.kx as usize, tables.k2 as usize); let slots = 16usize; - let mut hf = vec![vec![Complex::new(1e-9, 0.0); slots]; k2 - kx]; - let ch = SbrChannel { - t_env: vec![0, 16], - freq_res: vec![0], - t_noise: vec![0, 16], - e_q: vec![vec![]], - q_q: vec![vec![]], - invf_mode: vec![], - add_harmonic: None, - df_env: vec![], - df_noise: vec![], - }; - let env_energy = vec![vec![1.0e6f64; tables.n_low]]; - // (Round-21) noise_energy is now a Q_div ratio against the cell's - // own envelope target, not a standalone absolute energy -- zero - // keeps this test focused on the signal-gain limiter it names, not - // noise injection. - let noise_energy = vec![vec![0.0f64; tables.n_q]]; - let mut rng = NoiseGen::new(1); - let lim_table = - limiter_band_table(&tables, &build_patches(&tables), header(1, 0).limiter_bands); - adjust( - &mut hf, - &tables, - &header(1, 0), - &ch, - &env_energy, - &noise_energy, - &mut rng, - &lim_table, - ); - let target_amp = 1.0e6f64.sqrt(); // ~1000, the envelope's own amplitude scale - for band in 0..hf.len() { - for slot in 0..slots { - let amp = hf[band][slot].norm_sqr().sqrt(); - assert!( - amp.is_finite() && amp < 10.0 * target_amp, - "gain escaped to a non-finite/unbounded value at band {band} slot {slot}: {:?}", - hf[band][slot] - ); - } + let mut hf = vec![vec![Complex::new(0.1, 0.0); slots]; k2 - kx]; + let target = 4.0f64; + let env_energy = vec![vec![target; tables.n_high]]; + // Q_mapped = 1 (q_q = 6): half the target is noise. + let noise_energy = vec![vec![1.0f64; tables.n_q]]; + let hdr = header(1, 3); + let lim = limiter_band_table(&tables, &build_patches(&tables), hdr.limiter_bands); + let mut st = AdjustState::new(); + adjust(&mut hf, &tables, &hdr, &channel(&tables, None), &env_energy, &noise_energy, &lim, &mut st, true); + for m in 0..k2 - kx { + let avg: f64 = hf[m].iter().map(|c| c.norm_sqr()).sum::() / slots as f64; + // signal share exactly target/2 (flat input, G cancels E_curr); + // noise share target/2 in expectation over the V table. + assert!((avg - target).abs() / target < 0.4, "m={m}: avg {avg} vs target {target}"); } } #[test] - fn a_content_empty_cell_inherits_its_limiter_bands_aggregate_cap() { - // (Round-33) One low-res band has real HF content, its neighbour is - // perfectly silent (current=0, the exact case a per-cell cap makes - // infinite -- round-33's convicted mechanism). Both fall in the - // same limiter_bands=0 (single aggregate band) table here, so the - // silent cell must be capped by the AGGREGATE ratio (dominated by - // the loud cell's huge current), not blown up on its own. + fn sinusoid_lands_on_the_centre_subband_only_and_mutes_noise_there() { let tables = flat_tables(); - let kx = tables.kx as usize; - let k2 = tables.k2 as usize; + let (kx, k2) = (tables.kx as usize, tables.k2 as usize); let slots = 16usize; - let mut hf = vec![vec![Complex::new(0.1, 0.0); slots]; k2 - kx]; - // Silence the top half of the HF region (the empty target cell). - let mid = hf.len() / 2; - for row in &mut hf[mid..] { - for c in row.iter_mut() { - *c = Complex::ZERO; - } - } - let ch = SbrChannel { - t_env: vec![0, 16], - freq_res: vec![0], - t_noise: vec![0, 16], - e_q: vec![vec![]], - q_q: vec![vec![]], - invf_mode: vec![], - add_harmonic: None, - df_env: vec![], - df_noise: vec![], - }; - let target = 4.0f64; - let env_energy = vec![vec![target; tables.n_low]]; + let mut hf = vec![vec![Complex::ZERO; slots]; k2 - kx]; + let mut flags = vec![0u8; tables.n_high]; + flags[1] = 1; + let env_energy = vec![vec![4.0f64; tables.n_high]]; let noise_energy = vec![vec![0.0f64; tables.n_q]]; - let mut rng = NoiseGen::new(1); - let mut h = header(1, 1); - h.limiter_bands = 0; // single aggregate band spanning the whole HF region - let lim_table = limiter_band_table(&tables, &build_patches(&tables), h.limiter_bands); - assert_eq!(lim_table, vec![tables.kx, tables.k2]); - adjust( - &mut hf, - &tables, - &h, - &ch, - &env_energy, - &noise_energy, - &mut rng, - &lim_table, - ); - // The previously-silent cells must stay bounded (not blown up to - // the old per-cell `limiter_max*64` absolute ceiling on a target of - // 4.0 -- they should land well under it, inheriting the band's - // aggregate cap instead). - for row in &hf[mid..] { - for c in row { - assert!( - c.norm_sqr() < target * 4.0, - "empty cell escaped its limiter band's aggregate cap: {c:?}" - ); + let hdr = header(1, 1); + let lim = limiter_band_table(&tables, &build_patches(&tables), hdr.limiter_bands); + let mut st = AdjustState::new(); + adjust(&mut hf, &tables, &hdr, &channel(&tables, Some(flags)), &env_energy, &noise_energy, &lim, &mut st, true); + let mid = ((tables.f_high[1] + tables.f_high[2]) >> 1) as usize - kx; + for m in 0..k2 - kx { + let e: f64 = hf[m].iter().map(|c| c.norm_sqr()).sum::() / slots as f64; + if m == mid { + // S_M^2 = E_orig/(1+Q) = 4, boost capped at 1.5849^2 at most. + assert!(e >= 4.0 - 1e-9 && e <= 4.0 * BOOST_MAX * BOOST_MAX + 1e-6, "mid {e}"); + // Phase walks 0,90,180,270 degrees per slot. + assert!((hf[m][0].re - hf[m][0].norm_sqr().sqrt()).abs() < 1e-9 && hf[m][1].re.abs() < 1e-9); + } else { + assert!(e < 1e-9, "m={m}: {e}"); } } } #[test] fn coupled_balance_round_trips_at_a_centred_ratio() { - // The ratio's exponent is `pan_raw - panOffset` (ISO/IEC 14496-3 - // §4.6.18.7.2, see the module doc): it's centred (ratio=1) at - // pan_raw=12 for amp_res=1 and pan_raw=24 for amp_res=0. - let (e0, e1) = dequant_pair(10, 12, 1, 1); + let (e0, e1) = dequant_pair(10, 6, 1); let e0_plain = dequant_env(10, 1); - assert!( - (e0 - e0_plain).abs() < 1e-6 && (e1 - e0_plain).abs() < 1e-6, - "{e0} {e1} vs {e0_plain}" - ); - let (e00, e10) = dequant_pair(10, 24, 0, 0); + assert!((e0 - e0_plain).abs() < 1e-6 && (e1 - e0_plain).abs() < 1e-6, "{e0} {e1} vs {e0_plain}"); + let (e00, e10) = dequant_pair(10, 12, 0); let e00_plain = dequant_env(10, 0); - assert!( - (e00 - e00_plain).abs() < 1e-6 && (e10 - e00_plain).abs() < 1e-6, - "{e00} {e10} vs {e00_plain}" - ); + assert!((e00 - e00_plain).abs() < 1e-6 && (e10 - e00_plain).abs() < 1e-6, "{e00} {e10} vs {e00_plain}"); + let (q0, q1) = dequant_noise_pair(3, 6); + assert!((q0 - dequant_noise(3)).abs() < 1e-9 && (q1 - q0).abs() < 1e-9); } #[test] - fn coupled_balance_shifts_energy_toward_the_channel_with_a_higher_raw_value() { - // §4.6.18.7.2: as the raw balance value grows past the centre - // (panOffset), env1 grows toward `2*Ecurr` and env0 shrinks toward - // 0 (env1's formula carries the `ratio` factor, env0's doesn't). - let (e0_low, e1_low) = dequant_pair(10, 0, 1, 1); - let (e0_high, e1_high) = dequant_pair(10, 24, 1, 1); - assert!(e0_low > e1_low, "{e0_low} vs {e1_low}"); - assert!(e0_high < e1_high, "{e0_high} vs {e1_high}"); + fn coupled_balance_shifts_energy_toward_channel_0_with_a_higher_raw_value() { + let (e0_low, e1_low) = dequant_pair(10, 0, 1); + let (e0_high, e1_high) = dequant_pair(10, 12, 1); + assert!(e0_low < e1_low, "{e0_low} vs {e1_low}"); + assert!(e0_high > e1_high, "{e0_high} vs {e1_high}"); + // One raw balance step is two amp_res steps of ratio: 6 dB at + // amp_res 1, 3 dB at amp_res 0. + let (a0, a1) = dequant_pair(10, 5, 1); + let (b0, b1) = dequant_pair(10, 11, 0); + assert!((a1 / a0 - 4.0).abs() < 1e-9 && (b1 / b0 - 2.0).abs() < 1e-9, "{a0} {a1} {b0} {b1}"); } } diff --git a/crates/ec-aac/src/sbr_hf.rs b/crates/ec-aac/src/sbr_hf.rs index 6f3824ab..42189e22 100644 --- a/crates/ec-aac/src/sbr_hf.rs +++ b/crates/ec-aac/src/sbr_hf.rs @@ -124,60 +124,75 @@ pub struct Patch { pub width: usize, } -/// Builds the patch list filling `[tables.kx, tables.k2)` from bands below -/// `kx`, walking the source pointer down and wrapping it back to `kx` when -/// exhausted. Deterministic: the same tables always produce the same patches. +/// Patch construction, ISO/IEC 14496-3 §4.6.18.6.3 (Figure 4.31): source +/// bands are read downward from `k0 = f_master[0]`, patches end on master +/// borders, `goalSb = round(2048 kHz / fs)` bounds the first patch, and a +/// trailing patch narrower than 3 bands is dropped. pub fn build_patches(tables: &BandTables) -> Vec { - let kx = tables.kx as usize; - let k2 = tables.k2 as usize; - let f_high: Vec = tables.f_high.iter().map(|&b| b as usize).collect(); + let kx = tables.kx; + let k2 = tables.k2; + let fm = &tables.f_master; let mut patches = Vec::new(); - if kx == 0 || k2 <= kx { + if kx <= 0 || k2 <= kx || fm.len() < 2 { return patches; } - let mut msb = kx; // source read pointer, decreasing - let mut sb = kx; // target write pointer, increasing - while sb < k2 { - // Widest run of consecutive f_high intervals starting at `sb` whose - // total width still fits below the current source pointer. - let mut width = 0usize; - let mut probe = sb; + let k0 = fm[0]; + let n_master = fm.len() - 1; + let goal_sb = ((1000i64 << 11) + i64::from(tables.rate >> 1)) / i64::from(tables.rate.max(1)); + let mut k = if goal_sb < k2 { + fm.iter().position(|&b| b >= goal_sb).unwrap_or(n_master) + } else { + n_master + }; + let (mut msb, mut usb) = (k0, kx); + let (mut last_k, mut last_msb) = (usize::MAX, i64::MIN); + let mut sb; + loop { + if k == last_k && msb == last_msb { + break; // construction failed; keep what we have + } + last_k = k; + last_msb = msb; + let mut odd = 0i64; + let mut i = k; loop { - let next_border = f_high.iter().find(|&&b| b > probe).copied(); - let Some(border) = next_border else { break }; - let iv = border - probe; - if width + iv > msb || border > k2 { + sb = fm[i]; + odd = (sb + k0) & 1; + if i == 0 || sb <= k0 - 1 + msb - odd { break; } - width += iv; - probe = border; + i -= 1; + } + let width = (sb - usb).max(0); + if width > 0 { + patches.push(Patch { + source_start: (k0 - odd - width).max(0) as usize, + target_start: usb as usize, + width: width as usize, + }); + usb = sb; + msb = sb; + } else { + msb = kx; + } + if fm[k] - sb < 3 { + k = n_master; } - if width == 0 { - width = (k2 - sb).min(msb.max(1)); + if sb == k2 || patches.len() > 6 { + break; } - let source_start = msb - width.min(msb); - patches.push(Patch { - source_start, - target_start: sb, - width, - }); - sb += width; - msb = if source_start == 0 { kx } else { source_start }; + } + if patches.len() > 1 && patches.last().is_some_and(|p| p.width < 3) { + patches.pop(); } patches } -/// Builds the limiter band table (ISO/IEC 14496-3 §4.6.18.7.2): the union -/// of the low-resolution envelope band borders (`tables.f_low`) and the -/// patch target boundaries, thinned so no band is narrower than one -/// limiter band's worth of octaves at the transmitted `bs_limiter_bands` -/// density (`0` => a single band spanning the whole HF region; `1`/`2`/`3` -/// => ~1/2/3 bands per octave, log2-spaced the same way [`f_master`]'s own -/// band construction thins its candidate borders). The limiter's gain cap -/// is applied per band on this table, aggregated over every cell it -/// covers, so a content-empty target cell inherits its band's aggregate -/// cap instead of amplifying numeric dust toward an unbounded per-cell -/// ratio. +/// Builds the limiter band table (ISO/IEC 14496-3 §4.6.18.7.2, Figure 4.33): +/// the union of `f_low` and the patch borders, sorted, then thinned so two +/// borders closer than `0.49/limBands` octaves collapse (`bs_limiter_bands` +/// 1/2/3 => 1.2/2/3 bands per octave), keeping patch borders over +/// envelope borders when one of the pair must go. `0` => one band. pub fn limiter_band_table(tables: &BandTables, patches: &[Patch], limiter_bands: u8) -> Vec { let kx = tables.kx; let k2 = tables.k2; @@ -187,43 +202,50 @@ pub fn limiter_band_table(tables: &BandTables, patches: &[Patch], limiter_bands: if limiter_bands == 0 { return vec![kx, k2]; } - let bands_per_octave = match limiter_bands { - 1 => 1.0, - 2 => 2.0, - _ => 3.0, + let warped = match limiter_bands { + 1 => 2f64.powf(0.49 / 1.2), + 2 => 2f64.powf(0.49 / 2.0), + _ => 2f64.powf(0.49 / 3.0), }; - let mut borders: Vec = tables - .f_low - .iter() - .copied() - .chain(patches.iter().map(|p| p.target_start as i64)) - .chain(std::iter::once(k2)) - .chain(std::iter::once(kx)) - .filter(|&b| b >= kx && b <= k2) - .collect(); - borders.sort_unstable(); - borders.dedup(); - let mut out = vec![borders[0]]; - for &b in &borders[1..] { + let mut patch_borders: Vec = vec![kx]; + for p in patches { + patch_borders.push(patch_borders.last().unwrap() + p.width as i64); + } + let mut table: Vec = tables.f_low.clone(); + table.extend(patch_borders.iter().skip(1).take(patches.len().saturating_sub(1))); + table.sort_unstable(); + let is_patch = |b: i64| patch_borders.contains(&b); + let mut out: Vec = vec![table[0]]; + for &b in &table[1..] { let last = *out.last().unwrap(); - if b <= last { - continue; - } - let octaves = (b as f64 / last as f64).log2(); - if octaves * bands_per_octave < 1.0 && b != k2 { - continue; // too narrow on its own: merges into the current band + if (b as f64) >= (last as f64) * warped { + out.push(b); + } else if b == last || !is_patch(b) { + // drop the incoming border + } else if !is_patch(last) { + *out.last_mut().unwrap() = b; + } else { + out.push(b); } - out.push(b); - } - if *out.last().unwrap() != k2 { - out.push(k2); } out } -/// `bs_invf_mode` bandwidth-expansion targets (OFF, LOW, MID, HIGH), the -/// four inverse-filtering strengths §4.6.18.6.2 defines. -const BW_TABLE: [f64; 4] = [0.0, 0.6, 0.9, 0.98]; +/// `bs_invf_mode` chirp targets per ISO 14496-3 4.6.18.6.3 (Table 4.163): +/// the target depends on the current AND previous frame's mode -- +/// OFF is 0.0 except 0.6 when falling from LOW; LOW is 0.75 except 0.6 +/// when rising from OFF; MID 0.9; HIGH 0.98. The previous flat table +/// (`[0, 0.6, 0.9, 0.98]`) under-whitened every steady-state LOW band. +fn bw_target(mode: u8, prev_mode: u8) -> f64 { + match (mode, prev_mode) { + (0, 1) => 0.6, + (0, _) => 0.0, + (1, 0) => 0.6, + (1, _) => 0.75, + (2, _) => 0.9, + _ => 0.98, + } +} /// Per-noise-band chirp factor state, smoothed frame to frame with a /// fast-attack (toward a *lower* bw, i.e. more whitening) / slow-release @@ -231,18 +253,22 @@ const BW_TABLE: [f64; 4] = [0.0, 0.6, 0.9, 0.98]; #[derive(Clone, Debug)] pub struct ChirpState { bw: Vec, + prev_mode: Vec, } impl ChirpState { pub fn new(n_q: usize) -> ChirpState { - ChirpState { bw: vec![0.0; n_q] } + ChirpState { + bw: vec![0.0; n_q], + prev_mode: vec![0; n_q], + } } /// 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 + /// scales the chirp 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); @@ -251,15 +277,20 @@ impl ChirpState { 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)] * scale).min(0.999_999); + for ((slot, prev), &mode) in self.bw.iter_mut().zip(&mut self.prev_mode).zip(invf_mode) { + let target = (bw_target(mode, *prev) * scale).min(0.999_999); + *prev = mode; *slot = match smooth { ChirpSmooth::None => target, ChirpSmooth::Current => { + // 4.6.18.6.3 bwArray smoothing: both branches weight the + // NEW value (0.75 falling, 0.90625 rising). The rising + // branch previously had the operands swapped (0.09375 + // of the new value), making every rise ~10x too slow. if target < *slot { 0.75 * target + 0.25 * *slot } else { - 0.90625 * *slot + 0.09375 * target + 0.90625 * target + 0.09375 * *slot } } ChirpSmooth::Swap => { @@ -270,12 +301,16 @@ impl ChirpState { } } }; + // 4.6.18.6.3: a smoothed bw under 0.015 is forced to zero. + if *slot < 0.015 { + *slot = 0.0; + } } &self.bw } } -/// `EC_AAC_SBR_BW_SCALE` global multiplier on `BW_TABLE`, clamped below 1.0 +/// `EC_AAC_SBR_BW_SCALE` global multiplier on the chirp target, 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 { @@ -301,95 +336,45 @@ fn chirp_smooth_mode() -> ChirpSmooth { } } -/// 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` -/// is too short or the system is singular (silence or a near-constant -/// subband, both of which need no prediction). -/// (Round-57) AR(2) coefficients via the Yule-Walker/autocorrelation -/// method (`r(k) = sum_n x[n]*conj(x[n-k])`, Hermitian-Toeplitz `R`), -/// replacing the previous unwindowed covariance-method normal-equation -/// solve. The autocorrelation matrix is always positive semi-definite, -/// which is what gives Levinson-Durbin-style AR fits their built-in -/// BIBO-stability guarantee (poles inside or on the unit circle) -- the -/// covariance method has no such guarantee and was measured producing -/// resonant poles that blow `cur` (the raw HF estimate energy) up to -/// 1e7-1e11 against a ~1e4 transmitted target on real content -/// (heaac_48000_64k.m4a's crossover-straddling sweep window), which then -/// poisons the WHOLE limiter band's aggregate `E_curr` (4.6.18.7.5) and -/// crushes every other cell sharing that band's gain cap, not just the -/// outlier cell itself (round-56's stabilize-bound tightening measured -/// zero effect because `raw_gain=sqrt(target/cur)` cancels `cur` exactly -/// for the outlier cell's OWN gain -- it never reaches the neighbors this -/// aggregate-poisoning does). +/// Order-2 linear-prediction coefficients per ISO 14496-3 4.6.18.6.2 +/// (covariance method, `phi(i,j) = sum_n x[n-i]*conj(x[n-j])` over +/// `n = 2..x.len()`, index 0 of `x` is the oldest slot). Returns the spec's +/// `(alpha0, alpha1)` -- the PREDICTION-ERROR filter taps, i.e. the +/// negated predictor coefficients: for `x[n] = a1*x[n-1] + a2*x[n-2] + e` +/// this yields `(-a1, -a2)`, so `x + alpha0*x[n-1] + alpha1*x[n-2]` +/// whitens. `(0, 0)` on degenerate input or when either |alpha| >= 4 +/// (spec guard). Witness: scratch `alpha/witness.py` (numpy) recovers a +/// synthetic complex AR(2) with this sign convention and whitens at bw=1. pub fn lpc2(x: &[Complex]) -> (Complex, Complex) { if x.len() < 3 { return (Complex::ZERO, Complex::ZERO); } - let mut r0 = 0.0f64; - let mut r1 = Complex::ZERO; - let mut r2 = Complex::ZERO; - for n in 0..x.len() { - r0 += x[n].norm_sqr(); - if n >= 1 { - r1 = r1 + x[n] * x[n - 1].conj(); - } - if n >= 2 { - r2 = r2 + x[n] * x[n - 2].conj(); - } - } - // Yule-Walker: [[r0, conj(r1)], [r1, r0]] * [a1, a2]^T = [r1, r2]^T. - let det = r0 * r0 - r1.norm_sqr(); - if det.abs() < 1e-20 { - return (Complex::ZERO, Complex::ZERO); - } - let a1 = (r1.scale(r0) - r1.conj() * r2).scale(1.0 / det); - let a2 = (r2.scale(r0) - r1 * r1).scale(1.0 / det); - (a1, a2) -} - -/// Bounds an AR(2) predictor's coefficients so the resynthesis recursion -/// this module runs (`y = residual + ca1*y[n-1] + ca2*y[n-2]`) cannot -/// diverge. -/// -/// `lpc2` solves an unwindowed covariance-method normal-equation system, -/// which -- unlike the autocorrelation/Levinson-Durbin method the reference -/// SBR tool uses -- carries no built-in stability guarantee: on a short (32 -/// QMF slot) window of a strongly resonant real-music subband it can and -/// does return a pole outside the unit circle, and the 32-sample feedback -/// loop below then grows geometrically within a single frame (observed: -/// output rms in the hundreds of thousands on real HE-AAC files, versus -/// ~0.2 for a working decode). `|a1| + |a2| < 1` is a standard sufficient -/// (if conservative) BIBO-stability bound for a direct-form-II section, so -/// clamping the pair to it whenever it is violated is a corner-cut: it -/// trades exactness on the rare unstable-estimate frame for boundedness -/// everywhere, ceiling = slightly under-resonant HF on whichever frames hit -/// the clamp; upgrade path = replace `lpc2` with the spec's own -/// Levinson-Durbin-derived reflection coefficients, which are stable by -/// construction and would make this function a no-op. -fn stabilize(coeffs: (Complex, Complex)) -> (Complex, Complex) { - let (a1, a2) = coeffs; - let mag = a1.norm_sqr().sqrt() + a2.norm_sqr().sqrt(); - // (Round-56) Tried tightening this bound to 0.9 on the theory that a - // pole at 0.999 gives ~1e6x power resonant gain (`~1/(1-r)^2`), which - // `EC_AAC_SBR_CELLDUMP` traces do show happening (`cur`, the raw - // pre-gain HF estimate, reaching 1e7-1e11 against a ~1e4 transmitted - // target on heaac_48000_64k.m4a's crossover-straddling sweep window, - // in the SAME limiter band as starved neighbor cells) -- measured - // ZERO effect on the t=18s/24s corr cliff (0.054601->0.054536, - // 0.058942->0.058797) or the `EC_AAC_SBR_HF_BYPASS` A/B, because - // `raw_gain = sqrt(target/cur)` cancels `cur` exactly for any - // non-capped cell regardless of this bound's value -- reverted, no - // measured benefit to justify the regression risk on frames that - // legitimately need resonance near this bound. Left at `0.999`. - if mag > 0.999 && mag.is_finite() { - let s = 0.999 / mag; - (a1.scale(s), a2.scale(s)) - } else if mag.is_finite() { - (a1, a2) + let phi = |i: usize, j: usize| -> Complex { + (2..x.len()).fold(Complex::ZERO, |acc, n| acc + x[n - i] * x[n - j].conj()) + }; + let p11 = phi(1, 1).re; + let p22 = phi(2, 2).re; + let p01 = phi(0, 1); + let p02 = phi(0, 2); + let p12 = phi(1, 2); + const EPS: f64 = 1e-6; + let d = p22 * p11 - p12.norm_sqr() / (1.0 + EPS); + let alpha1 = if d.abs() < 1e-30 { + Complex::ZERO } else { - (Complex::ZERO, Complex::ZERO) + (p01 * p12 - p02.scale(p11)).scale(1.0 / d) + }; + let alpha0 = if p11.abs() < 1e-30 { + Complex::ZERO + } else { + (p01 + alpha1 * p12.conj()).scale(-1.0 / p11) + }; + let m0 = alpha0.norm_sqr(); + let m1 = alpha1.norm_sqr(); + if !(m0 < 16.0 && m1 < 16.0) { + return (Complex::ZERO, Complex::ZERO); } + (alpha0, alpha1) } /// Per-source-subband history: the last two QMF slots, carried across @@ -397,15 +382,18 @@ fn stabilize(coeffs: (Complex, Complex)) -> (Complex, Complex; 2]>, - y: Vec<[Complex; 2]>, + /// Last `HIST` slots per source band (4.6.18.6.2's covariance window + /// spans the frame plus the 6 overlap slots before it; the filter + /// itself only taps the last two). + x: Vec<[Complex; HIST]>, } +const HIST: usize = 6; + impl HfHistory { pub fn new(bands: usize) -> HfHistory { HfHistory { - x: vec![[Complex::ZERO; 2]; bands], - y: vec![[Complex::ZERO; 2]; bands], + x: vec![[Complex::ZERO; HIST]; bands], } } } @@ -448,17 +436,15 @@ pub fn generate( continue; } let series = &low_cur[source_band]; - let (a1, a2) = { - let mut ext = Vec::with_capacity(num_slots + 2); + let (alpha0, alpha1) = { + let mut ext = Vec::with_capacity(num_slots + HIST); if source_band < history.x.len() { - ext.push(history.x[source_band][0]); - ext.push(history.x[source_band][1]); + ext.extend_from_slice(&history.x[source_band]); } else { - ext.push(Complex::ZERO); - ext.push(Complex::ZERO); + ext.resize(HIST, Complex::ZERO); } ext.extend_from_slice(series); - stabilize(lpc2(&ext)) + lpc2(&ext) }; let g = bw[noise_band_of(target_band)]; // (Round-46, Task 2) `EC_AAC_SBR_BW_DUMP` -- one line per patched @@ -468,40 +454,35 @@ pub fn generate( if std::env::var("EC_AAC_SBR_BW_DUMP").is_ok() { eprintln!("BW_DUMP target_band={target_band} source_band={source_band} bw={g:.6}"); } - let ca1 = a1.scale(g); - let ca2 = a2.scale(g * g); - let (mut y_prev1, mut y_prev2) = if source_band < history.y.len() { - (history.y[source_band][1], history.y[source_band][0]) - } else { - (Complex::ZERO, Complex::ZERO) - }; + // 4.6.18.6.3 feed-forward: X_high = X_low + bw*alpha0*X_low[l-1] + // + bw^2*alpha1*X_low[l-2]. bw=0 is a plain copy, bw->1 is the + // full inverse (whitening) filter. The all-pole recursion this + // replaced (`y = residual + bw*a1*y[l-1] + bw^2*a2*y[l-2]`) had + // that mapping INVERTED (bw=0 whitened fully, bw=0.98 ~ copy), + // and the earlier feed-forward attempt (8bc305b) used the + // predictor sign (+a) instead of the spec's prediction-error + // sign (-a), which reinforces the resonance instead of + // cancelling it -- hence it measured worse than the inverted + // all-pole form. + let c1 = alpha0.scale(g); + let c2 = alpha1.scale(g * g); let (mut x_prev1, mut x_prev2) = if source_band < history.x.len() { - (history.x[source_band][1], history.x[source_band][0]) + ( + history.x[source_band][HIST - 1], + history.x[source_band][HIST - 2], + ) } else { (Complex::ZERO, Complex::ZERO) }; let dst = &mut out[target_band - kx]; for (n, &x) in series.iter().enumerate() { - let residual = x - a1 * x_prev1 - a2 * x_prev2; - let y = residual + ca1 * y_prev1 + ca2 * y_prev2; // Round-37 (Task 2): `band_shift_correction` is proven exact - // in isolation (a stationary tone replayed through this - // patch-copy site lands within a couple of FFT bins of its - // corrected absolute frequency -- see - // `sbr_qmf::tests::patch_replay_through_generate_preserves_absolute_frequency_mapping`) - // but a real-file mechanical A/B (round-36/37, - // `EC_AAC_SBR_PARITY_SPLIT`) shows applying it REGRESSES - // odd-gap coherence against the reference decoder (ch0 - // 0.1907->0.0714, ch1 0.2461->0.0741; sign-flipped and - // half-rate variants both regress it too, 0.0757/0.1449 resp. - // on ch0). The reference apparently exhibits this bank's own - // "wrong" cross-band placement convention, so matching it is - // the bar: `dst` stays the plain, uncorrected copy. - dst[n] = y; + // in isolation but a real-file A/B (`EC_AAC_SBR_PARITY_SPLIT`) + // shows applying it REGRESSES odd-gap coherence against the + // reference; `dst` stays the uncorrected band placement. + dst[n] = x + c1 * x_prev1 + c2 * x_prev2; x_prev2 = x_prev1; x_prev1 = x; - y_prev2 = y_prev1; - y_prev1 = y; } } } @@ -509,14 +490,12 @@ pub fn generate( // Every source subband's history advances regardless of whether a // patch used it this frame: the low-band QMF stream is continuous. for (band, series) in low_cur.iter().enumerate() { - if band >= history.x.len() || series.len() < 2 { + if band >= history.x.len() { continue; } - let n = series.len(); - history.x[band] = [series[n - 2], series[n - 1]]; - // y-history only meaningfully advances for bands a patch actually - // wrote; untouched bands hold their input as a neutral seed. - history.y[band] = [series[n - 2], series[n - 1]]; + let h = &mut history.x[band]; + let keep: Vec> = h.iter().copied().chain(series.iter().copied()).collect(); + h.copy_from_slice(&keep[keep.len() - HIST..]); } out @@ -579,8 +558,15 @@ mod tests { // previous covariance-method solve) for a stability guarantee real // content needs -- still recovers the synthetic poles to well // within this looser bound. - assert!((fa1 - a1).norm_sqr().sqrt() < 0.2, "a1 {fa1:?} vs {a1:?}"); - assert!((fa2 - a2).norm_sqr().sqrt() < 0.2, "a2 {fa2:?} vs {a2:?}"); + // spec alpha = negated predictor coefficients + assert!( + (fa1 + a1).norm_sqr().sqrt() < 0.2, + "alpha0 {fa1:?} vs {a1:?}" + ); + assert!( + (fa2 + a2).norm_sqr().sqrt() < 0.2, + "alpha1 {fa2:?} vs {a2:?}" + ); } #[test] @@ -589,7 +575,7 @@ mod tests { // Jump from OFF straight to HIGH: attack (rising bw) is the slow // (0.90625/0.09375) branch here since target > current. let after_rise = chirp.update(&[3])[0]; - assert!(after_rise > 0.0 && after_rise < BW_TABLE[3]); + assert!(after_rise > 0.0 && after_rise < 0.98); // Now drop back to OFF: release (falling bw) is the fast // (0.75/0.25) branch, so it should move further in one step than // the rise did. @@ -603,35 +589,8 @@ mod tests { ); } - /// (Round-50) Pins the all-pole residual-resynthesis structure that - /// round-50's real-file A/B empirically favours over the feed-forward - /// FIR round-48 briefly shipped (see the module doc). Both structures - /// were implemented and measured against the reference decoder on real - /// content; this one matched closer, so it is the one pinned here -- - /// the feed-forward alternative's own discriminating test - /// (`feed_forward_extension_matches_bw_endpoints`, commit 8bc305b) is - /// documented history, not dead code to resurrect casually. - /// - /// Drives the same noiseless AR(2) source as that alternative test - /// through two consecutive frames, `x[n] = a1*x[n-1] + a2*x[n-2]` - /// exactly, so `lpc2`'s fit recovers `(a1, a2)` closely enough that the - /// *residual* `x[l] - a1*x[l-1] - a2*x[l-2]` is near zero throughout. - /// That residual, not the raw copy, is what this structure resynthesises - /// through the bandwidth-expanded all-pole recursion `y[l] = residual + - /// ca1*y[l-1] + ca2*y[l-2]` -- the key structural difference from - /// feed-forward, which adds taps onto the copy instead of replacing it - /// with a filtered residual: - /// - `bw=0` (`bs_invf_mode` OFF): `ca1=ca2=0`, so `y = residual ~= 0` -- - /// the output collapses toward silence, NOT the exact plain copy - /// feed-forward produces at this same setting. - /// - `bw~=0.98` (`bs_invf_mode` HIGH): `ca1,ca2` are close to the - /// original `(a1,a2)` (scaled by `bw`, `bw^2`), so with residual~=0 the - /// recursion nearly reproduces the source's own AR(2) resonance from - /// history alone -- output tracks `x` closely in magnitude and phase, - /// not the ~1.98x reinforcement feed-forward produces at the same - /// setting. #[test] - fn all_pole_resynthesis_matches_bw_endpoints() { + fn feed_forward_matches_bw_endpoints() { let tables = real_file_tables(); let kx = tables.kx as usize; let a1 = 0.6f64; @@ -652,7 +611,7 @@ mod tests { let invf_off = vec![0u8; tables.n_q]; let invf_high = vec![3u8; tables.n_q]; - // bw = 0: residual resynthesis collapses toward silence, not a copy. + // bw = 0: exact plain copy (4.6.18.6.3 with both taps zeroed). let mut chirp0 = ChirpState::new(tables.n_q); let mut hist0 = HfHistory::new(kx); let _ = generate(&frame1, &tables, &invf_off, &mut chirp0, &mut hist0); @@ -664,13 +623,13 @@ mod tests { continue; } assert!( - y.re.abs() < 0.1 * expect.abs(), - "bw=0 residual should collapse toward silence at n={n}: {y:?} vs input {expect}" + (y - Complex::new(expect, 0.0)).norm_sqr().sqrt() < 1e-9 * expect.abs().max(1.0), + "bw=0 must copy at n={n}: {y:?} vs input {expect}" ); } - // bw ~= 0.98: residual~=0, so the recursion tracks the source's own - // resonance from history alone -- ratio near 1, not ~1.98. + // bw ~= 0.98: near-full inverse filter of a noiseless AR(2) -> the + // output is close to the (zero) prediction residual, far below x. let mut chirp1 = ChirpState::new(tables.n_q); chirp1.bw = vec![0.0; tables.n_q]; // priming frame at bw=0 let mut hist1 = HfHistory::new(kx); @@ -683,14 +642,9 @@ mod tests { if expect.abs() < 1e-6 { continue; } - let ratio = y.re / expect; - assert!( - (0.5..1.5).contains(&ratio), - "bw=0.98 ratio out of range at n={n}: ratio={ratio} y={y:?} x={expect}" - ); assert!( - y.im.abs() < 0.05 * expect.abs().max(1e-6), - "unexpected imaginary part at n={n}: {y:?}" + y.norm_sqr().sqrt() < 0.15 * expect.abs(), + "bw=0.98 should whiten at n={n}: y={y:?} x={expect}" ); } } diff --git a/crates/ec-aac/src/sbr_payload.rs b/crates/ec-aac/src/sbr_payload.rs index 5df71cfd..6f06442d 100644 --- a/crates/ec-aac/src/sbr_payload.rs +++ b/crates/ec-aac/src/sbr_payload.rs @@ -23,7 +23,7 @@ use ec_core::{BitReader, Error, Result}; const NUM_TIME_SLOTS: i64 = 16; /// `sbr_header()` fields, held across frames: a stream need not repeat it. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq, Eq)] pub struct SbrHeader { pub amp_res: u8, pub start_freq: u8, @@ -60,6 +60,13 @@ pub struct SbrChannel { pub df_env: Vec, /// `bs_df_noise` per noise floor, same convention as `df_env`. pub df_noise: Vec, + /// `l_A` (ISO/IEC 14496-3 §4.6.18.3.3): index of the envelope that starts + /// at the transient border, `-1` when the frame has none. Gates where + /// added sinusoids begin and which envelope skips noise/smoothing. + pub l_a: i64, + /// The frame's effective amp_res: `bs_amp_res`, except a FIXFIX frame + /// with a single envelope is forced to 0 (1.5 dB) -- §4.6.18.3.3. + pub amp_res: u8, } /// One `sbr_data()` frame: one channel for an SCE, two for a CPE. @@ -79,31 +86,43 @@ struct Grid { freq_res: Vec, t_env: Vec, t_noise: Vec, + l_a: i64, + fixfix: bool, } impl Grid { - /// `pointer` is `bs_pointer` (0 for FIXFIX, which has no such field -- - /// the spec's own `bs_pointer == 0` case: the middle noise border is - /// `num_env >> 1`). Per ISO/IEC 14496-3 §4.6.18.3.3: `bs_pointer == 0` - /// selects `num_env >> 1`, `== 1` selects the last envelope border - /// (`num_env - 1`), otherwise `bs_pointer - 1`. - fn new(num_env: usize, freq_res: Vec, t_env: Vec, pointer: usize) -> Grid { + /// `pointer` is `bs_pointer` (0 for FIXFIX, which has no such field). + /// Middle noise border and `l_A` per ISO/IEC 14496-3 §4.6.18.3.3, + /// Tables 4.146/4.147 -- they depend on `frame_class` (0 FIXFIX, + /// 1 FIXVAR, 2 VARFIX, 3 VARVAR), not on `bs_pointer` alone. + fn new(num_env: usize, freq_res: Vec, t_env: Vec, pointer: usize, frame_class: u32) -> Grid { let num_noise = if num_env == 1 { 1 } else { 2 }; let t_noise = if num_noise == 1 { vec![t_env[0], t_env[num_env]] } else { - let middle = match pointer { + let middle = match frame_class { 0 => num_env >> 1, - 1 => num_env - 1, - p => p - 1, + 1 | 3 => num_env - pointer.saturating_sub(1).max(1), + _ => match pointer { + 0 => 1, + 1 => num_env - 1, + p => p - 1, + }, }; - vec![t_env[0], t_env[middle], t_env[num_env]] + vec![t_env[0], t_env[middle.min(num_env)], t_env[num_env]] + }; + let l_a = match frame_class { + 1 | 3 if pointer > 0 => num_env as i64 + 1 - pointer as i64, + 2 if pointer > 1 => pointer as i64 - 1, + _ => -1, }; Grid { num_env, freq_res, t_env, t_noise, + l_a, + fixfix: frame_class == 0, } } } @@ -166,9 +185,43 @@ fn raw_env_width(balance: bool, amp_res: u8) -> u32 { const RAW_NOISE_WIDTH: u32 = 5; /// A FIXFIX frame with a single envelope forces the 1.5 dB resolution -/// regardless of `bs_amp_res` (measured by the table-derivation rig). -fn amp_res_of(header_amp_res: u8, num_env: usize) -> u8 { - if num_env == 1 { 0 } else { header_amp_res } +/// regardless of `bs_amp_res` (§4.6.18.3.3); a one-envelope VARFIX/FIXVAR +/// frame keeps the header's value. +fn amp_res_of(header_amp_res: u8, grid: &Grid) -> u8 { + if grid.fixfix && grid.num_env == 1 { 0 } else { header_amp_res } +} + +/// Delta-time base for an envelope whose frequency resolution differs from +/// the envelope it is coded against (§4.6.18.3.3): a high-res band takes the +/// low-res band containing it, a low-res band the high-res band starting at +/// the same edge. Same resolution (or a degenerate table) passes through. +/// Without this the top half of a high-res row coded against a low-res row +/// read an out-of-range base of 0 -- a near-silent envelope -- and every +/// low-res band read the high-res band of half its frequency. +fn map_prev_env(prev: &[i32], tables: &BandTables, cur_high: bool) -> Vec { + let (n_low, n_high) = (tables.n_low, tables.n_high); + if n_low == n_high || prev.len() == if cur_high { n_high } else { n_low } { + return prev.to_vec(); + } + let (f_low, f_high) = (&tables.f_low, &tables.f_high); + if cur_high { + (0..n_high) + .map(|j| { + let k = (0..n_low) + .rev() + .find(|&k| f_low[k] <= f_high[j]) + .unwrap_or(0); + prev.get(k).copied().unwrap_or(0) + }) + .collect() + } else { + (0..n_low) + .map(|j| { + let k = (0..n_high).find(|&k| f_high[k] == f_low[j]).unwrap_or(0); + prev.get(k).copied().unwrap_or(0) + }) + .collect() + } } /// Reads one Huffman codeword by walking bit-by-bit until it matches a table @@ -237,7 +290,7 @@ impl SbrParser { let t_env: Vec = (0..=num_env) .map(|i| (i as i64) * NUM_TIME_SLOTS / num_env as i64) .collect(); - Ok(Grid::new(num_env, vec![fr; num_env], t_env, 0)) + Ok(Grid::new(num_env, vec![fr; num_env], t_env, 0, 0)) } 1 | 2 => { // FIXVAR (1, trailing variable border) / VARFIX (2, leading variable border) @@ -285,7 +338,7 @@ impl SbrParser { } t[num_env] = NUM_TIME_SLOTS; } - Ok(Grid::new(num_env, freq_res, t, pointer)) + Ok(Grid::new(num_env, freq_res, t, pointer, frame_class)) } _ => { // VARVAR @@ -325,7 +378,7 @@ impl SbrParser { if t.windows(2).any(|w| w[0] >= w[1]) { return Err(Error::corrupt("sbr: non-monotone envelope time borders")); } - Ok(Grid::new(num_env, freq_res, t, pointer)) + Ok(Grid::new(num_env, freq_res, t, pointer, frame_class)) } } } @@ -535,7 +588,7 @@ impl SbrParser { let mut read_env = |this: &mut Self, r: &mut BitReader, ch: usize| -> Result<()> { let balance = is_cpe && coupling && ch == 1; let num_env = grids[ch].num_env; - let amp_res = amp_res_of(header.amp_res, num_env); + let amp_res = amp_res_of(header.amp_res, &grids[ch]); let mut e_q: Vec> = Vec::with_capacity(num_env); for i in 0..num_env { let bands = if grids[ch].freq_res[i] != 0 { @@ -549,7 +602,12 @@ impl SbrParser { } else { &this.state[ch].last_env }; - let row = this.decode_envelope(r, bands, dt, balance, amp_res, prev)?; + let prev = if dt { + map_prev_env(prev, &tables, grids[ch].freq_res[i] != 0) + } else { + Vec::new() + }; + let row = this.decode_envelope(r, bands, dt, balance, amp_res, &prev)?; e_q.push(row); } e_q_all[ch] = e_q; @@ -593,7 +651,7 @@ impl SbrParser { for ch in 0..n_channels { let balance = is_cpe && coupling && ch == 1; let num_env = grids[ch].num_env; - let amp_res = amp_res_of(header.amp_res, num_env); + let amp_res = amp_res_of(header.amp_res, &grids[ch]); let e_q = e_q_all[ch].clone(); let q_q = q_q_all[ch].clone(); @@ -628,6 +686,8 @@ impl SbrParser { add_harmonic: None, df_env: df_env[ch].iter().map(|&b| u8::from(b)).collect(), df_noise: df_noise[ch].iter().map(|&b| u8::from(b)).collect(), + l_a: grids[ch].l_a, + amp_res, }); } diff --git a/crates/ec-aac/src/sbr_qmf.rs b/crates/ec-aac/src/sbr_qmf.rs index 96524792..5c363ab6 100644 --- a/crates/ec-aac/src/sbr_qmf.rs +++ b/crates/ec-aac/src/sbr_qmf.rs @@ -2,27 +2,18 @@ //! analysis, folded to a shared core) and 4.6.18.8.2 (64-band synthesis) //! polyphase machinery HE-AAC's spectral band replication is built on. //! -//! # Bank sharing and the 32-band bridge +//! # Banks //! -//! The spec defines two analysis banks (32-band, 4.6.18.4.1, and 64-band, -//! 4.6.18.4) and two synthesis banks (64-band, 4.6.18.8.2, and a downsampled -//! 32-band variant, 4.6.18.8.3). A numpy round-trip campaign (see -//! `scripts/aac-tables/qmf_check.py` and the ledger, round "sbr-hunt") found -//! the 64-band analysis/synthesis pair self-consistent to `corr=0.999999` -//! against the literal spec equations, but the 32-band analysis and 32-band -//! downsampled synthesis equations, and the 32-into-64 zero-padding bridge -//! the SBR core signal actually needs, never cleared 0.7 correlation under -//! the same exact-equation reading. Zero-stuffing the 32 core samples to 64 -//! (`x64[2m] = 2*x32[m]`, odd samples 0) and running them through the -//! VERIFIED 64-band analysis, keeping bands `0..32` and dropping the -//! zero-stuffing image that lands in bands `32..64`, reached `corr=0.9994` -//! against an ideal band-limited 2x upsample -- short of the 0.9999 numpy -//! target but a real, spec-traceable near-PR bank, not a fitted -//! approximation. [`Analysis`] and [`HfAnalysis`] therefore share one -//! [`QmfAnalysis64`] core: the difference between them is only whether the -//! caller has 32 core samples (zero-stuffed by [`Analysis`]) or 64 -//! already-doubled-rate samples ([`HfAnalysis`], used only for measurement). -//! [`Synthesis`] is the 64-band bank directly, unmodified for either caller. +//! [`Analysis`] is the 32-band core analysis (4.6.18.4.1: `c[2n]` taps over +//! 320 samples, 64-point modulation), [`Synthesis`] the 64-band bank +//! (4.6.18.8.2) and [`HfAnalysis`] a 64-band analysis used only by the +//! measurement instruments. The numpy round-trip campaign +//! (`scripts/aac-tables/qmf_check.py`, ledger round "sbr-hunt") verified the +//! 64-band pair to `corr=0.999999` against the literal equations; its +//! 32-band attempt used full-rate taps and a conjugated carrier, which is +//! why it "never cleared 0.7" and the bank shipped for a while as a +//! zero-stuffed 64-band bridge instead (see [`Analysis`] for the per-band +//! phase that bridge imposed on the HF patches). //! //! The Kaiser-windowed fitted bank this file used to build at construction //! time (`prototype`/`theta`/`modulation_tables`/`analytic_gain`, tuned by a @@ -40,11 +31,6 @@ pub const ANALYSIS_BANDS: usize = 32; /// Synthesis channel count (twice the core's, spanning the doubled band). pub const SYNTHESIS_BANDS: usize = 64; -/// Zero-stuffing gain the 32-into-64 bridge needs to read back unity -/// amplitude (numpy-measured: `gain=2.0` gives `amp_ratio ~ 0.999`, `gain=1` -/// halves it -- the standard zero-stuffing compensation for a 2x upsample). -const ZERO_STUFF_GAIN: f64 = 2.0; - /// The shared ISO/IEC 14496-3 4.6.18.4 64-band analysis core: `PROTO_LEN` /// real history samples in (newest inserted last, matching PCM order), /// `SYNTHESIS_BANDS` complex subbands out per slot of `SYNTHESIS_BANDS` new @@ -106,20 +92,50 @@ impl QmfAnalysis64 { } } -/// The 32-band bridge: core PCM in (32 samples/slot), complex subband slots -/// out (32/slot), via zero-stuffing into the verified 64-band core and -/// keeping the low half (see the module doc for why this replaces a native -/// 32-band analysis). +/// ISO/IEC 14496-3 4.6.18.4.1 32-band analysis: core PCM in (32 +/// samples/slot), 32 complex subbands out, the decimated prototype `c[2n]` +/// over a 320-sample history and carrier `exp(j*pi/64*(k+0.5)*(2n-0.5))` +/// (see `new` for the -0.5). +/// +/// Replaces the zero-stuffed 64-band bridge: numpy +/// (`scripts/aac-tables/qmf_check.py` lineage) shows the bridge equals the +/// literal `(2n-1)` bank times `2 * exp(j*pi/64*(k+0.5)*1.5)` per band -- +/// a 1.5-sample (at the doubled rate) delay plus 2x gain. Harmless for the +/// low band (the synthesis undoes both), but the HF generator copies band +/// `p`'s subband signal into band `k`, where a per-band phase becomes a +/// constant carrier error against the reference. pub struct Analysis { - core: QmfAnalysis64, + hist: [f64; PROTO_LEN / 2], + cos_tab: Vec, + sin_tab: Vec, } impl Analysis { /// A fresh bank with an all-zero history (the usual filter startup /// transient applies to its first ~`PROTO_LEN` output samples). pub fn new() -> Analysis { + let mut cos_tab = vec![0.0f64; ANALYSIS_BANDS * 64]; + let mut sin_tab = vec![0.0f64; ANALYSIS_BANDS * 64]; + for k in 0..ANALYSIS_BANDS { + for n in 0..64 { + // Carrier offset -0.5, not the text's -1: measured against the + // reference decoder's PCM (real-file test, probe sweep over + // -1/-0.5/0/+0.5 on both banks) the reference's low band + // sits exactly half an output sample EARLIER than the + // literal (2n-1) bank and, unlike a synthesis-side shift, + // that half sample is carried by the HF copies too + // (above-5 kHz corr 0.9997 vs 0.9995 synthesis-side, 0.984 + // literal). Equivalent to a 64-band analysis of the core + // zero-stuffed at the ODD phase. + let theta = std::f64::consts::PI / 64.0 * (k as f64 + 0.5) * (2.0 * n as f64 - 0.5); + cos_tab[k * 64 + n] = theta.cos(); + sin_tab[k * 64 + n] = theta.sin(); + } + } Analysis { - core: QmfAnalysis64::new(), + hist: [0.0; PROTO_LEN / 2], + cos_tab, + sin_tab, } } @@ -130,13 +146,26 @@ impl Analysis { &mut self, samples: &[f32; ANALYSIS_BANDS], ) -> [Complex; ANALYSIS_BANDS] { - let mut x64 = [0.0f64; SYNTHESIS_BANDS]; - for (m, &s) in samples.iter().enumerate() { - x64[2 * m] = ZERO_STUFF_GAIN * s as f64; + const LEN: usize = PROTO_LEN / 2; + for &s in samples { + self.hist.copy_within(0..LEN - 1, 1); + self.hist[0] = s as f64; + } + // Z[n] = x[n]*c[2n], n=0..319; u[n] = sum_{j=0}^{4} Z[n+64j], n=0..63 + let mut u = [0.0f64; 64]; + for (n, uu) in u.iter_mut().enumerate() { + *uu = (0..5).map(|j| self.hist[n + 64 * j] * QMF_WINDOW[2 * (n + 64 * j)]).sum(); } - let full = self.core.process_slot(&x64); let mut out = [Complex::new(0.0, 0.0); ANALYSIS_BANDS]; - out.copy_from_slice(&full[0..ANALYSIS_BANDS]); + for (k, slot) in out.iter_mut().enumerate() { + let row = k * 64; + let (mut re, mut im) = (0.0f64, 0.0f64); + for n in 0..64 { + re += u[n] * self.cos_tab[row + n]; + im += u[n] * self.sin_tab[row + n]; + } + *slot = Complex::new(re, im); + } out } } @@ -315,11 +344,18 @@ mod tests { fft.forward(&mut spectrum); let mut padded = vec![Complex::new(0.0, 0.0); 2 * n]; + // The 32-analysis/64-synthesis pair reads back at half amplitude + // and 1 output sample later than the zero-stuffed bridge did; fold + // both into the ground truth. + let delay = |m: f64| { + let ph = -2.0 * std::f64::consts::PI * m / (2 * n) as f64; + Complex::new(ph.cos(), ph.sin()) + }; for k in 0..n / 2 { - padded[k] = spectrum[k].scale(2.0); + padded[k] = spectrum[k].scale(2.0) * delay(k as f64); } for k in n / 2..n { - padded[2 * n - n + k] = spectrum[k].scale(2.0); + padded[2 * n - n + k] = spectrum[k].scale(2.0) * delay(k as f64 - n as f64); } let mut fft2 = Fft::::new(2 * n); fft2.inverse(&mut padded); @@ -411,8 +447,8 @@ mod tests { "measured filterbank delay: {best_lag} samples, correlation {best_corr:.6}, amplitude ratio {amp_ratio:.6}" ); assert!( - (0.98..=1.02).contains(&_ratio), - "round-trip amplitude ratio {amp_ratio} not within 2% of unity gain" + (0.49..=0.51).contains(&_ratio), + "round-trip amplitude ratio {amp_ratio} not within 2% of the spec pair's 0.5 (sbr_chain restores the 2x)" ); assert!( best_corr >= 0.9999, diff --git a/crates/ec-aac/src/sbr_tables.rs b/crates/ec-aac/src/sbr_tables.rs index 3f13ea10..aeb40ef1 100644 --- a/crates/ec-aac/src/sbr_tables.rs +++ b/crates/ec-aac/src/sbr_tables.rs @@ -7,6 +7,13 @@ //! `env_facs_q`/`noise_facs_q` range check reads the delta value each //! codeword carries off the same payload. Every table here closed with //! a Kraft sum of exactly 1 (asserted below). +//! +//! GENERATED: books by `sbrtables.py --stage values`, then the four 3.0 dB +//! books (`ENV30_F`, `ENV30_T`, `ENVB30_F`, `ENVB30_T`) re-valued in place by +//! `scripts/aac-tables/sbrvalues.py`, which walks each codeword's delta out +//! of range by delta-time ACCUMULATION (a single +d on the 6-bit 3 dB raw +//! field never reaches the 7-bit ceiling, so the one-shot stage read every +//! positive 3 dB delta as 0). Do not hand-edit the books. #![allow(dead_code)] /// SBR Huffman book `ENV15_F`: (length, code, delta) by codeword. @@ -263,31 +270,31 @@ pub(crate) static ENV15_T: [(u8, u32, i32); 121] = [ pub(crate) static ENV30_T: [(u8, u32, i32); 63] = [ (1, 0, 0), (2, 2, -1), - (3, 6, 0), + (3, 6, 1), (4, 14, -2), - (5, 30, 0), + (5, 30, 2), (6, 62, -3), - (7, 126, 0), + (7, 126, 3), (8, 254, -4), - (9, 510, 0), + (9, 510, 4), (11, 2044, -5), - (11, 2045, 0), + (11, 2045, 5), (12, 4092, -6), (13, 8186, -7), - (13, 8187, 0), + (13, 8187, 6), (14, 16376, -8), - (14, 16377, 0), + (14, 16377, 7), (14, 16378, -9), (14, 16379, -10), - (14, 16380, 0), - (15, 32762, 0), - (16, 65526, 0), + (14, 16380, 8), + (15, 32762, 9), + (16, 65526, 10), (16, 65527, -13), (16, 65528, -11), (16, 65529, -12), (17, 131060, -14), - (17, 131061, 0), - (18, 262124, 0), + (17, 131061, 11), + (18, 262124, 12), (18, 262125, -31), (18, 262126, -30), (19, 524254, -29), @@ -305,76 +312,76 @@ pub(crate) static ENV30_T: [(u8, u32, i32); 63] = [ (19, 524266, -17), (19, 524267, -16), (19, 524268, -15), - (19, 524269, 0), - (19, 524270, 0), - (19, 524271, 0), - (19, 524272, 0), - (19, 524273, 0), - (19, 524274, 0), - (19, 524275, 0), - (19, 524276, 0), - (19, 524277, 0), - (19, 524278, 0), - (19, 524279, 0), - (19, 524280, 0), - (19, 524281, 0), - (19, 524282, 0), - (19, 524283, 0), - (19, 524284, 0), - (19, 524285, 0), - (19, 524286, 0), - (19, 524287, 0), + (19, 524269, 13), + (19, 524270, 14), + (19, 524271, 15), + (19, 524272, 16), + (19, 524273, 17), + (19, 524274, 18), + (19, 524275, 19), + (19, 524276, 20), + (19, 524277, 21), + (19, 524278, 22), + (19, 524279, 23), + (19, 524280, 24), + (19, 524281, 25), + (19, 524282, 26), + (19, 524283, 27), + (19, 524284, 28), + (19, 524285, 29), + (19, 524286, 30), + (19, 524287, 31), ]; /// SBR Huffman book `ENV30_F`: (length, code, delta) by codeword. pub(crate) static ENV30_F: [(u8, u32, i32); 63] = [ (1, 0, 0), (2, 2, -1), - (3, 6, 0), + (3, 6, 1), (4, 14, -2), - (5, 30, 0), + (5, 30, 2), (6, 62, -3), - (8, 252, 0), + (8, 252, 3), (8, 253, -4), - (9, 508, 0), + (9, 508, 4), (9, 509, -5), - (10, 1020, 0), + (10, 1020, 5), (10, 1021, -6), - (11, 2044, 0), + (11, 2044, 6), (11, 2045, -7), - (12, 4092, 0), + (12, 4092, 7), (12, 4093, -8), - (13, 8188, 0), - (14, 16378, 0), + (13, 8188, 8), + (14, 16378, 9), (14, 16379, -9), (15, 32760, -10), - (15, 32761, 0), - (15, 32762, 0), + (15, 32761, 10), + (15, 32762, 11), (16, 65526, -11), (16, 65527, -12), - (16, 65528, 0), - (16, 65529, 0), + (16, 65528, 12), + (16, 65529, 13), (17, 131060, -13), (17, 131061, -15), - (17, 131062, 0), - (17, 131063, 0), + (17, 131062, 14), + (17, 131063, 15), (18, 262128, -14), - (18, 262129, 0), + (18, 262129, 18), (18, 262130, -18), (18, 262131, -24), (18, 262132, -19), - (18, 262133, 0), - (18, 262134, 0), + (18, 262133, 16), + (18, 262134, 17), (19, 524270, -22), (19, 524271, -21), (19, 524272, -16), - (19, 524273, 0), - (19, 524274, 0), - (19, 524275, 0), - (19, 524276, 0), + (19, 524273, 20), + (19, 524274, 21), + (19, 524275, 22), + (19, 524276, 25), (19, 524277, -23), (19, 524278, -20), - (19, 524279, 0), + (19, 524279, 24), (20, 1048560, -31), (20, 1048561, -30), (20, 1048562, -29), @@ -383,14 +390,14 @@ pub(crate) static ENV30_F: [(u8, u32, i32); 63] = [ (20, 1048565, -26), (20, 1048566, -25), (20, 1048567, -17), - (20, 1048568, 0), - (20, 1048569, 0), - (20, 1048570, 0), - (20, 1048571, 0), - (20, 1048572, 0), - (20, 1048573, 0), - (20, 1048574, 0), - (20, 1048575, 0), + (20, 1048568, 19), + (20, 1048569, 23), + (20, 1048570, 26), + (20, 1048571, 27), + (20, 1048572, 28), + (20, 1048573, 29), + (20, 1048574, 30), + (20, 1048575, 31), ]; /// SBR Huffman book `NOISE_T`: (length, code, delta) by codeword. @@ -636,14 +643,14 @@ pub(crate) static ENVB15_T: [(u8, u32, i32); 49] = [ /// SBR Huffman book `ENVB30_T`: (length, code, delta) by codeword. pub(crate) static ENVB30_T: [(u8, u32, i32); 25] = [ (1, 0, 0), - (2, 2, 0), + (2, 2, 1), (3, 6, -1), (4, 14, -2), - (5, 30, 0), - (6, 62, 0), + (5, 30, 2), + (6, 62, 3), (7, 126, -3), (8, 254, -4), - (9, 510, 0), + (9, 510, 4), (12, 4088, -5), (13, 8178, -12), (13, 8179, -11), @@ -652,30 +659,30 @@ pub(crate) static ENVB30_T: [(u8, u32, i32); 25] = [ (13, 8182, -8), (13, 8183, -7), (13, 8184, -6), - (13, 8185, 0), - (13, 8186, 0), - (13, 8187, 0), - (13, 8188, 0), - (13, 8189, 0), - (13, 8190, 0), - (14, 16382, 0), - (14, 16383, 0), + (13, 8185, 5), + (13, 8186, 6), + (13, 8187, 7), + (13, 8188, 8), + (13, 8189, 9), + (13, 8190, 10), + (14, 16382, 11), + (14, 16383, 12), ]; /// SBR Huffman book `ENVB30_F`: (length, code, delta) by codeword. pub(crate) static ENVB30_F: [(u8, u32, i32); 25] = [ (1, 0, 0), (2, 2, -1), - (3, 6, 0), + (3, 6, 1), (4, 14, -2), - (5, 30, 0), - (6, 62, 0), + (5, 30, 2), + (6, 62, 3), (7, 126, -3), (8, 254, -4), - (9, 510, 0), + (9, 510, 4), (11, 2044, -5), - (12, 4090, 0), - (13, 8182, 0), + (12, 4090, 5), + (13, 8182, 6), (13, 8183, -12), (13, 8184, -11), (13, 8185, -10), @@ -683,12 +690,12 @@ pub(crate) static ENVB30_F: [(u8, u32, i32); 25] = [ (13, 8187, -8), (14, 16376, -7), (14, 16377, -6), - (14, 16378, 0), - (14, 16379, 0), - (14, 16380, 0), - (14, 16381, 0), - (14, 16382, 0), - (14, 16383, 0), + (14, 16378, 7), + (14, 16379, 8), + (14, 16380, 9), + (14, 16381, 10), + (14, 16382, 11), + (14, 16383, 12), ]; /// SBR Huffman book `NOISEB_T`: (length, code, delta) by codeword. @@ -749,6 +756,524 @@ pub(crate) static NOISEB_F: [(u8, u32, i32); 25] = [ (14, 16383, 12), ]; +/// ISO/IEC 14496-3 Table 4.A.88: the 512-entry complex noise sequence +/// `V` the envelope adjuster draws from (`f_IndexNoise` wraps at 512), as +/// `(re, im)` pairs. +pub(crate) static SBR_NOISE: [(f64, f64); 512] = [ + (-0.99948153278296, -0.59483417516607), + (0.97113454393991, -0.67528515225647), + (0.14130051758487, -0.95090983575689), + (-0.47005496701697, -0.37340549728647), + (0.80705063769351, 0.29653668284408), + (-0.38981478896926, 0.89572605717087), + (-0.01053049862020, -0.66959058036166), + (-0.91266367957293, -0.11522938140034), + (0.54840422910309, 0.75221367176302), + (0.40009252867955, -0.98929400334421), + (-0.99867974711855, -0.88147068645358), + (-0.95531076805040, 0.90908757154593), + (-0.45725933317144, -0.56716323646760), + (-0.72929675029275, -0.98008272727324), + (0.75622801399036, 0.20950329995549), + (0.07069442601050, -0.78247898470706), + (0.74496252926055, -0.91169004445807), + (-0.96440182703856, -0.94739918296622), + (0.30424629369539, -0.49438267012479), + (0.66565033746925, 0.64652935542491), + (0.91697008020594, 0.17514097332009), + (-0.70774918760427, 0.52548653416543), + (-0.70051415345560, -0.45340028808763), + (-0.99496513054797, -0.90071908066973), + (0.98164490790123, -0.77463155528697), + (-0.54671580548181, -0.02570928536004), + (-0.01689629065389, 0.00287506445732), + (-0.86110349531986, 0.42548583726477), + (-0.98892980586032, -0.87881132267556), + (0.51756627678691, 0.66926784710139), + (-0.99635026409640, -0.58107730574765), + (-0.99969370862163, 0.98369989360250), + (0.55266258627194, 0.59449057465591), + (0.34581177741673, 0.94879421061866), + (0.62664209577999, -0.74402970906471), + (-0.77149701404973, -0.33883658042801), + (-0.91592244254432, 0.03687901376713), + (-0.76285492357887, -0.91371867919124), + (0.79788337195331, -0.93180971199849), + (0.54473080610200, -0.11919206037186), + (-0.85639281671058, 0.42429854760451), + (-0.92882402971423, 0.27871809078609), + (-0.11708371046774, -0.99800843444966), + (0.21356749817493, -0.90716295627033), + (-0.76191692573909, 0.99768118356265), + (0.98111043100884, -0.95854459734407), + (-0.85913269895572, 0.95766566168880), + (-0.93307242253692, 0.49431757696466), + (0.30485754879632, -0.70540034357529), + (0.85289650925190, 0.46766131791044), + (0.91328082618125, -0.99839597361769), + (-0.05890199924154, 0.70741827819497), + (0.28398686150148, 0.34633555702188), + (0.95258164539612, -0.54893416026939), + (-0.78566324168507, -0.75568541079691), + (-0.95789495447877, -0.20423194696966), + (0.82411158711197, 0.96654618432562), + (-0.65185446735885, -0.88734990773289), + (-0.93643603134666, 0.99870790442385), + (0.91427159529618, -0.98290505544444), + (-0.70395684036886, 0.58796798221039), + (0.00563771969365, 0.61768196727244), + (0.89065051931895, 0.52783352697585), + (-0.68683707712762, 0.80806944710339), + (0.72165342518718, -0.69259857349564), + (-0.62928247730667, 0.13627037407335), + (0.29938434065514, -0.46051329682246), + (-0.91781958879280, -0.74012716684186), + (0.99298717043688, 0.40816610075661), + (0.82368298622748, -0.74036047190173), + (-0.98512833386833, -0.99972330709594), + (-0.95915368242257, -0.99237800466040), + (-0.21411126572790, -0.93424819052545), + (-0.68821476106884, -0.26892306315457), + (0.91851997982317, 0.09358228901785), + (-0.96062769559127, 0.36099095133739), + (0.51646184922287, -0.71373332873917), + (0.61130721139669, 0.46950141175917), + (0.47336129371299, -0.27333178296162), + (0.90998308703519, 0.96715662938132), + (0.44844799194357, 0.99211574628306), + (0.66614891079092, 0.96590176169121), + (0.74922239129237, -0.89879858826087), + (-0.99571588506485, 0.52785521494349), + (0.97401082477563, -0.16855870075190), + (0.72683747733879, -0.48060774432251), + (0.95432193457128, 0.68849603408441), + (-0.72962208425191, -0.76608443420917), + (-0.85359479233537, 0.88738125901579), + (-0.81412430338535, -0.97480768049637), + (-0.87930772356786, 0.74748307690436), + (-0.71573331064977, -0.98570608178923), + (0.83524300028228, 0.83702537075163), + (-0.48086065601423, -0.98848504923531), + (0.97139128574778, 0.80093621198236), + (0.51992825347895, 0.80247631400510), + (-0.00848591195325, -0.76670128000486), + (-0.70294374303036, 0.55359910445577), + (-0.95894428168140, -0.43265504344783), + (0.97079252950321, 0.09325857238682), + (-0.92404293670797, 0.85507704027855), + (-0.69506469500450, 0.98633412625459), + (0.26559203620024, 0.73314307966524), + (0.28038443336943, 0.14537913654427), + (-0.74138124825523, 0.99310339807762), + (-0.01752795995444, -0.82616635284178), + (-0.55126773094930, -0.98898543862153), + (0.97960898850996, -0.94021446752851), + (-0.99196309146936, 0.67019017358456), + (-0.67684928085260, 0.12631491649378), + (0.09140039465500, -0.20537731453108), + (-0.71658965751996, -0.97788200391224), + (0.81014640078925, 0.53722648362443), + (0.40616991671205, -0.26469008598449), + (-0.67680188682972, 0.94502052337695), + (0.86849774348749, -0.18333598647899), + (-0.99500381284851, -0.02634122068550), + (0.84329189340667, 0.10406957462213), + (-0.09215968531446, 0.69540012101253), + (0.99956173327206, -0.12358542001404), + (-0.79732779473535, -0.91582524736159), + (0.96349973642406, 0.96640458041000), + (-0.79942778496547, 0.64323902822857), + (-0.11566039853896, 0.28587846253726), + (-0.39922954514662, 0.94129601616966), + (0.99089197565987, -0.92062625581587), + (0.28631285179909, -0.91035047143603), + (-0.83302725605608, -0.67330410892084), + (0.95404443402072, 0.49162765398743), + (-0.06449863579434, 0.03250560813135), + (-0.99575054486311, 0.42389784469507), + (-0.65501142790847, 0.82546114655624), + (-0.81254441908887, -0.51627234660629), + (-0.99646369485481, 0.84490533520752), + (0.00287840603348, 0.64768261158166), + (0.70176989408455, -0.20453028573322), + (0.96361882270190, 0.40706967140989), + (-0.68883758192426, 0.91338958840772), + (-0.34875585502238, 0.71472290693300), + (0.91980081243087, 0.66507455644919), + (-0.99009048343881, 0.85868021604848), + (0.68865791458395, 0.55660316809678), + (-0.99484402129368, -0.20052559254934), + (0.94214511408023, -0.99696425367461), + (-0.67414626793544, 0.49548221180078), + (-0.47339353684664, -0.85904328834047), + (0.14323651387360, -0.94145598222488), + (-0.29268293575672, 0.05759224927952), + (0.43793861458754, -0.78904969892724), + (-0.36345126374441, 0.64874435357162), + (-0.08750604656825, 0.97686944362527), + (-0.96495267812511, -0.53960305946511), + (0.55526940659947, 0.78891523734774), + (0.73538215752630, 0.96452072373404), + (-0.30889773919437, -0.80664389776860), + (0.03574995626194, -0.97325616900959), + (0.98720684660488, 0.48409133691962), + (-0.81689296271203, -0.90827703628298), + (0.67866860118215, 0.81284503870856), + (-0.15808569732583, 0.85279555024382), + (0.80723395114371, -0.24717418514605), + (0.47788757329038, -0.46333147839295), + (0.96367554763201, 0.38486749303242), + (-0.99143875716818, -0.24945277239809), + (0.83081876925833, -0.94780851414763), + (-0.58753191905341, 0.01290772389163), + (0.95538108220960, -0.85557052096538), + (-0.96490920476211, -0.64020970923102), + (-0.97327101028521, 0.12378128133110), + (0.91400366022124, 0.57972471346930), + (-0.99925837363824, 0.71084847864067), + (-0.86875903507313, -0.20291699203564), + (-0.26240034795124, -0.68264554369108), + (-0.24664412953388, -0.87642273115183), + (0.02416275806869, 0.27192914288905), + (0.82068619590515, -0.85087787994476), + (0.88547373760759, -0.89636802901469), + (-0.18173078152226, -0.26152145156800), + (0.09355476558534, 0.54845123045604), + (-0.54668414224090, 0.95980774020221), + (0.37050990604091, -0.59910140383171), + (-0.70373594262891, 0.91227665827081), + (-0.34600785879594, -0.99441426144200), + (-0.68774481731008, -0.30238837956299), + (-0.26843291251234, 0.83115668004362), + (0.49072334613242, -0.45359708737775), + (0.38975993093975, 0.95515358099121), + (-0.97757125224150, 0.05305894580606), + (-0.17325552859616, -0.92770672250494), + (0.99948035025744, 0.58285545563426), + (-0.64946246527458, 0.68645507104960), + (-0.12016920576437, -0.57147322153312), + (-0.58947456517751, -0.34847132454388), + (-0.41815140454465, 0.16276422358861), + (0.99885650204884, 0.11136095490444), + (-0.56649614128386, -0.90494866361587), + (0.94138021032330, 0.35281916733018), + (-0.75725076534641, 0.53650549640587), + (0.20541973692630, -0.94435144369918), + (0.99980371023351, 0.79835913565599), + (0.29078277605775, 0.35393777921520), + (-0.62858772103030, 0.38765693387102), + (0.43440904467688, -0.98546330463232), + (-0.98298583762390, 0.21021524625209), + (0.19513029146934, -0.94239832251867), + (-0.95476662400101, 0.98364554179143), + (0.93379635304810, -0.70881994583682), + (-0.85235410573336, -0.08342347966410), + (-0.86425093011245, -0.45795025029466), + (0.38879779059045, 0.97274429344593), + (0.92045124735495, -0.62433652524220), + (0.89162532251878, 0.54950955570563), + (-0.36834336949252, 0.96458298020975), + (0.93891760988045, -0.89968353740388), + (0.99267657565094, -0.03757034316958), + (-0.94063471614176, 0.41332338538963), + (0.99740224117019, -0.16830494996370), + (-0.35899413170555, -0.46633226649613), + (0.05237237274947, -0.25640361602661), + (0.36703583957424, -0.38653265641875), + (0.91653180367913, -0.30587628726597), + (0.69000803499316, 0.90952171386132), + (-0.38658751133527, 0.99501571208985), + (-0.29250814029851, 0.37444994344615), + (-0.60182204677608, 0.86779651036123), + (-0.97418588163217, 0.96468523666475), + (0.88461574003963, 0.57508405276414), + (0.05198933055162, 0.21269661669964), + (-0.53499621979720, 0.97241553731237), + (-0.49429560226497, 0.98183865291903), + (-0.98935142339139, -0.40249159006933), + (-0.98081380091130, -0.72856895534041), + (-0.27338148835532, 0.99950922447209), + (0.06310802338302, -0.54539587529618), + (-0.20461677199539, -0.14209977628489), + (0.66223843141647, 0.72528579940326), + (-0.84764345483665, 0.02372316801261), + (-0.89039863483811, 0.88866581484602), + (0.95903308477986, 0.76744927173873), + (0.73504123909879, -0.03747203173192), + (-0.31744434966056, -0.36834111883652), + (-0.34110827591623, 0.40211222807691), + (0.47803883714199, -0.39423219786288), + (0.98299195879514, 0.01989791390047), + (-0.30963073129751, -0.18076720599336), + (0.99992588229018, -0.26281872094289), + (-0.93149731080767, -0.98313162570490), + (0.99923472302773, -0.80142993767554), + (-0.26024169633417, -0.75999759855752), + (-0.35712514743563, 0.19298963768574), + (-0.99899084509530, 0.74645156992493), + (0.86557171579452, 0.55593866696299), + (0.33408042438752, 0.86185953874709), + (0.99010736374716, 0.04602397576623), + (-0.66694269691195, -0.91643611810148), + (0.64016792079480, 0.15649530836856), + (0.99570534804836, 0.45844586038111), + (-0.63431466947340, 0.21079116459234), + (-0.07706847005931, -0.89581437101329), + (0.98590090577724, 0.88241721133981), + (0.80099335254678, -0.36851896710853), + (0.78368131392666, 0.45506999802597), + (0.08707806671691, 0.80938994918745), + (-0.86811883080712, 0.39347308654705), + (-0.39466529740375, -0.66809432114456), + (0.97875325649683, -0.72467840967746), + (-0.95038560288864, 0.89563219587625), + (0.17005239424212, 0.54683053962658), + (-0.76910792026848, -0.96226617549298), + (0.99743281016846, 0.42697157037567), + (0.95437383549973, 0.97002324109952), + (0.99578905365569, -0.54106826257356), + (0.28058259829990, -0.85361420634036), + (0.85256524470573, -0.64567607735589), + (-0.50608540105128, -0.65846015480300), + (-0.97210735183243, -0.23095213067791), + (0.95424048234441, -0.99240147091219), + (-0.96926570524023, 0.73775654896574), + (0.30872163214726, 0.41514960556126), + (-0.24523839572639, 0.63206633394807), + (-0.33813265086024, -0.38661779441897), + (-0.05826828420146, -0.06940774188029), + (-0.22898461455054, 0.97054853316316), + (-0.18509915019881, 0.47565762892084), + (-0.10488238045009, -0.87769947402394), + (-0.71886586182037, 0.78030982480538), + (0.99793873738654, 0.90041310491497), + (0.57563307626120, -0.91034337352097), + (0.28909646383717, 0.96307783970534), + (0.42188998312520, 0.48148651230437), + (0.93335049681047, -0.43537023883588), + (-0.97087374418267, 0.86636445711364), + (0.36722871286923, 0.65291654172961), + (-0.81093025665696, 0.08778370229363), + (-0.26240603062237, -0.92774095379098), + (0.83996497984604, 0.55839849139647), + (-0.99909615720225, -0.96024605713970), + (0.74649464155061, 0.12144893606462), + (-0.74774595569805, -0.26898062008959), + (0.95781667469567, -0.79047927052628), + (0.95472308713099, -0.08588776019550), + (0.48708332746299, 0.99999041579432), + (0.46332038247497, 0.10964126185063), + (-0.76497004940162, 0.89210929242238), + (0.57397389364339, 0.35289703373760), + (0.75374316974495, 0.96705214651335), + (-0.59174397685714, -0.89405370422752), + (0.75087906691890, -0.29612672982396), + (-0.98607857336230, 0.25034911730023), + (-0.40761056640505, -0.90045573444695), + (0.66929266740477, 0.98629493401748), + (-0.97463695257310, -0.00190223301301), + (0.90145509409859, 0.99781390365446), + (-0.87259289048043, 0.99233587353666), + (-0.91529461447692, -0.15698707534206), + (-0.03305738840705, -0.37205262859764), + (0.07223051368337, -0.88805001733626), + (0.99498012188353, 0.97094358113387), + (-0.74904939500519, 0.99985483641521), + (0.04585228574211, 0.99812337444082), + (-0.89054954257993, -0.31791913188064), + (-0.83782144651251, 0.97637632547466), + (0.33454804933804, -0.86231516800408), + (-0.99707579362824, 0.93237990079441), + (-0.22827527843994, 0.18874759397997), + (0.67248046289143, -0.03646211390569), + (-0.05146538187944, -0.92599700120679), + (0.99947295749905, 0.93625229707912), + (0.66951124390363, 0.98905825623893), + (-0.99602956559179, -0.44654715757688), + (0.82104905483590, 0.99540741724928), + (0.99186510988782, 0.72023001312947), + (-0.65284592392918, 0.52186723253637), + (0.93885443798188, -0.74895312615259), + (0.96735248738388, 0.90891816978629), + (-0.22225968841114, 0.57124029781228), + (-0.44132783753414, -0.92688840659280), + (-0.85694974219574, 0.88844532719844), + (0.91783042091762, -0.46356892383970), + (0.72556974415690, -0.99899555770747), + (-0.99711581834508, 0.58211560180426), + (0.77638976371966, 0.94321834873819), + (0.07717324253925, 0.58638399856595), + (-0.56049829194163, 0.82522301569036), + (0.98398893639988, 0.39467440420569), + (0.47546946844938, 0.68613044836811), + (0.65675089314631, 0.18331637134880), + (0.03273375457980, -0.74933109564108), + (-0.38684144784738, 0.51337349030406), + (-0.97346267944545, -0.96549364384098), + (-0.53282156061942, -0.91423265091354), + (0.99817310731176, 0.61133572482148), + (-0.50254500772635, -0.88829338134294), + (0.01995873238855, 0.85223515096765), + (0.99930381973804, 0.94578896296649), + (0.82907767600783, -0.06323442598128), + (-0.58660709669728, 0.96840773806582), + (-0.17573736667267, -0.48166920859485), + (0.83434292401346, -0.13023450646997), + (0.05946491307025, 0.20511047074866), + (0.81505484574602, -0.94685947861369), + (-0.44976380954860, 0.40894572671545), + (-0.89746474625671, 0.99846578838537), + (0.39677256130792, -0.74854668609359), + (-0.07588948563079, 0.74096214084170), + (0.76343198951445, 0.41746629422634), + (-0.74490104699626, 0.94725911744610), + (0.64880119792759, 0.41336660830571), + (0.62319537462542, -0.93098313552599), + (0.42215817594807, -0.07712787385208), + (0.02704554141885, -0.05417518053666), + (0.80001773566818, 0.91542195141039), + (-0.79351832348816, -0.36208897989136), + (0.63872359151636, 0.08128252493444), + (0.52890520960295, 0.60048872455592), + (0.74238552914587, 0.04491915291044), + (0.99096131449250, -0.19451182854402), + (-0.80412329643109, -0.88513818199457), + (-0.64612616129736, 0.72198674804544), + (0.11657770663191, -0.83662833815041), + (-0.95053182488101, -0.96939905138082), + (-0.62228872928622, 0.82767262846661), + (0.03004475787316, -0.99738896333384), + (-0.97987214341034, 0.36526129686425), + (-0.99986980746200, -0.36021610299715), + (0.89110648599879, -0.97894250343044), + (0.10407960510582, 0.77357793811619), + (0.95964737821728, -0.35435818285502), + (0.50843233159162, 0.96107691266205), + (0.17006334670615, -0.76854025314829), + (0.25872675063360, 0.99893303933816), + (-0.01115998681937, 0.98496019742444), + (-0.79598702973261, 0.97138411318894), + (-0.99264708948101, -0.99542822402536), + (-0.99829663752818, 0.01877138824311), + (-0.70801016548184, 0.33680685948117), + (-0.70467057786826, 0.93272777501857), + (0.99846021905254, -0.98725746254433), + (-0.63364968534650, -0.16473594423746), + (-0.16258217500792, -0.95939125400802), + (-0.43645594360633, -0.94805030113284), + (-0.99848471702976, 0.96245166923809), + (-0.16796458968998, -0.98987511890470), + (-0.87979225745213, -0.71725725041680), + (0.44183099021786, -0.93568974498761), + (0.93310180125532, -0.99913308068246), + (-0.93941931782002, -0.56409379640356), + (-0.88590003188677, 0.47624600491382), + (0.99971463703691, -0.83889954253462), + (-0.75376385639978, 0.00814643438625), + (0.93887685615875, -0.11284528204636), + (0.85126435782309, 0.52349251543547), + (0.39701421446381, 0.81779634174316), + (-0.37024464187437, -0.87071656222959), + (-0.36024828242896, 0.34655735648287), + (-0.93388812549209, -0.84476541096429), + (-0.65298804552119, -0.18439575450921), + (0.11960319006843, 0.99899346780168), + (0.94292565553160, 0.83163906518293), + (0.75081145286948, -0.35533223142265), + (0.56721979748394, -0.24076836414499), + (0.46857766746029, -0.30140233457198), + (0.97312313923635, -0.99548191630031), + (-0.38299976567017, 0.98516909715427), + (0.41025800019463, 0.02116736935734), + (0.09638062008048, 0.04411984381457), + (-0.85283249275397, 0.91475563922421), + (0.88866808958124, -0.99735267083226), + (-0.48202429536989, -0.96805608884164), + (0.27572582416567, 0.58634753335832), + (-0.65889129659168, 0.58835634138583), + (0.98838086953732, 0.99994349600236), + (-0.20651349620689, 0.54593044066355), + (-0.62126416356920, -0.59893681700392), + (0.20320105410437, -0.86879180355289), + (-0.97790548600584, 0.96290806999242), + (0.11112534735126, 0.21484763313301), + (-0.41368337314182, 0.28216837680365), + (0.24133038992960, 0.51294362630238), + (-0.66393410674885, -0.08249679629081), + (-0.53697829178752, -0.97649903936228), + (-0.97224737889348, 0.22081333579837), + (0.87392477144549, -0.12796173740361), + (0.19050361015753, 0.01602615387195), + (-0.46353441212724, -0.95249041539006), + (-0.07064096339021, -0.94479803205886), + (-0.92444085484466, -0.10457590187436), + (-0.83822593578728, -0.01695043208885), + (0.75214681811150, -0.99955681042665), + (-0.42102998829339, 0.99720941999394), + (-0.72094786237696, -0.35008961934255), + (0.78843311019251, 0.52851398958271), + (0.97394027897442, -0.26695944086561), + (0.99206463477946, -0.57010120849429), + (0.76789609461795, -0.76519356730966), + (-0.82002421836409, -0.73530179553767), + (0.81924990025724, 0.99698425250579), + (-0.26719850873357, 0.68903369776193), + (-0.43311260380975, 0.85321815947490), + (0.99194979673836, 0.91876249766422), + (-0.80692001248487, -0.32627540663214), + (0.43080003649976, -0.21919095636638), + (0.67709491937357, -0.95478075822906), + (0.56151770568316, -0.70693811747778), + (0.10831862810749, -0.08628837174592), + (0.91229417540436, -0.65987351408410), + (-0.48972893932274, 0.56289246362686), + (-0.89033658689697, -0.71656563987082), + (0.65269447475094, 0.65916004833932), + (0.67439478141121, -0.81684380846796), + (-0.47770832416973, -0.16789556203025), + (-0.99715979260878, -0.93565784007648), + (-0.90889593602546, 0.62034397054380), + (-0.06618622548177, -0.23812217221359), + (0.99430266919728, 0.18812555317553), + (0.97686402381843, -0.28664534366620), + (0.94813650221268, -0.97506640027128), + (-0.95434497492853, -0.79607978501983), + (-0.49104783137150, 0.32895214359663), + (0.99881175120751, 0.88993983831354), + (0.50449166760303, -0.85995072408434), + (0.47162891065108, -0.18680204049569), + (-0.62081581361840, 0.75000676218956), + (-0.43867015250812, 0.99998069244322), + (0.98630563232075, -0.53578899600662), + (-0.61510362277374, -0.89515019899997), + (-0.03841517601843, -0.69888815681179), + (-0.30102157304644, -0.07667808922205), + (0.41881284182683, 0.02188098922282), + (-0.86135454941237, 0.98947480909359), + (0.67226861393788, -0.13494389011014), + (-0.70737398842068, -0.76547349325992), + (0.94044946687963, 0.09026201157416), + (-0.82386352534327, 0.08924768823676), + (-0.32070666698656, 0.50143421908753), + (0.57593163224487, -0.98966422921509), + (-0.36326018419965, 0.07440243123228), + (0.99979044674350, -0.14130287347405), + (-0.92366023326932, -0.97979298068180), + (-0.44607178518598, -0.54233252016394), + (0.44226800932956, 0.71326756742752), + (0.03671907158312, 0.63606389366675), + (0.52175424682195, -0.85396826735705), + (-0.94701139690956, -0.01826348194255), + (-0.98759606946049, 0.82288714303073), + (0.87434794743625, 0.89399495655433), + (-0.93412041758744, 0.41374052024363), + (0.96063943315511, 0.93116709541280), + (0.97534253457837, 0.86150930812689), + (0.99642466504163, 0.70190043427512), + (-0.94705089665984, -0.29580042814306), + (0.91599807087376, -0.98147830385781), +]; + #[cfg(test)] mod tests { use super::*; diff --git a/crates/ec-aac/tests/sbr_real_library.rs b/crates/ec-aac/tests/sbr_real_library.rs index 1372e59e..e590e93b 100644 --- a/crates/ec-aac/tests/sbr_real_library.rs +++ b/crates/ec-aac/tests/sbr_real_library.rs @@ -305,6 +305,19 @@ fn best_lag_correlation_ex(ours: &[f32], theirs: &[f32], lag_max: i64) -> (i64, if !found { best = coarse_best; } + // A winning lag at the search bound is not a measurement (the true + // alignment may lie outside it): widen once to `SEARCH_LAG_MAX`, and if + // it still sits at the edge fail here rather than hand any caller a + // noise-driven number (instrument-at-bound class). + if at_edge && lag_max < SEARCH_LAG_MAX { + return best_lag_correlation_ex(ours, theirs, SEARCH_LAG_MAX); + } + assert!( + !at_edge, + "winning lag {} sits at the +/-{lag_max} search bound -- the true \ + alignment is outside the search, corr {:.6} is noise, not a measurement", + best.0, best.2 + ); (best.0, best.2, at_edge) } @@ -2249,18 +2262,24 @@ fn full_chain_low_band_matches_own_core() { // without exposing the well-behaved one to the wider bound's // noise floor. const WIDE_LAG_MAX: i64 = 20_000; - let (mut lag, mut corr, mut at_edge) = best_lag_correlation_ex(&ol, &ul, WIDE_LAG_MAX); + // Top-K refinement, not the single coarse winner: FMJ's single + // coarse pick landed on an in-bounds noise peak (lag 18995, + // corr 0.10) while its true alignment scores >0.99 on refine. + // A winner at the bound widens once, then is asserted off it. + let (mut lag, mut corr, mut at_edge) = + robust_lag_topk(&ol, &ul, WIDE_LAG_MAX, core_rate, 8); let mut bound = WIDE_LAG_MAX; - if at_edge { + // A sub-bar winner inside the narrow bound is the same symptom + // (true peak outside the search), so it widens too. + if at_edge || corr < 0.99 { bound = SEARCH_LAG_MAX; - (lag, corr, at_edge) = best_lag_correlation_ex(&ol, &ul, SEARCH_LAG_MAX); + (lag, corr, at_edge) = robust_lag_topk(&ol, &ul, SEARCH_LAG_MAX, core_rate, 8); } println!(" ch{ch}: measured best lag {lag}, corr {corr:.6}"); assert!( !at_edge, "{} ch{ch}: winning lag {lag} sits at the +/-{bound} \ - search bound -- the true alignment is outside the search, \ - corr {corr:.6} is noise, not a measurement", + search bound -- corr {corr:.6} is noise, not a measurement", c.path.display() ); assert!( @@ -2755,6 +2774,8 @@ fn sbr_real_library_matches_reference() { let high = if n >= 1024 { let oh = highpass(&o[oa..oa + n], rate, c.crossover_hz); let th = highpass(&t[ob..ob + n], rate, c.crossover_hz); + let rms = |v: &[f32]| (v.iter().map(|x| f64::from(*x).powi(2)).sum::() / v.len().max(1) as f64).sqrt(); + println!(" ch{ch} above-crossover RMS ours/ref = {:.4}", rms(&oh) / rms(&th).max(1e-12)); correlation(&oh, &th) } else { 0.0 @@ -2772,15 +2793,16 @@ fn sbr_real_library_matches_reference() { println!( " NOISE-FRACTION ceiling prediction (band_hz, f_noise, predicted_ceiling):" ); - for (band, signal, noise) in ec_aac::noise_fraction_table() { + for (band, signal, noise, out) in ec_aac::noise_fraction_table() { if signal + noise <= 0.0 { continue; } let f = noise / (signal + noise); println!( - " {:>6.0}Hz band{band:>3}: signal {signal:.3e} noise {noise:.3e} f_noise {f:.6} ceiling {:.4}", + " {:>6.0}Hz band{band:>3}: signal {signal:.3e} noise {noise:.3e} f_noise {f:.6} ceiling {:.4} realised/target {:.4}", band as f64 * band_hz, - (1.0 - f).max(0.0).sqrt() + (1.0 - f).max(0.0).sqrt(), + out / (signal + noise) ); } } @@ -3004,6 +3026,25 @@ fn sbr_real_library_matches_reference() { let win = &o[oa..oa + n]; let twin = &t[ob..ob + n]; let (vs_ref, vs_ours, ours_vs_ref) = hf_patch_simulator_qmf(win, twin); + // Per-QMF-band energy ratio and coherence, ours vs reference + // (the envelope-adjuster instrument: a level offset shows as + // a constant dB ratio, a gain-shape defect as per-band dB). + { + let (o_spec, t_spec, _) = qmf_domain_spec(win, twin); + println!(" ch{ch} QMF-BAND ours-vs-REFERENCE (band, ratio_dB, coherence):"); + for band in 0..o_spec.len().min(t_spec.len()).min(48) { + let (mut eo, mut et, mut cr, mut ci) = (0.0f64, 0.0f64, 0.0f64, 0.0f64); + for (a, b) in o_spec[band].iter().zip(&t_spec[band]) { + eo += a.norm_sqr(); + et += b.norm_sqr(); + let c = *a * b.conj(); + cr += c.re; + ci += c.im; + } + let coh = (cr * cr + ci * ci).sqrt() / (eo * et).sqrt().max(1e-30); + println!(" band{band:>3}: {:>7.2} dB coh {coh:.4}", 10.0 * (eo / et.max(1e-30)).log10()); + } + } let mean_in = |rows: &[(usize, f64)], lo: usize, hi: usize| { let vals: Vec = rows .iter() @@ -3358,12 +3399,12 @@ fn sbr_actual_noise_fraction() { // invoke this test by name, not as part of a parallel `cargo test` run. unsafe { std::env::remove_var("EC_AAC_SBR_NOISE_ZERO"); - std::env::set_var("EC_AAC_SBR_NOISE_FRACTION_DEBUG", "1"); + std::env::set_var("EC_AAC_SBR_NOISE_FRACTION", "1"); } let (ours_on, _, rate) = our_decode(&path, 0).expect("our_decode works (noise on)"); let bookkept = ec_aac::noise_fraction_table(); unsafe { - std::env::remove_var("EC_AAC_SBR_NOISE_FRACTION_DEBUG"); + std::env::remove_var("EC_AAC_SBR_NOISE_FRACTION"); std::env::set_var("EC_AAC_SBR_NOISE_ZERO", "1"); } let (ours_off, _, _) = our_decode(&path, 0).expect("our_decode works (noise zeroed)"); @@ -3415,7 +3456,7 @@ fn sbr_actual_noise_fraction() { let book = bookkept .iter() .find(|(b, ..)| *b == band) - .map(|(_, s, n)| if s + n > 0.0 { n / (s + n) } else { 0.0 }) + .map(|(_, s, n, _)| if s + n > 0.0 { n / (s + n) } else { 0.0 }) .unwrap_or(0.0); println!( " {hz:>6.0}Hz: on {e_on:.3e} off {e_off:.3e} actual {actual:.4} bookkept {book:.4}" @@ -4598,3 +4639,104 @@ fn sbr_hf_window_band_probe() { ); } } + +/// Round-59 residual locator: per-2048-sample-window corr at lag 0 (worst +/// windows, with the output frame index) plus a complex-STFT per-band +/// correlation (Parseval: equals the time-domain corr restricted to that +/// band, so it needs no calibration) with an ours-vs-ours self-check column. +#[test] +fn sbr_residual_locator() { + if !have_ffmpeg() { + return; + } + let home = std::env::var("HOME").unwrap(); + // `EC_AAC_SBR_LOCATOR_FILE` points the same instrument at any other + // HE-AAC file (e.g. a mono, uncoupled, noise-only probe encode). + let path = std::env::var("EC_AAC_SBR_LOCATOR_FILE") + .map(PathBuf::from) + .unwrap_or_else(|_| PathBuf::from(format!("{home}/Music/reeln.mp4"))); + if !path.exists() { + return; + } + let Some((ours, _, rate)) = our_decode(&path, 0) else { return }; + let theirs = ffmpeg_decode(&path, 0, ours.len()); + const W: usize = 2048; + const FFT_LEN: usize = 2048; + const HOP: usize = 1024; + let bins = FFT_LEN / 2 + 1; + let mut rfft = ec_dsp::RealFft::::new(FFT_LEN); + let win = ec_dsp::Window::::sine(FFT_LEN); + for ch in 0..ours.len() { + let n = ours[ch].len().min(theirs[ch].len()); + let (o, t) = (&ours[ch][..n], &theirs[ch][..n]); + let mut wins: Vec<(f64, usize)> = (0..n / W) + .map(|w| (correlation(&o[w * W..(w + 1) * W], &t[w * W..(w + 1) * W]), w)) + .collect(); + wins.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap()); + println!("ch{ch} worst windows (corr, frame): {:?}", &wins[..12]); + let hops = (n - FFT_LEN) / HOP + 1; + let mut spec = vec![ec_dsp::Complex::new(0.0f32, 0.0); bins]; + let mut acc = vec![[0.0f64; 3]; bins]; // re(o*conj t), |o|^2, |t|^2 + let mut os = vec![ec_dsp::Complex::new(0.0f32, 0.0); bins]; + for h in 0..hops { + let mut b = o[h * HOP..h * HOP + FFT_LEN].to_vec(); + win.apply(&mut b); + rfft.forward(&b, &mut spec); + os.copy_from_slice(&spec); + let mut b = t[h * HOP..h * HOP + FFT_LEN].to_vec(); + win.apply(&mut b); + rfft.forward(&b, &mut spec); + for k in 0..bins { + let (a, c) = (os[k], spec[k]); + acc[k][0] += f64::from(a.re * c.re + a.im * c.im); + acc[k][1] += f64::from(a.norm_sqr()); + acc[k][2] += f64::from(c.norm_sqr()); + } + } + let hz = f64::from(rate) / FFT_LEN as f64; + let tot: f64 = acc.iter().map(|a| a[1] + a[2]).sum(); + // With `EC_AAC_SBR_NOISE_FRACTION` set the decoder bookkeeps the + // dequantized target per QMF band; print it next to the reference's + // measured energy in the same band so a target-side (bitstream -> + // E_orig) tilt separates from an adjust/synthesis-side one. + if ch == 0 { + let band_hz = f64::from(rate) / 128.0; + for (band, sig, noi, out) in ec_aac::noise_fraction_table() { + let (lo, hi) = ( + (band as f64 * band_hz / hz) as usize, + ((band + 1) as f64 * band_hz / hz) as usize, + ); + let pt: f64 = (lo..hi.min(bins)).map(|k| acc[k][2]).sum(); + let po: f64 = (lo..hi.min(bins)).map(|k| acc[k][1]).sum(); + println!( + "TARGET band {band:>2} {:>6.0}Hz target {:.3e} realised/target {:.4} ref_pcm {:.3e} ours_pcm {:.3e} target/ref_pcm {:.3e}", + band as f64 * band_hz, + sig + noi, + out / (sig + noi), + pt, + po, + (sig + noi) / pt + ); + } + } + // group into 250 Hz bands up to 8 kHz, then 1 kHz + let mut edges: Vec = (0..=32).map(|i| ((i as f64 * 250.0) / hz) as usize).collect(); + edges.extend((9..=22).map(|i| ((i as f64 * 1000.0) / hz) as usize)); + for e in edges.windows(2) { + let (mut c, mut po, mut pt) = (0.0, 0.0, 0.0); + for k in e[0]..e[1].min(bins) { + c += acc[k][0]; + po += acc[k][1]; + pt += acc[k][2]; + } + println!( + "ch{ch} {:5.0}-{:5.0} Hz corr {:.5} rms ours/ref {:.4} energy share {:.4}", + e[0] as f64 * hz, + e[1] as f64 * hz, + c / (po * pt).sqrt(), + (po / pt).sqrt(), + (po + pt) / tot + ); + } + } +} diff --git a/scripts/aac-tables/sbrvalues.py b/scripts/aac-tables/sbrvalues.py new file mode 100644 index 00000000..e653c935 --- /dev/null +++ b/scripts/aac-tables/sbrvalues.py @@ -0,0 +1,182 @@ +#!/usr/bin/env python3 +"""Reads the delta every 3.0 dB envelope codeword carries off the reference +decoder's `env_facs_q V is invalid` range check, by ACCUMULATION. + +`sbrtables.py --stage values` applies a codeword once to a raw start value and +reads the delta from the out-of-range complaint. The 3.0 dB books ride a 6-bit +(5-bit balance) raw field but are checked against a 7-bit ceiling, so a single +positive 3.0 dB delta never trips it and every one was emitted as 0 +(ENV30_F/ENV30_T/ENVB30_F/ENVB30_T: 32/32/13/13 zeros). + +The check sees the ACCUMULATED value, and delta-time coding accumulates across +envelopes and frames: a `_T` codeword repeated for enough envelopes walks any +non-zero delta out of range, and a `_F` codeword is walked out by trusted +negative `_T` steps riding after it. The complaint reports the first value out +of range (mod 256); a tiny simulator predicts that value for every candidate +delta and the one candidate that reproduces every probe is the answer. Trusted +negative entries go through the same readout and must come back unchanged. + +Writes the values in place into crates/ec-aac/src/sbr_tables.rs. + + python3 scripts/aac-tables/sbrvalues.py +""" + +import os +import re +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +import sbrtables as T # noqa: E402 +from sbrprobe import silent # noqa: E402 + +RS = os.path.join(T.ROOT, "crates", "ec-aac", "src", "sbr_tables.rs") +KINDS = ["ENV30_T", "ENVB30_T", "ENV30_F", "ENVB30_F"] +INVALID = re.compile(r"env_facs_q (-?\d+) is invalid") +RUNS = 40 + + +def load_books(): + src = open(RS).read() + books = {} + for m in re.finditer(r"static (\w+): \[\(u8, u32, i32\); \d+\] = \[(.*?)\n\];", src, re.S): + books[m.group(1)] = { + (int(a), int(b)): int(c) + for a, b, c in re.findall(r"\((\d+), (\d+), (-?\d+)\)", m.group(2)) + } + return books + + +def by_value(book, v): + return T.as_bits(*next(lc for lc, d in book.items() if d == v)) + + +def first_invalid(err): + m = INVALID.search(err) + return int(m.group(1)) if m else None + + +def simulate(steps, scale, raw): + """First out-of-range `scale * value` (mod 256) along `raw + cumsum(steps)`.""" + acc = raw + for s in steps: + acc += s + v = scale * acc + if v < 0 or v > 127: + return v % 256 + return None + + +def probe_t(kind, book, cfg, tables, word, raw, balance): + """env0 F-coded from `raw` (no F slots: one band), env1 T-coded with `word`, + then RUNS frames with both envelopes T-coded with `word`. ch0 of a coupled + pair rides trusted zero words.""" + key = "env0b" if balance else "env0" + start = dict(cfg, **{key: [raw] * 8}) + run = dict(cfg, df_env=[1, 1] + [0] * 6, **{key: [raw] * 8}) + z = by_value(T_BOOK, 0) + ch0 = [z] if balance else [] + frames = [silent(cfg["sf_index"]), T.frame(start, tables, ch0 + [word])] + frames += [T.frame(run, tables, ch0 * 2 + [word, word])] * RUNS + return b"".join(frames), [None] + [None] * (2 * RUNS) # steps = word each + + +def probe_f(kind, book, cfg, tables, word, raw, balance, step_book, step): + """env0 F-coded from `raw` with `word` in band 1, env1 T-coded with band 0 + zero and band 1 `step`, then RUNS frames of the same T pair.""" + key = "env0b" if balance else "env0" + start = dict(cfg, df_env=[0, 1] + [0] * 6, **{key: [raw] * 8}) + run = dict(cfg, df_env=[1, 1] + [0] * 6, **{key: [raw] * 8}) + zf, zt = by_value(F_BOOK, 0), by_value(T_BOOK, 0) + s = by_value(step_book, step) + zs = by_value(T_BOOK if balance else step_book, 0) + ch0 = [zf, zt, zt] if balance else [] + ch0r = [zt, zt, zt, zt] if balance else [] + frames = [silent(cfg["sf_index"]), T.frame(start, tables, ch0 + [word, zs, s])] + frames += [T.frame(run, tables, ch0r + [zs, s, zs, s])] * 6 + return b"".join(frames), [None] + [step] * 13 + + +def read_book(oracle, kind, books): + book = books[kind] + balance = kind.startswith("ENVB") + scale = 2 if balance else 1 + span = 12 if balance else 31 + cands = range(-span, span + 1) + cfg, tables = T.recipe_config(kind) + raw_max = 31 if balance else 63 + out = {} + for lc in sorted(book): + word = T.as_bits(*lc) + obs = [] # (steps template, raw, observed) + alive = set(cands) + # Probe until exactly one candidate reproduces every observation. + if kind.endswith("_T"): + plan = [("t", raw, None) for raw in range(raw_max, -1, -1)] + else: + sb = books["ENVB30_T" if balance else "ENV30_T"] + neg = sorted({d for d in sb.values() if d < 0}) + plan = [("f", raw_max, s) for s in neg[:4]] + [("f", 0, s) for s in neg[:4]] + for mode, raw, s in plan: + if mode == "t": + data, steps = probe_t(kind, book, cfg, tables, word, raw, balance) + else: + data, steps = probe_f(kind, book, cfg, tables, word, raw, balance, sb, s) + err = oracle.one(f"acc:{kind}:{lc}:{mode}:{raw}:{s}", data) + got = first_invalid(err) + alive = { + d for d in alive + if simulate([d if x is None else x for x in steps], scale, raw) == got + } + if len(alive) <= 1: + break + if len(alive) != 1: + print(f" {kind} {lc}: UNRESOLVED, candidates {sorted(alive)}") + continue + d = next(iter(alive)) + old = book[lc] + flag = "" if old == d else (" (was 0)" if old == 0 else f" <-- DISAGREES with {old}") + print(f" {kind} {lc}: {d:>4}{flag}") + out[lc] = d + vals = sorted(out.values()) + complete = vals == list(cands) and len(out) == len(book) + print(f"{kind}: {len(out)}/{len(book)} read, values {'complete -%d..%d once each' % (span, span) if complete else 'NOT a permutation: ' + str(vals)}") + return out, complete + + +def main(): + books = load_books() + global F_BOOK, T_BOOK + F_BOOK, T_BOOK = books["ENV30_F"], books["ENV30_T"] + oracle = T.Oracle(12) + out = {} + try: + for kind in KINDS: + vals, complete = read_book(oracle, kind, books) + if complete: + out[kind] = vals + books[kind] = vals # later books ride on these + if kind == "ENV30_T": + T_BOOK = vals + finally: + oracle.save() + src = open(RS).read() + + def patch_block(m): + name, body = m.group(1), m.group(2) + if name not in out: + return m.group(0) + new = re.sub( + r"\((\d+), (\d+), (-?\d+)\)", + lambda t: f"({t.group(1)}, {t.group(2)}, {out[name][(int(t.group(1)), int(t.group(2)))]})", + body, + ) + return m.group(0).replace(body, new) + + src = re.sub(r"static (\w+): \[\(u8, u32, i32\); \d+\] = \[(.*?)\n\];", patch_block, src, flags=re.S) + open(RS, "w").write(src) + print(f"wrote {RS}: {sorted(out)}") + + +if __name__ == "__main__": + main()