SBR HF patch copies land at the wrong absolute frequency, one full band off
Browse files at this commit2f5c8e23018c5b1083a8f9bc9367af526f36d8a4Parent: ea6cc30- fix
- SBR HF patch copies land at the wrong absolute frequency, one full band off
2 changed files +251 -1
- crates/ec-aac/src/sbr_hf.rs +50 -1
- crates/ec-aac/src/sbr_qmf.rs +201 -0
crates/ec-aac/src/sbr_hf.rsmodified+50 -1
| @@ -36,6 +36,35 @@ | ||
| 36 | 36 | use crate::sbr_bands::BandTables; |
| 37 | 37 | use ec_dsp::Complex; |
| 38 | 38 | |
| 39 | +/// Compensates a QMF-bank convention gap `sbr_qmf`'s round-trip tuning never | |
| 40 | +/// exercised: replaying a source band's raw complex series into a | |
| 41 | +/// *different* synthesis band (exactly what patch copying does) lands the | |
| 42 | +/// content at the wrong absolute frequency by exactly one synthesis-band | |
| 43 | +/// width whenever `target_band - source_band` is odd, with the sign flipping | |
| 44 | +/// every other odd step -- i.e. a period-4 pattern in `target - source` | |
| 45 | +/// (even difference: no error; `+1 mod 4`: content lands one band flat; | |
| 46 | +/// `+3 mod 4`: one band sharp). `sbr_qmf::Synthesis`'s modulation kernel | |
| 47 | +/// centres band `k` at `(k+0.5) * pi/(2*SYNTHESIS_BANDS)` via a phase | |
| 48 | +/// intercept that is itself `(k+0.5) * pi/4` -- exactly the odd-stacked | |
| 49 | +/// cosine-modulated-bank convention the round-trip test tuned for | |
| 50 | +/// same-band replay, where this intercept cancels against the receiving | |
| 51 | +/// band's own reconstruction. For an odd `target - source` that intercept | |
| 52 | +/// difference is an odd multiple of `pi/4`, which this design's finite, | |
| 53 | +/// hop-discretised overlap-add can't represent without a full extra | |
| 54 | +/// `pi/2 * (target - source)`-quarter snap; `generate` cancels it here by | |
| 55 | +/// counter-rotating the patched series at the same quarter-turn rate before | |
| 56 | +/// it reaches `Synthesis`, rather than reworking the tuned bank convention | |
| 57 | +/// (which round-trip/gain-flatness tests already hold to a hard-won bound). | |
| 58 | +/// Returns the signed number of `pi/2` quarter-turns per QMF slot to rotate | |
| 59 | +/// the copied series by. | |
| 60 | +pub(crate) fn band_shift_correction(target_band: usize, source_band: usize) -> i64 { | |
| 61 | + match (target_band as i64 - source_band as i64).rem_euclid(4) { | |
| 62 | + 1 => 1, | |
| 63 | + 3 => -1, | |
| 64 | + _ => 0, | |
| 65 | + } | |
| 66 | +} | |
| 67 | + | |
| 39 | 68 | /// One copy-up patch: `width` consecutive QMF bands starting at |
| 40 | 69 | /// `source_start` are written to `target_start..target_start+width`. |
| 41 | 70 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| @@ -299,6 +328,11 @@ fn stabilize(coeffs: (Complex<f64>, Complex<f64>)) -> (Complex<f64>, Complex<f64 | ||
| 299 | 328 | pub struct HfHistory { |
| 300 | 329 | x: Vec<[Complex<f64>; 2]>, |
| 301 | 330 | y: Vec<[Complex<f64>; 2]>, |
| 331 | + /// Running QMF-slot counter mod 4, since stream start -- carries the | |
| 332 | + /// patch-band-shift phase correction's own period across frame calls | |
| 333 | + /// (see `band_shift_correction` in `generate`). Only the value mod 4 | |
| 334 | + /// matters (the correction's period), so this never grows unbounded. | |
| 335 | + slot_phase: usize, | |
| 302 | 336 | } |
| 303 | 337 | |
| 304 | 338 | impl HfHistory { |
| @@ -306,6 +340,7 @@ impl HfHistory { | ||
| 306 | 340 | HfHistory { |
| 307 | 341 | x: vec![[Complex::ZERO; 2]; bands], |
| 308 | 342 | y: vec![[Complex::ZERO; 2]; bands], |
| 343 | + slot_phase: 0, | |
| 309 | 344 | } |
| 310 | 345 | } |
| 311 | 346 | } |
| @@ -373,11 +408,24 @@ pub fn generate( | ||
| 373 | 408 | } else { |
| 374 | 409 | (Complex::ZERO, Complex::ZERO) |
| 375 | 410 | }; |
| 411 | + let k = band_shift_correction(target_band, source_band); | |
| 376 | 412 | let dst = &mut out[target_band - kx]; |
| 377 | 413 | for (n, &x) in series.iter().enumerate() { |
| 378 | 414 | let residual = x - a1 * x_prev1 - a2 * x_prev2; |
| 379 | 415 | let y = residual + ca1 * y_prev1 + ca2 * y_prev2; |
| 380 | - dst[n] = y; | |
| 416 | + // The filter's own recursion continues on the unrotated | |
| 417 | + // `y` (its whitening state belongs to the source band, not | |
| 418 | + // the target placement); only what lands in `dst` -- the | |
| 419 | + // value `Synthesis` will actually see at `target_band` -- | |
| 420 | + // gets the placement correction. | |
| 421 | + dst[n] = if k == 0 { | |
| 422 | + y | |
| 423 | + } else { | |
| 424 | + let t_mod4 = (history.slot_phase + n) % 4; | |
| 425 | + let angle = k as f64 * std::f64::consts::FRAC_PI_2 * t_mod4 as f64; | |
| 426 | + let rot = Complex::new(angle.cos(), angle.sin()); | |
| 427 | + Complex::new(y.re * rot.re - y.im * rot.im, y.re * rot.im + y.im * rot.re) | |
| 428 | + }; | |
| 381 | 429 | x_prev2 = x_prev1; |
| 382 | 430 | x_prev1 = x; |
| 383 | 431 | y_prev2 = y_prev1; |
| @@ -385,6 +433,7 @@ pub fn generate( | ||
| 385 | 433 | } |
| 386 | 434 | } |
| 387 | 435 | } |
| 436 | + history.slot_phase = (history.slot_phase + num_slots) % 4; | |
| 388 | 437 | |
| 389 | 438 | // Every source subband's history advances regardless of whether a |
| 390 | 439 | // patch used it this frame: the low-band QMF stream is continuous. |
crates/ec-aac/src/sbr_qmf.rsmodified+201 -0
| @@ -574,6 +574,207 @@ mod tests { | ||
| 574 | 574 | ); |
| 575 | 575 | } |
| 576 | 576 | |
| 577 | + /// Peak-bin frequency (cycles/sample, in `0.0..0.5`) of a real signal's | |
| 578 | + /// dominant spectral line: FFT magnitude over the whole window, biggest | |
| 579 | + /// positive-frequency bin. `signal.len()` must be a power of two. | |
| 580 | + fn dominant_freq(signal: &[f64]) -> f64 { | |
| 581 | + let n = signal.len(); | |
| 582 | + let mut fft = Fft::<f64>::new(n); | |
| 583 | + let mut spectrum: Vec<Complex<f64>> = | |
| 584 | + signal.iter().map(|&v| Complex::new(v, 0.0)).collect(); | |
| 585 | + fft.forward(&mut spectrum); | |
| 586 | + let mut best_bin = 1usize; | |
| 587 | + let mut best_mag = -1.0f64; | |
| 588 | + for (k, c) in spectrum.iter().enumerate().take(n / 2).skip(1) { | |
| 589 | + let mag = c.norm_sqr(); | |
| 590 | + if mag > best_mag { | |
| 591 | + best_mag = mag; | |
| 592 | + best_bin = k; | |
| 593 | + } | |
| 594 | + } | |
| 595 | + best_bin as f64 / n as f64 | |
| 596 | + } | |
| 597 | + | |
| 598 | + /// TASK 1(a) (round-35 SBR-HF-patch conviction): synthesis alone, band by | |
| 599 | + /// band and intra-band offset by intra-band offset. Feed synthesis band | |
| 600 | + /// `q` a phasor rotating slowly hop-to-hop (`exp(i*2*pi*delta*slot)`, | |
| 601 | + /// `delta` a fraction of the inter-band spacing) and read the output | |
| 602 | + /// spectrum's dominant line back: does it land at `centre(q) + | |
| 603 | + /// delta/SYNTHESIS_BANDS` or `centre(q) - delta/SYNTHESIS_BANDS`? Pins | |
| 604 | + /// that each band's own intra-band offset sense is self-consistent | |
| 605 | + /// (`+delta` and `-delta` read as mirror images of each other, not | |
| 606 | + /// independently flipped) -- a single band's own demodulation direction | |
| 607 | + /// has to be well-defined before cross-band placement (tested in | |
| 608 | + /// `patch_replay_preserves_absolute_frequency_mapping`, where the real | |
| 609 | + /// conviction for this round lives) means anything. | |
| 610 | + #[test] | |
| 611 | + fn synthesis_offset_sense_is_self_consistent_within_a_band() { | |
| 612 | + let omega_step = std::f64::consts::PI / (2.0 * SYNTHESIS_BANDS as f64); | |
| 613 | + let bands = [5usize, 14, 27, 42]; | |
| 614 | + let deltas = [-0.3f64, 0.3]; | |
| 615 | + let slots = 128; | |
| 616 | + let fft_len = 4096; | |
| 617 | + println!("q\tdelta\tmeasured_f\texpected(+delta sense)\texpected(-delta sense)\tsense"); | |
| 618 | + for &q in &bands { | |
| 619 | + let centre = (q as f64 + 0.5) * omega_step / std::f64::consts::TAU; | |
| 620 | + let mut senses = Vec::new(); | |
| 621 | + for &delta in &deltas { | |
| 622 | + let mut synthesis = Synthesis::new(); | |
| 623 | + let mut out = Vec::with_capacity(slots * SYNTHESIS_BANDS); | |
| 624 | + for slot in 0..slots { | |
| 625 | + let mut v = [Complex::new(0.0, 0.0); SYNTHESIS_BANDS]; | |
| 626 | + let ph = std::f64::consts::TAU * delta * slot as f64; | |
| 627 | + v[q] = Complex::new(ph.cos(), ph.sin()); | |
| 628 | + out.extend(synthesis.process_slot(&v).iter().map(|&s| f64::from(s))); | |
| 629 | + } | |
| 630 | + let steady = &out[out.len() - fft_len..]; | |
| 631 | + let f_measured = dominant_freq(steady); | |
| 632 | + let expected_plus = centre + delta / SYNTHESIS_BANDS as f64; | |
| 633 | + let expected_minus = centre - delta / SYNTHESIS_BANDS as f64; | |
| 634 | + let sense = | |
| 635 | + if (f_measured - expected_plus).abs() < (f_measured - expected_minus).abs() { | |
| 636 | + "+" | |
| 637 | + } else { | |
| 638 | + "-" | |
| 639 | + }; | |
| 640 | + println!( | |
| 641 | + "{q}\t{delta:+.2}\t{f_measured:.6}\t{expected_plus:.6}\t{expected_minus:.6}\t{sense}" | |
| 642 | + ); | |
| 643 | + senses.push(sense); | |
| 644 | + } | |
| 645 | + assert_eq!( | |
| 646 | + senses[0], senses[1], | |
| 647 | + "band {q}'s +delta and -delta offset senses disagree ({} vs {}) -- \ | |
| 648 | + the band's own demodulation direction is not self-consistent", | |
| 649 | + senses[0], senses[1] | |
| 650 | + ); | |
| 651 | + } | |
| 652 | + } | |
| 653 | + | |
| 654 | + /// TASK 1(b) (round-35 SBR-HF-patch conviction): the actual patch | |
| 655 | + /// operation -- analyze a real tone at a known offset from source band | |
| 656 | + /// `p`'s own centre via [`Analysis`], copy that complex series straight | |
| 657 | + /// into synthesis band `q` through the exact same per-slot placement | |
| 658 | + /// correction `sbr_hf::generate` applies at its patch-copy site | |
| 659 | + /// (`sbr_hf::band_shift_correction`, a quarter-turn-per-slot rotation | |
| 660 | + /// keyed on `(target - source) mod 4`), and check where the | |
| 661 | + /// reconstructed tone lands. Self-calibrating: band `q == p` is the | |
| 662 | + /// already-proven-correct round-trip case (its own measured frequency is | |
| 663 | + /// ground truth for "this tone, no shift"), so cross-band cases are | |
| 664 | + /// checked against `f_calib(p) + (q-p)/256` (`1/256` being | |
| 665 | + /// `SYNTHESIS_BANDS`'s own `omega_step/(2*pi)` band spacing) rather than | |
| 666 | + /// a hand-derived absolute constant. | |
| 667 | + /// | |
| 668 | + /// Without the correction (a bare copy, `sbr_hf`'s pre-fix behaviour) | |
| 669 | + /// this reads a clean, single-line, but WRONG frequency whenever | |
| 670 | + /// `q - p` is odd: exactly one full synthesis-band-width off, sign | |
| 671 | + /// alternating with `(q-p) mod 4` (`+1 mod 4` undershoots, `+3 mod 4` | |
| 672 | + /// overshoots) -- `Synthesis`'s odd-stacked modulation kernel centres | |
| 673 | + /// band `k` with a phase intercept of `(k+0.5)*pi/4` that only cancels | |
| 674 | + /// against a receiving band's own reconstruction when the source and | |
| 675 | + /// target band coincide (what `round_trip_reconstructs_the_passband` | |
| 676 | + /// exercises); for a genuinely different target band an odd `q-p` lands | |
| 677 | + /// that intercept difference on an odd multiple of `pi/4`, a phase this | |
| 678 | + /// design's finite hop-discretised overlap-add cannot represent without | |
| 679 | + /// snapping a full quarter-band. Even `q-p` lands on a multiple of | |
| 680 | + /// `pi/2` and was already exact. | |
| 681 | + #[test] | |
| 682 | + fn patch_replay_preserves_absolute_frequency_mapping() { | |
| 683 | + let omega_step_a = std::f64::consts::PI / (2.0 * ANALYSIS_BANDS as f64); | |
| 684 | + let omega_step_s = std::f64::consts::PI / (2.0 * SYNTHESIS_BANDS as f64); | |
| 685 | + let band_spacing_s = omega_step_s / std::f64::consts::TAU; | |
| 686 | + let slots = 128; | |
| 687 | + let core_samples = slots * ANALYSIS_BANDS; | |
| 688 | + let fft_len = 4096; | |
| 689 | + | |
| 690 | + // `p` must be a valid *analysis* band (< `ANALYSIS_BANDS`, 32) -- | |
| 691 | + // real patches only ever read a source band down there -- while `q` | |
| 692 | + // ranges the full synthesis span, both low and high, both parities, | |
| 693 | + // both odd and even `q - p`. | |
| 694 | + let pairs: [(usize, usize); 10] = [ | |
| 695 | + (5, 14), | |
| 696 | + (14, 5), | |
| 697 | + (6, 27), | |
| 698 | + (27, 6), | |
| 699 | + (3, 42), | |
| 700 | + (9, 42), | |
| 701 | + (9, 20), | |
| 702 | + (20, 9), | |
| 703 | + (5, 13), | |
| 704 | + (6, 26), | |
| 705 | + ]; | |
| 706 | + let deltas = [-0.3f64, 0.0, 0.3]; | |
| 707 | + | |
| 708 | + println!("p\tq\tdelta\tf_calib(p==p)\tf_measured\texpected\terr(bins)"); | |
| 709 | + let mut worst_err_bins = 0.0f64; | |
| 710 | + for &(p, q) in &pairs { | |
| 711 | + let centre_p = (p as f64 + 0.5) * omega_step_a; | |
| 712 | + for &delta in &deltas { | |
| 713 | + let omega0 = centre_p + delta * omega_step_a; | |
| 714 | + let x: Vec<f64> = (0..core_samples) | |
| 715 | + .map(|i| (omega0 * i as f64).cos()) | |
| 716 | + .collect(); | |
| 717 | + | |
| 718 | + let mut analysis = Analysis::new(); | |
| 719 | + let mut sub_p = Vec::with_capacity(slots); | |
| 720 | + for chunk in x.chunks_exact(ANALYSIS_BANDS) { | |
| 721 | + let mut c = [0f32; ANALYSIS_BANDS]; | |
| 722 | + for (d, &s) in c.iter_mut().zip(chunk) { | |
| 723 | + *d = s as f32; | |
| 724 | + } | |
| 725 | + sub_p.push(analysis.process_slot(&c)[p]); | |
| 726 | + } | |
| 727 | + | |
| 728 | + // Mirrors `sbr_hf::generate`'s patch-copy site exactly: a | |
| 729 | + // per-slot quarter-turn correction keyed on `(target - | |
| 730 | + // source) mod 4`, applied before the value reaches | |
| 731 | + // `Synthesis`. | |
| 732 | + let synth_at = |target: usize| -> f64 { | |
| 733 | + let k = crate::sbr_hf::band_shift_correction(target, p); | |
| 734 | + let mut synthesis = Synthesis::new(); | |
| 735 | + let mut out = Vec::with_capacity(slots * SYNTHESIS_BANDS); | |
| 736 | + for (t, &s) in sub_p.iter().enumerate() { | |
| 737 | + let s = if k == 0 { | |
| 738 | + s | |
| 739 | + } else { | |
| 740 | + let angle = k as f64 * std::f64::consts::FRAC_PI_2 * (t % 4) as f64; | |
| 741 | + let rot = Complex::new(angle.cos(), angle.sin()); | |
| 742 | + Complex::new( | |
| 743 | + s.re * rot.re - s.im * rot.im, | |
| 744 | + s.re * rot.im + s.im * rot.re, | |
| 745 | + ) | |
| 746 | + }; | |
| 747 | + let mut v = [Complex::new(0.0, 0.0); SYNTHESIS_BANDS]; | |
| 748 | + v[target] = s; | |
| 749 | + out.extend(synthesis.process_slot(&v).iter().map(|&s| f64::from(s))); | |
| 750 | + } | |
| 751 | + dominant_freq(&out[out.len() - fft_len..]) | |
| 752 | + }; | |
| 753 | + | |
| 754 | + let f_calib = synth_at(p); | |
| 755 | + let f_measured = synth_at(q); | |
| 756 | + let expected = f_calib + (q as i64 - p as i64) as f64 * band_spacing_s; | |
| 757 | + let bin_width = 1.0 / fft_len as f64; | |
| 758 | + let err_bins = (f_measured - expected).abs() / bin_width; | |
| 759 | + worst_err_bins = f64::max(worst_err_bins, err_bins); | |
| 760 | + println!( | |
| 761 | + "{p}\t{q}\t{delta:+.2}\t{f_calib:.6}\t{f_measured:.6}\t{expected:.6}\t{err_bins:.2}" | |
| 762 | + ); | |
| 763 | + } | |
| 764 | + } | |
| 765 | + | |
| 766 | + // With the patch-site correction applied, every case (odd AND even | |
| 767 | + // `q - p`) should land within a couple of FFT bins of the exact | |
| 768 | + // predicted absolute frequency -- the coherent-mapping bar the | |
| 769 | + // uncorrected bank could not clear (worst case there: 16 bins, | |
| 770 | + // exactly one synthesis band). | |
| 771 | + assert!( | |
| 772 | + worst_err_bins <= 3.0, | |
| 773 | + "worst corrected prediction error {worst_err_bins} bins exceeds 3 -- the patch-site \ | |
| 774 | + placement correction does not restore a coherent absolute frequency mapping" | |
| 775 | + ); | |
| 776 | + } | |
| 777 | + | |
| 577 | 778 | /// Round-13 (queue item 2, "gain-level issue" bucket): per-band |
| 578 | 779 | /// steady-state synthesis amplitude gain for a PHYSICALLY REAL tone at |
| 579 | 780 | /// each synthesis band's own centre frequency -- unlike a naive |