forge
Explore
Log in

Don't you dare go Hollow

QMF-domain exact third witness for SBR HF content (round-46)

Browse files at this commit

be3ee94494bca1ebc2e944c8e45adac68d5fcde0Ahmet Kaan GümüşParent: 1117d7a
  • test
    • QMF-domain exact third witness for SBR HF content (round-46)
Show full message
test(aac): QMF-domain exact third witness for SBR HF content (round-46)

Adds HfAnalysis (a 64-band forward analysis bank sharing Synthesis's own
convention) plus a validated self-consistency control, and rebuilds the
STFT-approximate patch-copy simulator (round-45) in this exact band grid
(EC_AAC_SBR_QMF_WITNESS) with a per-band 2nd-order complex transfer fit
between the plain-copy sim and the reference's real HF content
(hf_patch_transfer_fit) plus a bw-value dump (EC_AAC_SBR_BW_DUMP) for
comparison against our own chirp coefficients.

On reeln, the exact-domain witness overturns round-45's STFT-based
lead: for patch (3,28,11) sim-vs-reference clears 0.5 on most bands
(0.42-0.79) while sim-vs-ours stays well under it (0.26-0.42) -- the
opposite polarity from the STFT approximation's hint. The fitted
sim-to-reference transfer on that same patch shows non-trivial order-2
structure with a phase signature (~i, ~-1, ~-i across taps 0/1/2) matching
this file's own already-characterized (and currently disabled)
band_shift_correction quarter-turn convention -- flagged in the ledger as
the next concrete thing to re-test with this sharper instrument, not
implemented here (round-37's contrary real-file evidence used a
scale-trap-prone 8-bin STFT metric this round's own control work found
unreliable; re-enabling a previously-reverted correction needs its own
verification budget).
crates/ec-aac/src/lib.rsmodified+1 -1
@@ -35,7 +35,7 @@ mod sbr_chain;
35 mod sbr_env;35 mod sbr_env;
36 mod sbr_hf;36 mod sbr_hf;
37 mod sbr_payload;37 mod sbr_payload;
38-mod sbr_qmf;38+pub mod sbr_qmf;
39 mod sbr_tables;39 mod sbr_tables;
40 pub mod tables;40 pub mod tables;
41 41
crates/ec-aac/src/sbr_hf.rsmodified+7 -0
@@ -400,6 +400,13 @@ pub fn generate(
400 stabilize(lpc2(&ext))400 stabilize(lpc2(&ext))
401 };401 };
402 let g = bw[noise_band_of(target_band)];402 let g = bw[noise_band_of(target_band)];
403+ // (Round-46, Task 2) `EC_AAC_SBR_BW_DUMP` -- one line per patched
404+ // band per frame with the smoothed chirp bw actually applied,
405+ // to compare against the QMF-domain fitted reference transfer
406+ // (`hf_patch_transfer_fit` in the real-file test).
407+ if std::env::var("EC_AAC_SBR_BW_DUMP").is_ok() {
408+ eprintln!("BW_DUMP target_band={target_band} source_band={source_band} bw={g:.6}");
409+ }
403 let ca1 = a1.scale(g);410 let ca1 = a1.scale(g);
404 let ca2 = a2.scale(g * g);411 let ca2 = a2.scale(g * g);
405 let (mut y_prev1, mut y_prev2) = if source_band < history.y.len() {412 let (mut y_prev1, mut y_prev2) = if source_band < history.y.len() {
crates/ec-aac/src/sbr_qmf.rsmodified+218 -0
@@ -224,6 +224,69 @@ impl Default for Analysis {
224 }224 }
225 }225 }
226 226
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
230+/// [`SYNTHESIS_BANDS`] input samples. The decoder itself never runs this --
231+/// 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
233+/// 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
235+/// 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.
238+pub struct HfAnalysis {
239+ hist: Vec<f64>,
240+ cos_tab: Vec<f64>,
241+ sin_tab: Vec<f64>,
242+}
243+
244+impl HfAnalysis {
245+ 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 {
251+ hist: vec![0.0; PROTO_LEN],
252+ cos_tab,
253+ sin_tab,
254+ }
255+ }
256+
257+ /// Feeds exactly [`SYNTHESIS_BANDS`] new samples (oldest first, matching
258+ /// PCM order) and returns the [`SYNTHESIS_BANDS`] complex subband
259+ /// samples for this slot.
260+ pub fn process_slot(
261+ &mut self,
262+ samples: &[f32; SYNTHESIS_BANDS],
263+ ) -> [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);
279+ }
280+ out
281+ }
282+}
283+
284+impl Default for HfAnalysis {
285+ fn default() -> HfAnalysis {
286+ HfAnalysis::new()
287+ }
288+}
289+
227 /// The 64-band complex synthesis QMF bank: complex subband slots in, core (or290 /// The 64-band complex synthesis QMF bank: complex subband slots in, core (or
228 /// doubled-rate, when fed above-Nyquist bands) PCM out, [`SYNTHESIS_BANDS`]291 /// doubled-rate, when fed above-Nyquist bands) PCM out, [`SYNTHESIS_BANDS`]
229 /// output samples per slot.292 /// output samples per slot.
@@ -450,6 +513,161 @@ mod tests {
450 );513 );
451 }514 }
452 515
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+
453 /// (b) Prototype sanity: the lowpass crosses -6 dB at its cutoff (the671 /// (b) Prototype sanity: the lowpass crosses -6 dB at its cutoff (the
454 /// adjacent-band handoff point for a cosine-modulated bank) and is well672 /// adjacent-band handoff point for a cosine-modulated bank) and is well
455 /// attenuated a full subband away, within stated bounds.673 /// attenuated a full subband away, within stated bounds.
crates/ec-aac/tests/sbr_real_library.rsmodified+273 -0
@@ -1276,6 +1276,229 @@ fn hf_patch_simulator(o: &[f32], t: &[f32], rate: u32) -> (BandCoherenceTable, B
1276 (band_coherence(&t_spec), band_coherence(&o_spec))1276 (band_coherence(&t_spec), band_coherence(&o_spec))
1277 }1277 }
1278 1278
1279+/// (Round-46) The QMF-domain exact version of [`hf_patch_simulator`]: same
1280+/// plain-patch+gain model, same verified patch map, but read through the
1281+/// crate's own [`ec_aac::sbr_qmf::HfAnalysis`] (64-band, `rate/128`-wide
1282+/// bands -- exactly the patch map's own band unit) instead of an 8-bin-wide
1283+/// STFT approximation, closing the "too crude to reach a verdict" gap
1284+/// round-45's STFT simulator hit. Validated by
1285+/// `hf_analysis_self_consistency_control` in `sbr_qmf.rs` before use here
1286+/// (own-band plurality + self-coherence + round-trip control). Same
1287+/// per-(band, window) energy-rescale-then-coherence method as the STFT
1288+/// version, windowed over `WIN` consecutive QMF slots (`WIN * SYNTHESIS_BANDS
1289+/// = 1024` samples, matching the STFT version's hop) so the rescale has
1290+/// enough samples to estimate energy from, not so many that within-window
1291+/// phase drift is averaged away.
1292+const QMF_PATCHES: [(usize, usize, usize); 4] = [(0, 14, 14), (3, 28, 11), (0, 39, 3), (13, 42, 1)];
1293+
1294+/// Shared build step for the QMF-domain third-witness instruments: both
1295+/// PCMs read through [`ec_aac::sbr_qmf::HfAnalysis`], plus the plain
1296+/// patch-copy simulation of the reference's own low band, all in the
1297+/// `(band, slot)` domain. Returns `(ours, reference, sim)`.
1298+/// `[band][slot]` complex QMF-domain series.
1299+type QmfBandSlots = Vec<Vec<ec_dsp::Complex<f64>>>;
1300+
1301+fn qmf_domain_spec(o: &[f32], t: &[f32]) -> (QmfBandSlots, QmfBandSlots, QmfBandSlots) {
1302+ use ec_aac::sbr_qmf::{HfAnalysis, SYNTHESIS_BANDS};
1303+ let n = o.len().min(t.len());
1304+ let slots = n / SYNTHESIS_BANDS;
1305+ let analyze = |pcm: &[f32]| -> QmfBandSlots {
1306+ let mut ana = HfAnalysis::new();
1307+ let mut out: QmfBandSlots = (0..SYNTHESIS_BANDS)
1308+ .map(|_| Vec::with_capacity(slots))
1309+ .collect();
1310+ for s in 0..slots {
1311+ let mut chunk = [0.0f32; SYNTHESIS_BANDS];
1312+ chunk.copy_from_slice(&pcm[s * SYNTHESIS_BANDS..(s + 1) * SYNTHESIS_BANDS]);
1313+ let sub = ana.process_slot(&chunk);
1314+ for (b, c) in sub.iter().enumerate() {
1315+ out[b].push(*c);
1316+ }
1317+ }
1318+ out
1319+ };
1320+ let o_spec = analyze(o);
1321+ let t_spec = analyze(t);
1322+ // Plain patch copy: sim's target-band slot series is the reference's
1323+ // source-band slot series, unmodified.
1324+ let mut sim_spec = vec![vec![ec_dsp::Complex::new(0.0f64, 0.0); slots]; SYNTHESIS_BANDS];
1325+ for (src, tgt, width) in QMF_PATCHES {
1326+ for i in 0..width {
1327+ if src + i >= SYNTHESIS_BANDS || tgt + i >= SYNTHESIS_BANDS {
1328+ continue;
1329+ }
1330+ sim_spec[tgt + i] = t_spec[src + i].clone();
1331+ }
1332+ }
1333+ (o_spec, t_spec, sim_spec)
1334+}
1335+
1336+fn hf_patch_simulator_qmf(o: &[f32], t: &[f32]) -> (BandCoherenceTable, BandCoherenceTable) {
1337+ use ec_aac::sbr_qmf::SYNTHESIS_BANDS;
1338+ const WIN: usize = 16;
1339+ let (o_spec, t_spec, sim_spec) = qmf_domain_spec(o, t);
1340+ let slots = sim_spec.first().map(Vec::len).unwrap_or(0);
1341+ if slots < WIN {
1342+ return (Vec::new(), Vec::new());
1343+ }
1344+ let top_band = 43.min(SYNTHESIS_BANDS);
1345+ let windows = slots / WIN;
1346+ let band_coherence = |target: &[Vec<ec_dsp::Complex<f64>>]| -> Vec<(usize, f64)> {
1347+ (14..top_band)
1348+ .map(|band| {
1349+ let mut cross_re = 0.0f64;
1350+ let mut cross_im = 0.0f64;
1351+ let mut sim_e = 0.0f64;
1352+ let mut tgt_e = 0.0f64;
1353+ for w in 0..windows {
1354+ let lo = w * WIN;
1355+ let hi = lo + WIN;
1356+ let se: f64 = sim_spec[band][lo..hi]
1357+ .iter()
1358+ .map(|c| c.re * c.re + c.im * c.im)
1359+ .sum();
1360+ let te: f64 = target[band][lo..hi]
1361+ .iter()
1362+ .map(|c| c.re * c.re + c.im * c.im)
1363+ .sum();
1364+ if se <= 1e-20 || te <= 0.0 {
1365+ continue;
1366+ }
1367+ let scale = (te / se).sqrt();
1368+ for i in lo..hi {
1369+ let sc = sim_spec[band][i].scale(scale);
1370+ let tc = target[band][i];
1371+ let cross = sc * tc.conj();
1372+ cross_re += cross.re;
1373+ cross_im += cross.im;
1374+ sim_e += sc.re * sc.re + sc.im * sc.im;
1375+ tgt_e += tc.re * tc.re + tc.im * tc.im;
1376+ }
1377+ }
1378+ let den = (sim_e * tgt_e).sqrt();
1379+ let coh = if den > 0.0 {
1380+ (cross_re * cross_re + cross_im * cross_im).sqrt() / den
1381+ } else {
1382+ 0.0
1383+ };
1384+ (band, coh)
1385+ })
1386+ .collect()
1387+ };
1388+ (band_coherence(&t_spec), band_coherence(&o_spec))
1389+}
1390+
1391+/// (Round-46, Task 2) Per-band 2nd-order complex prediction transfer fit
1392+/// between the plain-copy sim series and the REFERENCE's own HF series for
1393+/// that band: `ref[l] ~= a0*sim[l] + a1*sim[l-1] + a2*sim[l-2]`, least
1394+/// squares over the whole file -- the same shape `sbr_hf::generate`'s own
1395+/// chirp filter has (`y = residual + ca1*y[n-1] + ca2*y[n-2]`, an IIR rather
1396+/// than this FIR, but both are order-2 linear reshapings of the same copied
1397+/// content), so the fitted taps are directly comparable in spirit to our own
1398+/// bandwidth-expanded LPC coefficients: near `(1,0,0)` means "reference is
1399+/// also just a plain copy here", taps with real weight on lag 1/2 mean a
1400+/// genuine order-2 transformation is present.
1401+#[allow(clippy::needless_range_loop)] // fixed 3x3 complex Gaussian elimination, index math throughout
1402+fn hf_patch_transfer_fit(
1403+ o: &[f32],
1404+ t: &[f32],
1405+ bands: &[usize],
1406+) -> Vec<(usize, [ec_dsp::Complex<f64>; 3])> {
1407+ let (_, t_spec, sim_spec) = qmf_domain_spec(o, t);
1408+ let mut results = Vec::new();
1409+ for &band in bands {
1410+ if band >= sim_spec.len() {
1411+ continue;
1412+ }
1413+ let sim_raw = &sim_spec[band];
1414+ let ref_raw = &t_spec[band];
1415+ let len = sim_raw.len().min(ref_raw.len());
1416+ if len < 8 {
1417+ continue;
1418+ }
1419+ // Normalize each series to unit RMS first: the raw QMF-domain
1420+ // amplitudes differ by orders of magnitude (sim carries no envelope
1421+ // gain, `ref` does), which would otherwise make every fitted
1422+ // coefficient collapse toward the gain ratio rather than the
1423+ // fraction-of-`ref`-explained-by-which-lag this fit is meant to
1424+ // read off.
1425+ let rms = |s: &[ec_dsp::Complex<f64>]| -> f64 {
1426+ (s[..len]
1427+ .iter()
1428+ .map(|c| c.re * c.re + c.im * c.im)
1429+ .sum::<f64>()
1430+ / len as f64)
1431+ .sqrt()
1432+ .max(1e-300)
1433+ };
1434+ let sim_scale = 1.0 / rms(sim_raw);
1435+ let ref_scale = 1.0 / rms(ref_raw);
1436+ let sim: Vec<ec_dsp::Complex<f64>> =
1437+ sim_raw[..len].iter().map(|c| c.scale(sim_scale)).collect();
1438+ let refb: Vec<ec_dsp::Complex<f64>> =
1439+ ref_raw[..len].iter().map(|c| c.scale(ref_scale)).collect();
1440+ let sim = &sim[..];
1441+ let refb = &refb[..];
1442+ // Complex 3x3 Hermitian normal equations: r[i][j] = sum sim[l-i] conj(sim[l-j]),
1443+ // p[i] = sum sim[l-i] conj(ref[l])... solved as R^T a = p with R real basis in
1444+ // complex arithmetic (Gaussian elimination with partial pivoting by magnitude).
1445+ let mut r = [[ec_dsp::Complex::new(0.0f64, 0.0); 3]; 3];
1446+ let mut p = [ec_dsp::Complex::new(0.0f64, 0.0); 3];
1447+ for l in 2..len {
1448+ let s = [sim[l], sim[l - 1], sim[l - 2]];
1449+ let y = refb[l];
1450+ for i in 0..3 {
1451+ p[i] = p[i] + s[i].conj() * y;
1452+ for j in 0..3 {
1453+ r[i][j] = r[i][j] + s[i].conj() * s[j];
1454+ }
1455+ }
1456+ }
1457+ // Gaussian elimination on the augmented [r | p] system.
1458+ let mut aug = r;
1459+ let mut rhs = p;
1460+ for col in 0..3 {
1461+ let mut piv = col;
1462+ let mut best = aug[col][col].norm_sqr();
1463+ for row in (col + 1)..3 {
1464+ let m = aug[row][col].norm_sqr();
1465+ if m > best {
1466+ best = m;
1467+ piv = row;
1468+ }
1469+ }
1470+ if best < 1e-24 {
1471+ continue;
1472+ }
1473+ aug.swap(col, piv);
1474+ rhs.swap(col, piv);
1475+ let inv = aug[col][col].conj().scale(1.0 / best);
1476+ for row in (col + 1)..3 {
1477+ let f = aug[row][col] * inv;
1478+ for k in 0..3 {
1479+ aug[row][k] = aug[row][k] - f * aug[col][k];
1480+ }
1481+ rhs[row] = rhs[row] - f * rhs[col];
1482+ }
1483+ }
1484+ let mut a = [ec_dsp::Complex::new(0.0f64, 0.0); 3];
1485+ for row in (0..3).rev() {
1486+ let mut acc = rhs[row];
1487+ for k in (row + 1)..3 {
1488+ acc = acc - aug[row][k] * a[k];
1489+ }
1490+ let d = aug[row][row];
1491+ a[row] = if d.norm_sqr() > 1e-24 {
1492+ acc * d.conj().scale(1.0 / d.norm_sqr())
1493+ } else {
1494+ ec_dsp::Complex::new(0.0, 0.0)
1495+ };
1496+ }
1497+ results.push((band, a));
1498+ }
1499+ results
1500+}
1501+
1279 /// A file discovered under the user's own media directories: its path, which1502 /// A file discovered under the user's own media directories: its path, which
1280 /// AAC stream in it (0-based among AAC streams only) carries HE-AAC, and the1503 /// AAC stream in it (0-based among AAC streams only) carries HE-AAC, and the
1281 /// core/SBR crossover an ffprobe/ASC inspection already pinned for it -- used1504 /// core/SBR crossover an ffprobe/ASC inspection already pinned for it -- used
@@ -2026,6 +2249,56 @@ fn sbr_real_library_matches_reference() {
2026 mean_in(&vs_ours, 28, 43)2249 mean_in(&vs_ours, 28, 43)
2027 );2250 );
2028 }2251 }
2252+ // (Round-46, Task 1) QMF-domain exact third witness -- see
2253+ // `hf_patch_simulator_qmf`'s doc comment.
2254+ if std::env::var("EC_AAC_SBR_QMF_WITNESS").is_ok() && n >= 4_096 {
2255+ let win = &o[oa..oa + n];
2256+ let twin = &t[ob..ob + n];
2257+ let (vs_ref, vs_ours) = hf_patch_simulator_qmf(win, twin);
2258+ let mean_in = |rows: &[(usize, f64)], lo: usize, hi: usize| {
2259+ let vals: Vec<f64> = rows
2260+ .iter()
2261+ .filter(|(b, _)| *b >= lo && *b < hi)
2262+ .map(|(_, c)| *c)
2263+ .collect();
2264+ if vals.is_empty() {
2265+ 0.0
2266+ } else {
2267+ vals.iter().sum::<f64>() / vals.len() as f64
2268+ }
2269+ };
2270+ println!(" ch{ch} QMF-WITNESS sim-vs-REFERENCE per-band coherence (band, coh):");
2271+ for (b, coh) in &vs_ref {
2272+ println!(" band{b:>3}: {coh:.4}");
2273+ }
2274+ println!(
2275+ " ch{ch} QMF-WITNESS sim-vs-REFERENCE mean: even-gap[14,28)={:.4} odd-gap[28,43)={:.4}",
2276+ mean_in(&vs_ref, 14, 28),
2277+ mean_in(&vs_ref, 28, 43)
2278+ );
2279+ println!(" ch{ch} QMF-WITNESS sim-vs-OURS per-band coherence (band, coh):");
2280+ for (b, coh) in &vs_ours {
2281+ println!(" band{b:>3}: {coh:.4}");
2282+ }
2283+ println!(
2284+ " ch{ch} QMF-WITNESS sim-vs-OURS mean: even-gap[14,28)={:.4} odd-gap[28,43)={:.4}",
2285+ mean_in(&vs_ours, 14, 28),
2286+ mean_in(&vs_ours, 28, 43)
2287+ );
2288+ // (Round-46, Task 2) fitted sim-to-reference transfer, one
2289+ // representative band per patch plus a spread across the
2290+ // strong odd-gap patch (3,28,11) where the QMF witness shows
2291+ // sim-vs-reference clearing 0.5.
2292+ let fit_bands = [14, 18, 22, 26, 28, 30, 32, 34, 36, 38, 39, 42];
2293+ let fits = hf_patch_transfer_fit(win, twin, &fit_bands);
2294+ println!(" ch{ch} TASK2 FIT ref[l]~=a0*sim[l]+a1*sim[l-1]+a2*sim[l-2]:");
2295+ for (b, a) in &fits {
2296+ println!(
2297+ " band{b:>3}: a0=({:>7.3},{:>7.3}) a1=({:>7.3},{:>7.3}) a2=({:>7.3},{:>7.3})",
2298+ a[0].re, a[0].im, a[1].re, a[1].im, a[2].re, a[2].im
2299+ );
2300+ }
2301+ }
2029 println!(2302 println!(
2030 " ch{ch}: lag {lag}, full {full:.6}, below {:.0}Hz {low:.6}, above {:.0}Hz {high:.6}",2303 " ch{ch}: lag {lag}, full {full:.6}, below {:.0}Hz {low:.6}, above {:.0}Hz {high:.6}",
2031 c.crossover_hz, c.crossover_hz2304 c.crossover_hz, c.crossover_hz