forge
Explore
Log in

Don't you dare go Hollow

Spec covariance alpha + feed-forward HF generator + spec chirp table/smoothing

Browse files at this commit

7cb600080c2fbe8fe38412d5633d8b2c602c34e6Ahmet Kaan GümüşParent: b966d5e
  • fix
    • spec covariance alpha + feed-forward HF generator + spec chirp table/smoothing
Show full message
fix(aac-sbr): spec covariance alpha + feed-forward HF generator + spec chirp table/smoothing

Root cause of the HE-AAC HF mismatch was three sign/direction errors in
sbr_hf.rs that partially cancelled:

1. The HF generator was a recursive all-pole resynthesis (y = residual +
   bw*a1*y[l-1] + bw^2*a2*y[l-2]) whose bw mapping is INVERTED relative to
   4.6.18.6.3: bw=0 whitened fully, bw=0.98 was ~a plain copy. The earlier
   feed-forward attempt (8bc305b) measured worse because it used the
   predictor sign (+a) instead of the spec's prediction-error sign; the
   spec's alpha = -(predictor coeffs). Now: covariance-method alpha per
   4.6.18.6.2 (phi(i,j) = sum x[n-i]conj(x[n-j]) over 6 overlap + frame
   slots, |alpha|>=4 guard) and X_high = X_low + bw*alpha0*X_low[l-1] +
   bw^2*alpha1*X_low[l-2]. Verified on a synthetic complex AR(2) (numpy
   witness, scratch) and lpc_recovers_the_poles_of_a_synthetic_ar2_process.
2. Chirp smoothing's rising branch had its operands swapped (0.09375 of the
   new value instead of 0.90625), making every rise ~10x too slow.
3. Chirp target table was flat [0,0.6,0.9,0.98]; spec Table 4.163 depends on
   the previous mode (LOW=0.75 steady, 0.6 only on OFF<->LOW transitions),
   plus the <0.015 -> 0 floor.

reeln vs reference (lag 385, at_edge=false): ch0 0.987529 -> 0.992732,
ch1 0.986560 -> 0.991760 (above 5 kHz: 0.974 -> 0.987 / 0.980 -> 0.992).
synthetic_heaac_matrix 'above' column >= baseline on all 8 HE rows
(e.g. 48000/48k 0.9926 -> 0.9941). AAC-LC rows unchanged (1.0000/0.9999).
Still short of the 0.999 bar; residual is diffuse HF (no local collapse
after t=0.5 s) and persists even with bw forced to 0.98 everywhere.
crates/ec-aac/src/sbr_hf.rsmodified+121 -177
@@ -221,9 +221,21 @@ pub fn limiter_band_table(tables: &BandTables, patches: &[Patch], limiter_bands:
221221 out
222222 }
223223
224-/// `bs_invf_mode` bandwidth-expansion targets (OFF, LOW, MID, HIGH), the
225-/// four inverse-filtering strengths §4.6.18.6.2 defines.
226-const BW_TABLE: [f64; 4] = [0.0, 0.6, 0.9, 0.98];
224+/// `bs_invf_mode` chirp targets per ISO 14496-3 4.6.18.6.3 (Table 4.163):
225+/// the target depends on the current AND previous frame's mode --
226+/// OFF is 0.0 except 0.6 when falling from LOW; LOW is 0.75 except 0.6
227+/// when rising from OFF; MID 0.9; HIGH 0.98. The previous flat table
228+/// (`[0, 0.6, 0.9, 0.98]`) under-whitened every steady-state LOW band.
229+fn bw_target(mode: u8, prev_mode: u8) -> f64 {
230+ match (mode, prev_mode) {
231+ (0, 1) => 0.6,
232+ (0, _) => 0.0,
233+ (1, 0) => 0.6,
234+ (1, _) => 0.75,
235+ (2, _) => 0.9,
236+ _ => 0.98,
237+ }
238+}
227239
228240 /// Per-noise-band chirp factor state, smoothed frame to frame with a
229241 /// fast-attack (toward a *lower* bw, i.e. more whitening) / slow-release
@@ -231,18 +243,22 @@ const BW_TABLE: [f64; 4] = [0.0, 0.6, 0.9, 0.98];
231243 #[derive(Clone, Debug)]
232244 pub struct ChirpState {
233245 bw: Vec<f64>,
246+ prev_mode: Vec<u8>,
234247 }
235248
236249 impl ChirpState {
237250 pub fn new(n_q: usize) -> ChirpState {
238- ChirpState { bw: vec![0.0; n_q] }
251+ ChirpState {
252+ bw: vec![0.0; n_q],
253+ prev_mode: vec![0; n_q],
254+ }
239255 }
240256
241257 /// Advances the state one frame given this frame's `bs_invf_mode` per
242258 /// noise band, returning the smoothed bw to use for HF generation.
243259 ///
244260 /// (Round-22 sweep instrumentation, zero cost unset) `EC_AAC_SBR_BW_SCALE`
245- /// scales `BW_TABLE`'s target globally (clamped below 1.0) before
261+ /// scales the chirp target globally (clamped below 1.0) before
246262 /// smoothing, to probe whether the chirp/inverse-filter strength is
247263 /// miscalibrated on real content. `EC_AAC_SBR_CHIRP_SMOOTH=none` skips
248264 /// the attack/release smoothing entirely (target used immediately);
@@ -251,15 +267,20 @@ impl ChirpState {
251267 pub fn update(&mut self, invf_mode: &[u8]) -> &[f64] {
252268 let scale = bw_scale_override();
253269 let smooth = chirp_smooth_mode();
254- for (slot, &mode) in self.bw.iter_mut().zip(invf_mode) {
255- let target = (BW_TABLE[usize::from(mode).min(3)] * scale).min(0.999_999);
270+ for ((slot, prev), &mode) in self.bw.iter_mut().zip(&mut self.prev_mode).zip(invf_mode) {
271+ let target = (bw_target(mode, *prev) * scale).min(0.999_999);
272+ *prev = mode;
256273 *slot = match smooth {
257274 ChirpSmooth::None => target,
258275 ChirpSmooth::Current => {
276+ // 4.6.18.6.3 bwArray smoothing: both branches weight the
277+ // NEW value (0.75 falling, 0.90625 rising). The rising
278+ // branch previously had the operands swapped (0.09375
279+ // of the new value), making every rise ~10x too slow.
259280 if target < *slot {
260281 0.75 * target + 0.25 * *slot
261282 } else {
262- 0.90625 * *slot + 0.09375 * target
283+ 0.90625 * target + 0.09375 * *slot
263284 }
264285 }
265286 ChirpSmooth::Swap => {
@@ -270,12 +291,16 @@ impl ChirpState {
270291 }
271292 }
272293 };
294+ // 4.6.18.6.3: a smoothed bw under 0.015 is forced to zero.
295+ if *slot < 0.015 {
296+ *slot = 0.0;
297+ }
273298 }
274299 &self.bw
275300 }
276301 }
277302
278-/// `EC_AAC_SBR_BW_SCALE` global multiplier on `BW_TABLE`, clamped below 1.0
303+/// `EC_AAC_SBR_BW_SCALE` global multiplier on the chirp target, clamped below 1.0
279304 /// (a chirp target at or past 1.0 is an undamped all-pole resonance, not a
280305 /// meaningful "stronger" whitening). `1.0` (no-op) when unset or unparsable.
281306 fn bw_scale_override() -> f64 {
@@ -301,95 +326,45 @@ fn chirp_smooth_mode() -> ChirpSmooth {
301326 }
302327 }
303328
304-/// Order-2 covariance-method LPC over `x` (index 0 is the oldest sample):
305-/// solves the 2x2 normal equations minimizing `sum |x[n] - a1*x[n-1] -
306-/// a2*x[n-2]|^2` over `n = 2..x.len()`. Returns `(a1, a2)`; `(0, 0)` if `x`
307-/// is too short or the system is singular (silence or a near-constant
308-/// subband, both of which need no prediction).
309-/// (Round-57) AR(2) coefficients via the Yule-Walker/autocorrelation
310-/// method (`r(k) = sum_n x[n]*conj(x[n-k])`, Hermitian-Toeplitz `R`),
311-/// replacing the previous unwindowed covariance-method normal-equation
312-/// solve. The autocorrelation matrix is always positive semi-definite,
313-/// which is what gives Levinson-Durbin-style AR fits their built-in
314-/// BIBO-stability guarantee (poles inside or on the unit circle) -- the
315-/// covariance method has no such guarantee and was measured producing
316-/// resonant poles that blow `cur` (the raw HF estimate energy) up to
317-/// 1e7-1e11 against a ~1e4 transmitted target on real content
318-/// (heaac_48000_64k.m4a's crossover-straddling sweep window), which then
319-/// poisons the WHOLE limiter band's aggregate `E_curr` (4.6.18.7.5) and
320-/// crushes every other cell sharing that band's gain cap, not just the
321-/// outlier cell itself (round-56's stabilize-bound tightening measured
322-/// zero effect because `raw_gain=sqrt(target/cur)` cancels `cur` exactly
323-/// for the outlier cell's OWN gain -- it never reaches the neighbors this
324-/// aggregate-poisoning does).
329+/// Order-2 linear-prediction coefficients per ISO 14496-3 4.6.18.6.2
330+/// (covariance method, `phi(i,j) = sum_n x[n-i]*conj(x[n-j])` over
331+/// `n = 2..x.len()`, index 0 of `x` is the oldest slot). Returns the spec's
332+/// `(alpha0, alpha1)` -- the PREDICTION-ERROR filter taps, i.e. the
333+/// negated predictor coefficients: for `x[n] = a1*x[n-1] + a2*x[n-2] + e`
334+/// this yields `(-a1, -a2)`, so `x + alpha0*x[n-1] + alpha1*x[n-2]`
335+/// whitens. `(0, 0)` on degenerate input or when either |alpha| >= 4
336+/// (spec guard). Witness: scratch `alpha/witness.py` (numpy) recovers a
337+/// synthetic complex AR(2) with this sign convention and whitens at bw=1.
325338 pub fn lpc2(x: &[Complex<f64>]) -> (Complex<f64>, Complex<f64>) {
326339 if x.len() < 3 {
327340 return (Complex::ZERO, Complex::ZERO);
328341 }
329- let mut r0 = 0.0f64;
330- let mut r1 = Complex::ZERO;
331- let mut r2 = Complex::ZERO;
332- for n in 0..x.len() {
333- r0 += x[n].norm_sqr();
334- if n >= 1 {
335- r1 = r1 + x[n] * x[n - 1].conj();
336- }
337- if n >= 2 {
338- r2 = r2 + x[n] * x[n - 2].conj();
339- }
340- }
341- // Yule-Walker: [[r0, conj(r1)], [r1, r0]] * [a1, a2]^T = [r1, r2]^T.
342- let det = r0 * r0 - r1.norm_sqr();
343- if det.abs() < 1e-20 {
344- return (Complex::ZERO, Complex::ZERO);
345- }
346- let a1 = (r1.scale(r0) - r1.conj() * r2).scale(1.0 / det);
347- let a2 = (r2.scale(r0) - r1 * r1).scale(1.0 / det);
348- (a1, a2)
349-}
350-
351-/// Bounds an AR(2) predictor's coefficients so the resynthesis recursion
352-/// this module runs (`y = residual + ca1*y[n-1] + ca2*y[n-2]`) cannot
353-/// diverge.
354-///
355-/// `lpc2` solves an unwindowed covariance-method normal-equation system,
356-/// which -- unlike the autocorrelation/Levinson-Durbin method the reference
357-/// SBR tool uses -- carries no built-in stability guarantee: on a short (32
358-/// QMF slot) window of a strongly resonant real-music subband it can and
359-/// does return a pole outside the unit circle, and the 32-sample feedback
360-/// loop below then grows geometrically within a single frame (observed:
361-/// output rms in the hundreds of thousands on real HE-AAC files, versus
362-/// ~0.2 for a working decode). `|a1| + |a2| < 1` is a standard sufficient
363-/// (if conservative) BIBO-stability bound for a direct-form-II section, so
364-/// clamping the pair to it whenever it is violated is a corner-cut: it
365-/// trades exactness on the rare unstable-estimate frame for boundedness
366-/// everywhere, ceiling = slightly under-resonant HF on whichever frames hit
367-/// the clamp; upgrade path = replace `lpc2` with the spec's own
368-/// Levinson-Durbin-derived reflection coefficients, which are stable by
369-/// construction and would make this function a no-op.
370-fn stabilize(coeffs: (Complex<f64>, Complex<f64>)) -> (Complex<f64>, Complex<f64>) {
371- let (a1, a2) = coeffs;
372- let mag = a1.norm_sqr().sqrt() + a2.norm_sqr().sqrt();
373- // (Round-56) Tried tightening this bound to 0.9 on the theory that a
374- // pole at 0.999 gives ~1e6x power resonant gain (`~1/(1-r)^2`), which
375- // `EC_AAC_SBR_CELLDUMP` traces do show happening (`cur`, the raw
376- // pre-gain HF estimate, reaching 1e7-1e11 against a ~1e4 transmitted
377- // target on heaac_48000_64k.m4a's crossover-straddling sweep window,
378- // in the SAME limiter band as starved neighbor cells) -- measured
379- // ZERO effect on the t=18s/24s corr cliff (0.054601->0.054536,
380- // 0.058942->0.058797) or the `EC_AAC_SBR_HF_BYPASS` A/B, because
381- // `raw_gain = sqrt(target/cur)` cancels `cur` exactly for any
382- // non-capped cell regardless of this bound's value -- reverted, no
383- // measured benefit to justify the regression risk on frames that
384- // legitimately need resonance near this bound. Left at `0.999`.
385- if mag > 0.999 && mag.is_finite() {
386- let s = 0.999 / mag;
387- (a1.scale(s), a2.scale(s))
388- } else if mag.is_finite() {
389- (a1, a2)
342+ let phi = |i: usize, j: usize| -> Complex<f64> {
343+ (2..x.len()).fold(Complex::ZERO, |acc, n| acc + x[n - i] * x[n - j].conj())
344+ };
345+ let p11 = phi(1, 1).re;
346+ let p22 = phi(2, 2).re;
347+ let p01 = phi(0, 1);
348+ let p02 = phi(0, 2);
349+ let p12 = phi(1, 2);
350+ const EPS: f64 = 1e-6;
351+ let d = p22 * p11 - p12.norm_sqr() / (1.0 + EPS);
352+ let alpha1 = if d.abs() < 1e-30 {
353+ Complex::ZERO
390354 } else {
391- (Complex::ZERO, Complex::ZERO)
355+ (p01 * p12 - p02.scale(p11)).scale(1.0 / d)
356+ };
357+ let alpha0 = if p11.abs() < 1e-30 {
358+ Complex::ZERO
359+ } else {
360+ (p01 + alpha1 * p12.conj()).scale(-1.0 / p11)
361+ };
362+ let m0 = alpha0.norm_sqr();
363+ let m1 = alpha1.norm_sqr();
364+ if !(m0 < 16.0 && m1 < 16.0) {
365+ return (Complex::ZERO, Complex::ZERO);
392366 }
367+ (alpha0, alpha1)
393368 }
394369
395370 /// Per-source-subband history: the last two QMF slots, carried across
@@ -397,15 +372,18 @@ fn stabilize(coeffs: (Complex<f64>, Complex<f64>)) -> (Complex<f64>, Complex<f64
397372 /// frame boundaries instead of restarting cold every frame.
398373 #[derive(Clone, Debug)]
399374 pub struct HfHistory {
400- x: Vec<[Complex<f64>; 2]>,
401- y: Vec<[Complex<f64>; 2]>,
375+ /// Last `HIST` slots per source band (4.6.18.6.2's covariance window
376+ /// spans the frame plus the 6 overlap slots before it; the filter
377+ /// itself only taps the last two).
378+ x: Vec<[Complex<f64>; HIST]>,
402379 }
403380
381+const HIST: usize = 6;
382+
404383 impl HfHistory {
405384 pub fn new(bands: usize) -> HfHistory {
406385 HfHistory {
407- x: vec![[Complex::ZERO; 2]; bands],
408- y: vec![[Complex::ZERO; 2]; bands],
386+ x: vec![[Complex::ZERO; HIST]; bands],
409387 }
410388 }
411389 }
@@ -448,17 +426,15 @@ pub fn generate(
448426 continue;
449427 }
450428 let series = &low_cur[source_band];
451- let (a1, a2) = {
452- let mut ext = Vec::with_capacity(num_slots + 2);
429+ let (alpha0, alpha1) = {
430+ let mut ext = Vec::with_capacity(num_slots + HIST);
453431 if source_band < history.x.len() {
454- ext.push(history.x[source_band][0]);
455- ext.push(history.x[source_band][1]);
432+ ext.extend_from_slice(&history.x[source_band]);
456433 } else {
457- ext.push(Complex::ZERO);
458- ext.push(Complex::ZERO);
434+ ext.resize(HIST, Complex::ZERO);
459435 }
460436 ext.extend_from_slice(series);
461- stabilize(lpc2(&ext))
437+ lpc2(&ext)
462438 };
463439 let g = bw[noise_band_of(target_band)];
464440 // (Round-46, Task 2) `EC_AAC_SBR_BW_DUMP` -- one line per patched
@@ -468,40 +444,35 @@ pub fn generate(
468444 if std::env::var("EC_AAC_SBR_BW_DUMP").is_ok() {
469445 eprintln!("BW_DUMP target_band={target_band} source_band={source_band} bw={g:.6}");
470446 }
471- let ca1 = a1.scale(g);
472- let ca2 = a2.scale(g * g);
473- let (mut y_prev1, mut y_prev2) = if source_band < history.y.len() {
474- (history.y[source_band][1], history.y[source_band][0])
475- } else {
476- (Complex::ZERO, Complex::ZERO)
477- };
447+ // 4.6.18.6.3 feed-forward: X_high = X_low + bw*alpha0*X_low[l-1]
448+ // + bw^2*alpha1*X_low[l-2]. bw=0 is a plain copy, bw->1 is the
449+ // full inverse (whitening) filter. The all-pole recursion this
450+ // replaced (`y = residual + bw*a1*y[l-1] + bw^2*a2*y[l-2]`) had
451+ // that mapping INVERTED (bw=0 whitened fully, bw=0.98 ~ copy),
452+ // and the earlier feed-forward attempt (8bc305b) used the
453+ // predictor sign (+a) instead of the spec's prediction-error
454+ // sign (-a), which reinforces the resonance instead of
455+ // cancelling it -- hence it measured worse than the inverted
456+ // all-pole form.
457+ let c1 = alpha0.scale(g);
458+ let c2 = alpha1.scale(g * g);
478459 let (mut x_prev1, mut x_prev2) = if source_band < history.x.len() {
479- (history.x[source_band][1], history.x[source_band][0])
460+ (
461+ history.x[source_band][HIST - 1],
462+ history.x[source_band][HIST - 2],
463+ )
480464 } else {
481465 (Complex::ZERO, Complex::ZERO)
482466 };
483467 let dst = &mut out[target_band - kx];
484468 for (n, &x) in series.iter().enumerate() {
485- let residual = x - a1 * x_prev1 - a2 * x_prev2;
486- let y = residual + ca1 * y_prev1 + ca2 * y_prev2;
487469 // Round-37 (Task 2): `band_shift_correction` is proven exact
488- // in isolation (a stationary tone replayed through this
489- // patch-copy site lands within a couple of FFT bins of its
490- // corrected absolute frequency -- see
491- // `sbr_qmf::tests::patch_replay_through_generate_preserves_absolute_frequency_mapping`)
492- // but a real-file mechanical A/B (round-36/37,
493- // `EC_AAC_SBR_PARITY_SPLIT`) shows applying it REGRESSES
494- // odd-gap coherence against the reference decoder (ch0
495- // 0.1907->0.0714, ch1 0.2461->0.0741; sign-flipped and
496- // half-rate variants both regress it too, 0.0757/0.1449 resp.
497- // on ch0). The reference apparently exhibits this bank's own
498- // "wrong" cross-band placement convention, so matching it is
499- // the bar: `dst` stays the plain, uncorrected copy.
500- dst[n] = y;
470+ // in isolation but a real-file A/B (`EC_AAC_SBR_PARITY_SPLIT`)
471+ // shows applying it REGRESSES odd-gap coherence against the
472+ // reference; `dst` stays the uncorrected band placement.
473+ dst[n] = x + c1 * x_prev1 + c2 * x_prev2;
501474 x_prev2 = x_prev1;
502475 x_prev1 = x;
503- y_prev2 = y_prev1;
504- y_prev1 = y;
505476 }
506477 }
507478 }
@@ -509,14 +480,12 @@ pub fn generate(
509480 // Every source subband's history advances regardless of whether a
510481 // patch used it this frame: the low-band QMF stream is continuous.
511482 for (band, series) in low_cur.iter().enumerate() {
512- if band >= history.x.len() || series.len() < 2 {
483+ if band >= history.x.len() {
513484 continue;
514485 }
515- let n = series.len();
516- history.x[band] = [series[n - 2], series[n - 1]];
517- // y-history only meaningfully advances for bands a patch actually
518- // wrote; untouched bands hold their input as a neutral seed.
519- history.y[band] = [series[n - 2], series[n - 1]];
486+ let h = &mut history.x[band];
487+ let keep: Vec<Complex<f64>> = h.iter().copied().chain(series.iter().copied()).collect();
488+ h.copy_from_slice(&keep[keep.len() - HIST..]);
520489 }
521490
522491 out
@@ -579,8 +548,15 @@ mod tests {
579548 // previous covariance-method solve) for a stability guarantee real
580549 // content needs -- still recovers the synthetic poles to well
581550 // within this looser bound.
582- assert!((fa1 - a1).norm_sqr().sqrt() < 0.2, "a1 {fa1:?} vs {a1:?}");
583- assert!((fa2 - a2).norm_sqr().sqrt() < 0.2, "a2 {fa2:?} vs {a2:?}");
551+ // spec alpha = negated predictor coefficients
552+ assert!(
553+ (fa1 + a1).norm_sqr().sqrt() < 0.2,
554+ "alpha0 {fa1:?} vs {a1:?}"
555+ );
556+ assert!(
557+ (fa2 + a2).norm_sqr().sqrt() < 0.2,
558+ "alpha1 {fa2:?} vs {a2:?}"
559+ );
584560 }
585561
586562 #[test]
@@ -589,7 +565,7 @@ mod tests {
589565 // Jump from OFF straight to HIGH: attack (rising bw) is the slow
590566 // (0.90625/0.09375) branch here since target > current.
591567 let after_rise = chirp.update(&[3])[0];
592- assert!(after_rise > 0.0 && after_rise < BW_TABLE[3]);
568+ assert!(after_rise > 0.0 && after_rise < 0.98);
593569 // Now drop back to OFF: release (falling bw) is the fast
594570 // (0.75/0.25) branch, so it should move further in one step than
595571 // the rise did.
@@ -603,35 +579,8 @@ mod tests {
603579 );
604580 }
605581
606- /// (Round-50) Pins the all-pole residual-resynthesis structure that
607- /// round-50's real-file A/B empirically favours over the feed-forward
608- /// FIR round-48 briefly shipped (see the module doc). Both structures
609- /// were implemented and measured against the reference decoder on real
610- /// content; this one matched closer, so it is the one pinned here --
611- /// the feed-forward alternative's own discriminating test
612- /// (`feed_forward_extension_matches_bw_endpoints`, commit 8bc305b) is
613- /// documented history, not dead code to resurrect casually.
614- ///
615- /// Drives the same noiseless AR(2) source as that alternative test
616- /// through two consecutive frames, `x[n] = a1*x[n-1] + a2*x[n-2]`
617- /// exactly, so `lpc2`'s fit recovers `(a1, a2)` closely enough that the
618- /// *residual* `x[l] - a1*x[l-1] - a2*x[l-2]` is near zero throughout.
619- /// That residual, not the raw copy, is what this structure resynthesises
620- /// through the bandwidth-expanded all-pole recursion `y[l] = residual +
621- /// ca1*y[l-1] + ca2*y[l-2]` -- the key structural difference from
622- /// feed-forward, which adds taps onto the copy instead of replacing it
623- /// with a filtered residual:
624- /// - `bw=0` (`bs_invf_mode` OFF): `ca1=ca2=0`, so `y = residual ~= 0` --
625- /// the output collapses toward silence, NOT the exact plain copy
626- /// feed-forward produces at this same setting.
627- /// - `bw~=0.98` (`bs_invf_mode` HIGH): `ca1,ca2` are close to the
628- /// original `(a1,a2)` (scaled by `bw`, `bw^2`), so with residual~=0 the
629- /// recursion nearly reproduces the source's own AR(2) resonance from
630- /// history alone -- output tracks `x` closely in magnitude and phase,
631- /// not the ~1.98x reinforcement feed-forward produces at the same
632- /// setting.
633582 #[test]
634- fn all_pole_resynthesis_matches_bw_endpoints() {
583+ fn feed_forward_matches_bw_endpoints() {
635584 let tables = real_file_tables();
636585 let kx = tables.kx as usize;
637586 let a1 = 0.6f64;
@@ -652,7 +601,7 @@ mod tests {
652601 let invf_off = vec![0u8; tables.n_q];
653602 let invf_high = vec![3u8; tables.n_q];
654603
655- // bw = 0: residual resynthesis collapses toward silence, not a copy.
604+ // bw = 0: exact plain copy (4.6.18.6.3 with both taps zeroed).
656605 let mut chirp0 = ChirpState::new(tables.n_q);
657606 let mut hist0 = HfHistory::new(kx);
658607 let _ = generate(&frame1, &tables, &invf_off, &mut chirp0, &mut hist0);
@@ -664,13 +613,13 @@ mod tests {
664613 continue;
665614 }
666615 assert!(
667- y.re.abs() < 0.1 * expect.abs(),
668- "bw=0 residual should collapse toward silence at n={n}: {y:?} vs input {expect}"
616+ (y - Complex::new(expect, 0.0)).norm_sqr().sqrt() < 1e-9 * expect.abs().max(1.0),
617+ "bw=0 must copy at n={n}: {y:?} vs input {expect}"
669618 );
670619 }
671620
672- // bw ~= 0.98: residual~=0, so the recursion tracks the source's own
673- // resonance from history alone -- ratio near 1, not ~1.98.
621+ // bw ~= 0.98: near-full inverse filter of a noiseless AR(2) -> the
622+ // output is close to the (zero) prediction residual, far below x.
674623 let mut chirp1 = ChirpState::new(tables.n_q);
675624 chirp1.bw = vec![0.0; tables.n_q]; // priming frame at bw=0
676625 let mut hist1 = HfHistory::new(kx);
@@ -683,14 +632,9 @@ mod tests {
683632 if expect.abs() < 1e-6 {
684633 continue;
685634 }
686- let ratio = y.re / expect;
687- assert!(
688- (0.5..1.5).contains(&ratio),
689- "bw=0.98 ratio out of range at n={n}: ratio={ratio} y={y:?} x={expect}"
690- );
691635 assert!(
692- y.im.abs() < 0.05 * expect.abs().max(1e-6),
693- "unexpected imaginary part at n={n}: {y:?}"
636+ y.norm_sqr().sqrt() < 0.15 * expect.abs(),
637+ "bw=0.98 should whiten at n={n}: y={y:?} x={expect}"
694638 );
695639 }
696640 }