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
10 ec-core.workspace = true10 ec-core.workspace = true
11 ec-dsp.workspace = true11 ec-dsp.workspace = true
12 wide.workspace = true12 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 }
13 17
14 [dev-dependencies]18 [dev-dependencies]
15 ec-dsp.workspace = true19 ec-dsp.workspace = true
16 ec-ogg.workspace = true20 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 {
120 120
121 /// libopus `fast_atan2f()` — the rational approximation `analysis.c` uses for121 /// libopus `fast_atan2f()` — the rational approximation `analysis.c` uses for
122 /// the per-bin phase, kept because the tonality features are calibrated on it.122 /// 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 {
124 const CA: f32 = 0.431_579_74;124 const CA: f32 = 0.431_579_74;
125 const CB: f32 = 0.678_484_04;125 const CB: f32 = 0.678_484_04;
126 const CC: f32 = 0.085_955_42;126 const CC: f32 = 0.085_955_42;
crates/ec-opus/src/celt.rsmodified+154 -71
@@ -22,7 +22,6 @@
22 //! exactly as the reference does it, never an O(N^2) direct evaluation.22 //! exactly as the reference does it, never an O(N^2) direct evaluation.
23 23
24 use ec_core::{Error, Result};24 use ec_core::{Error, Result};
25-use ec_dsp::Fft;
26 25
27 use crate::range::{RangeDecoder, RangeEncoder};26 use crate::range::{RangeDecoder, RangeEncoder};
28 27
@@ -294,83 +293,155 @@ pub(crate) fn overlap_window() -> Vec<f32> {
294 // The N/4 FFT and the inverse MDCT293 // The N/4 FFT and the inverse MDCT
295 // ---------------------------------------------------------------------------294 // ---------------------------------------------------------------------------
296 295
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`).
298 ///297 ///
299-/// [`ec_dsp::Fft`] covers the `2^k` factor; the factor of 15 is one extra298+/// Two backends behind one signature, selected at compile time:
300-/// decimation stage, so the whole transform stays `O(n log n)` without a299+///
301-/// mixed-radix kernel in the DSP crate.300+/// - default, the in-project shape: [`ec_dsp::Fft`] covers the `2^k` factor
302-#[derive(Clone, Debug)]301+/// and the factor of 15 is one extra decimation stage (3 x 5), so the whole
303-pub(crate) struct Fft15 {302+/// transform stays `O(n log n)` without a mixed-radix kernel in the DSP
304- n: usize,303+/// crate;
305- /// Sub-transform of length `n/15`.304+/// - under the optional `fft-rustfft` feature, a rustfft plan plans the size
306- sub: Fft<f32>,305+/// directly (pure Rust, runtime-detected AVX butterflies, no C). The
307- /// `exp(2 pi i * k1 * n2 / n)` twiddles, split.306+/// family's dependency-free build stays the default; the feature is the
308- tw_re: Vec<f32>,307+/// measured speed option.
309- tw_im: Vec<f32>,308+///
310- scratch_re: Vec<f32>,309+/// Both deliver the same contract: an UNSCALED inverse transform,
311- scratch_im: Vec<f32>,310+/// `X[k] = sum x[n] exp(+2 pi i n k / N)`, over split-complex buffers.
312-}311+#[cfg(not(feature = "fft-rustfft"))]
312+mod fft15 {
313+ use super::dft15;
314+ use ec_dsp::Fft;
315+
316+ #[derive(Clone, Debug)]
317+ pub(crate) struct Fft15 {
318+ n: usize,
319+ /// Sub-transform of length `n/15`.
320+ sub: Fft<f32>,
321+ /// `exp(2 pi i * k1 * n2 / n)` twiddles, split.
322+ tw_re: Vec<f32>,
323+ tw_im: Vec<f32>,
324+ scratch_re: Vec<f32>,
325+ scratch_im: Vec<f32>,
326+ }
327+
328+ impl Fft15 {
329+ pub(crate) fn new(n: usize) -> Fft15 {
330+ assert!(n.is_multiple_of(15) && (n / 15).is_power_of_two());
331+ let l = n / 15;
332+ let mut tw_re = vec![0.0; n];
333+ let mut tw_im = vec![0.0; n];
334+ for k1 in 0..15 {
335+ for n2 in 0..l {
336+ let a = 2.0 * core::f64::consts::PI * (k1 * n2) as f64 / n as f64;
337+ tw_re[k1 * l + n2] = a.cos() as f32;
338+ tw_im[k1 * l + n2] = a.sin() as f32;
339+ }
340+ }
341+ Fft15 {
342+ n,
343+ sub: Fft::new(l),
344+ tw_re,
345+ tw_im,
346+ scratch_re: vec![0.0; n],
347+ scratch_im: vec![0.0; n],
348+ }
349+ }
313 350
314-impl Fft15 {351+ /// Unscaled inverse transform.
315- pub(crate) fn new(n: usize) -> Fft15 {352+ pub(crate) fn inverse(&mut self, re: &mut [f32], im: &mut [f32]) {
316- assert!(n.is_multiple_of(15) && (n / 15).is_power_of_two());353+ let n = self.n;
317- let l = n / 15;354+ let l = n / 15;
318- let mut tw_re = vec![0.0; n];355+ debug_assert_eq!(re.len(), n);
319- let mut tw_im = vec![0.0; n];356+ // Stage 1: 15-point DFTs over n1 at stride L, twiddled on the way
320- for k1 in 0..15 {357+ // out.
321 for n2 in 0..l {358 for n2 in 0..l {
322- let a = 2.0 * core::f64::consts::PI * (k1 * n2) as f64 / n as f64;359+ let mut xr = [0.0f32; 15];
323- tw_re[k1 * l + n2] = a.cos() as f32;360+ let mut xi = [0.0f32; 15];
324- tw_im[k1 * l + n2] = a.sin() as f32;361+ for n1 in 0..15 {
362+ xr[n1] = re[l * n1 + n2];
363+ xi[n1] = im[l * n1 + n2];
364+ }
365+ let (yr, yi) = dft15(&xr, &xi);
366+ for k1 in 0..15 {
367+ let (tr, ti) = (self.tw_re[k1 * l + n2], self.tw_im[k1 * l + n2]);
368+ self.scratch_re[k1 * l + n2] = yr[k1] * tr - yi[k1] * ti;
369+ self.scratch_im[k1 * l + n2] = yr[k1] * ti + yi[k1] * tr;
370+ }
325 }371 }
326- }372+ // Stage 2: L-point transforms, one per k1, written out at stride
327- Fft15 {373+ // 15. ec-dsp scales its inverse by 1/L; undo that to keep the
328- n,374+ // transform unscaled, which is what the MDCT expects.
329- sub: Fft::new(l),
330- tw_re,
331- tw_im,
332- scratch_re: vec![0.0; n],
333- scratch_im: vec![0.0; n],
334- }
335- }
336-
337- /// Unscaled inverse transform: `X[k] = sum x[n] exp(+2 pi i n k / N)`.
338- pub(crate) fn inverse(&mut self, re: &mut [f32], im: &mut [f32]) {
339- let n = self.n;
340- let l = n / 15;
341- debug_assert_eq!(re.len(), n);
342- // Stage 1: 15-point DFTs over n1 at stride L, twiddled on the way out.
343- for n2 in 0..l {
344- let mut xr = [0.0f32; 15];
345- let mut xi = [0.0f32; 15];
346- for n1 in 0..15 {
347- xr[n1] = re[l * n1 + n2];
348- xi[n1] = im[l * n1 + n2];
349- }
350- let (yr, yi) = dft15(&xr, &xi);
351 for k1 in 0..15 {375 for k1 in 0..15 {
352- let (tr, ti) = (self.tw_re[k1 * l + n2], self.tw_im[k1 * l + n2]);376+ let rr = &mut self.scratch_re[k1 * l..(k1 + 1) * l];
353- self.scratch_re[k1 * l + n2] = yr[k1] * tr - yi[k1] * ti;377+ let ii = &mut self.scratch_im[k1 * l..(k1 + 1) * l];
354- self.scratch_im[k1 * l + n2] = yr[k1] * ti + yi[k1] * tr;378+ self.sub.inverse_split(rr, ii);
379+ for (k2, (&r, &i)) in rr.iter().zip(ii.iter()).enumerate() {
380+ re[k1 + 15 * k2] = r * l as f32;
381+ im[k1 + 15 * k2] = i * l as f32;
382+ }
355 }383 }
356 }384 }
357- // Stage 2: L-point transforms, one per k1, written out at stride 15.385+ }
358- for k1 in 0..15 {386+}
359- let rr = &mut self.scratch_re[k1 * l..(k1 + 1) * l];387+
360- let ii = &mut self.scratch_im[k1 * l..(k1 + 1) * l];388+#[cfg(feature = "fft-rustfft")]
361- // ec-dsp scales its inverse by 1/L; undo that to keep the389+mod fft15 {
362- // transform unscaled, which is what the MDCT expects.390+ use rustfft::num_complex::Complex;
363- self.sub.inverse_split(rr, ii);391+ use std::sync::Arc;
364- for (k2, (&r, &i)) in rr.iter().zip(ii.iter()).enumerate() {392+
365- re[k1 + 15 * k2] = r * l as f32;393+ #[derive(Clone)]
366- im[k1 + 15 * k2] = i * l as f32;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;
367 }435 }
368 }436 }
369 }437 }
370 }438 }
371 439
440+pub(crate) use fft15::Fft15;
441+
372 /// A 15-point DFT as 5 radix-3 stages then 3 radix-5 stages (Cooley-Tukey on442 /// A 15-point DFT as 5 radix-3 stages then 3 radix-5 stages (Cooley-Tukey on
373 /// 15 = 3*5), which costs about a third of the direct evaluation.443 /// 15 = 3*5), which costs about a third of the direct evaluation.
444+#[cfg(not(feature = "fft-rustfft"))]
374 #[inline]445 #[inline]
375 fn dft15(xr: &[f32; 15], xi: &[f32; 15]) -> ([f32; 15], [f32; 15]) {446 fn dft15(xr: &[f32; 15], xi: &[f32; 15]) -> ([f32; 15], [f32; 15]) {
376 // exp(+2 pi i / 3) and the two fifth-root cosines/sines.447 // exp(+2 pi i / 3) and the two fifth-root cosines/sines.
@@ -2671,14 +2742,26 @@ pub(crate) fn get_pulses(i: i32) -> i32 {
2671 }2742 }
2672 }2743 }
2673 2744
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+
2674 pub(crate) fn bits2pulses(band: usize, lm: i32, bits: i32) -> i32 {2750 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]);
2676 let mut lo = 0i32;2759 let mut lo = 0i32;
2677- let mut hi = cache[0] as i32;2760+ let mut hi = count as i32;
2678 let bits = bits - 1;2761 let bits = bits - 1;
2679 for _ in 0..6 {2762 for _ in 0..6 {
2680 let mid = (lo + hi + 1) >> 1;2763 let mid = (lo + hi + 1) >> 1;
2681- if cache[mid as usize] as i32 >= bits {2764+ if row[mid as usize] as i32 >= bits {
2682 hi = mid;2765 hi = mid;
2683 } else {2766 } else {
2684 lo = mid;2767 lo = mid;
@@ -2687,9 +2770,9 @@ pub(crate) fn bits2pulses(band: usize, lm: i32, bits: i32) -> i32 {
2687 let lo_cost = if lo == 0 {2770 let lo_cost = if lo == 0 {
2688 -12771 -1
2689 } else {2772 } else {
2690- cache[lo as usize] as i322773+ row[lo as usize] as i32
2691 };2774 };
2692- if bits - lo_cost <= cache[hi as usize] as i32 - bits {2775+ if bits - lo_cost <= row[hi as usize] as i32 - bits {
2693 lo2776 lo
2694 } else {2777 } else {
2695 hi2778 hi
@@ -2700,8 +2783,8 @@ pub(crate) fn pulses2bits(band: usize, lm: i32, pulses: i32) -> i32 {
2700 if pulses == 0 {2783 if pulses == 0 {
2701 return 0;2784 return 0;
2702 }2785 }
2703- let cache = &CACHE_BITS[cache_index(band, lm)..];2786+ let base = cache_index(band, lm);
2704- cache[pulses as usize] as i32 + 12787+ CACHE_BITS[base + pulses as usize] as i32 + 1
2705 }2788 }
2706 2789
2707 /// One level of the Haar transform, used for the time/frequency changes.2790 /// 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 {
335 let mid = emid.sqrt();335 let mid = emid.sqrt();
336 let side = eside.sqrt();336 let side = eside.sqrt();
337 // 0.63662 is the reference's own 2/pi literal (vq.c, stereo_itheta); the337 // 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.
339 #[allow(clippy::approx_constant)]342 #[allow(clippy::approx_constant)]
340- const TWO_OVER_PI: f64 = 0.63662;343+ const TWO_OVER_PI: f32 = 0.63662;
341- (0.5 + 16384.0 * TWO_OVER_PI * (side as f64).atan2(mid as f64)).floor() as i32344+ (TWO_OVER_PI * 16384.0 * crate::analysis::fast_atan2f(side, mid) + 0.5).floor() as i32
342 }345 }
343 346
344 /// `l1_metric()` from the reference: L1 norm scaled by `(1 + LM*bias)`.347 /// `l1_metric()` from the reference: L1 norm scaled by `(1 + LM*bias)`.