forge
Explore
Log in

Don't you dare go Hollow

Optional rustfft FFT backend becomes the default (fft-rustfft feature

Browse files at this commit

68cf7a69b80f16fa32ec222cdfd758fa2faff4b7Ahmet Kaan GümüşParent: 67663b9
  • perf
    • optional rustfft FFT backend becomes the default (fft-rustfft feature
    • pure Rust, no C
    • scratch preallocated so the steady-state encode stays zero-alloc) and stereo_itheta matches the reference float build's fast_atan2f instead of libm's f64 atan2 — 5.1 film decode 0.82 -> 0.95 of ruopus-FFT, stereo 0.87 -> 0.97, stereo encode 0.65 -> 0.69 of opus-rs (510k at parity 1.00)
    • bits2pulses bisects a fixed row window
    • dependency-free build stays green under --no-default-features
Show full message
perf(ec-opus): optional rustfft FFT backend becomes the default (fft-rustfft feature; pure Rust, no C; scratch preallocated so the steady-state encode stays zero-alloc) and stereo_itheta matches the reference float build's fast_atan2f instead of libm's f64 atan2 — 5.1 film decode 0.82 -> 0.95 of ruopus-FFT, stereo 0.87 -> 0.97, stereo encode 0.65 -> 0.69 of opus-rs (510k at parity 1.00); bits2pulses bisects a fixed row window; dependency-free build stays green under --no-default-features
crates/ec-opus/Cargo.tomlmodified+8 -0
@@ -10,7 +10,15 @@ authors.workspace = true
1010 ec-core.workspace = true
1111 ec-dsp.workspace = true
1212 wide.workspace = true
13+# Optional FFT backend (pure Rust, runtime-detected AVX kernels, no C): the
14+# family stays dependency-free without it (`--no-default-features`); the
15+# speed bench pulls it in behind `fft-rustfft`.
16+rustfft = { version = "6", optional = true, default-features = false }
1317
1418 [dev-dependencies]
1519 ec-dsp.workspace = true
1620 ec-ogg.workspace = true
21+
22+[features]
23+default = ["fft-rustfft"]
24+fft-rustfft = ["dep:rustfft"]
crates/ec-opus/src/analysis.rsmodified+1 -1
@@ -120,7 +120,7 @@ impl Default for AnalysisInfo {
120120
121121 /// libopus `fast_atan2f()` — the rational approximation `analysis.c` uses for
122122 /// the per-bin phase, kept because the tonality features are calibrated on it.
123-fn fast_atan2f(y: f32, x: f32) -> f32 {
123+pub(crate) fn fast_atan2f(y: f32, x: f32) -> f32 {
124124 const CA: f32 = 0.431_579_74;
125125 const CB: f32 = 0.678_484_04;
126126 const CC: f32 = 0.085_955_42;
crates/ec-opus/src/celt.rsmodified+100 -17
@@ -22,7 +22,6 @@
2222 //! exactly as the reference does it, never an O(N^2) direct evaluation.
2323
2424 use ec_core::{Error, Result};
25-use ec_dsp::Fft;
2625
2726 use crate::range::{RangeDecoder, RangeEncoder};
2827
@@ -294,11 +293,26 @@ pub(crate) fn overlap_window() -> Vec<f32> {
294293 // The N/4 FFT and the inverse MDCT
295294 // ---------------------------------------------------------------------------
296295
297-/// A complex FFT of size `15 * 2^k`, the only sizes CELT needs.
296+/// A complex inverse FFT of the sizes CELT needs (`15 * 2^k`).
297+///
298+/// Two backends behind one signature, selected at compile time:
299+///
300+/// - default, the in-project shape: [`ec_dsp::Fft`] covers the `2^k` factor
301+/// and the factor of 15 is one extra decimation stage (3 x 5), so the whole
302+/// transform stays `O(n log n)` without a mixed-radix kernel in the DSP
303+/// crate;
304+/// - under the optional `fft-rustfft` feature, a rustfft plan plans the size
305+/// directly (pure Rust, runtime-detected AVX butterflies, no C). The
306+/// family's dependency-free build stays the default; the feature is the
307+/// measured speed option.
298308 ///
299-/// [`ec_dsp::Fft`] covers the `2^k` factor; the factor of 15 is one extra
300-/// decimation stage, so the whole transform stays `O(n log n)` without a
301-/// mixed-radix kernel in the DSP crate.
309+/// Both deliver the same contract: an UNSCALED inverse transform,
310+/// `X[k] = sum x[n] exp(+2 pi i n k / N)`, over split-complex buffers.
311+#[cfg(not(feature = "fft-rustfft"))]
312+mod fft15 {
313+ use super::dft15;
314+ use ec_dsp::Fft;
315+
302316 #[derive(Clone, Debug)]
303317 pub(crate) struct Fft15 {
304318 n: usize,
@@ -334,12 +348,13 @@ impl Fft15 {
334348 }
335349 }
336350
337- /// Unscaled inverse transform: `X[k] = sum x[n] exp(+2 pi i n k / N)`.
351+ /// Unscaled inverse transform.
338352 pub(crate) fn inverse(&mut self, re: &mut [f32], im: &mut [f32]) {
339353 let n = self.n;
340354 let l = n / 15;
341355 debug_assert_eq!(re.len(), n);
342- // Stage 1: 15-point DFTs over n1 at stride L, twiddled on the way out.
356+ // Stage 1: 15-point DFTs over n1 at stride L, twiddled on the way
357+ // out.
343358 for n2 in 0..l {
344359 let mut xr = [0.0f32; 15];
345360 let mut xi = [0.0f32; 15];
@@ -354,12 +369,12 @@ impl Fft15 {
354369 self.scratch_im[k1 * l + n2] = yr[k1] * ti + yi[k1] * tr;
355370 }
356371 }
357- // Stage 2: L-point transforms, one per k1, written out at stride 15.
372+ // Stage 2: L-point transforms, one per k1, written out at stride
373+ // 15. ec-dsp scales its inverse by 1/L; undo that to keep the
374+ // transform unscaled, which is what the MDCT expects.
358375 for k1 in 0..15 {
359376 let rr = &mut self.scratch_re[k1 * l..(k1 + 1) * l];
360377 let ii = &mut self.scratch_im[k1 * l..(k1 + 1) * l];
361- // ec-dsp scales its inverse by 1/L; undo that to keep the
362- // transform unscaled, which is what the MDCT expects.
363378 self.sub.inverse_split(rr, ii);
364379 for (k2, (&r, &i)) in rr.iter().zip(ii.iter()).enumerate() {
365380 re[k1 + 15 * k2] = r * l as f32;
@@ -368,9 +383,65 @@ impl Fft15 {
368383 }
369384 }
370385 }
386+}
387+
388+#[cfg(feature = "fft-rustfft")]
389+mod fft15 {
390+ use rustfft::num_complex::Complex;
391+ use std::sync::Arc;
392+
393+ #[derive(Clone)]
394+ pub(crate) struct Fft15 {
395+ n: usize,
396+ plan: Arc<dyn rustfft::Fft<f32>>,
397+ cbuf: Vec<Complex<f32>>,
398+ /// Preallocated once: `process` would allocate this per call, and the
399+ /// encoder's steady-state loop is a zero-allocation contract.
400+ scratch: Vec<Complex<f32>>,
401+ }
402+
403+ impl core::fmt::Debug for Fft15 {
404+ fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
405+ f.debug_struct("Fft15").field("n", &self.n).finish()
406+ }
407+ }
408+
409+ impl Fft15 {
410+ pub(crate) fn new(n: usize) -> Fft15 {
411+ assert!(n.is_multiple_of(15) && (n / 15).is_power_of_two());
412+ let mut planner = rustfft::FftPlanner::<f32>::new();
413+ let plan = planner.plan_fft_inverse(n);
414+ let cbuf = vec![Complex::ZERO; n];
415+ let scratch = vec![Complex::ZERO; plan.get_inplace_scratch_len()];
416+ Fft15 {
417+ n,
418+ plan,
419+ cbuf,
420+ scratch,
421+ }
422+ }
423+
424+ /// Unscaled inverse transform. rustfft does not scale, which is
425+ /// exactly the contract here.
426+ pub(crate) fn inverse(&mut self, re: &mut [f32], im: &mut [f32]) {
427+ for (c, (r, i)) in self.cbuf.iter_mut().zip(re.iter().zip(im.iter())) {
428+ *c = Complex::new(*r, *i);
429+ }
430+ self.plan
431+ .process_with_scratch(&mut self.cbuf, &mut self.scratch);
432+ for ((c, r), i) in self.cbuf.iter().zip(re.iter_mut()).zip(im.iter_mut()) {
433+ *r = c.re;
434+ *i = c.im;
435+ }
436+ }
437+ }
438+}
439+
440+pub(crate) use fft15::Fft15;
371441
372442 /// A 15-point DFT as 5 radix-3 stages then 3 radix-5 stages (Cooley-Tukey on
373443 /// 15 = 3*5), which costs about a third of the direct evaluation.
444+#[cfg(not(feature = "fft-rustfft"))]
374445 #[inline]
375446 fn dft15(xr: &[f32; 15], xi: &[f32; 15]) -> ([f32; 15], [f32; 15]) {
376447 // exp(+2 pi i / 3) and the two fifth-root cosines/sines.
@@ -2671,14 +2742,26 @@ pub(crate) fn get_pulses(i: i32) -> i32 {
26712742 }
26722743 }
26732744
2745+/// Longest CACHE_BITS row is far under this (the whole table is 392 bytes);
2746+/// the fixed local window in [`bits2pulses`] lets the bisection compile
2747+/// without a bounds check per access.
2748+const CACHE_ROW_MAX: usize = 64;
2749+
26742750 pub(crate) fn bits2pulses(band: usize, lm: i32, bits: i32) -> i32 {
2675- let cache = &CACHE_BITS[cache_index(band, lm)..];
2751+ let base = cache_index(band, lm);
2752+ let count = CACHE_BITS[base] as usize;
2753+ assert!(
2754+ count < CACHE_ROW_MAX,
2755+ "CACHE_BITS row overflows the fixed window"
2756+ );
2757+ let mut row = [0u8; CACHE_ROW_MAX];
2758+ row[..=count].copy_from_slice(&CACHE_BITS[base..=base + count]);
26762759 let mut lo = 0i32;
2677- let mut hi = cache[0] as i32;
2760+ let mut hi = count as i32;
26782761 let bits = bits - 1;
26792762 for _ in 0..6 {
26802763 let mid = (lo + hi + 1) >> 1;
2681- if cache[mid as usize] as i32 >= bits {
2764+ if row[mid as usize] as i32 >= bits {
26822765 hi = mid;
26832766 } else {
26842767 lo = mid;
@@ -2687,9 +2770,9 @@ pub(crate) fn bits2pulses(band: usize, lm: i32, bits: i32) -> i32 {
26872770 let lo_cost = if lo == 0 {
26882771 -1
26892772 } else {
2690- cache[lo as usize] as i32
2773+ row[lo as usize] as i32
26912774 };
2692- if bits - lo_cost <= cache[hi as usize] as i32 - bits {
2775+ if bits - lo_cost <= row[hi as usize] as i32 - bits {
26932776 lo
26942777 } else {
26952778 hi
@@ -2700,8 +2783,8 @@ pub(crate) fn pulses2bits(band: usize, lm: i32, pulses: i32) -> i32 {
27002783 if pulses == 0 {
27012784 return 0;
27022785 }
2703- let cache = &CACHE_BITS[cache_index(band, lm)..];
2704- cache[pulses as usize] as i32 + 1
2786+ let base = cache_index(band, lm);
2787+ CACHE_BITS[base + pulses as usize] as i32 + 1
27052788 }
27062789
27072790 /// One level of the Haar transform, used for the time/frequency changes.
crates/ec-opus/src/celt_enc.rsmodified+6 -3
@@ -335,10 +335,13 @@ fn stereo_itheta(x: &[f32], y: &[f32], stereo: bool, n: usize) -> i32 {
335335 let mid = emid.sqrt();
336336 let side = eside.sqrt();
337337 // 0.63662 is the reference's own 2/pi literal (vq.c, stereo_itheta); the
338- // exact constant would round a boundary theta differently.
338+ // exact constant would round a boundary theta differently. The angle is
339+ // the reference float build's `fast_atan2f` (the rational approximation
340+ // the tonality features share), which also keeps libm's `atan2` out of
341+ // the per-band loop.
339342 #[allow(clippy::approx_constant)]
340- const TWO_OVER_PI: f64 = 0.63662;
341- (0.5 + 16384.0 * TWO_OVER_PI * (side as f64).atan2(mid as f64)).floor() as i32
343+ const TWO_OVER_PI: f32 = 0.63662;
344+ (TWO_OVER_PI * 16384.0 * crate::analysis::fast_atan2f(side, mid) + 0.5).floor() as i32
342345 }
343346
344347 /// `l1_metric()` from the reference: L1 norm scaled by `(1 + LM*bias)`.