Sbr_hf::generate back to all-pole residual resynthesis, measurement over recall
Browse files at this commitfee35a82feb4b34a5940e95188574aab86c0d0ffParent: dd00c7c- revert
- sbr_hf::generate back to all-pole residual resynthesis, measurement over recall
1 changed file +94 -68
- crates/ec-aac/src/sbr_hf.rs +94 -68
crates/ec-aac/src/sbr_hf.rsmodified+94 -68
| @@ -24,16 +24,31 @@ | ||
| 24 | 24 | //! |
| 25 | 25 | //! For each *source* subband, a covariance-method order-2 LPC is fit to |
| 26 | 26 | //! 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. | |
| 37 | 52 | |
| 38 | 53 | use crate::sbr_bands::BandTables; |
| 39 | 54 | use ec_dsp::Complex; |
| @@ -319,27 +334,25 @@ pub fn lpc2(x: &[Complex<f64>]) -> (Complex<f64>, Complex<f64>) { | ||
| 319 | 334 | (a1, a2) |
| 320 | 335 | } |
| 321 | 336 | |
| 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. | |
| 326 | 340 | /// |
| 327 | 341 | /// `lpc2` solves an unwindowed covariance-method normal-equation system, |
| 328 | 342 | /// which -- unlike the autocorrelation/Levinson-Durbin method the reference |
| 329 | 343 | /// SBR tool uses -- carries no built-in stability guarantee: on a short (32 |
| 330 | 344 | /// 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. | |
| 343 | 356 | fn stabilize(coeffs: (Complex<f64>, Complex<f64>)) -> (Complex<f64>, Complex<f64>) { |
| 344 | 357 | let (a1, a2) = coeffs; |
| 345 | 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]`, | |
| 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. | |
| 360 | 372 | #[derive(Clone, Debug)] |
| 361 | 373 | pub struct HfHistory { |
| 362 | 374 | x: Vec<[Complex<f64>; 2]>, |
| 375 | + y: Vec<[Complex<f64>; 2]>, | |
| 363 | 376 | } |
| 364 | 377 | |
| 365 | 378 | impl HfHistory { |
| 366 | 379 | pub fn new(bands: usize) -> HfHistory { |
| 367 | 380 | HfHistory { |
| 368 | 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 | 442 | if std::env::var("EC_AAC_SBR_BW_DUMP").is_ok() { |
| 429 | 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 | 445 | let ca1 = a1.scale(g); |
| 442 | 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 | 452 | let (mut x_prev1, mut x_prev2) = if source_band < history.x.len() { |
| 444 | 453 | (history.x[source_band][1], history.x[source_band][0]) |
| 445 | 454 | } else { |
| @@ -447,6 +456,8 @@ pub fn generate( | ||
| 447 | 456 | }; |
| 448 | 457 | let dst = &mut out[target_band - kx]; |
| 449 | 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 | 461 | // Round-37 (Task 2): `band_shift_correction` is proven exact |
| 451 | 462 | // in isolation (a stationary tone replayed through this |
| 452 | 463 | // patch-copy site lands within a couple of FFT bins of its |
| @@ -460,9 +471,11 @@ pub fn generate( | ||
| 460 | 471 | // on ch0). The reference apparently exhibits this bank's own |
| 461 | 472 | // "wrong" cross-band placement convention, so matching it is |
| 462 | 473 | // the bar: `dst` stays the plain, uncorrected copy. |
| 463 | - dst[n] = x + ca1 * x_prev1 + ca2 * x_prev2; | |
| 474 | + dst[n] = y; | |
| 464 | 475 | x_prev2 = x_prev1; |
| 465 | 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 | 489 | let n = series.len(); |
| 477 | 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 | 496 | 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 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. | |
| 561 | 581 | /// |
| 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. | |
| 575 | 600 | #[test] |
| 576 | - fn feed_forward_extension_matches_bw_endpoints() { | |
| 601 | + fn all_pole_resynthesis_matches_bw_endpoints() { | |
| 577 | 602 | let tables = real_file_tables(); |
| 578 | 603 | let kx = tables.kx as usize; |
| 579 | 604 | let a1 = 0.6f64; |
| @@ -594,22 +619,25 @@ mod tests { | ||
| 594 | 619 | let invf_off = vec![0u8; tables.n_q]; |
| 595 | 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 | 623 | let mut chirp0 = ChirpState::new(tables.n_q); |
| 599 | 624 | let mut hist0 = HfHistory::new(kx); |
| 600 | 625 | let _ = generate(&frame1, &tables, &invf_off, &mut chirp0, &mut hist0); |
| 601 | 626 | let out0 = generate(&frame2, &tables, &invf_off, &mut chirp0, &mut hist0); |
| 602 | 627 | 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 | 629 | let expect = x[30 + n]; |
| 630 | + if expect.abs() < 1e-6 { | |
| 631 | + continue; | |
| 632 | + } | |
| 605 | 633 | 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}" | |
| 608 | 636 | ); |
| 609 | 637 | } |
| 610 | 638 | |
| 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. | |
| 613 | 641 | let mut chirp1 = ChirpState::new(tables.n_q); |
| 614 | 642 | chirp1.bw = vec![0.0; tables.n_q]; // priming frame at bw=0 |
| 615 | 643 | let mut hist1 = HfHistory::new(kx); |
| @@ -617,8 +645,6 @@ mod tests { | ||
| 617 | 645 | chirp1.bw = vec![0.98; tables.n_q]; // preload the exact target: `update` below is then a no-op |
| 618 | 646 | let out1 = generate(&frame2, &tables, &invf_high, &mut chirp1, &mut hist1); |
| 619 | 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 | 648 | for (n, &y) in dst1.iter().enumerate().skip(4) { |
| 623 | 649 | let expect = x[30 + n]; |
| 624 | 650 | if expect.abs() < 1e-6 { |
| @@ -626,7 +652,7 @@ mod tests { | ||
| 626 | 652 | } |
| 627 | 653 | let ratio = y.re / expect; |
| 628 | 654 | assert!( |
| 629 | - (1.0..2.1).contains(&ratio), | |
| 655 | + (0.5..1.5).contains(&ratio), | |
| 630 | 656 | "bw=0.98 ratio out of range at n={n}: ratio={ratio} y={y:?} x={expect}" |
| 631 | 657 | ); |
| 632 | 658 | assert!( |