Bladeren bron

XMA: build the inverse transform's rotations once per subframe size

imdct_half worked out every pre- and post-rotation with sin_cos on each
call (n of them per subframe) and ran its FFT on two fresh Vecs. The
rotations, the bit-reversed order and the butterfly rotations now come
from a table built once for 128, 256 and 512 samples; the work buffers
live on the stack. Every value is computed with the same expression (the
butterflies with the same running product), so the output is bit for
bit what it was.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
(cherry picked from commit 4eb0898b3cbd6d0bbbffad540aca5d7e3531ac58)
TG0000 3 dagen geleden
bovenliggende
commit
ade1da1129
1 gewijzigde bestanden met toevoegingen van 296 en 34 verwijderingen
  1. 296 34
      crates/victory-formats/src/xma.rs

+ 296 - 34
crates/victory-formats/src/xma.rs

@@ -293,59 +293,180 @@ fn log2(v: usize) -> u32 {
 /// `n` coefficients to the middle `n` samples of the 2n-sample window,
 /// negated and scaled by `scale`. Computed as a DCT-IV through an
 /// n/2-point complex FFT.
+///
+/// The rotations come from [`Rotations`], built once per subframe size, so
+/// a subframe costs no sines or cosines and no allocation.
 fn imdct_half(input: &[f32], out: &mut [f32], scale: f32) {
     let n = input.len();
     let m = n / 2;
-    let mut re = vec![0f64; m];
-    let mut im = vec![0f64; m];
-    for k in 0..m {
+    let built;
+    let rotations = match rotations().get(log2(n).wrapping_sub(7) as usize) {
+        Some(r) if r.pre_re.len() == m => r,
+        _ => {
+            built = Rotations::new(n);
+            &built
+        }
+    };
+    let mut stack = [0f64; FRAME_SAMPLES];
+    let mut heap = Vec::new();
+    let (re, im) = if m <= stack.len() / 2 {
+        stack.split_at_mut(m)
+    } else {
+        heap.resize(2 * m, 0f64);
+        heap.split_at_mut(m)
+    };
+    let im = &mut im[..m];
+    // Pre-rotation, each point stored at its bit-reversed place, which is
+    // where the FFT's input permutation would move it.
+    let pre = rotations
+        .pre_re
+        .iter()
+        .zip(&rotations.pre_im)
+        .zip(&rotations.reversed);
+    for (k, ((&c, &s), &to)) in pre.enumerate() {
         let (a, b) = (input[2 * k] as f64, input[n - 1 - 2 * k] as f64);
-        let (s, c) = (-std::f64::consts::PI * k as f64 / n as f64).sin_cos();
-        (re[k], im[k]) = (a * c - b * s, a * s + b * c);
+        re[to as usize] = a * c - b * s;
+        im[to as usize] = a * s + b * c;
     }
-    fft(&mut re, &mut im);
-    for k in 0..m {
-        let (s, c) = (-std::f64::consts::PI * (4 * k + 1) as f64 / (4 * n) as f64).sin_cos();
-        let (wr, wi) = (re[k] * c - im[k] * s, re[k] * s + im[k] * c);
+    rotations.butterflies(re, im);
+    let post = rotations.post_re.iter().zip(&rotations.post_im);
+    for (k, ((&re, &im), (&c, &s))) in re.iter().zip(im.iter()).zip(post).enumerate() {
+        let (wr, wi) = (re * c - im * s, re * s + im * c);
         // DCT-IV: c[2k] = Re, c[n-1-2k] = -Im; output j is c[n-1-j].
         out[n - 1 - 2 * k] = (wr as f32) * scale;
         out[2 * k] = -(wi as f32) * scale;
     }
 }
 
-/// In-place radix-2 forward DFT (`exp(-2πi nk/N)`).
-fn fft(re: &mut [f64], im: &mut [f64]) {
-    let n = re.len();
-    let mut j = 0;
-    for i in 1..n {
-        let mut bit = n >> 1;
-        while j & bit != 0 {
-            j ^= bit;
-            bit >>= 1;
-        }
-        j |= bit;
-        if i < j {
-            re.swap(i, j);
-            im.swap(i, j);
+/// Everything [`imdct_half`] needs for one size `n` that does not depend on
+/// the coefficients: the pre-rotation `exp(-iπk/n)` and post-rotation
+/// `exp(-iπ(4k+1)/4n)` of each of the n/2 FFT points, the FFT's bit-reversed
+/// order and its butterfly rotations. Each value is computed with the same
+/// expression (for the butterflies the same running product) the transform
+/// used to work out on every call, so it gives the same bits.
+struct Rotations {
+    pre_re: Vec<f64>,
+    pre_im: Vec<f64>,
+    post_re: Vec<f64>,
+    post_im: Vec<f64>,
+    /// Where the bit-reversal permutation puts each point.
+    reversed: Vec<u16>,
+    /// The butterfly rotations of every stage, the stage of length `len`
+    /// starting at `len / 2 - 1`.
+    twiddle_re: Vec<f64>,
+    twiddle_im: Vec<f64>,
+}
+
+impl Rotations {
+    fn new(n: usize) -> Rotations {
+        let m = n / 2;
+        let (pre_re, pre_im) = (0..m)
+            .map(|k| {
+                let (s, c) = (-std::f64::consts::PI * k as f64 / n as f64).sin_cos();
+                (c, s)
+            })
+            .unzip();
+        let (post_re, post_im) = (0..m)
+            .map(|k| {
+                let (s, c) =
+                    (-std::f64::consts::PI * (4 * k + 1) as f64 / (4 * n) as f64).sin_cos();
+                (c, s)
+            })
+            .unzip();
+        // The swaps of the in-place bit-reversal, applied to the identity.
+        let mut reversed: Vec<u16> = (0..m as u16).collect();
+        let mut j = 0;
+        for i in 1..m {
+            let mut bit = m >> 1;
+            while j & bit != 0 {
+                j ^= bit;
+                bit >>= 1;
+            }
+            j |= bit;
+            if i < j {
+                reversed.swap(i, j);
+            }
         }
-    }
-    let mut len = 2;
-    while len <= n {
-        let (ws, wc) = (-2.0 * std::f64::consts::PI / len as f64).sin_cos();
-        for start in (0..n).step_by(len) {
+        let mut twiddle_re = Vec::with_capacity(m.saturating_sub(1));
+        let mut twiddle_im = Vec::with_capacity(m.saturating_sub(1));
+        let mut len = 2;
+        while len <= m {
+            let (ws, wc) = (-2.0 * std::f64::consts::PI / len as f64).sin_cos();
             let (mut cr, mut ci) = (1.0, 0.0);
-            for k in 0..len / 2 {
-                let (a, b) = (start + k, start + k + len / 2);
-                let (tr, ti) = (re[b] * cr - im[b] * ci, re[b] * ci + im[b] * cr);
-                (re[b], im[b]) = (re[a] - tr, im[a] - ti);
-                (re[a], im[a]) = (re[a] + tr, im[a] + ti);
+            for _ in 0..len / 2 {
+                twiddle_re.push(cr);
+                twiddle_im.push(ci);
                 (cr, ci) = (cr * wc - ci * ws, cr * ws + ci * wc);
             }
+            len <<= 1;
+        }
+        Rotations {
+            pre_re,
+            pre_im,
+            post_re,
+            post_im,
+            reversed,
+            twiddle_re,
+            twiddle_im,
         }
-        len <<= 1;
+    }
+
+    /// The butterfly stages of an in-place radix-2 forward DFT
+    /// (`exp(-2πi nk/N)`) on points already in bit-reversed order.
+    fn butterflies(&self, re: &mut [f64], im: &mut [f64]) {
+        let m = re.len().min(im.len());
+        let mut len = 2;
+        while len <= m {
+            let half = len / 2;
+            let wr = &self.twiddle_re[half - 1..][..half];
+            let wi = &self.twiddle_im[half - 1..][..half];
+            let blocks = re[..m]
+                .chunks_exact_mut(len)
+                .zip(im[..m].chunks_exact_mut(len));
+            for (re, im) in blocks {
+                let (are, bre) = re.split_at_mut(half);
+                let (aim, bim) = im.split_at_mut(half);
+                butterfly_block(are, aim, bre, bim, wr, wi);
+            }
+            len <<= 1;
+        }
+    }
+}
+
+/// One block of butterflies: `a + w·b` into `a`, `a − w·b` into `b`.
+#[inline(always)]
+fn butterfly_block(
+    are: &mut [f64],
+    aim: &mut [f64],
+    bre: &mut [f64],
+    bim: &mut [f64],
+    wr: &[f64],
+    wi: &[f64],
+) {
+    let lanes = are
+        .iter_mut()
+        .zip(aim)
+        .zip(bre.iter_mut().zip(bim))
+        .zip(wr.iter().zip(wi));
+    for (((ar, ai), (br, bi)), (&cr, &ci)) in lanes {
+        let (tr, ti) = (*br * cr - *bi * ci, *br * ci + *bi * cr);
+        (*br, *bi) = (*ar - tr, *ai - ti);
+        (*ar, *ai) = (*ar + tr, *ai + ti);
     }
 }
 
+/// [`Rotations`] for subframes of 128, 256 and 512 samples.
+fn rotations() -> &'static [Rotations; 3] {
+    static ROTATIONS: OnceLock<[Rotations; 3]> = OnceLock::new();
+    ROTATIONS.get_or_init(|| {
+        [
+            Rotations::new(128),
+            Rotations::new(256),
+            Rotations::new(512),
+        ]
+    })
+}
+
 /// `ff_sine_windows`: the rising half of a sine window of length `n`.
 fn sine_window(n: usize) -> Vec<f32> {
     (0..n)
@@ -1115,6 +1236,147 @@ mod tests {
         }
     }
 
+    /// The transform as it was before [`Rotations`]: every rotation worked
+    /// out again on each call, the FFT on two fresh buffers.
+    fn imdct_half_untabled(input: &[f32], out: &mut [f32], scale: f32) {
+        let n = input.len();
+        let m = n / 2;
+        let mut re = vec![0f64; m];
+        let mut im = vec![0f64; m];
+        for k in 0..m {
+            let (a, b) = (input[2 * k] as f64, input[n - 1 - 2 * k] as f64);
+            let (s, c) = (-std::f64::consts::PI * k as f64 / n as f64).sin_cos();
+            (re[k], im[k]) = (a * c - b * s, a * s + b * c);
+        }
+        let mut j = 0;
+        for i in 1..m {
+            let mut bit = m >> 1;
+            while j & bit != 0 {
+                j ^= bit;
+                bit >>= 1;
+            }
+            j |= bit;
+            if i < j {
+                re.swap(i, j);
+                im.swap(i, j);
+            }
+        }
+        let mut len = 2;
+        while len <= m {
+            let (ws, wc) = (-2.0 * std::f64::consts::PI / len as f64).sin_cos();
+            for start in (0..m).step_by(len) {
+                let (mut cr, mut ci) = (1.0, 0.0);
+                for k in 0..len / 2 {
+                    let (a, b) = (start + k, start + k + len / 2);
+                    let (tr, ti) = (re[b] * cr - im[b] * ci, re[b] * ci + im[b] * cr);
+                    (re[b], im[b]) = (re[a] - tr, im[a] - ti);
+                    (re[a], im[a]) = (re[a] + tr, im[a] + ti);
+                    (cr, ci) = (cr * wc - ci * ws, cr * ws + ci * wc);
+                }
+            }
+            len <<= 1;
+        }
+        for k in 0..m {
+            let (s, c) = (-std::f64::consts::PI * (4 * k + 1) as f64 / (4 * n) as f64).sin_cos();
+            let (wr, wi) = (re[k] * c - im[k] * s, re[k] * s + im[k] * c);
+            out[n - 1 - 2 * k] = (wr as f32) * scale;
+            out[2 * k] = -(wi as f32) * scale;
+        }
+    }
+
+    /// Pseudo-random coefficients spread over many magnitudes, as dequantised
+    /// subframes are.
+    fn noise(n: usize, seed: u64) -> Vec<f32> {
+        let mut state = seed | 1;
+        (0..n)
+            .map(|_| {
+                state ^= state << 13;
+                state ^= state >> 7;
+                state ^= state << 17;
+                let mantissa = (state >> 40) as f32 / (1u64 << 24) as f32 - 0.5;
+                mantissa * 2f32.powi((state % 24) as i32 - 4)
+            })
+            .collect()
+    }
+
+    /// The tables change nothing: every subframe size (and sizes the decoder
+    /// never uses, which build their tables on the spot) gives the bits the
+    /// untabled transform gives.
+    #[test]
+    fn tabled_imdct_gives_the_same_bits() {
+        for n in [2usize, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048] {
+            for seed in 0..16 {
+                let input = noise(n, seed * 7919 + n as u64);
+                let scale = 2.0 / n as f32 / 32768.0;
+                let mut tabled = vec![0f32; n];
+                let mut untabled = vec![0f32; n];
+                imdct_half(&input, &mut tabled, scale);
+                imdct_half_untabled(&input, &mut untabled, scale);
+                let tabled: Vec<u32> = tabled.iter().map(|v| v.to_bits()).collect();
+                let untabled: Vec<u32> = untabled.iter().map(|v| v.to_bits()).collect();
+                assert_eq!(tabled, untabled, "n {n}, seed {seed}");
+            }
+        }
+        let mut out = [0f32; 0];
+        imdct_half(&[], &mut out, 1.0);
+    }
+
+    /// The cached tables are the ones the sizes ask for.
+    #[test]
+    fn cached_rotations_match_their_sizes() {
+        for (r, n) in rotations().iter().zip([128usize, 256, 512]) {
+            let fresh = Rotations::new(n);
+            assert_eq!((&r.pre_re, &r.pre_im), (&fresh.pre_re, &fresh.pre_im));
+            assert_eq!((&r.post_re, &r.post_im), (&fresh.post_re, &fresh.post_im));
+            assert_eq!(r.reversed, fresh.reversed);
+            assert_eq!(
+                (&r.twiddle_re, &r.twiddle_im),
+                (&fresh.twiddle_re, &fresh.twiddle_im)
+            );
+            assert_eq!(r.pre_re.len(), n / 2);
+            assert_eq!(r.twiddle_re.len(), n / 2 - 1);
+            // The order is a permutation that undoes itself.
+            for (i, &to) in r.reversed.iter().enumerate() {
+                assert_eq!(r.reversed[to as usize] as usize, i);
+            }
+        }
+    }
+
+    /// Release benchmark of one inverse transform per subframe size, tabled
+    /// against untabled:
+    /// `cargo test --release -p victory-formats imdct_throughput -- --ignored --nocapture`.
+    #[test]
+    #[ignore = "benchmark"]
+    fn imdct_throughput() {
+        for n in [128usize, 256, 512] {
+            let inputs: Vec<Vec<f32>> = (0..64).map(|seed| noise(n, seed)).collect();
+            let mut out = vec![0f32; n];
+            let rounds = 20_000;
+            let mut time = |f: fn(&[f32], &mut [f32], f32)| {
+                let mut best = f64::MAX;
+                for _ in 0..3 {
+                    let started = std::time::Instant::now();
+                    for i in 0..rounds {
+                        f(
+                            std::hint::black_box(&inputs[i % inputs.len()]),
+                            &mut out,
+                            1.0,
+                        );
+                        std::hint::black_box(&out);
+                    }
+                    best = best.min(started.elapsed().as_secs_f64() * 1e9 / rounds as f64);
+                }
+                best
+            };
+            let before = time(imdct_half_untabled);
+            let after = time(imdct_half);
+            println!(
+                "n {n}: untabled {before:.0} ns, tabled {after:.0} ns, {:.1}x",
+                before / after
+            );
+        }
+    }
+
     /// Windowed MDCT blocks of a signal, put back together the way the
     /// decoder does (half IMDCT, then window and overlap), give the signal.
     #[test]