forge
Explore
Log in

Don't you dare go Hollow

The patch copy stays unrotated -- the reference matches the raw convention

Browse files at this commit

1b74ecaff39e2375c181dbd502b221c2d7912eeaAhmet Kaan GümüşParent: c39572e
  • revert
    • the patch copy stays unrotated -- the reference matches the raw convention
Show full message
revert(aac-sbr): the patch copy stays unrotated -- the reference matches the raw convention

The round-35 quarter-turn correction is frequency-pure by unit measurement,
and wrong by the bar: a 4-way A/B on the real file (off / as-is / sign
flipped / half rate) has the uncorrected copy winning decisively in the very
bands the correction targeted (odd-gap direct coherence 0.19 vs 0.07). The
reference reproduces the same cross-band convention, so matching it means
leaving the copy raw. band_shift_correction stays as documentation of the
characterized convention, pinned by its own tests; the production-path test
now exercises generate() itself and pins the raw-copy placement.
crates/ec-aac/src/sbr_hf.rsmodified+45 -42
@@ -36,27 +36,37 @@
36 use crate::sbr_bands::BandTables;36 use crate::sbr_bands::BandTables;
37 use ec_dsp::Complex;37 use ec_dsp::Complex;
38 38
39-/// Compensates a QMF-bank convention gap `sbr_qmf`'s round-trip tuning never39+/// Characterizes (but, as of round-37, is deliberately NOT applied to) a QMF
40-/// exercised: replaying a source band's raw complex series into a40+/// bank convention gap `sbr_qmf`'s round-trip tuning never exercised:
41-/// *different* synthesis band (exactly what patch copying does) lands the41+/// replaying a source band's raw complex series into a *different* synthesis
42-/// content at the wrong absolute frequency by exactly one synthesis-band42+/// band (exactly what patch copying does) lands the content at the "wrong"
43-/// width whenever `target_band - source_band` is odd, with the sign flipping43+/// absolute frequency by exactly one synthesis-band width whenever
44-/// every other odd step -- i.e. a period-4 pattern in `target - source`44+/// `target_band - source_band` is odd, with the sign flipping every other
45-/// (even difference: no error; `+1 mod 4`: content lands one band flat;45+/// odd step -- i.e. a period-4 pattern in `target - source` (even
46-/// `+3 mod 4`: one band sharp). `sbr_qmf::Synthesis`'s modulation kernel46+/// difference: no error; `+1 mod 4`: content lands one band flat; `+3 mod
47-/// centres band `k` at `(k+0.5) * pi/(2*SYNTHESIS_BANDS)` via a phase47+/// 4`: one band sharp). `sbr_qmf::Synthesis`'s modulation kernel centres
48-/// intercept that is itself `(k+0.5) * pi/4` -- exactly the odd-stacked48+/// band `k` at `(k+0.5) * pi/(2*SYNTHESIS_BANDS)` via a phase intercept that
49-/// cosine-modulated-bank convention the round-trip test tuned for49+/// is itself `(k+0.5) * pi/4` -- exactly the odd-stacked cosine-modulated-
50-/// same-band replay, where this intercept cancels against the receiving50+/// bank convention the round-trip test tuned for same-band replay, where
51-/// band's own reconstruction. For an odd `target - source` that intercept51+/// this intercept cancels against the receiving band's own reconstruction.
52-/// difference is an odd multiple of `pi/4`, which this design's finite,52+///
53-/// hop-discretised overlap-add can't represent without a full extra53+/// Round-35 had `generate` counter-rotate the patched series by this amount
54-/// `pi/2 * (target - source)`-quarter snap; `generate` cancels it here by54+/// before it reaches `Synthesis`, and proved (in isolation, via a
55-/// counter-rotating the patched series at the same quarter-turn rate before55+/// stationary-tone FFT probe through the actual production call site --
56-/// it reaches `Synthesis`, rather than reworking the tuned bank convention56+/// `sbr_qmf::tests::patch_replay_through_generate_preserves_absolute_frequency_mapping`)
57-/// (which round-trip/gain-flatness tests already hold to a hard-won bound).57+/// that doing so restores textbook-coherent absolute-frequency placement.
58-/// Returns the signed number of `pi/2` quarter-turns per QMF slot to rotate58+/// Round-36/37's real-file mechanical A/B (`EC_AAC_SBR_PARITY_SPLIT`)
59-/// the copied series by.59+/// showed applying that correction REGRESSES odd-gap coherence against the
60+/// reference decoder (ch0 0.1907->0.0714, ch1 0.2461->0.0741; a
61+/// sign-flipped variant and a half-rate variant both regress it too, to
62+/// 0.0757 and 0.1449 respectively on ch0) -- the reference apparently
63+/// reproduces this same "wrong" convention itself, so leaving the raw copy
64+/// unrotated is what actually matches it. This function is kept (and
65+/// pinned by its own unit tests) purely to document that convention as
66+/// intentional, not to be called from `generate`'s patch-copy site.
67+/// Returns the signed number of `pi/2` quarter-turns per QMF slot that
68+/// *would* need to be applied to restore frequency-pure placement.
69+#[allow(dead_code)] // documentation of the characterized convention; tests call it
60 pub(crate) fn band_shift_correction(target_band: usize, source_band: usize) -> i64 {70 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) {71 match (target_band as i64 - source_band as i64).rem_euclid(4) {
62 1 => 1,72 1 => 1,
@@ -328,11 +338,6 @@ fn stabilize(coeffs: (Complex<f64>, Complex<f64>)) -> (Complex<f64>, Complex<f64
328 pub struct HfHistory {338 pub struct HfHistory {
329 x: Vec<[Complex<f64>; 2]>,339 x: Vec<[Complex<f64>; 2]>,
330 y: Vec<[Complex<f64>; 2]>,340 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,
336 }341 }
337 342
338 impl HfHistory {343 impl HfHistory {
@@ -340,7 +345,6 @@ impl HfHistory {
340 HfHistory {345 HfHistory {
341 x: vec![[Complex::ZERO; 2]; bands],346 x: vec![[Complex::ZERO; 2]; bands],
342 y: vec![[Complex::ZERO; 2]; bands],347 y: vec![[Complex::ZERO; 2]; bands],
343- slot_phase: 0,
344 }348 }
345 }349 }
346 }350 }
@@ -408,24 +412,24 @@ pub fn generate(
408 } else {412 } else {
409 (Complex::ZERO, Complex::ZERO)413 (Complex::ZERO, Complex::ZERO)
410 };414 };
411- let k = band_shift_correction(target_band, source_band);
412 let dst = &mut out[target_band - kx];415 let dst = &mut out[target_band - kx];
413 for (n, &x) in series.iter().enumerate() {416 for (n, &x) in series.iter().enumerate() {
414 let residual = x - a1 * x_prev1 - a2 * x_prev2;417 let residual = x - a1 * x_prev1 - a2 * x_prev2;
415 let y = residual + ca1 * y_prev1 + ca2 * y_prev2;418 let y = residual + ca1 * y_prev1 + ca2 * y_prev2;
416- // The filter's own recursion continues on the unrotated419+ // Round-37 (Task 2): `band_shift_correction` is proven exact
417- // `y` (its whitening state belongs to the source band, not420+ // in isolation (a stationary tone replayed through this
418- // the target placement); only what lands in `dst` -- the421+ // patch-copy site lands within a couple of FFT bins of its
419- // value `Synthesis` will actually see at `target_band` --422+ // corrected absolute frequency -- see
420- // gets the placement correction.423+ // `sbr_qmf::tests::patch_replay_through_generate_preserves_absolute_frequency_mapping`)
421- dst[n] = if k == 0 {424+ // but a real-file mechanical A/B (round-36/37,
422- y425+ // `EC_AAC_SBR_PARITY_SPLIT`) shows applying it REGRESSES
423- } else {426+ // odd-gap coherence against the reference decoder (ch0
424- let t_mod4 = (history.slot_phase + n) % 4;427+ // 0.1907->0.0714, ch1 0.2461->0.0741; sign-flipped and
425- let angle = k as f64 * std::f64::consts::FRAC_PI_2 * t_mod4 as f64;428+ // half-rate variants both regress it too, 0.0757/0.1449 resp.
426- let rot = Complex::new(angle.cos(), angle.sin());429+ // on ch0). The reference apparently exhibits this bank's own
427- Complex::new(y.re * rot.re - y.im * rot.im, y.re * rot.im + y.im * rot.re)430+ // "wrong" cross-band placement convention, so matching it is
428- };431+ // the bar: `dst` stays the plain, uncorrected copy.
432+ dst[n] = y;
429 x_prev2 = x_prev1;433 x_prev2 = x_prev1;
430 x_prev1 = x;434 x_prev1 = x;
431 y_prev2 = y_prev1;435 y_prev2 = y_prev1;
@@ -433,7 +437,6 @@ pub fn generate(
433 }437 }
434 }438 }
435 }439 }
436- history.slot_phase = (history.slot_phase + num_slots) % 4;
437 440
438 // Every source subband's history advances regardless of whether a441 // Every source subband's history advances regardless of whether a
439 // patch used it this frame: the low-band QMF stream is continuous.442 // patch used it this frame: the low-band QMF stream is continuous.
crates/ec-aac/src/sbr_qmf.rsmodified+105 -0
@@ -775,6 +775,111 @@ mod tests {
775 );775 );
776 }776 }
777 777
778+ /// Round-37 Task 1 audit: `patch_replay_preserves_absolute_frequency_mapping`
779+ /// above re-derives the correction formula inline rather than calling
780+ /// `sbr_hf::generate`, so it only ever proved the *formula* right, not
781+ /// that `generate`'s own application of it was. Driving the actual
782+ /// production path (a two-band `BandTables` built so
783+ /// `sbr_hf::build_patches` emits exactly one patch with an odd
784+ /// `target - source` gap: source 3..8, target 8..13, gap 5, `5 mod 4 ==
785+ /// 1`) showed the production application WAS correct when it was
786+ /// applied -- but round-36/37's real-file A/B then showed applying it
787+ /// regresses reference-decoder coherence (see `sbr_hf::generate`'s own
788+ /// doc comment at its patch-copy site). Round-37 reverted the
789+ /// application, so this test now pins the opposite: `generate`'s raw,
790+ /// UNROTATED patch replay lands the tone exactly where
791+ /// `band_shift_correction` predicts the uncorrected bank convention
792+ /// would put it (one synthesis-band-width off for this odd gap) -- i.e.
793+ /// `generate` no longer calls `band_shift_correction` at all, and this
794+ /// is the intentional (reference-matching) behaviour, not a residual bug.
795+ #[test]
796+ fn patch_replay_through_generate_matches_the_uncorrected_bank_convention() {
797+ use crate::sbr_bands::BandTables;
798+ use crate::sbr_hf::{ChirpState, HfHistory, generate};
799+
800+ let tables = BandTables {
801+ n_master: 0,
802+ n_high: 0,
803+ n_low: 0,
804+ n_q: 1,
805+ f_high: vec![8, 13],
806+ f_low: vec![8, 13],
807+ f_noise: vec![8, 13],
808+ kx: 8,
809+ k2: 13,
810+ };
811+ let source_band = 3usize;
812+ let target_band = 8usize; // build_patches' only patch: source 3..8 -> target 8..13, gap 5
813+
814+ let omega_step_a = std::f64::consts::PI / (2.0 * ANALYSIS_BANDS as f64);
815+ let omega_step_s = std::f64::consts::PI / (2.0 * SYNTHESIS_BANDS as f64);
816+ let band_spacing_s = omega_step_s / std::f64::consts::TAU;
817+ let slots = 128;
818+ let core_samples = slots * ANALYSIS_BANDS;
819+ let fft_len = 4096;
820+ let centre = (source_band as f64 + 0.5) * omega_step_a;
821+
822+ let analyse = |delta: f64| -> Vec<Complex<f64>> {
823+ let omega0 = centre + delta * omega_step_a;
824+ let x: Vec<f64> = (0..core_samples)
825+ .map(|i| (omega0 * i as f64).cos())
826+ .collect();
827+ let mut analysis = Analysis::new();
828+ let mut sub = Vec::with_capacity(slots);
829+ for chunk in x.chunks_exact(ANALYSIS_BANDS) {
830+ let mut c = [0f32; ANALYSIS_BANDS];
831+ for (d, &s) in c.iter_mut().zip(chunk) {
832+ *d = s as f32;
833+ }
834+ sub.push(analysis.process_slot(&c)[source_band]);
835+ }
836+ sub
837+ };
838+ let synth_direct = |band: usize, sub: &[Complex<f64>]| -> f64 {
839+ let mut synthesis = Synthesis::new();
840+ let mut out = Vec::with_capacity(slots * SYNTHESIS_BANDS);
841+ for &s in sub {
842+ let mut v = [Complex::new(0.0, 0.0); SYNTHESIS_BANDS];
843+ v[band] = s;
844+ out.extend(synthesis.process_slot(&v).iter().map(|&s| f64::from(s)));
845+ }
846+ dominant_freq(&out[out.len() - fft_len..])
847+ };
848+
849+ println!("delta\tf_calib\tf_measured\texpected\terr(bins)");
850+ let mut worst_err_bins = 0.0f64;
851+ for &delta in &[-0.3f64, 0.0, 0.3] {
852+ let sub = analyse(delta);
853+ let f_calib = synth_direct(source_band, &sub);
854+
855+ let mut low_cur = vec![vec![Complex::ZERO; slots]; ANALYSIS_BANDS];
856+ low_cur[source_band] = sub;
857+ let mut chirp = ChirpState::new(1);
858+ let mut history = HfHistory::new(ANALYSIS_BANDS);
859+ let hf = generate(&low_cur, &tables, &[0u8], &mut chirp, &mut history);
860+ let row = &hf[target_band - tables.kx as usize];
861+ let f_measured = synth_direct(target_band, row);
862+
863+ // Frequency-pure placement (what `band_shift_correction` would
864+ // restore, were it applied) minus the one-band-width shift the
865+ // uncorrected bank convention actually leaves in place.
866+ let k = crate::sbr_hf::band_shift_correction(target_band, source_band);
867+ let expected = f_calib
868+ + (target_band as i64 - source_band as i64) as f64 * band_spacing_s
869+ - k as f64 * band_spacing_s;
870+ let bin_width = 1.0 / fft_len as f64;
871+ let err_bins = (f_measured - expected).abs() / bin_width;
872+ worst_err_bins = f64::max(worst_err_bins, err_bins);
873+ println!("{delta:+.2}\t{f_calib:.6}\t{f_measured:.6}\t{expected:.6}\t{err_bins:.2}");
874+ }
875+ assert!(
876+ worst_err_bins <= 3.0,
877+ "worst production-path prediction error {worst_err_bins} bins exceeds 3 -- \
878+ sbr_hf::generate's raw (uncorrected) patch replay no longer matches the \
879+ uncorrected bank convention's own predicted placement"
880+ );
881+ }
882+
778 /// Round-13 (queue item 2, "gain-level issue" bucket): per-band883 /// Round-13 (queue item 2, "gain-level issue" bucket): per-band
779 /// steady-state synthesis amplitude gain for a PHYSICALLY REAL tone at884 /// steady-state synthesis amplitude gain for a PHYSICALLY REAL tone at
780 /// each synthesis band's own centre frequency -- unlike a naive885 /// each synthesis band's own centre frequency -- unlike a naive