Spec covariance alpha + feed-forward HF generator + spec chirp table/smoothing
Browse files at this commit7cb600080c2fbe8fe38412d5633d8b2c602c34e6Parent: b966d5e- fix
- spec covariance alpha + feed-forward HF generator + spec chirp table/smoothing
1 changed file +121 -177
- crates/ec-aac/src/sbr_hf.rs +121 -177
crates/ec-aac/src/sbr_hf.rsmodified+121 -177
| @@ -221,9 +221,21 @@ pub fn limiter_band_table(tables: &BandTables, patches: &[Patch], limiter_bands: | |||
| 221 | out | 221 | out |
| 222 | } | 222 | } |
| 223 | 223 | ||
| 224 | -/// `bs_invf_mode` bandwidth-expansion targets (OFF, LOW, MID, HIGH), the | 224 | +/// `bs_invf_mode` chirp targets per ISO 14496-3 4.6.18.6.3 (Table 4.163): |
| 225 | -/// four inverse-filtering strengths §4.6.18.6.2 defines. | 225 | +/// the target depends on the current AND previous frame's mode -- |
| 226 | -const BW_TABLE: [f64; 4] = [0.0, 0.6, 0.9, 0.98]; | 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 | +} | ||
| 227 | 239 | ||
| 228 | /// Per-noise-band chirp factor state, smoothed frame to frame with a | 240 | /// Per-noise-band chirp factor state, smoothed frame to frame with a |
| 229 | /// fast-attack (toward a *lower* bw, i.e. more whitening) / slow-release | 241 | /// 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]; | |||
| 231 | #[derive(Clone, Debug)] | 243 | #[derive(Clone, Debug)] |
| 232 | pub struct ChirpState { | 244 | pub struct ChirpState { |
| 233 | bw: Vec<f64>, | 245 | bw: Vec<f64>, |
| 246 | + prev_mode: Vec<u8>, | ||
| 234 | } | 247 | } |
| 235 | 248 | ||
| 236 | impl ChirpState { | 249 | impl ChirpState { |
| 237 | pub fn new(n_q: usize) -> ChirpState { | 250 | 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 | + } | ||
| 239 | } | 255 | } |
| 240 | 256 | ||
| 241 | /// Advances the state one frame given this frame's `bs_invf_mode` per | 257 | /// Advances the state one frame given this frame's `bs_invf_mode` per |
| 242 | /// noise band, returning the smoothed bw to use for HF generation. | 258 | /// noise band, returning the smoothed bw to use for HF generation. |
| 243 | /// | 259 | /// |
| 244 | /// (Round-22 sweep instrumentation, zero cost unset) `EC_AAC_SBR_BW_SCALE` | 260 | /// (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 |
| 246 | /// smoothing, to probe whether the chirp/inverse-filter strength is | 262 | /// smoothing, to probe whether the chirp/inverse-filter strength is |
| 247 | /// miscalibrated on real content. `EC_AAC_SBR_CHIRP_SMOOTH=none` skips | 263 | /// miscalibrated on real content. `EC_AAC_SBR_CHIRP_SMOOTH=none` skips |
| 248 | /// the attack/release smoothing entirely (target used immediately); | 264 | /// the attack/release smoothing entirely (target used immediately); |
| @@ -251,15 +267,20 @@ impl ChirpState { | |||
| 251 | pub fn update(&mut self, invf_mode: &[u8]) -> &[f64] { | 267 | pub fn update(&mut self, invf_mode: &[u8]) -> &[f64] { |
| 252 | let scale = bw_scale_override(); | 268 | let scale = bw_scale_override(); |
| 253 | let smooth = chirp_smooth_mode(); | 269 | let smooth = chirp_smooth_mode(); |
| 254 | - for (slot, &mode) in self.bw.iter_mut().zip(invf_mode) { | 270 | + for ((slot, prev), &mode) in self.bw.iter_mut().zip(&mut self.prev_mode).zip(invf_mode) { |
| 255 | - let target = (BW_TABLE[usize::from(mode).min(3)] * scale).min(0.999_999); | 271 | + let target = (bw_target(mode, *prev) * scale).min(0.999_999); |
| 272 | + *prev = mode; | ||
| 256 | *slot = match smooth { | 273 | *slot = match smooth { |
| 257 | ChirpSmooth::None => target, | 274 | ChirpSmooth::None => target, |
| 258 | ChirpSmooth::Current => { | 275 | 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. | ||
| 259 | if target < *slot { | 280 | if target < *slot { |
| 260 | 0.75 * target + 0.25 * *slot | 281 | 0.75 * target + 0.25 * *slot |
| 261 | } else { | 282 | } else { |
| 262 | - 0.90625 * *slot + 0.09375 * target | 283 | + 0.90625 * target + 0.09375 * *slot |
| 263 | } | 284 | } |
| 264 | } | 285 | } |
| 265 | ChirpSmooth::Swap => { | 286 | ChirpSmooth::Swap => { |
| @@ -270,12 +291,16 @@ impl ChirpState { | |||
| 270 | } | 291 | } |
| 271 | } | 292 | } |
| 272 | }; | 293 | }; |
| 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 | + } | ||
| 273 | } | 298 | } |
| 274 | &self.bw | 299 | &self.bw |
| 275 | } | 300 | } |
| 276 | } | 301 | } |
| 277 | 302 | ||
| 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 |
| 279 | /// (a chirp target at or past 1.0 is an undamped all-pole resonance, not a | 304 | /// (a chirp target at or past 1.0 is an undamped all-pole resonance, not a |
| 280 | /// meaningful "stronger" whitening). `1.0` (no-op) when unset or unparsable. | 305 | /// meaningful "stronger" whitening). `1.0` (no-op) when unset or unparsable. |
| 281 | fn bw_scale_override() -> f64 { | 306 | fn bw_scale_override() -> f64 { |
| @@ -301,95 +326,45 @@ fn chirp_smooth_mode() -> ChirpSmooth { | |||
| 301 | } | 326 | } |
| 302 | } | 327 | } |
| 303 | 328 | ||
| 304 | -/// Order-2 covariance-method LPC over `x` (index 0 is the oldest sample): | 329 | +/// Order-2 linear-prediction coefficients per ISO 14496-3 4.6.18.6.2 |
| 305 | -/// solves the 2x2 normal equations minimizing `sum |x[n] - a1*x[n-1] - | 330 | +/// (covariance method, `phi(i,j) = sum_n x[n-i]*conj(x[n-j])` over |
| 306 | -/// a2*x[n-2]|^2` over `n = 2..x.len()`. Returns `(a1, a2)`; `(0, 0)` if `x` | 331 | +/// `n = 2..x.len()`, index 0 of `x` is the oldest slot). Returns the spec's |
| 307 | -/// is too short or the system is singular (silence or a near-constant | 332 | +/// `(alpha0, alpha1)` -- the PREDICTION-ERROR filter taps, i.e. the |
| 308 | -/// subband, both of which need no prediction). | 333 | +/// negated predictor coefficients: for `x[n] = a1*x[n-1] + a2*x[n-2] + e` |
| 309 | -/// (Round-57) AR(2) coefficients via the Yule-Walker/autocorrelation | 334 | +/// this yields `(-a1, -a2)`, so `x + alpha0*x[n-1] + alpha1*x[n-2]` |
| 310 | -/// method (`r(k) = sum_n x[n]*conj(x[n-k])`, Hermitian-Toeplitz `R`), | 335 | +/// whitens. `(0, 0)` on degenerate input or when either |alpha| >= 4 |
| 311 | -/// replacing the previous unwindowed covariance-method normal-equation | 336 | +/// (spec guard). Witness: scratch `alpha/witness.py` (numpy) recovers a |
| 312 | -/// solve. The autocorrelation matrix is always positive semi-definite, | 337 | +/// synthetic complex AR(2) with this sign convention and whitens at bw=1. |
| 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). | ||
| 325 | pub fn lpc2(x: &[Complex<f64>]) -> (Complex<f64>, Complex<f64>) { | 338 | pub fn lpc2(x: &[Complex<f64>]) -> (Complex<f64>, Complex<f64>) { |
| 326 | if x.len() < 3 { | 339 | if x.len() < 3 { |
| 327 | return (Complex::ZERO, Complex::ZERO); | 340 | return (Complex::ZERO, Complex::ZERO); |
| 328 | } | 341 | } |
| 329 | - let mut r0 = 0.0f64; | 342 | + let phi = |i: usize, j: usize| -> Complex<f64> { |
| 330 | - let mut r1 = Complex::ZERO; | 343 | + (2..x.len()).fold(Complex::ZERO, |acc, n| acc + x[n - i] * x[n - j].conj()) |
| 331 | - let mut r2 = Complex::ZERO; | 344 | + }; |
| 332 | - for n in 0..x.len() { | 345 | + let p11 = phi(1, 1).re; |
| 333 | - r0 += x[n].norm_sqr(); | 346 | + let p22 = phi(2, 2).re; |
| 334 | - if n >= 1 { | 347 | + let p01 = phi(0, 1); |
| 335 | - r1 = r1 + x[n] * x[n - 1].conj(); | 348 | + let p02 = phi(0, 2); |
| 336 | - } | 349 | + let p12 = phi(1, 2); |
| 337 | - if n >= 2 { | 350 | + const EPS: f64 = 1e-6; |
| 338 | - r2 = r2 + x[n] * x[n - 2].conj(); | 351 | + let d = p22 * p11 - p12.norm_sqr() / (1.0 + EPS); |
| 339 | - } | 352 | + let alpha1 = if d.abs() < 1e-30 { |
| 340 | - } | 353 | + Complex::ZERO |
| 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) | ||
| 390 | } else { | 354 | } 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); | ||
| 392 | } | 366 | } |
| 367 | + (alpha0, alpha1) | ||
| 393 | } | 368 | } |
| 394 | 369 | ||
| 395 | /// Per-source-subband history: the last two QMF slots, carried across | 370 | /// 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 | |||
| 397 | /// frame boundaries instead of restarting cold every frame. | 372 | /// frame boundaries instead of restarting cold every frame. |
| 398 | #[derive(Clone, Debug)] | 373 | #[derive(Clone, Debug)] |
| 399 | pub struct HfHistory { | 374 | pub struct HfHistory { |
| 400 | - x: Vec<[Complex<f64>; 2]>, | 375 | + /// Last `HIST` slots per source band (4.6.18.6.2's covariance window |
| 401 | - y: Vec<[Complex<f64>; 2]>, | 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]>, | ||
| 402 | } | 379 | } |
| 403 | 380 | ||
| 381 | +const HIST: usize = 6; | ||
| 382 | + | ||
| 404 | impl HfHistory { | 383 | impl HfHistory { |
| 405 | pub fn new(bands: usize) -> HfHistory { | 384 | pub fn new(bands: usize) -> HfHistory { |
| 406 | HfHistory { | 385 | HfHistory { |
| 407 | - x: vec![[Complex::ZERO; 2]; bands], | 386 | + x: vec![[Complex::ZERO; HIST]; bands], |
| 408 | - y: vec![[Complex::ZERO; 2]; bands], | ||
| 409 | } | 387 | } |
| 410 | } | 388 | } |
| 411 | } | 389 | } |
| @@ -448,17 +426,15 @@ pub fn generate( | |||
| 448 | continue; | 426 | continue; |
| 449 | } | 427 | } |
| 450 | let series = &low_cur[source_band]; | 428 | let series = &low_cur[source_band]; |
| 451 | - let (a1, a2) = { | 429 | + let (alpha0, alpha1) = { |
| 452 | - let mut ext = Vec::with_capacity(num_slots + 2); | 430 | + let mut ext = Vec::with_capacity(num_slots + HIST); |
| 453 | if source_band < history.x.len() { | 431 | if source_band < history.x.len() { |
| 454 | - ext.push(history.x[source_band][0]); | 432 | + ext.extend_from_slice(&history.x[source_band]); |
| 455 | - ext.push(history.x[source_band][1]); | ||
| 456 | } else { | 433 | } else { |
| 457 | - ext.push(Complex::ZERO); | 434 | + ext.resize(HIST, Complex::ZERO); |
| 458 | - ext.push(Complex::ZERO); | ||
| 459 | } | 435 | } |
| 460 | ext.extend_from_slice(series); | 436 | ext.extend_from_slice(series); |
| 461 | - stabilize(lpc2(&ext)) | 437 | + lpc2(&ext) |
| 462 | }; | 438 | }; |
| 463 | let g = bw[noise_band_of(target_band)]; | 439 | let g = bw[noise_band_of(target_band)]; |
| 464 | // (Round-46, Task 2) `EC_AAC_SBR_BW_DUMP` -- one line per patched | 440 | // (Round-46, Task 2) `EC_AAC_SBR_BW_DUMP` -- one line per patched |
| @@ -468,40 +444,35 @@ pub fn generate( | |||
| 468 | if std::env::var("EC_AAC_SBR_BW_DUMP").is_ok() { | 444 | if std::env::var("EC_AAC_SBR_BW_DUMP").is_ok() { |
| 469 | eprintln!("BW_DUMP target_band={target_band} source_band={source_band} bw={g:.6}"); | 445 | eprintln!("BW_DUMP target_band={target_band} source_band={source_band} bw={g:.6}"); |
| 470 | } | 446 | } |
| 471 | - let ca1 = a1.scale(g); | 447 | + // 4.6.18.6.3 feed-forward: X_high = X_low + bw*alpha0*X_low[l-1] |
| 472 | - let ca2 = a2.scale(g * g); | 448 | + // + bw^2*alpha1*X_low[l-2]. bw=0 is a plain copy, bw->1 is the |
| 473 | - let (mut y_prev1, mut y_prev2) = if source_band < history.y.len() { | 449 | + // full inverse (whitening) filter. The all-pole recursion this |
| 474 | - (history.y[source_band][1], history.y[source_band][0]) | 450 | + // replaced (`y = residual + bw*a1*y[l-1] + bw^2*a2*y[l-2]`) had |
| 475 | - } else { | 451 | + // that mapping INVERTED (bw=0 whitened fully, bw=0.98 ~ copy), |
| 476 | - (Complex::ZERO, Complex::ZERO) | 452 | + // and the earlier feed-forward attempt (8bc305b) used the |
| 477 | - }; | 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); | ||
| 478 | let (mut x_prev1, mut x_prev2) = if source_band < history.x.len() { | 459 | 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 | + ) | ||
| 480 | } else { | 464 | } else { |
| 481 | (Complex::ZERO, Complex::ZERO) | 465 | (Complex::ZERO, Complex::ZERO) |
| 482 | }; | 466 | }; |
| 483 | let dst = &mut out[target_band - kx]; | 467 | let dst = &mut out[target_band - kx]; |
| 484 | for (n, &x) in series.iter().enumerate() { | 468 | 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; | ||
| 487 | // Round-37 (Task 2): `band_shift_correction` is proven exact | 469 | // Round-37 (Task 2): `band_shift_correction` is proven exact |
| 488 | - // in isolation (a stationary tone replayed through this | 470 | + // in isolation but a real-file A/B (`EC_AAC_SBR_PARITY_SPLIT`) |
| 489 | - // patch-copy site lands within a couple of FFT bins of its | 471 | + // shows applying it REGRESSES odd-gap coherence against the |
| 490 | - // corrected absolute frequency -- see | 472 | + // reference; `dst` stays the uncorrected band placement. |
| 491 | - // `sbr_qmf::tests::patch_replay_through_generate_preserves_absolute_frequency_mapping`) | 473 | + dst[n] = x + c1 * x_prev1 + c2 * x_prev2; |
| 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; | ||
| 501 | x_prev2 = x_prev1; | 474 | x_prev2 = x_prev1; |
| 502 | x_prev1 = x; | 475 | x_prev1 = x; |
| 503 | - y_prev2 = y_prev1; | ||
| 504 | - y_prev1 = y; | ||
| 505 | } | 476 | } |
| 506 | } | 477 | } |
| 507 | } | 478 | } |
| @@ -509,14 +480,12 @@ pub fn generate( | |||
| 509 | // Every source subband's history advances regardless of whether a | 480 | // Every source subband's history advances regardless of whether a |
| 510 | // patch used it this frame: the low-band QMF stream is continuous. | 481 | // patch used it this frame: the low-band QMF stream is continuous. |
| 511 | for (band, series) in low_cur.iter().enumerate() { | 482 | for (band, series) in low_cur.iter().enumerate() { |
| 512 | - if band >= history.x.len() || series.len() < 2 { | 483 | + if band >= history.x.len() { |
| 513 | continue; | 484 | continue; |
| 514 | } | 485 | } |
| 515 | - let n = series.len(); | 486 | + let h = &mut history.x[band]; |
| 516 | - history.x[band] = [series[n - 2], series[n - 1]]; | 487 | + let keep: Vec<Complex<f64>> = h.iter().copied().chain(series.iter().copied()).collect(); |
| 517 | - // y-history only meaningfully advances for bands a patch actually | 488 | + h.copy_from_slice(&keep[keep.len() - HIST..]); |
| 518 | - // wrote; untouched bands hold their input as a neutral seed. | ||
| 519 | - history.y[band] = [series[n - 2], series[n - 1]]; | ||
| 520 | } | 489 | } |
| 521 | 490 | ||
| 522 | out | 491 | out |
| @@ -579,8 +548,15 @@ mod tests { | |||
| 579 | // previous covariance-method solve) for a stability guarantee real | 548 | // previous covariance-method solve) for a stability guarantee real |
| 580 | // content needs -- still recovers the synthetic poles to well | 549 | // content needs -- still recovers the synthetic poles to well |
| 581 | // within this looser bound. | 550 | // within this looser bound. |
| 582 | - assert!((fa1 - a1).norm_sqr().sqrt() < 0.2, "a1 {fa1:?} vs {a1:?}"); | 551 | + // spec alpha = negated predictor coefficients |
| 583 | - assert!((fa2 - a2).norm_sqr().sqrt() < 0.2, "a2 {fa2:?} vs {a2:?}"); | 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 | + ); | ||
| 584 | } | 560 | } |
| 585 | 561 | ||
| 586 | #[test] | 562 | #[test] |
| @@ -589,7 +565,7 @@ mod tests { | |||
| 589 | // Jump from OFF straight to HIGH: attack (rising bw) is the slow | 565 | // Jump from OFF straight to HIGH: attack (rising bw) is the slow |
| 590 | // (0.90625/0.09375) branch here since target > current. | 566 | // (0.90625/0.09375) branch here since target > current. |
| 591 | let after_rise = chirp.update(&[3])[0]; | 567 | 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); |
| 593 | // Now drop back to OFF: release (falling bw) is the fast | 569 | // Now drop back to OFF: release (falling bw) is the fast |
| 594 | // (0.75/0.25) branch, so it should move further in one step than | 570 | // (0.75/0.25) branch, so it should move further in one step than |
| 595 | // the rise did. | 571 | // the rise did. |
| @@ -603,35 +579,8 @@ mod tests { | |||
| 603 | ); | 579 | ); |
| 604 | } | 580 | } |
| 605 | 581 | ||
| 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. | ||
| 633 | #[test] | 582 | #[test] |
| 634 | - fn all_pole_resynthesis_matches_bw_endpoints() { | 583 | + fn feed_forward_matches_bw_endpoints() { |
| 635 | let tables = real_file_tables(); | 584 | let tables = real_file_tables(); |
| 636 | let kx = tables.kx as usize; | 585 | let kx = tables.kx as usize; |
| 637 | let a1 = 0.6f64; | 586 | let a1 = 0.6f64; |
| @@ -652,7 +601,7 @@ mod tests { | |||
| 652 | let invf_off = vec![0u8; tables.n_q]; | 601 | let invf_off = vec![0u8; tables.n_q]; |
| 653 | let invf_high = vec![3u8; tables.n_q]; | 602 | let invf_high = vec![3u8; tables.n_q]; |
| 654 | 603 | ||
| 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). |
| 656 | let mut chirp0 = ChirpState::new(tables.n_q); | 605 | let mut chirp0 = ChirpState::new(tables.n_q); |
| 657 | let mut hist0 = HfHistory::new(kx); | 606 | let mut hist0 = HfHistory::new(kx); |
| 658 | let _ = generate(&frame1, &tables, &invf_off, &mut chirp0, &mut hist0); | 607 | let _ = generate(&frame1, &tables, &invf_off, &mut chirp0, &mut hist0); |
| @@ -664,13 +613,13 @@ mod tests { | |||
| 664 | continue; | 613 | continue; |
| 665 | } | 614 | } |
| 666 | assert!( | 615 | assert!( |
| 667 | - y.re.abs() < 0.1 * expect.abs(), | 616 | + (y - Complex::new(expect, 0.0)).norm_sqr().sqrt() < 1e-9 * expect.abs().max(1.0), |
| 668 | - "bw=0 residual should collapse toward silence at n={n}: {y:?} vs input {expect}" | 617 | + "bw=0 must copy at n={n}: {y:?} vs input {expect}" |
| 669 | ); | 618 | ); |
| 670 | } | 619 | } |
| 671 | 620 | ||
| 672 | - // bw ~= 0.98: residual~=0, so the recursion tracks the source's own | 621 | + // bw ~= 0.98: near-full inverse filter of a noiseless AR(2) -> the |
| 673 | - // resonance from history alone -- ratio near 1, not ~1.98. | 622 | + // output is close to the (zero) prediction residual, far below x. |
| 674 | let mut chirp1 = ChirpState::new(tables.n_q); | 623 | let mut chirp1 = ChirpState::new(tables.n_q); |
| 675 | chirp1.bw = vec![0.0; tables.n_q]; // priming frame at bw=0 | 624 | chirp1.bw = vec![0.0; tables.n_q]; // priming frame at bw=0 |
| 676 | let mut hist1 = HfHistory::new(kx); | 625 | let mut hist1 = HfHistory::new(kx); |
| @@ -683,14 +632,9 @@ mod tests { | |||
| 683 | if expect.abs() < 1e-6 { | 632 | if expect.abs() < 1e-6 { |
| 684 | continue; | 633 | continue; |
| 685 | } | 634 | } |
| 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 | - ); | ||
| 691 | assert!( | 635 | assert!( |
| 692 | - y.im.abs() < 0.05 * expect.abs().max(1e-6), | 636 | + y.norm_sqr().sqrt() < 0.15 * expect.abs(), |
| 693 | - "unexpected imaginary part at n={n}: {y:?}" | 637 | + "bw=0.98 should whiten at n={n}: y={y:?} x={expect}" |
| 694 | ); | 638 | ); |
| 695 | } | 639 | } |
| 696 | } | 640 | } |