forge
Explore
Log in

Don't you dare go Hollow

Sbr_hf::generate back to all-pole residual resynthesis, measurement over recall

Browse files at this commit

fee35a82feb4b34a5940e95188574aab86c0d0ffAhmet Kaan GümüşParent: dd00c7c
  • revert
    • sbr_hf::generate back to all-pole residual resynthesis, measurement over recall
Show full message
revert(aac): sbr_hf::generate back to all-pole residual resynthesis, measurement over recall

Round-48 (8bc305b) rewrote the chirp stage from all-pole residual
resynthesis to the spec's literal feed-forward FIR extension, justified
as spec-correct, and it regressed the real-file bar: full-band
correlation against the reference decoder on reeln dropped
0.972474->0.963863 (ch0) and 0.969785->0.961027 (ch1), same direction on
below-crossover (0.992799->0.991256, 0.992329->0.990690) and whole-file
windowed-mean correlation (0.955717->0.953189, 0.951577->0.949116).

Round-50 A/B at HEAD, both arms otherwise identical (reeln, single
deterministic run each -- no RNG in this decode path so a repeat run
would be bit-identical):

  metric                    all-pole (ch0/ch1)   feed-forward (ch0/ch1)
  full-band corr             0.972474 / 0.969785   0.963863 / 0.961027
  below-crossover corr       0.992799 / 0.992329   0.991256 / 0.990690
  whole-file windowed mean   0.955717 / 0.951577   0.953189 / 0.949116

All-pole wins on every metric, both channels, by well over the 0.002
noise floor. This project's standing discipline: a from-memory "spec"
label does not outrank a measurement; the bar is matching the reference
decoder's actual output. Reverting the filter structure; the round-48
unit test is rewritten (`all_pole_resynthesis_matches_bw_endpoints`) to
pin the all-pole behavior as the empirically-matching variant, with a
module-doc paragraph documenting that both structures were implemented
and measured, and which one won. The feed-forward alternative and its
own discriminating test stay in history (8bc305b) as the documented
"spec-literal" alternative, should some other pipeline change ever make
it the better match.

FMJ's pre-existing, separately-tracked ch1 decorrelation is unaffected
(unchanged by this revert, out of scope).
crates/ec-aac/src/sbr_hf.rsmodified+94 -68
@@ -24,16 +24,31 @@
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), 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.
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.
35+//!
36+//! Round-48 replaced this all-pole residual resynthesis with the spec's
37+//! literal reading of §4.6.18.6, a feed-forward 2-tap FIR extension of the
38+//! raw copy (`X_high[l] = X_src[l] + bw*a1*X_src[l-1] + bw^2*a2*X_src[l-2]`).
39+//! That version compiled, passed its own unit test, and is *closer* to a
40+//! literal spec transcription -- but measured reproducibly WORSE on real
41+//! content: full-band correlation against the reference decoder on
42+//! reeln dropped 0.972474->0.963863 (ch0) and 0.969785->0.961027 (ch1),
43+//! same direction on below-crossover and whole-file windowed-mean
44+//! correlation too (round-50 A/B, ledger-recorded). This module reverted to
45+//! the all-pole structure documented above on that measurement, not on the
46+//! spec reading: the bar this project holds itself to is matching the
47+//! reference decoder's actual output, and a from-memory "more spec-literal"
48+//! label does not outrank it. The feed-forward alternative and its
49+//! discriminating unit test remain in history (commit 8bc305b) as the
50+//! documented alternative, should some other change in this pipeline ever
51+//! make it the better match.
3752
3853 use crate::sbr_bands::BandTables;
3954 use ec_dsp::Complex;
@@ -319,27 +334,25 @@ pub fn lpc2(x: &[Complex<f64>]) -> (Complex<f64>, Complex<f64>) {
319334 (a1, a2)
320335 }
321336
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.
337+/// Bounds an AR(2) predictor's coefficients so the resynthesis recursion
338+/// this module runs (`y = residual + ca1*y[n-1] + ca2*y[n-2]`) cannot
339+/// diverge.
326340 ///
327341 /// `lpc2` solves an unwindowed covariance-method normal-equation system,
328342 /// which -- unlike the autocorrelation/Levinson-Durbin method the reference
329343 /// SBR tool uses -- carries no built-in stability guarantee: on a short (32
330344 /// QMF slot) window of a strongly resonant real-music subband it can and
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.
345+/// does return a pole outside the unit circle, and the 32-sample feedback
346+/// loop below then grows geometrically within a single frame (observed:
347+/// output rms in the hundreds of thousands on real HE-AAC files, versus
348+/// ~0.2 for a working decode). `|a1| + |a2| < 1` is a standard sufficient
349+/// (if conservative) BIBO-stability bound for a direct-form-II section, so
350+/// clamping the pair to it whenever it is violated is a corner-cut: it
351+/// trades exactness on the rare unstable-estimate frame for boundedness
352+/// everywhere, ceiling = slightly under-resonant HF on whichever frames hit
353+/// the clamp; upgrade path = replace `lpc2` with the spec's own
354+/// Levinson-Durbin-derived reflection coefficients, which are stable by
355+/// construction and would make this function a no-op.
343356 fn stabilize(coeffs: (Complex<f64>, Complex<f64>)) -> (Complex<f64>, Complex<f64>) {
344357 let (a1, a2) = coeffs;
345358 let mag = a1.norm_sqr().sqrt() + a2.norm_sqr().sqrt();
@@ -353,19 +366,20 @@ fn stabilize(coeffs: (Complex<f64>, Complex<f64>)) -> (Complex<f64>, Complex<f64
353366 }
354367 }
355368
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.
369+/// Per-source-subband history: the last two QMF slots, carried across
370+/// `generate` calls so the LPC and whitening filter have continuity at
371+/// frame boundaries instead of restarting cold every frame.
360372 #[derive(Clone, Debug)]
361373 pub struct HfHistory {
362374 x: Vec<[Complex<f64>; 2]>,
375+ y: Vec<[Complex<f64>; 2]>,
363376 }
364377
365378 impl HfHistory {
366379 pub fn new(bands: usize) -> HfHistory {
367380 HfHistory {
368381 x: vec![[Complex::ZERO; 2]; bands],
382+ y: vec![[Complex::ZERO; 2]; bands],
369383 }
370384 }
371385 }
@@ -428,18 +442,13 @@ pub fn generate(
428442 if std::env::var("EC_AAC_SBR_BW_DUMP").is_ok() {
429443 eprintln!("BW_DUMP target_band={target_band} source_band={source_band} bw={g:.6}");
430444 }
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`).
441445 let ca1 = a1.scale(g);
442446 let ca2 = a2.scale(g * g);
447+ let (mut y_prev1, mut y_prev2) = if source_band < history.y.len() {
448+ (history.y[source_band][1], history.y[source_band][0])
449+ } else {
450+ (Complex::ZERO, Complex::ZERO)
451+ };
443452 let (mut x_prev1, mut x_prev2) = if source_band < history.x.len() {
444453 (history.x[source_band][1], history.x[source_band][0])
445454 } else {
@@ -447,6 +456,8 @@ pub fn generate(
447456 };
448457 let dst = &mut out[target_band - kx];
449458 for (n, &x) in series.iter().enumerate() {
459+ let residual = x - a1 * x_prev1 - a2 * x_prev2;
460+ let y = residual + ca1 * y_prev1 + ca2 * y_prev2;
450461 // Round-37 (Task 2): `band_shift_correction` is proven exact
451462 // in isolation (a stationary tone replayed through this
452463 // patch-copy site lands within a couple of FFT bins of its
@@ -460,9 +471,11 @@ pub fn generate(
460471 // on ch0). The reference apparently exhibits this bank's own
461472 // "wrong" cross-band placement convention, so matching it is
462473 // the bar: `dst` stays the plain, uncorrected copy.
463- dst[n] = x + ca1 * x_prev1 + ca2 * x_prev2;
474+ dst[n] = y;
464475 x_prev2 = x_prev1;
465476 x_prev1 = x;
477+ y_prev2 = y_prev1;
478+ y_prev1 = y;
466479 }
467480 }
468481 }
@@ -475,6 +488,9 @@ pub fn generate(
475488 }
476489 let n = series.len();
477490 history.x[band] = [series[n - 2], series[n - 1]];
491+ // y-history only meaningfully advances for bands a patch actually
492+ // wrote; untouched bands hold their input as a neutral seed.
493+ history.y[band] = [series[n - 2], series[n - 1]];
478494 }
479495
480496 out
@@ -554,26 +570,35 @@ mod tests {
554570 );
555571 }
556572
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.
573+ /// (Round-50) Pins the all-pole residual-resynthesis structure that
574+ /// round-50's real-file A/B empirically favours over the feed-forward
575+ /// FIR round-48 briefly shipped (see the module doc). Both structures
576+ /// were implemented and measured against the reference decoder on real
577+ /// content; this one matched closer, so it is the one pinned here --
578+ /// the feed-forward alternative's own discriminating test
579+ /// (`feed_forward_extension_matches_bw_endpoints`, commit 8bc305b) is
580+ /// documented history, not dead code to resurrect casually.
561581 ///
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".
582+ /// Drives the same noiseless AR(2) source as that alternative test
583+ /// through two consecutive frames, `x[n] = a1*x[n-1] + a2*x[n-2]`
584+ /// exactly, so `lpc2`'s fit recovers `(a1, a2)` closely enough that the
585+ /// *residual* `x[l] - a1*x[l-1] - a2*x[l-2]` is near zero throughout.
586+ /// That residual, not the raw copy, is what this structure resynthesises
587+ /// through the bandwidth-expanded all-pole recursion `y[l] = residual +
588+ /// ca1*y[l-1] + ca2*y[l-2]` -- the key structural difference from
589+ /// feed-forward, which adds taps onto the copy instead of replacing it
590+ /// with a filtered residual:
591+ /// - `bw=0` (`bs_invf_mode` OFF): `ca1=ca2=0`, so `y = residual ~= 0` --
592+ /// the output collapses toward silence, NOT the exact plain copy
593+ /// feed-forward produces at this same setting.
594+ /// - `bw~=0.98` (`bs_invf_mode` HIGH): `ca1,ca2` are close to the
595+ /// original `(a1,a2)` (scaled by `bw`, `bw^2`), so with residual~=0 the
596+ /// recursion nearly reproduces the source's own AR(2) resonance from
597+ /// history alone -- output tracks `x` closely in magnitude and phase,
598+ /// not the ~1.98x reinforcement feed-forward produces at the same
599+ /// setting.
575600 #[test]
576- fn feed_forward_extension_matches_bw_endpoints() {
601+ fn all_pole_resynthesis_matches_bw_endpoints() {
577602 let tables = real_file_tables();
578603 let kx = tables.kx as usize;
579604 let a1 = 0.6f64;
@@ -594,22 +619,25 @@ mod tests {
594619 let invf_off = vec![0u8; tables.n_q];
595620 let invf_high = vec![3u8; tables.n_q];
596621
597- // bw = 0: extension is an exact plain copy.
622+ // bw = 0: residual resynthesis collapses toward silence, not a copy.
598623 let mut chirp0 = ChirpState::new(tables.n_q);
599624 let mut hist0 = HfHistory::new(kx);
600625 let _ = generate(&frame1, &tables, &invf_off, &mut chirp0, &mut hist0);
601626 let out0 = generate(&frame2, &tables, &invf_off, &mut chirp0, &mut hist0);
602627 let dst0 = &out0[14 - kx]; // target band 14, patch (0,14,14) offset 0
603- for (n, &y) in dst0.iter().enumerate() {
628+ for (n, &y) in dst0.iter().enumerate().skip(4) {
604629 let expect = x[30 + n];
630+ if expect.abs() < 1e-6 {
631+ continue;
632+ }
605633 assert!(
606- (y.re - expect).abs() < 1e-9 && y.im.abs() < 1e-9,
607- "bw=0 mismatch at n={n}: {y:?} vs {expect}"
634+ y.re.abs() < 0.1 * expect.abs(),
635+ "bw=0 residual should collapse toward silence at n={n}: {y:?} vs input {expect}"
608636 );
609637 }
610638
611- // bw ~= 0.98: reinforces the source's own resonance, ~1.98x, same
612- // phase -- not the ~0.02x a negated convention would produce.
639+ // bw ~= 0.98: residual~=0, so the recursion tracks the source's own
640+ // resonance from history alone -- ratio near 1, not ~1.98.
613641 let mut chirp1 = ChirpState::new(tables.n_q);
614642 chirp1.bw = vec![0.0; tables.n_q]; // priming frame at bw=0
615643 let mut hist1 = HfHistory::new(kx);
@@ -617,8 +645,6 @@ mod tests {
617645 chirp1.bw = vec![0.98; tables.n_q]; // preload the exact target: `update` below is then a no-op
618646 let out1 = generate(&frame2, &tables, &invf_high, &mut chirp1, &mut hist1);
619647 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.
622648 for (n, &y) in dst1.iter().enumerate().skip(4) {
623649 let expect = x[30 + n];
624650 if expect.abs() < 1e-6 {
@@ -626,7 +652,7 @@ mod tests {
626652 }
627653 let ratio = y.re / expect;
628654 assert!(
629- (1.0..2.1).contains(&ratio),
655+ (0.5..1.5).contains(&ratio),
630656 "bw=0.98 ratio out of range at n={n}: ratio={ratio} y={y:?} x={expect}"
631657 );
632658 assert!(