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 @@
24 //!24 //!
25 //! For each *source* subband, a covariance-method order-2 LPC is fit to25 //! For each *source* subband, a covariance-method order-2 LPC is fit to
26 //! that subband's own QMF time series (two slots of carried-over history26 //! that subband's own QMF time series (two slots of carried-over history
27-//! plus the current frame's slots), giving prediction coefficients `(a1,27+//! plus the current frame's slots). The residual against those raw
28-//! a2)` such that `x[l] ~= a1*x[l-1] + a2*x[l-2]`. Per §4.6.18.6, the copied28+//! coefficients is then re-synthesised through a *bandwidth-expanded*
29-//! series is then extended *feed-forward* by a bandwidth-expanded 2-tap FIR29+//! all-pole filter -- coefficients scaled by `bw` and `bw^2` -- which is
30-//! built from those same coefficients: `X_high[l] = X_src[l] + bw*a1*30+//! the standard SBR "inverse filtering" trick: `bw` near 1 leaves the
31-//! X_src[l-1] + bw^2*a2*X_src[l-2]`. This is the standard SBR "inverse31+//! subband's own resonance intact (a strongly tonal patch), `bw` near 0
32-//! filtering" trick: `bw` near 1 reinforces the subband's own resonance atop32+//! flattens it toward its whitened residual (a noise-like patch). `bw`
33-//! the raw copy (a strongly tonal patch), `bw` at 0 degenerates to the plain33+//! itself comes from `bs_invf_mode` and is smoothed frame to frame with a
34-//! copy (no extra tap energy at all). `bw` itself comes from `bs_invf_mode`34+//! fast-attack/slow-release curve so inverse-filter mode changes don't pop.
35-//! and is smoothed frame to frame with a fast-attack/slow-release curve so35+//!
36-//! inverse-filter mode changes don't pop.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.
37 52
38 use crate::sbr_bands::BandTables;53 use crate::sbr_bands::BandTables;
39 use ec_dsp::Complex;54 use ec_dsp::Complex;
@@ -319,27 +334,25 @@ pub fn lpc2(x: &[Complex<f64>]) -> (Complex<f64>, Complex<f64>) {
319 (a1, a2)334 (a1, a2)
320 }335 }
321 336
322-/// Bounds an AR(2) predictor's coefficients so the feed-forward FIR337+/// Bounds an AR(2) predictor's coefficients so the resynthesis recursion
323-/// extension `generate` builds from them (`X_high[l] = X_src[l] +338+/// this module runs (`y = residual + ca1*y[n-1] + ca2*y[n-2]`) cannot
324-/// bw*a1*X_src[l-1] + bw^2*a2*X_src[l-2]`) cannot blow up the copied tap339+/// diverge.
325-/// energy on a badly-conditioned fit.
326 ///340 ///
327 /// `lpc2` solves an unwindowed covariance-method normal-equation system,341 /// `lpc2` solves an unwindowed covariance-method normal-equation system,
328 /// which -- unlike the autocorrelation/Levinson-Durbin method the reference342 /// which -- unlike the autocorrelation/Levinson-Durbin method the reference
329 /// SBR tool uses -- carries no built-in stability guarantee: on a short (32343 /// SBR tool uses -- carries no built-in stability guarantee: on a short (32
330 /// QMF slot) window of a strongly resonant real-music subband it can and344 /// 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 to345+/// does return a pole outside the unit circle, and the 32-sample feedback
332-/// unreasonably large magnitude for what should be a bounded-gain346+/// loop below then grows geometrically within a single frame (observed:
333-/// extension (observed: output rms in the hundreds of thousands on real347+/// output rms in the hundreds of thousands on real HE-AAC files, versus
334-/// HE-AAC files, versus ~0.2 for a working decode, back when this fed an348+/// ~0.2 for a working decode). `|a1| + |a2| < 1` is a standard sufficient
335-/// IIR recursion; the same unstable estimate still over-weights the taps349+/// (if conservative) BIBO-stability bound for a direct-form-II section, so
336-/// here). `|a1| + |a2| < 1` is a standard sufficient (if conservative)350+/// clamping the pair to it whenever it is violated is a corner-cut: it
337-/// bound, so clamping the pair to it whenever it is violated is a351+/// trades exactness on the rare unstable-estimate frame for boundedness
338-/// corner-cut: it trades exactness on the rare unstable-estimate frame for352+/// everywhere, ceiling = slightly under-resonant HF on whichever frames hit
339-/// boundedness everywhere, ceiling = slightly under-resonant HF on353+/// the clamp; upgrade path = replace `lpc2` with the spec's own
340-/// whichever frames hit the clamp; upgrade path = replace `lpc2` with the354+/// Levinson-Durbin-derived reflection coefficients, which are stable by
341-/// spec's own Levinson-Durbin-derived reflection coefficients, which are355+/// construction and would make this function a no-op.
342-/// stable by construction and would make this function a no-op.
343 fn stabilize(coeffs: (Complex<f64>, Complex<f64>)) -> (Complex<f64>, Complex<f64>) {356 fn stabilize(coeffs: (Complex<f64>, Complex<f64>)) -> (Complex<f64>, Complex<f64>) {
344 let (a1, a2) = coeffs;357 let (a1, a2) = coeffs;
345 let mag = a1.norm_sqr().sqrt() + a2.norm_sqr().sqrt();358 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
353 }366 }
354 }367 }
355 368
356-/// Per-source-subband history: the last two QMF slots (`X_src[l-1]`,369+/// Per-source-subband history: the last two QMF slots, carried across
357-/// `X_src[l-2]`), carried across `generate` calls so the LPC fit and the370+/// `generate` calls so the LPC and whitening filter have continuity at
358-/// feed-forward FIR extension both have continuity at frame boundaries371+/// frame boundaries instead of restarting cold every frame.
359-/// instead of restarting cold every frame.
360 #[derive(Clone, Debug)]372 #[derive(Clone, Debug)]
361 pub struct HfHistory {373 pub struct HfHistory {
362 x: Vec<[Complex<f64>; 2]>,374 x: Vec<[Complex<f64>; 2]>,
375+ y: Vec<[Complex<f64>; 2]>,
363 }376 }
364 377
365 impl HfHistory {378 impl HfHistory {
366 pub fn new(bands: usize) -> HfHistory {379 pub fn new(bands: usize) -> HfHistory {
367 HfHistory {380 HfHistory {
368 x: vec![[Complex::ZERO; 2]; bands],381 x: vec![[Complex::ZERO; 2]; bands],
382+ y: vec![[Complex::ZERO; 2]; bands],
369 }383 }
370 }384 }
371 }385 }
@@ -428,18 +442,13 @@ pub fn generate(
428 if std::env::var("EC_AAC_SBR_BW_DUMP").is_ok() {442 if std::env::var("EC_AAC_SBR_BW_DUMP").is_ok() {
429 eprintln!("BW_DUMP target_band={target_band} source_band={source_band} bw={g:.6}");443 eprintln!("BW_DUMP target_band={target_band} source_band={source_band} bw={g:.6}");
430 }444 }
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`).
441 let ca1 = a1.scale(g);445 let ca1 = a1.scale(g);
442 let ca2 = a2.scale(g * g);446 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+ };
443 let (mut x_prev1, mut x_prev2) = if source_band < history.x.len() {452 let (mut x_prev1, mut x_prev2) = if source_band < history.x.len() {
444 (history.x[source_band][1], history.x[source_band][0])453 (history.x[source_band][1], history.x[source_band][0])
445 } else {454 } else {
@@ -447,6 +456,8 @@ pub fn generate(
447 };456 };
448 let dst = &mut out[target_band - kx];457 let dst = &mut out[target_band - kx];
449 for (n, &x) in series.iter().enumerate() {458 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;
450 // Round-37 (Task 2): `band_shift_correction` is proven exact461 // Round-37 (Task 2): `band_shift_correction` is proven exact
451 // in isolation (a stationary tone replayed through this462 // in isolation (a stationary tone replayed through this
452 // patch-copy site lands within a couple of FFT bins of its463 // patch-copy site lands within a couple of FFT bins of its
@@ -460,9 +471,11 @@ pub fn generate(
460 // on ch0). The reference apparently exhibits this bank's own471 // on ch0). The reference apparently exhibits this bank's own
461 // "wrong" cross-band placement convention, so matching it is472 // "wrong" cross-band placement convention, so matching it is
462 // the bar: `dst` stays the plain, uncorrected copy.473 // the bar: `dst` stays the plain, uncorrected copy.
463- dst[n] = x + ca1 * x_prev1 + ca2 * x_prev2;474+ dst[n] = y;
464 x_prev2 = x_prev1;475 x_prev2 = x_prev1;
465 x_prev1 = x;476 x_prev1 = x;
477+ y_prev2 = y_prev1;
478+ y_prev1 = y;
466 }479 }
467 }480 }
468 }481 }
@@ -475,6 +488,9 @@ pub fn generate(
475 }488 }
476 let n = series.len();489 let n = series.len();
477 history.x[band] = [series[n - 2], series[n - 1]];490 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]];
478 }494 }
479 495
480 out496 out
@@ -554,26 +570,35 @@ mod tests {
554 );570 );
555 }571 }
556 572
557- /// (Round-48, Task 3) Pins the feed-forward extension's sign convention573+ /// (Round-50) Pins the all-pole residual-resynthesis structure that
558- /// and `bw` endpoints against the spec-shaped formula (`generate`'s own574+ /// round-50's real-file A/B empirically favours over the feed-forward
559- /// doc comment): `X_high[l] = X_src[l] + bw*a1*X_src[l-1] +575+ /// FIR round-48 briefly shipped (see the module doc). Both structures
560- /// bw^2*a2*X_src[l-2]`, `a1`/`a2` used unnegated.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.
561 ///581 ///
562- /// Drives a *noiseless* AR(2) source (`x[n] = a1*x[n-1] + a2*x[n-2]`582+ /// Drives the same noiseless AR(2) source as that alternative test
563- /// exactly, `|a1|+|a2| = 0.9 < 0.999` so `stabilize` never clamps) through583+ /// through two consecutive frames, `x[n] = a1*x[n-1] + a2*x[n-2]`
564- /// two consecutive frames so the second frame's history/LPC fit is on584+ /// exactly, so `lpc2`'s fit recovers `(a1, a2)` closely enough that the
565- /// data that satisfies the recurrence exactly end to end. At `bw=0`585+ /// *residual* `x[l] - a1*x[l-1] - a2*x[l-2]` is near zero throughout.
566- /// (`bs_invf_mode` OFF) the extension must degenerate to the plain copy.586+ /// That residual, not the raw copy, is what this structure resynthesises
567- /// At `bw` near 1 (`bs_invf_mode` HIGH, `BW_TABLE[3] = 0.98`), since the587+ /// through the bandwidth-expanded all-pole recursion `y[l] = residual +
568- /// noiseless source satisfies `a1*x[l-1] + a2*x[l-2] == x[l]` exactly,588+ /// ca1*y[l-1] + ca2*y[l-2]` -- the key structural difference from
569- /// the correct (unnegated) convention algebraically collapses to589+ /// feed-forward, which adds taps onto the copy instead of replacing it
570- /// `y[l] ~= (1 + bw) * x[l] ~= 1.98 * x[l]` -- strictly *more* tonal590+ /// with a filtered residual:
571- /// (same phase, amplified), not attenuated or inverted the way the591+ /// - `bw=0` (`bs_invf_mode` OFF): `ca1=ca2=0`, so `y = residual ~= 0` --
572- /// negated convention would produce (`y[l] ~= (1 - bw) * x[l] ~= 0.02 *592+ /// the output collapses toward silence, NOT the exact plain copy
573- /// x[l]`, nearly cancelling the signal). This directly discriminates the593+ /// feed-forward produces at this same setting.
574- /// two sign conventions, not just "some nonzero tap fired".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.
575 #[test]600 #[test]
576- fn feed_forward_extension_matches_bw_endpoints() {601+ fn all_pole_resynthesis_matches_bw_endpoints() {
577 let tables = real_file_tables();602 let tables = real_file_tables();
578 let kx = tables.kx as usize;603 let kx = tables.kx as usize;
579 let a1 = 0.6f64;604 let a1 = 0.6f64;
@@ -594,22 +619,25 @@ mod tests {
594 let invf_off = vec![0u8; tables.n_q];619 let invf_off = vec![0u8; tables.n_q];
595 let invf_high = vec![3u8; tables.n_q];620 let invf_high = vec![3u8; tables.n_q];
596 621
597- // bw = 0: extension is an exact plain copy.622+ // bw = 0: residual resynthesis collapses toward silence, not a copy.
598 let mut chirp0 = ChirpState::new(tables.n_q);623 let mut chirp0 = ChirpState::new(tables.n_q);
599 let mut hist0 = HfHistory::new(kx);624 let mut hist0 = HfHistory::new(kx);
600 let _ = generate(&frame1, &tables, &invf_off, &mut chirp0, &mut hist0);625 let _ = generate(&frame1, &tables, &invf_off, &mut chirp0, &mut hist0);
601 let out0 = generate(&frame2, &tables, &invf_off, &mut chirp0, &mut hist0);626 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 0627 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) {
604 let expect = x[30 + n];629 let expect = x[30 + n];
630+ if expect.abs() < 1e-6 {
631+ continue;
632+ }
605 assert!(633 assert!(
606- (y.re - expect).abs() < 1e-9 && y.im.abs() < 1e-9,634+ y.re.abs() < 0.1 * expect.abs(),
607- "bw=0 mismatch at n={n}: {y:?} vs {expect}"635+ "bw=0 residual should collapse toward silence at n={n}: {y:?} vs input {expect}"
608 );636 );
609 }637 }
610 638
611- // bw ~= 0.98: reinforces the source's own resonance, ~1.98x, same639+ // bw ~= 0.98: residual~=0, so the recursion tracks the source's own
612- // phase -- not the ~0.02x a negated convention would produce.640+ // resonance from history alone -- ratio near 1, not ~1.98.
613 let mut chirp1 = ChirpState::new(tables.n_q);641 let mut chirp1 = ChirpState::new(tables.n_q);
614 chirp1.bw = vec![0.0; tables.n_q]; // priming frame at bw=0642 chirp1.bw = vec![0.0; tables.n_q]; // priming frame at bw=0
615 let mut hist1 = HfHistory::new(kx);643 let mut hist1 = HfHistory::new(kx);
@@ -617,8 +645,6 @@ mod tests {
617 chirp1.bw = vec![0.98; tables.n_q]; // preload the exact target: `update` below is then a no-op645 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);646 let out1 = generate(&frame2, &tables, &invf_high, &mut chirp1, &mut hist1);
619 let dst1 = &out1[14 - kx];647 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) {648 for (n, &y) in dst1.iter().enumerate().skip(4) {
623 let expect = x[30 + n];649 let expect = x[30 + n];
624 if expect.abs() < 1e-6 {650 if expect.abs() < 1e-6 {
@@ -626,7 +652,7 @@ mod tests {
626 }652 }
627 let ratio = y.re / expect;653 let ratio = y.re / expect;
628 assert!(654 assert!(
629- (1.0..2.1).contains(&ratio),655+ (0.5..1.5).contains(&ratio),
630 "bw=0.98 ratio out of range at n={n}: ratio={ratio} y={y:?} x={expect}"656 "bw=0.98 ratio out of range at n={n}: ratio={ratio} y={y:?} x={expect}"
631 );657 );
632 assert!(658 assert!(