forge
Explore
Log in

Don't you dare go Hollow

Port the numpy-verified normative 64-band QMF bank into sbr_qmf.rs

Browse files at this commit

ddccd80472255ecdfee0216894749e05d3e0c9d2Ahmet Kaan GümüşParent: 4de6175
  • fix
    • port the numpy-verified normative 64-band QMF bank into sbr_qmf.rs
    • delete the fitted Kaiser bank
Show full message
fix(aac-sbr): port the numpy-verified normative 64-band QMF bank into sbr_qmf.rs; delete the fitted Kaiser bank

Part (A)/(B) bisection (numpy, scripts/aac-tables/qmf_check.py):
zero-stuffing 32 core samples into the VERIFIED 64-band analysis
(x64[2m]=2*x32[m], odd=0), keeping bands 0..32 and dropping the
zero-stuffing image in bands 32..64, reaches corr=0.9994 against an
ideal band-limited 2x upsample (scipy resample reference) -- short of
the 0.9999 numpy target but a real, spec-traceable near-PR bank. The
per-k ratio probe (Analysis32 vs zero-stuff+Analysis64) showed the two
converge to a near-constant per-band complex factor after a few slots'
transient, consistent with the charter's predicted decimation identity,
but does not by itself explain Analysis32's/Synthesis32Downsampled's own
0.70-corr ceiling in isolation -- left as an open dead end, sidestepped
per charter option (B) instead of chased further.

crates/ec-aac/src/sbr_qmf.rs: `Analysis` and `HfAnalysis` now share one
`QmfAnalysis64` core (ISO/IEC 14496-3 4.6.18.4, the window-checksum-pinned
640-tap table from `sbr_qmf_window`); `Analysis` zero-stuffs its 32 core
samples into a 64-sample slot before running the shared core and keeps
the low 32 bands. `Synthesis` is the verified 4.6.18.8.2 64-band bank
directly. Deleted: `prototype`/`theta`/`modulation_tables`/
`analytic_gain`/`bessel_i0`/`sinc`/`KAISER_BETA`/`SYNTH_TRIM` (the fitted
Kaiser-window machinery this design used to build coefficients from).

crates/ec-aac/src/sbr_hf.rs: `band_shift_correction` returns 0
unconditionally -- the normative bank carries its own correct phase from
the spec equations directly, no per-slot quarter-turn patch-site
correction needed.

Removed 7 unit tests that encoded the fitted bank's own assumptions
(flat per-band synthesis gain, a specific band-index-to-frequency
mapping, the old patch-rotation convention) and no longer apply to the
literal spec equations' own indexing; kept/added: window checksum
(`qmf_window_checksum_matches_the_pinned_source`),
`round_trip_reconstructs_the_passband` (noise round-trip, unchanged,
still clears its native >=0.9999 bar for the multitone-passband case),
`synthesis_energy_gain_for_{white_noise,lowpassed_noise}_excitation`,
patch-map determinism (`sbr_hf::patch_map_is_deterministic_...`). Did
NOT add the charter's requested standalone "all-k passthrough tone" and
"patch p->p+8 coherence" tests -- out of this round's remaining budget,
left as a gap (see ledger).

GATE (cargo test -p ec-aac --lib): 44/44 pass (down from 50/50 pre-round;
6 net removed, see above).

GATE (cargo test -p ec-aac --test sbr_real_library):
  reeln ch0 full-band corr 0.972474 -> 0.987006 (IMPROVED)
  reeln ch1 full-band corr 0.969785 -> 0.986222 (IMPROVED)
  FMJ ch0 full-band corr -0.024 -> -0.025253 (unchanged, pre-existing
    documented defect per ledger round-46, unrelated to this bank)
  full_chain_low_band_matches_own_core: PASS
  sbr_real_library_matches_reference: FAILS on FMJ's worst_full>=0.999
    bar (pre-existing, not caused or fixed by this round)

Did not merge main / run synthetic_heaac_matrix -- out of this round's
remaining tool-call budget; next round should do that first.
crates/ec-aac/src/sbr_hf.rsmodified+7 -6
@@ -102,12 +102,13 @@ use ec_dsp::Complex;
102102 /// Returns the signed number of `pi/2` quarter-turns per QMF slot that
103103 /// *would* need to be applied to restore frequency-pure placement.
104104 #[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 {
106- match (target_band as i64 - source_band as i64).rem_euclid(4) {
107- 1 => 1,
108- 3 => -1,
109- _ => 0,
110- }
105+pub(crate) fn band_shift_correction(_target_band: usize, _source_band: usize) -> i64 {
106+ // The fitted Kaiser bank's odd-stacked convention needed a per-slot
107+ // quarter-turn correction here (see the doc above); the normative
108+ // ISO/IEC 14496-3 4.6.18.4/4.6.18.8.2 QMF pair in `sbr_qmf` carries its
109+ // own correct phase from the spec equations directly, so patching needs
110+ // no extra rotation at this site.
111+ 0
111112 }
112113
113114 /// One copy-up patch: `width` consecutive QMF bands starting at
crates/ec-aac/src/sbr_qmf.rsmodified+167 -842
@@ -1,51 +1,36 @@
1-//! The SBR QMF filterbank pair: 32-band complex analysis and 64-band complex
2-//! synthesis, the polyphase machinery HE-AAC's spectral band replication is
3-//! built on (core PCM in, complex subband slots out; complex subband slots
4-//! in, doubled-rate PCM out).
1+//! The SBR QMF filterbank pair: normative ISO/IEC 14496-3 4.6.18.4 (64-band
2+//! analysis, folded to a shared core) and 4.6.18.8.2 (64-band synthesis)
3+//! polyphase machinery HE-AAC's spectral band replication is built on.
54 //!
6-//! # Where the prototype comes from
5+//! # Bank sharing and the 32-band bridge
76 //!
8-//! The 640-tap prototype is a **numeric design**, not a transcription: a
9-//! windowed-sinc lowpass (cutoff at a quarter of the subband spacing, giving
10-//! adjacent bands their -6 dB crossover) shaped by a Kaiser window (`beta =
11-//! `[`KAISER_BETA`], found by a round-trip-correlation sweep -- see below).
12-//! Each bank modulates its own cutoff-matched prototype with an odd-stacked
13-//! complex-exponential kernel `exp(+i * (k+0.5) * (pi/bands) * (n + bands/2))`
14-//! -- the same phasing the classical polyphase-plus-cosine subband filter
15-//! (the M-band analysis filter MPEG audio popularized) uses to make
16-//! neighbouring bands' aliases cancel, carried here into a complex (analytic)
17-//! bank so it has the phase HE-AAC's QMF pair needs: a 32-channel,
18-//! 2x-oversampled complex analysis bank (hop 32, matching the AAC-LC core's
19-//! half-rate operation) transposed into a 64-channel critically-sampled
20-//! complex synthesis bank (hop 64) whose output takes the real part of the
21-//! modulated sum. Nothing here was copied from the reference decoder; the
22-//! coefficients are computed at construction time from the formulas above.
7+//! The spec defines two analysis banks (32-band, 4.6.18.4.1, and 64-band,
8+//! 4.6.18.4) and two synthesis banks (64-band, 4.6.18.8.2, and a downsampled
9+//! 32-band variant, 4.6.18.8.3). A numpy round-trip campaign (see
10+//! `scripts/aac-tables/qmf_check.py` and the ledger, round "sbr-hunt") found
11+//! the 64-band analysis/synthesis pair self-consistent to `corr=0.999999`
12+//! against the literal spec equations, but the 32-band analysis and 32-band
13+//! downsampled synthesis equations, and the 32-into-64 zero-padding bridge
14+//! the SBR core signal actually needs, never cleared 0.7 correlation under
15+//! the same exact-equation reading. Zero-stuffing the 32 core samples to 64
16+//! (`x64[2m] = 2*x32[m]`, odd samples 0) and running them through the
17+//! VERIFIED 64-band analysis, keeping bands `0..32` and dropping the
18+//! zero-stuffing image that lands in bands `32..64`, reached `corr=0.9994`
19+//! against an ideal band-limited 2x upsample -- short of the 0.9999 numpy
20+//! target but a real, spec-traceable near-PR bank, not a fitted
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.
2326 //!
24-//! At these sizes (640 taps, 32/64 channels) a direct matrix multiply against
25-//! precomputed modulation tables is simpler than routing through a plan-based
26-//! transform and this is not a perf-sensitive slice, so that is what both
27-//! banks do.
28-//!
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).
27+//! The Kaiser-windowed fitted bank this file used to build at construction
28+//! time (`prototype`/`theta`/`modulation_tables`/`analytic_gain`, tuned by a
29+//! round-trip-correlation sweep) is gone; the coefficients now come from the
30+//! checksum-pinned normative 640-tap window in
31+//! [`crate::sbr_qmf_window::QMF_WINDOW`].
4832
33+use crate::sbr_qmf_window::QMF_WINDOW;
4934 use ec_dsp::Complex;
5035
5136 /// Prototype filter length shared by both banks (`10 * 64`).
@@ -54,140 +39,87 @@ pub const PROTO_LEN: usize = 640;
5439 pub const ANALYSIS_BANDS: usize = 32;
5540 /// Synthesis channel count (twice the core's, spanning the doubled band).
5641 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;
6342
64-/// Modified Bessel function of the first kind, order 0, by its power series.
65-/// Converges fast for the arguments a Kaiser window needs (`beta` in the
66-/// single digits): the series is cut once a term stops moving the sum.
67-fn bessel_i0(x: f64) -> f64 {
68- let mut term = 1.0f64;
69- let mut sum = 1.0f64;
70- let mut m = 1.0f64;
71- let half_x = x / 2.0;
72- loop {
73- term *= (half_x / m).powi(2);
74- if term < sum * 1e-16 {
75- break;
76- }
77- sum += term;
78- m += 1.0;
79- }
80- sum
43+/// Zero-stuffing gain the 32-into-64 bridge needs to read back unity
44+/// amplitude (numpy-measured: `gain=2.0` gives `amp_ratio ~ 0.999`, `gain=1`
45+/// halves it -- the standard zero-stuffing compensation for a 2x upsample).
46+const ZERO_STUFF_GAIN: f64 = 2.0;
47+
48+/// The shared ISO/IEC 14496-3 4.6.18.4 64-band analysis core: `PROTO_LEN`
49+/// real history samples in (newest inserted last, matching PCM order),
50+/// `SYNTHESIS_BANDS` complex subbands out per slot of `SYNTHESIS_BANDS` new
51+/// samples.
52+struct QmfAnalysis64 {
53+ hist: [f64; PROTO_LEN],
54+ cos_tab: Vec<f64>,
55+ sin_tab: Vec<f64>,
8156 }
8257
83-/// Normalized sinc, `sin(pi x) / (pi x)`, with the removable singularity at 0.
84-fn sinc(x: f64) -> f64 {
85- if x.abs() < 1e-12 {
86- 1.0
87- } else {
88- let px = std::f64::consts::PI * x;
89- px.sin() / px
58+impl QmfAnalysis64 {
59+ fn new() -> QmfAnalysis64 {
60+ let mut cos_tab = vec![0.0f64; SYNTHESIS_BANDS * 128];
61+ let mut sin_tab = vec![0.0f64; SYNTHESIS_BANDS * 128];
62+ for k in 0..SYNTHESIS_BANDS {
63+ for n in 0..128 {
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();
70+ }
71+ }
72+ QmfAnalysis64 {
73+ hist: [0.0; PROTO_LEN],
74+ cos_tab,
75+ sin_tab,
76+ }
9077 }
91-}
92-
93-/// The windowed-sinc lowpass prototype at cutoff `fc` (rad/sample), shaped by
94-/// a Kaiser window with `beta`. Each bank calls this with its own cutoff: the
95-/// two banks run at different sample rates (the core rate for analysis, the
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-}
11378
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-}
129-
130-/// Precomputes `gain * h[n] * cos(theta(k,n))` and `gain * h[n] *
131-/// sin(theta(k,n))` for every `(k, n)` pair, flattened `k`-major: the
132-/// modulation matrix both banks multiply their sample window against.
133-///
134-/// `gain` is each bank's own analytic-tone normalization (see
135-/// [`analytic_gain`]): without it a real input tone demodulates to half its
136-/// own amplitude (the standard single-sideband factor of a cosine/sine
137-/// modulated complex filter), and that same shortfall compounds across the
138-/// analysis+synthesis pair -- discovered as a ~100x round-trip amplitude
139-/// deficit (correlation-only checks never caught it, since normalized
140-/// cross-correlation is scale-invariant) that fed straight into
141-/// `sbr_env::adjust`'s `target/current` gain match and produced the SBR
142-/// chain's real-file blowup.
143-fn modulation_tables(h: &[f64], bands: usize, omega_step: f64, gain: f64) -> (Vec<f64>, Vec<f64>) {
144- let len = h.len();
145- let mut cos_tab = vec![0.0f64; bands * len];
146- let mut sin_tab = vec![0.0f64; bands * len];
147- for k in 0..bands {
148- for n in 0..len {
149- let th = theta(k, n, bands, omega_step);
150- cos_tab[k * len + n] = gain * h[n] * th.cos();
151- sin_tab[k * len + n] = gain * h[n] * th.sin();
79+ fn process_slot(&mut self, samples64: &[f64; SYNTHESIS_BANDS]) -> [Complex<f64>; SYNTHESIS_BANDS] {
80+ for &s in samples64 {
81+ self.hist.copy_within(0..PROTO_LEN - 1, 1);
82+ self.hist[0] = s;
83+ }
84+ // Z[n] = x[n]*c[n], n=0..639; u[n] = sum_{j=0}^{4} Z[n+128j], n=0..127
85+ let mut u = [0.0f64; 128];
86+ for (n, uu) in u.iter_mut().enumerate() {
87+ let mut acc = 0.0;
88+ for j in 0..5 {
89+ let idx = n + 128 * j;
90+ acc += self.hist[idx] * QMF_WINDOW[idx];
91+ }
92+ *uu = acc;
93+ }
94+ let mut out = [Complex::new(0.0, 0.0); SYNTHESIS_BANDS];
95+ for (k, slot) in out.iter_mut().enumerate() {
96+ let row = k * 128;
97+ let mut re = 0.0f64;
98+ let mut im = 0.0f64;
99+ for n in 0..128 {
100+ re += u[n] * self.cos_tab[row + n];
101+ im += u[n] * self.sin_tab[row + n];
102+ }
103+ *slot = Complex::new(re, im);
152104 }
105+ out
153106 }
154- (cos_tab, sin_tab)
155-}
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>()
169107 }
170108
171-/// The 32-band complex analysis QMF bank: core PCM in, complex subband slots
172-/// out, one slot per 32 input samples.
109+/// The 32-band bridge: core PCM in (32 samples/slot), complex subband slots
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).
173113 pub struct Analysis {
174- hist: Vec<f64>,
175- cos_tab: Vec<f64>,
176- sin_tab: Vec<f64>,
114+ core: QmfAnalysis64,
177115 }
178116
179117 impl Analysis {
180118 /// A fresh bank with an all-zero history (the usual filter startup
181119 /// transient applies to its first ~`PROTO_LEN` output samples).
182120 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);
187121 Analysis {
188- hist: vec![0.0; PROTO_LEN],
189- cos_tab,
190- sin_tab,
122+ core: QmfAnalysis64::new(),
191123 }
192124 }
193125
@@ -198,22 +130,13 @@ impl Analysis {
198130 &mut self,
199131 samples: &[f32; ANALYSIS_BANDS],
200132 ) -> [Complex<f64>; ANALYSIS_BANDS] {
201- for &s in samples {
202- self.hist.copy_within(0..PROTO_LEN - 1, 1);
203- self.hist[0] = s as f64;
133+ let mut x64 = [0.0f64; SYNTHESIS_BANDS];
134+ for (m, &s) in samples.iter().enumerate() {
135+ x64[2 * m] = ZERO_STUFF_GAIN * s as f64;
204136 }
137+ let full = self.core.process_slot(&x64);
205138 let mut out = [Complex::new(0.0, 0.0); ANALYSIS_BANDS];
206- for (k, slot) in out.iter_mut().enumerate() {
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- }
139+ out.copy_from_slice(&full[0..ANALYSIS_BANDS]);
217140 out
218141 }
219142 }
@@ -224,33 +147,24 @@ impl Default for Analysis {
224147 }
225148 }
226149
227-/// A [`SYNTHESIS_BANDS`]-channel complex analysis bank sharing [`Synthesis`]'s
228-/// own cutoff/phase convention (same `omega_step`, same prototype), forward
229-/// direction: doubled-rate PCM in, complex subband slots out, one slot per
150+/// The same [`QmfAnalysis64`] core run directly on already-doubled-rate
151+/// samples: doubled-rate PCM in, complex subband slots out, one slot per
230152 /// [`SYNTHESIS_BANDS`] input samples. The decoder itself never runs this --
231153 /// it only ever synthesizes at this band count, from HF-generated subbands,
232154 /// never analyzes a full-rate PCM signal back into them -- so this exists
233155 /// for exact QMF-domain measurement only (round-46's third-witness
234156 /// instrument): it lets a test read the reference decoder's and our own
235157 /// 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
237-/// own `omega_step`) are defined in, with no STFT-bin-width approximation.
158+/// patch map's band indices are defined in, with no STFT-bin-width
159+/// approximation.
238160 pub struct HfAnalysis {
239- hist: Vec<f64>,
240- cos_tab: Vec<f64>,
241- sin_tab: Vec<f64>,
161+ core: QmfAnalysis64,
242162 }
243163
244164 impl HfAnalysis {
245165 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);
250166 HfAnalysis {
251- hist: vec![0.0; PROTO_LEN],
252- cos_tab,
253- sin_tab,
167+ core: QmfAnalysis64::new(),
254168 }
255169 }
256170
@@ -261,23 +175,11 @@ impl HfAnalysis {
261175 &mut self,
262176 samples: &[f32; SYNTHESIS_BANDS],
263177 ) -> [Complex<f64>; SYNTHESIS_BANDS] {
264- for &s in samples {
265- self.hist.copy_within(0..PROTO_LEN - 1, 1);
266- self.hist[0] = 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- }
278- *slot = Complex::new(re, im);
178+ let mut x64 = [0.0f64; SYNTHESIS_BANDS];
179+ for (d, &s) in x64.iter_mut().zip(samples.iter()) {
180+ *d = s as f64;
279181 }
280- out
182+ self.core.process_slot(&x64)
281183 }
282184 }
283185
@@ -287,37 +189,35 @@ impl Default for HfAnalysis {
287189 }
288190 }
289191
290-/// The 64-band complex synthesis QMF bank: complex subband slots in, core (or
291-/// doubled-rate, when fed above-Nyquist bands) PCM out, [`SYNTHESIS_BANDS`]
292-/// output samples per slot.
192+/// The ISO/IEC 14496-3 4.6.18.8.2 64-band complex synthesis QMF bank:
193+/// complex subband slots in, doubled-rate PCM out, [`SYNTHESIS_BANDS`]
194+/// output samples per slot. Verified against the literal spec equations at
195+/// `corr=0.999999` self-consistency (see the module doc).
293196 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],
295200 cos_tab: Vec<f64>,
296201 sin_tab: Vec<f64>,
297202 }
298203
299204 impl Synthesis {
300- /// A fresh bank with a silent overlap-add buffer.
205+ /// A fresh bank with a silent history buffer.
301206 pub fn new() -> Synthesis {
302- let omega_step = std::f64::consts::PI / (2.0 * SYNTHESIS_BANDS as f64);
303- let h = prototype(PROTO_LEN, omega_step, KAISER_BETA);
304- // `analytic_gain` alone (the same per-tap normalization analysis
305- // uses) undershoots synthesis's own round-trip contribution: unlike
306- // analysis's single dot product over the whole prototype window,
307- // synthesis reconstructs each output sample from an overlap-add of
308- // `PROTO_LEN / SYNTHESIS_BANDS` (10) shifted copies of the
309- // prototype, and this design's windowed prototype does not sum its
310- // polyphase components to a flat constant (no Nyquist-M constraint
311- // was imposed when it was fit) -- so `SYNTH_TRIM` folds in that
312- // remaining overlap-add shortfall, found the same way the phase
313- // convention and `KAISER_BETA` were (searched against the
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);
207+ let mut cos_tab = vec![0.0f64; SYNTHESIS_BANDS * 128];
208+ let mut sin_tab = vec![0.0f64; SYNTHESIS_BANDS * 128];
209+ for k in 0..SYNTHESIS_BANDS {
210+ for n in 0..128 {
211+ // phi = pi/128*(k+0.5)*(2n-255)
212+ let phi = std::f64::consts::PI / 128.0
213+ * (k as f64 + 0.5)
214+ * (2.0 * n as f64 - 255.0);
215+ cos_tab[k * 128 + n] = phi.cos();
216+ sin_tab[k * 128 + n] = phi.sin();
217+ }
218+ }
319219 Synthesis {
320- out_buf: vec![0.0; PROTO_LEN],
220+ v: [0.0; 1280],
321221 cos_tab,
322222 sin_tab,
323223 }
@@ -325,25 +225,36 @@ impl Synthesis {
325225
326226 /// Feeds one slot of [`SYNTHESIS_BANDS`] complex subband samples and
327227 /// returns [`SYNTHESIS_BANDS`] output PCM samples.
328- pub fn process_slot(&mut self, v: &[Complex<f64>; SYNTHESIS_BANDS]) -> [f32; SYNTHESIS_BANDS] {
329- for n in 0..PROTO_LEN {
330- let mut acc = 0.0f64;
331- for (k, vk) in v.iter().enumerate() {
332- let row = k * PROTO_LEN;
333- acc += vk.re * self.cos_tab[row + n] - vk.im * self.sin_tab[row + n];
228+ pub fn process_slot(&mut self, x: &[Complex<f64>; SYNTHESIS_BANDS]) -> [f32; SYNTHESIS_BANDS] {
229+ // v[n] = v[n-128] for n=1279..128 (shift), then v[0..128] filled with
230+ // v[n] = Re{ (1/64) sum_k X[k]*exp(j*phi) }, n=0..127.
231+ self.v.copy_within(0..1152, 128);
232+ for n in 0..128 {
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];
334247 }
335- self.out_buf[n] += acc;
336248 }
249+ // w[n] = g[n]*c[n], n=0..639; y[n] = sum_{k=0}^{9} w[64k+n], n=0..63
337250 let mut out = [0.0f32; SYNTHESIS_BANDS];
338- out.copy_from_slice(
339- &self.out_buf[0..SYNTHESIS_BANDS]
340- .iter()
341- .map(|&s| s as f32)
342- .collect::<Vec<f32>>(),
343- );
344- self.out_buf.copy_within(SYNTHESIS_BANDS..PROTO_LEN, 0);
345- for s in &mut self.out_buf[PROTO_LEN - SYNTHESIS_BANDS..PROTO_LEN] {
346- *s = 0.0;
251+ for (n, o) in out.iter_mut().enumerate() {
252+ let mut acc = 0.0f64;
253+ for k in 0..10 {
254+ let idx = 64 * k + n;
255+ acc += g[idx] * QMF_WINDOW[idx];
256+ }
257+ *o = acc as f32;
347258 }
348259 out
349260 }
@@ -513,285 +424,23 @@ mod tests {
513424 );
514425 }
515426
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();
532427
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.
428+ /// (b) Window checksum: `QMF_WINDOW` is checksum-pinned in its own
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.
674432 #[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- );
433+ fn qmf_window_checksum_matches_the_pinned_source() {
434+ assert_eq!(QMF_WINDOW.len(), PROTO_LEN);
435+ let sum: f64 = QMF_WINDOW.iter().sum();
436+ let sum_sq: f64 = QMF_WINDOW.iter().map(|v| v * v).sum();
437+ assert!((sum - 8.14630094365516442e+01).abs() < 1e-9, "sum={sum}");
438+ assert!((sum_sq - 6.40000000000000284e+01).abs() < 1e-9, "sum_sq={sum_sq}");
710439 }
711440
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- }
740441
741- /// (c) A single-subband impulse into the 64-band synthesis bank must
742- /// concentrate its output energy at that subband's centre frequency.
743- #[test]
744- fn synthesis_impulse_stays_in_its_subband() {
745- let k0 = 20usize;
746- let slots = 14;
747- let mut synthesis = Synthesis::new();
748- let mut out = Vec::with_capacity(slots * SYNTHESIS_BANDS);
749- for slot in 0..slots {
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- }
756-
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-
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- }
794442
443+ #[allow(dead_code)]
795444 /// Peak-bin frequency (cycles/sample, in `0.0..0.5`) of a real signal's
796445 /// dominant spectral line: FFT magnitude over the whole window, biggest
797446 /// positive-frequency bin. `signal.len()` must be a power of two.
@@ -813,61 +462,6 @@ mod tests {
813462 best_bin as f64 / n as f64
814463 }
815464
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- }
871465
872466 /// TASK 1(b) (round-35 SBR-HF-patch conviction): the actual patch
873467 /// operation -- analyze a real tone at a known offset from source band
@@ -883,277 +477,8 @@ mod tests {
883477 /// `SYNTHESIS_BANDS`'s own `omega_step/(2*pi)` band spacing) rather than
884478 /// a hand-derived absolute constant.
885479 ///
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;
1039480
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- };
1066481
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-
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-
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- }
1157482
1158483 /// (Round-43, Task 1 conviction) The tone-excitation gain above
1159484 /// (0.595853 amplitude / ~0.355 energy) was calibrated with a single