diff --git a/crates/ec-aac/src/sbr_hf.rs b/crates/ec-aac/src/sbr_hf.rs index cd82b12e..7699fcfe 100644 --- a/crates/ec-aac/src/sbr_hf.rs +++ b/crates/ec-aac/src/sbr_hf.rs @@ -24,14 +24,16 @@ //! //! For each *source* subband, a covariance-method order-2 LPC is fit to //! that subband's own QMF time series (two slots of carried-over history -//! plus the current frame's slots). The residual against those raw -//! coefficients is then re-synthesised through a *bandwidth-expanded* -//! all-pole filter -- coefficients scaled by `bw` and `bw^2` -- which is -//! the standard SBR "inverse filtering" trick: `bw` near 1 leaves the -//! subband's own resonance intact (a strongly tonal patch), `bw` near 0 -//! flattens it toward its whitened residual (a noise-like patch). `bw` -//! itself comes from `bs_invf_mode` and is smoothed frame to frame with a -//! fast-attack/slow-release curve so inverse-filter mode changes don't pop. +//! plus the current frame's slots), giving prediction coefficients `(a1, +//! a2)` such that `x[l] ~= a1*x[l-1] + a2*x[l-2]`. Per §4.6.18.6, the copied +//! series is then extended *feed-forward* by a bandwidth-expanded 2-tap FIR +//! built from those same coefficients: `X_high[l] = X_src[l] + bw*a1* +//! X_src[l-1] + bw^2*a2*X_src[l-2]`. This is the standard SBR "inverse +//! filtering" trick: `bw` near 1 reinforces the subband's own resonance atop +//! the raw copy (a strongly tonal patch), `bw` at 0 degenerates to the plain +//! copy (no extra tap energy at all). `bw` itself comes from `bs_invf_mode` +//! and is smoothed frame to frame with a fast-attack/slow-release curve so +//! inverse-filter mode changes don't pop. use crate::sbr_bands::BandTables; use ec_dsp::Complex; @@ -317,25 +319,27 @@ pub fn lpc2(x: &[Complex]) -> (Complex, Complex) { (a1, a2) } -/// Bounds an AR(2) predictor's coefficients so the resynthesis recursion -/// this module runs (`y = residual + ca1*y[n-1] + ca2*y[n-2]`) cannot -/// diverge. +/// Bounds an AR(2) predictor's coefficients so the feed-forward FIR +/// extension `generate` builds from them (`X_high[l] = X_src[l] + +/// bw*a1*X_src[l-1] + bw^2*a2*X_src[l-2]`) cannot blow up the copied tap +/// energy on a badly-conditioned fit. /// /// `lpc2` solves an unwindowed covariance-method normal-equation system, /// which -- unlike the autocorrelation/Levinson-Durbin method the reference /// SBR tool uses -- carries no built-in stability guarantee: on a short (32 /// QMF slot) window of a strongly resonant real-music subband it can and -/// does return a pole outside the unit circle, and the 32-sample feedback -/// loop below then grows geometrically within a single frame (observed: -/// output rms in the hundreds of thousands on real HE-AAC files, versus -/// ~0.2 for a working decode). `|a1| + |a2| < 1` is a standard sufficient -/// (if conservative) BIBO-stability bound for a direct-form-II section, so -/// clamping the pair to it whenever it is violated is a corner-cut: it -/// trades exactness on the rare unstable-estimate frame for boundedness -/// everywhere, ceiling = slightly under-resonant HF on whichever frames hit -/// the clamp; upgrade path = replace `lpc2` with the spec's own -/// Levinson-Durbin-derived reflection coefficients, which are stable by -/// construction and would make this function a no-op. +/// does return a pole outside the unit circle, driving the FIR taps to +/// unreasonably large magnitude for what should be a bounded-gain +/// extension (observed: output rms in the hundreds of thousands on real +/// HE-AAC files, versus ~0.2 for a working decode, back when this fed an +/// IIR recursion; the same unstable estimate still over-weights the taps +/// here). `|a1| + |a2| < 1` is a standard sufficient (if conservative) +/// bound, so clamping the pair to it whenever it is violated is a +/// corner-cut: it trades exactness on the rare unstable-estimate frame for +/// boundedness everywhere, ceiling = slightly under-resonant HF on +/// whichever frames hit the clamp; upgrade path = replace `lpc2` with the +/// spec's own Levinson-Durbin-derived reflection coefficients, which are +/// stable by construction and would make this function a no-op. fn stabilize(coeffs: (Complex, Complex)) -> (Complex, Complex) { let (a1, a2) = coeffs; let mag = a1.norm_sqr().sqrt() + a2.norm_sqr().sqrt(); @@ -349,20 +353,19 @@ fn stabilize(coeffs: (Complex, Complex)) -> (Complex, Complex; 2]>, - y: Vec<[Complex; 2]>, } impl HfHistory { pub fn new(bands: usize) -> HfHistory { HfHistory { x: vec![[Complex::ZERO; 2]; bands], - y: vec![[Complex::ZERO; 2]; bands], } } } @@ -425,13 +428,18 @@ pub fn generate( if std::env::var("EC_AAC_SBR_BW_DUMP").is_ok() { eprintln!("BW_DUMP target_band={target_band} source_band={source_band} bw={g:.6}"); } + // (Round-48, Task 3) §4.6.18.6 feed-forward extension: `X_high[l] + // = X_src[l] + bw*a1*X_src[l-1] + bw^2*a2*X_src[l-2]`. `a1`/`a2` + // are used directly (not negated): `lpc2` returns them in the + // "predicts forward" convention (`x[l] ~= a1*x[l-1] + + // a2*x[l-2]`, pinned by `lpc_recovers_the_poles_of_a_synthetic_ + // ar2_process`), so applying them unnegated to the raw copy + // continues the source subband's own AR resonance into the + // patched band -- `bw` at 1 is maximally tonal, `bw` at 0 + // degenerates the whole tap to zero, leaving the plain copy + // (see `feed_forward_extension_matches_bw_endpoints`). let ca1 = a1.scale(g); let ca2 = a2.scale(g * g); - let (mut y_prev1, mut y_prev2) = if source_band < history.y.len() { - (history.y[source_band][1], history.y[source_band][0]) - } else { - (Complex::ZERO, Complex::ZERO) - }; let (mut x_prev1, mut x_prev2) = if source_band < history.x.len() { (history.x[source_band][1], history.x[source_band][0]) } else { @@ -439,8 +447,6 @@ pub fn generate( }; let dst = &mut out[target_band - kx]; for (n, &x) in series.iter().enumerate() { - let residual = x - a1 * x_prev1 - a2 * x_prev2; - let y = residual + ca1 * y_prev1 + ca2 * y_prev2; // Round-37 (Task 2): `band_shift_correction` is proven exact // in isolation (a stationary tone replayed through this // patch-copy site lands within a couple of FFT bins of its @@ -454,11 +460,9 @@ pub fn generate( // on ch0). The reference apparently exhibits this bank's own // "wrong" cross-band placement convention, so matching it is // the bar: `dst` stays the plain, uncorrected copy. - dst[n] = y; + dst[n] = x + ca1 * x_prev1 + ca2 * x_prev2; x_prev2 = x_prev1; x_prev1 = x; - y_prev2 = y_prev1; - y_prev1 = y; } } } @@ -471,9 +475,6 @@ pub fn generate( } let n = series.len(); history.x[band] = [series[n - 2], series[n - 1]]; - // y-history only meaningfully advances for bands a patch actually - // wrote; untouched bands hold their input as a neutral seed. - history.y[band] = [series[n - 2], series[n - 1]]; } out @@ -552,4 +553,86 @@ mod tests { "fall {fall_step} rise {rise_step}" ); } + + /// (Round-48, Task 3) Pins the feed-forward extension's sign convention + /// and `bw` endpoints against the spec-shaped formula (`generate`'s own + /// doc comment): `X_high[l] = X_src[l] + bw*a1*X_src[l-1] + + /// bw^2*a2*X_src[l-2]`, `a1`/`a2` used unnegated. + /// + /// Drives a *noiseless* AR(2) source (`x[n] = a1*x[n-1] + a2*x[n-2]` + /// exactly, `|a1|+|a2| = 0.9 < 0.999` so `stabilize` never clamps) through + /// two consecutive frames so the second frame's history/LPC fit is on + /// data that satisfies the recurrence exactly end to end. At `bw=0` + /// (`bs_invf_mode` OFF) the extension must degenerate to the plain copy. + /// At `bw` near 1 (`bs_invf_mode` HIGH, `BW_TABLE[3] = 0.98`), since the + /// noiseless source satisfies `a1*x[l-1] + a2*x[l-2] == x[l]` exactly, + /// the correct (unnegated) convention algebraically collapses to + /// `y[l] ~= (1 + bw) * x[l] ~= 1.98 * x[l]` -- strictly *more* tonal + /// (same phase, amplified), not attenuated or inverted the way the + /// negated convention would produce (`y[l] ~= (1 - bw) * x[l] ~= 0.02 * + /// x[l]`, nearly cancelling the signal). This directly discriminates the + /// two sign conventions, not just "some nonzero tap fired". + #[test] + fn feed_forward_extension_matches_bw_endpoints() { + let tables = real_file_tables(); + let kx = tables.kx as usize; + let a1 = 0.6f64; + let a2 = -0.3f64; + let total = 60usize; + let mut x = vec![1.0f64, 0.5]; + for _ in 2..total { + let n = x.len(); + x.push(a1 * x[n - 1] + a2 * x[n - 2]); + } + let make_low_cur = |chunk: &[f64]| -> Vec>> { + let mut low = vec![vec![Complex::ZERO; chunk.len()]; kx]; + low[0] = chunk.iter().map(|&v| Complex::new(v, 0.0)).collect(); + low + }; + let frame1 = make_low_cur(&x[0..30]); + let frame2 = make_low_cur(&x[30..60]); + let invf_off = vec![0u8; tables.n_q]; + let invf_high = vec![3u8; tables.n_q]; + + // bw = 0: extension is an exact plain copy. + let mut chirp0 = ChirpState::new(tables.n_q); + let mut hist0 = HfHistory::new(kx); + let _ = generate(&frame1, &tables, &invf_off, &mut chirp0, &mut hist0); + let out0 = generate(&frame2, &tables, &invf_off, &mut chirp0, &mut hist0); + let dst0 = &out0[14 - kx]; // target band 14, patch (0,14,14) offset 0 + for (n, &y) in dst0.iter().enumerate() { + let expect = x[30 + n]; + assert!( + (y.re - expect).abs() < 1e-9 && y.im.abs() < 1e-9, + "bw=0 mismatch at n={n}: {y:?} vs {expect}" + ); + } + + // bw ~= 0.98: reinforces the source's own resonance, ~1.98x, same + // phase -- not the ~0.02x a negated convention would produce. + let mut chirp1 = ChirpState::new(tables.n_q); + chirp1.bw = vec![0.0; tables.n_q]; // priming frame at bw=0 + let mut hist1 = HfHistory::new(kx); + let _ = generate(&frame1, &tables, &invf_off, &mut chirp1, &mut hist1); + chirp1.bw = vec![0.98; tables.n_q]; // preload the exact target: `update` below is then a no-op + let out1 = generate(&frame2, &tables, &invf_high, &mut chirp1, &mut hist1); + let dst1 = &out1[14 - kx]; + // Skip the first couple of slots (LPC fit needs the history to + // settle); check the steady-state ratio on the rest. + for (n, &y) in dst1.iter().enumerate().skip(4) { + let expect = x[30 + n]; + if expect.abs() < 1e-6 { + continue; + } + let ratio = y.re / expect; + assert!( + (1.0..2.1).contains(&ratio), + "bw=0.98 ratio out of range at n={n}: ratio={ratio} y={y:?} x={expect}" + ); + assert!( + y.im.abs() < 0.05 * expect.abs().max(1e-6), + "unexpected imaginary part at n={n}: {y:?}" + ); + } + } } diff --git a/crates/ec-aac/tests/sbr_real_library.rs b/crates/ec-aac/tests/sbr_real_library.rs index bf898173..9f696c44 100644 --- a/crates/ec-aac/tests/sbr_real_library.rs +++ b/crates/ec-aac/tests/sbr_real_library.rs @@ -1333,17 +1333,26 @@ fn qmf_domain_spec(o: &[f32], t: &[f32]) -> (QmfBandSlots, QmfBandSlots, QmfBand (o_spec, t_spec, sim_spec) } -fn hf_patch_simulator_qmf(o: &[f32], t: &[f32]) -> (BandCoherenceTable, BandCoherenceTable) { +/// Returns `(sim-vs-reference, sim-vs-ours, ours-vs-reference)` -- the last +/// pairing (round-48, Task 4a) is the ultimate content-match witness: how +/// well our actual HF QMF content agrees with the reference's, with no +/// simulator in between. +fn hf_patch_simulator_qmf( + o: &[f32], + t: &[f32], +) -> (BandCoherenceTable, BandCoherenceTable, BandCoherenceTable) { use ec_aac::sbr_qmf::SYNTHESIS_BANDS; const WIN: usize = 16; let (o_spec, t_spec, sim_spec) = qmf_domain_spec(o, t); let slots = sim_spec.first().map(Vec::len).unwrap_or(0); if slots < WIN { - return (Vec::new(), Vec::new()); + return (Vec::new(), Vec::new(), Vec::new()); } let top_band = 43.min(SYNTHESIS_BANDS); let windows = slots / WIN; - let band_coherence = |target: &[Vec>]| -> Vec<(usize, f64)> { + let band_coherence = |source: &[Vec>], + target: &[Vec>]| + -> Vec<(usize, f64)> { (14..top_band) .map(|band| { let mut cross_re = 0.0f64; @@ -1353,7 +1362,7 @@ fn hf_patch_simulator_qmf(o: &[f32], t: &[f32]) -> (BandCoherenceTable, BandCohe for w in 0..windows { let lo = w * WIN; let hi = lo + WIN; - let se: f64 = sim_spec[band][lo..hi] + let se: f64 = source[band][lo..hi] .iter() .map(|c| c.re * c.re + c.im * c.im) .sum(); @@ -1366,7 +1375,7 @@ fn hf_patch_simulator_qmf(o: &[f32], t: &[f32]) -> (BandCoherenceTable, BandCohe } let scale = (te / se).sqrt(); for i in lo..hi { - let sc = sim_spec[band][i].scale(scale); + let sc = source[band][i].scale(scale); let tc = target[band][i]; let cross = sc * tc.conj(); cross_re += cross.re; @@ -1385,7 +1394,11 @@ fn hf_patch_simulator_qmf(o: &[f32], t: &[f32]) -> (BandCoherenceTable, BandCohe }) .collect() }; - (band_coherence(&t_spec), band_coherence(&o_spec)) + ( + band_coherence(&sim_spec, &t_spec), + band_coherence(&sim_spec, &o_spec), + band_coherence(&o_spec, &t_spec), + ) } /// (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 /// bandwidth-expanded LPC coefficients: near `(1,0,0)` means "reference is /// also just a plain copy here", taps with real weight on lag 1/2 mean a /// genuine order-2 transformation is present. +/// `target_is_ours`: fit against our own decode (`o_spec`) instead of the +/// reference's (`t_spec`) -- same `sim` (built from the reference's own low +/// band either way), so the two calls' fitted taps are directly comparable: +/// what transform sim would need to become ours vs. to become the reference. #[allow(clippy::needless_range_loop)] // fixed 3x3 complex Gaussian elimination, index math throughout fn hf_patch_transfer_fit( o: &[f32], t: &[f32], bands: &[usize], + target_is_ours: bool, ) -> Vec<(usize, [ec_dsp::Complex; 3])> { - let (_, t_spec, sim_spec) = qmf_domain_spec(o, t); + let (o_spec, t_spec, sim_spec) = qmf_domain_spec(o, t); + let target_spec = if target_is_ours { &o_spec } else { &t_spec }; let mut results = Vec::new(); for &band in bands { if band >= sim_spec.len() { continue; } let sim_raw = &sim_spec[band]; - let ref_raw = &t_spec[band]; + let ref_raw = &target_spec[band]; let len = sim_raw.len().min(ref_raw.len()); if len < 8 { continue; @@ -2254,7 +2273,7 @@ fn sbr_real_library_matches_reference() { if std::env::var("EC_AAC_SBR_QMF_WITNESS").is_ok() && n >= 4_096 { let win = &o[oa..oa + n]; let twin = &t[ob..ob + n]; - let (vs_ref, vs_ours) = hf_patch_simulator_qmf(win, twin); + let (vs_ref, vs_ours, ours_vs_ref) = hf_patch_simulator_qmf(win, twin); let mean_in = |rows: &[(usize, f64)], lo: usize, hi: usize| { let vals: Vec = rows .iter() @@ -2285,14 +2304,37 @@ fn sbr_real_library_matches_reference() { mean_in(&vs_ours, 14, 28), mean_in(&vs_ours, 28, 43) ); + // (Round-48, Task 4a) the ultimate content-match witness: + // our HF QMF content directly against the reference's, no + // simulator step in between. + println!(" ch{ch} QMF-WITNESS ours-vs-REFERENCE per-band coherence (band, coh):"); + for (b, coh) in &ours_vs_ref { + println!(" band{b:>3}: {coh:.4}"); + } + println!( + " ch{ch} QMF-WITNESS ours-vs-REFERENCE mean: even-gap[14,28)={:.4} odd-gap[28,43)={:.4}", + mean_in(&ours_vs_ref, 14, 28), + mean_in(&ours_vs_ref, 28, 43) + ); // (Round-46, Task 2) fitted sim-to-reference transfer, one // representative band per patch plus a spread across the // strong odd-gap patch (3,28,11) where the QMF witness shows // sim-vs-reference clearing 0.5. let fit_bands = [14, 18, 22, 26, 28, 30, 32, 34, 36, 38, 39, 42]; - let fits = hf_patch_transfer_fit(win, twin, &fit_bands); + let fits_ref = hf_patch_transfer_fit(win, twin, &fit_bands, false); println!(" ch{ch} TASK2 FIT ref[l]~=a0*sim[l]+a1*sim[l-1]+a2*sim[l-2]:"); - for (b, a) in &fits { + for (b, a) in &fits_ref { + println!( + " band{b:>3}: a0=({:>7.3},{:>7.3}) a1=({:>7.3},{:>7.3}) a2=({:>7.3},{:>7.3})", + a[0].re, a[0].im, a[1].re, a[1].im, a[2].re, a[2].im + ); + } + // (Round-48, Task 2) same fit, target = ours: side by side + // with the above shows exactly what our transform does to + // the plain copy vs what the reference's does. + let fits_ours = hf_patch_transfer_fit(win, twin, &fit_bands, true); + println!(" ch{ch} TASK2 FIT ours[l]~=a0*sim[l]+a1*sim[l-1]+a2*sim[l-2]:"); + for (b, a) in &fits_ours { println!( " band{b:>3}: a0=({:>7.3},{:>7.3}) a1=({:>7.3},{:>7.3}) a2=({:>7.3},{:>7.3})", a[0].re, a[0].im, a[1].re, a[1].im, a[2].re, a[2].im