forge
Explore
Log in

Don't you dare go Hollow

Sbr_hf::generate runs the spec's feed-forward FIR, not an all-pole resynthesis

Browse files at this commit

857b408bf0321a6be4941d3d4a639f8eb371cf74Ahmet Kaan GümüşParent: 20037c7
  • fix
    • sbr_hf::generate runs the spec's feed-forward FIR, not an all-pole resynthesis
Show full message
fix(aac): sbr_hf::generate runs the spec's feed-forward FIR, not an all-pole resynthesis

The module's own doc admitted the chirp stage re-synthesised the copied
subband's residual through a bandwidth-expanded ALL-POLE filter (`y =
residual + ca1*y[n-1] + ca2*y[n-2]`). ISO/IEC 14496-3 SS4.6.18.6 is
feed-forward: X_high[l] = X_src[l] + bw*a1*X_src[l-1] + bw^2*a2*X_src[l-2],
a 2-tap FIR extension of the raw copy, using the source band's own
covariance-method LPC coefficients unnegated (pinned by the new
`feed_forward_extension_matches_bw_endpoints` unit test: a noiseless AR(2)
source at bw~0.98 comes out ~1.98x reinforced/same-phase, not attenuated or
inverted the way a negated convention would produce; bw=0 is an exact plain
copy). HfHistory drops its now-unused y-history half.

Round-48, Task 2's sim->ours vs sim->ref transfer fit (patch (3,28,11),
`hf_patch_transfer_fit` now takes a `target_is_ours` flag) shows the two
fits already have similar order-2 shape before and after this change --
the structural gap this round targeted wasn't gating most of the shortfall.
Judged on reeln (both channels), the fix is spec-correct but measures
slightly WORSE on every witness, not better:
  full-band correlation:  ch0 0.972474->0.963863, ch1 0.969785->0.961027
  QMF-WITNESS sim-vs-ours (odd-gap[28,43)): ch0 0.3082->0.2814
  QMF-WITNESS ours-vs-ref (odd-gap[28,43), new pairing added to the
    witness this round): ch0 0.4400->0.4222, ch1 0.4635->0.4258
FMJ's pre-existing, separately-tracked ch1 decorrelation is unaffected
(out of scope here). No regression bound is weakened; this is reported as
a spec-compliance fix with a measured (small) real-file cost, not a win.
crates/ec-aac/src/sbr_hf.rsmodified+123 -40
@@ -24,14 +24,16 @@
2424 //!
2525 //! For each *source* subband, a covariance-method order-2 LPC is fit to
2626 //! that subband's own QMF time series (two slots of carried-over history
27-//! plus the current frame's slots). The residual against those raw
28-//! coefficients is then re-synthesised through a *bandwidth-expanded*
29-//! all-pole filter -- coefficients scaled by `bw` and `bw^2` -- which is
30-//! the standard SBR "inverse filtering" trick: `bw` near 1 leaves the
31-//! subband's own resonance intact (a strongly tonal patch), `bw` near 0
32-//! flattens it toward its whitened residual (a noise-like patch). `bw`
33-//! itself comes from `bs_invf_mode` and is smoothed frame to frame with a
34-//! fast-attack/slow-release curve so inverse-filter mode changes don't pop.
27+//! plus the current frame's slots), giving prediction coefficients `(a1,
28+//! a2)` such that `x[l] ~= a1*x[l-1] + a2*x[l-2]`. Per §4.6.18.6, the copied
29+//! series is then extended *feed-forward* by a bandwidth-expanded 2-tap FIR
30+//! built from those same coefficients: `X_high[l] = X_src[l] + bw*a1*
31+//! X_src[l-1] + bw^2*a2*X_src[l-2]`. This is the standard SBR "inverse
32+//! filtering" trick: `bw` near 1 reinforces the subband's own resonance atop
33+//! the raw copy (a strongly tonal patch), `bw` at 0 degenerates to the plain
34+//! copy (no extra tap energy at all). `bw` itself comes from `bs_invf_mode`
35+//! and is smoothed frame to frame with a fast-attack/slow-release curve so
36+//! inverse-filter mode changes don't pop.
3537
3638 use crate::sbr_bands::BandTables;
3739 use ec_dsp::Complex;
@@ -317,25 +319,27 @@ pub fn lpc2(x: &[Complex<f64>]) -> (Complex<f64>, Complex<f64>) {
317319 (a1, a2)
318320 }
319321
320-/// Bounds an AR(2) predictor's coefficients so the resynthesis recursion
321-/// this module runs (`y = residual + ca1*y[n-1] + ca2*y[n-2]`) cannot
322-/// diverge.
322+/// Bounds an AR(2) predictor's coefficients so the feed-forward FIR
323+/// extension `generate` builds from them (`X_high[l] = X_src[l] +
324+/// bw*a1*X_src[l-1] + bw^2*a2*X_src[l-2]`) cannot blow up the copied tap
325+/// energy on a badly-conditioned fit.
323326 ///
324327 /// `lpc2` solves an unwindowed covariance-method normal-equation system,
325328 /// which -- unlike the autocorrelation/Levinson-Durbin method the reference
326329 /// SBR tool uses -- carries no built-in stability guarantee: on a short (32
327330 /// QMF slot) window of a strongly resonant real-music subband it can and
328-/// does return a pole outside the unit circle, and the 32-sample feedback
329-/// loop below then grows geometrically within a single frame (observed:
330-/// output rms in the hundreds of thousands on real HE-AAC files, versus
331-/// ~0.2 for a working decode). `|a1| + |a2| < 1` is a standard sufficient
332-/// (if conservative) BIBO-stability bound for a direct-form-II section, so
333-/// clamping the pair to it whenever it is violated is a corner-cut: it
334-/// trades exactness on the rare unstable-estimate frame for boundedness
335-/// everywhere, ceiling = slightly under-resonant HF on whichever frames hit
336-/// the clamp; upgrade path = replace `lpc2` with the spec's own
337-/// Levinson-Durbin-derived reflection coefficients, which are stable by
338-/// construction and would make this function a no-op.
331+/// does return a pole outside the unit circle, driving the FIR taps to
332+/// unreasonably large magnitude for what should be a bounded-gain
333+/// extension (observed: output rms in the hundreds of thousands on real
334+/// HE-AAC files, versus ~0.2 for a working decode, back when this fed an
335+/// IIR recursion; the same unstable estimate still over-weights the taps
336+/// here). `|a1| + |a2| < 1` is a standard sufficient (if conservative)
337+/// bound, so clamping the pair to it whenever it is violated is a
338+/// corner-cut: it trades exactness on the rare unstable-estimate frame for
339+/// boundedness everywhere, ceiling = slightly under-resonant HF on
340+/// whichever frames hit the clamp; upgrade path = replace `lpc2` with the
341+/// spec's own Levinson-Durbin-derived reflection coefficients, which are
342+/// stable by construction and would make this function a no-op.
339343 fn stabilize(coeffs: (Complex<f64>, Complex<f64>)) -> (Complex<f64>, Complex<f64>) {
340344 let (a1, a2) = coeffs;
341345 let mag = a1.norm_sqr().sqrt() + a2.norm_sqr().sqrt();
@@ -349,20 +353,19 @@ fn stabilize(coeffs: (Complex<f64>, Complex<f64>)) -> (Complex<f64>, Complex<f64
349353 }
350354 }
351355
352-/// Per-source-subband history: the last two QMF slots, carried across
353-/// `generate` calls so the LPC and whitening filter have continuity at
354-/// frame boundaries instead of restarting cold every frame.
356+/// Per-source-subband history: the last two QMF slots (`X_src[l-1]`,
357+/// `X_src[l-2]`), carried across `generate` calls so the LPC fit and the
358+/// feed-forward FIR extension both have continuity at frame boundaries
359+/// instead of restarting cold every frame.
355360 #[derive(Clone, Debug)]
356361 pub struct HfHistory {
357362 x: Vec<[Complex<f64>; 2]>,
358- y: Vec<[Complex<f64>; 2]>,
359363 }
360364
361365 impl HfHistory {
362366 pub fn new(bands: usize) -> HfHistory {
363367 HfHistory {
364368 x: vec![[Complex::ZERO; 2]; bands],
365- y: vec![[Complex::ZERO; 2]; bands],
366369 }
367370 }
368371 }
@@ -425,13 +428,18 @@ pub fn generate(
425428 if std::env::var("EC_AAC_SBR_BW_DUMP").is_ok() {
426429 eprintln!("BW_DUMP target_band={target_band} source_band={source_band} bw={g:.6}");
427430 }
431+ // (Round-48, Task 3) §4.6.18.6 feed-forward extension: `X_high[l]
432+ // = X_src[l] + bw*a1*X_src[l-1] + bw^2*a2*X_src[l-2]`. `a1`/`a2`
433+ // are used directly (not negated): `lpc2` returns them in the
434+ // "predicts forward" convention (`x[l] ~= a1*x[l-1] +
435+ // a2*x[l-2]`, pinned by `lpc_recovers_the_poles_of_a_synthetic_
436+ // ar2_process`), so applying them unnegated to the raw copy
437+ // continues the source subband's own AR resonance into the
438+ // patched band -- `bw` at 1 is maximally tonal, `bw` at 0
439+ // degenerates the whole tap to zero, leaving the plain copy
440+ // (see `feed_forward_extension_matches_bw_endpoints`).
428441 let ca1 = a1.scale(g);
429442 let ca2 = a2.scale(g * g);
430- let (mut y_prev1, mut y_prev2) = if source_band < history.y.len() {
431- (history.y[source_band][1], history.y[source_band][0])
432- } else {
433- (Complex::ZERO, Complex::ZERO)
434- };
435443 let (mut x_prev1, mut x_prev2) = if source_band < history.x.len() {
436444 (history.x[source_band][1], history.x[source_band][0])
437445 } else {
@@ -439,8 +447,6 @@ pub fn generate(
439447 };
440448 let dst = &mut out[target_band - kx];
441449 for (n, &x) in series.iter().enumerate() {
442- let residual = x - a1 * x_prev1 - a2 * x_prev2;
443- let y = residual + ca1 * y_prev1 + ca2 * y_prev2;
444450 // Round-37 (Task 2): `band_shift_correction` is proven exact
445451 // in isolation (a stationary tone replayed through this
446452 // patch-copy site lands within a couple of FFT bins of its
@@ -454,11 +460,9 @@ pub fn generate(
454460 // on ch0). The reference apparently exhibits this bank's own
455461 // "wrong" cross-band placement convention, so matching it is
456462 // the bar: `dst` stays the plain, uncorrected copy.
457- dst[n] = y;
463+ dst[n] = x + ca1 * x_prev1 + ca2 * x_prev2;
458464 x_prev2 = x_prev1;
459465 x_prev1 = x;
460- y_prev2 = y_prev1;
461- y_prev1 = y;
462466 }
463467 }
464468 }
@@ -471,9 +475,6 @@ pub fn generate(
471475 }
472476 let n = series.len();
473477 history.x[band] = [series[n - 2], series[n - 1]];
474- // y-history only meaningfully advances for bands a patch actually
475- // wrote; untouched bands hold their input as a neutral seed.
476- history.y[band] = [series[n - 2], series[n - 1]];
477478 }
478479
479480 out
@@ -552,4 +553,86 @@ mod tests {
552553 "fall {fall_step} rise {rise_step}"
553554 );
554555 }
556+
557+ /// (Round-48, Task 3) Pins the feed-forward extension's sign convention
558+ /// and `bw` endpoints against the spec-shaped formula (`generate`'s own
559+ /// doc comment): `X_high[l] = X_src[l] + bw*a1*X_src[l-1] +
560+ /// bw^2*a2*X_src[l-2]`, `a1`/`a2` used unnegated.
561+ ///
562+ /// Drives a *noiseless* AR(2) source (`x[n] = a1*x[n-1] + a2*x[n-2]`
563+ /// exactly, `|a1|+|a2| = 0.9 < 0.999` so `stabilize` never clamps) through
564+ /// two consecutive frames so the second frame's history/LPC fit is on
565+ /// data that satisfies the recurrence exactly end to end. At `bw=0`
566+ /// (`bs_invf_mode` OFF) the extension must degenerate to the plain copy.
567+ /// At `bw` near 1 (`bs_invf_mode` HIGH, `BW_TABLE[3] = 0.98`), since the
568+ /// noiseless source satisfies `a1*x[l-1] + a2*x[l-2] == x[l]` exactly,
569+ /// the correct (unnegated) convention algebraically collapses to
570+ /// `y[l] ~= (1 + bw) * x[l] ~= 1.98 * x[l]` -- strictly *more* tonal
571+ /// (same phase, amplified), not attenuated or inverted the way the
572+ /// negated convention would produce (`y[l] ~= (1 - bw) * x[l] ~= 0.02 *
573+ /// x[l]`, nearly cancelling the signal). This directly discriminates the
574+ /// two sign conventions, not just "some nonzero tap fired".
575+ #[test]
576+ fn feed_forward_extension_matches_bw_endpoints() {
577+ let tables = real_file_tables();
578+ let kx = tables.kx as usize;
579+ let a1 = 0.6f64;
580+ let a2 = -0.3f64;
581+ let total = 60usize;
582+ let mut x = vec![1.0f64, 0.5];
583+ for _ in 2..total {
584+ let n = x.len();
585+ x.push(a1 * x[n - 1] + a2 * x[n - 2]);
586+ }
587+ let make_low_cur = |chunk: &[f64]| -> Vec<Vec<Complex<f64>>> {
588+ let mut low = vec![vec![Complex::ZERO; chunk.len()]; kx];
589+ low[0] = chunk.iter().map(|&v| Complex::new(v, 0.0)).collect();
590+ low
591+ };
592+ let frame1 = make_low_cur(&x[0..30]);
593+ let frame2 = make_low_cur(&x[30..60]);
594+ let invf_off = vec![0u8; tables.n_q];
595+ let invf_high = vec![3u8; tables.n_q];
596+
597+ // bw = 0: extension is an exact plain copy.
598+ let mut chirp0 = ChirpState::new(tables.n_q);
599+ let mut hist0 = HfHistory::new(kx);
600+ let _ = generate(&frame1, &tables, &invf_off, &mut chirp0, &mut hist0);
601+ let out0 = generate(&frame2, &tables, &invf_off, &mut chirp0, &mut hist0);
602+ let dst0 = &out0[14 - kx]; // target band 14, patch (0,14,14) offset 0
603+ for (n, &y) in dst0.iter().enumerate() {
604+ let expect = x[30 + n];
605+ assert!(
606+ (y.re - expect).abs() < 1e-9 && y.im.abs() < 1e-9,
607+ "bw=0 mismatch at n={n}: {y:?} vs {expect}"
608+ );
609+ }
610+
611+ // bw ~= 0.98: reinforces the source's own resonance, ~1.98x, same
612+ // phase -- not the ~0.02x a negated convention would produce.
613+ let mut chirp1 = ChirpState::new(tables.n_q);
614+ chirp1.bw = vec![0.0; tables.n_q]; // priming frame at bw=0
615+ let mut hist1 = HfHistory::new(kx);
616+ let _ = generate(&frame1, &tables, &invf_off, &mut chirp1, &mut hist1);
617+ chirp1.bw = vec![0.98; tables.n_q]; // preload the exact target: `update` below is then a no-op
618+ let out1 = generate(&frame2, &tables, &invf_high, &mut chirp1, &mut hist1);
619+ let dst1 = &out1[14 - kx];
620+ // Skip the first couple of slots (LPC fit needs the history to
621+ // settle); check the steady-state ratio on the rest.
622+ for (n, &y) in dst1.iter().enumerate().skip(4) {
623+ let expect = x[30 + n];
624+ if expect.abs() < 1e-6 {
625+ continue;
626+ }
627+ let ratio = y.re / expect;
628+ assert!(
629+ (1.0..2.1).contains(&ratio),
630+ "bw=0.98 ratio out of range at n={n}: ratio={ratio} y={y:?} x={expect}"
631+ );
632+ assert!(
633+ y.im.abs() < 0.05 * expect.abs().max(1e-6),
634+ "unexpected imaginary part at n={n}: {y:?}"
635+ );
636+ }
637+ }
555638 }
crates/ec-aac/tests/sbr_real_library.rsmodified+53 -11
@@ -1333,17 +1333,26 @@ fn qmf_domain_spec(o: &[f32], t: &[f32]) -> (QmfBandSlots, QmfBandSlots, QmfBand
13331333 (o_spec, t_spec, sim_spec)
13341334 }
13351335
1336-fn hf_patch_simulator_qmf(o: &[f32], t: &[f32]) -> (BandCoherenceTable, BandCoherenceTable) {
1336+/// Returns `(sim-vs-reference, sim-vs-ours, ours-vs-reference)` -- the last
1337+/// pairing (round-48, Task 4a) is the ultimate content-match witness: how
1338+/// well our actual HF QMF content agrees with the reference's, with no
1339+/// simulator in between.
1340+fn hf_patch_simulator_qmf(
1341+ o: &[f32],
1342+ t: &[f32],
1343+) -> (BandCoherenceTable, BandCoherenceTable, BandCoherenceTable) {
13371344 use ec_aac::sbr_qmf::SYNTHESIS_BANDS;
13381345 const WIN: usize = 16;
13391346 let (o_spec, t_spec, sim_spec) = qmf_domain_spec(o, t);
13401347 let slots = sim_spec.first().map(Vec::len).unwrap_or(0);
13411348 if slots < WIN {
1342- return (Vec::new(), Vec::new());
1349+ return (Vec::new(), Vec::new(), Vec::new());
13431350 }
13441351 let top_band = 43.min(SYNTHESIS_BANDS);
13451352 let windows = slots / WIN;
1346- let band_coherence = |target: &[Vec<ec_dsp::Complex<f64>>]| -> Vec<(usize, f64)> {
1353+ let band_coherence = |source: &[Vec<ec_dsp::Complex<f64>>],
1354+ target: &[Vec<ec_dsp::Complex<f64>>]|
1355+ -> Vec<(usize, f64)> {
13471356 (14..top_band)
13481357 .map(|band| {
13491358 let mut cross_re = 0.0f64;
@@ -1353,7 +1362,7 @@ fn hf_patch_simulator_qmf(o: &[f32], t: &[f32]) -> (BandCoherenceTable, BandCohe
13531362 for w in 0..windows {
13541363 let lo = w * WIN;
13551364 let hi = lo + WIN;
1356- let se: f64 = sim_spec[band][lo..hi]
1365+ let se: f64 = source[band][lo..hi]
13571366 .iter()
13581367 .map(|c| c.re * c.re + c.im * c.im)
13591368 .sum();
@@ -1366,7 +1375,7 @@ fn hf_patch_simulator_qmf(o: &[f32], t: &[f32]) -> (BandCoherenceTable, BandCohe
13661375 }
13671376 let scale = (te / se).sqrt();
13681377 for i in lo..hi {
1369- let sc = sim_spec[band][i].scale(scale);
1378+ let sc = source[band][i].scale(scale);
13701379 let tc = target[band][i];
13711380 let cross = sc * tc.conj();
13721381 cross_re += cross.re;
@@ -1385,7 +1394,11 @@ fn hf_patch_simulator_qmf(o: &[f32], t: &[f32]) -> (BandCoherenceTable, BandCohe
13851394 })
13861395 .collect()
13871396 };
1388- (band_coherence(&t_spec), band_coherence(&o_spec))
1397+ (
1398+ band_coherence(&sim_spec, &t_spec),
1399+ band_coherence(&sim_spec, &o_spec),
1400+ band_coherence(&o_spec, &t_spec),
1401+ )
13891402 }
13901403
13911404 /// (Round-46, Task 2) Per-band 2nd-order complex prediction transfer fit
@@ -1398,20 +1411,26 @@ fn hf_patch_simulator_qmf(o: &[f32], t: &[f32]) -> (BandCoherenceTable, BandCohe
13981411 /// bandwidth-expanded LPC coefficients: near `(1,0,0)` means "reference is
13991412 /// also just a plain copy here", taps with real weight on lag 1/2 mean a
14001413 /// genuine order-2 transformation is present.
1414+/// `target_is_ours`: fit against our own decode (`o_spec`) instead of the
1415+/// reference's (`t_spec`) -- same `sim` (built from the reference's own low
1416+/// band either way), so the two calls' fitted taps are directly comparable:
1417+/// what transform sim would need to become ours vs. to become the reference.
14011418 #[allow(clippy::needless_range_loop)] // fixed 3x3 complex Gaussian elimination, index math throughout
14021419 fn hf_patch_transfer_fit(
14031420 o: &[f32],
14041421 t: &[f32],
14051422 bands: &[usize],
1423+ target_is_ours: bool,
14061424 ) -> Vec<(usize, [ec_dsp::Complex<f64>; 3])> {
1407- let (_, t_spec, sim_spec) = qmf_domain_spec(o, t);
1425+ let (o_spec, t_spec, sim_spec) = qmf_domain_spec(o, t);
1426+ let target_spec = if target_is_ours { &o_spec } else { &t_spec };
14081427 let mut results = Vec::new();
14091428 for &band in bands {
14101429 if band >= sim_spec.len() {
14111430 continue;
14121431 }
14131432 let sim_raw = &sim_spec[band];
1414- let ref_raw = &t_spec[band];
1433+ let ref_raw = &target_spec[band];
14151434 let len = sim_raw.len().min(ref_raw.len());
14161435 if len < 8 {
14171436 continue;
@@ -2254,7 +2273,7 @@ fn sbr_real_library_matches_reference() {
22542273 if std::env::var("EC_AAC_SBR_QMF_WITNESS").is_ok() && n >= 4_096 {
22552274 let win = &o[oa..oa + n];
22562275 let twin = &t[ob..ob + n];
2257- let (vs_ref, vs_ours) = hf_patch_simulator_qmf(win, twin);
2276+ let (vs_ref, vs_ours, ours_vs_ref) = hf_patch_simulator_qmf(win, twin);
22582277 let mean_in = |rows: &[(usize, f64)], lo: usize, hi: usize| {
22592278 let vals: Vec<f64> = rows
22602279 .iter()
@@ -2285,14 +2304,37 @@ fn sbr_real_library_matches_reference() {
22852304 mean_in(&vs_ours, 14, 28),
22862305 mean_in(&vs_ours, 28, 43)
22872306 );
2307+ // (Round-48, Task 4a) the ultimate content-match witness:
2308+ // our HF QMF content directly against the reference's, no
2309+ // simulator step in between.
2310+ println!(" ch{ch} QMF-WITNESS ours-vs-REFERENCE per-band coherence (band, coh):");
2311+ for (b, coh) in &ours_vs_ref {
2312+ println!(" band{b:>3}: {coh:.4}");
2313+ }
2314+ println!(
2315+ " ch{ch} QMF-WITNESS ours-vs-REFERENCE mean: even-gap[14,28)={:.4} odd-gap[28,43)={:.4}",
2316+ mean_in(&ours_vs_ref, 14, 28),
2317+ mean_in(&ours_vs_ref, 28, 43)
2318+ );
22882319 // (Round-46, Task 2) fitted sim-to-reference transfer, one
22892320 // representative band per patch plus a spread across the
22902321 // strong odd-gap patch (3,28,11) where the QMF witness shows
22912322 // sim-vs-reference clearing 0.5.
22922323 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);
2324+ let fits_ref = hf_patch_transfer_fit(win, twin, &fit_bands, false);
22942325 println!(" ch{ch} TASK2 FIT ref[l]~=a0*sim[l]+a1*sim[l-1]+a2*sim[l-2]:");
2295- for (b, a) in &fits {
2326+ for (b, a) in &fits_ref {
2327+ println!(
2328+ " band{b:>3}: a0=({:>7.3},{:>7.3}) a1=({:>7.3},{:>7.3}) a2=({:>7.3},{:>7.3})",
2329+ a[0].re, a[0].im, a[1].re, a[1].im, a[2].re, a[2].im
2330+ );
2331+ }
2332+ // (Round-48, Task 2) same fit, target = ours: side by side
2333+ // with the above shows exactly what our transform does to
2334+ // the plain copy vs what the reference's does.
2335+ let fits_ours = hf_patch_transfer_fit(win, twin, &fit_bands, true);
2336+ println!(" ch{ch} TASK2 FIT ours[l]~=a0*sim[l]+a1*sim[l-1]+a2*sim[l-2]:");
2337+ for (b, a) in &fits_ours {
22962338 println!(
22972339 " band{b:>3}: a0=({:>7.3},{:>7.3}) a1=({:>7.3},{:>7.3}) a2=({:>7.3},{:>7.3})",
22982340 a[0].re, a[0].im, a[1].re, a[1].im, a[2].re, a[2].im