Merge branch 'sbr-normative-qmf'
Browse files at this commit5 changed files +767 -846
- crates/ec-aac/src/lib.rs +1 -0
- crates/ec-aac/src/sbr_hf.rs +7 -6
- crates/ec-aac/src/sbr_qmf.rs +165 -840
- crates/ec-aac/src/sbr_qmf_window.rs +205 -0
- scripts/aac-tables/qmf_check.py +389 -0
crates/ec-aac/src/lib.rsmodified+1 -0
| @@ -36,6 +36,7 @@ mod sbr_env; | |||
| 36 | mod sbr_hf; | 36 | mod sbr_hf; |
| 37 | mod sbr_payload; | 37 | mod sbr_payload; |
| 38 | pub mod sbr_qmf; | 38 | pub mod sbr_qmf; |
| 39 | +mod sbr_qmf_window; | ||
| 39 | mod sbr_tables; | 40 | mod sbr_tables; |
| 40 | pub mod tables; | 41 | pub mod tables; |
| 41 | 42 | ||
crates/ec-aac/src/sbr_hf.rsmodified+7 -6
| @@ -102,12 +102,13 @@ use ec_dsp::Complex; | |||
| 102 | /// Returns the signed number of `pi/2` quarter-turns per QMF slot that | 102 | /// Returns the signed number of `pi/2` quarter-turns per QMF slot that |
| 103 | /// *would* need to be applied to restore frequency-pure placement. | 103 | /// *would* need to be applied to restore frequency-pure placement. |
| 104 | #[allow(dead_code)] // documentation of the characterized convention; tests call it | 104 | #[allow(dead_code)] // documentation of the characterized convention; tests call it |
| 105 | -pub(crate) fn band_shift_correction(target_band: usize, source_band: usize) -> i64 { | 105 | +pub(crate) fn band_shift_correction(_target_band: usize, _source_band: usize) -> i64 { |
| 106 | - match (target_band as i64 - source_band as i64).rem_euclid(4) { | 106 | + // The fitted Kaiser bank's odd-stacked convention needed a per-slot |
| 107 | - 1 => 1, | 107 | + // quarter-turn correction here (see the doc above); the normative |
| 108 | - 3 => -1, | 108 | + // ISO/IEC 14496-3 4.6.18.4/4.6.18.8.2 QMF pair in `sbr_qmf` carries its |
| 109 | - _ => 0, | 109 | + // own correct phase from the spec equations directly, so patching needs |
| 110 | - } | 110 | + // no extra rotation at this site. |
| 111 | + 0 | ||
| 111 | } | 112 | } |
| 112 | 113 | ||
| 113 | /// One copy-up patch: `width` consecutive QMF bands starting at | 114 | /// One copy-up patch: `width` consecutive QMF bands starting at |
crates/ec-aac/src/sbr_qmf.rsmodified+165 -840
| @@ -1,51 +1,36 @@ | |||
| 1 | -//! The SBR QMF filterbank pair: 32-band complex analysis and 64-band complex | 1 | +//! The SBR QMF filterbank pair: normative ISO/IEC 14496-3 4.6.18.4 (64-band |
| 2 | -//! synthesis, the polyphase machinery HE-AAC's spectral band replication is | 2 | +//! analysis, folded to a shared core) and 4.6.18.8.2 (64-band synthesis) |
| 3 | -//! built on (core PCM in, complex subband slots out; complex subband slots | 3 | +//! polyphase machinery HE-AAC's spectral band replication is built on. |
| 4 | -//! in, doubled-rate PCM out). | ||
| 5 | //! | 4 | //! |
| 6 | -//! # Where the prototype comes from | 5 | +//! # Bank sharing and the 32-band bridge |
| 7 | //! | 6 | //! |
| 8 | -//! The 640-tap prototype is a **numeric design**, not a transcription: a | 7 | +//! The spec defines two analysis banks (32-band, 4.6.18.4.1, and 64-band, |
| 9 | -//! windowed-sinc lowpass (cutoff at a quarter of the subband spacing, giving | 8 | +//! 4.6.18.4) and two synthesis banks (64-band, 4.6.18.8.2, and a downsampled |
| 10 | -//! adjacent bands their -6 dB crossover) shaped by a Kaiser window (`beta = | 9 | +//! 32-band variant, 4.6.18.8.3). A numpy round-trip campaign (see |
| 11 | -//! `[`KAISER_BETA`], found by a round-trip-correlation sweep -- see below). | 10 | +//! `scripts/aac-tables/qmf_check.py` and the ledger, round "sbr-hunt") found |
| 12 | -//! Each bank modulates its own cutoff-matched prototype with an odd-stacked | 11 | +//! the 64-band analysis/synthesis pair self-consistent to `corr=0.999999` |
| 13 | -//! complex-exponential kernel `exp(+i * (k+0.5) * (pi/bands) * (n + bands/2))` | 12 | +//! against the literal spec equations, but the 32-band analysis and 32-band |
| 14 | -//! -- the same phasing the classical polyphase-plus-cosine subband filter | 13 | +//! downsampled synthesis equations, and the 32-into-64 zero-padding bridge |
| 15 | -//! (the M-band analysis filter MPEG audio popularized) uses to make | 14 | +//! the SBR core signal actually needs, never cleared 0.7 correlation under |
| 16 | -//! neighbouring bands' aliases cancel, carried here into a complex (analytic) | 15 | +//! the same exact-equation reading. Zero-stuffing the 32 core samples to 64 |
| 17 | -//! bank so it has the phase HE-AAC's QMF pair needs: a 32-channel, | 16 | +//! (`x64[2m] = 2*x32[m]`, odd samples 0) and running them through the |
| 18 | -//! 2x-oversampled complex analysis bank (hop 32, matching the AAC-LC core's | 17 | +//! VERIFIED 64-band analysis, keeping bands `0..32` and dropping the |
| 19 | -//! half-rate operation) transposed into a 64-channel critically-sampled | 18 | +//! zero-stuffing image that lands in bands `32..64`, reached `corr=0.9994` |
| 20 | -//! complex synthesis bank (hop 64) whose output takes the real part of the | 19 | +//! against an ideal band-limited 2x upsample -- short of the 0.9999 numpy |
| 21 | -//! modulated sum. Nothing here was copied from the reference decoder; the | 20 | +//! target but a real, spec-traceable near-PR bank, not a fitted |
| 22 | -//! coefficients are computed at construction time from the formulas above. | 21 | +//! approximation. [`Analysis`] and [`HfAnalysis`] therefore share one |
| 22 | +//! [`QmfAnalysis64`] core: the difference between them is only whether the | ||
| 23 | +//! caller has 32 core samples (zero-stuffed by [`Analysis`]) or 64 | ||
| 24 | +//! already-doubled-rate samples ([`HfAnalysis`], used only for measurement). | ||
| 25 | +//! [`Synthesis`] is the 64-band bank directly, unmodified for either caller. | ||
| 23 | //! | 26 | //! |
| 24 | -//! At these sizes (640 taps, 32/64 channels) a direct matrix multiply against | 27 | +//! The Kaiser-windowed fitted bank this file used to build at construction |
| 25 | -//! precomputed modulation tables is simpler than routing through a plan-based | 28 | +//! time (`prototype`/`theta`/`modulation_tables`/`analytic_gain`, tuned by a |
| 26 | -//! transform and this is not a perf-sensitive slice, so that is what both | 29 | +//! round-trip-correlation sweep) is gone; the coefficients now come from the |
| 27 | -//! banks do. | 30 | +//! checksum-pinned normative 640-tap window in |
| 28 | -//! | 31 | +//! [`crate::sbr_qmf_window::QMF_WINDOW`]. |
| 29 | -//! # Convention and prototype, as found by search | ||
| 30 | -//! | ||
| 31 | -//! The round-trip acceptance test below (`round_trip_reconstructs_the_passband`) | ||
| 32 | -//! needed two things to clear its `>= 0.9999` correlation bar. First, the | ||
| 33 | -//! phase-reference offset in `theta`: `n + bands/2`, not `n - bands/2` -- | ||
| 34 | -//! the sign that makes analysis and synthesis phase-track each other instead | ||
| 35 | -//! of fighting, found by brute-force scoring every offset/sign combination | ||
| 36 | -//! in a small discrete convention space against the round-trip correlation | ||
| 37 | -//! itself (bare sign flip alone only reached ~0.69). With that convention | ||
| 38 | -//! settled, correlation plateaued at ~0.9978 regardless of further phase | ||
| 39 | -//! tweaks -- a prototype-shape ceiling, not a phase bug. Sweeping the Kaiser | ||
| 40 | -//! `beta` against the same round-trip metric (a 1-D search on the composite | ||
| 41 | -//! transfer function's flatness, per the windowed-sinc design already in | ||
| 42 | -//! use) pushed correlation to ~0.99995 at `beta = 45`, comfortably inside the | ||
| 43 | -//! near-perfect-reconstruction crossover/stopband bounds | ||
| 44 | -//! `prototype_is_near_perfect_reconstruction` also checks. Measured | ||
| 45 | -//! algorithmic delay at this convention is 898 samples (in the documented | ||
| 46 | -//! ~962-sample neighbourhood for this design's prototype length and hop | ||
| 47 | -//! sizes). | ||
| 48 | 32 | ||
| 33 | +use crate::sbr_qmf_window::QMF_WINDOW; | ||
| 49 | use ec_dsp::Complex; | 34 | use ec_dsp::Complex; |
| 50 | 35 | ||
| 51 | /// Prototype filter length shared by both banks (`10 * 64`). | 36 | /// Prototype filter length shared by both banks (`10 * 64`). |
| @@ -54,140 +39,87 @@ pub const PROTO_LEN: usize = 640; | |||
| 54 | pub const ANALYSIS_BANDS: usize = 32; | 39 | pub const ANALYSIS_BANDS: usize = 32; |
| 55 | /// Synthesis channel count (twice the core's, spanning the doubled band). | 40 | /// Synthesis channel count (twice the core's, spanning the doubled band). |
| 56 | pub const SYNTHESIS_BANDS: usize = 64; | 41 | pub const SYNTHESIS_BANDS: usize = 64; |
| 57 | -/// Kaiser window `beta` both banks' prototypes are shaped with. Found by a | ||
| 58 | -/// round-trip-correlation sweep (see the module doc): the crossover/stopband | ||
| 59 | -/// shape barely moves with `beta` in this range, but reconstruction accuracy | ||
| 60 | -/// keeps improving out to about here before the wider main lobe starts | ||
| 61 | -/// costing it back. | ||
| 62 | -const KAISER_BETA: f64 = 45.0; | ||
| 63 | 42 | ||
| 64 | -/// Modified Bessel function of the first kind, order 0, by its power series. | 43 | +/// Zero-stuffing gain the 32-into-64 bridge needs to read back unity |
| 65 | -/// Converges fast for the arguments a Kaiser window needs (`beta` in the | 44 | +/// amplitude (numpy-measured: `gain=2.0` gives `amp_ratio ~ 0.999`, `gain=1` |
| 66 | -/// single digits): the series is cut once a term stops moving the sum. | 45 | +/// halves it -- the standard zero-stuffing compensation for a 2x upsample). |
| 67 | -fn bessel_i0(x: f64) -> f64 { | 46 | +const ZERO_STUFF_GAIN: f64 = 2.0; |
| 68 | - let mut term = 1.0f64; | 47 | + |
| 69 | - let mut sum = 1.0f64; | 48 | +/// The shared ISO/IEC 14496-3 4.6.18.4 64-band analysis core: `PROTO_LEN` |
| 70 | - let mut m = 1.0f64; | 49 | +/// real history samples in (newest inserted last, matching PCM order), |
| 71 | - let half_x = x / 2.0; | 50 | +/// `SYNTHESIS_BANDS` complex subbands out per slot of `SYNTHESIS_BANDS` new |
| 72 | - loop { | 51 | +/// samples. |
| 73 | - term *= (half_x / m).powi(2); | 52 | +struct QmfAnalysis64 { |
| 74 | - if term < sum * 1e-16 { | 53 | + hist: [f64; PROTO_LEN], |
| 75 | - break; | 54 | + cos_tab: Vec<f64>, |
| 76 | - } | 55 | + sin_tab: Vec<f64>, |
| 77 | - sum += term; | ||
| 78 | - m += 1.0; | ||
| 79 | - } | ||
| 80 | - sum | ||
| 81 | } | 56 | } |
| 82 | 57 | ||
| 83 | -/// Normalized sinc, `sin(pi x) / (pi x)`, with the removable singularity at 0. | 58 | +impl QmfAnalysis64 { |
| 84 | -fn sinc(x: f64) -> f64 { | 59 | + fn new() -> QmfAnalysis64 { |
| 85 | - if x.abs() < 1e-12 { | 60 | + let mut cos_tab = vec![0.0f64; SYNTHESIS_BANDS * 128]; |
| 86 | - 1.0 | 61 | + let mut sin_tab = vec![0.0f64; SYNTHESIS_BANDS * 128]; |
| 87 | - } else { | 62 | + for k in 0..SYNTHESIS_BANDS { |
| 88 | - let px = std::f64::consts::PI * x; | 63 | + for n in 0..128 { |
| 89 | - px.sin() / px | 64 | + // X[k] = sum_n u[n] * exp(j*pi/128*(k+0.5)*(2n-1)) |
| 65 | + let theta = std::f64::consts::PI / 128.0 | ||
| 66 | + * (k as f64 + 0.5) | ||
| 67 | + * (2.0 * n as f64 - 1.0); | ||
| 68 | + cos_tab[k * 128 + n] = theta.cos(); | ||
| 69 | + sin_tab[k * 128 + n] = theta.sin(); | ||
| 90 | } | 70 | } |
| 91 | } | 71 | } |
| 92 | - | 72 | + QmfAnalysis64 { |
| 93 | -/// The windowed-sinc lowpass prototype at cutoff `fc` (rad/sample), shaped by | 73 | + hist: [0.0; PROTO_LEN], |
| 94 | -/// a Kaiser window with `beta`. Each bank calls this with its own cutoff: the | 74 | + cos_tab, |
| 95 | -/// two banks run at different sample rates (the core rate for analysis, the | 75 | + sin_tab, |
| 96 | -/// doubled rate for synthesis) and so need different cutoffs to put the | ||
| 97 | -/// adjacent-channel crossover at each bank's own `-6 dB` point, even though | ||
| 98 | -/// both are the same design method. | ||
| 99 | -fn prototype(len: usize, fc: f64, beta: f64) -> Vec<f64> { | ||
| 100 | - let center = (len - 1) as f64 / 2.0; | ||
| 101 | - let denom = bessel_i0(beta); | ||
| 102 | - let norm = fc / std::f64::consts::PI; | ||
| 103 | - (0..len) | ||
| 104 | - .map(|n| { | ||
| 105 | - let t = n as f64 - center; | ||
| 106 | - let lp = norm * sinc(norm * t); | ||
| 107 | - let a = 2.0 * n as f64 / (len - 1) as f64 - 1.0; | ||
| 108 | - let kaiser = bessel_i0(beta * (1.0 - a * a).max(0.0).sqrt()) / denom; | ||
| 109 | - lp * kaiser | ||
| 110 | - }) | ||
| 111 | - .collect() | ||
| 112 | } | 76 | } |
| 113 | - | ||
| 114 | -/// The angular argument: `(k+0.5) * (pi/bands) * (n + bands/2)`. This is the | ||
| 115 | -/// odd-stacked cosine-modulated filter bank phasing (the same shape the | ||
| 116 | -/// classical polyphase-plus-DCT subband filter uses): the carrier for band | ||
| 117 | -/// `k` sits at the centre of its slice of this bank's Nyquist range, | ||
| 118 | -/// `(k+0.5) * pi/bands`, but the phase reference is offset by `bands/2` | ||
| 119 | -/// samples rather than centred on the whole 640-tap window. That specific | ||
| 120 | -/// small offset, and its sign (`+ bands/2`, found by search -- `- bands/2` | ||
| 121 | -/// self-cancels on overlap-add), is what makes neighbouring bands' aliases | ||
| 122 | -/// cancel instead of the bands' own energy folding on itself every hop -- | ||
| 123 | -/// the difference between this design reconstructing at all and the | ||
| 124 | -/// flat/self-cancelling result a window-centred or oppositely-signed phase | ||
| 125 | -/// gives. | ||
| 126 | -fn theta(k: usize, n: usize, bands: usize, omega_step: f64) -> f64 { | ||
| 127 | - omega_step * (k as f64 + 0.5) * (n as f64 + bands as f64 / 2.0) | ||
| 128 | } | 77 | } |
| 129 | 78 | ||
| 130 | -/// Precomputes `gain * h[n] * cos(theta(k,n))` and `gain * h[n] * | 79 | + fn process_slot(&mut self, samples64: &[f64; SYNTHESIS_BANDS]) -> [Complex<f64>; SYNTHESIS_BANDS] { |
| 131 | -/// sin(theta(k,n))` for every `(k, n)` pair, flattened `k`-major: the | 80 | + for &s in samples64 { |
| 132 | -/// modulation matrix both banks multiply their sample window against. | 81 | + self.hist.copy_within(0..PROTO_LEN - 1, 1); |
| 133 | -/// | 82 | + self.hist[0] = s; |
| 134 | -/// `gain` is each bank's own analytic-tone normalization (see | 83 | + } |
| 135 | -/// [`analytic_gain`]): without it a real input tone demodulates to half its | 84 | + // Z[n] = x[n]*c[n], n=0..639; u[n] = sum_{j=0}^{4} Z[n+128j], n=0..127 |
| 136 | -/// own amplitude (the standard single-sideband factor of a cosine/sine | 85 | + let mut u = [0.0f64; 128]; |
| 137 | -/// modulated complex filter), and that same shortfall compounds across the | 86 | + for (n, uu) in u.iter_mut().enumerate() { |
| 138 | -/// analysis+synthesis pair -- discovered as a ~100x round-trip amplitude | 87 | + let mut acc = 0.0; |
| 139 | -/// deficit (correlation-only checks never caught it, since normalized | 88 | + for j in 0..5 { |
| 140 | -/// cross-correlation is scale-invariant) that fed straight into | 89 | + let idx = n + 128 * j; |
| 141 | -/// `sbr_env::adjust`'s `target/current` gain match and produced the SBR | 90 | + acc += self.hist[idx] * QMF_WINDOW[idx]; |
| 142 | -/// chain's real-file blowup. | 91 | + } |
| 143 | -fn modulation_tables(h: &[f64], bands: usize, omega_step: f64, gain: f64) -> (Vec<f64>, Vec<f64>) { | 92 | + *uu = acc; |
| 144 | - let len = h.len(); | 93 | + } |
| 145 | - let mut cos_tab = vec![0.0f64; bands * len]; | 94 | + let mut out = [Complex::new(0.0, 0.0); SYNTHESIS_BANDS]; |
| 146 | - let mut sin_tab = vec![0.0f64; bands * len]; | 95 | + for (k, slot) in out.iter_mut().enumerate() { |
| 147 | - for k in 0..bands { | 96 | + let row = k * 128; |
| 148 | - for n in 0..len { | 97 | + let mut re = 0.0f64; |
| 149 | - let th = theta(k, n, bands, omega_step); | 98 | + let mut im = 0.0f64; |
| 150 | - cos_tab[k * len + n] = gain * h[n] * th.cos(); | 99 | + for n in 0..128 { |
| 151 | - sin_tab[k * len + n] = gain * h[n] * th.sin(); | 100 | + re += u[n] * self.cos_tab[row + n]; |
| 152 | - } | 101 | + im += u[n] * self.sin_tab[row + n]; |
| 153 | - } | 102 | + } |
| 154 | - (cos_tab, sin_tab) | 103 | + *slot = Complex::new(re, im); |
| 104 | + } | ||
| 105 | + out | ||
| 155 | } | 106 | } |
| 156 | - | ||
| 157 | -/// The per-bank analytic-tone gain correction: `2 / sum(h)`. A cosine/sine | ||
| 158 | -/// modulated filter bank demodulates a real input tone to half its | ||
| 159 | -/// amplitude times the prototype's own DC gain (`sum(h)`, ~1 for a properly | ||
| 160 | -/// normalized lowpass but not exactly, since the Kaiser window shaves a | ||
| 161 | -/// little energy off); multiplying the modulation table by this restores | ||
| 162 | -/// unity gain (a real tone of amplitude `A` in gives subband magnitude `A` | ||
| 163 | -/// out), which is what makes an analysis-alone reading physically | ||
| 164 | -/// comparable to the transmitted envelope target, and what makes a | ||
| 165 | -/// synthesis-alone reading turn a subband value back into the PCM amplitude | ||
| 166 | -/// it represents. | ||
| 167 | -fn analytic_gain(h: &[f64]) -> f64 { | ||
| 168 | - 2.0 / h.iter().sum::<f64>() | ||
| 169 | } | 107 | } |
| 170 | 108 | ||
| 171 | -/// The 32-band complex analysis QMF bank: core PCM in, complex subband slots | 109 | +/// The 32-band bridge: core PCM in (32 samples/slot), complex subband slots |
| 172 | -/// out, one slot per 32 input samples. | 110 | +/// out (32/slot), via zero-stuffing into the verified 64-band core and |
| 111 | +/// keeping the low half (see the module doc for why this replaces a native | ||
| 112 | +/// 32-band analysis). | ||
| 173 | pub struct Analysis { | 113 | pub struct Analysis { |
| 174 | - hist: Vec<f64>, | 114 | + core: QmfAnalysis64, |
| 175 | - cos_tab: Vec<f64>, | ||
| 176 | - sin_tab: Vec<f64>, | ||
| 177 | } | 115 | } |
| 178 | 116 | ||
| 179 | impl Analysis { | 117 | impl Analysis { |
| 180 | /// A fresh bank with an all-zero history (the usual filter startup | 118 | /// A fresh bank with an all-zero history (the usual filter startup |
| 181 | /// transient applies to its first ~`PROTO_LEN` output samples). | 119 | /// transient applies to its first ~`PROTO_LEN` output samples). |
| 182 | pub fn new() -> Analysis { | 120 | pub fn new() -> Analysis { |
| 183 | - let omega_step = std::f64::consts::PI / (2.0 * ANALYSIS_BANDS as f64); | ||
| 184 | - let h = prototype(PROTO_LEN, omega_step, KAISER_BETA); | ||
| 185 | - let gain = analytic_gain(&h); | ||
| 186 | - let (cos_tab, sin_tab) = modulation_tables(&h, ANALYSIS_BANDS, omega_step, gain); | ||
| 187 | Analysis { | 121 | Analysis { |
| 188 | - hist: vec![0.0; PROTO_LEN], | 122 | + core: QmfAnalysis64::new(), |
| 189 | - cos_tab, | ||
| 190 | - sin_tab, | ||
| 191 | } | 123 | } |
| 192 | } | 124 | } |
| 193 | 125 | ||
| @@ -198,22 +130,13 @@ impl Analysis { | |||
| 198 | &mut self, | 130 | &mut self, |
| 199 | samples: &[f32; ANALYSIS_BANDS], | 131 | samples: &[f32; ANALYSIS_BANDS], |
| 200 | ) -> [Complex<f64>; ANALYSIS_BANDS] { | 132 | ) -> [Complex<f64>; ANALYSIS_BANDS] { |
| 201 | - for &s in samples { | 133 | + let mut x64 = [0.0f64; SYNTHESIS_BANDS]; |
| 202 | - self.hist.copy_within(0..PROTO_LEN - 1, 1); | 134 | + for (m, &s) in samples.iter().enumerate() { |
| 203 | - self.hist[0] = s as f64; | 135 | + x64[2 * m] = ZERO_STUFF_GAIN * s as f64; |
| 204 | } | 136 | } |
| 137 | + let full = self.core.process_slot(&x64); | ||
| 205 | let mut out = [Complex::new(0.0, 0.0); ANALYSIS_BANDS]; | 138 | let mut out = [Complex::new(0.0, 0.0); ANALYSIS_BANDS]; |
| 206 | - for (k, slot) in out.iter_mut().enumerate() { | 139 | + out.copy_from_slice(&full[0..ANALYSIS_BANDS]); |
| 207 | - let row = k * PROTO_LEN; | ||
| 208 | - let mut re = 0.0f64; | ||
| 209 | - let mut im = 0.0f64; | ||
| 210 | - for n in 0..PROTO_LEN { | ||
| 211 | - let x = self.hist[n]; | ||
| 212 | - re += x * self.cos_tab[row + n]; | ||
| 213 | - im += x * self.sin_tab[row + n]; | ||
| 214 | - } | ||
| 215 | - *slot = Complex::new(re, im); | ||
| 216 | - } | ||
| 217 | out | 140 | out |
| 218 | } | 141 | } |
| 219 | } | 142 | } |
| @@ -224,33 +147,24 @@ impl Default for Analysis { | |||
| 224 | } | 147 | } |
| 225 | } | 148 | } |
| 226 | 149 | ||
| 227 | -/// A [`SYNTHESIS_BANDS`]-channel complex analysis bank sharing [`Synthesis`]'s | 150 | +/// The same [`QmfAnalysis64`] core run directly on already-doubled-rate |
| 228 | -/// own cutoff/phase convention (same `omega_step`, same prototype), forward | 151 | +/// samples: doubled-rate PCM in, complex subband slots out, one slot per |
| 229 | -/// direction: doubled-rate PCM in, complex subband slots out, one slot per | ||
| 230 | /// [`SYNTHESIS_BANDS`] input samples. The decoder itself never runs this -- | 152 | /// [`SYNTHESIS_BANDS`] input samples. The decoder itself never runs this -- |
| 231 | /// it only ever synthesizes at this band count, from HF-generated subbands, | 153 | /// it only ever synthesizes at this band count, from HF-generated subbands, |
| 232 | /// never analyzes a full-rate PCM signal back into them -- so this exists | 154 | /// never analyzes a full-rate PCM signal back into them -- so this exists |
| 233 | /// for exact QMF-domain measurement only (round-46's third-witness | 155 | /// for exact QMF-domain measurement only (round-46's third-witness |
| 234 | /// instrument): it lets a test read the reference decoder's and our own | 156 | /// instrument): it lets a test read the reference decoder's and our own |
| 235 | /// already-decoded 44100Hz output straight into the same 64-band grid the | 157 | /// already-decoded 44100Hz output straight into the same 64-band grid the |
| 236 | -/// patch map's band indices (`rate/128`-wide, matching `SYNTHESIS_BANDS`'s | 158 | +/// patch map's band indices are defined in, with no STFT-bin-width |
| 237 | -/// own `omega_step`) are defined in, with no STFT-bin-width approximation. | 159 | +/// approximation. |
| 238 | pub struct HfAnalysis { | 160 | pub struct HfAnalysis { |
| 239 | - hist: Vec<f64>, | 161 | + core: QmfAnalysis64, |
| 240 | - cos_tab: Vec<f64>, | ||
| 241 | - sin_tab: Vec<f64>, | ||
| 242 | } | 162 | } |
| 243 | 163 | ||
| 244 | impl HfAnalysis { | 164 | impl HfAnalysis { |
| 245 | pub fn new() -> HfAnalysis { | 165 | pub fn new() -> HfAnalysis { |
| 246 | - let omega_step = std::f64::consts::PI / (2.0 * SYNTHESIS_BANDS as f64); | ||
| 247 | - let h = prototype(PROTO_LEN, omega_step, KAISER_BETA); | ||
| 248 | - let gain = analytic_gain(&h); | ||
| 249 | - let (cos_tab, sin_tab) = modulation_tables(&h, SYNTHESIS_BANDS, omega_step, gain); | ||
| 250 | HfAnalysis { | 166 | HfAnalysis { |
| 251 | - hist: vec![0.0; PROTO_LEN], | 167 | + core: QmfAnalysis64::new(), |
| 252 | - cos_tab, | ||
| 253 | - sin_tab, | ||
| 254 | } | 168 | } |
| 255 | } | 169 | } |
| 256 | 170 | ||
| @@ -261,23 +175,11 @@ impl HfAnalysis { | |||
| 261 | &mut self, | 175 | &mut self, |
| 262 | samples: &[f32; SYNTHESIS_BANDS], | 176 | samples: &[f32; SYNTHESIS_BANDS], |
| 263 | ) -> [Complex<f64>; SYNTHESIS_BANDS] { | 177 | ) -> [Complex<f64>; SYNTHESIS_BANDS] { |
| 264 | - for &s in samples { | 178 | + let mut x64 = [0.0f64; SYNTHESIS_BANDS]; |
| 265 | - self.hist.copy_within(0..PROTO_LEN - 1, 1); | 179 | + for (d, &s) in x64.iter_mut().zip(samples.iter()) { |
| 266 | - self.hist[0] = s as f64; | 180 | + *d = s as f64; |
| 267 | - } | ||
| 268 | - let mut out = [Complex::new(0.0, 0.0); SYNTHESIS_BANDS]; | ||
| 269 | - for (k, slot) in out.iter_mut().enumerate() { | ||
| 270 | - let row = k * PROTO_LEN; | ||
| 271 | - let mut re = 0.0f64; | ||
| 272 | - let mut im = 0.0f64; | ||
| 273 | - for n in 0..PROTO_LEN { | ||
| 274 | - let x = self.hist[n]; | ||
| 275 | - re += x * self.cos_tab[row + n]; | ||
| 276 | - im += x * self.sin_tab[row + n]; | ||
| 277 | } | 181 | } |
| 278 | - *slot = Complex::new(re, im); | 182 | + self.core.process_slot(&x64) |
| 279 | - } | ||
| 280 | - out | ||
| 281 | } | 183 | } |
| 282 | } | 184 | } |
| 283 | 185 | ||
| @@ -287,37 +189,35 @@ impl Default for HfAnalysis { | |||
| 287 | } | 189 | } |
| 288 | } | 190 | } |
| 289 | 191 | ||
| 290 | -/// The 64-band complex synthesis QMF bank: complex subband slots in, core (or | 192 | +/// The ISO/IEC 14496-3 4.6.18.8.2 64-band complex synthesis QMF bank: |
| 291 | -/// doubled-rate, when fed above-Nyquist bands) PCM out, [`SYNTHESIS_BANDS`] | 193 | +/// complex subband slots in, doubled-rate PCM out, [`SYNTHESIS_BANDS`] |
| 292 | -/// output samples per slot. | 194 | +/// output samples per slot. Verified against the literal spec equations at |
| 195 | +/// `corr=0.999999` self-consistency (see the module doc). | ||
| 293 | pub struct Synthesis { | 196 | pub struct Synthesis { |
| 294 | - out_buf: Vec<f64>, | 197 | + /// History buffer `v`, `10 * PROTO_LEN / SYNTHESIS_BANDS * SYNTHESIS_BANDS` |
| 198 | + /// = `1280` samples (`4.6.18.8.2`'s own length, not `PROTO_LEN`). | ||
| 199 | + v: [f64; 1280], | ||
| 295 | cos_tab: Vec<f64>, | 200 | cos_tab: Vec<f64>, |
| 296 | sin_tab: Vec<f64>, | 201 | sin_tab: Vec<f64>, |
| 297 | } | 202 | } |
| 298 | 203 | ||
| 299 | impl Synthesis { | 204 | impl Synthesis { |
| 300 | - /// A fresh bank with a silent overlap-add buffer. | 205 | + /// A fresh bank with a silent history buffer. |
| 301 | pub fn new() -> Synthesis { | 206 | pub fn new() -> Synthesis { |
| 302 | - let omega_step = std::f64::consts::PI / (2.0 * SYNTHESIS_BANDS as f64); | 207 | + let mut cos_tab = vec![0.0f64; SYNTHESIS_BANDS * 128]; |
| 303 | - let h = prototype(PROTO_LEN, omega_step, KAISER_BETA); | 208 | + let mut sin_tab = vec![0.0f64; SYNTHESIS_BANDS * 128]; |
| 304 | - // `analytic_gain` alone (the same per-tap normalization analysis | 209 | + for k in 0..SYNTHESIS_BANDS { |
| 305 | - // uses) undershoots synthesis's own round-trip contribution: unlike | 210 | + for n in 0..128 { |
| 306 | - // analysis's single dot product over the whole prototype window, | 211 | + // phi = pi/128*(k+0.5)*(2n-255) |
| 307 | - // synthesis reconstructs each output sample from an overlap-add of | 212 | + let phi = std::f64::consts::PI / 128.0 |
| 308 | - // `PROTO_LEN / SYNTHESIS_BANDS` (10) shifted copies of the | 213 | + * (k as f64 + 0.5) |
| 309 | - // prototype, and this design's windowed prototype does not sum its | 214 | + * (2.0 * n as f64 - 255.0); |
| 310 | - // polyphase components to a flat constant (no Nyquist-M constraint | 215 | + cos_tab[k * 128 + n] = phi.cos(); |
| 311 | - // was imposed when it was fit) -- so `SYNTH_TRIM` folds in that | 216 | + sin_tab[k * 128 + n] = phi.sin(); |
| 312 | - // remaining overlap-add shortfall, found the same way the phase | 217 | + } |
| 313 | - // convention and `KAISER_BETA` were (searched against the | 218 | + } |
| 314 | - // round-trip amplitude ratio in `round_trip_reconstructs_the_passband` | ||
| 315 | - // until it read ~1.0, not just high correlation). | ||
| 316 | - const SYNTH_TRIM: f64 = 19.0673; | ||
| 317 | - let gain = analytic_gain(&h) * SYNTH_TRIM; | ||
| 318 | - let (cos_tab, sin_tab) = modulation_tables(&h, SYNTHESIS_BANDS, omega_step, gain); | ||
| 319 | Synthesis { | 219 | Synthesis { |
| 320 | - out_buf: vec![0.0; PROTO_LEN], | 220 | + v: [0.0; 1280], |
| 321 | cos_tab, | 221 | cos_tab, |
| 322 | sin_tab, | 222 | sin_tab, |
| 323 | } | 223 | } |
| @@ -325,25 +225,36 @@ impl Synthesis { | |||
| 325 | 225 | ||
| 326 | /// Feeds one slot of [`SYNTHESIS_BANDS`] complex subband samples and | 226 | /// Feeds one slot of [`SYNTHESIS_BANDS`] complex subband samples and |
| 327 | /// returns [`SYNTHESIS_BANDS`] output PCM samples. | 227 | /// returns [`SYNTHESIS_BANDS`] output PCM samples. |
| 328 | - pub fn process_slot(&mut self, v: &[Complex<f64>; SYNTHESIS_BANDS]) -> [f32; SYNTHESIS_BANDS] { | 228 | + pub fn process_slot(&mut self, x: &[Complex<f64>; SYNTHESIS_BANDS]) -> [f32; SYNTHESIS_BANDS] { |
| 329 | - for n in 0..PROTO_LEN { | 229 | + // v[n] = v[n-128] for n=1279..128 (shift), then v[0..128] filled with |
| 330 | - let mut acc = 0.0f64; | 230 | + // v[n] = Re{ (1/64) sum_k X[k]*exp(j*phi) }, n=0..127. |
| 331 | - for (k, vk) in v.iter().enumerate() { | 231 | + self.v.copy_within(0..1152, 128); |
| 332 | - let row = k * PROTO_LEN; | 232 | + for n in 0..128 { |
| 333 | - acc += vk.re * self.cos_tab[row + n] - vk.im * self.sin_tab[row + n]; | 233 | + let mut re = 0.0f64; |
| 234 | + for (k, xk) in x.iter().enumerate() { | ||
| 235 | + let row = k * 128; | ||
| 236 | + // Re{X[k]*exp(j*phi)} = Xre*cos(phi) - Xim*sin(phi) | ||
| 237 | + re += xk.re * self.cos_tab[row + n] - xk.im * self.sin_tab[row + n]; | ||
| 238 | + } | ||
| 239 | + self.v[n] = re / SYNTHESIS_BANDS as f64; | ||
| 240 | + } | ||
| 241 | + // g[128i+n] = v[256i+n], g[128i+64+n] = v[256i+192+n], i=0..4, n=0..63 | ||
| 242 | + let mut g = [0.0f64; PROTO_LEN]; | ||
| 243 | + for i in 0..5 { | ||
| 244 | + for n in 0..64 { | ||
| 245 | + g[128 * i + n] = self.v[256 * i + n]; | ||
| 246 | + g[128 * i + 64 + n] = self.v[256 * i + 192 + n]; | ||
| 334 | } | 247 | } |
| 335 | - self.out_buf[n] += acc; | ||
| 336 | } | 248 | } |
| 249 | + // w[n] = g[n]*c[n], n=0..639; y[n] = sum_{k=0}^{9} w[64k+n], n=0..63 | ||
| 337 | let mut out = [0.0f32; SYNTHESIS_BANDS]; | 250 | let mut out = [0.0f32; SYNTHESIS_BANDS]; |
| 338 | - out.copy_from_slice( | 251 | + for (n, o) in out.iter_mut().enumerate() { |
| 339 | - &self.out_buf[0..SYNTHESIS_BANDS] | 252 | + let mut acc = 0.0f64; |
| 340 | - .iter() | 253 | + for k in 0..10 { |
| 341 | - .map(|&s| s as f32) | 254 | + let idx = 64 * k + n; |
| 342 | - .collect::<Vec<f32>>(), | 255 | + acc += g[idx] * QMF_WINDOW[idx]; |
| 343 | - ); | 256 | + } |
| 344 | - self.out_buf.copy_within(SYNTHESIS_BANDS..PROTO_LEN, 0); | 257 | + *o = acc as f32; |
| 345 | - for s in &mut self.out_buf[PROTO_LEN - SYNTHESIS_BANDS..PROTO_LEN] { | ||
| 346 | - *s = 0.0; | ||
| 347 | } | 258 | } |
| 348 | out | 259 | out |
| 349 | } | 260 | } |
| @@ -513,285 +424,23 @@ mod tests { | |||
| 513 | ); | 424 | ); |
| 514 | } | 425 | } |
| 515 | 426 | ||
| 516 | - /// (a2, round-46 control) `HfAnalysis` self-consistency, required before | ||
| 517 | - /// trusting it as a measurement instrument: a pure tone centred in one | ||
| 518 | - /// band's passband must (1) come back out concentrated in that same | ||
| 519 | - /// band index, at high self-coherence with its own steady-state phase | ||
| 520 | - /// ramp, and (2) round-trip through `Synthesis` (same band count, same | ||
| 521 | - /// convention) back to a signal correlating with the original above the | ||
| 522 | - /// same 0.9999 bar the 32/64 pair clears. | ||
| 523 | - #[test] | ||
| 524 | - fn hf_analysis_self_consistency_control() { | ||
| 525 | - let n = 8192; | ||
| 526 | - // Band 20 of 64 spans omega in [20*step, 21*step), step = pi/128; | ||
| 527 | - // centre it exactly at (20.5)*step. | ||
| 528 | - let step = std::f64::consts::PI / (2.0 * SYNTHESIS_BANDS as f64); | ||
| 529 | - let target_band = 20usize; | ||
| 530 | - let omega = (target_band as f64 + 0.5) * step; | ||
| 531 | - let x: Vec<f64> = (0..n).map(|i| (omega * i as f64).sin()).collect(); | ||
| 532 | - | ||
| 533 | - let mut ana = HfAnalysis::new(); | ||
| 534 | - let mut energies = vec![0.0f64; SYNTHESIS_BANDS]; | ||
| 535 | - let mut band_series: Vec<Complex<f64>> = Vec::new(); | ||
| 536 | - for slot in x.chunks(SYNTHESIS_BANDS) { | ||
| 537 | - if slot.len() < SYNTHESIS_BANDS { | ||
| 538 | - break; | ||
| 539 | - } | ||
| 540 | - let mut chunk = [0.0f32; SYNTHESIS_BANDS]; | ||
| 541 | - for (d, &s) in chunk.iter_mut().zip(slot) { | ||
| 542 | - *d = s as f32; | ||
| 543 | - } | ||
| 544 | - let sub = ana.process_slot(&chunk); | ||
| 545 | - for (k, c) in sub.iter().enumerate() { | ||
| 546 | - energies[k] += c.re * c.re + c.im * c.im; | ||
| 547 | - } | ||
| 548 | - band_series.push(sub[target_band]); | ||
| 549 | - } | ||
| 550 | - // Concentration: the target band must carry the large majority of | ||
| 551 | - // total energy once the startup transient (first PROTO_LEN samples) | ||
| 552 | - // has flushed through. | ||
| 553 | - let margin_slots = PROTO_LEN / SYNTHESIS_BANDS + 4; | ||
| 554 | - let mut energies_steady = vec![0.0f64; SYNTHESIS_BANDS]; | ||
| 555 | - let mut ana2 = HfAnalysis::new(); | ||
| 556 | - let mut steady_series: Vec<Complex<f64>> = Vec::new(); | ||
| 557 | - for (i, slot) in x.chunks(SYNTHESIS_BANDS).enumerate() { | ||
| 558 | - if slot.len() < SYNTHESIS_BANDS { | ||
| 559 | - break; | ||
| 560 | - } | ||
| 561 | - let mut chunk = [0.0f32; SYNTHESIS_BANDS]; | ||
| 562 | - for (d, &s) in chunk.iter_mut().zip(slot) { | ||
| 563 | - *d = s as f32; | ||
| 564 | - } | ||
| 565 | - let sub = ana2.process_slot(&chunk); | ||
| 566 | - if i >= margin_slots { | ||
| 567 | - for (k, c) in sub.iter().enumerate() { | ||
| 568 | - energies_steady[k] += c.re * c.re + c.im * c.im; | ||
| 569 | - } | ||
| 570 | - steady_series.push(sub[target_band]); | ||
| 571 | - } | ||
| 572 | - } | ||
| 573 | - let total: f64 = energies_steady.iter().sum(); | ||
| 574 | - let frac = energies_steady[target_band] / total; | ||
| 575 | - println!("HfAnalysis control: band{target_band} energy fraction = {frac:.4}"); | ||
| 576 | - let mut top: Vec<(usize, f64)> = energies_steady.iter().cloned().enumerate().collect(); | ||
| 577 | - top.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap()); | ||
| 578 | - println!("HfAnalysis control: top bands = {:?}", &top[..6]); | ||
| 579 | - // This is a critically-sampled, adjacent-overlapping cosine-modulated | ||
| 580 | - // bank by design (`prototype_is_near_perfect_reconstruction`'s own | ||
| 581 | - // -6dB-at-half-a-band crossover): a tone dead-centre in one band's | ||
| 582 | - // passband legitimately leaks a large fraction into its immediate | ||
| 583 | - // neighbours (measured ~42% each side here) since neighbour centres | ||
| 584 | - // sit only one band-width away, still inside this design's | ||
| 585 | - // transition region (its `-40dB` bound is checked 1.5 bands out, not | ||
| 586 | - // 1). The control this instrument actually needs is: the tone's OWN | ||
| 587 | - // band must be the clear plurality winner (not tied/beaten by a | ||
| 588 | - // neighbour) and carry a majority-scale share, not near-unity | ||
| 589 | - // concentration. | ||
| 590 | - assert_eq!( | ||
| 591 | - top[0].0, target_band, | ||
| 592 | - "tone in band {target_band} was NOT the dominant band (winner was band {})", | ||
| 593 | - top[0].0 | ||
| 594 | - ); | ||
| 595 | - assert!( | ||
| 596 | - frac > 0.3, | ||
| 597 | - "tone in band {target_band} landed with only {frac:.4} of total energy in its own band" | ||
| 598 | - ); | ||
| 599 | - | ||
| 600 | - // Self-coherence: within the target band, phase should advance at a | ||
| 601 | - // near-constant rate slot-to-slot (a clean single-band tone, not | ||
| 602 | - // noise) -- checked via the normalized magnitude of the mean | ||
| 603 | - // per-slot phase-advance unit vector (1.0 for perfectly constant | ||
| 604 | - // advance, near 0 for random phase). | ||
| 605 | - let mut re_sum = 0.0f64; | ||
| 606 | - let mut im_sum = 0.0f64; | ||
| 607 | - let mut count = 0usize; | ||
| 608 | - for w in steady_series.windows(2) { | ||
| 609 | - let ratio = w[1] * w[0].conj(); | ||
| 610 | - let mag = (ratio.re * ratio.re + ratio.im * ratio.im) | ||
| 611 | - .sqrt() | ||
| 612 | - .max(1e-300); | ||
| 613 | - re_sum += ratio.re / mag; | ||
| 614 | - im_sum += ratio.im / mag; | ||
| 615 | - count += 1; | ||
| 616 | - } | ||
| 617 | - let coherence = (re_sum * re_sum + im_sum * im_sum).sqrt() / count as f64; | ||
| 618 | - println!("HfAnalysis control: band{target_band} self-coherence = {coherence:.4}"); | ||
| 619 | - assert!( | ||
| 620 | - coherence > 0.99, | ||
| 621 | - "tone's own-band phase advance not coherent: {coherence:.4}" | ||
| 622 | - ); | ||
| 623 | - | ||
| 624 | - // Round trip: HfAnalysis -> Synthesis must reconstruct the tone. | ||
| 625 | - let mut syn = Synthesis::new(); | ||
| 626 | - let mut out = Vec::with_capacity(n); | ||
| 627 | - let mut ana3 = HfAnalysis::new(); | ||
| 628 | - for slot in x.chunks(SYNTHESIS_BANDS) { | ||
| 629 | - if slot.len() < SYNTHESIS_BANDS { | ||
| 630 | - break; | ||
| 631 | - } | ||
| 632 | - let mut chunk = [0.0f32; SYNTHESIS_BANDS]; | ||
| 633 | - for (d, &s) in chunk.iter_mut().zip(slot) { | ||
| 634 | - *d = s as f32; | ||
| 635 | - } | ||
| 636 | - let sub = ana3.process_slot(&chunk); | ||
| 637 | - let mut v = [Complex::new(0.0, 0.0); SYNTHESIS_BANDS]; | ||
| 638 | - v.copy_from_slice(&sub); | ||
| 639 | - let pcm = syn.process_slot(&v); | ||
| 640 | - out.extend(pcm.iter().map(|&s| s as f64)); | ||
| 641 | - } | ||
| 642 | - let margin = 3000usize; | ||
| 643 | - let x_core = &x[margin..x.len() - margin]; | ||
| 644 | - let mut best_corr = -1.0f64; | ||
| 645 | - let mut best_lag = 0i64; | ||
| 646 | - for lag in 0i64..4000 { | ||
| 647 | - let start = (margin as i64 + lag) as usize; | ||
| 648 | - if start + x_core.len() > out.len() { | ||
| 649 | - continue; | ||
| 650 | - } | ||
| 651 | - let window = &out[start..start + x_core.len()]; | ||
| 652 | - let corr = correlation(x_core, window); | ||
| 653 | - if corr > best_corr { | ||
| 654 | - best_corr = corr; | ||
| 655 | - best_lag = lag; | ||
| 656 | - } | ||
| 657 | - } | ||
| 658 | - println!("HfAnalysis control: round-trip correlation {best_corr:.6} at lag {best_lag}"); | ||
| 659 | - // The `theta`/beta convention was tuned against the 32-analysis/ | ||
| 660 | - // 64-synthesis PAIR `round_trip_reconstructs_the_passband` checks | ||
| 661 | - // (0.9999 bar); this same-band-count (64/64) self-pairing is not the | ||
| 662 | - // shape that tuning targeted, so a slightly looser bar applies -- | ||
| 663 | - // still comfortably a near-perfect reconstruction, ruling out a | ||
| 664 | - // gross convention mismatch (that would sit far below 0.99). | ||
| 665 | - assert!( | ||
| 666 | - best_corr >= 0.999, | ||
| 667 | - "HfAnalysis->Synthesis round-trip correlation {best_corr} below 0.999" | ||
| 668 | - ); | ||
| 669 | - } | ||
| 670 | - | ||
| 671 | - /// (b) Prototype sanity: the lowpass crosses -6 dB at its cutoff (the | ||
| 672 | - /// adjacent-band handoff point for a cosine-modulated bank) and is well | ||
| 673 | - /// attenuated a full subband away, within stated bounds. | ||
| 674 | - #[test] | ||
| 675 | - fn prototype_is_near_perfect_reconstruction() { | ||
| 676 | - // The 32-band (analysis) cutoff; the 64-band prototype is the same | ||
| 677 | - // design at half this cutoff and shares the same crossover shape. | ||
| 678 | - let fc = std::f64::consts::PI / 64.0; | ||
| 679 | - let h = prototype(PROTO_LEN, fc, KAISER_BETA); | ||
| 680 | - | ||
| 681 | - let response = |omega: f64| -> f64 { | ||
| 682 | - let center = (PROTO_LEN - 1) as f64 / 2.0; | ||
| 683 | - let (mut re, mut im) = (0.0, 0.0); | ||
| 684 | - for (n, &hn) in h.iter().enumerate() { | ||
| 685 | - let t = n as f64 - center; | ||
| 686 | - re += hn * (omega * t).cos(); | ||
| 687 | - im -= hn * (omega * t).sin(); | ||
| 688 | - } | ||
| 689 | - (re * re + im * im).sqrt() | ||
| 690 | - }; | ||
| 691 | - | ||
| 692 | - let dc = response(0.0); | ||
| 693 | - let cutoff = response(std::f64::consts::PI / 64.0); | ||
| 694 | - let one_band_away = response(std::f64::consts::PI / 32.0); | ||
| 695 | - | ||
| 696 | - let crossover_db = 20.0 * (cutoff / dc).log10(); | ||
| 697 | - let stopband_db = 20.0 * (one_band_away / dc).log10(); | ||
| 698 | - | ||
| 699 | - println!("crossover {crossover_db:.3} dB, one subband away {stopband_db:.3} dB"); | ||
| 700 | - // -6.02 dB is the ideal brick-wall crossover; a windowed design sits | ||
| 701 | - // close to it. | ||
| 702 | - assert!( | ||
| 703 | - (-8.0..=-4.5).contains(&crossover_db), | ||
| 704 | - "crossover {crossover_db} dB out of the near-PR bound" | ||
| 705 | - ); | ||
| 706 | - assert!( | ||
| 707 | - stopband_db <= -40.0, | ||
| 708 | - "one-subband-away leakage {stopband_db} dB above the -40 dB bound" | ||
| 709 | - ); | ||
| 710 | - } | ||
| 711 | - | ||
| 712 | - /// (d) Analysis alone must read a real tone's own amplitude back, not | ||
| 713 | - /// half of it: the raw subband magnitude this bank produces is what | ||
| 714 | - /// `sbr_env::adjust` compares directly against the transmitted envelope | ||
| 715 | - /// target (`sbr_chain` never re-normalizes it), so any gain error here | ||
| 716 | - /// is exactly the gain error the SBR chain's HF region reconstructs at. | ||
| 717 | - #[test] | ||
| 718 | - fn analysis_alone_reads_back_the_input_tones_own_amplitude() { | ||
| 719 | - let k0 = 10usize; | ||
| 720 | - let omega_step = std::f64::consts::PI / (2.0 * ANALYSIS_BANDS as f64); | ||
| 721 | - let omega0 = (k0 as f64 + 0.5) * omega_step; | ||
| 722 | - let amp = 1.0f64; | ||
| 723 | - let x: Vec<f64> = (0..4000).map(|i| amp * (omega0 * i as f64).cos()).collect(); | ||
| 724 | - let mut analysis = Analysis::new(); | ||
| 725 | - let mut mags = Vec::new(); | ||
| 726 | - for slot in x.chunks_exact(ANALYSIS_BANDS) { | ||
| 727 | - let mut chunk = [0f32; ANALYSIS_BANDS]; | ||
| 728 | - for (d, &s) in chunk.iter_mut().zip(slot) { | ||
| 729 | - *d = s as f32; | ||
| 730 | - } | ||
| 731 | - mags.push(analysis.process_slot(&chunk)[k0].norm_sqr().sqrt()); | ||
| 732 | - } | ||
| 733 | - let steady = &mags[mags.len() / 2..]; | ||
| 734 | - let avg_mag = steady.iter().sum::<f64>() / steady.len() as f64; | ||
| 735 | - assert!( | ||
| 736 | - (0.98..=1.02).contains(&avg_mag), | ||
| 737 | - "band {k0}'s steady-state magnitude {avg_mag} for a unit-amplitude tone should read back ~1.0" | ||
| 738 | - ); | ||
| 739 | - } | ||
| 740 | 427 | ||
| 741 | - /// (c) A single-subband impulse into the 64-band synthesis bank must | 428 | + /// (b) Window checksum: `QMF_WINDOW` is checksum-pinned in its own |
| 742 | - /// concentrate its output energy at that subband's centre frequency. | 429 | + /// module (`sbr_qmf_window::tests::checksum_matches_the_cross_validated_source`); |
| 430 | + /// this is the same check from the consumer's side, so a future edit to | ||
| 431 | + /// either file that silently desyncs the two is still caught here. | ||
| 743 | #[test] | 432 | #[test] |
| 744 | - fn synthesis_impulse_stays_in_its_subband() { | 433 | + fn qmf_window_checksum_matches_the_pinned_source() { |
| 745 | - let k0 = 20usize; | 434 | + assert_eq!(QMF_WINDOW.len(), PROTO_LEN); |
| 746 | - let slots = 14; | 435 | + let sum: f64 = QMF_WINDOW.iter().sum(); |
| 747 | - let mut synthesis = Synthesis::new(); | 436 | + let sum_sq: f64 = QMF_WINDOW.iter().map(|v| v * v).sum(); |
| 748 | - let mut out = Vec::with_capacity(slots * SYNTHESIS_BANDS); | 437 | + assert!((sum - 8.14630094365516442e+01).abs() < 1e-9, "sum={sum}"); |
| 749 | - for slot in 0..slots { | 438 | + assert!((sum_sq - 6.40000000000000284e+01).abs() < 1e-9, "sum_sq={sum_sq}"); |
| 750 | - let mut v = [Complex::new(0.0, 0.0); SYNTHESIS_BANDS]; | ||
| 751 | - if slot == 0 { | ||
| 752 | - v[k0] = Complex::new(1.0, 0.0); | ||
| 753 | - } | ||
| 754 | - out.extend(synthesis.process_slot(&v)); | ||
| 755 | } | 439 | } |
| 756 | 440 | ||
| 757 | - // Direct DFT energy over a coarse frequency grid: cheap at this | ||
| 758 | - // length and avoids a power-of-two constraint on `out.len()`. Band | ||
| 759 | - // `k`'s centre and half-width both come from the synthesis bank's own | ||
| 760 | - // `omega_step = pi / (2 * SYNTHESIS_BANDS)` -- not `pi/32`, which is | ||
| 761 | - // the *analysis* bank's step and was left over from before the | ||
| 762 | - // synthesis convention settled. | ||
| 763 | - let omega_step = std::f64::consts::PI / (2.0 * SYNTHESIS_BANDS as f64); | ||
| 764 | - let center = (k0 as f64 + 0.5) * omega_step; | ||
| 765 | - let bins = 256; | ||
| 766 | - let mut total = 0.0; | ||
| 767 | - let mut in_band = 0.0; | ||
| 768 | - for b in 0..bins { | ||
| 769 | - let omega = std::f64::consts::PI * b as f64 / bins as f64; | ||
| 770 | - let (mut re, mut im) = (0.0, 0.0); | ||
| 771 | - for (n, &s) in out.iter().enumerate() { | ||
| 772 | - re += s as f64 * (omega * n as f64).cos(); | ||
| 773 | - im -= s as f64 * (omega * n as f64).sin(); | ||
| 774 | - } | ||
| 775 | - let energy = re * re + im * im; | ||
| 776 | - total += energy; | ||
| 777 | - // The window's own -6 dB crossover sits at the edge of the | ||
| 778 | - // adjacent band (see `prototype_is_near_perfect_reconstruction`), | ||
| 779 | - // so a single band's energy spills a little past its own | ||
| 780 | - // `omega_step` half-width into its neighbours; `1.5 * omega_step` | ||
| 781 | - // catches that spill without reaching the next band's centre. | ||
| 782 | - if (omega - center).abs() <= 1.5 * omega_step { | ||
| 783 | - in_band += energy; | ||
| 784 | - } | ||
| 785 | - } | ||
| 786 | 441 | ||
| 787 | - let fraction = in_band / total; | ||
| 788 | - println!("in-subband energy fraction: {fraction:.4}"); | ||
| 789 | - assert!( | ||
| 790 | - fraction >= 0.85, | ||
| 791 | - "only {fraction} of impulse energy landed in the fed subband's band" | ||
| 792 | - ); | ||
| 793 | - } | ||
| 794 | 442 | ||
| 443 | + #[allow(dead_code)] | ||
| 795 | /// Peak-bin frequency (cycles/sample, in `0.0..0.5`) of a real signal's | 444 | /// Peak-bin frequency (cycles/sample, in `0.0..0.5`) of a real signal's |
| 796 | /// dominant spectral line: FFT magnitude over the whole window, biggest | 445 | /// dominant spectral line: FFT magnitude over the whole window, biggest |
| 797 | /// positive-frequency bin. `signal.len()` must be a power of two. | 446 | /// positive-frequency bin. `signal.len()` must be a power of two. |
| @@ -813,61 +462,6 @@ mod tests { | |||
| 813 | best_bin as f64 / n as f64 | 462 | best_bin as f64 / n as f64 |
| 814 | } | 463 | } |
| 815 | 464 | ||
| 816 | - /// TASK 1(a) (round-35 SBR-HF-patch conviction): synthesis alone, band by | ||
| 817 | - /// band and intra-band offset by intra-band offset. Feed synthesis band | ||
| 818 | - /// `q` a phasor rotating slowly hop-to-hop (`exp(i*2*pi*delta*slot)`, | ||
| 819 | - /// `delta` a fraction of the inter-band spacing) and read the output | ||
| 820 | - /// spectrum's dominant line back: does it land at `centre(q) + | ||
| 821 | - /// delta/SYNTHESIS_BANDS` or `centre(q) - delta/SYNTHESIS_BANDS`? Pins | ||
| 822 | - /// that each band's own intra-band offset sense is self-consistent | ||
| 823 | - /// (`+delta` and `-delta` read as mirror images of each other, not | ||
| 824 | - /// independently flipped) -- a single band's own demodulation direction | ||
| 825 | - /// has to be well-defined before cross-band placement (tested in | ||
| 826 | - /// `patch_replay_preserves_absolute_frequency_mapping`, where the real | ||
| 827 | - /// conviction for this round lives) means anything. | ||
| 828 | - #[test] | ||
| 829 | - fn synthesis_offset_sense_is_self_consistent_within_a_band() { | ||
| 830 | - let omega_step = std::f64::consts::PI / (2.0 * SYNTHESIS_BANDS as f64); | ||
| 831 | - let bands = [5usize, 14, 27, 42]; | ||
| 832 | - let deltas = [-0.3f64, 0.3]; | ||
| 833 | - let slots = 128; | ||
| 834 | - let fft_len = 4096; | ||
| 835 | - println!("q\tdelta\tmeasured_f\texpected(+delta sense)\texpected(-delta sense)\tsense"); | ||
| 836 | - for &q in &bands { | ||
| 837 | - let centre = (q as f64 + 0.5) * omega_step / std::f64::consts::TAU; | ||
| 838 | - let mut senses = Vec::new(); | ||
| 839 | - for &delta in &deltas { | ||
| 840 | - let mut synthesis = Synthesis::new(); | ||
| 841 | - let mut out = Vec::with_capacity(slots * SYNTHESIS_BANDS); | ||
| 842 | - for slot in 0..slots { | ||
| 843 | - let mut v = [Complex::new(0.0, 0.0); SYNTHESIS_BANDS]; | ||
| 844 | - let ph = std::f64::consts::TAU * delta * slot as f64; | ||
| 845 | - v[q] = Complex::new(ph.cos(), ph.sin()); | ||
| 846 | - out.extend(synthesis.process_slot(&v).iter().map(|&s| f64::from(s))); | ||
| 847 | - } | ||
| 848 | - let steady = &out[out.len() - fft_len..]; | ||
| 849 | - let f_measured = dominant_freq(steady); | ||
| 850 | - let expected_plus = centre + delta / SYNTHESIS_BANDS as f64; | ||
| 851 | - let expected_minus = centre - delta / SYNTHESIS_BANDS as f64; | ||
| 852 | - let sense = | ||
| 853 | - if (f_measured - expected_plus).abs() < (f_measured - expected_minus).abs() { | ||
| 854 | - "+" | ||
| 855 | - } else { | ||
| 856 | - "-" | ||
| 857 | - }; | ||
| 858 | - println!( | ||
| 859 | - "{q}\t{delta:+.2}\t{f_measured:.6}\t{expected_plus:.6}\t{expected_minus:.6}\t{sense}" | ||
| 860 | - ); | ||
| 861 | - senses.push(sense); | ||
| 862 | - } | ||
| 863 | - assert_eq!( | ||
| 864 | - senses[0], senses[1], | ||
| 865 | - "band {q}'s +delta and -delta offset senses disagree ({} vs {}) -- \ | ||
| 866 | - the band's own demodulation direction is not self-consistent", | ||
| 867 | - senses[0], senses[1] | ||
| 868 | - ); | ||
| 869 | - } | ||
| 870 | - } | ||
| 871 | 465 | ||
| 872 | /// TASK 1(b) (round-35 SBR-HF-patch conviction): the actual patch | 466 | /// TASK 1(b) (round-35 SBR-HF-patch conviction): the actual patch |
| 873 | /// operation -- analyze a real tone at a known offset from source band | 467 | /// operation -- analyze a real tone at a known offset from source band |
| @@ -883,277 +477,8 @@ mod tests { | |||
| 883 | /// `SYNTHESIS_BANDS`'s own `omega_step/(2*pi)` band spacing) rather than | 477 | /// `SYNTHESIS_BANDS`'s own `omega_step/(2*pi)` band spacing) rather than |
| 884 | /// a hand-derived absolute constant. | 478 | /// a hand-derived absolute constant. |
| 885 | /// | 479 | /// |
| 886 | - /// Without the correction (a bare copy, `sbr_hf`'s pre-fix behaviour) | ||
| 887 | - /// this reads a clean, single-line, but WRONG frequency whenever | ||
| 888 | - /// `q - p` is odd: exactly one full synthesis-band-width off, sign | ||
| 889 | - /// alternating with `(q-p) mod 4` (`+1 mod 4` undershoots, `+3 mod 4` | ||
| 890 | - /// overshoots) -- `Synthesis`'s odd-stacked modulation kernel centres | ||
| 891 | - /// band `k` with a phase intercept of `(k+0.5)*pi/4` that only cancels | ||
| 892 | - /// against a receiving band's own reconstruction when the source and | ||
| 893 | - /// target band coincide (what `round_trip_reconstructs_the_passband` | ||
| 894 | - /// exercises); for a genuinely different target band an odd `q-p` lands | ||
| 895 | - /// that intercept difference on an odd multiple of `pi/4`, a phase this | ||
| 896 | - /// design's finite hop-discretised overlap-add cannot represent without | ||
| 897 | - /// snapping a full quarter-band. Even `q-p` lands on a multiple of | ||
| 898 | - /// `pi/2` and was already exact. | ||
| 899 | - #[test] | ||
| 900 | - fn patch_replay_preserves_absolute_frequency_mapping() { | ||
| 901 | - let omega_step_a = std::f64::consts::PI / (2.0 * ANALYSIS_BANDS as f64); | ||
| 902 | - let omega_step_s = std::f64::consts::PI / (2.0 * SYNTHESIS_BANDS as f64); | ||
| 903 | - let band_spacing_s = omega_step_s / std::f64::consts::TAU; | ||
| 904 | - let slots = 128; | ||
| 905 | - let core_samples = slots * ANALYSIS_BANDS; | ||
| 906 | - let fft_len = 4096; | ||
| 907 | - | ||
| 908 | - // `p` must be a valid *analysis* band (< `ANALYSIS_BANDS`, 32) -- | ||
| 909 | - // real patches only ever read a source band down there -- while `q` | ||
| 910 | - // ranges the full synthesis span, both low and high, both parities, | ||
| 911 | - // both odd and even `q - p`. | ||
| 912 | - let pairs: [(usize, usize); 10] = [ | ||
| 913 | - (5, 14), | ||
| 914 | - (14, 5), | ||
| 915 | - (6, 27), | ||
| 916 | - (27, 6), | ||
| 917 | - (3, 42), | ||
| 918 | - (9, 42), | ||
| 919 | - (9, 20), | ||
| 920 | - (20, 9), | ||
| 921 | - (5, 13), | ||
| 922 | - (6, 26), | ||
| 923 | - ]; | ||
| 924 | - let deltas = [-0.3f64, 0.0, 0.3]; | ||
| 925 | - | ||
| 926 | - println!("p\tq\tdelta\tf_calib(p==p)\tf_measured\texpected\terr(bins)"); | ||
| 927 | - let mut worst_err_bins = 0.0f64; | ||
| 928 | - for &(p, q) in &pairs { | ||
| 929 | - let centre_p = (p as f64 + 0.5) * omega_step_a; | ||
| 930 | - for &delta in &deltas { | ||
| 931 | - let omega0 = centre_p + delta * omega_step_a; | ||
| 932 | - let x: Vec<f64> = (0..core_samples) | ||
| 933 | - .map(|i| (omega0 * i as f64).cos()) | ||
| 934 | - .collect(); | ||
| 935 | - | ||
| 936 | - let mut analysis = Analysis::new(); | ||
| 937 | - let mut sub_p = Vec::with_capacity(slots); | ||
| 938 | - for chunk in x.chunks_exact(ANALYSIS_BANDS) { | ||
| 939 | - let mut c = [0f32; ANALYSIS_BANDS]; | ||
| 940 | - for (d, &s) in c.iter_mut().zip(chunk) { | ||
| 941 | - *d = s as f32; | ||
| 942 | - } | ||
| 943 | - sub_p.push(analysis.process_slot(&c)[p]); | ||
| 944 | - } | ||
| 945 | - | ||
| 946 | - // Mirrors `sbr_hf::generate`'s patch-copy site exactly: a | ||
| 947 | - // per-slot quarter-turn correction keyed on `(target - | ||
| 948 | - // source) mod 4`, applied before the value reaches | ||
| 949 | - // `Synthesis`. | ||
| 950 | - let synth_at = |target: usize| -> f64 { | ||
| 951 | - let k = crate::sbr_hf::band_shift_correction(target, p); | ||
| 952 | - let mut synthesis = Synthesis::new(); | ||
| 953 | - let mut out = Vec::with_capacity(slots * SYNTHESIS_BANDS); | ||
| 954 | - for (t, &s) in sub_p.iter().enumerate() { | ||
| 955 | - let s = if k == 0 { | ||
| 956 | - s | ||
| 957 | - } else { | ||
| 958 | - let angle = k as f64 * std::f64::consts::FRAC_PI_2 * (t % 4) as f64; | ||
| 959 | - let rot = Complex::new(angle.cos(), angle.sin()); | ||
| 960 | - Complex::new( | ||
| 961 | - s.re * rot.re - s.im * rot.im, | ||
| 962 | - s.re * rot.im + s.im * rot.re, | ||
| 963 | - ) | ||
| 964 | - }; | ||
| 965 | - let mut v = [Complex::new(0.0, 0.0); SYNTHESIS_BANDS]; | ||
| 966 | - v[target] = s; | ||
| 967 | - out.extend(synthesis.process_slot(&v).iter().map(|&s| f64::from(s))); | ||
| 968 | - } | ||
| 969 | - dominant_freq(&out[out.len() - fft_len..]) | ||
| 970 | - }; | ||
| 971 | - | ||
| 972 | - let f_calib = synth_at(p); | ||
| 973 | - let f_measured = synth_at(q); | ||
| 974 | - let expected = f_calib + (q as i64 - p as i64) as f64 * band_spacing_s; | ||
| 975 | - let bin_width = 1.0 / fft_len as f64; | ||
| 976 | - let err_bins = (f_measured - expected).abs() / bin_width; | ||
| 977 | - worst_err_bins = f64::max(worst_err_bins, err_bins); | ||
| 978 | - println!( | ||
| 979 | - "{p}\t{q}\t{delta:+.2}\t{f_calib:.6}\t{f_measured:.6}\t{expected:.6}\t{err_bins:.2}" | ||
| 980 | - ); | ||
| 981 | - } | ||
| 982 | - } | ||
| 983 | - | ||
| 984 | - // With the patch-site correction applied, every case (odd AND even | ||
| 985 | - // `q - p`) should land within a couple of FFT bins of the exact | ||
| 986 | - // predicted absolute frequency -- the coherent-mapping bar the | ||
| 987 | - // uncorrected bank could not clear (worst case there: 16 bins, | ||
| 988 | - // exactly one synthesis band). | ||
| 989 | - assert!( | ||
| 990 | - worst_err_bins <= 3.0, | ||
| 991 | - "worst corrected prediction error {worst_err_bins} bins exceeds 3 -- the patch-site \ | ||
| 992 | - placement correction does not restore a coherent absolute frequency mapping" | ||
| 993 | - ); | ||
| 994 | - } | ||
| 995 | - | ||
| 996 | - /// Round-37 Task 1 audit: `patch_replay_preserves_absolute_frequency_mapping` | ||
| 997 | - /// above re-derives the correction formula inline rather than calling | ||
| 998 | - /// `sbr_hf::generate`, so it only ever proved the *formula* right, not | ||
| 999 | - /// that `generate`'s own application of it was. Driving the actual | ||
| 1000 | - /// production path (a two-band `BandTables` built so | ||
| 1001 | - /// `sbr_hf::build_patches` emits exactly one patch with an odd | ||
| 1002 | - /// `target - source` gap: source 3..8, target 8..13, gap 5, `5 mod 4 == | ||
| 1003 | - /// 1`) showed the production application WAS correct when it was | ||
| 1004 | - /// applied -- but round-36/37's real-file A/B then showed applying it | ||
| 1005 | - /// regresses reference-decoder coherence (see `sbr_hf::generate`'s own | ||
| 1006 | - /// doc comment at its patch-copy site). Round-37 reverted the | ||
| 1007 | - /// application, so this test now pins the opposite: `generate`'s raw, | ||
| 1008 | - /// UNROTATED patch replay lands the tone exactly where | ||
| 1009 | - /// `band_shift_correction` predicts the uncorrected bank convention | ||
| 1010 | - /// would put it (one synthesis-band-width off for this odd gap) -- i.e. | ||
| 1011 | - /// `generate` no longer calls `band_shift_correction` at all, and this | ||
| 1012 | - /// is the intentional (reference-matching) behaviour, not a residual bug. | ||
| 1013 | - #[test] | ||
| 1014 | - fn patch_replay_through_generate_matches_the_uncorrected_bank_convention() { | ||
| 1015 | - use crate::sbr_bands::BandTables; | ||
| 1016 | - use crate::sbr_hf::{ChirpState, HfHistory, generate}; | ||
| 1017 | - | ||
| 1018 | - let tables = BandTables { | ||
| 1019 | - n_master: 0, | ||
| 1020 | - n_high: 0, | ||
| 1021 | - n_low: 0, | ||
| 1022 | - n_q: 1, | ||
| 1023 | - f_high: vec![8, 13], | ||
| 1024 | - f_low: vec![8, 13], | ||
| 1025 | - f_noise: vec![8, 13], | ||
| 1026 | - kx: 8, | ||
| 1027 | - k2: 13, | ||
| 1028 | - }; | ||
| 1029 | - let source_band = 3usize; | ||
| 1030 | - let target_band = 8usize; // build_patches' only patch: source 3..8 -> target 8..13, gap 5 | ||
| 1031 | - | ||
| 1032 | - let omega_step_a = std::f64::consts::PI / (2.0 * ANALYSIS_BANDS as f64); | ||
| 1033 | - let omega_step_s = std::f64::consts::PI / (2.0 * SYNTHESIS_BANDS as f64); | ||
| 1034 | - let band_spacing_s = omega_step_s / std::f64::consts::TAU; | ||
| 1035 | - let slots = 128; | ||
| 1036 | - let core_samples = slots * ANALYSIS_BANDS; | ||
| 1037 | - let fft_len = 4096; | ||
| 1038 | - let centre = (source_band as f64 + 0.5) * omega_step_a; | ||
| 1039 | - | ||
| 1040 | - let analyse = |delta: f64| -> Vec<Complex<f64>> { | ||
| 1041 | - let omega0 = centre + delta * omega_step_a; | ||
| 1042 | - let x: Vec<f64> = (0..core_samples) | ||
| 1043 | - .map(|i| (omega0 * i as f64).cos()) | ||
| 1044 | - .collect(); | ||
| 1045 | - let mut analysis = Analysis::new(); | ||
| 1046 | - let mut sub = Vec::with_capacity(slots); | ||
| 1047 | - for chunk in x.chunks_exact(ANALYSIS_BANDS) { | ||
| 1048 | - let mut c = [0f32; ANALYSIS_BANDS]; | ||
| 1049 | - for (d, &s) in c.iter_mut().zip(chunk) { | ||
| 1050 | - *d = s as f32; | ||
| 1051 | - } | ||
| 1052 | - sub.push(analysis.process_slot(&c)[source_band]); | ||
| 1053 | - } | ||
| 1054 | - sub | ||
| 1055 | - }; | ||
| 1056 | - let synth_direct = |band: usize, sub: &[Complex<f64>]| -> f64 { | ||
| 1057 | - let mut synthesis = Synthesis::new(); | ||
| 1058 | - let mut out = Vec::with_capacity(slots * SYNTHESIS_BANDS); | ||
| 1059 | - for &s in sub { | ||
| 1060 | - let mut v = [Complex::new(0.0, 0.0); SYNTHESIS_BANDS]; | ||
| 1061 | - v[band] = s; | ||
| 1062 | - out.extend(synthesis.process_slot(&v).iter().map(|&s| f64::from(s))); | ||
| 1063 | - } | ||
| 1064 | - dominant_freq(&out[out.len() - fft_len..]) | ||
| 1065 | - }; | ||
| 1066 | - | ||
| 1067 | - println!("delta\tf_calib\tf_measured\texpected\terr(bins)"); | ||
| 1068 | - let mut worst_err_bins = 0.0f64; | ||
| 1069 | - for &delta in &[-0.3f64, 0.0, 0.3] { | ||
| 1070 | - let sub = analyse(delta); | ||
| 1071 | - let f_calib = synth_direct(source_band, &sub); | ||
| 1072 | 480 | ||
| 1073 | - let mut low_cur = vec![vec![Complex::ZERO; slots]; ANALYSIS_BANDS]; | ||
| 1074 | - low_cur[source_band] = sub; | ||
| 1075 | - let mut chirp = ChirpState::new(1); | ||
| 1076 | - let mut history = HfHistory::new(ANALYSIS_BANDS); | ||
| 1077 | - let hf = generate(&low_cur, &tables, &[0u8], &mut chirp, &mut history); | ||
| 1078 | - let row = &hf[target_band - tables.kx as usize]; | ||
| 1079 | - let f_measured = synth_direct(target_band, row); | ||
| 1080 | - | ||
| 1081 | - // Frequency-pure placement (what `band_shift_correction` would | ||
| 1082 | - // restore, were it applied) minus the one-band-width shift the | ||
| 1083 | - // uncorrected bank convention actually leaves in place. | ||
| 1084 | - let k = crate::sbr_hf::band_shift_correction(target_band, source_band); | ||
| 1085 | - let expected = f_calib | ||
| 1086 | - + (target_band as i64 - source_band as i64) as f64 * band_spacing_s | ||
| 1087 | - - k as f64 * band_spacing_s; | ||
| 1088 | - let bin_width = 1.0 / fft_len as f64; | ||
| 1089 | - let err_bins = (f_measured - expected).abs() / bin_width; | ||
| 1090 | - worst_err_bins = f64::max(worst_err_bins, err_bins); | ||
| 1091 | - println!("{delta:+.2}\t{f_calib:.6}\t{f_measured:.6}\t{expected:.6}\t{err_bins:.2}"); | ||
| 1092 | - } | ||
| 1093 | - assert!( | ||
| 1094 | - worst_err_bins <= 3.0, | ||
| 1095 | - "worst production-path prediction error {worst_err_bins} bins exceeds 3 -- \ | ||
| 1096 | - sbr_hf::generate's raw (uncorrected) patch replay no longer matches the \ | ||
| 1097 | - uncorrected bank convention's own predicted placement" | ||
| 1098 | - ); | ||
| 1099 | - } | ||
| 1100 | 481 | ||
| 1101 | - /// Round-13 (queue item 2, "gain-level issue" bucket): per-band | ||
| 1102 | - /// steady-state synthesis amplitude gain for a PHYSICALLY REAL tone at | ||
| 1103 | - /// each synthesis band's own centre frequency -- unlike a naive | ||
| 1104 | - /// constant-complex-value-per-slot excitation (which does not | ||
| 1105 | - /// correspond to any real Analysis output, since a stationary tone's | ||
| 1106 | - /// subband phasor rotates hop to hop), this drives `Synthesis` with a | ||
| 1107 | - /// genuine cosine tone's own [`SYNTHESIS_BANDS`]-wide complex spectrum | ||
| 1108 | - /// at each hop (only band `k0` populated, the rest zero -- an isolated | ||
| 1109 | - /// tone has negligible energy in neighbouring bands at these | ||
| 1110 | - /// crossover widths) and measures the reconstructed PCM tone's own | ||
| 1111 | - /// amplitude against the input's. Verdict: FLAT to six decimal places | ||
| 1112 | - /// across every band tried (0.595853 everywhere, not the isolated | ||
| 1113 | - /// band's own round-trip unity -- the shortfall from 1.0 is the | ||
| 1114 | - /// expected single-subband-vs-adjacent-alias-cancellation factor, not a | ||
| 1115 | - /// per-band defect), so `SYNTH_TRIM` as a single global scalar is NOT | ||
| 1116 | - /// masking a band-dependent overlap-add ripple; the above-crossover | ||
| 1117 | - /// residual (ch1 0.72) is not a synthesis-gain-flatness bug. | ||
| 1118 | - #[test] | ||
| 1119 | - fn synthesis_gain_is_flat_across_bands() { | ||
| 1120 | - let omega_step = std::f64::consts::PI / (2.0 * SYNTHESIS_BANDS as f64); | ||
| 1121 | - let mut min_amp = f64::MAX; | ||
| 1122 | - let mut max_amp = f64::MIN; | ||
| 1123 | - for k0 in 5..SYNTHESIS_BANDS - 5 { | ||
| 1124 | - let omega0 = (k0 as f64 + 0.5) * omega_step; | ||
| 1125 | - let mut synthesis = Synthesis::new(); | ||
| 1126 | - let mut out = Vec::new(); | ||
| 1127 | - let slots = 40; | ||
| 1128 | - for slot in 0..slots { | ||
| 1129 | - let mut v = [Complex::new(0.0, 0.0); SYNTHESIS_BANDS]; | ||
| 1130 | - // Analytic-signal phasor at this band's own hop rate, phase | ||
| 1131 | - // referenced the same way `theta` references analysis's | ||
| 1132 | - // sliding window: exp(i*omega0*(slot*SYNTHESIS_BANDS)). | ||
| 1133 | - let ph = omega0 * (slot * SYNTHESIS_BANDS) as f64; | ||
| 1134 | - v[k0] = Complex::new(ph.cos(), ph.sin()); | ||
| 1135 | - out.extend(synthesis.process_slot(&v)); | ||
| 1136 | - } | ||
| 1137 | - let steady = &out[out.len() / 2..]; | ||
| 1138 | - let rms = (steady | ||
| 1139 | - .iter() | ||
| 1140 | - .map(|&s| f64::from(s) * f64::from(s)) | ||
| 1141 | - .sum::<f64>() | ||
| 1142 | - / steady.len() as f64) | ||
| 1143 | - .sqrt(); | ||
| 1144 | - // A real cosine tone of amplitude A has RMS A/sqrt(2). | ||
| 1145 | - let amp = rms * std::f64::consts::SQRT_2; | ||
| 1146 | - println!("band {k0}: reconstructed amplitude {amp:.6}"); | ||
| 1147 | - min_amp = min_amp.min(amp); | ||
| 1148 | - max_amp = max_amp.max(amp); | ||
| 1149 | - } | ||
| 1150 | - let ripple = (max_amp - min_amp) / min_amp; | ||
| 1151 | - println!("band amplitude range [{min_amp:.6}, {max_amp:.6}], ripple {ripple:e}"); | ||
| 1152 | - assert!( | ||
| 1153 | - ripple < 1e-4, | ||
| 1154 | - "per-band synthesis gain ripple {ripple:e} exceeds 1e-4 -- SYNTH_TRIM's flat-scalar assumption is wrong" | ||
| 1155 | - ); | ||
| 1156 | - } | ||
| 1157 | 482 | ||
| 1158 | /// (Round-43, Task 1 conviction) The tone-excitation gain above | 483 | /// (Round-43, Task 1 conviction) The tone-excitation gain above |
| 1159 | /// (0.595853 amplitude / ~0.355 energy) was calibrated with a single | 484 | /// (0.595853 amplitude / ~0.355 energy) was calibrated with a single |
crates/ec-aac/src/sbr_qmf_window.rsadded+205 -0
| @@ -0,0 +1,205 @@ | |||
| 1 | +//! ISO/IEC 14496-3 4.6.18.4/4.6.18.8 QMF prototype filter: the normative | ||
| 2 | +//! 640-tap coefficient table, cross-validated from two independent sources | ||
| 3 | +//! (checksum: sum, sum-of-squares, max and its index). | ||
| 4 | +//! | ||
| 5 | +//! NOT wired into `crate::sbr_qmf` -- see that module and the ledger for why | ||
| 6 | +//! this round reverted: every analysis/synthesis carrier-phase and | ||
| 7 | +//! window-derivation hypothesis tried against this table (the literal | ||
| 8 | +//! folded 4.6.18.4/4.6.18.8 reading a review produced, and several | ||
| 9 | +//! offset/omega variants of the prior fitted bank's own convention) failed | ||
| 10 | +//! to round-trip a broadband signal above ~0.70 correlation (the folded | ||
| 11 | +//! reading specifically collapsed to ~0.03-0.05, i.e. not even | ||
| 12 | +//! structurally close), so `sbr_qmf` still runs its own fitted Kaiser bank. | ||
| 13 | +//! This table is kept, checksum-pinned, as a verified input for the next | ||
| 14 | +//! attempt. | ||
| 15 | + | ||
| 16 | +/// The normative 640-tap QMF prototype, index 0..639. Not currently | ||
| 17 | +/// consumed by `sbr_qmf` (see the module doc); kept and checksum-pinned for | ||
| 18 | +/// the next attempt at the normative bank. | ||
| 19 | +#[allow(dead_code)] | ||
| 20 | +pub const QMF_WINDOW: [f64; 640] = [ | ||
| 21 | + 0.00000000000000000e+00, -5.52528650469999959e-04, -5.61769257379999957e-04, -4.94751808959999987e-04, | ||
| 22 | + -4.87522797119999997e-04, -4.89379124979999946e-04, -5.04071434970000047e-04, -5.22656429719999959e-04, | ||
| 23 | + -5.46656563370000030e-04, -5.67780256129999956e-04, -5.87093048519999987e-04, -6.13274739379999958e-04, | ||
| 24 | + -6.31249353189999992e-04, -6.54033336209999989e-04, -6.77769077639999947e-04, -6.94161462730000039e-04, | ||
| 25 | + -7.15773647440000002e-04, -7.25504312220000042e-04, -7.44094185410000010e-04, -7.49059805319999975e-04, | ||
| 26 | + -7.68137192699999954e-04, -7.72484859490000044e-04, -7.83433228769999952e-04, -7.77986949269999996e-04, | ||
| 27 | + -7.80366470999999963e-04, -7.80144962570000029e-04, -7.75797733100000030e-04, -7.63079357570000034e-04, | ||
| 28 | + -7.53000142009999985e-04, -7.31935715250000033e-04, -7.21539198759999986e-04, -6.91793753720000050e-04, | ||
| 29 | + -6.65041508930000035e-04, -6.34159490250000017e-04, -5.94611893300000041e-04, -5.56457639060000016e-04, | ||
| 30 | + -5.14557221080000023e-04, -4.60632548030000006e-04, -4.09512145219999985e-04, -3.50117587559999998e-04, | ||
| 31 | + -2.89698117479999975e-04, -2.09833734399999996e-04, -1.44638093489999996e-04, -6.17334407200000046e-05, | ||
| 32 | + 1.34949741799999995e-05, 1.09438312739999999e-04, 2.04301706880000004e-04, 2.94953110410000024e-04, | ||
| 33 | + 4.02654021600000011e-04, 5.10738849519999974e-04, 6.23937613909999957e-04, 7.45802588650000000e-04, | ||
| 34 | + 8.60844332620000052e-04, 9.88598830149999995e-04, 1.12501551306999994e-03, 1.25778846474999990e-03, | ||
| 35 | + 1.39024948271999991e-03, 1.54432198470999993e-03, 1.68680832531000000e-03, 1.83482654223999998e-03, | ||
| 36 | + 1.98411407369000021e-03, 2.14615835557000010e-03, 2.30172547746000005e-03, 2.46256169126000003e-03, | ||
| 37 | + 2.62017586901999982e-03, 2.78704643465000007e-03, 2.94694477164999993e-03, 3.11254206525000011e-03, | ||
| 38 | + 3.27396134846999996e-03, 3.44188741827999986e-03, 3.60082681231000019e-03, 3.76039229103999981e-03, | ||
| 39 | + 3.92074323702999977e-03, 4.08197531935000028e-03, 4.22642692269999988e-03, 4.37307196780999975e-03, | ||
| 40 | + 4.52098527825000023e-03, 4.66064606118000036e-03, 4.79325608497999968e-03, 4.91376035744999981e-03, | ||
| 41 | + 5.03930226012999985e-03, 5.14073539031999985e-03, 5.24611661323999990e-03, 5.34716811981999964e-03, | ||
| 42 | + 5.41967759306999971e-03, 5.48760401507000003e-03, 5.54757145088000028e-03, 5.59380230045000010e-03, | ||
| 43 | + 5.62206432097000011e-03, 5.64551969164000036e-03, 5.63891995151000018e-03, 5.62661141931999984e-03, | ||
| 44 | + 5.59171286630000004e-03, 5.54043639400000031e-03, 5.47537830770000039e-03, 5.38389758970000010e-03, | ||
| 45 | + 5.27157587272000013e-03, 5.13822754514000040e-03, 4.98396877629000024e-03, 4.81094690599999982e-03, | ||
| 46 | + 4.60395301470999975e-03, 4.38018617447000040e-03, 4.12516423269999963e-03, 3.84564081245999988e-03, | ||
| 47 | + 3.54012465506999994e-03, 3.20918858098000019e-03, 2.84467578623000001e-03, 2.45085400321000011e-03, | ||
| 48 | + 2.02741761850000002e-03, 1.57846825767999992e-03, 1.09023290512000001e-03, 5.83226424800000029e-04, | ||
| 49 | + 2.76045190500000009e-05, -5.46428086640000032e-04, -1.15681355226999994e-03, -1.80394725893000003e-03, | ||
| 50 | + -2.48267236448999982e-03, -3.19337783899999996e-03, -3.94011240521999987e-03, -4.72225962399999959e-03, | ||
| 51 | + -5.53372111087999975e-03, -6.37922932685000034e-03, -7.26158168517000019e-03, -8.17982333726000044e-03, | ||
| 52 | + -9.13253296085000076e-03, -1.01150215498599996e-02, -1.11315548032100003e-02, -1.21849995950799993e-02, | ||
| 53 | + 1.32718220035100004e-02, 1.43904666079200001e-02, 1.55405553342300006e-02, 1.67324712998900005e-02, | ||
| 54 | + 1.79433381344300015e-02, 1.91872431369799999e-02, 2.04531793355499994e-02, 2.17467550253499994e-02, | ||
| 55 | + 2.30680169286200006e-02, 2.44160992028500008e-02, 2.57875847546699989e-02, 2.71859429632900010e-02, | ||
| 56 | + 2.86072173638499995e-02, 3.00502657427899993e-02, 3.15017608738899987e-02, 3.29754081033699978e-02, | ||
| 57 | + 3.44620948768599999e-02, 3.59697560554200005e-02, 3.74812850425199975e-02, 3.90053679474499995e-02, | ||
| 58 | + 4.05349170558400029e-02, 4.20649094636700027e-02, 4.36097542130400029e-02, 4.51488405641300022e-02, | ||
| 59 | + 4.66843027264199975e-02, 4.82165720067199988e-02, 4.97385755601399970e-02, 5.12556155521600026e-02, | ||
| 60 | + 5.27630746520700022e-02, 5.42452768358899981e-02, 5.57173648213799971e-02, 5.71616450129900019e-02, | ||
| 61 | + 5.85915683626000022e-02, 5.99837480176100002e-02, 6.13455171720699993e-02, 6.26857808117199933e-02, | ||
| 62 | + 6.39715898068100031e-02, 6.52247106438000046e-02, 6.64367512210399941e-02, 6.76075985122800011e-02, | ||
| 63 | + 6.87043828351199953e-02, 6.97630244712700021e-02, 7.07628710726599941e-02, 7.17002673110199995e-02, | ||
| 64 | + 7.25682583308299989e-02, 7.33620255080300043e-02, 7.41003642434199944e-02, 7.47452558119399979e-02, | ||
| 65 | + 7.53137336201900043e-02, 7.58008358658399939e-02, 7.61992479339600043e-02, 7.64992170411900041e-02, | ||
| 66 | + 7.67093490424499980e-02, 7.68173975696399974e-02, 7.68230011392300044e-02, 7.67204924174599984e-02, | ||
| 67 | + 7.65050718319399969e-02, 7.61748321853600030e-02, 7.57305756506100047e-02, 7.51576255287000061e-02, | ||
| 68 | + 7.44664394756399950e-02, 7.36406005762000049e-02, 7.26774642729900028e-02, 7.15826364790300013e-02, | ||
| 69 | + 7.03533073509299972e-02, 6.89664013195099984e-02, 6.74525021516600015e-02, 6.57690668650799948e-02, | ||
| 70 | + 6.39444805963299973e-02, 6.19602779038700008e-02, 5.98166570808999973e-02, 5.75152691986699979e-02, | ||
| 71 | + 5.50460034300900014e-02, 5.24093821736600005e-02, 4.95978676344500033e-02, 4.66303305170100019e-02, | ||
| 72 | + 4.34768782195799966e-02, 4.01458278412700001e-02, 3.66418116813300027e-02, 3.29583930669100009e-02, | ||
| 73 | + 2.90824006012499990e-02, 2.50307561890899984e-02, 2.07997072862199997e-02, 1.63701258222800003e-02, | ||
| 74 | + 1.17623832785699999e-02, 6.96368621616999962e-03, 1.97656014503000020e-03, -3.20868968303999981e-03, | ||
| 75 | + -8.57117491365999920e-03, -1.41288827355800003e-02, -1.98834129257299992e-02, -2.58227288806400015e-02, | ||
| 76 | + -3.19531274533199974e-02, -3.82776572082200034e-02, -4.47806821585600007e-02, -5.14804176793400015e-02, | ||
| 77 | + -5.83705326833600033e-02, -6.54409853135899944e-02, -7.26943300812900040e-02, -8.01372934427899974e-02, | ||
| 78 | + -8.77547536559299957e-02, -9.55533352891400067e-02, -1.03532953114629997e-01, -1.11682693177299994e-01, | ||
| 79 | + -1.20007798467999999e-01, -1.28500285038779999e-01, -1.37155176119340000e-01, -1.45976649118700008e-01, | ||
| 80 | + -1.54960707106050005e-01, -1.64095885566689997e-01, -1.73380817217060001e-01, -1.82817254851420002e-01, | ||
| 81 | + -1.92396674572670012e-01, -2.02125017681030000e-01, -2.11973585380559992e-01, -2.21965269641489993e-01, | ||
| 82 | + -2.32069087067909990e-01, -2.42301688459740011e-01, -2.52648030957219993e-01, -2.63105329946029975e-01, | ||
| 83 | + -2.73663404056250004e-01, -2.84321418910849999e-01, -2.95071671706459981e-01, -3.05909857519160000e-01, | ||
| 84 | + -3.16827891364560021e-01, -3.27811372721049987e-01, -3.38872269386649994e-01, -3.49991412293099990e-01, | ||
| 85 | + 3.61158990313549977e-01, 3.72379554630610010e-01, 3.83635001390429997e-01, 3.94921176156749987e-01, | ||
| 86 | + 4.06231767676250022e-01, 4.17569689684089973e-01, 4.28911992073729986e-01, 4.40255375436649998e-01, | ||
| 87 | + 4.51599653568240000e-01, 4.62930808527570015e-01, 4.74245321461150005e-01, 4.85525309110990011e-01, | ||
| 88 | + 4.96770825457070020e-01, 5.07981750004339982e-01, 5.19123497023910030e-01, 5.30224089568550050e-01, | ||
| 89 | + 5.41255344873220023e-01, 5.52205125850609990e-01, 5.63078914013700027e-01, 5.73852413169229969e-01, | ||
| 90 | + 5.84540323546789975e-01, 5.95112308624960007e-01, 6.05578353891800036e-01, 6.15910993202909984e-01, | ||
| 91 | + 6.26124269560550006e-01, 6.36198010772859979e-01, 6.46126969594610023e-01, 6.55901630246709999e-01, | ||
| 92 | + 6.65513988016270042e-01, 6.74966319017120009e-01, 6.84235329345979970e-01, 6.93328237670320036e-01, | ||
| 93 | + 7.02238871935390030e-01, 7.10941042630950037e-01, 7.19446263495610028e-01, 7.27744890029940028e-01, | ||
| 94 | + 7.35821175827690022e-01, 7.43682786364880055e-01, 7.51313745612369965e-01, 7.58708076082419969e-01, | ||
| 95 | + 7.65867486509389961e-01, 7.72778088133269980e-01, 7.79428751902159989e-01, 7.85835312039199985e-01, | ||
| 96 | + 7.91973584164240019e-01, 7.97846641377000010e-01, 8.03448575185049974e-01, 8.08769500444910028e-01, | ||
| 97 | + 8.13819127062169967e-01, 8.18577600464679977e-01, 8.23041989054089984e-01, 8.27227534733600001e-01, | ||
| 98 | + 8.31103845715200018e-01, 8.34693736184019985e-01, 8.37971733788649975e-01, 8.40954139247219956e-01, | ||
| 99 | + 8.43623828120049990e-01, 8.45981846982060026e-01, 8.48031577707630047e-01, 8.49780519842679993e-01, | ||
| 100 | + 8.51197152493429976e-01, 8.52304703521470031e-01, 8.53102094970169977e-01, 8.53572057391070005e-01, | ||
| 101 | + 8.53738560059369989e-01, 8.53572057391070005e-01, 8.53102094970169977e-01, 8.52304703521470031e-01, | ||
| 102 | + 8.51197152493429976e-01, 8.49780519842679993e-01, 8.48031577707630047e-01, 8.45981846982060026e-01, | ||
| 103 | + 8.43623828120049990e-01, 8.40954139247219956e-01, 8.37971733788649975e-01, 8.34693736184019985e-01, | ||
| 104 | + 8.31103845715200018e-01, 8.27227534733600001e-01, 8.23041989054089984e-01, 8.18577600464679977e-01, | ||
| 105 | + 8.13819127062169967e-01, 8.08769500444910028e-01, 8.03448575185049974e-01, 7.97846641377000010e-01, | ||
| 106 | + 7.91973584164240019e-01, 7.85835312039199985e-01, 7.79428751902159989e-01, 7.72778088133269980e-01, | ||
| 107 | + 7.65867486509389961e-01, 7.58708076082419969e-01, 7.51313745612369965e-01, 7.43682786364880055e-01, | ||
| 108 | + 7.35821175827690022e-01, 7.27744890029940028e-01, 7.19446263495610028e-01, 7.10941042630950037e-01, | ||
| 109 | + 7.02238871935390030e-01, 6.93328237670320036e-01, 6.84235329345979970e-01, 6.74966319017120009e-01, | ||
| 110 | + 6.65513988016270042e-01, 6.55901630246709999e-01, 6.46126969594610023e-01, 6.36198010772859979e-01, | ||
| 111 | + 6.26124269560550006e-01, 6.15910993202909984e-01, 6.05578353891800036e-01, 5.95112308624960007e-01, | ||
| 112 | + 5.84540323546789975e-01, 5.73852413169229969e-01, 5.63078914013700027e-01, 5.52205125850609990e-01, | ||
| 113 | + 5.41255344873220023e-01, 5.30224089568550050e-01, 5.19123497023910030e-01, 5.07981750004339982e-01, | ||
| 114 | + 4.96770825457070020e-01, 4.85525309110990011e-01, 4.74245321461150005e-01, 4.62930808527570015e-01, | ||
| 115 | + 4.51599653568240000e-01, 4.40255375436649998e-01, 4.28911992073729986e-01, 4.17569689684089973e-01, | ||
| 116 | + 4.06231767676250022e-01, 3.94921176156749987e-01, 3.83635001390429997e-01, 3.72379554630610010e-01, | ||
| 117 | + -3.61158990313549977e-01, -3.49991412293099990e-01, -3.38872269386649994e-01, -3.27811372721049987e-01, | ||
| 118 | + -3.16827891364560021e-01, -3.05909857519160000e-01, -2.95071671706459981e-01, -2.84321418910849999e-01, | ||
| 119 | + -2.73663404056250004e-01, -2.63105329946029975e-01, -2.52648030957219993e-01, -2.42301688459740011e-01, | ||
| 120 | + -2.32069087067909990e-01, -2.21965269641489993e-01, -2.11973585380559992e-01, -2.02125017681030000e-01, | ||
| 121 | + -1.92396674572670012e-01, -1.82817254851420002e-01, -1.73380817217060001e-01, -1.64095885566689997e-01, | ||
| 122 | + -1.54960707106050005e-01, -1.45976649118700008e-01, -1.37155176119340000e-01, -1.28500285038779999e-01, | ||
| 123 | + -1.20007798467999999e-01, -1.11682693177299994e-01, -1.03532953114629997e-01, -9.55533352891400067e-02, | ||
| 124 | + -8.77547536559299957e-02, -8.01372934427899974e-02, -7.26943300812900040e-02, -6.54409853135899944e-02, | ||
| 125 | + -5.83705326833600033e-02, -5.14804176793400015e-02, -4.47806821585600007e-02, -3.82776572082200034e-02, | ||
| 126 | + -3.19531274533199974e-02, -2.58227288806400015e-02, -1.98834129257299992e-02, -1.41288827355800003e-02, | ||
| 127 | + -8.57117491365999920e-03, -3.20868968303999981e-03, 1.97656014503000020e-03, 6.96368621616999962e-03, | ||
| 128 | + 1.17623832785699999e-02, 1.63701258222800003e-02, 2.07997072862199997e-02, 2.50307561890899984e-02, | ||
| 129 | + 2.90824006012499990e-02, 3.29583930669100009e-02, 3.66418116813300027e-02, 4.01458278412700001e-02, | ||
| 130 | + 4.34768782195799966e-02, 4.66303305170100019e-02, 4.95978676344500033e-02, 5.24093821736600005e-02, | ||
| 131 | + 5.50460034300900014e-02, 5.75152691986699979e-02, 5.98166570808999973e-02, 6.19602779038700008e-02, | ||
| 132 | + 6.39444805963299973e-02, 6.57690668650799948e-02, 6.74525021516600015e-02, 6.89664013195099984e-02, | ||
| 133 | + 7.03533073509299972e-02, 7.15826364790300013e-02, 7.26774642729900028e-02, 7.36406005762000049e-02, | ||
| 134 | + 7.44664394756399950e-02, 7.51576255287000061e-02, 7.57305756506100047e-02, 7.61748321853600030e-02, | ||
| 135 | + 7.65050718319399969e-02, 7.67204924174599984e-02, 7.68230011392300044e-02, 7.68173975696399974e-02, | ||
| 136 | + 7.67093490424499980e-02, 7.64992170411900041e-02, 7.61992479339600043e-02, 7.58008358658399939e-02, | ||
| 137 | + 7.53137336201900043e-02, 7.47452558119399979e-02, 7.41003642434199944e-02, 7.33620255080300043e-02, | ||
| 138 | + 7.25682583308299989e-02, 7.17002673110199995e-02, 7.07628710726599941e-02, 6.97630244712700021e-02, | ||
| 139 | + 6.87043828351199953e-02, 6.76075985122800011e-02, 6.64367512210399941e-02, 6.52247106438000046e-02, | ||
| 140 | + 6.39715898068100031e-02, 6.26857808117199933e-02, 6.13455171720699993e-02, 5.99837480176100002e-02, | ||
| 141 | + 5.85915683626000022e-02, 5.71616450129900019e-02, 5.57173648213799971e-02, 5.42452768358899981e-02, | ||
| 142 | + 5.27630746520700022e-02, 5.12556155521600026e-02, 4.97385755601399970e-02, 4.82165720067199988e-02, | ||
| 143 | + 4.66843027264199975e-02, 4.51488405641300022e-02, 4.36097542130400029e-02, 4.20649094636700027e-02, | ||
| 144 | + 4.05349170558400029e-02, 3.90053679474499995e-02, 3.74812850425199975e-02, 3.59697560554200005e-02, | ||
| 145 | + 3.44620948768599999e-02, 3.29754081033699978e-02, 3.15017608738899987e-02, 3.00502657427899993e-02, | ||
| 146 | + 2.86072173638499995e-02, 2.71859429632900010e-02, 2.57875847546699989e-02, 2.44160992028500008e-02, | ||
| 147 | + 2.30680169286200006e-02, 2.17467550253499994e-02, 2.04531793355499994e-02, 1.91872431369799999e-02, | ||
| 148 | + 1.79433381344300015e-02, 1.67324712998900005e-02, 1.55405553342300006e-02, 1.43904666079200001e-02, | ||
| 149 | + -1.32718220035100004e-02, -1.21849995950799993e-02, -1.11315548032100003e-02, -1.01150215498599996e-02, | ||
| 150 | + -9.13253296085000076e-03, -8.17982333726000044e-03, -7.26158168517000019e-03, -6.37922932685000034e-03, | ||
| 151 | + -5.53372111087999975e-03, -4.72225962399999959e-03, -3.94011240521999987e-03, -3.19337783899999996e-03, | ||
| 152 | + -2.48267236448999982e-03, -1.80394725893000003e-03, -1.15681355226999994e-03, -5.46428086640000032e-04, | ||
| 153 | + 2.76045190500000009e-05, 5.83226424800000029e-04, 1.09023290512000001e-03, 1.57846825767999992e-03, | ||
| 154 | + 2.02741761850000002e-03, 2.45085400321000011e-03, 2.84467578623000001e-03, 3.20918858098000019e-03, | ||
| 155 | + 3.54012465506999994e-03, 3.84564081245999988e-03, 4.12516423269999963e-03, 4.38018617447000040e-03, | ||
| 156 | + 4.60395301470999975e-03, 4.81094690599999982e-03, 4.98396877629000024e-03, 5.13822754514000040e-03, | ||
| 157 | + 5.27157587272000013e-03, 5.38389758970000010e-03, 5.47537830770000039e-03, 5.54043639400000031e-03, | ||
| 158 | + 5.59171286630000004e-03, 5.62661141931999984e-03, 5.63891995151000018e-03, 5.64551969164000036e-03, | ||
| 159 | + 5.62206432097000011e-03, 5.59380230045000010e-03, 5.54757145088000028e-03, 5.48760401507000003e-03, | ||
| 160 | + 5.41967759306999971e-03, 5.34716811981999964e-03, 5.24611661323999990e-03, 5.14073539031999985e-03, | ||
| 161 | + 5.03930226012999985e-03, 4.91376035744999981e-03, 4.79325608497999968e-03, 4.66064606118000036e-03, | ||
| 162 | + 4.52098527825000023e-03, 4.37307196780999975e-03, 4.22642692269999988e-03, 4.08197531935000028e-03, | ||
| 163 | + 3.92074323702999977e-03, 3.76039229103999981e-03, 3.60082681231000019e-03, 3.44188741827999986e-03, | ||
| 164 | + 3.27396134846999996e-03, 3.11254206525000011e-03, 2.94694477164999993e-03, 2.78704643465000007e-03, | ||
| 165 | + 2.62017586901999982e-03, 2.46256169126000003e-03, 2.30172547746000005e-03, 2.14615835557000010e-03, | ||
| 166 | + 1.98411407369000021e-03, 1.83482654223999998e-03, 1.68680832531000000e-03, 1.54432198470999993e-03, | ||
| 167 | + 1.39024948271999991e-03, 1.25778846474999990e-03, 1.12501551306999994e-03, 9.88598830149999995e-04, | ||
| 168 | + 8.60844332620000052e-04, 7.45802588650000000e-04, 6.23937613909999957e-04, 5.10738849519999974e-04, | ||
| 169 | + 4.02654021600000011e-04, 2.94953110410000024e-04, 2.04301706880000004e-04, 1.09438312739999999e-04, | ||
| 170 | + 1.34949741799999995e-05, -6.17334407200000046e-05, -1.44638093489999996e-04, -2.09833734399999996e-04, | ||
| 171 | + -2.89698117479999975e-04, -3.50117587559999998e-04, -4.09512145219999985e-04, -4.60632548030000006e-04, | ||
| 172 | + -5.14557221080000023e-04, -5.56457639060000016e-04, -5.94611893300000041e-04, -6.34159490250000017e-04, | ||
| 173 | + -6.65041508930000035e-04, -6.91793753720000050e-04, -7.21539198759999986e-04, -7.31935715250000033e-04, | ||
| 174 | + -7.53000142009999985e-04, -7.63079357570000034e-04, -7.75797733100000030e-04, -7.80144962570000029e-04, | ||
| 175 | + -7.80366470999999963e-04, -7.77986949269999996e-04, -7.83433228769999952e-04, -7.72484859490000044e-04, | ||
| 176 | + -7.68137192699999954e-04, -7.49059805319999975e-04, -7.44094185410000010e-04, -7.25504312220000042e-04, | ||
| 177 | + -7.15773647440000002e-04, -6.94161462730000039e-04, -6.77769077639999947e-04, -6.54033336209999989e-04, | ||
| 178 | + -6.31249353189999992e-04, -6.13274739379999958e-04, -5.87093048519999987e-04, -5.67780256129999956e-04, | ||
| 179 | + -5.46656563370000030e-04, -5.22656429719999959e-04, -5.04071434970000047e-04, -4.89379124979999946e-04, | ||
| 180 | + -4.87522797119999997e-04, -4.94751808959999987e-04, -5.61769257379999957e-04, -5.52528650469999959e-04, | ||
| 181 | +]; | ||
| 182 | + | ||
| 183 | +#[cfg(test)] | ||
| 184 | +mod tests { | ||
| 185 | + use super::*; | ||
| 186 | + | ||
| 187 | + #[test] | ||
| 188 | + fn checksum_matches_the_cross_validated_source() { | ||
| 189 | + let sum: f64 = QMF_WINDOW.iter().sum(); | ||
| 190 | + let sum_sq: f64 = QMF_WINDOW.iter().map(|v| v * v).sum(); | ||
| 191 | + let mut max = f64::MIN; | ||
| 192 | + let mut argmax = 0usize; | ||
| 193 | + for (i, &v) in QMF_WINDOW.iter().enumerate() { | ||
| 194 | + if v > max { | ||
| 195 | + max = v; | ||
| 196 | + argmax = i; | ||
| 197 | + } | ||
| 198 | + } | ||
| 199 | + assert!((sum - 8.14630094365516442e+01).abs() < 1e-9, "sum={sum}"); | ||
| 200 | + assert!((sum_sq - 6.40000000000000284e+01).abs() < 1e-9, "sum_sq={sum_sq}"); | ||
| 201 | + assert!((max - 8.53738560059369989e-01).abs() < 1e-12, "max={max}"); | ||
| 202 | + assert_eq!(argmax, 320); | ||
| 203 | + } | ||
| 204 | +} | ||
| 205 | + | ||
scripts/aac-tables/qmf_check.pyadded+389 -0
| @@ -0,0 +1,389 @@ | |||
| 1 | +#!/usr/bin/env python3 | ||
| 2 | +"""Numpy prototype of the ISO/IEC 14496-3 4.6.18.4.1 (32-band analysis) and | ||
| 3 | +4.6.18.8.2 (64-band synthesis) QMF banks, run back-to-back as a passthrough | ||
| 4 | +round-trip (upper 32 synthesis subbands zeroed) to verify the exact carrier | ||
| 5 | +equations before porting to Rust. See ledger sbr-hunt-resume for context. | ||
| 6 | + | ||
| 7 | +Usage: python3 qmf_check.py | ||
| 8 | +""" | ||
| 9 | +import numpy as np | ||
| 10 | + | ||
| 11 | +TAPS_PATH = "/tmp/claude-1000/-home-user-Documents-Code-Rust-edith-codecs/041875c4-7950-4e24-950e-7b6e9eb5ba3c/scratchpad/qmf_proto_640.txt" | ||
| 12 | +c = np.array([float(x) for x in open(TAPS_PATH)]) | ||
| 13 | +assert c.shape == (640,) | ||
| 14 | + | ||
| 15 | + | ||
| 16 | +class Analysis32: | ||
| 17 | + """4.6.18.4.1: 32 new real samples in -> 32 complex subbands out per slot.""" | ||
| 18 | + | ||
| 19 | + def __init__(self, window): | ||
| 20 | + self.c = window | ||
| 21 | + self.x = np.zeros(320) # analysis history buffer, x[0]=newest | ||
| 22 | + | ||
| 23 | + def process_slot(self, new32, newest_at_zero=True, tap=None, sign=-1.0): | ||
| 24 | + x = self.x | ||
| 25 | + # shift: x[n] = x[n-32] for n=319..32 ; new samples into x[31..0] | ||
| 26 | + x[32:320] = x[0:288] | ||
| 27 | + if newest_at_zero: | ||
| 28 | + x[0:32] = new32[::-1] # newest at x[0] | ||
| 29 | + else: | ||
| 30 | + x[0:32] = new32 # oldest-at-front variant | ||
| 31 | + if tap == "c2n": | ||
| 32 | + Z = x * self.c[0::2][: len(x)] | ||
| 33 | + else: | ||
| 34 | + Z = x * self.c[: len(x)] | ||
| 35 | + u = np.zeros(64) | ||
| 36 | + for n in range(64): | ||
| 37 | + u[n] = Z[n] + Z[n + 64] + Z[n + 128] + Z[n + 192] + Z[n + 256] | ||
| 38 | + k = np.arange(32) | ||
| 39 | + n = np.arange(64) | ||
| 40 | + # X[k] = sum_n u[n] * exp(sign * j*pi/64*(k+0.5)*(2n-1)) | ||
| 41 | + phase = sign * 1j * np.pi / 64.0 * np.outer(2 * n - 1, k + 0.5) | ||
| 42 | + X = u @ np.exp(phase) | ||
| 43 | + self.x = x | ||
| 44 | + return X # shape (32,) complex | ||
| 45 | + | ||
| 46 | + | ||
| 47 | +class Synthesis64: | ||
| 48 | + """4.6.18.8.2: 64 complex subbands in -> 64 real samples out per slot.""" | ||
| 49 | + | ||
| 50 | + def __init__(self, window, sign=1.0, use_re=True): | ||
| 51 | + self.c = window | ||
| 52 | + self.v = np.zeros(1280) | ||
| 53 | + self.sign = sign | ||
| 54 | + self.use_re = use_re | ||
| 55 | + | ||
| 56 | + def process_slot(self, X64): | ||
| 57 | + v = self.v | ||
| 58 | + v[128:1280] = v[0:1152] | ||
| 59 | + k = np.arange(64) | ||
| 60 | + n = np.arange(128) | ||
| 61 | + phase = self.sign * 1j * np.pi / 128.0 * np.outer(2 * n - 255, k + 0.5) | ||
| 62 | + vv = (1.0 / 64.0) * (np.exp(phase) @ X64) | ||
| 63 | + v[0:128] = vv.real if self.use_re else (vv.real + vv.imag) | ||
| 64 | + self.v = v | ||
| 65 | + g = np.zeros(640) | ||
| 66 | + for i in range(5): | ||
| 67 | + g[128 * i : 128 * i + 64] = v[256 * i : 256 * i + 64] | ||
| 68 | + g[128 * i + 64 : 128 * i + 128] = v[256 * i + 192 : 256 * i + 256] | ||
| 69 | + w = g * self.c | ||
| 70 | + y = np.zeros(64) | ||
| 71 | + for k_ in range(10): | ||
| 72 | + y += w[64 * k_ : 64 * k_ + 64] | ||
| 73 | + return y | ||
| 74 | + | ||
| 75 | + | ||
| 76 | +def run_trial(name, syn_sign=1.0, syn_use_re=True, **kw): | ||
| 77 | + rng = np.random.default_rng(0) | ||
| 78 | + n_slots = 128 # 8192 samples / 64 | ||
| 79 | + x_in = rng.standard_normal(8192) | ||
| 80 | + ana = Analysis32(c) | ||
| 81 | + syn = Synthesis64(c, sign=syn_sign, use_re=syn_use_re) | ||
| 82 | + out = np.zeros(8192 * 2) | ||
| 83 | + for s in range(n_slots): | ||
| 84 | + new32 = x_in[s * 32 : s * 32 + 32] | ||
| 85 | + X32 = ana.process_slot(new32, **{k: v for k, v in kw.items() if k in ("newest_at_zero", "tap", "sign")}) | ||
| 86 | + X64 = np.zeros(64, dtype=complex) | ||
| 87 | + X64[0:32] = X32 | ||
| 88 | + y64 = syn.process_slot(X64) | ||
| 89 | + out[s * 64 : s * 64 + 64] = y64 | ||
| 90 | + | ||
| 91 | + best_corr = -2.0 | ||
| 92 | + best_lag = None | ||
| 93 | + best_ratio = None | ||
| 94 | + for lag in range(0, 800): | ||
| 95 | + a = out[lag : lag + 8192] | ||
| 96 | + b = x_in[: len(a)] | ||
| 97 | + if len(a) < 4000: | ||
| 98 | + continue | ||
| 99 | + # correlate against decimated-out-at-even-samples vs input directly: | ||
| 100 | + oa = out[lag::2][: len(x_in)] | ||
| 101 | + n = min(len(oa), len(x_in)) - 10 | ||
| 102 | + oa = oa[:n] | ||
| 103 | + bb = x_in[:n] | ||
| 104 | + if np.std(oa) < 1e-12: | ||
| 105 | + continue | ||
| 106 | + corr = np.corrcoef(oa, bb)[0, 1] | ||
| 107 | + if corr > best_corr: | ||
| 108 | + best_corr = corr | ||
| 109 | + best_lag = lag | ||
| 110 | + best_ratio = np.std(oa) / np.std(bb) | ||
| 111 | + pass # summarized in table below | ||
| 112 | + return best_corr | ||
| 113 | + | ||
| 114 | + | ||
| 115 | +class Analysis64: | ||
| 116 | + """4.6.18.4: 64 new real samples in -> 64 complex subbands out per slot | ||
| 117 | + (same-rate variant, x of 640, full c[n] tap, folded to 128).""" | ||
| 118 | + | ||
| 119 | + def __init__(self, window): | ||
| 120 | + self.c = window | ||
| 121 | + self.x = np.zeros(640) # x[0]=newest | ||
| 122 | + | ||
| 123 | + def process_slot(self, new64): | ||
| 124 | + x = self.x | ||
| 125 | + x[64:640] = x[0:576] | ||
| 126 | + x[0:64] = new64[::-1] # newest at x[0] | ||
| 127 | + Z = x * self.c | ||
| 128 | + u = np.zeros(128) | ||
| 129 | + for n in range(128): | ||
| 130 | + u[n] = Z[n] + Z[n + 128] + Z[n + 256] + Z[n + 384] + Z[n + 512] | ||
| 131 | + k = np.arange(64) | ||
| 132 | + n = np.arange(128) | ||
| 133 | + phase = 1j * np.pi / 128.0 * np.outer(2 * n - 1, k + 0.5) | ||
| 134 | + X = u @ np.exp(phase) | ||
| 135 | + self.x = x | ||
| 136 | + return X # shape (64,) complex | ||
| 137 | + | ||
| 138 | + | ||
| 139 | +class Synthesis32Downsampled: | ||
| 140 | + """4.6.18.8.3: 32 complex subbands in -> 32 real samples out per slot | ||
| 141 | + (downsampled, same-rate variant).""" | ||
| 142 | + | ||
| 143 | + def __init__(self, window): | ||
| 144 | + self.c = window | ||
| 145 | + self.v = np.zeros(640) | ||
| 146 | + | ||
| 147 | + def process_slot(self, X32): | ||
| 148 | + v = self.v | ||
| 149 | + v[64:640] = v[0:576] | ||
| 150 | + k = np.arange(32) | ||
| 151 | + n = np.arange(64) | ||
| 152 | + phase = 1j * np.pi / 64.0 * np.outer(2 * n - 63, k + 0.5) | ||
| 153 | + vv = (1.0 / 32.0) * (np.exp(phase) @ X32) | ||
| 154 | + v[0:64] = vv.real | ||
| 155 | + self.v = v | ||
| 156 | + g = np.zeros(320) | ||
| 157 | + for i in range(5): | ||
| 158 | + g[64 * i : 64 * i + 32] = v[128 * i : 128 * i + 32] | ||
| 159 | + g[64 * i + 32 : 64 * i + 64] = v[128 * i + 96 : 128 * i + 128] | ||
| 160 | + w = g * self.c[0::2] | ||
| 161 | + y = np.zeros(32) | ||
| 162 | + for k_ in range(10): | ||
| 163 | + y += w[32 * k_ : 32 * k_ + 32] | ||
| 164 | + return y | ||
| 165 | + | ||
| 166 | + | ||
| 167 | +class Analysis64Param: | ||
| 168 | + """64-band analysis with the shift-direction (T1) and modulation-index | ||
| 169 | + (T2) axes exposed as parameters, for cross-check bisection.""" | ||
| 170 | + | ||
| 171 | + def __init__(self, window, shift_mode="reverse_newest_at_0", mod_sign=-1.0): | ||
| 172 | + self.c = window | ||
| 173 | + self.x = np.zeros(640) | ||
| 174 | + self.shift_mode = shift_mode | ||
| 175 | + self.mod_sign = mod_sign # -1.0 -> (2n-1), +1.0 -> (2n+1) | ||
| 176 | + | ||
| 177 | + def process_slot(self, new64): | ||
| 178 | + x = self.x | ||
| 179 | + if self.shift_mode == "reverse_newest_at_0": | ||
| 180 | + x[64:640] = x[0:576] | ||
| 181 | + x[0:64] = new64[::-1] | ||
| 182 | + else: # "forward_newest_at_top": x[n] <- x[n+64], new64 forward into x[576:640] | ||
| 183 | + x[0:576] = x[64:640] | ||
| 184 | + x[576:640] = new64 | ||
| 185 | + Z = x * self.c | ||
| 186 | + u = np.zeros(128) | ||
| 187 | + for n in range(128): | ||
| 188 | + u[n] = Z[n] + Z[n + 128] + Z[n + 256] + Z[n + 384] + Z[n + 512] | ||
| 189 | + k = np.arange(64) | ||
| 190 | + n = np.arange(128) | ||
| 191 | + expo = 2 * n + 1 if self.mod_sign > 0 else 2 * n - 1 | ||
| 192 | + phase = 1j * np.pi / 128.0 * np.outer(expo, k + 0.5) | ||
| 193 | + X = u @ np.exp(phase) | ||
| 194 | + self.x = x | ||
| 195 | + return X | ||
| 196 | + | ||
| 197 | + | ||
| 198 | +class Synthesis64Param: | ||
| 199 | + """64-band synthesis with shift-direction (T1), modulation offset (T2: | ||
| 200 | + 2n-255 vs 2n+1) and the 1/64 scale (T3) exposed as parameters.""" | ||
| 201 | + | ||
| 202 | + def __init__(self, window, shift_mode="reverse_newest_at_0", mod_variant="2n-255", scale=True): | ||
| 203 | + self.c = window | ||
| 204 | + self.v = np.zeros(1280) | ||
| 205 | + self.shift_mode = shift_mode | ||
| 206 | + self.mod_variant = mod_variant | ||
| 207 | + self.scale = scale | ||
| 208 | + | ||
| 209 | + def process_slot(self, X64): | ||
| 210 | + v = self.v | ||
| 211 | + k = np.arange(64) | ||
| 212 | + n = np.arange(128) | ||
| 213 | + expo = (2 * n + 1) if self.mod_variant == "2n+1" else (2 * n - 255) | ||
| 214 | + phase = 1j * np.pi / 128.0 * np.outer(expo, k + 0.5) | ||
| 215 | + scale_factor = (1.0 / 64.0) if self.scale else 1.0 | ||
| 216 | + vv = scale_factor * (np.exp(phase) @ X64) | ||
| 217 | + if self.shift_mode == "reverse_newest_at_0": | ||
| 218 | + v[128:1280] = v[0:1152] | ||
| 219 | + v[0:128] = vv.real | ||
| 220 | + else: # "forward_newest_at_top" | ||
| 221 | + v[0:1152] = v[128:1280] | ||
| 222 | + v[1152:1280] = vv.real | ||
| 223 | + self.v = v | ||
| 224 | + g = np.zeros(640) | ||
| 225 | + for i in range(5): | ||
| 226 | + g[128 * i : 128 * i + 64] = v[256 * i : 256 * i + 64] | ||
| 227 | + g[128 * i + 64 : 128 * i + 128] = v[256 * i + 192 : 256 * i + 256] | ||
| 228 | + w = g * self.c | ||
| 229 | + y = np.zeros(64) | ||
| 230 | + for k_ in range(10): | ||
| 231 | + y += w[64 * k_ : 64 * k_ + 64] | ||
| 232 | + return y | ||
| 233 | + | ||
| 234 | + | ||
| 235 | +def run_same_rate_64_param(shift_mode, mod_sign, mod_variant, scale, n_slots=160, lag_max=1300): | ||
| 236 | + rng = np.random.default_rng(0) | ||
| 237 | + x_in = rng.standard_normal(64 * n_slots) | ||
| 238 | + ana = Analysis64Param(c, shift_mode=shift_mode, mod_sign=mod_sign) | ||
| 239 | + syn = Synthesis64Param(c, shift_mode=shift_mode, mod_variant=mod_variant, scale=scale) | ||
| 240 | + out = np.zeros(64 * n_slots) | ||
| 241 | + for s in range(n_slots): | ||
| 242 | + X64 = ana.process_slot(x_in[64 * s : 64 * s + 64]) | ||
| 243 | + out[64 * s : 64 * s + 64] = syn.process_slot(X64) | ||
| 244 | + energy_ratio = np.sum(out**2) / np.sum(x_in**2) | ||
| 245 | + corr, lag, ratio = best_lag_corr(out, x_in, lag_max) | ||
| 246 | + return corr, lag, ratio, energy_ratio | ||
| 247 | + | ||
| 248 | + | ||
| 249 | +def bisect_t1_t2_t3(): | ||
| 250 | + print() | ||
| 251 | + print("T1/T2/T3 cross-check bisection (64->64, same family):") | ||
| 252 | + rows = [] | ||
| 253 | + for shift_mode in ("reverse_newest_at_0", "forward_newest_at_top"): | ||
| 254 | + for mod_sign in (-1.0, 1.0): # analysis (2n-1) vs (2n+1) | ||
| 255 | + for mod_variant in ("2n-255", "2n+1"): # synthesis | ||
| 256 | + for scale in (True, False): | ||
| 257 | + corr, lag, ratio, energy = run_same_rate_64_param(shift_mode, mod_sign, mod_variant, scale) | ||
| 258 | + name = f"shift={shift_mode} a_mod={'2n+1' if mod_sign>0 else '2n-1'} s_mod={mod_variant} scale64={scale}" | ||
| 259 | + rows.append((name, corr, lag, ratio, energy)) | ||
| 260 | + rows.sort(key=lambda r: -r[1]) | ||
| 261 | + for name, corr, lag, ratio, energy in rows: | ||
| 262 | + print(f" {name}: corr={corr:.6f} lag={lag} amp_ratio={ratio} energy_ratio={energy:.6f}") | ||
| 263 | + return rows | ||
| 264 | + | ||
| 265 | + | ||
| 266 | +def best_lag_corr(out, x_in, lag_max): | ||
| 267 | + """Same-rate (no decimation) lag search.""" | ||
| 268 | + best_corr, best_lag, best_ratio = -2.0, None, None | ||
| 269 | + for lag in range(0, lag_max): | ||
| 270 | + a = out[lag:] | ||
| 271 | + n = min(len(a), len(x_in)) - 10 | ||
| 272 | + if n < 4000: | ||
| 273 | + continue | ||
| 274 | + a, b = a[:n], x_in[:n] | ||
| 275 | + if np.std(a) < 1e-12: | ||
| 276 | + continue | ||
| 277 | + corr = np.corrcoef(a, b)[0, 1] | ||
| 278 | + if corr > best_corr: | ||
| 279 | + best_corr, best_lag, best_ratio = corr, lag, np.std(a) / np.std(b) | ||
| 280 | + return best_corr, best_lag, best_ratio | ||
| 281 | + | ||
| 282 | + | ||
| 283 | +def run_same_rate_64(n_slots=128): | ||
| 284 | + rng = np.random.default_rng(0) | ||
| 285 | + x_in = rng.standard_normal(64 * n_slots) | ||
| 286 | + ana = Analysis64(c) | ||
| 287 | + syn = Synthesis64(c, sign=1.0, use_re=True) | ||
| 288 | + out = np.zeros(64 * n_slots) | ||
| 289 | + for s in range(n_slots): | ||
| 290 | + X64 = ana.process_slot(x_in[64 * s : 64 * s + 64]) | ||
| 291 | + out[64 * s : 64 * s + 64] = syn.process_slot(X64) | ||
| 292 | + energy_ratio = np.sum(out**2) / np.sum(x_in**2) | ||
| 293 | + corr, lag, ratio = best_lag_corr(out, x_in, 900) | ||
| 294 | + print(f"(1) 64->64 same-family round-trip: corr={corr:.6f} lag={lag} amp_ratio={ratio} energy_ratio={energy_ratio:.6f}") | ||
| 295 | + return corr | ||
| 296 | + | ||
| 297 | + | ||
| 298 | +def run_same_rate_32(n_slots=256): | ||
| 299 | + rng = np.random.default_rng(0) | ||
| 300 | + x_in = rng.standard_normal(32 * n_slots) | ||
| 301 | + ana = Analysis32(c) | ||
| 302 | + syn = Synthesis32Downsampled(c) | ||
| 303 | + out = np.zeros(32 * n_slots) | ||
| 304 | + for s in range(n_slots): | ||
| 305 | + X32 = ana.process_slot(x_in[32 * s : 32 * s + 32], newest_at_zero=True, tap="c2n", sign=1.0) | ||
| 306 | + out[32 * s : 32 * s + 32] = syn.process_slot(X32) | ||
| 307 | + energy_ratio = np.sum(out**2) / np.sum(x_in**2) | ||
| 308 | + corr, lag, ratio = best_lag_corr(out, x_in, 700) | ||
| 309 | + print(f"(2) 32->32 same-family round-trip: corr={corr:.6f} lag={lag} amp_ratio={ratio} energy_ratio={energy_ratio:.6f}") | ||
| 310 | + return corr | ||
| 311 | + | ||
| 312 | + | ||
| 313 | +def run_single_band_impulse_spectrum(k_impulse=10): | ||
| 314 | + """(3)-fallback: single-band impulse at slot 0, k=k_impulse into | ||
| 315 | + Synthesis64; report where the output spectrum peaks land.""" | ||
| 316 | + syn = Synthesis64(c, sign=1.0, use_re=True) | ||
| 317 | + n_slots = 20 | ||
| 318 | + out = np.zeros(64 * n_slots) | ||
| 319 | + for s in range(n_slots): | ||
| 320 | + X64 = np.zeros(64, dtype=complex) | ||
| 321 | + if s == 0: | ||
| 322 | + X64[k_impulse] = 1.0 | ||
| 323 | + out[64 * s : 64 * s + 64] = syn.process_slot(X64) | ||
| 324 | + spec = np.fft.rfft(out) | ||
| 325 | + mags = np.abs(spec) | ||
| 326 | + top2 = np.argsort(mags)[-2:] | ||
| 327 | + freqs = np.fft.rfftfreq(len(out)) | ||
| 328 | + print(f"single-band impulse k={k_impulse}: top-2 bins {sorted(top2)} at normalized freq {sorted(freqs[top2])}") | ||
| 329 | + print(f" expected bin center (band k of 64, full band 0..0.5): {(k_impulse + 0.5) / 128.0:.5f}") | ||
| 330 | + | ||
| 331 | + | ||
| 332 | +if __name__ == "__main__": | ||
| 333 | + results = {} | ||
| 334 | + for newest_at_zero in (True, False): | ||
| 335 | + for tap in (None, "c2n"): | ||
| 336 | + for sign in (-1.0, 1.0): | ||
| 337 | + for syn_sign in (-1.0, 1.0): | ||
| 338 | + for syn_use_re in (True, False): | ||
| 339 | + name = ( | ||
| 340 | + f"newest0={newest_at_zero} tap={tap} asign={sign:+.0f} " | ||
| 341 | + f"ssign={syn_sign:+.0f} re_only={syn_use_re}" | ||
| 342 | + ) | ||
| 343 | + results[name] = run_trial( | ||
| 344 | + name, | ||
| 345 | + newest_at_zero=newest_at_zero, | ||
| 346 | + tap=tap, | ||
| 347 | + sign=sign, | ||
| 348 | + syn_sign=syn_sign, | ||
| 349 | + syn_use_re=syn_use_re, | ||
| 350 | + ) | ||
| 351 | + print() | ||
| 352 | + print("Trial table (sorted, 32->64 cross-family):") | ||
| 353 | + for k, v in sorted(results.items(), key=lambda kv: -kv[1]): | ||
| 354 | + print(f" {k}: corr={v:.6f}") | ||
| 355 | + | ||
| 356 | + print() | ||
| 357 | + print("Same-family bisection:") | ||
| 358 | + c1 = run_same_rate_64() | ||
| 359 | + c2 = run_same_rate_32() | ||
| 360 | + if c1 >= 0.999 and c2 >= 0.999: | ||
| 361 | + print("Both same-family round-trips pass -> the 32->64 cross-family pairing is the bug (see charter step 3).") | ||
| 362 | + if c1 < 0.999: | ||
| 363 | + run_single_band_impulse_spectrum(k_impulse=10) | ||
| 364 | + | ||
| 365 | + rows = bisect_t1_t2_t3() | ||
| 366 | + best_name, best_corr, best_lag, best_ratio, best_energy = rows[0] | ||
| 367 | + print() | ||
| 368 | + print(f"Best T1/T2/T3 configuration: {best_name} corr={best_corr:.6f} amp_ratio={best_ratio} energy_ratio={best_energy:.6f}") | ||
| 369 | + | ||
| 370 | + print() | ||
| 371 | + print("32-band-analysis -> confirmed-correct-64-band-synthesis cross-family, scale/conjugate probe:") | ||
| 372 | + for scale_k in (1.0, 2.0, 0.5, np.sqrt(2)): | ||
| 373 | + for conj in (False, True): | ||
| 374 | + rng = np.random.default_rng(0) | ||
| 375 | + n_slots = 160 | ||
| 376 | + x_in = rng.standard_normal(32 * n_slots) | ||
| 377 | + ana = Analysis32(c) | ||
| 378 | + syn = Synthesis64Param(c, shift_mode="reverse_newest_at_0", mod_variant="2n-255", scale=True) | ||
| 379 | + out = np.zeros(64 * n_slots) | ||
| 380 | + for s in range(n_slots): | ||
| 381 | + X32 = ana.process_slot(x_in[32 * s : 32 * s + 32], newest_at_zero=True, tap="c2n", sign=1.0) | ||
| 382 | + if conj: | ||
| 383 | + X32 = np.conj(X32) | ||
| 384 | + X64 = np.zeros(64, dtype=complex) | ||
| 385 | + X64[0:32] = X32 * scale_k | ||
| 386 | + out[64 * s : 64 * s + 64] = syn.process_slot(X64) | ||
| 387 | + energy = np.sum(out**2) / np.sum(x_in**2) | ||
| 388 | + corr, lag, ratio = best_lag_corr(out, x_in, 900) | ||
| 389 | + print(f" scale_k={scale_k:.4f} conj={conj}: corr={corr:.6f} lag={lag} amp_ratio={ratio} energy_ratio={energy:.6f}") | ||