diff --git a/Cargo.lock b/Cargo.lock index 1c075aa2..10d7a0df 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -419,6 +419,7 @@ dependencies = [ "ec-core", "ec-dsp", "ec-ogg", + "rustfft", "wide", ] @@ -987,6 +988,15 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "primal-check" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc0d895b311e3af9902528fbb8f928688abbd95872819320517cc24ca6b2bd08" +dependencies = [ + "num-integer", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -1207,6 +1217,20 @@ dependencies = [ "ec-opus", ] +[[package]] +name = "rustfft" +version = "6.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21db5f9893e91f41798c88680037dba611ca6674703c1a18601b01a72c8adb89" +dependencies = [ + "num-complex", + "num-integer", + "num-traits", + "primal-check", + "strength_reduce", + "transpose", +] + [[package]] name = "rustversion" version = "1.0.23" @@ -1287,6 +1311,12 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" +[[package]] +name = "strength_reduce" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe895eb47f22e2ddd4dabc02bce419d2e643c8e3b585c78158b349195bc24d82" + [[package]] name = "symphonia" version = "0.6.0" @@ -1371,6 +1401,16 @@ dependencies = [ "zune-jpeg", ] +[[package]] +name = "transpose" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad61aed86bc3faea4300c7aee358b4c6d0c8d6ccc36524c96e4c92ccf26e77e" +dependencies = [ + "num-integer", + "strength_reduce", +] + [[package]] name = "unicode-ident" version = "1.0.24" diff --git a/crates/ec-opus/Cargo.toml b/crates/ec-opus/Cargo.toml index 6d68c1a2..58fe05b0 100644 --- a/crates/ec-opus/Cargo.toml +++ b/crates/ec-opus/Cargo.toml @@ -10,7 +10,15 @@ authors.workspace = true ec-core.workspace = true ec-dsp.workspace = true wide.workspace = true +# Optional FFT backend (pure Rust, runtime-detected AVX kernels, no C): the +# family stays dependency-free without it (`--no-default-features`); the +# speed bench pulls it in behind `fft-rustfft`. +rustfft = { version = "6", optional = true, default-features = false } [dev-dependencies] ec-dsp.workspace = true ec-ogg.workspace = true + +[features] +default = ["fft-rustfft"] +fft-rustfft = ["dep:rustfft"] diff --git a/crates/ec-opus/src/analysis.rs b/crates/ec-opus/src/analysis.rs index 52b2fad1..18c1e8bc 100644 --- a/crates/ec-opus/src/analysis.rs +++ b/crates/ec-opus/src/analysis.rs @@ -120,7 +120,7 @@ impl Default for AnalysisInfo { /// libopus `fast_atan2f()` — the rational approximation `analysis.c` uses for /// the per-bin phase, kept because the tonality features are calibrated on it. -fn fast_atan2f(y: f32, x: f32) -> f32 { +pub(crate) fn fast_atan2f(y: f32, x: f32) -> f32 { const CA: f32 = 0.431_579_74; const CB: f32 = 0.678_484_04; const CC: f32 = 0.085_955_42; diff --git a/crates/ec-opus/src/celt.rs b/crates/ec-opus/src/celt.rs index 428d5414..2ad87710 100644 --- a/crates/ec-opus/src/celt.rs +++ b/crates/ec-opus/src/celt.rs @@ -22,7 +22,6 @@ //! exactly as the reference does it, never an O(N^2) direct evaluation. use ec_core::{Error, Result}; -use ec_dsp::Fft; use crate::range::{RangeDecoder, RangeEncoder}; @@ -294,83 +293,155 @@ pub(crate) fn overlap_window() -> Vec { // The N/4 FFT and the inverse MDCT // --------------------------------------------------------------------------- -/// A complex FFT of size `15 * 2^k`, the only sizes CELT needs. +/// A complex inverse FFT of the sizes CELT needs (`15 * 2^k`). /// -/// [`ec_dsp::Fft`] covers the `2^k` factor; the factor of 15 is one extra -/// decimation stage, so the whole transform stays `O(n log n)` without a -/// mixed-radix kernel in the DSP crate. -#[derive(Clone, Debug)] -pub(crate) struct Fft15 { - n: usize, - /// Sub-transform of length `n/15`. - sub: Fft, - /// `exp(2 pi i * k1 * n2 / n)` twiddles, split. - tw_re: Vec, - tw_im: Vec, - scratch_re: Vec, - scratch_im: Vec, -} +/// Two backends behind one signature, selected at compile time: +/// +/// - default, the in-project shape: [`ec_dsp::Fft`] covers the `2^k` factor +/// and the factor of 15 is one extra decimation stage (3 x 5), so the whole +/// transform stays `O(n log n)` without a mixed-radix kernel in the DSP +/// crate; +/// - under the optional `fft-rustfft` feature, a rustfft plan plans the size +/// directly (pure Rust, runtime-detected AVX butterflies, no C). The +/// family's dependency-free build stays the default; the feature is the +/// measured speed option. +/// +/// Both deliver the same contract: an UNSCALED inverse transform, +/// `X[k] = sum x[n] exp(+2 pi i n k / N)`, over split-complex buffers. +#[cfg(not(feature = "fft-rustfft"))] +mod fft15 { + use super::dft15; + use ec_dsp::Fft; + + #[derive(Clone, Debug)] + pub(crate) struct Fft15 { + n: usize, + /// Sub-transform of length `n/15`. + sub: Fft, + /// `exp(2 pi i * k1 * n2 / n)` twiddles, split. + tw_re: Vec, + tw_im: Vec, + scratch_re: Vec, + scratch_im: Vec, + } + + impl Fft15 { + pub(crate) fn new(n: usize) -> Fft15 { + assert!(n.is_multiple_of(15) && (n / 15).is_power_of_two()); + let l = n / 15; + let mut tw_re = vec![0.0; n]; + let mut tw_im = vec![0.0; n]; + for k1 in 0..15 { + for n2 in 0..l { + let a = 2.0 * core::f64::consts::PI * (k1 * n2) as f64 / n as f64; + tw_re[k1 * l + n2] = a.cos() as f32; + tw_im[k1 * l + n2] = a.sin() as f32; + } + } + Fft15 { + n, + sub: Fft::new(l), + tw_re, + tw_im, + scratch_re: vec![0.0; n], + scratch_im: vec![0.0; n], + } + } -impl Fft15 { - pub(crate) fn new(n: usize) -> Fft15 { - assert!(n.is_multiple_of(15) && (n / 15).is_power_of_two()); - let l = n / 15; - let mut tw_re = vec![0.0; n]; - let mut tw_im = vec![0.0; n]; - for k1 in 0..15 { + /// Unscaled inverse transform. + pub(crate) fn inverse(&mut self, re: &mut [f32], im: &mut [f32]) { + let n = self.n; + let l = n / 15; + debug_assert_eq!(re.len(), n); + // Stage 1: 15-point DFTs over n1 at stride L, twiddled on the way + // out. for n2 in 0..l { - let a = 2.0 * core::f64::consts::PI * (k1 * n2) as f64 / n as f64; - tw_re[k1 * l + n2] = a.cos() as f32; - tw_im[k1 * l + n2] = a.sin() as f32; + let mut xr = [0.0f32; 15]; + let mut xi = [0.0f32; 15]; + for n1 in 0..15 { + xr[n1] = re[l * n1 + n2]; + xi[n1] = im[l * n1 + n2]; + } + let (yr, yi) = dft15(&xr, &xi); + for k1 in 0..15 { + let (tr, ti) = (self.tw_re[k1 * l + n2], self.tw_im[k1 * l + n2]); + self.scratch_re[k1 * l + n2] = yr[k1] * tr - yi[k1] * ti; + self.scratch_im[k1 * l + n2] = yr[k1] * ti + yi[k1] * tr; + } } - } - Fft15 { - n, - sub: Fft::new(l), - tw_re, - tw_im, - scratch_re: vec![0.0; n], - scratch_im: vec![0.0; n], - } - } - - /// Unscaled inverse transform: `X[k] = sum x[n] exp(+2 pi i n k / N)`. - pub(crate) fn inverse(&mut self, re: &mut [f32], im: &mut [f32]) { - let n = self.n; - let l = n / 15; - debug_assert_eq!(re.len(), n); - // Stage 1: 15-point DFTs over n1 at stride L, twiddled on the way out. - for n2 in 0..l { - let mut xr = [0.0f32; 15]; - let mut xi = [0.0f32; 15]; - for n1 in 0..15 { - xr[n1] = re[l * n1 + n2]; - xi[n1] = im[l * n1 + n2]; - } - let (yr, yi) = dft15(&xr, &xi); + // Stage 2: L-point transforms, one per k1, written out at stride + // 15. ec-dsp scales its inverse by 1/L; undo that to keep the + // transform unscaled, which is what the MDCT expects. for k1 in 0..15 { - let (tr, ti) = (self.tw_re[k1 * l + n2], self.tw_im[k1 * l + n2]); - self.scratch_re[k1 * l + n2] = yr[k1] * tr - yi[k1] * ti; - self.scratch_im[k1 * l + n2] = yr[k1] * ti + yi[k1] * tr; + let rr = &mut self.scratch_re[k1 * l..(k1 + 1) * l]; + let ii = &mut self.scratch_im[k1 * l..(k1 + 1) * l]; + self.sub.inverse_split(rr, ii); + for (k2, (&r, &i)) in rr.iter().zip(ii.iter()).enumerate() { + re[k1 + 15 * k2] = r * l as f32; + im[k1 + 15 * k2] = i * l as f32; + } } } - // Stage 2: L-point transforms, one per k1, written out at stride 15. - for k1 in 0..15 { - let rr = &mut self.scratch_re[k1 * l..(k1 + 1) * l]; - let ii = &mut self.scratch_im[k1 * l..(k1 + 1) * l]; - // ec-dsp scales its inverse by 1/L; undo that to keep the - // transform unscaled, which is what the MDCT expects. - self.sub.inverse_split(rr, ii); - for (k2, (&r, &i)) in rr.iter().zip(ii.iter()).enumerate() { - re[k1 + 15 * k2] = r * l as f32; - im[k1 + 15 * k2] = i * l as f32; + } +} + +#[cfg(feature = "fft-rustfft")] +mod fft15 { + use rustfft::num_complex::Complex; + use std::sync::Arc; + + #[derive(Clone)] + pub(crate) struct Fft15 { + n: usize, + plan: Arc>, + cbuf: Vec>, + /// Preallocated once: `process` would allocate this per call, and the + /// encoder's steady-state loop is a zero-allocation contract. + scratch: Vec>, + } + + impl core::fmt::Debug for Fft15 { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.debug_struct("Fft15").field("n", &self.n).finish() + } + } + + impl Fft15 { + pub(crate) fn new(n: usize) -> Fft15 { + assert!(n.is_multiple_of(15) && (n / 15).is_power_of_two()); + let mut planner = rustfft::FftPlanner::::new(); + let plan = planner.plan_fft_inverse(n); + let cbuf = vec![Complex::ZERO; n]; + let scratch = vec![Complex::ZERO; plan.get_inplace_scratch_len()]; + Fft15 { + n, + plan, + cbuf, + scratch, + } + } + + /// Unscaled inverse transform. rustfft does not scale, which is + /// exactly the contract here. + pub(crate) fn inverse(&mut self, re: &mut [f32], im: &mut [f32]) { + for (c, (r, i)) in self.cbuf.iter_mut().zip(re.iter().zip(im.iter())) { + *c = Complex::new(*r, *i); + } + self.plan + .process_with_scratch(&mut self.cbuf, &mut self.scratch); + for ((c, r), i) in self.cbuf.iter().zip(re.iter_mut()).zip(im.iter_mut()) { + *r = c.re; + *i = c.im; } } } } +pub(crate) use fft15::Fft15; + /// A 15-point DFT as 5 radix-3 stages then 3 radix-5 stages (Cooley-Tukey on /// 15 = 3*5), which costs about a third of the direct evaluation. +#[cfg(not(feature = "fft-rustfft"))] #[inline] fn dft15(xr: &[f32; 15], xi: &[f32; 15]) -> ([f32; 15], [f32; 15]) { // exp(+2 pi i / 3) and the two fifth-root cosines/sines. @@ -558,71 +629,124 @@ impl ImdctPlan { // PVQ // --------------------------------------------------------------------------- -/// Builds the `U(n, .)` row used to count PVQ codewords, returning `V(n, k)`. -/// -/// `V(n,k) = U(n,k) + U(n,k+1)` with `U` obeying -/// `u[n][k] = u[n-1][k] + u[n][k-1] + u[n-1][k-1]` (Section 4.3.4.2). -fn pvq_urow(n: usize, k: usize, u: &mut [u32]) -> u32 { - u[0] = 0; - u[1] = 1; - for (j, slot) in u.iter_mut().enumerate().take(k + 2).skip(2) { - *slot = (2 * j - 1) as u32; - } - for _ in 2..n { - unext(&mut u[1..k + 2], 1); - } - u[k].wrapping_add(u[k + 1]) +/// Offsets of each `U` row in the flat table below (`CELT_PVQ_U_ROW`, the +/// non-custom reference build's layout): row `m` holds `U(m, c)` at index +/// `PVQ_U_ROW[m] + c` for `c ≥ m`, exploiting the symmetry `U(n, k) = U(k, n)`. +/// The walks below only ever read entries with `min(n, k) ≤ 14`, which holds +/// because every entry they read is bounded by `i < V(n, k)` — a bound the +/// range decode enforces and the cache-bounded allocation guarantees. +const PVQ_U_ROW: [usize; 16] = [ + 0, 176, 351, 525, 698, 870, 1041, 1131, 1178, 1207, 1226, 1240, 1248, 1254, 1257, 1272, +]; +const PVQ_U_LEN: usize = PVQ_U_ROW[15]; + +/// The flat `U` table, computed at compile time from the same recurrence the +/// row-stepping used, `U(m,c) = U(m-1,c) + U(m,c-1) + U(m-1,c-1)` off +/// `U(0,0) = 1` (Section 4.3.4.2), in wrapping arithmetic: unreachable entries +/// wrap exactly as the runtime stepping wrapped. +const fn compute_pvq_u() -> [u32; PVQ_U_LEN] { + // The full triangle for a ≤ 14, b ≤ 176 (the widest standard band), + // then scattered so `U(m, c)` sits at `PVQ_U_ROW[m] + c`. + let mut uu = [[0u32; 177]; 15]; + uu[0][0] = 1; // U(0,0)=1; U(0,b>0) = U(a>0,0) = 0. + let mut a = 1; + while a < 15 { + let mut b = 1; + while b < 177 { + uu[a][b] = uu[a - 1][b].wrapping_add(uu[a][b - 1]).wrapping_add(uu[a - 1][b - 1]); + b += 1; + } + a += 1; + } + let mut d = [0u32; PVQ_U_LEN]; + let mut m = 0; + while m < 15 { + let start = PVQ_U_ROW[m] + m; // raw start of row m + let end = if m < 14 { + PVQ_U_ROW[m + 1] + (m + 1) + } else { + PVQ_U_ROW[15] + }; + let mut p = start; + while p < end { + d[p] = uu[m][p - PVQ_U_ROW[m]]; + p += 1; + } + m += 1; + } + d } -/// Steps a `U` row up one dimension in place. -pub(crate) fn unext(u: &mut [u32], mut ui0: u32) { - for j in 1..u.len() { - let ui1 = u[j].wrapping_add(u[j - 1]).wrapping_add(ui0); - u[j - 1] = ui0; - ui0 = ui1; - } - let last = u.len() - 1; - u[last] = ui0; +static PVQ_U: [u32; PVQ_U_LEN] = compute_pvq_u(); + +/// `U(n, k)` from the table. +#[inline] +pub(crate) fn pvq_u(n: usize, k: usize) -> u32 { + let (lo, hi) = if n < k { (n, k) } else { (k, n) }; + debug_assert!(lo <= 14, "U({n},{k}) outside the reference table"); + PVQ_U[PVQ_U_ROW[lo] + hi] } -/// Steps a `U` row down one dimension in place. -fn uprev(u: &mut [u32], mut ui0: u32) { - for j in 1..u.len() { - let ui1 = u[j].wrapping_sub(u[j - 1]).wrapping_sub(ui0); - u[j - 1] = ui0; - ui0 = ui1; - } - let last = u.len() - 1; - u[last] = ui0; +/// `V(n, k) = U(n,k) + U(n,k+1)`: the size of the `(n, k)` PVQ codebook. +#[inline] +pub(crate) fn pvq_v(n: usize, k: usize) -> u32 { + pvq_u(n, k).wrapping_add(pvq_u(n, k + 1)) } /// Decodes one PVQ codeword of `k` pulses in `n` dimensions. -pub(crate) fn decode_pulses( - dec: &mut RangeDecoder, - n: usize, - k: usize, - y: &mut [i32], - u: &mut [u32], -) { - let v = pvq_urow(n, k, u); +/// +/// The reference Appendix A unranking walk (`cwrsi`), with the `U` row read +/// from the table instead of stepped one dimension at a time: `O(N)` lookups +/// rather than `O(N·K)` row arithmetic. +pub(crate) fn decode_pulses(dec: &mut RangeDecoder, n: usize, k: usize, y: &mut [i32]) { + let v = pvq_v(n, k); let mut i = dec.dec_uint(v.max(2)); + let dims = n; + let mut n = n; let mut k = k; - for slot in y.iter_mut().take(n) { - let p = u[k + 1]; - let neg = i >= p; - if neg { + for slot in y.iter_mut().take(dims) { + if n > 2 { + let mut p = pvq_u(n, k + 1); + let neg = i >= p; + if neg { + i -= p; + } + let k0 = k; + p = pvq_u(n, k); + while p > i { + k -= 1; + p = pvq_u(n, k); + } i -= p; + let mag = (k0 - k) as i32; + *slot = if neg { -mag } else { mag }; + n -= 1; + } else if n == 2 { + // `U(2, k) = 2k-1` and `U(2, k+1) = 2k+1`: one sign, then the + // largest split the index leaves room for. + let p = 2 * k as u32 + 1; + let neg = i >= p; + if neg { + i -= p; + } + let k0 = k; + k = ((i + 1) >> 1) as usize; + if k != 0 { + i -= 2 * k as u32 - 1; + } + let mag = (k0 - k) as i32; + *slot = if neg { -mag } else { mag }; + n -= 1; + } else { + // `U(1, k)` is 1 for k ≥ 1 and 0 at k = 0, so `V(1, k) = 2`: the + // index is one sign plus a remainder that is already zero here. + let neg = i >= 1; + if neg { + i -= 1; + } + debug_assert_eq!(i, 0, "PVQ index overrun at the last dimension"); + *slot = if neg { -(k as i32) } else { k as i32 }; } - let k0 = k; - let mut p = u[k]; - while p > i { - k -= 1; - p = u[k]; - } - i -= p; - let mag = (k0 - k) as i32; - *slot = if neg { -mag } else { mag }; - uprev(&mut u[..k + 2], 0); } } @@ -1182,7 +1306,6 @@ pub struct CeltDecoder { tf_res: [i32; NB_BANDS], collapse_masks: [u8; 2 * NB_BANDS], iy: Vec, - urow: Vec, mdct_buf: Vec, diag: CeltDecDiag, } @@ -1225,7 +1348,6 @@ impl CeltDecoder { tf_res: [0; NB_BANDS], collapse_masks: [0; 2 * NB_BANDS], iy: vec![0; max_n], - urow: vec![0; 256], mdct_buf: vec![0.0; max_n + OVERLAP], diag: CeltDecDiag { silence: false, @@ -2355,10 +2477,7 @@ impl CeltDecoder { b_blocks: usize, gain: f32, ) -> u32 { - if self.urow.len() < k + 2 { - self.urow.resize(k + 2, 0); - } - decode_pulses(dec, n, k, &mut self.iy, &mut self.urow); + decode_pulses(dec, n, k, &mut self.iy); let mut ryy = 0.0f32; for j in 0..n { ryy += (self.iy[j] * self.iy[j]) as f32; @@ -2623,14 +2742,28 @@ pub(crate) fn get_pulses(i: i32) -> i32 { } } +/// Longest CACHE_BITS row is far under this (the whole table is 392 bytes); +/// the fixed local window in [`bits2pulses`] lets the bisection compile +/// without a bounds check per access. +const CACHE_ROW_MAX: usize = 64; + pub(crate) fn bits2pulses(band: usize, lm: i32, bits: i32) -> i32 { - let cache = &CACHE_BITS[cache_index(band, lm)..]; + let base = cache_index(band, lm); + let count = CACHE_BITS[base] as usize; + // Statically decidable from the unchanged CACHE_BITS table (reviewer P3); + // the copy below still panics if the table ever outgrew the window. + debug_assert!( + count < CACHE_ROW_MAX, + "CACHE_BITS row overflows the fixed window" + ); + let mut row = [0u8; CACHE_ROW_MAX]; + row[..=count].copy_from_slice(&CACHE_BITS[base..=base + count]); let mut lo = 0i32; - let mut hi = cache[0] as i32; + let mut hi = count as i32; let bits = bits - 1; for _ in 0..6 { let mid = (lo + hi + 1) >> 1; - if cache[mid as usize] as i32 >= bits { + if row[mid as usize] as i32 >= bits { hi = mid; } else { lo = mid; @@ -2639,9 +2772,9 @@ pub(crate) fn bits2pulses(band: usize, lm: i32, bits: i32) -> i32 { let lo_cost = if lo == 0 { -1 } else { - cache[lo as usize] as i32 + row[lo as usize] as i32 }; - if bits - lo_cost <= cache[hi as usize] as i32 - bits { + if bits - lo_cost <= row[hi as usize] as i32 - bits { lo } else { hi @@ -2652,8 +2785,8 @@ pub(crate) fn pulses2bits(band: usize, lm: i32, pulses: i32) -> i32 { if pulses == 0 { return 0; } - let cache = &CACHE_BITS[cache_index(band, lm)..]; - cache[pulses as usize] as i32 + 1 + let base = cache_index(band, lm); + CACHE_BITS[base + pulses as usize] as i32 + 1 } /// One level of the Haar transform, used for the time/frequency changes. @@ -2946,21 +3079,58 @@ mod tests { #[test] fn pvq_index_round_trips_within_v() { // V(N,K) from the recursion in Section 4.3.4.2, checked against the - // closed forms the RFC gives for small N. - let mut u = vec![0u32; 300]; - assert_eq!(pvq_urow(2, 1, &mut u), 4); - assert_eq!(pvq_urow(2, 3, &mut u), 12); - assert_eq!(pvq_urow(3, 2, &mut u), 18); - assert_eq!(pvq_urow(4, 2, &mut u), 32); - // V(N,K) = V(N-1,K) + V(N,K-1) + V(N-1,K-1). + // closed forms the RFC gives for small N, and the table against a + // fresh runtime build of the same recurrence over the whole stored + // triangle. + assert_eq!(pvq_v(2, 1), 4); + assert_eq!(pvq_v(2, 3), 12); + assert_eq!(pvq_v(3, 2), 18); + assert_eq!(pvq_v(4, 2), 32); + // U(N,K) = U(N-1,K) + U(N,K-1) + U(N-1,K-1). for n in 3..8usize { for k in 2..8usize { - let mut a = vec![0u32; 300]; - let v = pvq_urow(n, k, &mut a); - let v1 = pvq_urow(n - 1, k, &mut a); - let v2 = pvq_urow(n, k - 1, &mut a); - let v3 = pvq_urow(n - 1, k - 1, &mut a); - assert_eq!(v, v1 + v2 + v3, "V({n},{k})"); + let (v1, v2, v3, v) = + (pvq_v(n - 1, k), pvq_v(n, k - 1), pvq_v(n - 1, k - 1), pvq_v(n, k)); + assert_eq!(v, v1.wrapping_add(v2).wrapping_add(v3), "V({n},{k})"); + } + } + // The table equals the runtime row-stepping everywhere it is stored: + // rows 0..15, columns as laid out by PVQ_U_ROW. + let mut u = vec![0u32; 400]; + for n in 0..=176usize { + for k in 0..=176usize { + let (lo, hi) = if n < k { (n, k) } else { (k, n) }; + if lo > 14 { + continue; + } + let col_max = if lo < 14 { + PVQ_U_ROW[lo + 1] - PVQ_U_ROW[lo] + lo + } else { + 14 + }; + if hi > col_max || hi < 2 { + // Outside the stored span, or a base row the row-stepping + // never built (rows 0 and 1 are its seeds). + continue; + } + // Runtime U via the old row-stepping, in wrapping arithmetic. + u[0] = 0; + u[1] = 1; + for (j, slot) in u.iter_mut().enumerate().take(hi + 2).skip(2) { + *slot = (2 * j - 1) as u32; + } + for _ in 2..hi { + // unext over the slice u[1..lo+2] with ui0 = 1, exactly as + // the row-stepping drove it. + let mut ui0 = 1u32; + for j in 2..lo + 2 { + let ui1 = u[j].wrapping_add(u[j - 1]).wrapping_add(ui0); + u[j - 1] = ui0; + ui0 = ui1; + } + u[lo + 1] = ui0; + } + assert_eq!(pvq_u(hi, lo), u[lo], "U({hi},{lo})"); } } } diff --git a/crates/ec-opus/src/celt_enc.rs b/crates/ec-opus/src/celt_enc.rs index dff7405c..a5d33452 100644 --- a/crates/ec-opus/src/celt_enc.rs +++ b/crates/ec-opus/src/celt_enc.rs @@ -40,7 +40,6 @@ use crate::celt::{ SPREAD_NONE, SPREAD_NORMAL, TF_SELECT, TRIM_ICDF, bitexact_cos, bitexact_log2tan, bits2pulses, cache_index, compute_allocation_encode, compute_qn, deinterleave_hadamard, exp_rotation, frac_mul16, get_pulses, haar1, pulses2bits, - unext, }; use crate::range::RangeEncoder; @@ -296,31 +295,22 @@ fn laplace_encode(enc: &mut RangeEncoder, value: &mut i32, mut fs: u32, decay: i /// `encode_pulses()` for the general case: index the pulse vector in the /// V(N,K) enumeration and code it as one uniform symbol (Section 5.3.4). -fn encode_pulses(enc: &mut RangeEncoder, iy: &[i32], n: usize, k: usize, u: &mut [u32]) { +fn encode_pulses(enc: &mut RangeEncoder, iy: &[i32], n: usize, k: usize) { debug_assert!(n >= 2 && k > 0); - u[0] = 0; - for (kk, slot) in u.iter_mut().enumerate().take(k + 2).skip(1) { - *slot = (2 * kk - 1) as u32; - } - let mut i = u32::from(iy[n - 1] < 0); - let mut kk = iy[n - 1].unsigned_abs() as usize; - let j = n - 2; - i = i.wrapping_add(u[kk]); - kk += iy[j].unsigned_abs() as usize; - if iy[j] < 0 { - i = i.wrapping_add(u[kk + 1]); - } - let mut j = j; + let mut j = n - 1; + let mut i = u32::from(iy[j] < 0); + let mut kk = iy[j].unsigned_abs() as usize; while j > 0 { j -= 1; - unext(&mut u[..k + 2], 0); - i = i.wrapping_add(u[kk]); + // The row the reference stepping left in place at this dimension is + // `U(n - j, .)`; read it from the table instead. + i = i.wrapping_add(celt::pvq_u(n - j, kk)); kk += iy[j].unsigned_abs() as usize; if iy[j] < 0 { - i = i.wrapping_add(u[kk + 1]); + i = i.wrapping_add(celt::pvq_u(n - j, kk + 1)); } } - let nc = u[kk].wrapping_add(u[kk + 1]); + let nc = celt::pvq_v(n, kk); enc.enc_uint(i, nc.max(2)); } @@ -345,10 +335,13 @@ fn stereo_itheta(x: &[f32], y: &[f32], stereo: bool, n: usize) -> i32 { let mid = emid.sqrt(); let side = eside.sqrt(); // 0.63662 is the reference's own 2/pi literal (vq.c, stereo_itheta); the - // exact constant would round a boundary theta differently. + // exact constant would round a boundary theta differently. The angle is + // the reference float build's `fast_atan2f` (the rational approximation + // the tonality features share), which also keeps libm's `atan2` out of + // the per-band loop. #[allow(clippy::approx_constant)] - const TWO_OVER_PI: f64 = 0.63662; - (0.5 + 16384.0 * TWO_OVER_PI * (side as f64).atan2(mid as f64)).floor() as i32 + const TWO_OVER_PI: f32 = 0.63662; + (TWO_OVER_PI * 16384.0 * crate::analysis::fast_atan2f(side, mid) + 0.5).floor() as i32 } /// `l1_metric()` from the reference: L1 norm scaled by `(1 + LM*bias)`. @@ -529,7 +522,6 @@ pub struct CeltEncoder { iy: Vec, pvq_y: Vec, pvq_sign: Vec, - urow: Vec, /// Per-frame diagnostics captured at the end of the last `encode` call. last_diag: CeltFrameDiag, /// libopus `st->analysis`'s per-frame output, handed in by @@ -592,7 +584,6 @@ impl CeltEncoder { iy: vec![0; max_n], pvq_y: vec![0.0; max_n], pvq_sign: vec![0; max_n], - urow: vec![0; 1280], last_diag: CeltFrameDiag::default(), info: AnalysisInfo::default(), } @@ -2681,10 +2672,7 @@ impl CeltEncoder { iy[j] = -iy[j]; } } - if self.urow.len() < k + 2 { - self.urow.resize(k + 2, 0); - } - encode_pulses(enc, &self.iy[..n], n, k, &mut self.urow); + encode_pulses(enc, &self.iy[..n], n, k); } } @@ -2787,15 +2775,13 @@ mod tests { } let mut enc = RangeEncoder::new(); enc.reset(600); - let mut u = vec![0u32; k + 2]; - encode_pulses(&mut enc, &iy, n, k, &mut u); + encode_pulses(&mut enc, &iy, n, k); enc.done(); assert!(!enc.error()); let data = enc.data().to_vec(); let mut dec = RangeDecoder::new(&data); let mut got = vec![0i32; n]; - let mut u2 = vec![0u32; k + 2]; - crate::celt::decode_pulses(&mut dec, n, k, &mut got, &mut u2); + crate::celt::decode_pulses(&mut dec, n, k, &mut got); assert_eq!(got, iy, "n={n} k={k}"); } } diff --git a/lanes/opus-perf-r1.report.md b/lanes/opus-perf-r1.report.md new file mode 100644 index 00000000..9fca876e --- /dev/null +++ b/lanes/opus-perf-r1.report.md @@ -0,0 +1,148 @@ +# lane-opusperf — ec-opus speed A/B vs the FFT-built comparators (r1) + +Charter: close the ~1.5x ec-opus speed gap vs ruopus 0.1.2 [std, spectrograms] +(decode) and opus-rs 0.1.26 (encode), the exact builds the old edith seats ran. +Branch lane-opusperf off d27a904d. Worktree-only; no merges, no pushes. + +## Method + +- A/B harness: `~/Documents/Code/Rust/opus-perf-ab` (scratch crate, outside the + family workspace; ec-opus by path into THIS worktree). Also rsynced to + server-3 (user@host-b, `~/opusperf/`) with the media. +- Media: a real 5.1 film (`~/Videos/Films/reelc.mkv`, + read-only). `full51.opus` = the full 5.1 track remuxed by ffmpeg (clean); + `film2.opus` = libopus 256k stereo transcode of the 600–1320 s window; + `film2_seg.f32` / `film51_seg.f32` = 120 s of f32 PCM from the 600–720 s + window. Both sides of every pair get byte-identical inputs. +- Protocol per row: one warm-up pass each side, then 7 alternating rounds + (A/B and B/A by round), min per side, `/proc/loadavg` captured per round. + Cross-check before the decode rows: both 5.1 decoders over 25 packets, + worst-channel correlation > 0.999, final_range equality asserted. +- Profiles: perf record/annotate on a `prof` driver looping one workload. + +## Baseline (d27a904d, local, loadavg 3.0–3.4) + +| row | ec-opus | comparator | ratio | +|---|---|---|---| +| decode 5.1 120 s film | 170–174x | 246–248x ruopus | 0.69–0.70 | +| decode stereo 120 s film | 346x | 524x ruopus | 0.66 | +| encode 128k CBR stereo | 261x | 438x opus-rs | 0.59 | +| encode 256k CBR stereo | 187x | 319x opus-rs | 0.59 | + +(The campaign's local numbers, 246x vs 407x / 1.41–1.57x, were taken on a +quieter box; sibling lanes were running during this round. All comparisons +below are same-session pairs, so ratios stay comparable.) + +## Profile (the assignment's FFT hypothesis is wrong for both paths) + +- decode stereo: `quant_band` 65% — inside it `decode_pulses` 43% + (pvq_urow row-stepping 19% + uprev 11%); FFT (Fft15::inverse + + inverse_split) ~10%. +- encode 256k: `quant_band` ~60–64% — `alg_quant` ~51% (search + init + + encode_pulses 14%); FFT+MDCT ~9%. `floorf` 3.6%, stereo_itheta's f64 + atan2 ~2.5%. + +## Landed + +### 88f22a66 — PVQ U-table (decode + encode) + +`decode_pulses`/`encode_pulses` now read the reference non-custom build's +1272-entry flat `U` table (const-computed from the same recurrence in +wrapping arithmetic; layout `U(m,c)` at `PVQ_U_ROW[m]+c`, symmetric in +min(n,k)) instead of stepping `U` rows at runtime: O(N) lookups vs O(N·K) +arithmetic. Decoder/encoder `urow` scratch fields deleted; a lib test +cross-checks every stored entry against a fresh runtime row-stepping build. + +Fidelity: full `cargo test -p ec-opus --release` green per commit (35 lib + +28 conformance: RFC 6716 vectors range-state-exact, ffmpeg/libopus +correlation gates, oracle rate table, roundtrips at every rate, +garbage-payload fuzz, speed floors). Zero warnings (`#![forbid(unsafe_code)]` +holds). + +Committed state, local, loadavg 0.3–7 (two consistent batteries): + +| row | ec-opus | comparator | ratio | baseline | +|---|---|---|---|---| +| decode 5.1 | 207x | 251–254x ruopus | 0.82 | 0.70 | +| decode stereo | 461–465x | 529–533x ruopus | 0.86–0.88 | 0.66 | +| encode 128k CBR | 275–276x | 429–431x opus-rs | 0.64 | 0.59 | +| encode 256k CBR | 204–205x | 316–317x opus-rs | 0.65 | 0.59 | +| encode 510k CBR | 185–187x | 201–202x opus-rs | 0.92 | n/a | +| encode 256k VBR | 204–206x | 315–317x opus-rs | 0.65 | n/a | +| encode 256k | 204–206x | 408–411x ruopus | 0.50 | n/a | +| encode 5.1 384k (absolute; no comparator has a multistream encoder) | 87x | — | — | n/a | + +## Measured and reverted (both on top of 88f22a66, not committed) + +- FOUR independent champion groups in the vector sweep (killing the serial + compare chain): no change — 0.65 at 256k either way. The chain was not the + bottleneck. +- Padded 8-lane sweep for ALL band sizes (pad `yy` = 1e17 sentinel): REGRESSED + encode to 153x / 0.48 at 256k. Instrumented counts + (2.24 M alg_quant calls, 398 M scalar lane-visits vs 12 M vector + chunk-visits) made small bands look dominant, but each small-band scalar + visit is cheap and an 8-lane sweep of a 4-sample band wastes lanes. Reverted + (`git checkout`); the instrumentation came out with it. + +## What remains + +1. server-3 clean-machine A/B (media + harness already in `~/opusperf` there) for + an uncontended final table; local numbers above carry sibling load. +2. decode 5.1: 0.82 vs the 0.9 target. The remaining decode cost is spread + (PVQ walk now table-driven); candidates: `bits2pulses` (2.7% linear scan), + `dec_uint` path, denorm/deemphasis loops. +3. encode 256k: 0.65 vs the 0.8 target. The comparator's search is rsqrt-form + AVX2 (libopus 1.6 port); `#![forbid(unsafe_code)]` rules out intrinsics and + `wide` has no rsqrt, so the lever is either a safe rsqrt approximation + (bit-trick via `to_bits`, needs a wide/i32 bridge) or reducing searches + (allocation shape). `stereo_itheta`'s f64 `atan2` (≈2.5%) → the crate's own + `fast_atan2f` is a safe small win. +4. FFT/MDCT lever (~9–10% of each path): realfft behind a default feature or + further kernel shaping — worth it only after 2–3. + +Housekeeping: `opus-perf-ab` is a scratch crate outside the family tree; +`fixtures` symlink in the worktree root is gitignored as usual. + +## Round 2 (c86a49fd) — decode target met + +- `fft-rustfft` (default feature): rustfft plans the MDCT's quarter-size + complex inverse directly (pure Rust, runtime-detected AVX butterflies, no + C). Scratch preallocated — `process` would allocate per call and the + steady-state zero-alloc encode contract caught it. Dependency-free build + stays green under `--no-default-features`. +- `stereo_itheta`: reference float build's `fast_atan2f` instead of libm f64 + `atan2` (~2.5% of encode). +- `bits2pulses`: bisection over a fixed row window (bounds-check folding). + No measurable decode delta on its own — the 6.7% profile share was largely + attribution noise; kept as cleanup. +- Measured and kept: none of the round-1 reverted search variants were + retried; `#![forbid(unsafe_code)]` + `wide` (no bit-cast on `f32x8`) rule + out the comparator's rsqrt-AVX2 shape honestly. + +Fidelity: full suite green on the default build (35 lib + 28 conformance, +zero-alloc encode test included) and the dependency-free lib build green; +per-commit as before. + +### server-3 clean-machine final table (4 vCPU, loadavg 2.2-3.0 at start, +1.1-1.8 at end; min-of-7 alternating; media dir ~/opusperf/media) + +| row | ec-opus | comparator | ratio | +|---|---|---|---| +| decode 5.1 120 s film | 124x | 133x ruopus-FFT | 0.93 | +| decode stereo 120 s film | 279x | 298x ruopus-FFT | 0.93 | +| encode 128k CBR | 169x | 228x opus-rs | 0.74 | +| encode 256k CBR | 127x | 173x opus-rs | 0.74 | +| encode 510k CBR | 114x | 113x opus-rs | 1.01 | +| encode 256k VBR | 127x | 173x opus-rs | 0.73 | +| encode 256k | 128x | 210x ruopus | 0.61 | +| encode 5.1 384k (absolute) | 51x | — | — | + +Targets: decode ≥0.9 of ruopus-FFT — MET (0.93 / 0.93). Encode ≥0.8 of +opus-rs — NOT met honestly: 0.74 at the product rates, 1.01 at 510k. Per the +charter's stop rule the encode lever stops here: the residual gap is the +comparator's rsqrt-AVX2 pulse search, unreachable under the family's +`forbid(unsafe_code)` without a new safe-SIMD shape, and the seat the product +pays is decode-dominated (0.93-0.93 vs the replaced seats' 0.60-0.66). + +Local quiet-box (loadavg ~1.2-1.4, 12-core) same commit: decode 5.1 242x/ +254x = 0.95, stereo 515x/532x = 0.97; encode 0.69-0.70 (256k), 1.00 (510k).