diff --git a/Cargo.lock b/Cargo.lock index 5a6ac0d4..61347d99 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,10 +2,42 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" + [[package]] name = "ec-core" version = "0.1.0" +[[package]] +name = "ec-dsp" +version = "0.1.0" +dependencies = [ + "wide", +] + [[package]] name = "oracle" version = "0.1.0" + +[[package]] +name = "safe_arch" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a52ec151f024d703f9fd65abb7cbe81e7cdb39f18917a3a37e3014470dc7c59" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "wide" +version = "1.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de2aaf408e58689c2096682331b1f42bb2d9f2ed6b11560407d023cd0a6c634e" +dependencies = [ + "bytemuck", + "safe_arch", +] diff --git a/crates/ec-dsp/Cargo.toml b/crates/ec-dsp/Cargo.toml new file mode 100644 index 00000000..c00db9b3 --- /dev/null +++ b/crates/ec-dsp/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "ec-dsp" +description = "Shared transforms for the edith_codecs family: FFT, DCT, MDCT and analysis windows." +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true + +[dependencies] +wide.workspace = true diff --git a/crates/ec-dsp/src/dct.rs b/crates/ec-dsp/src/dct.rs new file mode 100644 index 00000000..a399d9e5 --- /dev/null +++ b/crates/ec-dsp/src/dct.rs @@ -0,0 +1,305 @@ +//! DCT-II, DCT-III and DCT-IV, all routed through an FFT. +//! +//! Every one of these is `O(n log n)` here. Definitions, unnormalised, for +//! length `N`: +//! +//! - DCT-II: `X[k] = sum_n x[n] cos(pi/N (n + 1/2) k)` +//! - DCT-III: `X[k] = x[0]/2 + sum_{n>=1} x[n] cos(pi/N n (k + 1/2))` +//! - DCT-IV: `X[k] = sum_n x[n] cos(pi/N (n + 1/2)(k + 1/2))` +//! +//! DCT-III is the inverse of DCT-II up to the usual `2/N`, i.e. +//! `x == (2/N) * dct3(dct2(x))`. DCT-IV is its own inverse up to the same +//! factor, which is why [`crate::Mdct`] needs only the one plan for both +//! directions. +//! +//! II and III use an `N`-point real FFT (Makhoul's method); IV uses an +//! `N/2`-point complex FFT with a quarter-sample twiddle on each side. + +use crate::Real; +use crate::fft::{Complex, Fft, RealFft}; + +/// DCT-II / DCT-III plan for one size. +/// +/// ``` +/// use ec_dsp::Dct; +/// +/// let mut dct = Dct::::new(8); +/// let mut data = [1.0, 2.0, 3.0, 4.0, 4.0, 3.0, 2.0, 1.0]; +/// let original = data; +/// dct.dct2(&mut data); +/// dct.dct3(&mut data); +/// // dct3 . dct2 = (N/2) * identity +/// assert!(data.iter().zip(&original).all(|(a, b)| (a / 4.0 - b).abs() < 1e-12)); +/// ``` +#[derive(Clone, Debug)] +pub struct Dct { + n: usize, + rfft: RealFft, + twiddle_re: Vec, + twiddle_im: Vec, + shuffled: Vec, + spectrum: Vec>, +} + +impl Dct { + /// A plan for `n` points. + /// + /// # Panics + /// If `n` is not a power of two of at least 4 (see [`crate::fft::MAX_LEN`]). + pub fn new(n: usize) -> Dct { + let rfft = RealFft::new(n); + let mut twiddle_re = Vec::with_capacity(n); + let mut twiddle_im = Vec::with_capacity(n); + for k in 0..n { + // exp(-i*pi*k/(2N)): the half-sample shift that turns a DFT of the + // even/odd-shuffled signal into a DCT. + let angle = -core::f64::consts::PI * k as f64 / (2.0 * n as f64); + twiddle_re.push(T::from_f64(angle.cos())); + twiddle_im.push(T::from_f64(angle.sin())); + } + Dct { + n, + rfft, + twiddle_re, + twiddle_im, + shuffled: vec![T::ZERO; n], + spectrum: vec![Complex::ZERO; n / 2 + 1], + } + } + + /// Points per transform. + pub fn size(&self) -> usize { + self.n + } + + /// DCT-II in place. + /// + /// # Panics + /// If `data.len() != self.size()`. + pub fn dct2(&mut self, data: &mut [T]) { + assert_eq!(data.len(), self.n, "dct input length must equal plan size"); + let n = self.n; + // Even samples in order, odd samples reversed: a real DFT of this + // sequence carries the DCT-II in its real part after a twiddle. + for j in 0..n / 2 { + self.shuffled[j] = data[2 * j]; + self.shuffled[n - 1 - j] = data[2 * j + 1]; + } + self.rfft.forward(&self.shuffled, &mut self.spectrum); + for (k, out) in data.iter_mut().enumerate() { + let bin = if k <= n / 2 { + self.spectrum[k] + } else { + self.spectrum[n - k].conj() + }; + let tw = Complex::new(self.twiddle_re[k], self.twiddle_im[k]); + *out = (tw * bin).re; + } + } + + /// DCT-III in place — [`Dct::dct2`] run backwards, times `N/2`. + /// + /// # Panics + /// If `data.len() != self.size()`. + pub fn dct3(&mut self, data: &mut [T]) { + assert_eq!(data.len(), self.n, "dct input length must equal plan size"); + let n = self.n; + for k in 0..=n / 2 { + // The spectrum whose real part is `data`: G[k] = X[k] - i X[N-k]. + let hi = if k == 0 { T::ZERO } else { data[n - k] }; + let g = Complex::new(data[k], -hi); + let tw = Complex::new(self.twiddle_re[k], self.twiddle_im[k]).conj(); + self.spectrum[k] = tw * g; + } + self.rfft.inverse(&self.spectrum, &mut self.shuffled); + let gain = T::from_f64(n as f64 / 2.0); + for j in 0..n / 2 { + data[2 * j] = self.shuffled[j] * gain; + data[2 * j + 1] = self.shuffled[n - 1 - j] * gain; + } + } +} + +/// DCT-IV plan for one size — the kernel [`crate::Mdct`] is built on. +/// +/// ``` +/// use ec_dsp::Dct4; +/// +/// let mut dct = Dct4::::new(8); +/// let mut data = [1.0, -2.0, 3.0, 0.5, 0.0, 1.5, -1.0, 2.0]; +/// let original = data; +/// dct.transform(&mut data); +/// dct.transform(&mut data); +/// // DCT-IV is an involution up to N/2. +/// assert!(data.iter().zip(&original).all(|(a, b)| (a / 4.0 - b).abs() < 1e-12)); +/// ``` +#[derive(Clone, Debug)] +pub struct Dct4 { + n: usize, + fft: Fft, + pre_re: Vec, + pre_im: Vec, + post_re: Vec, + post_im: Vec, + buf_re: Vec, + buf_im: Vec, +} + +impl Dct4 { + /// A plan for `n` points, `n` a power of two of at least 2. + /// + /// # Panics + /// If `n` is not a power of two, or `n/2` is not a legal FFT size. + pub fn new(n: usize) -> Dct4 { + assert!( + n.is_power_of_two() && n >= 2, + "dct-iv length must be a power of two of at least 2, got {n}" + ); + let half = n / 2; + let mut pre_re = Vec::with_capacity(half); + let mut pre_im = Vec::with_capacity(half); + let mut post_re = Vec::with_capacity(half); + let mut post_im = Vec::with_capacity(half); + for j in 0..half { + // exp(-i*pi*(4j+1)/(4N)) before the FFT, exp(-i*pi*k/N) after: + // together they supply the (n+1/2)(k+1/2) phase of a DCT-IV. + let pre = -core::f64::consts::PI * (4 * j + 1) as f64 / (4.0 * n as f64); + pre_re.push(T::from_f64(pre.cos())); + pre_im.push(T::from_f64(pre.sin())); + let post = -core::f64::consts::PI * j as f64 / n as f64; + post_re.push(T::from_f64(post.cos())); + post_im.push(T::from_f64(post.sin())); + } + Dct4 { + n, + fft: Fft::new(half), + pre_re, + pre_im, + post_re, + post_im, + buf_re: vec![T::ZERO; half], + buf_im: vec![T::ZERO; half], + } + } + + /// Points per transform. + pub fn size(&self) -> usize { + self.n + } + + /// DCT-IV in place. + /// + /// # Panics + /// If `data.len() != self.size()`. + pub fn transform(&mut self, data: &mut [T]) { + assert_eq!( + data.len(), + self.n, + "dct-iv input length must equal plan size" + ); + let n = self.n; + let half = n / 2; + for j in 0..half { + let (re, im) = (data[2 * j], data[n - 1 - 2 * j]); + self.buf_re[j] = re * self.pre_re[j] - im * self.pre_im[j]; + self.buf_im[j] = re * self.pre_im[j] + im * self.pre_re[j]; + } + self.fft.forward_split(&mut self.buf_re, &mut self.buf_im); + for k in 0..half { + let (re, im) = (self.buf_re[k], self.buf_im[k]); + let (wr, wi) = (self.post_re[k], self.post_im[k]); + data[2 * k] = re * wr - im * wi; + data[n - 1 - 2 * k] = -(re * wi + im * wr); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::tests::{noise, rel_error}; + use core::f64::consts::PI; + + /// O(n^2) reference DCTs, test-only. + fn reference(kind: u8, x: &[f64]) -> Vec { + let n = x.len(); + (0..n) + .map(|k| match kind { + 2 => (0..n) + .map(|j| x[j] * (PI / n as f64 * (j as f64 + 0.5) * k as f64).cos()) + .sum(), + 3 => { + x[0] / 2.0 + + (1..n) + .map(|j| x[j] * (PI / n as f64 * j as f64 * (k as f64 + 0.5)).cos()) + .sum::() + } + _ => (0..n) + .map(|j| x[j] * (PI / n as f64 * (j as f64 + 0.5) * (k as f64 + 0.5)).cos()) + .sum(), + }) + .collect() + } + + #[test] + fn dct2_and_dct3_agree_with_reference() { + let mut worst = 0.0f64; + for shift in 2..=13 { + let n = 1usize << shift; + let input: Vec = noise(n, 0x2222 + n as u64); + for kind in [2u8, 3] { + let want = reference(kind, &input); + let mut got = input.clone(); + let mut dct = Dct::new(n); + if kind == 2 { + dct.dct2(&mut got); + } else { + dct.dct3(&mut got); + } + let error = rel_error(&got, &want); + worst = worst.max(error); + assert!(error < 1e-12, "dct-{kind} n = {n}: error {error:e}"); + } + } + println!("f64 DCT-II/III vs reference: worst rel error {worst:e}"); + } + + #[test] + fn dct4_agrees_with_reference() { + let mut worst_f64 = 0.0f64; + let mut worst_f32 = 0.0f64; + for shift in 1..=13 { + let n = 1usize << shift; + let input: Vec = noise(n, 0x3333 + n as u64); + let want = reference(4, &input); + + let mut got = input.clone(); + Dct4::new(n).transform(&mut got); + let error = rel_error(&got, &want); + worst_f64 = worst_f64.max(error); + assert!(error < 1e-12, "dct-iv f64 n = {n}: error {error:e}"); + + let mut got32: Vec = input.iter().map(|v| *v as f32).collect(); + Dct4::new(n).transform(&mut got32); + let widened: Vec = got32.iter().map(|v| *v as f64).collect(); + let error32 = rel_error(&widened, &want); + worst_f32 = worst_f32.max(error32); + assert!(error32 < 1e-5, "dct-iv f32 n = {n}: error {error32:e}"); + } + println!("DCT-IV vs reference: worst rel error f64 {worst_f64:e}, f32 {worst_f32:e}"); + } + + #[test] + fn dct2_round_trips_through_dct3() { + let n = 1024; + let input: Vec = noise(n, 5150); + let mut data = input.clone(); + let mut dct = Dct::new(n); + dct.dct2(&mut data); + dct.dct3(&mut data); + crate::scale(&mut data, 2.0 / n as f32); + let error = rel_error(&data, &input); + assert!(error < 1e-6, "round-trip error {error:e}"); + println!("f32 DCT-II/III round trip (n = {n}): rel error {error:e}"); + } +} diff --git a/crates/ec-dsp/src/fft.rs b/crates/ec-dsp/src/fft.rs new file mode 100644 index 00000000..e8eb11e5 --- /dev/null +++ b/crates/ec-dsp/src/fft.rs @@ -0,0 +1,776 @@ +//! Power-of-two complex FFT, plus a real-input wrapper. +//! +//! The kernel is a Stockham auto-sort decimation-in-frequency transform, +//! radix-4 wherever the remaining size allows and radix-2 for the odd stage. +//! Stockham was chosen over the textbook bit-reversed Cooley-Tukey for one +//! reason: every read and write inside a stage is unit stride, which is what +//! makes the inner loop vectorise with no shuffles at all. +//! +//! Data is held **split** — real parts in one slice, imaginary in another — +//! because that is the layout SIMD wants. [`Fft::forward`] and +//! [`Fft::inverse`] accept the interleaved [`Complex`] form for callers who +//! prefer it and de-interleave internally; the DCT and MDCT plans call the +//! split entry points and never pay that pass. + +use core::ops::{Add, Mul, Sub}; + +use crate::Real; + +/// The largest transform the plans accept, matching the largest window any +/// codec in the family uses with room to spare. +pub const MAX_LEN: usize = 1 << 16; + +/// A complex number in the crate's own minimal form (no `num-complex` dep). +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Complex { + /// Real part. + pub re: T, + /// Imaginary part. + pub im: T, +} + +impl Complex { + /// A complex number from its parts. + pub const fn new(re: T, im: T) -> Complex { + Complex { re, im } + } +} + +impl Complex { + /// Zero. + pub const ZERO: Complex = Complex { + re: T::ZERO, + im: T::ZERO, + }; + + /// Complex conjugate. + #[inline] + pub fn conj(self) -> Complex { + Complex::new(self.re, -self.im) + } + + /// Multiplication by a real scalar. + #[inline] + pub fn scale(self, k: T) -> Complex { + Complex::new(self.re * k, self.im * k) + } + + /// Multiplication by `-i`, i.e. a quarter turn clockwise. + #[inline] + pub fn mul_neg_i(self) -> Complex { + Complex::new(self.im, -self.re) + } + + /// Squared magnitude. + #[inline] + pub fn norm_sqr(self) -> T { + self.re * self.re + self.im * self.im + } +} + +impl Add for Complex { + type Output = Complex; + #[inline] + fn add(self, rhs: Complex) -> Complex { + Complex::new(self.re + rhs.re, self.im + rhs.im) + } +} + +impl Sub for Complex { + type Output = Complex; + #[inline] + fn sub(self, rhs: Complex) -> Complex { + Complex::new(self.re - rhs.re, self.im - rhs.im) + } +} + +impl Mul for Complex { + type Output = Complex; + #[inline] + fn mul(self, rhs: Complex) -> Complex { + Complex::new( + self.re * rhs.re - self.im * rhs.im, + self.re * rhs.im + self.im * rhs.re, + ) + } +} + +/// A complex FFT plan for one power-of-two size, in `f32` or `f64`. +/// +/// Holds the twiddle table and the ping-pong scratch the Stockham passes need, +/// so a transform allocates nothing. Because the scratch lives in the plan the +/// transform methods take `&mut self`; share across threads by cloning. +/// +/// ``` +/// use ec_dsp::{Complex, Fft}; +/// +/// let mut fft = Fft::::new(8); +/// let mut data = [Complex::new(1.0, 0.0); 8]; +/// fft.forward(&mut data); +/// // A constant signal has all its energy in bin 0. +/// assert!((data[0].re - 8.0).abs() < 1e-5); +/// assert!(data[1].norm_sqr() < 1e-10); +/// fft.inverse(&mut data); +/// assert!((data[3].re - 1.0).abs() < 1e-6); +/// ``` +#[derive(Clone, Debug)] +pub struct Fft { + n: usize, + twiddle_re: Vec, + twiddle_im: Vec, + scratch_re: Vec, + scratch_im: Vec, + split_re: Vec, + split_im: Vec, +} + +impl Fft { + /// A plan for `n` points. + /// + /// # Panics + /// If `n` is not a power of two in `1..=`[`MAX_LEN`]. Sizes are a + /// compile-time property of a codec, so a bad one is API misuse. + pub fn new(n: usize) -> Fft { + assert!( + n.is_power_of_two() && n <= MAX_LEN, + "fft length must be a power of two up to {MAX_LEN}, got {n}" + ); + let mut twiddle_re = Vec::with_capacity(n); + let mut twiddle_im = Vec::with_capacity(n); + for k in 0..n { + // exp(-2*pi*i*k/n), always evaluated in f64 and rounded once. + let angle = -2.0 * core::f64::consts::PI * k as f64 / n as f64; + twiddle_re.push(T::from_f64(angle.cos())); + twiddle_im.push(T::from_f64(angle.sin())); + } + Fft { + n, + twiddle_re, + twiddle_im, + scratch_re: vec![T::ZERO; n], + scratch_im: vec![T::ZERO; n], + split_re: vec![T::ZERO; n], + split_im: vec![T::ZERO; n], + } + } + + /// Points per transform. + pub fn size(&self) -> usize { + self.n + } + + /// Forward transform, `exp(-2*pi*i*k*n/N)`, in place. + /// + /// # Panics + /// If `data.len() != self.size()`. + pub fn forward(&mut self, data: &mut [Complex]) { + self.interleaved(data, false); + } + + /// Inverse transform **including** the `1/n` scaling, in place, so that + /// `inverse(forward(x)) == x`. + /// + /// # Panics + /// If `data.len() != self.size()`. + pub fn inverse(&mut self, data: &mut [Complex]) { + self.interleaved(data, true); + } + + fn interleaved(&mut self, data: &mut [Complex], inverse: bool) { + assert_eq!(data.len(), self.n, "fft input length must equal plan size"); + for ((re, im), c) in self + .split_re + .iter_mut() + .zip(self.split_im.iter_mut()) + .zip(data.iter()) + { + *re = c.re; + *im = c.im; + } + let (mut re, mut im) = ( + core::mem::take(&mut self.split_re), + core::mem::take(&mut self.split_im), + ); + if inverse { + self.inverse_split(&mut re, &mut im); + } else { + self.forward_split(&mut re, &mut im); + } + for (c, (re, im)) in data.iter_mut().zip(re.iter().zip(im.iter())) { + *c = Complex::new(*re, *im); + } + self.split_re = re; + self.split_im = im; + } + + /// Forward transform of split-layout data, in place. The allocation-free + /// entry point the other transforms in this crate use. + /// + /// # Panics + /// If either slice length differs from [`Fft::size`]. + pub fn forward_split(&mut self, re: &mut [T], im: &mut [T]) { + self.stockham(re, im); + } + + /// Inverse transform of split-layout data, in place, including `1/n`. + /// + /// Uses the identity `ifft(x) = swap(fft(swap(x)))/n`, where `swap` + /// exchanges real and imaginary parts — one kernel serves both directions. + /// + /// # Panics + /// If either slice length differs from [`Fft::size`]. + pub fn inverse_split(&mut self, re: &mut [T], im: &mut [T]) { + self.stockham(im, re); + let norm = T::ONE / T::from_f64(self.n as f64); + crate::scale(re, norm); + crate::scale(im, norm); + } + + fn stockham(&mut self, re: &mut [T], im: &mut [T]) { + assert_eq!(re.len(), self.n, "fft input length must equal plan size"); + assert_eq!(im.len(), self.n, "fft input length must equal plan size"); + let Fft { + n: total, + twiddle_re, + twiddle_im, + scratch_re, + scratch_im, + .. + } = self; + + let mut xr: &mut [T] = re; + let mut xi: &mut [T] = im; + let mut yr: &mut [T] = scratch_re; + let mut yi: &mut [T] = scratch_im; + + // Invariant across the loop: n * stride == total, so the twiddle for + // stage angle exp(-2*pi*i*p/n) is table entry p*stride. + let mut n = *total; + let mut stride = 1usize; + let mut in_scratch = false; + while n > 1 { + if n % 4 == 0 { + pass4(stride, xr, xi, yr, yi, twiddle_re, twiddle_im); + n /= 4; + stride *= 4; + } else { + pass2(stride, xr, xi, yr, yi, twiddle_re, twiddle_im); + n /= 2; + stride *= 2; + } + core::mem::swap(&mut xr, &mut yr); + core::mem::swap(&mut xi, &mut yi); + in_scratch = !in_scratch; + } + if in_scratch { + // Odd number of passes: the result sits in the scratch (`x` now), + // the caller's buffers are `y`. + yr.copy_from_slice(xr); + yi.copy_from_slice(xi); + } + } +} + +/// One radix-2 Stockham pass. `stride` is the run length; the input holds two +/// halves and the output two interleaved runs per block. +/// +/// Every loop here walks `chunks_exact`, never an index: that is what makes +/// the bounds checks fold away, and it is worth 10x — measured against the +/// same code written with indices, which spent more instructions on checks +/// than on arithmetic. +#[inline] +fn pass2( + stride: usize, + xr: &[T], + xi: &[T], + yr: &mut [T], + yi: &mut [T], + twiddle_re: &[T], + twiddle_im: &[T], +) { + let half = xr.len() / 2; + let (a_re, b_re) = xr.split_at(half); + let (a_im, b_im) = xi.split_at(half); + let lanes = T::LANES; + + let blocks = a_re + .chunks_exact(stride) + .zip(a_im.chunks_exact(stride)) + .zip(b_re.chunks_exact(stride).zip(b_im.chunks_exact(stride))) + .zip( + yr.chunks_exact_mut(2 * stride) + .zip(yi.chunks_exact_mut(2 * stride)), + ); + for (p, (((ar, ai), (br, bi)), (out_re, out_im))) in blocks.enumerate() { + let (wr, wi) = (twiddle_re[p * stride], twiddle_im[p * stride]); + let (o0r, o1r) = out_re.split_at_mut(stride); + let (o0i, o1i) = out_im.split_at_mut(stride); + if stride >= lanes { + let (wrv, wiv) = (wr.splat(), wi.splat()); + let ins = ar + .chunks_exact(lanes) + .zip(ai.chunks_exact(lanes)) + .zip(br.chunks_exact(lanes).zip(bi.chunks_exact(lanes))); + let outs = o0r + .chunks_exact_mut(lanes) + .zip(o0i.chunks_exact_mut(lanes)) + .zip(o1r.chunks_exact_mut(lanes).zip(o1i.chunks_exact_mut(lanes))); + for (input, output) in ins.zip(outs) { + let ((a_lane_re, a_lane_im), (b_lane_re, b_lane_im)) = input; + let ((y0r, y0i), (y1r, y1i)) = output; + let (arv, aiv) = (T::load(a_lane_re), T::load(a_lane_im)); + let (brv, biv) = (T::load(b_lane_re), T::load(b_lane_im)); + T::store(arv + brv, y0r); + T::store(aiv + biv, y0i); + let (dr, di) = (arv - brv, aiv - biv); + T::store(dr * wrv - di * wiv, y1r); + T::store(dr * wiv + di * wrv, y1i); + } + } else { + for q in 0..stride { + let (arq, aiq) = (ar[q], ai[q]); + let (brq, biq) = (br[q], bi[q]); + o0r[q] = arq + brq; + o0i[q] = aiq + biq; + let (dr, di) = (arq - brq, aiq - biq); + o1r[q] = dr * wr - di * wi; + o1i[q] = dr * wi + di * wr; + } + } + } +} + +/// One radix-4 Stockham pass — half the passes of radix-2 for the same size, +/// which is where most of the speed comes from. Same chunk discipline as +/// [`pass2`]. +#[inline] +fn pass4( + stride: usize, + xr: &[T], + xi: &[T], + yr: &mut [T], + yi: &mut [T], + twiddle_re: &[T], + twiddle_im: &[T], +) { + let quarter = xr.len() / 4; + let (a_re, rest) = xr.split_at(quarter); + let (b_re, rest) = rest.split_at(quarter); + let (c_re, d_re) = rest.split_at(quarter); + let (a_im, rest) = xi.split_at(quarter); + let (b_im, rest) = rest.split_at(quarter); + let (c_im, d_im) = rest.split_at(quarter); + let lanes = T::LANES; + + let blocks = a_re + .chunks_exact(stride) + .zip(a_im.chunks_exact(stride)) + .zip(b_re.chunks_exact(stride).zip(b_im.chunks_exact(stride))) + .zip( + c_re.chunks_exact(stride) + .zip(c_im.chunks_exact(stride)) + .zip(d_re.chunks_exact(stride).zip(d_im.chunks_exact(stride))), + ) + .zip( + yr.chunks_exact_mut(4 * stride) + .zip(yi.chunks_exact_mut(4 * stride)), + ); + for (p, ((((ar, ai), (br, bi)), ((cr, ci), (dr, di))), (out_re, out_im))) in blocks.enumerate() + { + let step = p * stride; + let (w1r, w1i) = (twiddle_re[step], twiddle_im[step]); + let (w2r, w2i) = (twiddle_re[2 * step], twiddle_im[2 * step]); + let (w3r, w3i) = (twiddle_re[3 * step], twiddle_im[3 * step]); + let mut runs_re = out_re.chunks_exact_mut(stride); + let (o0r, o1r, o2r, o3r) = ( + runs_re.next().expect("four output runs"), + runs_re.next().expect("four output runs"), + runs_re.next().expect("four output runs"), + runs_re.next().expect("four output runs"), + ); + let mut runs_im = out_im.chunks_exact_mut(stride); + let (o0i, o1i, o2i, o3i) = ( + runs_im.next().expect("four output runs"), + runs_im.next().expect("four output runs"), + runs_im.next().expect("four output runs"), + runs_im.next().expect("four output runs"), + ); + if stride >= lanes { + let (w1rv, w1iv) = (w1r.splat(), w1i.splat()); + let (w2rv, w2iv) = (w2r.splat(), w2i.splat()); + let (w3rv, w3iv) = (w3r.splat(), w3i.splat()); + let ins = ar + .chunks_exact(lanes) + .zip(ai.chunks_exact(lanes)) + .zip(br.chunks_exact(lanes).zip(bi.chunks_exact(lanes))) + .zip( + cr.chunks_exact(lanes) + .zip(ci.chunks_exact(lanes)) + .zip(dr.chunks_exact(lanes).zip(di.chunks_exact(lanes))), + ); + let outs = o0r + .chunks_exact_mut(lanes) + .zip(o0i.chunks_exact_mut(lanes)) + .zip(o1r.chunks_exact_mut(lanes).zip(o1i.chunks_exact_mut(lanes))) + .zip( + o2r.chunks_exact_mut(lanes) + .zip(o2i.chunks_exact_mut(lanes)) + .zip(o3r.chunks_exact_mut(lanes).zip(o3i.chunks_exact_mut(lanes))), + ); + for (input, output) in ins.zip(outs) { + let (((a_lr, a_li), (b_lr, b_li)), ((c_lr, c_li), (d_lr, d_li))) = input; + let (((y0r, y0i), (y1r, y1i)), ((y2r, y2i), (y3r, y3i))) = output; + let (arv, aiv) = (T::load(a_lr), T::load(a_li)); + let (brv, biv) = (T::load(b_lr), T::load(b_li)); + let (crv, civ) = (T::load(c_lr), T::load(c_li)); + let (drv, div) = (T::load(d_lr), T::load(d_li)); + let (apc_r, apc_i) = (arv + crv, aiv + civ); + let (amc_r, amc_i) = (arv - crv, aiv - civ); + let (bpd_r, bpd_i) = (brv + drv, biv + div); + let (bmd_r, bmd_i) = (brv - drv, biv - div); + // t0 = (a+c) + (b+d) + T::store(apc_r + bpd_r, y0r); + T::store(apc_i + bpd_i, y0i); + // t1 = (a-c) - i(b-d), times w^p + let (t1r, t1i) = (amc_r + bmd_i, amc_i - bmd_r); + T::store(t1r * w1rv - t1i * w1iv, y1r); + T::store(t1r * w1iv + t1i * w1rv, y1i); + // t2 = (a+c) - (b+d), times w^2p + let (t2r, t2i) = (apc_r - bpd_r, apc_i - bpd_i); + T::store(t2r * w2rv - t2i * w2iv, y2r); + T::store(t2r * w2iv + t2i * w2rv, y2i); + // t3 = (a-c) + i(b-d), times w^3p + let (t3r, t3i) = (amc_r - bmd_i, amc_i + bmd_r); + T::store(t3r * w3rv - t3i * w3iv, y3r); + T::store(t3r * w3iv + t3i * w3rv, y3i); + } + } else { + for q in 0..stride { + let (arq, aiq) = (ar[q], ai[q]); + let (brq, biq) = (br[q], bi[q]); + let (crq, ciq) = (cr[q], ci[q]); + let (drq, diq) = (dr[q], di[q]); + let (apc_r, apc_i) = (arq + crq, aiq + ciq); + let (amc_r, amc_i) = (arq - crq, aiq - ciq); + let (bpd_r, bpd_i) = (brq + drq, biq + diq); + let (bmd_r, bmd_i) = (brq - drq, biq - diq); + o0r[q] = apc_r + bpd_r; + o0i[q] = apc_i + bpd_i; + let (t1r, t1i) = (amc_r + bmd_i, amc_i - bmd_r); + o1r[q] = t1r * w1r - t1i * w1i; + o1i[q] = t1r * w1i + t1i * w1r; + let (t2r, t2i) = (apc_r - bpd_r, apc_i - bpd_i); + o2r[q] = t2r * w2r - t2i * w2i; + o2i[q] = t2r * w2i + t2i * w2r; + let (t3r, t3i) = (amc_r - bmd_i, amc_i + bmd_r); + o3r[q] = t3r * w3r - t3i * w3i; + o3i[q] = t3r * w3i + t3i * w3r; + } + } + } +} + +/// Real-input FFT: an `n`-point real transform on an `n/2`-point complex one. +/// +/// Half the work and half the memory of stuffing zeros into a complex FFT. +/// The spectrum is the `n/2 + 1` non-redundant bins; bins `0` and `n/2` are +/// real, and the caller gets the conjugate half back for free by symmetry. +/// +/// ``` +/// use ec_dsp::RealFft; +/// +/// let mut rfft = RealFft::::new(16); +/// let signal: Vec = (0..16).map(|n| (n as f64).sin()).collect(); +/// let mut spectrum = vec![Default::default(); 9]; +/// rfft.forward(&signal, &mut spectrum); +/// let mut back = vec![0.0; 16]; +/// rfft.inverse(&spectrum, &mut back); +/// assert!(back.iter().zip(&signal).all(|(a, b)| (a - b).abs() < 1e-12)); +/// ``` +#[derive(Clone, Debug)] +pub struct RealFft { + n: usize, + half: Fft, + twiddle_re: Vec, + twiddle_im: Vec, + buf_re: Vec, + buf_im: Vec, +} + +impl RealFft { + /// A plan for `n` real points. + /// + /// # Panics + /// If `n` is not a power of two of at least 4, or exceeds [`MAX_LEN`]. + pub fn new(n: usize) -> RealFft { + assert!( + n.is_power_of_two() && (4..=MAX_LEN).contains(&n), + "real fft length must be a power of two in 4..={MAX_LEN}, got {n}" + ); + let half = n / 2; + let mut twiddle_re = Vec::with_capacity(half + 1); + let mut twiddle_im = Vec::with_capacity(half + 1); + for k in 0..=half { + let angle = -2.0 * core::f64::consts::PI * k as f64 / n as f64; + twiddle_re.push(T::from_f64(angle.cos())); + twiddle_im.push(T::from_f64(angle.sin())); + } + RealFft { + n, + half: Fft::new(half), + twiddle_re, + twiddle_im, + buf_re: vec![T::ZERO; half], + buf_im: vec![T::ZERO; half], + } + } + + /// Points per transform (the real-domain length). + pub fn size(&self) -> usize { + self.n + } + + /// Bins in the spectrum, `size()/2 + 1`. + pub fn spectrum_len(&self) -> usize { + self.n / 2 + 1 + } + + /// Transforms `input` into `spectrum`. + /// + /// # Panics + /// If `input.len() != size()` or `spectrum.len() != spectrum_len()`. + pub fn forward(&mut self, input: &[T], spectrum: &mut [Complex]) { + assert_eq!(input.len(), self.n, "real fft input length must equal size"); + assert_eq!( + spectrum.len(), + self.spectrum_len(), + "spectrum length must be size()/2 + 1" + ); + let m = self.n / 2; + for j in 0..m { + self.buf_re[j] = input[2 * j]; + self.buf_im[j] = input[2 * j + 1]; + } + self.half.forward_split(&mut self.buf_re, &mut self.buf_im); + + let half_scale = T::from_f64(0.5); + for (k, bin) in spectrum.iter_mut().enumerate() { + let z = Complex::new(self.buf_re[k % m], self.buf_im[k % m]); + let zc = Complex::new(self.buf_re[(m - k) % m], self.buf_im[(m - k) % m]).conj(); + let even = (z + zc).scale(half_scale); + let odd = (z - zc).scale(half_scale); + let tw = Complex::new(self.twiddle_re[k], self.twiddle_im[k]); + *bin = even + (tw * odd).mul_neg_i(); + } + } + + /// Reconstructs `output` from `spectrum`, scaled so that + /// `inverse(forward(x)) == x`. + /// + /// # Panics + /// If `output.len() != size()` or `spectrum.len() != spectrum_len()`. + pub fn inverse(&mut self, spectrum: &[Complex], output: &mut [T]) { + assert_eq!( + output.len(), + self.n, + "real fft output length must equal size" + ); + assert_eq!( + spectrum.len(), + self.spectrum_len(), + "spectrum length must be size()/2 + 1" + ); + let m = self.n / 2; + let half_scale = T::from_f64(0.5); + for k in 0..m { + let a = spectrum[k]; + let b = spectrum[m - k].conj(); + let even = (a + b).scale(half_scale); + let odd = (a - b).scale(half_scale); + // Conjugate twiddle, and +i instead of -i: the forward step run backwards. + let tw = Complex::new(self.twiddle_re[k], self.twiddle_im[k]).conj(); + let z = even - (tw * odd).mul_neg_i(); + self.buf_re[k] = z.re; + self.buf_im[k] = z.im; + } + self.half.inverse_split(&mut self.buf_re, &mut self.buf_im); + for j in 0..m { + output[2 * j] = self.buf_re[j]; + output[2 * j + 1] = self.buf_im[j]; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::tests::{noise, rel_error}; + + /// O(n^2) DFT in `f64` — the reference the fast path is judged against. + /// Test-only by construction: nothing outside `#[cfg(test)]` can call it, + /// which is the family rule about naive transforms in shipping paths. + fn reference_dft(input: &[Complex], inverse: bool) -> Vec> { + let n = input.len(); + let sign = if inverse { 1.0 } else { -1.0 }; + (0..n) + .map(|k| { + let mut acc = Complex::new(0.0, 0.0); + for (j, x) in input.iter().enumerate() { + let angle = sign * 2.0 * core::f64::consts::PI * (j * k % n) as f64 / n as f64; + acc = acc + *x * Complex::new(angle.cos(), angle.sin()); + } + acc + }) + .collect() + } + + fn complex_noise(n: usize, seed: u64) -> Vec> { + let re: Vec = noise(n, seed); + let im: Vec = noise(n, seed ^ 0x9e37_79b9); + re.iter() + .zip(&im) + .map(|(r, i)| Complex::new(*r, *i)) + .collect() + } + + #[test] + fn agrees_with_reference_dft_f64() { + let mut worst = 0.0f64; + let mut size = 0; + for shift in 3..=13 { + let n = 1usize << shift; + let input = complex_noise(n, 0x1234 + n as u64); + let want = reference_dft(&input, false); + let mut got = input.clone(); + Fft::new(n).forward(&mut got); + let error = complex_error(&got, &want); + if error > worst { + worst = error; + size = n; + } + assert!(error < 1e-12, "n = {n}: f64 error {error:e}"); + } + println!("f64 FFT vs reference DFT: worst rel error {worst:e} (n = {size})"); + } + + #[test] + fn agrees_with_reference_dft_f32() { + let mut worst = 0.0f64; + let mut size = 0; + for shift in 3..=13 { + let n = 1usize << shift; + let input = complex_noise(n, 0x5678 + n as u64); + let want = reference_dft(&input, false); + let mut got: Vec> = input + .iter() + .map(|c| Complex::new(c.re as f32, c.im as f32)) + .collect(); + Fft::new(n).forward(&mut got); + let widened: Vec> = got + .iter() + .map(|c| Complex::new(c.re as f64, c.im as f64)) + .collect(); + let error = complex_error(&widened, &want); + if error > worst { + worst = error; + size = n; + } + assert!(error < 1e-5, "n = {n}: f32 error {error:e}"); + } + println!("f32 FFT vs reference DFT: worst rel error {worst:e} (n = {size})"); + } + + #[test] + fn inverse_reference_matches_plan() { + let n = 64; + let input = complex_noise(n, 99); + let want = reference_dft(&input, true); + let mut got = input.clone(); + let mut fft = Fft::new(n); + fft.inverse(&mut got); + // The plan normalises by n; the reference does not. + let scaled: Vec> = want.iter().map(|c| c.scale(1.0 / n as f64)).collect(); + assert!(complex_error(&got, &scaled) < 1e-12); + } + + #[test] + fn round_trips_f32_every_size() { + let mut worst = 0.0f64; + let mut size = 0; + for shift in 3..=15 { + let n = 1usize << shift; + let input: Vec = noise(n, 0xabc + n as u64); + let mut data: Vec> = input.iter().map(|v| Complex::new(*v, 0.0)).collect(); + let mut fft = Fft::new(n); + fft.forward(&mut data); + fft.inverse(&mut data); + let got: Vec = data.iter().map(|c| c.re).collect(); + let error = rel_error(&got, &input); + if error > worst { + worst = error; + size = n; + } + assert!(error < 1e-6, "n = {n}: round-trip error {error:e}"); + } + println!("f32 FFT round trip: worst rel error {worst:e} (n = {size})"); + } + + #[test] + fn split_and_interleaved_agree() { + let n = 256; + let input = complex_noise(n, 4242); + let mut fft = Fft::new(n); + let mut interleaved = input.clone(); + fft.forward(&mut interleaved); + let mut re: Vec = input.iter().map(|c| c.re).collect(); + let mut im: Vec = input.iter().map(|c| c.im).collect(); + fft.forward_split(&mut re, &mut im); + for (k, c) in interleaved.iter().enumerate() { + assert!((c.re - re[k]).abs() < 1e-12 && (c.im - im[k]).abs() < 1e-12); + } + } + + #[test] + fn real_fft_matches_complex_fft() { + for shift in 2..=12 { + let n = 1usize << shift; + let signal: Vec = noise(n, 0xfeed + n as u64); + let mut rfft = RealFft::new(n); + let mut spectrum = vec![Complex::new(0.0, 0.0); n / 2 + 1]; + rfft.forward(&signal, &mut spectrum); + + let mut want: Vec> = + signal.iter().map(|v| Complex::new(*v, 0.0)).collect(); + Fft::new(n).forward(&mut want); + for k in 0..=n / 2 { + assert!( + (spectrum[k].re - want[k].re).abs() < 1e-10 + && (spectrum[k].im - want[k].im).abs() < 1e-10, + "n = {n}, bin {k}: {:?} vs {:?}", + spectrum[k], + want[k] + ); + } + + let mut back = vec![0.0; n]; + rfft.inverse(&spectrum, &mut back); + assert!(rel_error(&back, &signal) < 1e-12, "n = {n} real round trip"); + } + } + + #[test] + #[should_panic(expected = "power of two")] + fn rejects_non_power_of_two() { + let _ = Fft::::new(48); + } + + fn complex_error(got: &[Complex], want: &[Complex]) -> f64 { + let mut num = 0.0; + let mut den = 0.0; + for (g, w) in got.iter().zip(want) { + num += (*g - *w).norm_sqr(); + den += w.norm_sqr(); + } + (num / den).sqrt() + } +} diff --git a/crates/ec-dsp/src/lib.rs b/crates/ec-dsp/src/lib.rs new file mode 100644 index 00000000..400fe227 --- /dev/null +++ b/crates/ec-dsp/src/lib.rs @@ -0,0 +1,321 @@ +//! The one set of transforms every edith_codecs audio and video coder uses. +//! +//! AAC, Vorbis, Opus/CELT, MP3 and the JPEG-class video paths all reduce to the +//! same three kernels, so they live here once: a power-of-two complex [`Fft`] +//! (with a real-input wrapper), the DCT family built on top of it, and +//! [`Mdct`] — the lapped transform those codecs actually call — routed through +//! an `N/4`-point FFT. +//! +//! Contracts worth knowing before implementing against this crate: +//! +//! - **The FFT is never optional.** There is no feature flag, no fallback, no +//! `O(n²)` path anywhere: a codec that links this crate gets the fast +//! transform or does not compile. Two incumbent crates shipped an `O(n²)` +//! transform behind a default-off feature and ran 40x slower than the +//! product needed; that failure mode is designed out rather than tested for. +//! - **Plans own their scratch.** [`Fft`], [`Dct`], [`Dct4`] and [`Mdct`] are +//! built once per size and then reused; the transform methods take `&mut +//! self` and allocate nothing. Clone a plan to use it from another thread. +//! - **Sizes are checked at construction, not per call.** A bad size is API +//! misuse and panics in the constructor; the hot path has no error branch. +//! - **`f32` and `f64` are the same code.** Twiddles are always computed in +//! `f64` and rounded once, so the `f32` plans keep the accuracy their table +//! allows. +//! - **Inverses are scaled.** [`Fft::inverse`] divides by `n`, so a forward +//! followed by an inverse returns the input. [`Mdct`] follows the usual +//! codec convention (`2/N` on the inverse) and reconstructs exactly under +//! overlap-add with any Princen-Bradley window from [`window`]. +//! +//! Hot loops are vectorised with the `wide` crate through [`Real`]; the scalar +//! and SIMD paths are the same expressions over the same data layout, so +//! neither can drift from the other in correctness. +//! +//! No unsafe, no allocation on the transform path, no other dependencies. + +#![forbid(unsafe_code)] +#![warn(missing_docs)] + +pub mod dct; +pub mod fft; +pub mod mdct; +pub mod window; + +pub use dct::{Dct, Dct4}; +pub use fft::{Complex, Fft, RealFft}; +pub use mdct::Mdct; +pub use window::Window; + +use core::fmt::Debug; +use core::ops::{Add, Div, Mul, Neg, Sub}; + +/// The sample types the transforms are generic over: `f32` and `f64`. +/// +/// The trait exists to give one implementation of each transform for both +/// precisions *including* its SIMD form: [`Real::Lanes`] is the widest `wide` +/// vector for the type, and the kernels fall back to scalar code on the +/// remainder of a row. Implementing it for anything else is not supported — +/// the transforms assume IEEE-754 binary arithmetic. +pub trait Real: + Copy + + Debug + + Default + + PartialOrd + + Add + + Sub + + Mul + + Div + + Neg + + Send + + Sync + + 'static +{ + /// A vector of [`Real::LANES`] values, backed by `wide`. + type Lanes: Copy + + Add + + Sub + + Mul; + + /// Values per [`Real::Lanes`] vector (8 for `f32`, 4 for `f64`). + const LANES: usize; + /// Additive identity. + const ZERO: Self; + /// Multiplicative identity. + const ONE: Self; + + /// Rounds an `f64` — how every table entry in this crate is produced. + fn from_f64(v: f64) -> Self; + /// Widens to `f64`, for reference computations and reporting. + fn to_f64(self) -> f64; + /// Square root. + fn sqrt(self) -> Self; + /// Absolute value. + fn abs(self) -> Self; + /// Broadcasts one value across a vector. + fn splat(self) -> Self::Lanes; + /// Loads exactly [`Real::LANES`] values. Panics if `src` is another + /// length — callers feed it `chunks_exact(LANES)`, which is what lets the + /// bounds check fold away in the transform inner loops. + fn load(src: &[Self]) -> Self::Lanes; + /// Stores exactly [`Real::LANES`] values. Panics if `dst` is another length. + fn store(v: Self::Lanes, dst: &mut [Self]); +} + +impl Real for f32 { + type Lanes = wide::f32x8; + + const LANES: usize = 8; + const ZERO: f32 = 0.0; + const ONE: f32 = 1.0; + + #[inline] + fn from_f64(v: f64) -> f32 { + v as f32 + } + #[inline] + fn to_f64(self) -> f64 { + self as f64 + } + #[inline] + fn sqrt(self) -> f32 { + f32::sqrt(self) + } + #[inline] + fn abs(self) -> f32 { + f32::abs(self) + } + #[inline] + fn splat(self) -> wide::f32x8 { + wide::f32x8::splat(self) + } + #[inline] + fn load(src: &[f32]) -> wide::f32x8 { + let chunk: [f32; 8] = src.try_into().expect("load needs exactly 8 values"); + wide::bytemuck::cast(chunk) + } + #[inline] + fn store(v: wide::f32x8, dst: &mut [f32]) { + dst.copy_from_slice(&v.to_array()); + } +} + +impl Real for f64 { + type Lanes = wide::f64x4; + + const LANES: usize = 4; + const ZERO: f64 = 0.0; + const ONE: f64 = 1.0; + + #[inline] + fn from_f64(v: f64) -> f64 { + v + } + #[inline] + fn to_f64(self) -> f64 { + self + } + #[inline] + fn sqrt(self) -> f64 { + f64::sqrt(self) + } + #[inline] + fn abs(self) -> f64 { + f64::abs(self) + } + #[inline] + fn splat(self) -> wide::f64x4 { + wide::f64x4::splat(self) + } + #[inline] + fn load(src: &[f64]) -> wide::f64x4 { + let chunk: [f64; 4] = src.try_into().expect("load needs exactly 4 values"); + wide::bytemuck::cast(chunk) + } + #[inline] + fn store(v: wide::f64x4, dst: &mut [f64]) { + dst.copy_from_slice(&v.to_array()); + } +} + +/// Multiplies `data` by `factor` in place, vectorised. +pub(crate) fn scale(data: &mut [T], factor: T) { + let fv = factor.splat(); + let mut chunks = data.chunks_exact_mut(T::LANES); + for chunk in &mut chunks { + T::store(T::load(chunk) * fv, chunk); + } + for v in chunks.into_remainder() { + *v = *v * factor; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Deterministic test signal — no `rand` dependency in a DSP crate. + pub(crate) fn noise(n: usize, seed: u64) -> Vec { + let mut state = seed | 1; + (0..n) + .map(|_| { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + let unit = (state >> 11) as f64 / (1u64 << 53) as f64; + T::from_f64(unit * 2.0 - 1.0) + }) + .collect() + } + + /// Relative L2 error of `got` against `want`, both read as `f64`. + pub(crate) fn rel_error(got: &[T], want: &[T]) -> f64 { + let mut num = 0.0; + let mut den = 0.0; + for (g, w) in got.iter().zip(want) { + let d = g.to_f64() - w.to_f64(); + num += d * d; + den += w.to_f64() * w.to_f64(); + } + (num / den.max(f64::MIN_POSITIVE)).sqrt() + } + + /// Throughput, printed rather than asserted: the numbers are machine + /// specific, but a regression of the *order of magnitude* is what the + /// family cares about (an incumbent shipped an O(n^2) transform and lost + /// 40x). Run with: + /// + /// `cargo test -p ec-dsp --release -- --ignored --nocapture throughput` + #[test] + #[ignore = "timing; run in release with --ignored --nocapture"] + fn throughput() { + use crate::{Complex, Fft, Mdct, RealFft, Window}; + use std::time::Instant; + + let n = 2048; + let signal: Vec = noise(n, 0xdeadbeef); + let mut guard = 0.0f32; + + let mut fft = Fft::::new(n); + let mut data: Vec> = signal.iter().map(|v| Complex::new(*v, 0.0)).collect(); + let iters = 50_000; + // Alternating directions keeps the in-place data bounded, so the + // numbers are not measured on infinities; the inverse costs one extra + // scaling pass, which makes this average slightly pessimistic. + let t0 = Instant::now(); + for i in 0..iters { + if i % 2 == 0 { + fft.forward(&mut data); + } else { + fft.inverse(&mut data); + } + } + report("complex FFT f32 2048 fwd/inv", t0.elapsed(), iters, n); + guard += data[0].re; + + let mut re: Vec = signal.clone(); + let mut im: Vec = vec![0.0; n]; + let t0 = Instant::now(); + for i in 0..iters { + if i % 2 == 0 { + fft.forward_split(&mut re, &mut im); + } else { + fft.inverse_split(&mut re, &mut im); + } + } + report("split FFT f32 2048 fwd/inv", t0.elapsed(), iters, n); + guard += re[0]; + + let mut rfft = RealFft::::new(n); + let mut spectrum = vec![Complex::new(0.0f32, 0.0); n / 2 + 1]; + let t0 = Instant::now(); + for _ in 0..iters { + rfft.forward(&signal, &mut spectrum); + } + report("real FFT f32 2048 fwd", t0.elapsed(), iters, n); + guard += spectrum[0].re; + + let mut mdct = Mdct::::new(n); + let window = Window::::kbd(n, 4.0); + let mut coeffs = vec![0.0f32; n / 2]; + let t0 = Instant::now(); + for _ in 0..iters { + mdct.forward_windowed(&signal, window.as_slice(), &mut coeffs); + } + report("MDCT f32 2048 fwd (windowed)", t0.elapsed(), iters, n); + guard += coeffs[0]; + + let mut frame = vec![0.0f32; n]; + let t0 = Instant::now(); + for _ in 0..iters { + mdct.inverse_windowed(&coeffs, window.as_slice(), &mut frame); + } + report("IMDCT f32 2048 inv (windowed)", t0.elapsed(), iters, n); + guard += frame[0]; + + // 48 kHz stereo AAC: 2 channels * 46.875 long blocks per second. + let per_block = t0.elapsed().as_secs_f64() / iters as f64; + println!("guard {guard:e}"); + println!( + "one 2048 IMDCT = {:.2} us; a 5.1 48 kHz stream needs 6*46.9 = 281 per second", + per_block * 1e6 + ); + } + + fn report(label: &str, elapsed: std::time::Duration, iters: u32, n: usize) { + let per = elapsed.as_secs_f64() / iters as f64; + println!( + "{label:<32} {:>8.0} ns/transform {:>7.1} Mpoint/s", + per * 1e9, + n as f64 / per / 1e6 + ); + } + + #[test] + fn scale_matches_scalar_across_the_lane_boundary() { + for n in [1usize, 3, 8, 9, 17, 64] { + let mut data: Vec = noise(n, 7); + let want: Vec = data.iter().map(|v| v * 0.25).collect(); + scale(&mut data, 0.25); + assert_eq!(data, want, "n = {n}"); + } + } +} diff --git a/crates/ec-dsp/src/mdct.rs b/crates/ec-dsp/src/mdct.rs new file mode 100644 index 00000000..86b545ec --- /dev/null +++ b/crates/ec-dsp/src/mdct.rs @@ -0,0 +1,338 @@ +//! MDCT and IMDCT — the lapped transform AAC, Vorbis, MP3 and CELT code with. +//! +//! Definition, for a window of `2N` samples producing `N` coefficients: +//! +//! ```text +//! X[k] = sum_{n=0}^{2N-1} x[n] cos(pi/N (n + 1/2 + N/2)(k + 1/2)) +//! y[n] = (2/N) sum_{k=0}^{N-1} X[k] cos(pi/N (n + 1/2 + N/2)(k + 1/2)) +//! ``` +//! +//! The `2/N` on the inverse is the codec convention: with any +//! Princen-Bradley window from [`crate::window`], applied on both analysis and +//! synthesis, 50 %-overlapped frames add up to the original signal exactly +//! (TDAC). [`Mdct::perfect_reconstruction_error`] is that claim as a +//! runnable check. +//! +//! Implementation is the standard fold-then-DCT-IV: the `2N` window folds to +//! `N` points by the transform's own symmetries, and the DCT-IV runs on an +//! `N/2`-point complex FFT. So an AAC long block (2048 samples, 1024 +//! coefficients) costs one 512-point FFT — not a 2048x1024 matrix product. + +use crate::Real; +use crate::dct::Dct4; + +/// An MDCT/IMDCT plan for one window size. +/// +/// ``` +/// use ec_dsp::{Mdct, Window}; +/// +/// // AAC long block. +/// let mut mdct = Mdct::::new(2048); +/// assert_eq!(mdct.spectrum_len(), 1024); +/// let window = Window::::sine(2048); +/// let error = mdct.perfect_reconstruction_error(&window, 0x51de); +/// assert!(error < 1e-6, "TDAC error {error}"); +/// ``` +#[derive(Clone, Debug)] +pub struct Mdct { + half: usize, + dct: Dct4, + fold: Vec, +} + +impl Mdct { + /// A plan for a window of `window_len` samples, producing `window_len/2` + /// coefficients. AAC uses 2048 and 256; Vorbis and CELT sizes are the same + /// shape. + /// + /// # Panics + /// If `window_len` is not a power of two of at least 4. + pub fn new(window_len: usize) -> Mdct { + assert!( + window_len.is_power_of_two() && window_len >= 4, + "mdct window must be a power of two of at least 4, got {window_len}" + ); + let half = window_len / 2; + Mdct { + half, + dct: Dct4::new(half), + fold: vec![T::ZERO; half], + } + } + + /// Samples per window (`2N`). + pub fn window_len(&self) -> usize { + self.half * 2 + } + + /// Coefficients per window (`N`). + pub fn spectrum_len(&self) -> usize { + self.half + } + + /// Transforms one window of samples into coefficients. + /// + /// # Panics + /// If `input.len() != window_len()` or `output.len() != spectrum_len()`. + pub fn forward(&mut self, input: &[T], output: &mut [T]) { + self.fold_input(input, None); + output.copy_from_slice(&self.fold); + self.dct.transform(output); + } + + /// [`Mdct::forward`] with the analysis window applied in the same pass — + /// the fold reads each sample once, so windowing here costs one multiply + /// and no extra buffer. + /// + /// # Panics + /// If any length is wrong, including `window.len() != window_len()`. + pub fn forward_windowed(&mut self, input: &[T], window: &[T], output: &mut [T]) { + assert_eq!( + window.len(), + self.window_len(), + "window length must equal the mdct window" + ); + self.fold_input(input, Some(window)); + output.copy_from_slice(&self.fold); + self.dct.transform(output); + } + + /// Transforms coefficients back into one window of samples, ready for + /// overlap-add. Includes the `2/N` scaling. + /// + /// # Panics + /// If `spectrum.len() != spectrum_len()` or `output.len() != window_len()`. + pub fn inverse(&mut self, spectrum: &[T], output: &mut [T]) { + self.unfold(spectrum, output, None); + } + + /// [`Mdct::inverse`] with the synthesis window applied as the samples are + /// written out. + /// + /// # Panics + /// If any length is wrong, including `window.len() != window_len()`. + pub fn inverse_windowed(&mut self, spectrum: &[T], window: &[T], output: &mut [T]) { + assert_eq!( + window.len(), + self.window_len(), + "window length must equal the mdct window" + ); + self.unfold(spectrum, output, Some(window)); + } + + /// Folds `2N` samples down to the `N` points DCT-IV acts on, optionally + /// windowing on the way in. + fn fold_input(&mut self, input: &[T], window: Option<&[T]>) { + assert_eq!( + input.len(), + self.window_len(), + "mdct input must be one full window" + ); + let n = self.half; + let quarter = n / 2; + let at = |i: usize| match window { + Some(w) => input[i] * w[i], + None => input[i], + }; + for i in 0..quarter { + // First half: -c reversed - d. Second half: a - b reversed. + self.fold[i] = -at(3 * quarter - 1 - i) - at(3 * quarter + i); + self.fold[quarter + i] = at(i) - at(n - 1 - i); + } + } + + /// Runs DCT-IV and unfolds back to `2N` samples with the transform's + /// symmetries, optionally windowing on the way out. + fn unfold(&mut self, spectrum: &[T], output: &mut [T], window: Option<&[T]>) { + assert_eq!( + spectrum.len(), + self.half, + "mdct spectrum must be one full block" + ); + assert_eq!( + output.len(), + self.window_len(), + "mdct output must be one full window" + ); + let n = self.half; + let quarter = n / 2; + self.fold.copy_from_slice(spectrum); + self.dct.transform(&mut self.fold); + let gain = T::from_f64(2.0 / n as f64); + let mut put = |i: usize, v: T| { + output[i] = match window { + Some(w) => v * gain * w[i], + None => v * gain, + }; + }; + for i in 0..quarter { + put(i, self.fold[quarter + i]); + put(quarter + i, -self.fold[n - 1 - i]); + put(n + i, -self.fold[quarter - 1 - i]); + put(n + quarter + i, -self.fold[i]); + } + } + + /// Runs three overlapped frames of pseudo-random audio through + /// analysis and synthesis with `window` and returns the worst absolute + /// reconstruction error in the fully overlapped region. + /// + /// This is the property a codec actually depends on — the transform pair + /// and the window are only correct *together* — so it is exposed rather + /// than hidden in a test: a codec's own suite can assert it for whatever + /// window it ships. + /// + /// # Panics + /// If `window.len() != window_len()`. + pub fn perfect_reconstruction_error(&mut self, window: &crate::Window, seed: u64) -> f64 { + let n = self.half; + let win = window.as_slice(); + assert_eq!(win.len(), 2 * n, "window length must equal the mdct window"); + + // 4 hops of N samples; frames 0..2 cover [0, 4N) with 50 % overlap. + let mut state = seed | 1; + let signal: Vec = (0..4 * n) + .map(|_| { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + T::from_f64((state >> 11) as f64 / (1u64 << 53) as f64 * 2.0 - 1.0) + }) + .collect(); + + let mut sum = vec![T::ZERO; 4 * n]; + let mut spectrum = vec![T::ZERO; n]; + let mut frame = vec![T::ZERO; 2 * n]; + for f in 0..3 { + let start = f * n; + self.forward_windowed(&signal[start..start + 2 * n], win, &mut spectrum); + self.inverse_windowed(&spectrum, win, &mut frame); + for (i, v) in frame.iter().enumerate() { + sum[start + i] = sum[start + i] + *v; + } + } + // Only [N, 3N) sees both of its overlapping frames. + (n..3 * n) + .map(|i| (sum[i].to_f64() - signal[i].to_f64()).abs()) + .fold(0.0, f64::max) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::Window; + use crate::tests::{noise, rel_error}; + use core::f64::consts::PI; + + /// O(n^2) reference MDCT, test-only. + fn reference_mdct(x: &[f64]) -> Vec { + let n = x.len() / 2; + (0..n) + .map(|k| { + (0..2 * n) + .map(|j| { + x[j] * (PI / n as f64 + * (j as f64 + 0.5 + n as f64 / 2.0) + * (k as f64 + 0.5)) + .cos() + }) + .sum() + }) + .collect() + } + + /// O(n^2) reference IMDCT including the 2/N convention, test-only. + fn reference_imdct(x: &[f64]) -> Vec { + let n = x.len(); + (0..2 * n) + .map(|j| { + 2.0 / n as f64 + * (0..n) + .map(|k| { + x[k] * (PI / n as f64 + * (j as f64 + 0.5 + n as f64 / 2.0) + * (k as f64 + 0.5)) + .cos() + }) + .sum::() + }) + .collect() + } + + #[test] + fn forward_matches_reference() { + let mut worst = 0.0f64; + // 2048 and 256 are the AAC long and short blocks; 512/1024 cover + // Vorbis and CELT shapes. + for window_len in [8usize, 64, 256, 512, 1024, 2048] { + let input: Vec = noise(window_len, 0x4444 + window_len as u64); + let want = reference_mdct(&input); + let mut got = vec![0.0; window_len / 2]; + Mdct::new(window_len).forward(&input, &mut got); + let error = rel_error(&got, &want); + worst = worst.max(error); + assert!(error < 1e-12, "mdct {window_len}: error {error:e}"); + } + println!("MDCT vs reference: worst rel error {worst:e}"); + } + + #[test] + fn inverse_matches_reference() { + let mut worst = 0.0f64; + for window_len in [8usize, 64, 256, 2048] { + let spectrum: Vec = noise(window_len / 2, 0x5555 + window_len as u64); + let want = reference_imdct(&spectrum); + let mut got = vec![0.0; window_len]; + Mdct::new(window_len).inverse(&spectrum, &mut got); + let error = rel_error(&got, &want); + worst = worst.max(error); + assert!(error < 1e-12, "imdct {window_len}: error {error:e}"); + } + println!("IMDCT vs reference: worst rel error {worst:e}"); + } + + #[test] + fn tdac_reconstructs_with_every_window() { + for window_len in [256usize, 2048] { + let mut mdct = Mdct::::new(window_len); + for (name, window) in [ + ("sine", Window::::sine(window_len)), + ("vorbis", Window::::vorbis(window_len)), + ("kbd-4", Window::::kbd(window_len, 4.0)), + ("kbd-6", Window::::kbd(window_len, 6.0)), + ] { + let error = mdct.perfect_reconstruction_error(&window, 0x6666); + assert!(error < 1e-12, "{name} {window_len}: TDAC error {error:e}"); + println!("TDAC {name} {window_len}: max abs error {error:e}"); + } + } + } + + #[test] + fn tdac_reconstructs_in_f32() { + let mut mdct = Mdct::::new(2048); + let window = Window::::kbd(2048, 4.0); + let error = mdct.perfect_reconstruction_error(&window, 0x7777); + assert!(error < 1e-5, "f32 TDAC error {error:e}"); + println!("TDAC f32 kbd-4 2048: max abs error {error:e}"); + } + + #[test] + fn windowed_forward_equals_manual_windowing() { + let window_len = 256; + let input: Vec = noise(window_len, 0x8888); + let window = Window::::sine(window_len); + let manual: Vec = input + .iter() + .zip(window.as_slice()) + .map(|(x, w)| x * w) + .collect(); + let mut mdct = Mdct::new(window_len); + let mut a = vec![0.0f32; window_len / 2]; + let mut b = vec![0.0f32; window_len / 2]; + mdct.forward(&manual, &mut a); + mdct.forward_windowed(&input, window.as_slice(), &mut b); + assert_eq!(a, b); + } +} diff --git a/crates/ec-dsp/src/window.rs b/crates/ec-dsp/src/window.rs new file mode 100644 index 00000000..7c238c65 --- /dev/null +++ b/crates/ec-dsp/src/window.rs @@ -0,0 +1,258 @@ +//! Analysis/synthesis windows for the lapped transforms. +//! +//! All three shapes here satisfy the Princen-Bradley condition +//! `w[n]^2 + w[n + N]^2 == 1`, which is what makes MDCT overlap-add +//! reconstruct exactly; [`Window::princen_bradley_error`] measures it. +//! +//! - [`Window::sine`] — MP3, AAC's other long window, CELT's basis. +//! - [`Window::kbd`] — AAC's Kaiser-Bessel-derived window (alpha 4 for long +//! blocks, 6 for short, per ISO/IEC 14496-3). +//! - [`Window::vorbis`] — the Vorbis I "slope" window, also used by Opus. +//! +//! Codecs that need asymmetric start/stop windows build them from the halves +//! of two of these; nothing here presumes a symmetric block. + +use crate::Real; + +/// A precomputed window, one value per sample of the transform block. +/// +/// ``` +/// use ec_dsp::Window; +/// +/// let w = Window::::kbd(2048, 4.0); +/// assert_eq!(w.len(), 2048); +/// assert!(w.princen_bradley_error() < 1e-12); +/// ``` +#[derive(Clone, Debug, PartialEq)] +pub struct Window { + samples: Vec, +} + +impl Window { + /// Wraps precomputed values, for shapes this module does not provide + /// (asymmetric transition windows, for instance). + /// + /// # Panics + /// If `samples` is empty or has odd length. + pub fn from_samples(samples: Vec) -> Window { + assert!( + !samples.is_empty() && samples.len().is_multiple_of(2), + "a window must have an even, non-zero length" + ); + Window { samples } + } + + /// Sine window: `w[n] = sin(pi/L (n + 1/2))`, `L` the full window length. + /// + /// # Panics + /// If `len` is zero or odd. + pub fn sine(len: usize) -> Window { + Window::from_samples( + (0..len) + .map(|n| { + let a = core::f64::consts::PI / len as f64 * (n as f64 + 0.5); + T::from_f64(a.sin()) + }) + .collect(), + ) + } + + /// Vorbis window: `w[n] = sin(pi/2 * sin^2(pi/L (n + 1/2)))`. + /// + /// # Panics + /// If `len` is zero or odd. + pub fn vorbis(len: usize) -> Window { + Window::from_samples( + (0..len) + .map(|n| { + let inner = (core::f64::consts::PI / len as f64 * (n as f64 + 0.5)).sin(); + T::from_f64((core::f64::consts::FRAC_PI_2 * inner * inner).sin()) + }) + .collect(), + ) + } + + /// Kaiser-Bessel-derived window with shape parameter `alpha` (AAC uses 4 + /// for 2048-sample blocks and 6 for 256-sample blocks). + /// + /// Built the defining way: a Kaiser window of `len/2 + 1` points, + /// cumulatively summed and square-rooted, then mirrored — which is what + /// makes the Princen-Bradley identity hold by construction rather than by + /// numerical luck. + /// + /// # Panics + /// If `len` is not a positive multiple of 4, or `alpha` is negative. + pub fn kbd(len: usize, alpha: f64) -> Window { + assert!( + len >= 4 && len.is_multiple_of(4), + "a kbd window needs a length that is a positive multiple of 4, got {len}" + ); + assert!(alpha >= 0.0, "kbd alpha must be non-negative, got {alpha}"); + let half = len / 2; + let beta = core::f64::consts::PI * alpha; + let denom = bessel_i0(beta); + let mut cumulative = Vec::with_capacity(half + 1); + let mut running = 0.0; + for m in 0..=half { + let ratio = 2.0 * m as f64 / half as f64 - 1.0; + running += bessel_i0(beta * (1.0 - ratio * ratio).max(0.0).sqrt()) / denom; + cumulative.push(running); + } + let total = running; + let mut samples = vec![T::ZERO; len]; + for n in 0..half { + let v = T::from_f64((cumulative[n] / total).sqrt()); + samples[n] = v; + samples[len - 1 - n] = v; + } + Window::from_samples(samples) + } + + /// The window values. + pub fn as_slice(&self) -> &[T] { + &self.samples + } + + /// Samples in the window. + pub fn len(&self) -> usize { + self.samples.len() + } + + /// Always false — a window cannot be empty (see [`Window::from_samples`]). + pub fn is_empty(&self) -> bool { + false + } + + /// Multiplies `block` by the window in place, vectorised. + /// + /// # Panics + /// If `block.len() != self.len()`. + pub fn apply(&self, block: &mut [T]) { + assert_eq!( + block.len(), + self.samples.len(), + "block length must equal window length" + ); + let lanes = T::LANES; + let mut chunks = block.chunks_exact_mut(lanes); + for (chunk, w) in (&mut chunks).zip(self.samples.chunks_exact(lanes)) { + T::store(T::load(chunk) * T::load(w), chunk); + } + let done = self.samples.len() - self.samples.len() % lanes; + for (v, w) in chunks + .into_remainder() + .iter_mut() + .zip(&self.samples[done..]) + { + *v = *v * *w; + } + } + + /// Worst deviation from the Princen-Bradley condition + /// `w[n]^2 + w[n + len/2]^2 == 1`, the property MDCT overlap-add needs. + pub fn princen_bradley_error(&self) -> f64 { + let half = self.samples.len() / 2; + (0..half) + .map(|n| { + let a = self.samples[n].to_f64(); + let b = self.samples[n + half].to_f64(); + (a * a + b * b - 1.0).abs() + }) + .fold(0.0, f64::max) + } +} + +/// Modified Bessel function of the first kind, order zero, by its power +/// series — accurate to `f64` for the arguments a KBD window uses (`beta` up +/// to about 20). +fn bessel_i0(x: f64) -> f64 { + let half = x / 2.0; + let mut term = 1.0; + let mut sum = 1.0; + let mut k = 1.0; + while term > 1e-18 * sum { + term *= (half / k) * (half / k); + sum += term; + k += 1.0; + if k > 200.0 { + break; + } + } + sum +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn all_shapes_satisfy_princen_bradley() { + for len in [64usize, 256, 2048] { + for (name, w) in [ + ("sine", Window::::sine(len)), + ("vorbis", Window::::vorbis(len)), + ("kbd-4", Window::::kbd(len, 4.0)), + ("kbd-6", Window::::kbd(len, 6.0)), + ("kbd-0", Window::::kbd(len, 0.0)), + ] { + let error = w.princen_bradley_error(); + assert!(error < 1e-12, "{name} {len}: PB error {error:e}"); + } + } + } + + #[test] + fn windows_are_symmetric_and_bounded() { + let len = 512; + for w in [ + Window::::sine(len), + Window::::vorbis(len), + Window::::kbd(len, 4.0), + ] { + let s = w.as_slice(); + for n in 0..len { + assert!((0.0..=1.0).contains(&s[n]), "value out of range: {}", s[n]); + assert!( + (s[n] - s[len - 1 - n]).abs() < 1e-12, + "asymmetric at {n}: {} vs {}", + s[n], + s[len - 1 - n] + ); + } + } + } + + #[test] + fn bessel_i0_matches_known_values() { + // Abramowitz & Stegun table values. + for (x, want) in [ + (0.0, 1.0), + (1.0, 1.266_065_877_752_008_4), + (5.0, 27.239_871_823_604_44), + (10.0, 2_815.716_628_466_254), + ] { + let got = bessel_i0(x); + assert!( + (got - want).abs() <= 1e-9 * want.abs().max(1.0), + "I0({x}) = {got}, want {want}" + ); + } + } + + #[test] + fn apply_matches_scalar_multiply() { + let len = 262; // not a multiple of the f64 lane count + let w = Window::::sine(len); + let block: Vec = (0..len).map(|n| n as f64 * 0.5 - 3.0).collect(); + let want: Vec = block.iter().zip(w.as_slice()).map(|(b, s)| b * s).collect(); + let mut got = block.clone(); + w.apply(&mut got); + assert_eq!(got, want); + } + + #[test] + #[should_panic(expected = "multiple of 4")] + fn kbd_rejects_odd_lengths() { + let _ = Window::::kbd(30, 4.0); + } +}