diff --git a/crates/ec-aac/src/lib.rs b/crates/ec-aac/src/lib.rs index 2175849a..75c5aab7 100644 --- a/crates/ec-aac/src/lib.rs +++ b/crates/ec-aac/src/lib.rs @@ -36,6 +36,7 @@ mod sbr_env; mod sbr_hf; mod sbr_payload; pub mod sbr_qmf; +mod sbr_qmf_window; mod sbr_tables; pub mod tables; diff --git a/crates/ec-aac/src/sbr_hf.rs b/crates/ec-aac/src/sbr_hf.rs index 05fdf009..40155884 100644 --- a/crates/ec-aac/src/sbr_hf.rs +++ b/crates/ec-aac/src/sbr_hf.rs @@ -102,12 +102,13 @@ use ec_dsp::Complex; /// Returns the signed number of `pi/2` quarter-turns per QMF slot that /// *would* need to be applied to restore frequency-pure placement. #[allow(dead_code)] // documentation of the characterized convention; tests call it -pub(crate) fn band_shift_correction(target_band: usize, source_band: usize) -> i64 { - match (target_band as i64 - source_band as i64).rem_euclid(4) { - 1 => 1, - 3 => -1, - _ => 0, - } +pub(crate) fn band_shift_correction(_target_band: usize, _source_band: usize) -> i64 { + // The fitted Kaiser bank's odd-stacked convention needed a per-slot + // quarter-turn correction here (see the doc above); the normative + // ISO/IEC 14496-3 4.6.18.4/4.6.18.8.2 QMF pair in `sbr_qmf` carries its + // own correct phase from the spec equations directly, so patching needs + // no extra rotation at this site. + 0 } /// One copy-up patch: `width` consecutive QMF bands starting at diff --git a/crates/ec-aac/src/sbr_qmf.rs b/crates/ec-aac/src/sbr_qmf.rs index 2a39599a..96524792 100644 --- a/crates/ec-aac/src/sbr_qmf.rs +++ b/crates/ec-aac/src/sbr_qmf.rs @@ -1,51 +1,36 @@ -//! The SBR QMF filterbank pair: 32-band complex analysis and 64-band complex -//! synthesis, the polyphase machinery HE-AAC's spectral band replication is -//! built on (core PCM in, complex subband slots out; complex subband slots -//! in, doubled-rate PCM out). +//! The SBR QMF filterbank pair: normative ISO/IEC 14496-3 4.6.18.4 (64-band +//! analysis, folded to a shared core) and 4.6.18.8.2 (64-band synthesis) +//! polyphase machinery HE-AAC's spectral band replication is built on. //! -//! # Where the prototype comes from +//! # Bank sharing and the 32-band bridge //! -//! The 640-tap prototype is a **numeric design**, not a transcription: a -//! windowed-sinc lowpass (cutoff at a quarter of the subband spacing, giving -//! adjacent bands their -6 dB crossover) shaped by a Kaiser window (`beta = -//! `[`KAISER_BETA`], found by a round-trip-correlation sweep -- see below). -//! Each bank modulates its own cutoff-matched prototype with an odd-stacked -//! complex-exponential kernel `exp(+i * (k+0.5) * (pi/bands) * (n + bands/2))` -//! -- the same phasing the classical polyphase-plus-cosine subband filter -//! (the M-band analysis filter MPEG audio popularized) uses to make -//! neighbouring bands' aliases cancel, carried here into a complex (analytic) -//! bank so it has the phase HE-AAC's QMF pair needs: a 32-channel, -//! 2x-oversampled complex analysis bank (hop 32, matching the AAC-LC core's -//! half-rate operation) transposed into a 64-channel critically-sampled -//! complex synthesis bank (hop 64) whose output takes the real part of the -//! modulated sum. Nothing here was copied from the reference decoder; the -//! coefficients are computed at construction time from the formulas above. +//! The spec defines two analysis banks (32-band, 4.6.18.4.1, and 64-band, +//! 4.6.18.4) and two synthesis banks (64-band, 4.6.18.8.2, and a downsampled +//! 32-band variant, 4.6.18.8.3). A numpy round-trip campaign (see +//! `scripts/aac-tables/qmf_check.py` and the ledger, round "sbr-hunt") found +//! the 64-band analysis/synthesis pair self-consistent to `corr=0.999999` +//! against the literal spec equations, but the 32-band analysis and 32-band +//! downsampled synthesis equations, and the 32-into-64 zero-padding bridge +//! the SBR core signal actually needs, never cleared 0.7 correlation under +//! the same exact-equation reading. Zero-stuffing the 32 core samples to 64 +//! (`x64[2m] = 2*x32[m]`, odd samples 0) and running them through the +//! VERIFIED 64-band analysis, keeping bands `0..32` and dropping the +//! zero-stuffing image that lands in bands `32..64`, reached `corr=0.9994` +//! against an ideal band-limited 2x upsample -- short of the 0.9999 numpy +//! target but a real, spec-traceable near-PR bank, not a fitted +//! approximation. [`Analysis`] and [`HfAnalysis`] therefore share one +//! [`QmfAnalysis64`] core: the difference between them is only whether the +//! caller has 32 core samples (zero-stuffed by [`Analysis`]) or 64 +//! already-doubled-rate samples ([`HfAnalysis`], used only for measurement). +//! [`Synthesis`] is the 64-band bank directly, unmodified for either caller. //! -//! At these sizes (640 taps, 32/64 channels) a direct matrix multiply against -//! precomputed modulation tables is simpler than routing through a plan-based -//! transform and this is not a perf-sensitive slice, so that is what both -//! banks do. -//! -//! # Convention and prototype, as found by search -//! -//! The round-trip acceptance test below (`round_trip_reconstructs_the_passband`) -//! needed two things to clear its `>= 0.9999` correlation bar. First, the -//! phase-reference offset in `theta`: `n + bands/2`, not `n - bands/2` -- -//! the sign that makes analysis and synthesis phase-track each other instead -//! of fighting, found by brute-force scoring every offset/sign combination -//! in a small discrete convention space against the round-trip correlation -//! itself (bare sign flip alone only reached ~0.69). With that convention -//! settled, correlation plateaued at ~0.9978 regardless of further phase -//! tweaks -- a prototype-shape ceiling, not a phase bug. Sweeping the Kaiser -//! `beta` against the same round-trip metric (a 1-D search on the composite -//! transfer function's flatness, per the windowed-sinc design already in -//! use) pushed correlation to ~0.99995 at `beta = 45`, comfortably inside the -//! near-perfect-reconstruction crossover/stopband bounds -//! `prototype_is_near_perfect_reconstruction` also checks. Measured -//! algorithmic delay at this convention is 898 samples (in the documented -//! ~962-sample neighbourhood for this design's prototype length and hop -//! sizes). +//! The Kaiser-windowed fitted bank this file used to build at construction +//! time (`prototype`/`theta`/`modulation_tables`/`analytic_gain`, tuned by a +//! round-trip-correlation sweep) is gone; the coefficients now come from the +//! checksum-pinned normative 640-tap window in +//! [`crate::sbr_qmf_window::QMF_WINDOW`]. +use crate::sbr_qmf_window::QMF_WINDOW; use ec_dsp::Complex; /// Prototype filter length shared by both banks (`10 * 64`). @@ -54,140 +39,87 @@ pub const PROTO_LEN: usize = 640; pub const ANALYSIS_BANDS: usize = 32; /// Synthesis channel count (twice the core's, spanning the doubled band). pub const SYNTHESIS_BANDS: usize = 64; -/// Kaiser window `beta` both banks' prototypes are shaped with. Found by a -/// round-trip-correlation sweep (see the module doc): the crossover/stopband -/// shape barely moves with `beta` in this range, but reconstruction accuracy -/// keeps improving out to about here before the wider main lobe starts -/// costing it back. -const KAISER_BETA: f64 = 45.0; -/// Modified Bessel function of the first kind, order 0, by its power series. -/// Converges fast for the arguments a Kaiser window needs (`beta` in the -/// single digits): the series is cut once a term stops moving the sum. -fn bessel_i0(x: f64) -> f64 { - let mut term = 1.0f64; - let mut sum = 1.0f64; - let mut m = 1.0f64; - let half_x = x / 2.0; - loop { - term *= (half_x / m).powi(2); - if term < sum * 1e-16 { - break; - } - sum += term; - m += 1.0; - } - sum +/// Zero-stuffing gain the 32-into-64 bridge needs to read back unity +/// amplitude (numpy-measured: `gain=2.0` gives `amp_ratio ~ 0.999`, `gain=1` +/// halves it -- the standard zero-stuffing compensation for a 2x upsample). +const ZERO_STUFF_GAIN: f64 = 2.0; + +/// The shared ISO/IEC 14496-3 4.6.18.4 64-band analysis core: `PROTO_LEN` +/// real history samples in (newest inserted last, matching PCM order), +/// `SYNTHESIS_BANDS` complex subbands out per slot of `SYNTHESIS_BANDS` new +/// samples. +struct QmfAnalysis64 { + hist: [f64; PROTO_LEN], + cos_tab: Vec, + sin_tab: Vec, } -/// Normalized sinc, `sin(pi x) / (pi x)`, with the removable singularity at 0. -fn sinc(x: f64) -> f64 { - if x.abs() < 1e-12 { - 1.0 - } else { - let px = std::f64::consts::PI * x; - px.sin() / px +impl QmfAnalysis64 { + fn new() -> QmfAnalysis64 { + let mut cos_tab = vec![0.0f64; SYNTHESIS_BANDS * 128]; + let mut sin_tab = vec![0.0f64; SYNTHESIS_BANDS * 128]; + for k in 0..SYNTHESIS_BANDS { + for n in 0..128 { + // X[k] = sum_n u[n] * exp(j*pi/128*(k+0.5)*(2n-1)) + let theta = std::f64::consts::PI / 128.0 + * (k as f64 + 0.5) + * (2.0 * n as f64 - 1.0); + cos_tab[k * 128 + n] = theta.cos(); + sin_tab[k * 128 + n] = theta.sin(); + } + } + QmfAnalysis64 { + hist: [0.0; PROTO_LEN], + cos_tab, + sin_tab, + } } -} - -/// The windowed-sinc lowpass prototype at cutoff `fc` (rad/sample), shaped by -/// a Kaiser window with `beta`. Each bank calls this with its own cutoff: the -/// two banks run at different sample rates (the core rate for analysis, the -/// doubled rate for synthesis) and so need different cutoffs to put the -/// adjacent-channel crossover at each bank's own `-6 dB` point, even though -/// both are the same design method. -fn prototype(len: usize, fc: f64, beta: f64) -> Vec { - let center = (len - 1) as f64 / 2.0; - let denom = bessel_i0(beta); - let norm = fc / std::f64::consts::PI; - (0..len) - .map(|n| { - let t = n as f64 - center; - let lp = norm * sinc(norm * t); - let a = 2.0 * n as f64 / (len - 1) as f64 - 1.0; - let kaiser = bessel_i0(beta * (1.0 - a * a).max(0.0).sqrt()) / denom; - lp * kaiser - }) - .collect() -} -/// The angular argument: `(k+0.5) * (pi/bands) * (n + bands/2)`. This is the -/// odd-stacked cosine-modulated filter bank phasing (the same shape the -/// classical polyphase-plus-DCT subband filter uses): the carrier for band -/// `k` sits at the centre of its slice of this bank's Nyquist range, -/// `(k+0.5) * pi/bands`, but the phase reference is offset by `bands/2` -/// samples rather than centred on the whole 640-tap window. That specific -/// small offset, and its sign (`+ bands/2`, found by search -- `- bands/2` -/// self-cancels on overlap-add), is what makes neighbouring bands' aliases -/// cancel instead of the bands' own energy folding on itself every hop -- -/// the difference between this design reconstructing at all and the -/// flat/self-cancelling result a window-centred or oppositely-signed phase -/// gives. -fn theta(k: usize, n: usize, bands: usize, omega_step: f64) -> f64 { - omega_step * (k as f64 + 0.5) * (n as f64 + bands as f64 / 2.0) -} - -/// Precomputes `gain * h[n] * cos(theta(k,n))` and `gain * h[n] * -/// sin(theta(k,n))` for every `(k, n)` pair, flattened `k`-major: the -/// modulation matrix both banks multiply their sample window against. -/// -/// `gain` is each bank's own analytic-tone normalization (see -/// [`analytic_gain`]): without it a real input tone demodulates to half its -/// own amplitude (the standard single-sideband factor of a cosine/sine -/// modulated complex filter), and that same shortfall compounds across the -/// analysis+synthesis pair -- discovered as a ~100x round-trip amplitude -/// deficit (correlation-only checks never caught it, since normalized -/// cross-correlation is scale-invariant) that fed straight into -/// `sbr_env::adjust`'s `target/current` gain match and produced the SBR -/// chain's real-file blowup. -fn modulation_tables(h: &[f64], bands: usize, omega_step: f64, gain: f64) -> (Vec, Vec) { - let len = h.len(); - let mut cos_tab = vec![0.0f64; bands * len]; - let mut sin_tab = vec![0.0f64; bands * len]; - for k in 0..bands { - for n in 0..len { - let th = theta(k, n, bands, omega_step); - cos_tab[k * len + n] = gain * h[n] * th.cos(); - sin_tab[k * len + n] = gain * h[n] * th.sin(); + fn process_slot(&mut self, samples64: &[f64; SYNTHESIS_BANDS]) -> [Complex; SYNTHESIS_BANDS] { + for &s in samples64 { + self.hist.copy_within(0..PROTO_LEN - 1, 1); + self.hist[0] = s; + } + // Z[n] = x[n]*c[n], n=0..639; u[n] = sum_{j=0}^{4} Z[n+128j], n=0..127 + let mut u = [0.0f64; 128]; + for (n, uu) in u.iter_mut().enumerate() { + let mut acc = 0.0; + for j in 0..5 { + let idx = n + 128 * j; + acc += self.hist[idx] * QMF_WINDOW[idx]; + } + *uu = acc; + } + let mut out = [Complex::new(0.0, 0.0); SYNTHESIS_BANDS]; + for (k, slot) in out.iter_mut().enumerate() { + let row = k * 128; + let mut re = 0.0f64; + let mut im = 0.0f64; + for n in 0..128 { + re += u[n] * self.cos_tab[row + n]; + im += u[n] * self.sin_tab[row + n]; + } + *slot = Complex::new(re, im); } + out } - (cos_tab, sin_tab) -} - -/// The per-bank analytic-tone gain correction: `2 / sum(h)`. A cosine/sine -/// modulated filter bank demodulates a real input tone to half its -/// amplitude times the prototype's own DC gain (`sum(h)`, ~1 for a properly -/// normalized lowpass but not exactly, since the Kaiser window shaves a -/// little energy off); multiplying the modulation table by this restores -/// unity gain (a real tone of amplitude `A` in gives subband magnitude `A` -/// out), which is what makes an analysis-alone reading physically -/// comparable to the transmitted envelope target, and what makes a -/// synthesis-alone reading turn a subband value back into the PCM amplitude -/// it represents. -fn analytic_gain(h: &[f64]) -> f64 { - 2.0 / h.iter().sum::() } -/// The 32-band complex analysis QMF bank: core PCM in, complex subband slots -/// out, one slot per 32 input samples. +/// The 32-band bridge: core PCM in (32 samples/slot), complex subband slots +/// out (32/slot), via zero-stuffing into the verified 64-band core and +/// keeping the low half (see the module doc for why this replaces a native +/// 32-band analysis). pub struct Analysis { - hist: Vec, - cos_tab: Vec, - sin_tab: Vec, + core: QmfAnalysis64, } impl Analysis { /// A fresh bank with an all-zero history (the usual filter startup /// transient applies to its first ~`PROTO_LEN` output samples). pub fn new() -> Analysis { - let omega_step = std::f64::consts::PI / (2.0 * ANALYSIS_BANDS as f64); - let h = prototype(PROTO_LEN, omega_step, KAISER_BETA); - let gain = analytic_gain(&h); - let (cos_tab, sin_tab) = modulation_tables(&h, ANALYSIS_BANDS, omega_step, gain); Analysis { - hist: vec![0.0; PROTO_LEN], - cos_tab, - sin_tab, + core: QmfAnalysis64::new(), } } @@ -198,22 +130,13 @@ impl Analysis { &mut self, samples: &[f32; ANALYSIS_BANDS], ) -> [Complex; ANALYSIS_BANDS] { - for &s in samples { - self.hist.copy_within(0..PROTO_LEN - 1, 1); - self.hist[0] = s as f64; + let mut x64 = [0.0f64; SYNTHESIS_BANDS]; + for (m, &s) in samples.iter().enumerate() { + x64[2 * m] = ZERO_STUFF_GAIN * s as f64; } + let full = self.core.process_slot(&x64); let mut out = [Complex::new(0.0, 0.0); ANALYSIS_BANDS]; - for (k, slot) in out.iter_mut().enumerate() { - let row = k * PROTO_LEN; - let mut re = 0.0f64; - let mut im = 0.0f64; - for n in 0..PROTO_LEN { - let x = self.hist[n]; - re += x * self.cos_tab[row + n]; - im += x * self.sin_tab[row + n]; - } - *slot = Complex::new(re, im); - } + out.copy_from_slice(&full[0..ANALYSIS_BANDS]); out } } @@ -224,33 +147,24 @@ impl Default for Analysis { } } -/// A [`SYNTHESIS_BANDS`]-channel complex analysis bank sharing [`Synthesis`]'s -/// own cutoff/phase convention (same `omega_step`, same prototype), forward -/// direction: doubled-rate PCM in, complex subband slots out, one slot per +/// The same [`QmfAnalysis64`] core run directly on already-doubled-rate +/// samples: doubled-rate PCM in, complex subband slots out, one slot per /// [`SYNTHESIS_BANDS`] input samples. The decoder itself never runs this -- /// it only ever synthesizes at this band count, from HF-generated subbands, /// never analyzes a full-rate PCM signal back into them -- so this exists /// for exact QMF-domain measurement only (round-46's third-witness /// instrument): it lets a test read the reference decoder's and our own /// already-decoded 44100Hz output straight into the same 64-band grid the -/// patch map's band indices (`rate/128`-wide, matching `SYNTHESIS_BANDS`'s -/// own `omega_step`) are defined in, with no STFT-bin-width approximation. +/// patch map's band indices are defined in, with no STFT-bin-width +/// approximation. pub struct HfAnalysis { - hist: Vec, - cos_tab: Vec, - sin_tab: Vec, + core: QmfAnalysis64, } impl HfAnalysis { pub fn new() -> HfAnalysis { - let omega_step = std::f64::consts::PI / (2.0 * SYNTHESIS_BANDS as f64); - let h = prototype(PROTO_LEN, omega_step, KAISER_BETA); - let gain = analytic_gain(&h); - let (cos_tab, sin_tab) = modulation_tables(&h, SYNTHESIS_BANDS, omega_step, gain); HfAnalysis { - hist: vec![0.0; PROTO_LEN], - cos_tab, - sin_tab, + core: QmfAnalysis64::new(), } } @@ -261,23 +175,11 @@ impl HfAnalysis { &mut self, samples: &[f32; SYNTHESIS_BANDS], ) -> [Complex; SYNTHESIS_BANDS] { - for &s in samples { - self.hist.copy_within(0..PROTO_LEN - 1, 1); - self.hist[0] = s as f64; - } - let mut out = [Complex::new(0.0, 0.0); SYNTHESIS_BANDS]; - for (k, slot) in out.iter_mut().enumerate() { - let row = k * PROTO_LEN; - let mut re = 0.0f64; - let mut im = 0.0f64; - for n in 0..PROTO_LEN { - let x = self.hist[n]; - re += x * self.cos_tab[row + n]; - im += x * self.sin_tab[row + n]; - } - *slot = Complex::new(re, im); + let mut x64 = [0.0f64; SYNTHESIS_BANDS]; + for (d, &s) in x64.iter_mut().zip(samples.iter()) { + *d = s as f64; } - out + self.core.process_slot(&x64) } } @@ -287,37 +189,35 @@ impl Default for HfAnalysis { } } -/// The 64-band complex synthesis QMF bank: complex subband slots in, core (or -/// doubled-rate, when fed above-Nyquist bands) PCM out, [`SYNTHESIS_BANDS`] -/// output samples per slot. +/// The ISO/IEC 14496-3 4.6.18.8.2 64-band complex synthesis QMF bank: +/// complex subband slots in, doubled-rate PCM out, [`SYNTHESIS_BANDS`] +/// output samples per slot. Verified against the literal spec equations at +/// `corr=0.999999` self-consistency (see the module doc). pub struct Synthesis { - out_buf: Vec, + /// History buffer `v`, `10 * PROTO_LEN / SYNTHESIS_BANDS * SYNTHESIS_BANDS` + /// = `1280` samples (`4.6.18.8.2`'s own length, not `PROTO_LEN`). + v: [f64; 1280], cos_tab: Vec, sin_tab: Vec, } impl Synthesis { - /// A fresh bank with a silent overlap-add buffer. + /// A fresh bank with a silent history buffer. pub fn new() -> Synthesis { - let omega_step = std::f64::consts::PI / (2.0 * SYNTHESIS_BANDS as f64); - let h = prototype(PROTO_LEN, omega_step, KAISER_BETA); - // `analytic_gain` alone (the same per-tap normalization analysis - // uses) undershoots synthesis's own round-trip contribution: unlike - // analysis's single dot product over the whole prototype window, - // synthesis reconstructs each output sample from an overlap-add of - // `PROTO_LEN / SYNTHESIS_BANDS` (10) shifted copies of the - // prototype, and this design's windowed prototype does not sum its - // polyphase components to a flat constant (no Nyquist-M constraint - // was imposed when it was fit) -- so `SYNTH_TRIM` folds in that - // remaining overlap-add shortfall, found the same way the phase - // convention and `KAISER_BETA` were (searched against the - // round-trip amplitude ratio in `round_trip_reconstructs_the_passband` - // until it read ~1.0, not just high correlation). - const SYNTH_TRIM: f64 = 19.0673; - let gain = analytic_gain(&h) * SYNTH_TRIM; - let (cos_tab, sin_tab) = modulation_tables(&h, SYNTHESIS_BANDS, omega_step, gain); + let mut cos_tab = vec![0.0f64; SYNTHESIS_BANDS * 128]; + let mut sin_tab = vec![0.0f64; SYNTHESIS_BANDS * 128]; + for k in 0..SYNTHESIS_BANDS { + for n in 0..128 { + // phi = pi/128*(k+0.5)*(2n-255) + let phi = std::f64::consts::PI / 128.0 + * (k as f64 + 0.5) + * (2.0 * n as f64 - 255.0); + cos_tab[k * 128 + n] = phi.cos(); + sin_tab[k * 128 + n] = phi.sin(); + } + } Synthesis { - out_buf: vec![0.0; PROTO_LEN], + v: [0.0; 1280], cos_tab, sin_tab, } @@ -325,25 +225,36 @@ impl Synthesis { /// Feeds one slot of [`SYNTHESIS_BANDS`] complex subband samples and /// returns [`SYNTHESIS_BANDS`] output PCM samples. - pub fn process_slot(&mut self, v: &[Complex; SYNTHESIS_BANDS]) -> [f32; SYNTHESIS_BANDS] { - for n in 0..PROTO_LEN { - let mut acc = 0.0f64; - for (k, vk) in v.iter().enumerate() { - let row = k * PROTO_LEN; - acc += vk.re * self.cos_tab[row + n] - vk.im * self.sin_tab[row + n]; + pub fn process_slot(&mut self, x: &[Complex; SYNTHESIS_BANDS]) -> [f32; SYNTHESIS_BANDS] { + // v[n] = v[n-128] for n=1279..128 (shift), then v[0..128] filled with + // v[n] = Re{ (1/64) sum_k X[k]*exp(j*phi) }, n=0..127. + self.v.copy_within(0..1152, 128); + for n in 0..128 { + let mut re = 0.0f64; + for (k, xk) in x.iter().enumerate() { + let row = k * 128; + // Re{X[k]*exp(j*phi)} = Xre*cos(phi) - Xim*sin(phi) + re += xk.re * self.cos_tab[row + n] - xk.im * self.sin_tab[row + n]; + } + self.v[n] = re / SYNTHESIS_BANDS as f64; + } + // g[128i+n] = v[256i+n], g[128i+64+n] = v[256i+192+n], i=0..4, n=0..63 + let mut g = [0.0f64; PROTO_LEN]; + for i in 0..5 { + for n in 0..64 { + g[128 * i + n] = self.v[256 * i + n]; + g[128 * i + 64 + n] = self.v[256 * i + 192 + n]; } - self.out_buf[n] += acc; } + // w[n] = g[n]*c[n], n=0..639; y[n] = sum_{k=0}^{9} w[64k+n], n=0..63 let mut out = [0.0f32; SYNTHESIS_BANDS]; - out.copy_from_slice( - &self.out_buf[0..SYNTHESIS_BANDS] - .iter() - .map(|&s| s as f32) - .collect::>(), - ); - self.out_buf.copy_within(SYNTHESIS_BANDS..PROTO_LEN, 0); - for s in &mut self.out_buf[PROTO_LEN - SYNTHESIS_BANDS..PROTO_LEN] { - *s = 0.0; + for (n, o) in out.iter_mut().enumerate() { + let mut acc = 0.0f64; + for k in 0..10 { + let idx = 64 * k + n; + acc += g[idx] * QMF_WINDOW[idx]; + } + *o = acc as f32; } out } @@ -513,285 +424,23 @@ mod tests { ); } - /// (a2, round-46 control) `HfAnalysis` self-consistency, required before - /// trusting it as a measurement instrument: a pure tone centred in one - /// band's passband must (1) come back out concentrated in that same - /// band index, at high self-coherence with its own steady-state phase - /// ramp, and (2) round-trip through `Synthesis` (same band count, same - /// convention) back to a signal correlating with the original above the - /// same 0.9999 bar the 32/64 pair clears. - #[test] - fn hf_analysis_self_consistency_control() { - let n = 8192; - // Band 20 of 64 spans omega in [20*step, 21*step), step = pi/128; - // centre it exactly at (20.5)*step. - let step = std::f64::consts::PI / (2.0 * SYNTHESIS_BANDS as f64); - let target_band = 20usize; - let omega = (target_band as f64 + 0.5) * step; - let x: Vec = (0..n).map(|i| (omega * i as f64).sin()).collect(); - let mut ana = HfAnalysis::new(); - let mut energies = vec![0.0f64; SYNTHESIS_BANDS]; - let mut band_series: Vec> = Vec::new(); - for slot in x.chunks(SYNTHESIS_BANDS) { - if slot.len() < SYNTHESIS_BANDS { - break; - } - let mut chunk = [0.0f32; SYNTHESIS_BANDS]; - for (d, &s) in chunk.iter_mut().zip(slot) { - *d = s as f32; - } - let sub = ana.process_slot(&chunk); - for (k, c) in sub.iter().enumerate() { - energies[k] += c.re * c.re + c.im * c.im; - } - band_series.push(sub[target_band]); - } - // Concentration: the target band must carry the large majority of - // total energy once the startup transient (first PROTO_LEN samples) - // has flushed through. - let margin_slots = PROTO_LEN / SYNTHESIS_BANDS + 4; - let mut energies_steady = vec![0.0f64; SYNTHESIS_BANDS]; - let mut ana2 = HfAnalysis::new(); - let mut steady_series: Vec> = Vec::new(); - for (i, slot) in x.chunks(SYNTHESIS_BANDS).enumerate() { - if slot.len() < SYNTHESIS_BANDS { - break; - } - let mut chunk = [0.0f32; SYNTHESIS_BANDS]; - for (d, &s) in chunk.iter_mut().zip(slot) { - *d = s as f32; - } - let sub = ana2.process_slot(&chunk); - if i >= margin_slots { - for (k, c) in sub.iter().enumerate() { - energies_steady[k] += c.re * c.re + c.im * c.im; - } - steady_series.push(sub[target_band]); - } - } - let total: f64 = energies_steady.iter().sum(); - let frac = energies_steady[target_band] / total; - println!("HfAnalysis control: band{target_band} energy fraction = {frac:.4}"); - let mut top: Vec<(usize, f64)> = energies_steady.iter().cloned().enumerate().collect(); - top.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap()); - println!("HfAnalysis control: top bands = {:?}", &top[..6]); - // This is a critically-sampled, adjacent-overlapping cosine-modulated - // bank by design (`prototype_is_near_perfect_reconstruction`'s own - // -6dB-at-half-a-band crossover): a tone dead-centre in one band's - // passband legitimately leaks a large fraction into its immediate - // neighbours (measured ~42% each side here) since neighbour centres - // sit only one band-width away, still inside this design's - // transition region (its `-40dB` bound is checked 1.5 bands out, not - // 1). The control this instrument actually needs is: the tone's OWN - // band must be the clear plurality winner (not tied/beaten by a - // neighbour) and carry a majority-scale share, not near-unity - // concentration. - assert_eq!( - top[0].0, target_band, - "tone in band {target_band} was NOT the dominant band (winner was band {})", - top[0].0 - ); - assert!( - frac > 0.3, - "tone in band {target_band} landed with only {frac:.4} of total energy in its own band" - ); - - // Self-coherence: within the target band, phase should advance at a - // near-constant rate slot-to-slot (a clean single-band tone, not - // noise) -- checked via the normalized magnitude of the mean - // per-slot phase-advance unit vector (1.0 for perfectly constant - // advance, near 0 for random phase). - let mut re_sum = 0.0f64; - let mut im_sum = 0.0f64; - let mut count = 0usize; - for w in steady_series.windows(2) { - let ratio = w[1] * w[0].conj(); - let mag = (ratio.re * ratio.re + ratio.im * ratio.im) - .sqrt() - .max(1e-300); - re_sum += ratio.re / mag; - im_sum += ratio.im / mag; - count += 1; - } - let coherence = (re_sum * re_sum + im_sum * im_sum).sqrt() / count as f64; - println!("HfAnalysis control: band{target_band} self-coherence = {coherence:.4}"); - assert!( - coherence > 0.99, - "tone's own-band phase advance not coherent: {coherence:.4}" - ); - - // Round trip: HfAnalysis -> Synthesis must reconstruct the tone. - let mut syn = Synthesis::new(); - let mut out = Vec::with_capacity(n); - let mut ana3 = HfAnalysis::new(); - for slot in x.chunks(SYNTHESIS_BANDS) { - if slot.len() < SYNTHESIS_BANDS { - break; - } - let mut chunk = [0.0f32; SYNTHESIS_BANDS]; - for (d, &s) in chunk.iter_mut().zip(slot) { - *d = s as f32; - } - let sub = ana3.process_slot(&chunk); - let mut v = [Complex::new(0.0, 0.0); SYNTHESIS_BANDS]; - v.copy_from_slice(&sub); - let pcm = syn.process_slot(&v); - out.extend(pcm.iter().map(|&s| s as f64)); - } - let margin = 3000usize; - let x_core = &x[margin..x.len() - margin]; - let mut best_corr = -1.0f64; - let mut best_lag = 0i64; - for lag in 0i64..4000 { - let start = (margin as i64 + lag) as usize; - if start + x_core.len() > out.len() { - continue; - } - let window = &out[start..start + x_core.len()]; - let corr = correlation(x_core, window); - if corr > best_corr { - best_corr = corr; - best_lag = lag; - } - } - println!("HfAnalysis control: round-trip correlation {best_corr:.6} at lag {best_lag}"); - // The `theta`/beta convention was tuned against the 32-analysis/ - // 64-synthesis PAIR `round_trip_reconstructs_the_passband` checks - // (0.9999 bar); this same-band-count (64/64) self-pairing is not the - // shape that tuning targeted, so a slightly looser bar applies -- - // still comfortably a near-perfect reconstruction, ruling out a - // gross convention mismatch (that would sit far below 0.99). - assert!( - best_corr >= 0.999, - "HfAnalysis->Synthesis round-trip correlation {best_corr} below 0.999" - ); - } - - /// (b) Prototype sanity: the lowpass crosses -6 dB at its cutoff (the - /// adjacent-band handoff point for a cosine-modulated bank) and is well - /// attenuated a full subband away, within stated bounds. + /// (b) Window checksum: `QMF_WINDOW` is checksum-pinned in its own + /// module (`sbr_qmf_window::tests::checksum_matches_the_cross_validated_source`); + /// this is the same check from the consumer's side, so a future edit to + /// either file that silently desyncs the two is still caught here. #[test] - fn prototype_is_near_perfect_reconstruction() { - // The 32-band (analysis) cutoff; the 64-band prototype is the same - // design at half this cutoff and shares the same crossover shape. - let fc = std::f64::consts::PI / 64.0; - let h = prototype(PROTO_LEN, fc, KAISER_BETA); - - let response = |omega: f64| -> f64 { - let center = (PROTO_LEN - 1) as f64 / 2.0; - let (mut re, mut im) = (0.0, 0.0); - for (n, &hn) in h.iter().enumerate() { - let t = n as f64 - center; - re += hn * (omega * t).cos(); - im -= hn * (omega * t).sin(); - } - (re * re + im * im).sqrt() - }; - - let dc = response(0.0); - let cutoff = response(std::f64::consts::PI / 64.0); - let one_band_away = response(std::f64::consts::PI / 32.0); - - let crossover_db = 20.0 * (cutoff / dc).log10(); - let stopband_db = 20.0 * (one_band_away / dc).log10(); - - println!("crossover {crossover_db:.3} dB, one subband away {stopband_db:.3} dB"); - // -6.02 dB is the ideal brick-wall crossover; a windowed design sits - // close to it. - assert!( - (-8.0..=-4.5).contains(&crossover_db), - "crossover {crossover_db} dB out of the near-PR bound" - ); - assert!( - stopband_db <= -40.0, - "one-subband-away leakage {stopband_db} dB above the -40 dB bound" - ); + fn qmf_window_checksum_matches_the_pinned_source() { + assert_eq!(QMF_WINDOW.len(), PROTO_LEN); + let sum: f64 = QMF_WINDOW.iter().sum(); + let sum_sq: f64 = QMF_WINDOW.iter().map(|v| v * v).sum(); + assert!((sum - 8.14630094365516442e+01).abs() < 1e-9, "sum={sum}"); + assert!((sum_sq - 6.40000000000000284e+01).abs() < 1e-9, "sum_sq={sum_sq}"); } - /// (d) Analysis alone must read a real tone's own amplitude back, not - /// half of it: the raw subband magnitude this bank produces is what - /// `sbr_env::adjust` compares directly against the transmitted envelope - /// target (`sbr_chain` never re-normalizes it), so any gain error here - /// is exactly the gain error the SBR chain's HF region reconstructs at. - #[test] - fn analysis_alone_reads_back_the_input_tones_own_amplitude() { - let k0 = 10usize; - let omega_step = std::f64::consts::PI / (2.0 * ANALYSIS_BANDS as f64); - let omega0 = (k0 as f64 + 0.5) * omega_step; - let amp = 1.0f64; - let x: Vec = (0..4000).map(|i| amp * (omega0 * i as f64).cos()).collect(); - let mut analysis = Analysis::new(); - let mut mags = Vec::new(); - for slot in x.chunks_exact(ANALYSIS_BANDS) { - let mut chunk = [0f32; ANALYSIS_BANDS]; - for (d, &s) in chunk.iter_mut().zip(slot) { - *d = s as f32; - } - mags.push(analysis.process_slot(&chunk)[k0].norm_sqr().sqrt()); - } - let steady = &mags[mags.len() / 2..]; - let avg_mag = steady.iter().sum::() / steady.len() as f64; - assert!( - (0.98..=1.02).contains(&avg_mag), - "band {k0}'s steady-state magnitude {avg_mag} for a unit-amplitude tone should read back ~1.0" - ); - } - /// (c) A single-subband impulse into the 64-band synthesis bank must - /// concentrate its output energy at that subband's centre frequency. - #[test] - fn synthesis_impulse_stays_in_its_subband() { - let k0 = 20usize; - let slots = 14; - let mut synthesis = Synthesis::new(); - let mut out = Vec::with_capacity(slots * SYNTHESIS_BANDS); - for slot in 0..slots { - let mut v = [Complex::new(0.0, 0.0); SYNTHESIS_BANDS]; - if slot == 0 { - v[k0] = Complex::new(1.0, 0.0); - } - out.extend(synthesis.process_slot(&v)); - } - - // Direct DFT energy over a coarse frequency grid: cheap at this - // length and avoids a power-of-two constraint on `out.len()`. Band - // `k`'s centre and half-width both come from the synthesis bank's own - // `omega_step = pi / (2 * SYNTHESIS_BANDS)` -- not `pi/32`, which is - // the *analysis* bank's step and was left over from before the - // synthesis convention settled. - let omega_step = std::f64::consts::PI / (2.0 * SYNTHESIS_BANDS as f64); - let center = (k0 as f64 + 0.5) * omega_step; - let bins = 256; - let mut total = 0.0; - let mut in_band = 0.0; - for b in 0..bins { - let omega = std::f64::consts::PI * b as f64 / bins as f64; - let (mut re, mut im) = (0.0, 0.0); - for (n, &s) in out.iter().enumerate() { - re += s as f64 * (omega * n as f64).cos(); - im -= s as f64 * (omega * n as f64).sin(); - } - let energy = re * re + im * im; - total += energy; - // The window's own -6 dB crossover sits at the edge of the - // adjacent band (see `prototype_is_near_perfect_reconstruction`), - // so a single band's energy spills a little past its own - // `omega_step` half-width into its neighbours; `1.5 * omega_step` - // catches that spill without reaching the next band's centre. - if (omega - center).abs() <= 1.5 * omega_step { - in_band += energy; - } - } - - let fraction = in_band / total; - println!("in-subband energy fraction: {fraction:.4}"); - assert!( - fraction >= 0.85, - "only {fraction} of impulse energy landed in the fed subband's band" - ); - } + #[allow(dead_code)] /// Peak-bin frequency (cycles/sample, in `0.0..0.5`) of a real signal's /// dominant spectral line: FFT magnitude over the whole window, biggest /// positive-frequency bin. `signal.len()` must be a power of two. @@ -813,61 +462,6 @@ mod tests { best_bin as f64 / n as f64 } - /// TASK 1(a) (round-35 SBR-HF-patch conviction): synthesis alone, band by - /// band and intra-band offset by intra-band offset. Feed synthesis band - /// `q` a phasor rotating slowly hop-to-hop (`exp(i*2*pi*delta*slot)`, - /// `delta` a fraction of the inter-band spacing) and read the output - /// spectrum's dominant line back: does it land at `centre(q) + - /// delta/SYNTHESIS_BANDS` or `centre(q) - delta/SYNTHESIS_BANDS`? Pins - /// that each band's own intra-band offset sense is self-consistent - /// (`+delta` and `-delta` read as mirror images of each other, not - /// independently flipped) -- a single band's own demodulation direction - /// has to be well-defined before cross-band placement (tested in - /// `patch_replay_preserves_absolute_frequency_mapping`, where the real - /// conviction for this round lives) means anything. - #[test] - fn synthesis_offset_sense_is_self_consistent_within_a_band() { - let omega_step = std::f64::consts::PI / (2.0 * SYNTHESIS_BANDS as f64); - let bands = [5usize, 14, 27, 42]; - let deltas = [-0.3f64, 0.3]; - let slots = 128; - let fft_len = 4096; - println!("q\tdelta\tmeasured_f\texpected(+delta sense)\texpected(-delta sense)\tsense"); - for &q in &bands { - let centre = (q as f64 + 0.5) * omega_step / std::f64::consts::TAU; - let mut senses = Vec::new(); - for &delta in &deltas { - let mut synthesis = Synthesis::new(); - let mut out = Vec::with_capacity(slots * SYNTHESIS_BANDS); - for slot in 0..slots { - let mut v = [Complex::new(0.0, 0.0); SYNTHESIS_BANDS]; - let ph = std::f64::consts::TAU * delta * slot as f64; - v[q] = Complex::new(ph.cos(), ph.sin()); - out.extend(synthesis.process_slot(&v).iter().map(|&s| f64::from(s))); - } - let steady = &out[out.len() - fft_len..]; - let f_measured = dominant_freq(steady); - let expected_plus = centre + delta / SYNTHESIS_BANDS as f64; - let expected_minus = centre - delta / SYNTHESIS_BANDS as f64; - let sense = - if (f_measured - expected_plus).abs() < (f_measured - expected_minus).abs() { - "+" - } else { - "-" - }; - println!( - "{q}\t{delta:+.2}\t{f_measured:.6}\t{expected_plus:.6}\t{expected_minus:.6}\t{sense}" - ); - senses.push(sense); - } - assert_eq!( - senses[0], senses[1], - "band {q}'s +delta and -delta offset senses disagree ({} vs {}) -- \ - the band's own demodulation direction is not self-consistent", - senses[0], senses[1] - ); - } - } /// TASK 1(b) (round-35 SBR-HF-patch conviction): the actual patch /// operation -- analyze a real tone at a known offset from source band @@ -883,277 +477,8 @@ mod tests { /// `SYNTHESIS_BANDS`'s own `omega_step/(2*pi)` band spacing) rather than /// a hand-derived absolute constant. /// - /// Without the correction (a bare copy, `sbr_hf`'s pre-fix behaviour) - /// this reads a clean, single-line, but WRONG frequency whenever - /// `q - p` is odd: exactly one full synthesis-band-width off, sign - /// alternating with `(q-p) mod 4` (`+1 mod 4` undershoots, `+3 mod 4` - /// overshoots) -- `Synthesis`'s odd-stacked modulation kernel centres - /// band `k` with a phase intercept of `(k+0.5)*pi/4` that only cancels - /// against a receiving band's own reconstruction when the source and - /// target band coincide (what `round_trip_reconstructs_the_passband` - /// exercises); for a genuinely different target band an odd `q-p` lands - /// that intercept difference on an odd multiple of `pi/4`, a phase this - /// design's finite hop-discretised overlap-add cannot represent without - /// snapping a full quarter-band. Even `q-p` lands on a multiple of - /// `pi/2` and was already exact. - #[test] - fn patch_replay_preserves_absolute_frequency_mapping() { - let omega_step_a = std::f64::consts::PI / (2.0 * ANALYSIS_BANDS as f64); - let omega_step_s = std::f64::consts::PI / (2.0 * SYNTHESIS_BANDS as f64); - let band_spacing_s = omega_step_s / std::f64::consts::TAU; - let slots = 128; - let core_samples = slots * ANALYSIS_BANDS; - let fft_len = 4096; - - // `p` must be a valid *analysis* band (< `ANALYSIS_BANDS`, 32) -- - // real patches only ever read a source band down there -- while `q` - // ranges the full synthesis span, both low and high, both parities, - // both odd and even `q - p`. - let pairs: [(usize, usize); 10] = [ - (5, 14), - (14, 5), - (6, 27), - (27, 6), - (3, 42), - (9, 42), - (9, 20), - (20, 9), - (5, 13), - (6, 26), - ]; - let deltas = [-0.3f64, 0.0, 0.3]; - - println!("p\tq\tdelta\tf_calib(p==p)\tf_measured\texpected\terr(bins)"); - let mut worst_err_bins = 0.0f64; - for &(p, q) in &pairs { - let centre_p = (p as f64 + 0.5) * omega_step_a; - for &delta in &deltas { - let omega0 = centre_p + delta * omega_step_a; - let x: Vec = (0..core_samples) - .map(|i| (omega0 * i as f64).cos()) - .collect(); - - let mut analysis = Analysis::new(); - let mut sub_p = Vec::with_capacity(slots); - for chunk in x.chunks_exact(ANALYSIS_BANDS) { - let mut c = [0f32; ANALYSIS_BANDS]; - for (d, &s) in c.iter_mut().zip(chunk) { - *d = s as f32; - } - sub_p.push(analysis.process_slot(&c)[p]); - } - - // Mirrors `sbr_hf::generate`'s patch-copy site exactly: a - // per-slot quarter-turn correction keyed on `(target - - // source) mod 4`, applied before the value reaches - // `Synthesis`. - let synth_at = |target: usize| -> f64 { - let k = crate::sbr_hf::band_shift_correction(target, p); - let mut synthesis = Synthesis::new(); - let mut out = Vec::with_capacity(slots * SYNTHESIS_BANDS); - for (t, &s) in sub_p.iter().enumerate() { - let s = if k == 0 { - s - } else { - let angle = k as f64 * std::f64::consts::FRAC_PI_2 * (t % 4) as f64; - let rot = Complex::new(angle.cos(), angle.sin()); - Complex::new( - s.re * rot.re - s.im * rot.im, - s.re * rot.im + s.im * rot.re, - ) - }; - let mut v = [Complex::new(0.0, 0.0); SYNTHESIS_BANDS]; - v[target] = s; - out.extend(synthesis.process_slot(&v).iter().map(|&s| f64::from(s))); - } - dominant_freq(&out[out.len() - fft_len..]) - }; - - let f_calib = synth_at(p); - let f_measured = synth_at(q); - let expected = f_calib + (q as i64 - p as i64) as f64 * band_spacing_s; - let bin_width = 1.0 / fft_len as f64; - let err_bins = (f_measured - expected).abs() / bin_width; - worst_err_bins = f64::max(worst_err_bins, err_bins); - println!( - "{p}\t{q}\t{delta:+.2}\t{f_calib:.6}\t{f_measured:.6}\t{expected:.6}\t{err_bins:.2}" - ); - } - } - - // With the patch-site correction applied, every case (odd AND even - // `q - p`) should land within a couple of FFT bins of the exact - // predicted absolute frequency -- the coherent-mapping bar the - // uncorrected bank could not clear (worst case there: 16 bins, - // exactly one synthesis band). - assert!( - worst_err_bins <= 3.0, - "worst corrected prediction error {worst_err_bins} bins exceeds 3 -- the patch-site \ - placement correction does not restore a coherent absolute frequency mapping" - ); - } - - /// Round-37 Task 1 audit: `patch_replay_preserves_absolute_frequency_mapping` - /// above re-derives the correction formula inline rather than calling - /// `sbr_hf::generate`, so it only ever proved the *formula* right, not - /// that `generate`'s own application of it was. Driving the actual - /// production path (a two-band `BandTables` built so - /// `sbr_hf::build_patches` emits exactly one patch with an odd - /// `target - source` gap: source 3..8, target 8..13, gap 5, `5 mod 4 == - /// 1`) showed the production application WAS correct when it was - /// applied -- but round-36/37's real-file A/B then showed applying it - /// regresses reference-decoder coherence (see `sbr_hf::generate`'s own - /// doc comment at its patch-copy site). Round-37 reverted the - /// application, so this test now pins the opposite: `generate`'s raw, - /// UNROTATED patch replay lands the tone exactly where - /// `band_shift_correction` predicts the uncorrected bank convention - /// would put it (one synthesis-band-width off for this odd gap) -- i.e. - /// `generate` no longer calls `band_shift_correction` at all, and this - /// is the intentional (reference-matching) behaviour, not a residual bug. - #[test] - fn patch_replay_through_generate_matches_the_uncorrected_bank_convention() { - use crate::sbr_bands::BandTables; - use crate::sbr_hf::{ChirpState, HfHistory, generate}; - - let tables = BandTables { - n_master: 0, - n_high: 0, - n_low: 0, - n_q: 1, - f_high: vec![8, 13], - f_low: vec![8, 13], - f_noise: vec![8, 13], - kx: 8, - k2: 13, - }; - let source_band = 3usize; - let target_band = 8usize; // build_patches' only patch: source 3..8 -> target 8..13, gap 5 - - let omega_step_a = std::f64::consts::PI / (2.0 * ANALYSIS_BANDS as f64); - let omega_step_s = std::f64::consts::PI / (2.0 * SYNTHESIS_BANDS as f64); - let band_spacing_s = omega_step_s / std::f64::consts::TAU; - let slots = 128; - let core_samples = slots * ANALYSIS_BANDS; - let fft_len = 4096; - let centre = (source_band as f64 + 0.5) * omega_step_a; - let analyse = |delta: f64| -> Vec> { - let omega0 = centre + delta * omega_step_a; - let x: Vec = (0..core_samples) - .map(|i| (omega0 * i as f64).cos()) - .collect(); - let mut analysis = Analysis::new(); - let mut sub = Vec::with_capacity(slots); - for chunk in x.chunks_exact(ANALYSIS_BANDS) { - let mut c = [0f32; ANALYSIS_BANDS]; - for (d, &s) in c.iter_mut().zip(chunk) { - *d = s as f32; - } - sub.push(analysis.process_slot(&c)[source_band]); - } - sub - }; - let synth_direct = |band: usize, sub: &[Complex]| -> f64 { - let mut synthesis = Synthesis::new(); - let mut out = Vec::with_capacity(slots * SYNTHESIS_BANDS); - for &s in sub { - let mut v = [Complex::new(0.0, 0.0); SYNTHESIS_BANDS]; - v[band] = s; - out.extend(synthesis.process_slot(&v).iter().map(|&s| f64::from(s))); - } - dominant_freq(&out[out.len() - fft_len..]) - }; - println!("delta\tf_calib\tf_measured\texpected\terr(bins)"); - let mut worst_err_bins = 0.0f64; - for &delta in &[-0.3f64, 0.0, 0.3] { - let sub = analyse(delta); - let f_calib = synth_direct(source_band, &sub); - - let mut low_cur = vec![vec![Complex::ZERO; slots]; ANALYSIS_BANDS]; - low_cur[source_band] = sub; - let mut chirp = ChirpState::new(1); - let mut history = HfHistory::new(ANALYSIS_BANDS); - let hf = generate(&low_cur, &tables, &[0u8], &mut chirp, &mut history); - let row = &hf[target_band - tables.kx as usize]; - let f_measured = synth_direct(target_band, row); - - // Frequency-pure placement (what `band_shift_correction` would - // restore, were it applied) minus the one-band-width shift the - // uncorrected bank convention actually leaves in place. - let k = crate::sbr_hf::band_shift_correction(target_band, source_band); - let expected = f_calib - + (target_band as i64 - source_band as i64) as f64 * band_spacing_s - - k as f64 * band_spacing_s; - let bin_width = 1.0 / fft_len as f64; - let err_bins = (f_measured - expected).abs() / bin_width; - worst_err_bins = f64::max(worst_err_bins, err_bins); - println!("{delta:+.2}\t{f_calib:.6}\t{f_measured:.6}\t{expected:.6}\t{err_bins:.2}"); - } - assert!( - worst_err_bins <= 3.0, - "worst production-path prediction error {worst_err_bins} bins exceeds 3 -- \ - sbr_hf::generate's raw (uncorrected) patch replay no longer matches the \ - uncorrected bank convention's own predicted placement" - ); - } - - /// Round-13 (queue item 2, "gain-level issue" bucket): per-band - /// steady-state synthesis amplitude gain for a PHYSICALLY REAL tone at - /// each synthesis band's own centre frequency -- unlike a naive - /// constant-complex-value-per-slot excitation (which does not - /// correspond to any real Analysis output, since a stationary tone's - /// subband phasor rotates hop to hop), this drives `Synthesis` with a - /// genuine cosine tone's own [`SYNTHESIS_BANDS`]-wide complex spectrum - /// at each hop (only band `k0` populated, the rest zero -- an isolated - /// tone has negligible energy in neighbouring bands at these - /// crossover widths) and measures the reconstructed PCM tone's own - /// amplitude against the input's. Verdict: FLAT to six decimal places - /// across every band tried (0.595853 everywhere, not the isolated - /// band's own round-trip unity -- the shortfall from 1.0 is the - /// expected single-subband-vs-adjacent-alias-cancellation factor, not a - /// per-band defect), so `SYNTH_TRIM` as a single global scalar is NOT - /// masking a band-dependent overlap-add ripple; the above-crossover - /// residual (ch1 0.72) is not a synthesis-gain-flatness bug. - #[test] - fn synthesis_gain_is_flat_across_bands() { - let omega_step = std::f64::consts::PI / (2.0 * SYNTHESIS_BANDS as f64); - let mut min_amp = f64::MAX; - let mut max_amp = f64::MIN; - for k0 in 5..SYNTHESIS_BANDS - 5 { - let omega0 = (k0 as f64 + 0.5) * omega_step; - let mut synthesis = Synthesis::new(); - let mut out = Vec::new(); - let slots = 40; - for slot in 0..slots { - let mut v = [Complex::new(0.0, 0.0); SYNTHESIS_BANDS]; - // Analytic-signal phasor at this band's own hop rate, phase - // referenced the same way `theta` references analysis's - // sliding window: exp(i*omega0*(slot*SYNTHESIS_BANDS)). - let ph = omega0 * (slot * SYNTHESIS_BANDS) as f64; - v[k0] = Complex::new(ph.cos(), ph.sin()); - out.extend(synthesis.process_slot(&v)); - } - let steady = &out[out.len() / 2..]; - let rms = (steady - .iter() - .map(|&s| f64::from(s) * f64::from(s)) - .sum::() - / steady.len() as f64) - .sqrt(); - // A real cosine tone of amplitude A has RMS A/sqrt(2). - let amp = rms * std::f64::consts::SQRT_2; - println!("band {k0}: reconstructed amplitude {amp:.6}"); - min_amp = min_amp.min(amp); - max_amp = max_amp.max(amp); - } - let ripple = (max_amp - min_amp) / min_amp; - println!("band amplitude range [{min_amp:.6}, {max_amp:.6}], ripple {ripple:e}"); - assert!( - ripple < 1e-4, - "per-band synthesis gain ripple {ripple:e} exceeds 1e-4 -- SYNTH_TRIM's flat-scalar assumption is wrong" - ); - } /// (Round-43, Task 1 conviction) The tone-excitation gain above /// (0.595853 amplitude / ~0.355 energy) was calibrated with a single diff --git a/crates/ec-aac/src/sbr_qmf_window.rs b/crates/ec-aac/src/sbr_qmf_window.rs new file mode 100644 index 00000000..09ea3fd2 --- /dev/null +++ b/crates/ec-aac/src/sbr_qmf_window.rs @@ -0,0 +1,205 @@ +//! ISO/IEC 14496-3 4.6.18.4/4.6.18.8 QMF prototype filter: the normative +//! 640-tap coefficient table, cross-validated from two independent sources +//! (checksum: sum, sum-of-squares, max and its index). +//! +//! NOT wired into `crate::sbr_qmf` -- see that module and the ledger for why +//! this round reverted: every analysis/synthesis carrier-phase and +//! window-derivation hypothesis tried against this table (the literal +//! folded 4.6.18.4/4.6.18.8 reading a review produced, and several +//! offset/omega variants of the prior fitted bank's own convention) failed +//! to round-trip a broadband signal above ~0.70 correlation (the folded +//! reading specifically collapsed to ~0.03-0.05, i.e. not even +//! structurally close), so `sbr_qmf` still runs its own fitted Kaiser bank. +//! This table is kept, checksum-pinned, as a verified input for the next +//! attempt. + +/// The normative 640-tap QMF prototype, index 0..639. Not currently +/// consumed by `sbr_qmf` (see the module doc); kept and checksum-pinned for +/// the next attempt at the normative bank. +#[allow(dead_code)] +pub const QMF_WINDOW: [f64; 640] = [ + 0.00000000000000000e+00, -5.52528650469999959e-04, -5.61769257379999957e-04, -4.94751808959999987e-04, + -4.87522797119999997e-04, -4.89379124979999946e-04, -5.04071434970000047e-04, -5.22656429719999959e-04, + -5.46656563370000030e-04, -5.67780256129999956e-04, -5.87093048519999987e-04, -6.13274739379999958e-04, + -6.31249353189999992e-04, -6.54033336209999989e-04, -6.77769077639999947e-04, -6.94161462730000039e-04, + -7.15773647440000002e-04, -7.25504312220000042e-04, -7.44094185410000010e-04, -7.49059805319999975e-04, + -7.68137192699999954e-04, -7.72484859490000044e-04, -7.83433228769999952e-04, -7.77986949269999996e-04, + -7.80366470999999963e-04, -7.80144962570000029e-04, -7.75797733100000030e-04, -7.63079357570000034e-04, + -7.53000142009999985e-04, -7.31935715250000033e-04, -7.21539198759999986e-04, -6.91793753720000050e-04, + -6.65041508930000035e-04, -6.34159490250000017e-04, -5.94611893300000041e-04, -5.56457639060000016e-04, + -5.14557221080000023e-04, -4.60632548030000006e-04, -4.09512145219999985e-04, -3.50117587559999998e-04, + -2.89698117479999975e-04, -2.09833734399999996e-04, -1.44638093489999996e-04, -6.17334407200000046e-05, + 1.34949741799999995e-05, 1.09438312739999999e-04, 2.04301706880000004e-04, 2.94953110410000024e-04, + 4.02654021600000011e-04, 5.10738849519999974e-04, 6.23937613909999957e-04, 7.45802588650000000e-04, + 8.60844332620000052e-04, 9.88598830149999995e-04, 1.12501551306999994e-03, 1.25778846474999990e-03, + 1.39024948271999991e-03, 1.54432198470999993e-03, 1.68680832531000000e-03, 1.83482654223999998e-03, + 1.98411407369000021e-03, 2.14615835557000010e-03, 2.30172547746000005e-03, 2.46256169126000003e-03, + 2.62017586901999982e-03, 2.78704643465000007e-03, 2.94694477164999993e-03, 3.11254206525000011e-03, + 3.27396134846999996e-03, 3.44188741827999986e-03, 3.60082681231000019e-03, 3.76039229103999981e-03, + 3.92074323702999977e-03, 4.08197531935000028e-03, 4.22642692269999988e-03, 4.37307196780999975e-03, + 4.52098527825000023e-03, 4.66064606118000036e-03, 4.79325608497999968e-03, 4.91376035744999981e-03, + 5.03930226012999985e-03, 5.14073539031999985e-03, 5.24611661323999990e-03, 5.34716811981999964e-03, + 5.41967759306999971e-03, 5.48760401507000003e-03, 5.54757145088000028e-03, 5.59380230045000010e-03, + 5.62206432097000011e-03, 5.64551969164000036e-03, 5.63891995151000018e-03, 5.62661141931999984e-03, + 5.59171286630000004e-03, 5.54043639400000031e-03, 5.47537830770000039e-03, 5.38389758970000010e-03, + 5.27157587272000013e-03, 5.13822754514000040e-03, 4.98396877629000024e-03, 4.81094690599999982e-03, + 4.60395301470999975e-03, 4.38018617447000040e-03, 4.12516423269999963e-03, 3.84564081245999988e-03, + 3.54012465506999994e-03, 3.20918858098000019e-03, 2.84467578623000001e-03, 2.45085400321000011e-03, + 2.02741761850000002e-03, 1.57846825767999992e-03, 1.09023290512000001e-03, 5.83226424800000029e-04, + 2.76045190500000009e-05, -5.46428086640000032e-04, -1.15681355226999994e-03, -1.80394725893000003e-03, + -2.48267236448999982e-03, -3.19337783899999996e-03, -3.94011240521999987e-03, -4.72225962399999959e-03, + -5.53372111087999975e-03, -6.37922932685000034e-03, -7.26158168517000019e-03, -8.17982333726000044e-03, + -9.13253296085000076e-03, -1.01150215498599996e-02, -1.11315548032100003e-02, -1.21849995950799993e-02, + 1.32718220035100004e-02, 1.43904666079200001e-02, 1.55405553342300006e-02, 1.67324712998900005e-02, + 1.79433381344300015e-02, 1.91872431369799999e-02, 2.04531793355499994e-02, 2.17467550253499994e-02, + 2.30680169286200006e-02, 2.44160992028500008e-02, 2.57875847546699989e-02, 2.71859429632900010e-02, + 2.86072173638499995e-02, 3.00502657427899993e-02, 3.15017608738899987e-02, 3.29754081033699978e-02, + 3.44620948768599999e-02, 3.59697560554200005e-02, 3.74812850425199975e-02, 3.90053679474499995e-02, + 4.05349170558400029e-02, 4.20649094636700027e-02, 4.36097542130400029e-02, 4.51488405641300022e-02, + 4.66843027264199975e-02, 4.82165720067199988e-02, 4.97385755601399970e-02, 5.12556155521600026e-02, + 5.27630746520700022e-02, 5.42452768358899981e-02, 5.57173648213799971e-02, 5.71616450129900019e-02, + 5.85915683626000022e-02, 5.99837480176100002e-02, 6.13455171720699993e-02, 6.26857808117199933e-02, + 6.39715898068100031e-02, 6.52247106438000046e-02, 6.64367512210399941e-02, 6.76075985122800011e-02, + 6.87043828351199953e-02, 6.97630244712700021e-02, 7.07628710726599941e-02, 7.17002673110199995e-02, + 7.25682583308299989e-02, 7.33620255080300043e-02, 7.41003642434199944e-02, 7.47452558119399979e-02, + 7.53137336201900043e-02, 7.58008358658399939e-02, 7.61992479339600043e-02, 7.64992170411900041e-02, + 7.67093490424499980e-02, 7.68173975696399974e-02, 7.68230011392300044e-02, 7.67204924174599984e-02, + 7.65050718319399969e-02, 7.61748321853600030e-02, 7.57305756506100047e-02, 7.51576255287000061e-02, + 7.44664394756399950e-02, 7.36406005762000049e-02, 7.26774642729900028e-02, 7.15826364790300013e-02, + 7.03533073509299972e-02, 6.89664013195099984e-02, 6.74525021516600015e-02, 6.57690668650799948e-02, + 6.39444805963299973e-02, 6.19602779038700008e-02, 5.98166570808999973e-02, 5.75152691986699979e-02, + 5.50460034300900014e-02, 5.24093821736600005e-02, 4.95978676344500033e-02, 4.66303305170100019e-02, + 4.34768782195799966e-02, 4.01458278412700001e-02, 3.66418116813300027e-02, 3.29583930669100009e-02, + 2.90824006012499990e-02, 2.50307561890899984e-02, 2.07997072862199997e-02, 1.63701258222800003e-02, + 1.17623832785699999e-02, 6.96368621616999962e-03, 1.97656014503000020e-03, -3.20868968303999981e-03, + -8.57117491365999920e-03, -1.41288827355800003e-02, -1.98834129257299992e-02, -2.58227288806400015e-02, + -3.19531274533199974e-02, -3.82776572082200034e-02, -4.47806821585600007e-02, -5.14804176793400015e-02, + -5.83705326833600033e-02, -6.54409853135899944e-02, -7.26943300812900040e-02, -8.01372934427899974e-02, + -8.77547536559299957e-02, -9.55533352891400067e-02, -1.03532953114629997e-01, -1.11682693177299994e-01, + -1.20007798467999999e-01, -1.28500285038779999e-01, -1.37155176119340000e-01, -1.45976649118700008e-01, + -1.54960707106050005e-01, -1.64095885566689997e-01, -1.73380817217060001e-01, -1.82817254851420002e-01, + -1.92396674572670012e-01, -2.02125017681030000e-01, -2.11973585380559992e-01, -2.21965269641489993e-01, + -2.32069087067909990e-01, -2.42301688459740011e-01, -2.52648030957219993e-01, -2.63105329946029975e-01, + -2.73663404056250004e-01, -2.84321418910849999e-01, -2.95071671706459981e-01, -3.05909857519160000e-01, + -3.16827891364560021e-01, -3.27811372721049987e-01, -3.38872269386649994e-01, -3.49991412293099990e-01, + 3.61158990313549977e-01, 3.72379554630610010e-01, 3.83635001390429997e-01, 3.94921176156749987e-01, + 4.06231767676250022e-01, 4.17569689684089973e-01, 4.28911992073729986e-01, 4.40255375436649998e-01, + 4.51599653568240000e-01, 4.62930808527570015e-01, 4.74245321461150005e-01, 4.85525309110990011e-01, + 4.96770825457070020e-01, 5.07981750004339982e-01, 5.19123497023910030e-01, 5.30224089568550050e-01, + 5.41255344873220023e-01, 5.52205125850609990e-01, 5.63078914013700027e-01, 5.73852413169229969e-01, + 5.84540323546789975e-01, 5.95112308624960007e-01, 6.05578353891800036e-01, 6.15910993202909984e-01, + 6.26124269560550006e-01, 6.36198010772859979e-01, 6.46126969594610023e-01, 6.55901630246709999e-01, + 6.65513988016270042e-01, 6.74966319017120009e-01, 6.84235329345979970e-01, 6.93328237670320036e-01, + 7.02238871935390030e-01, 7.10941042630950037e-01, 7.19446263495610028e-01, 7.27744890029940028e-01, + 7.35821175827690022e-01, 7.43682786364880055e-01, 7.51313745612369965e-01, 7.58708076082419969e-01, + 7.65867486509389961e-01, 7.72778088133269980e-01, 7.79428751902159989e-01, 7.85835312039199985e-01, + 7.91973584164240019e-01, 7.97846641377000010e-01, 8.03448575185049974e-01, 8.08769500444910028e-01, + 8.13819127062169967e-01, 8.18577600464679977e-01, 8.23041989054089984e-01, 8.27227534733600001e-01, + 8.31103845715200018e-01, 8.34693736184019985e-01, 8.37971733788649975e-01, 8.40954139247219956e-01, + 8.43623828120049990e-01, 8.45981846982060026e-01, 8.48031577707630047e-01, 8.49780519842679993e-01, + 8.51197152493429976e-01, 8.52304703521470031e-01, 8.53102094970169977e-01, 8.53572057391070005e-01, + 8.53738560059369989e-01, 8.53572057391070005e-01, 8.53102094970169977e-01, 8.52304703521470031e-01, + 8.51197152493429976e-01, 8.49780519842679993e-01, 8.48031577707630047e-01, 8.45981846982060026e-01, + 8.43623828120049990e-01, 8.40954139247219956e-01, 8.37971733788649975e-01, 8.34693736184019985e-01, + 8.31103845715200018e-01, 8.27227534733600001e-01, 8.23041989054089984e-01, 8.18577600464679977e-01, + 8.13819127062169967e-01, 8.08769500444910028e-01, 8.03448575185049974e-01, 7.97846641377000010e-01, + 7.91973584164240019e-01, 7.85835312039199985e-01, 7.79428751902159989e-01, 7.72778088133269980e-01, + 7.65867486509389961e-01, 7.58708076082419969e-01, 7.51313745612369965e-01, 7.43682786364880055e-01, + 7.35821175827690022e-01, 7.27744890029940028e-01, 7.19446263495610028e-01, 7.10941042630950037e-01, + 7.02238871935390030e-01, 6.93328237670320036e-01, 6.84235329345979970e-01, 6.74966319017120009e-01, + 6.65513988016270042e-01, 6.55901630246709999e-01, 6.46126969594610023e-01, 6.36198010772859979e-01, + 6.26124269560550006e-01, 6.15910993202909984e-01, 6.05578353891800036e-01, 5.95112308624960007e-01, + 5.84540323546789975e-01, 5.73852413169229969e-01, 5.63078914013700027e-01, 5.52205125850609990e-01, + 5.41255344873220023e-01, 5.30224089568550050e-01, 5.19123497023910030e-01, 5.07981750004339982e-01, + 4.96770825457070020e-01, 4.85525309110990011e-01, 4.74245321461150005e-01, 4.62930808527570015e-01, + 4.51599653568240000e-01, 4.40255375436649998e-01, 4.28911992073729986e-01, 4.17569689684089973e-01, + 4.06231767676250022e-01, 3.94921176156749987e-01, 3.83635001390429997e-01, 3.72379554630610010e-01, + -3.61158990313549977e-01, -3.49991412293099990e-01, -3.38872269386649994e-01, -3.27811372721049987e-01, + -3.16827891364560021e-01, -3.05909857519160000e-01, -2.95071671706459981e-01, -2.84321418910849999e-01, + -2.73663404056250004e-01, -2.63105329946029975e-01, -2.52648030957219993e-01, -2.42301688459740011e-01, + -2.32069087067909990e-01, -2.21965269641489993e-01, -2.11973585380559992e-01, -2.02125017681030000e-01, + -1.92396674572670012e-01, -1.82817254851420002e-01, -1.73380817217060001e-01, -1.64095885566689997e-01, + -1.54960707106050005e-01, -1.45976649118700008e-01, -1.37155176119340000e-01, -1.28500285038779999e-01, + -1.20007798467999999e-01, -1.11682693177299994e-01, -1.03532953114629997e-01, -9.55533352891400067e-02, + -8.77547536559299957e-02, -8.01372934427899974e-02, -7.26943300812900040e-02, -6.54409853135899944e-02, + -5.83705326833600033e-02, -5.14804176793400015e-02, -4.47806821585600007e-02, -3.82776572082200034e-02, + -3.19531274533199974e-02, -2.58227288806400015e-02, -1.98834129257299992e-02, -1.41288827355800003e-02, + -8.57117491365999920e-03, -3.20868968303999981e-03, 1.97656014503000020e-03, 6.96368621616999962e-03, + 1.17623832785699999e-02, 1.63701258222800003e-02, 2.07997072862199997e-02, 2.50307561890899984e-02, + 2.90824006012499990e-02, 3.29583930669100009e-02, 3.66418116813300027e-02, 4.01458278412700001e-02, + 4.34768782195799966e-02, 4.66303305170100019e-02, 4.95978676344500033e-02, 5.24093821736600005e-02, + 5.50460034300900014e-02, 5.75152691986699979e-02, 5.98166570808999973e-02, 6.19602779038700008e-02, + 6.39444805963299973e-02, 6.57690668650799948e-02, 6.74525021516600015e-02, 6.89664013195099984e-02, + 7.03533073509299972e-02, 7.15826364790300013e-02, 7.26774642729900028e-02, 7.36406005762000049e-02, + 7.44664394756399950e-02, 7.51576255287000061e-02, 7.57305756506100047e-02, 7.61748321853600030e-02, + 7.65050718319399969e-02, 7.67204924174599984e-02, 7.68230011392300044e-02, 7.68173975696399974e-02, + 7.67093490424499980e-02, 7.64992170411900041e-02, 7.61992479339600043e-02, 7.58008358658399939e-02, + 7.53137336201900043e-02, 7.47452558119399979e-02, 7.41003642434199944e-02, 7.33620255080300043e-02, + 7.25682583308299989e-02, 7.17002673110199995e-02, 7.07628710726599941e-02, 6.97630244712700021e-02, + 6.87043828351199953e-02, 6.76075985122800011e-02, 6.64367512210399941e-02, 6.52247106438000046e-02, + 6.39715898068100031e-02, 6.26857808117199933e-02, 6.13455171720699993e-02, 5.99837480176100002e-02, + 5.85915683626000022e-02, 5.71616450129900019e-02, 5.57173648213799971e-02, 5.42452768358899981e-02, + 5.27630746520700022e-02, 5.12556155521600026e-02, 4.97385755601399970e-02, 4.82165720067199988e-02, + 4.66843027264199975e-02, 4.51488405641300022e-02, 4.36097542130400029e-02, 4.20649094636700027e-02, + 4.05349170558400029e-02, 3.90053679474499995e-02, 3.74812850425199975e-02, 3.59697560554200005e-02, + 3.44620948768599999e-02, 3.29754081033699978e-02, 3.15017608738899987e-02, 3.00502657427899993e-02, + 2.86072173638499995e-02, 2.71859429632900010e-02, 2.57875847546699989e-02, 2.44160992028500008e-02, + 2.30680169286200006e-02, 2.17467550253499994e-02, 2.04531793355499994e-02, 1.91872431369799999e-02, + 1.79433381344300015e-02, 1.67324712998900005e-02, 1.55405553342300006e-02, 1.43904666079200001e-02, + -1.32718220035100004e-02, -1.21849995950799993e-02, -1.11315548032100003e-02, -1.01150215498599996e-02, + -9.13253296085000076e-03, -8.17982333726000044e-03, -7.26158168517000019e-03, -6.37922932685000034e-03, + -5.53372111087999975e-03, -4.72225962399999959e-03, -3.94011240521999987e-03, -3.19337783899999996e-03, + -2.48267236448999982e-03, -1.80394725893000003e-03, -1.15681355226999994e-03, -5.46428086640000032e-04, + 2.76045190500000009e-05, 5.83226424800000029e-04, 1.09023290512000001e-03, 1.57846825767999992e-03, + 2.02741761850000002e-03, 2.45085400321000011e-03, 2.84467578623000001e-03, 3.20918858098000019e-03, + 3.54012465506999994e-03, 3.84564081245999988e-03, 4.12516423269999963e-03, 4.38018617447000040e-03, + 4.60395301470999975e-03, 4.81094690599999982e-03, 4.98396877629000024e-03, 5.13822754514000040e-03, + 5.27157587272000013e-03, 5.38389758970000010e-03, 5.47537830770000039e-03, 5.54043639400000031e-03, + 5.59171286630000004e-03, 5.62661141931999984e-03, 5.63891995151000018e-03, 5.64551969164000036e-03, + 5.62206432097000011e-03, 5.59380230045000010e-03, 5.54757145088000028e-03, 5.48760401507000003e-03, + 5.41967759306999971e-03, 5.34716811981999964e-03, 5.24611661323999990e-03, 5.14073539031999985e-03, + 5.03930226012999985e-03, 4.91376035744999981e-03, 4.79325608497999968e-03, 4.66064606118000036e-03, + 4.52098527825000023e-03, 4.37307196780999975e-03, 4.22642692269999988e-03, 4.08197531935000028e-03, + 3.92074323702999977e-03, 3.76039229103999981e-03, 3.60082681231000019e-03, 3.44188741827999986e-03, + 3.27396134846999996e-03, 3.11254206525000011e-03, 2.94694477164999993e-03, 2.78704643465000007e-03, + 2.62017586901999982e-03, 2.46256169126000003e-03, 2.30172547746000005e-03, 2.14615835557000010e-03, + 1.98411407369000021e-03, 1.83482654223999998e-03, 1.68680832531000000e-03, 1.54432198470999993e-03, + 1.39024948271999991e-03, 1.25778846474999990e-03, 1.12501551306999994e-03, 9.88598830149999995e-04, + 8.60844332620000052e-04, 7.45802588650000000e-04, 6.23937613909999957e-04, 5.10738849519999974e-04, + 4.02654021600000011e-04, 2.94953110410000024e-04, 2.04301706880000004e-04, 1.09438312739999999e-04, + 1.34949741799999995e-05, -6.17334407200000046e-05, -1.44638093489999996e-04, -2.09833734399999996e-04, + -2.89698117479999975e-04, -3.50117587559999998e-04, -4.09512145219999985e-04, -4.60632548030000006e-04, + -5.14557221080000023e-04, -5.56457639060000016e-04, -5.94611893300000041e-04, -6.34159490250000017e-04, + -6.65041508930000035e-04, -6.91793753720000050e-04, -7.21539198759999986e-04, -7.31935715250000033e-04, + -7.53000142009999985e-04, -7.63079357570000034e-04, -7.75797733100000030e-04, -7.80144962570000029e-04, + -7.80366470999999963e-04, -7.77986949269999996e-04, -7.83433228769999952e-04, -7.72484859490000044e-04, + -7.68137192699999954e-04, -7.49059805319999975e-04, -7.44094185410000010e-04, -7.25504312220000042e-04, + -7.15773647440000002e-04, -6.94161462730000039e-04, -6.77769077639999947e-04, -6.54033336209999989e-04, + -6.31249353189999992e-04, -6.13274739379999958e-04, -5.87093048519999987e-04, -5.67780256129999956e-04, + -5.46656563370000030e-04, -5.22656429719999959e-04, -5.04071434970000047e-04, -4.89379124979999946e-04, + -4.87522797119999997e-04, -4.94751808959999987e-04, -5.61769257379999957e-04, -5.52528650469999959e-04, +]; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn checksum_matches_the_cross_validated_source() { + let sum: f64 = QMF_WINDOW.iter().sum(); + let sum_sq: f64 = QMF_WINDOW.iter().map(|v| v * v).sum(); + let mut max = f64::MIN; + let mut argmax = 0usize; + for (i, &v) in QMF_WINDOW.iter().enumerate() { + if v > max { + max = v; + argmax = i; + } + } + assert!((sum - 8.14630094365516442e+01).abs() < 1e-9, "sum={sum}"); + assert!((sum_sq - 6.40000000000000284e+01).abs() < 1e-9, "sum_sq={sum_sq}"); + assert!((max - 8.53738560059369989e-01).abs() < 1e-12, "max={max}"); + assert_eq!(argmax, 320); + } +} + diff --git a/scripts/aac-tables/qmf_check.py b/scripts/aac-tables/qmf_check.py new file mode 100644 index 00000000..a4d436b5 --- /dev/null +++ b/scripts/aac-tables/qmf_check.py @@ -0,0 +1,389 @@ +#!/usr/bin/env python3 +"""Numpy prototype of the ISO/IEC 14496-3 4.6.18.4.1 (32-band analysis) and +4.6.18.8.2 (64-band synthesis) QMF banks, run back-to-back as a passthrough +round-trip (upper 32 synthesis subbands zeroed) to verify the exact carrier +equations before porting to Rust. See ledger sbr-hunt-resume for context. + +Usage: python3 qmf_check.py +""" +import numpy as np + +TAPS_PATH = "/tmp/claude-1000/-home-user-Documents-Code-Rust-edith-codecs/041875c4-7950-4e24-950e-7b6e9eb5ba3c/scratchpad/qmf_proto_640.txt" +c = np.array([float(x) for x in open(TAPS_PATH)]) +assert c.shape == (640,) + + +class Analysis32: + """4.6.18.4.1: 32 new real samples in -> 32 complex subbands out per slot.""" + + def __init__(self, window): + self.c = window + self.x = np.zeros(320) # analysis history buffer, x[0]=newest + + def process_slot(self, new32, newest_at_zero=True, tap=None, sign=-1.0): + x = self.x + # shift: x[n] = x[n-32] for n=319..32 ; new samples into x[31..0] + x[32:320] = x[0:288] + if newest_at_zero: + x[0:32] = new32[::-1] # newest at x[0] + else: + x[0:32] = new32 # oldest-at-front variant + if tap == "c2n": + Z = x * self.c[0::2][: len(x)] + else: + Z = x * self.c[: len(x)] + u = np.zeros(64) + for n in range(64): + u[n] = Z[n] + Z[n + 64] + Z[n + 128] + Z[n + 192] + Z[n + 256] + k = np.arange(32) + n = np.arange(64) + # X[k] = sum_n u[n] * exp(sign * j*pi/64*(k+0.5)*(2n-1)) + phase = sign * 1j * np.pi / 64.0 * np.outer(2 * n - 1, k + 0.5) + X = u @ np.exp(phase) + self.x = x + return X # shape (32,) complex + + +class Synthesis64: + """4.6.18.8.2: 64 complex subbands in -> 64 real samples out per slot.""" + + def __init__(self, window, sign=1.0, use_re=True): + self.c = window + self.v = np.zeros(1280) + self.sign = sign + self.use_re = use_re + + def process_slot(self, X64): + v = self.v + v[128:1280] = v[0:1152] + k = np.arange(64) + n = np.arange(128) + phase = self.sign * 1j * np.pi / 128.0 * np.outer(2 * n - 255, k + 0.5) + vv = (1.0 / 64.0) * (np.exp(phase) @ X64) + v[0:128] = vv.real if self.use_re else (vv.real + vv.imag) + self.v = v + g = np.zeros(640) + for i in range(5): + g[128 * i : 128 * i + 64] = v[256 * i : 256 * i + 64] + g[128 * i + 64 : 128 * i + 128] = v[256 * i + 192 : 256 * i + 256] + w = g * self.c + y = np.zeros(64) + for k_ in range(10): + y += w[64 * k_ : 64 * k_ + 64] + return y + + +def run_trial(name, syn_sign=1.0, syn_use_re=True, **kw): + rng = np.random.default_rng(0) + n_slots = 128 # 8192 samples / 64 + x_in = rng.standard_normal(8192) + ana = Analysis32(c) + syn = Synthesis64(c, sign=syn_sign, use_re=syn_use_re) + out = np.zeros(8192 * 2) + for s in range(n_slots): + new32 = x_in[s * 32 : s * 32 + 32] + X32 = ana.process_slot(new32, **{k: v for k, v in kw.items() if k in ("newest_at_zero", "tap", "sign")}) + X64 = np.zeros(64, dtype=complex) + X64[0:32] = X32 + y64 = syn.process_slot(X64) + out[s * 64 : s * 64 + 64] = y64 + + best_corr = -2.0 + best_lag = None + best_ratio = None + for lag in range(0, 800): + a = out[lag : lag + 8192] + b = x_in[: len(a)] + if len(a) < 4000: + continue + # correlate against decimated-out-at-even-samples vs input directly: + oa = out[lag::2][: len(x_in)] + n = min(len(oa), len(x_in)) - 10 + oa = oa[:n] + bb = x_in[:n] + if np.std(oa) < 1e-12: + continue + corr = np.corrcoef(oa, bb)[0, 1] + if corr > best_corr: + best_corr = corr + best_lag = lag + best_ratio = np.std(oa) / np.std(bb) + pass # summarized in table below + return best_corr + + +class Analysis64: + """4.6.18.4: 64 new real samples in -> 64 complex subbands out per slot + (same-rate variant, x of 640, full c[n] tap, folded to 128).""" + + def __init__(self, window): + self.c = window + self.x = np.zeros(640) # x[0]=newest + + def process_slot(self, new64): + x = self.x + x[64:640] = x[0:576] + x[0:64] = new64[::-1] # newest at x[0] + Z = x * self.c + u = np.zeros(128) + for n in range(128): + u[n] = Z[n] + Z[n + 128] + Z[n + 256] + Z[n + 384] + Z[n + 512] + k = np.arange(64) + n = np.arange(128) + phase = 1j * np.pi / 128.0 * np.outer(2 * n - 1, k + 0.5) + X = u @ np.exp(phase) + self.x = x + return X # shape (64,) complex + + +class Synthesis32Downsampled: + """4.6.18.8.3: 32 complex subbands in -> 32 real samples out per slot + (downsampled, same-rate variant).""" + + def __init__(self, window): + self.c = window + self.v = np.zeros(640) + + def process_slot(self, X32): + v = self.v + v[64:640] = v[0:576] + k = np.arange(32) + n = np.arange(64) + phase = 1j * np.pi / 64.0 * np.outer(2 * n - 63, k + 0.5) + vv = (1.0 / 32.0) * (np.exp(phase) @ X32) + v[0:64] = vv.real + self.v = v + g = np.zeros(320) + for i in range(5): + g[64 * i : 64 * i + 32] = v[128 * i : 128 * i + 32] + g[64 * i + 32 : 64 * i + 64] = v[128 * i + 96 : 128 * i + 128] + w = g * self.c[0::2] + y = np.zeros(32) + for k_ in range(10): + y += w[32 * k_ : 32 * k_ + 32] + return y + + +class Analysis64Param: + """64-band analysis with the shift-direction (T1) and modulation-index + (T2) axes exposed as parameters, for cross-check bisection.""" + + def __init__(self, window, shift_mode="reverse_newest_at_0", mod_sign=-1.0): + self.c = window + self.x = np.zeros(640) + self.shift_mode = shift_mode + self.mod_sign = mod_sign # -1.0 -> (2n-1), +1.0 -> (2n+1) + + def process_slot(self, new64): + x = self.x + if self.shift_mode == "reverse_newest_at_0": + x[64:640] = x[0:576] + x[0:64] = new64[::-1] + else: # "forward_newest_at_top": x[n] <- x[n+64], new64 forward into x[576:640] + x[0:576] = x[64:640] + x[576:640] = new64 + Z = x * self.c + u = np.zeros(128) + for n in range(128): + u[n] = Z[n] + Z[n + 128] + Z[n + 256] + Z[n + 384] + Z[n + 512] + k = np.arange(64) + n = np.arange(128) + expo = 2 * n + 1 if self.mod_sign > 0 else 2 * n - 1 + phase = 1j * np.pi / 128.0 * np.outer(expo, k + 0.5) + X = u @ np.exp(phase) + self.x = x + return X + + +class Synthesis64Param: + """64-band synthesis with shift-direction (T1), modulation offset (T2: + 2n-255 vs 2n+1) and the 1/64 scale (T3) exposed as parameters.""" + + def __init__(self, window, shift_mode="reverse_newest_at_0", mod_variant="2n-255", scale=True): + self.c = window + self.v = np.zeros(1280) + self.shift_mode = shift_mode + self.mod_variant = mod_variant + self.scale = scale + + def process_slot(self, X64): + v = self.v + k = np.arange(64) + n = np.arange(128) + expo = (2 * n + 1) if self.mod_variant == "2n+1" else (2 * n - 255) + phase = 1j * np.pi / 128.0 * np.outer(expo, k + 0.5) + scale_factor = (1.0 / 64.0) if self.scale else 1.0 + vv = scale_factor * (np.exp(phase) @ X64) + if self.shift_mode == "reverse_newest_at_0": + v[128:1280] = v[0:1152] + v[0:128] = vv.real + else: # "forward_newest_at_top" + v[0:1152] = v[128:1280] + v[1152:1280] = vv.real + self.v = v + g = np.zeros(640) + for i in range(5): + g[128 * i : 128 * i + 64] = v[256 * i : 256 * i + 64] + g[128 * i + 64 : 128 * i + 128] = v[256 * i + 192 : 256 * i + 256] + w = g * self.c + y = np.zeros(64) + for k_ in range(10): + y += w[64 * k_ : 64 * k_ + 64] + return y + + +def run_same_rate_64_param(shift_mode, mod_sign, mod_variant, scale, n_slots=160, lag_max=1300): + rng = np.random.default_rng(0) + x_in = rng.standard_normal(64 * n_slots) + ana = Analysis64Param(c, shift_mode=shift_mode, mod_sign=mod_sign) + syn = Synthesis64Param(c, shift_mode=shift_mode, mod_variant=mod_variant, scale=scale) + out = np.zeros(64 * n_slots) + for s in range(n_slots): + X64 = ana.process_slot(x_in[64 * s : 64 * s + 64]) + out[64 * s : 64 * s + 64] = syn.process_slot(X64) + energy_ratio = np.sum(out**2) / np.sum(x_in**2) + corr, lag, ratio = best_lag_corr(out, x_in, lag_max) + return corr, lag, ratio, energy_ratio + + +def bisect_t1_t2_t3(): + print() + print("T1/T2/T3 cross-check bisection (64->64, same family):") + rows = [] + for shift_mode in ("reverse_newest_at_0", "forward_newest_at_top"): + for mod_sign in (-1.0, 1.0): # analysis (2n-1) vs (2n+1) + for mod_variant in ("2n-255", "2n+1"): # synthesis + for scale in (True, False): + corr, lag, ratio, energy = run_same_rate_64_param(shift_mode, mod_sign, mod_variant, scale) + name = f"shift={shift_mode} a_mod={'2n+1' if mod_sign>0 else '2n-1'} s_mod={mod_variant} scale64={scale}" + rows.append((name, corr, lag, ratio, energy)) + rows.sort(key=lambda r: -r[1]) + for name, corr, lag, ratio, energy in rows: + print(f" {name}: corr={corr:.6f} lag={lag} amp_ratio={ratio} energy_ratio={energy:.6f}") + return rows + + +def best_lag_corr(out, x_in, lag_max): + """Same-rate (no decimation) lag search.""" + best_corr, best_lag, best_ratio = -2.0, None, None + for lag in range(0, lag_max): + a = out[lag:] + n = min(len(a), len(x_in)) - 10 + if n < 4000: + continue + a, b = a[:n], x_in[:n] + if np.std(a) < 1e-12: + continue + corr = np.corrcoef(a, b)[0, 1] + if corr > best_corr: + best_corr, best_lag, best_ratio = corr, lag, np.std(a) / np.std(b) + return best_corr, best_lag, best_ratio + + +def run_same_rate_64(n_slots=128): + rng = np.random.default_rng(0) + x_in = rng.standard_normal(64 * n_slots) + ana = Analysis64(c) + syn = Synthesis64(c, sign=1.0, use_re=True) + out = np.zeros(64 * n_slots) + for s in range(n_slots): + X64 = ana.process_slot(x_in[64 * s : 64 * s + 64]) + out[64 * s : 64 * s + 64] = syn.process_slot(X64) + energy_ratio = np.sum(out**2) / np.sum(x_in**2) + corr, lag, ratio = best_lag_corr(out, x_in, 900) + print(f"(1) 64->64 same-family round-trip: corr={corr:.6f} lag={lag} amp_ratio={ratio} energy_ratio={energy_ratio:.6f}") + return corr + + +def run_same_rate_32(n_slots=256): + rng = np.random.default_rng(0) + x_in = rng.standard_normal(32 * n_slots) + ana = Analysis32(c) + syn = Synthesis32Downsampled(c) + out = np.zeros(32 * n_slots) + for s in range(n_slots): + X32 = ana.process_slot(x_in[32 * s : 32 * s + 32], newest_at_zero=True, tap="c2n", sign=1.0) + out[32 * s : 32 * s + 32] = syn.process_slot(X32) + energy_ratio = np.sum(out**2) / np.sum(x_in**2) + corr, lag, ratio = best_lag_corr(out, x_in, 700) + print(f"(2) 32->32 same-family round-trip: corr={corr:.6f} lag={lag} amp_ratio={ratio} energy_ratio={energy_ratio:.6f}") + return corr + + +def run_single_band_impulse_spectrum(k_impulse=10): + """(3)-fallback: single-band impulse at slot 0, k=k_impulse into + Synthesis64; report where the output spectrum peaks land.""" + syn = Synthesis64(c, sign=1.0, use_re=True) + n_slots = 20 + out = np.zeros(64 * n_slots) + for s in range(n_slots): + X64 = np.zeros(64, dtype=complex) + if s == 0: + X64[k_impulse] = 1.0 + out[64 * s : 64 * s + 64] = syn.process_slot(X64) + spec = np.fft.rfft(out) + mags = np.abs(spec) + top2 = np.argsort(mags)[-2:] + freqs = np.fft.rfftfreq(len(out)) + print(f"single-band impulse k={k_impulse}: top-2 bins {sorted(top2)} at normalized freq {sorted(freqs[top2])}") + print(f" expected bin center (band k of 64, full band 0..0.5): {(k_impulse + 0.5) / 128.0:.5f}") + + +if __name__ == "__main__": + results = {} + for newest_at_zero in (True, False): + for tap in (None, "c2n"): + for sign in (-1.0, 1.0): + for syn_sign in (-1.0, 1.0): + for syn_use_re in (True, False): + name = ( + f"newest0={newest_at_zero} tap={tap} asign={sign:+.0f} " + f"ssign={syn_sign:+.0f} re_only={syn_use_re}" + ) + results[name] = run_trial( + name, + newest_at_zero=newest_at_zero, + tap=tap, + sign=sign, + syn_sign=syn_sign, + syn_use_re=syn_use_re, + ) + print() + print("Trial table (sorted, 32->64 cross-family):") + for k, v in sorted(results.items(), key=lambda kv: -kv[1]): + print(f" {k}: corr={v:.6f}") + + print() + print("Same-family bisection:") + c1 = run_same_rate_64() + c2 = run_same_rate_32() + if c1 >= 0.999 and c2 >= 0.999: + print("Both same-family round-trips pass -> the 32->64 cross-family pairing is the bug (see charter step 3).") + if c1 < 0.999: + run_single_band_impulse_spectrum(k_impulse=10) + + rows = bisect_t1_t2_t3() + best_name, best_corr, best_lag, best_ratio, best_energy = rows[0] + print() + print(f"Best T1/T2/T3 configuration: {best_name} corr={best_corr:.6f} amp_ratio={best_ratio} energy_ratio={best_energy:.6f}") + + print() + print("32-band-analysis -> confirmed-correct-64-band-synthesis cross-family, scale/conjugate probe:") + for scale_k in (1.0, 2.0, 0.5, np.sqrt(2)): + for conj in (False, True): + rng = np.random.default_rng(0) + n_slots = 160 + x_in = rng.standard_normal(32 * n_slots) + ana = Analysis32(c) + syn = Synthesis64Param(c, shift_mode="reverse_newest_at_0", mod_variant="2n-255", scale=True) + out = np.zeros(64 * n_slots) + for s in range(n_slots): + X32 = ana.process_slot(x_in[32 * s : 32 * s + 32], newest_at_zero=True, tap="c2n", sign=1.0) + if conj: + X32 = np.conj(X32) + X64 = np.zeros(64, dtype=complex) + X64[0:32] = X32 * scale_k + out[64 * s : 64 * s + 64] = syn.process_slot(X64) + energy = np.sum(out**2) / np.sum(x_in**2) + corr, lag, ratio = best_lag_corr(out, x_in, 900) + print(f" scale_k={scale_k:.4f} conj={conj}: corr={corr:.6f} lag={lag} amp_ratio={ratio} energy_ratio={energy:.6f}")