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