From 363af1c85c8b4d3f44f927a0f54b9eae55ad46a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 21 Aug 2026 00:49:47 +0300 Subject: [PATCH] fix(aac-sbr): spec-structured envelope adjuster (per-subband gains, limiter/boost with S_M and Q_M, V-table noise, sinusoid phases, slot smoothing, l_A/delta, 6-slot tHFAdj alignment, class-correct noise border, coupled noise dequant) reeln full 0.9927/0.9918 -> 0.9953/0.9946, above-5k 0.9868/0.9918 -> 0.9985/0.9984, lag 385 -> 1. --- crates/ec-aac/src/sbr_chain.rs | 85 +- crates/ec-aac/src/sbr_env.rs | 1332 +++++++++--------------------- crates/ec-aac/src/sbr_payload.rs | 43 +- crates/ec-aac/src/sbr_tables.rs | 518 ++++++++++++ 4 files changed, 1017 insertions(+), 961 deletions(-) diff --git a/crates/ec-aac/src/sbr_chain.rs b/crates/ec-aac/src/sbr_chain.rs index e06b73b3..f53e0333 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); } @@ -528,6 +587,7 @@ mod tests { add_harmonic: None, df_env: vec![], df_noise: vec![], + l_a: -1, } } @@ -551,6 +611,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 +711,7 @@ mod tests { .map(|i| ChannelState::new(n_q, 10 + i as u32)) .collect(), last_data: None, + last_header: None, }, ); chain @@ -694,6 +756,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..09b0ae8e 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,18 +30,17 @@ 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)`. +/// §4.6.18.7.2 carries an extra `* 64` here; it is a pure scale on the +/// whole HF region (the gain `sqrt(E_orig/E_curr)` cancels our own QMF +/// scale otherwise), and this chain's QMF domain is calibrated without it +/// (see `sbr_chain`'s OUTPUT_SCALE handling). pub fn dequant_env(e_q: i32, amp_res: u8) -> f64 { 2f64.powf(alpha(amp_res) * f64::from(e_q)) } -/// 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)) } @@ -76,24 +48,11 @@ pub fn dequant_noise(q_q: i32) -> f64 { /// 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. +/// `ratio = 2^(pan - panOffset)` where `pan` is the RAW balance value and +/// `panOffset` is 24 at `bs_amp_res=0` or 12 at `bs_amp_res=1`; +/// `env0 = 2*Ecurr/(1+ratio)`, `env1 = 2*Ecurr*ratio/(1+ratio)`. +/// `header_amp_res` 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 }; @@ -103,9 +62,18 @@ pub fn dequant_pair(e0_raw: i32, pan_raw: i32, env_amp_res: u8, header_amp_res: (env0, env1) } +/// Coupled noise-floor pair (§4.6.18.7.2): `Q0 = 2^(NOISE_FLOOR_OFFSET - q0 + 1) +/// / (1 + 2^(12 - q1))`, `Q1 = Q0 * 2^(12 - q1)`. +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 - 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], @@ -116,188 +84,116 @@ pub fn dequantize_frame( // 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 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, header.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)`. +pub fn noise_fraction_table() -> Vec<(usize, f64, f64)> { + let mut out: Vec<(usize, 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,265 @@ 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() - } 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; - } - 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) - } else { - 1.0 + // 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; } - }) - .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 { - 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), - 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], - ); + 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)); } } - 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]); + 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; + } } - // (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; + 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 { + 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 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); - } - } + let v = sum / (slots * (hi.saturating_sub(lo)).max(1) as f64); + for m in lo..hi { + e_curr[m] = v; } - 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, - )) + // 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 { - None - } - } else { - None - }; - // `bs_interpol_freq` (per-subband linear interpolation of these sfb - // gains, Sec 4.6.18.7.6) was tried here: a centre-frequency lerp - // between neighbouring sfbs' flat gain values, applied whenever - // `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 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; - } + (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; } + gain[e][m] = gain[e][m].min(g_max); } - } - 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)); + 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!( - "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 - }, + "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, + hi - lo, ); } } - - // 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 { + 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)); } } } } } - - // (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; - } + 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 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; + 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 { + 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), + }; + 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 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; + } + state.index_noise = (state.index_noise + m_max) & 0x1ff; + state.index_sine = (state.index_sine + 1) & 3; } } - q } #[cfg(test)] @@ -878,237 +490,85 @@ 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, } } - /// (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_plain = dequant_env(10, 1); - assert!( - (e0 - e0_plain).abs() < 1e-6 && (e1 - e0_plain).abs() < 1e-6, - "{e0} {e1} vs {e0_plain}" - ); + 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); 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, 12); + 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}"); diff --git a/crates/ec-aac/src/sbr_payload.rs b/crates/ec-aac/src/sbr_payload.rs index 5df71cfd..5dab5008 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,10 @@ 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, } /// One `sbr_data()` frame: one channel for an SCE, two for a CPE. @@ -79,31 +83,41 @@ struct Grid { freq_res: Vec, t_env: Vec, t_noise: Vec, + l_a: i64, } 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, } } } @@ -237,7 +251,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 +299,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 +339,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)) } } } @@ -628,6 +642,7 @@ 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, }); } diff --git a/crates/ec-aac/src/sbr_tables.rs b/crates/ec-aac/src/sbr_tables.rs index 3f13ea10..c3ccaa21 100644 --- a/crates/ec-aac/src/sbr_tables.rs +++ b/crates/ec-aac/src/sbr_tables.rs @@ -749,6 +749,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::*;