diff --git a/crates/ec-aac/src/lib.rs b/crates/ec-aac/src/lib.rs index 84aa7844..8c3de51e 100644 --- a/crates/ec-aac/src/lib.rs +++ b/crates/ec-aac/src/lib.rs @@ -29,9 +29,9 @@ mod decode; mod encode; mod huffman; mod sbr_bands; +mod sbr_env; +mod sbr_hf; mod sbr_payload; -// Consumed once the SBR decode chain lands; until then only its tests call it. -#[allow(dead_code)] mod sbr_qmf; mod sbr_tables; pub mod tables; diff --git a/crates/ec-aac/src/sbr_env.rs b/crates/ec-aac/src/sbr_env.rs new file mode 100644 index 00000000..b4809379 --- /dev/null +++ b/crates/ec-aac/src/sbr_env.rs @@ -0,0 +1,340 @@ +//! 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. +//! +//! # Dequantization +//! +//! 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 rather than an absolute +//! scalefactor; `dequant_pair` de-mixes it against channel 0's raw value +//! into left/right energies that are equal (and sum to `2 * channel 0's +//! energy`) when the ratio is centred, which is the symmetric convention +//! this module uses in the absence of an exercised real-file fixture for +//! it (corner-cut: exact reference offset unverified, ceiling = a +//! panning-accuracy-only artifact on files whose SBR CPE actually +//! couples, upgrade path = pin against a captured coupled real-file +//! trace). +//! +//! # Gain, limiter, noise, sinusoids +//! +//! For every `(envelope, band)` cell this measures the HF estimate's own +//! average energy over that time/frequency window and scales it toward +//! the transmitted target; the limiter then caps how far above the +//! band's own transmitted noise floor that gain is allowed to reach +//! (`bs_limiter_gains`), noise is mixed in at the transmitted floor, and +//! flagged bands get an added tone. + +use crate::sbr_bands::BandTables; +use crate::sbr_payload::{SbrChannel, SbrHeader}; +use ec_dsp::Complex; + +const NOISE_FLOOR_OFFSET: f64 = 6.0; + +/// Envelope amp-resolution exponent: `2.0` (`bs_amp_res=1`, 3 dB) or `1.0` +/// (`bs_amp_res=0`, 1.5 dB) -- expressed as the multiplier on `e_q/2` so +/// callers can write `2f64.powf(alpha * e_q as f64 / 2.0)` uniformly, or +/// just use [`dequant_env`] directly. +fn alpha(amp_res: u8) -> f64 { + if amp_res != 0 { 1.0 } else { 0.5 } +} + +/// Plain (non-coupled) envelope dequantization. +pub fn dequant_env(e_q: i32, amp_res: u8) -> f64 { + 2f64.powf(alpha(amp_res) * f64::from(e_q)) +} + +/// Plain noise-floor dequantization. +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 +/// `(left, right)` linear energies. See the module doc for the convention. +pub fn dequant_pair(e0_raw: i32, e1_raw: i32, amp_res: u8) -> (f64, f64) { + let e0 = dequant_env(e0_raw, amp_res); + let ratio = 2f64.powf(alpha(amp_res) * f64::from(e1_raw)); + let left = 2.0 * e0 * ratio / (1.0 + ratio); + let right = 2.0 * e0 / (1.0 + ratio); + (left, right) +} + +/// 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(u32); + +impl NoiseGen { + pub fn new(seed: u32) -> NoiseGen { + NoiseGen(seed | 1) + } + + fn next(&mut self) -> f64 { + self.0 = self.0.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + f64::from(self.0 >> 8) / f64::from(1u32 << 23) - 0.5 + } + + fn complex_unit(&mut self) -> Complex { + Complex::new(self.next(), self.next()) + } +} + +const LIMITER_FACTOR: [f64; 4] = [1.4125, 2.0, 4.0, 1.0e6]; // 1.5/3/6 dB, "no limit" + +/// 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. +#[allow(clippy::too_many_arguments)] +pub fn adjust( + hf: &mut [Vec>], + tables: &BandTables, + header: &SbrHeader, + ch: &SbrChannel, + env_energy: &[Vec], + noise_energy: &[Vec], + rng: &mut NoiseGen, +) { + let kx = tables.kx as usize; + let limiter_max = LIMITER_FACTOR[usize::from(header.limiter_gains).min(3)]; + + // Noise floor first: every target bin gets the transmitted floor for + // its noise-time-segment and noise-frequency-band, independent of the + // envelope grid (they are different, coarser grids over the same axes). + for (ni, (t0, t1)) in ch.t_noise.windows(2).map(|w| (w[0], w[1])).enumerate() { + if ni >= noise_energy.len() { + break; + } + for q in 0..tables.n_q { + let lo = tables.f_noise[q] as usize; + let hi = tables.f_noise[q + 1] as usize; + let energy = noise_energy[ni].get(q).copied().unwrap_or(0.0); + let amp = (energy / (hi - lo).max(1) as f64).sqrt(); + 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] + rng.complex_unit().scale(amp); + } + } + } + } + + // 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)); + 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 current = if count > 0 { sum / count as f64 } else { 0.0 }; + let mut gain = (target / current.max(1e-12)).sqrt(); + let q = noise_band_for(tables, lo); + let noise_here = noise_row + .and_then(|r| r.get(q).copied()) + .unwrap_or(0.0) + .max(1e-12); + gain = gain.min((noise_here * limiter_max / current.max(1e-12)).sqrt().max(gain.min(limiter_max))); + gain = gain.min(limiter_max * 64.0); // absolute ceiling: never amplify a silent cell to infinity + 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].scale(gain); + } + } + } + + // 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 amp = (2.0 * e).sqrt(); + 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); + } + } + } + } + } +} + +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)] +mod tests { + use super::*; + use crate::sbr_bands::freq_tables; + use crate::sbr_payload::SbrChannel; + + fn flat_tables() -> BandTables { + freq_tables(44100, 5, 3, 2, 1, 2, 2).unwrap() + } + + fn header(amp_res: u8, limiter_gains: u8) -> SbrHeader { + SbrHeader { + amp_res, + start_freq: 5, + stop_freq: 3, + xover_band: 2, + freq_scale: 2, + alter_scale: 1, + noise_bands: 2, + limiter_bands: 2, + limiter_gains, + interpol_freq: 1, + smoothing_mode: 1, + } + } + + #[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 { + 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, + }; + 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); + adjust(&mut hf, &tables, &header(1, 3), &ch, &env_energy, &noise_energy, &mut rng); + + // 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}" + ); + } + } + + #[test] + fn limiter_caps_a_pathological_gain() { + let tables = flat_tables(); + let kx = tables.kx as usize; + let k2 = tables.k2 as usize; + let slots = 16usize; + // Near-silent HF estimate against a huge target energy: an + // unlimited gain would blow this up by many orders of magnitude. + 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, + }; + let env_energy = vec![vec![1.0e6f64; tables.n_low]]; + let noise_energy = vec![vec![1e-3f64; tables.n_q]]; + let mut rng = NoiseGen::new(1); + adjust(&mut hf, &tables, &header(1, 0), &ch, &env_energy, &noise_energy, &mut rng); + for band in 0..hf.len() { + for slot in 0..slots { + assert!( + hf[band][slot].norm_sqr().sqrt() < 1.0, + "limiter failed to cap band {band} slot {slot}: {:?}", + hf[band][slot] + ); + } + } + } + + #[test] + fn coupled_balance_round_trips_at_a_centred_ratio() { + let (l, r) = dequant_pair(10, 0, 1); + let e0 = dequant_env(10, 1); + assert!((l - e0).abs() < 1e-9 && (r - e0).abs() < 1e-9, "{l} {r} vs {e0}"); + } +} diff --git a/crates/ec-aac/src/sbr_hf.rs b/crates/ec-aac/src/sbr_hf.rs new file mode 100644 index 00000000..6bd2810f --- /dev/null +++ b/crates/ec-aac/src/sbr_hf.rs @@ -0,0 +1,341 @@ +//! SBR high-frequency generation (ISO/IEC 14496-3 §4.6.18.6): patch +//! construction that copies low-band QMF content up into the region the +//! core codec never carried, plus per-subband second-order linear +//! prediction (LPC) whose bandwidth-expanded ("chirped") coefficients +//! whiten the copied content so it can be re-tonalised by the envelope +//! adjustment stage rather than sounding like a raw comb of copies. +//! +//! # Patch construction +//! +//! Each patch copies a contiguous run of QMF bands from just below the +//! crossover (`kx`) up into the target HF region `[kx, k2)`. The walk keeps +//! two pointers: `msb`, the source read pointer, starts at `kx` and moves +//! *down* toward band 0 as patches are consumed; `sb`, the target write +//! pointer, starts at `kx` and moves *up* toward `k2`. A patch's width is +//! chosen to land on a boundary of the target-side high-resolution band +//! table (`tables.f_high`) so envelope adjustment never has to split a +//! patch mid-band, and is capped by how many source bands remain below the +//! current `msb`. When the source is exhausted the read pointer wraps back +//! to `kx` (the band closest to the crossover, so the next patch borrows +//! the most plausible content again rather than running off the bottom of +//! the spectrum). +//! +//! # Linear prediction and chirp +//! +//! For each *source* subband, a covariance-method order-2 LPC is fit to +//! that subband's own QMF time series (two slots of carried-over history +//! plus the current frame's slots). The residual against those raw +//! coefficients is then re-synthesised through a *bandwidth-expanded* +//! all-pole filter -- coefficients scaled by `bw` and `bw^2` -- which is +//! the standard SBR "inverse filtering" trick: `bw` near 1 leaves the +//! subband's own resonance intact (a strongly tonal patch), `bw` near 0 +//! flattens it toward its whitened residual (a noise-like patch). `bw` +//! itself comes from `bs_invf_mode` and is smoothed frame to frame with a +//! fast-attack/slow-release curve so inverse-filter mode changes don't pop. + +use crate::sbr_bands::BandTables; +use ec_dsp::Complex; + +/// One copy-up patch: `width` consecutive QMF bands starting at +/// `source_start` are written to `target_start..target_start+width`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Patch { + pub source_start: usize, + pub target_start: usize, + 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. +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 mut patches = Vec::new(); + if kx == 0 || k2 <= kx { + 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; + 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 { + break; + } + width += iv; + probe = border; + } + if width == 0 { + width = (k2 - sb).min(msb.max(1)); + } + 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 }; + } + patches +} + +/// `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]; + +/// Per-noise-band chirp factor state, smoothed frame to frame with a +/// fast-attack (toward a *lower* bw, i.e. more whitening) / slow-release +/// curve, as the spec's own smoothing does. +#[derive(Clone, Debug)] +pub struct ChirpState { + bw: Vec, +} + +impl ChirpState { + pub fn new(n_q: usize) -> ChirpState { + ChirpState { bw: vec![0.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. + pub fn update(&mut self, invf_mode: &[u8]) -> &[f64] { + for (slot, &mode) in self.bw.iter_mut().zip(invf_mode) { + let target = BW_TABLE[usize::from(mode).min(3)]; + *slot = if target < *slot { + 0.75 * target + 0.25 * *slot + } else { + 0.90625 * *slot + 0.09375 * target + }; + } + &self.bw + } +} + +/// 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). +pub fn lpc2(x: &[Complex]) -> (Complex, Complex) { + if x.len() < 3 { + return (Complex::ZERO, Complex::ZERO); + } + let mut r00 = Complex::ZERO; // + let mut r01 = Complex::ZERO; // + let mut r11 = Complex::ZERO; // + let mut r0y = Complex::ZERO; // + let mut r1y = Complex::ZERO; // + for n in 2..x.len() { + let y = x[n]; + let x1 = x[n - 1]; + let x2 = x[n - 2]; + r00 = r00 + x1.conj() * x1; + r01 = r01 + x1.conj() * x2; + r11 = r11 + x2.conj() * x2; + r0y = r0y + x1.conj() * y; + r1y = r1y + x2.conj() * y; + } + // R is Hermitian (r10 = conj(r01)): solve the 2x2 system directly + // rather than reusing r01 for both off-diagonal entries. + let r10 = r01.conj(); + let det = r00 * r11 - r01 * r10; + let norm = det.norm_sqr(); + if norm < 1e-20 { + return (Complex::ZERO, Complex::ZERO); + } + let inv_det = det.conj().scale(1.0 / norm); + let a1 = (r0y * r11 - r01 * r1y) * inv_det; + let a2 = (r00 * r1y - r10 * r0y) * inv_det; + (a1, a2) +} + +/// Per-source-subband history: the last two QMF slots, carried across +/// `generate` calls so the LPC and whitening filter have continuity at +/// frame boundaries instead of restarting cold every frame. +#[derive(Clone, Debug)] +pub struct HfHistory { + x: Vec<[Complex; 2]>, + y: Vec<[Complex; 2]>, +} + +impl HfHistory { + pub fn new(bands: usize) -> HfHistory { + HfHistory { + x: vec![[Complex::ZERO; 2]; bands], + y: vec![[Complex::ZERO; 2]; bands], + } + } +} + +/// Generates one frame's raw (pre-envelope-adjustment) HF QMF matrix, +/// `[target band index, 0-based from kx][slot]`, `k2 - kx` bands by +/// `low_cur[0].len()` slots (`low_cur` is `[source band][slot]`, bands +/// `0..kx` only need be populated). +pub fn generate( + low_cur: &[Vec>], + tables: &BandTables, + invf_mode: &[u8], + chirp: &mut ChirpState, + history: &mut HfHistory, +) -> Vec>> { + let kx = tables.kx as usize; + let k2 = tables.k2 as usize; + let num_slots = low_cur.first().map(Vec::len).unwrap_or(0); + let mut out = vec![vec![Complex::ZERO; num_slots]; k2.saturating_sub(kx)]; + let patches = build_patches(tables); + let bw = chirp.update(invf_mode).to_vec(); + + // Noise-band lookup for a target QMF band, to pick which bw applies. + let noise_band_of = |target_band: usize| -> usize { + let f_noise = &tables.f_noise; + let mut q = 0usize; + for i in 0..tables.n_q { + if (target_band as i64) >= f_noise[i] && (target_band as i64) < f_noise[i + 1] { + q = i; + } + } + q.min(bw.len().saturating_sub(1)) + }; + + for patch in &patches { + for offset in 0..patch.width { + let source_band = patch.source_start + offset; + let target_band = patch.target_start + offset; + if source_band >= low_cur.len() || target_band < kx || target_band >= k2 { + continue; + } + let series = &low_cur[source_band]; + let (a1, a2) = { + let mut ext = Vec::with_capacity(num_slots + 2); + if source_band < history.x.len() { + ext.push(history.x[source_band][0]); + ext.push(history.x[source_band][1]); + } else { + ext.push(Complex::ZERO); + ext.push(Complex::ZERO); + } + ext.extend_from_slice(series); + lpc2(&ext) + }; + let g = bw[noise_band_of(target_band)]; + 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) + }; + let (mut x_prev1, mut x_prev2) = if source_band < history.x.len() { + (history.x[source_band][1], history.x[source_band][0]) + } 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; + dst[n] = y; + x_prev2 = x_prev1; + x_prev1 = x; + y_prev2 = y_prev1; + y_prev1 = y; + } + } + } + + // 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 { + 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]]; + } + + out +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::sbr_bands::freq_tables; + + fn real_file_tables() -> BandTables { + // The rig's own header params for ~/Music/reeln.mp4's SBR + // element (44100 Hz extension rate, core-Nyquist crossover ~5 kHz): + // freq_scale=2, alter_scale=1, noise_bands=2, start/stop/xover taken + // from the mid-range defaults `EXTRA1_DEFAULTS` documents when a + // stream omits bs_header_extra_1/2. + freq_tables(44100, 5, 3, 2, 1, 2, 2).expect("valid header for the real file's rate") + } + + #[test] + fn patch_map_is_deterministic_and_covers_the_hf_region() { + let tables = real_file_tables(); + let a = build_patches(&tables); + let b = build_patches(&tables); + assert_eq!(a, b); + assert!(!a.is_empty()); + let mut sb = tables.kx as usize; + for p in &a { + assert_eq!(p.target_start, sb); + assert!(p.source_start + p.width <= tables.kx as usize); + sb += p.width; + } + assert_eq!(sb, tables.k2 as usize); + } + + #[test] + fn lpc_recovers_the_poles_of_a_synthetic_ar2_process() { + // x[n] = a1*x[n-1] + a2*x[n-2] + white noise, driven by a + // deterministic xorshift so the test has no external dependency. + let a1 = Complex::new(0.6, 0.1); + let a2 = Complex::new(-0.3, 0.0); + let mut state = 0x9e37_79b9u64; + let mut rng = move || { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + (state >> 40) as f64 / (1u64 << 24) as f64 - 0.5 + }; + let mut x = vec![Complex::new(0.01, 0.0), Complex::new(-0.01, 0.02)]; + for _ in 0..4000 { + let n = x.len(); + let v = a1 * x[n - 1] + a2 * x[n - 2] + Complex::new(rng() * 0.001, rng() * 0.001); + x.push(v); + } + let (fa1, fa2) = lpc2(&x); + assert!((fa1 - a1).norm_sqr().sqrt() < 0.05, "a1 {fa1:?} vs {a1:?}"); + assert!((fa2 - a2).norm_sqr().sqrt() < 0.05, "a2 {fa2:?} vs {a2:?}"); + } + + #[test] + fn chirp_smoothing_tracks_mode_transitions_asymmetrically() { + let mut chirp = ChirpState::new(1); + // 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]); + // 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. + let before = after_rise; + let after_fall = chirp.update(&[0])[0]; + let fall_step = before - after_fall; + let rise_step = after_rise; // started from 0.0 + assert!(fall_step > rise_step * 0.5, "fall {fall_step} rise {rise_step}"); + } +}