forge
Explore
Log in

Don't you dare go Hollow

FFT/DCT/MDCT/window primitives

Browse files at this commit

09790f6f49d3ec5e80e89788dc789d7a574ad1c5Ahmet Kaan GümüşParent: 0dc3e2b
  • feat
    • FFT/DCT/MDCT/window primitives
Show full message
feat(dsp): FFT/DCT/MDCT/window primitives

Radix-4/radix-2 Stockham FFT (power-of-two, 1..65536, f32 and f64),
real-input wrapper on the N/2 complex trick, DCT-II/III via Makhoul and
DCT-IV via an N/2 FFT, MDCT/IMDCT folded onto DCT-IV (AAC 2048/256 and
Vorbis/CELT sizes go through an N/4-point FFT), and sine/KBD/Vorbis
windows with fused application.

No feature gates: the fast transform is the only transform, and the only
O(n^2) code in the crate is the reference DFT/DCT/MDCT behind cfg(test).
Hot loops vectorise through wide on chunks_exact, so the bounds checks
fold; the scalar remainder is the same expression.

Accuracy vs the f64 reference, sizes 8..8192: 3.1e-15 f64, 1.3e-7 f32;
f32 forward+inverse round trip 1.6e-7 to n=32768; MDCT TDAC 2.2e-15 f64
/ 4.8e-7 f32 with every window shipped.
Cargo.lockmodified+32 -0
@@ -2,10 +2,42 @@
2 # It is not intended for manual editing.2 # It is not intended for manual editing.
3 version = 43 version = 4
4 4
5+[[package]]
6+name = "bytemuck"
7+version = "1.25.2"
8+source = "registry+https://github.com/rust-lang/crates.io-index"
9+checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"
10+
5 [[package]]11 [[package]]
6 name = "ec-core"12 name = "ec-core"
7 version = "0.1.0"13 version = "0.1.0"
8 14
15+[[package]]
16+name = "ec-dsp"
17+version = "0.1.0"
18+dependencies = [
19+ "wide",
20+]
21+
9 [[package]]22 [[package]]
10 name = "oracle"23 name = "oracle"
11 version = "0.1.0"24 version = "0.1.0"
25+
26+[[package]]
27+name = "safe_arch"
28+version = "1.1.0"
29+source = "registry+https://github.com/rust-lang/crates.io-index"
30+checksum = "3a52ec151f024d703f9fd65abb7cbe81e7cdb39f18917a3a37e3014470dc7c59"
31+dependencies = [
32+ "bytemuck",
33+]
34+
35+[[package]]
36+name = "wide"
37+version = "1.6.1"
38+source = "registry+https://github.com/rust-lang/crates.io-index"
39+checksum = "de2aaf408e58689c2096682331b1f42bb2d9f2ed6b11560407d023cd0a6c634e"
40+dependencies = [
41+ "bytemuck",
42+ "safe_arch",
43+]
crates/ec-dsp/Cargo.tomladded+10 -0
@@ -0,0 +1,10 @@
1+[package]
2+name = "ec-dsp"
3+description = "Shared transforms for the edith_codecs family: FFT, DCT, MDCT and analysis windows."
4+version.workspace = true
5+edition.workspace = true
6+license.workspace = true
7+authors.workspace = true
8+
9+[dependencies]
10+wide.workspace = true
crates/ec-dsp/src/dct.rsadded+305 -0
@@ -0,0 +1,305 @@
1+//! DCT-II, DCT-III and DCT-IV, all routed through an FFT.
2+//!
3+//! Every one of these is `O(n log n)` here. Definitions, unnormalised, for
4+//! length `N`:
5+//!
6+//! - DCT-II: `X[k] = sum_n x[n] cos(pi/N (n + 1/2) k)`
7+//! - DCT-III: `X[k] = x[0]/2 + sum_{n>=1} x[n] cos(pi/N n (k + 1/2))`
8+//! - DCT-IV: `X[k] = sum_n x[n] cos(pi/N (n + 1/2)(k + 1/2))`
9+//!
10+//! DCT-III is the inverse of DCT-II up to the usual `2/N`, i.e.
11+//! `x == (2/N) * dct3(dct2(x))`. DCT-IV is its own inverse up to the same
12+//! factor, which is why [`crate::Mdct`] needs only the one plan for both
13+//! directions.
14+//!
15+//! II and III use an `N`-point real FFT (Makhoul's method); IV uses an
16+//! `N/2`-point complex FFT with a quarter-sample twiddle on each side.
17+
18+use crate::Real;
19+use crate::fft::{Complex, Fft, RealFft};
20+
21+/// DCT-II / DCT-III plan for one size.
22+///
23+/// ```
24+/// use ec_dsp::Dct;
25+///
26+/// let mut dct = Dct::<f64>::new(8);
27+/// let mut data = [1.0, 2.0, 3.0, 4.0, 4.0, 3.0, 2.0, 1.0];
28+/// let original = data;
29+/// dct.dct2(&mut data);
30+/// dct.dct3(&mut data);
31+/// // dct3 . dct2 = (N/2) * identity
32+/// assert!(data.iter().zip(&original).all(|(a, b)| (a / 4.0 - b).abs() < 1e-12));
33+/// ```
34+#[derive(Clone, Debug)]
35+pub struct Dct<T: Real> {
36+ n: usize,
37+ rfft: RealFft<T>,
38+ twiddle_re: Vec<T>,
39+ twiddle_im: Vec<T>,
40+ shuffled: Vec<T>,
41+ spectrum: Vec<Complex<T>>,
42+}
43+
44+impl<T: Real> Dct<T> {
45+ /// A plan for `n` points.
46+ ///
47+ /// # Panics
48+ /// If `n` is not a power of two of at least 4 (see [`crate::fft::MAX_LEN`]).
49+ pub fn new(n: usize) -> Dct<T> {
50+ let rfft = RealFft::new(n);
51+ let mut twiddle_re = Vec::with_capacity(n);
52+ let mut twiddle_im = Vec::with_capacity(n);
53+ for k in 0..n {
54+ // exp(-i*pi*k/(2N)): the half-sample shift that turns a DFT of the
55+ // even/odd-shuffled signal into a DCT.
56+ let angle = -core::f64::consts::PI * k as f64 / (2.0 * n as f64);
57+ twiddle_re.push(T::from_f64(angle.cos()));
58+ twiddle_im.push(T::from_f64(angle.sin()));
59+ }
60+ Dct {
61+ n,
62+ rfft,
63+ twiddle_re,
64+ twiddle_im,
65+ shuffled: vec![T::ZERO; n],
66+ spectrum: vec![Complex::ZERO; n / 2 + 1],
67+ }
68+ }
69+
70+ /// Points per transform.
71+ pub fn size(&self) -> usize {
72+ self.n
73+ }
74+
75+ /// DCT-II in place.
76+ ///
77+ /// # Panics
78+ /// If `data.len() != self.size()`.
79+ pub fn dct2(&mut self, data: &mut [T]) {
80+ assert_eq!(data.len(), self.n, "dct input length must equal plan size");
81+ let n = self.n;
82+ // Even samples in order, odd samples reversed: a real DFT of this
83+ // sequence carries the DCT-II in its real part after a twiddle.
84+ for j in 0..n / 2 {
85+ self.shuffled[j] = data[2 * j];
86+ self.shuffled[n - 1 - j] = data[2 * j + 1];
87+ }
88+ self.rfft.forward(&self.shuffled, &mut self.spectrum);
89+ for (k, out) in data.iter_mut().enumerate() {
90+ let bin = if k <= n / 2 {
91+ self.spectrum[k]
92+ } else {
93+ self.spectrum[n - k].conj()
94+ };
95+ let tw = Complex::new(self.twiddle_re[k], self.twiddle_im[k]);
96+ *out = (tw * bin).re;
97+ }
98+ }
99+
100+ /// DCT-III in place — [`Dct::dct2`] run backwards, times `N/2`.
101+ ///
102+ /// # Panics
103+ /// If `data.len() != self.size()`.
104+ pub fn dct3(&mut self, data: &mut [T]) {
105+ assert_eq!(data.len(), self.n, "dct input length must equal plan size");
106+ let n = self.n;
107+ for k in 0..=n / 2 {
108+ // The spectrum whose real part is `data`: G[k] = X[k] - i X[N-k].
109+ let hi = if k == 0 { T::ZERO } else { data[n - k] };
110+ let g = Complex::new(data[k], -hi);
111+ let tw = Complex::new(self.twiddle_re[k], self.twiddle_im[k]).conj();
112+ self.spectrum[k] = tw * g;
113+ }
114+ self.rfft.inverse(&self.spectrum, &mut self.shuffled);
115+ let gain = T::from_f64(n as f64 / 2.0);
116+ for j in 0..n / 2 {
117+ data[2 * j] = self.shuffled[j] * gain;
118+ data[2 * j + 1] = self.shuffled[n - 1 - j] * gain;
119+ }
120+ }
121+}
122+
123+/// DCT-IV plan for one size — the kernel [`crate::Mdct`] is built on.
124+///
125+/// ```
126+/// use ec_dsp::Dct4;
127+///
128+/// let mut dct = Dct4::<f64>::new(8);
129+/// let mut data = [1.0, -2.0, 3.0, 0.5, 0.0, 1.5, -1.0, 2.0];
130+/// let original = data;
131+/// dct.transform(&mut data);
132+/// dct.transform(&mut data);
133+/// // DCT-IV is an involution up to N/2.
134+/// assert!(data.iter().zip(&original).all(|(a, b)| (a / 4.0 - b).abs() < 1e-12));
135+/// ```
136+#[derive(Clone, Debug)]
137+pub struct Dct4<T: Real> {
138+ n: usize,
139+ fft: Fft<T>,
140+ pre_re: Vec<T>,
141+ pre_im: Vec<T>,
142+ post_re: Vec<T>,
143+ post_im: Vec<T>,
144+ buf_re: Vec<T>,
145+ buf_im: Vec<T>,
146+}
147+
148+impl<T: Real> Dct4<T> {
149+ /// A plan for `n` points, `n` a power of two of at least 2.
150+ ///
151+ /// # Panics
152+ /// If `n` is not a power of two, or `n/2` is not a legal FFT size.
153+ pub fn new(n: usize) -> Dct4<T> {
154+ assert!(
155+ n.is_power_of_two() && n >= 2,
156+ "dct-iv length must be a power of two of at least 2, got {n}"
157+ );
158+ let half = n / 2;
159+ let mut pre_re = Vec::with_capacity(half);
160+ let mut pre_im = Vec::with_capacity(half);
161+ let mut post_re = Vec::with_capacity(half);
162+ let mut post_im = Vec::with_capacity(half);
163+ for j in 0..half {
164+ // exp(-i*pi*(4j+1)/(4N)) before the FFT, exp(-i*pi*k/N) after:
165+ // together they supply the (n+1/2)(k+1/2) phase of a DCT-IV.
166+ let pre = -core::f64::consts::PI * (4 * j + 1) as f64 / (4.0 * n as f64);
167+ pre_re.push(T::from_f64(pre.cos()));
168+ pre_im.push(T::from_f64(pre.sin()));
169+ let post = -core::f64::consts::PI * j as f64 / n as f64;
170+ post_re.push(T::from_f64(post.cos()));
171+ post_im.push(T::from_f64(post.sin()));
172+ }
173+ Dct4 {
174+ n,
175+ fft: Fft::new(half),
176+ pre_re,
177+ pre_im,
178+ post_re,
179+ post_im,
180+ buf_re: vec![T::ZERO; half],
181+ buf_im: vec![T::ZERO; half],
182+ }
183+ }
184+
185+ /// Points per transform.
186+ pub fn size(&self) -> usize {
187+ self.n
188+ }
189+
190+ /// DCT-IV in place.
191+ ///
192+ /// # Panics
193+ /// If `data.len() != self.size()`.
194+ pub fn transform(&mut self, data: &mut [T]) {
195+ assert_eq!(
196+ data.len(),
197+ self.n,
198+ "dct-iv input length must equal plan size"
199+ );
200+ let n = self.n;
201+ let half = n / 2;
202+ for j in 0..half {
203+ let (re, im) = (data[2 * j], data[n - 1 - 2 * j]);
204+ self.buf_re[j] = re * self.pre_re[j] - im * self.pre_im[j];
205+ self.buf_im[j] = re * self.pre_im[j] + im * self.pre_re[j];
206+ }
207+ self.fft.forward_split(&mut self.buf_re, &mut self.buf_im);
208+ for k in 0..half {
209+ let (re, im) = (self.buf_re[k], self.buf_im[k]);
210+ let (wr, wi) = (self.post_re[k], self.post_im[k]);
211+ data[2 * k] = re * wr - im * wi;
212+ data[n - 1 - 2 * k] = -(re * wi + im * wr);
213+ }
214+ }
215+}
216+
217+#[cfg(test)]
218+mod tests {
219+ use super::*;
220+ use crate::tests::{noise, rel_error};
221+ use core::f64::consts::PI;
222+
223+ /// O(n^2) reference DCTs, test-only.
224+ fn reference(kind: u8, x: &[f64]) -> Vec<f64> {
225+ let n = x.len();
226+ (0..n)
227+ .map(|k| match kind {
228+ 2 => (0..n)
229+ .map(|j| x[j] * (PI / n as f64 * (j as f64 + 0.5) * k as f64).cos())
230+ .sum(),
231+ 3 => {
232+ x[0] / 2.0
233+ + (1..n)
234+ .map(|j| x[j] * (PI / n as f64 * j as f64 * (k as f64 + 0.5)).cos())
235+ .sum::<f64>()
236+ }
237+ _ => (0..n)
238+ .map(|j| x[j] * (PI / n as f64 * (j as f64 + 0.5) * (k as f64 + 0.5)).cos())
239+ .sum(),
240+ })
241+ .collect()
242+ }
243+
244+ #[test]
245+ fn dct2_and_dct3_agree_with_reference() {
246+ let mut worst = 0.0f64;
247+ for shift in 2..=13 {
248+ let n = 1usize << shift;
249+ let input: Vec<f64> = noise(n, 0x2222 + n as u64);
250+ for kind in [2u8, 3] {
251+ let want = reference(kind, &input);
252+ let mut got = input.clone();
253+ let mut dct = Dct::new(n);
254+ if kind == 2 {
255+ dct.dct2(&mut got);
256+ } else {
257+ dct.dct3(&mut got);
258+ }
259+ let error = rel_error(&got, &want);
260+ worst = worst.max(error);
261+ assert!(error < 1e-12, "dct-{kind} n = {n}: error {error:e}");
262+ }
263+ }
264+ println!("f64 DCT-II/III vs reference: worst rel error {worst:e}");
265+ }
266+
267+ #[test]
268+ fn dct4_agrees_with_reference() {
269+ let mut worst_f64 = 0.0f64;
270+ let mut worst_f32 = 0.0f64;
271+ for shift in 1..=13 {
272+ let n = 1usize << shift;
273+ let input: Vec<f64> = noise(n, 0x3333 + n as u64);
274+ let want = reference(4, &input);
275+
276+ let mut got = input.clone();
277+ Dct4::new(n).transform(&mut got);
278+ let error = rel_error(&got, &want);
279+ worst_f64 = worst_f64.max(error);
280+ assert!(error < 1e-12, "dct-iv f64 n = {n}: error {error:e}");
281+
282+ let mut got32: Vec<f32> = input.iter().map(|v| *v as f32).collect();
283+ Dct4::new(n).transform(&mut got32);
284+ let widened: Vec<f64> = got32.iter().map(|v| *v as f64).collect();
285+ let error32 = rel_error(&widened, &want);
286+ worst_f32 = worst_f32.max(error32);
287+ assert!(error32 < 1e-5, "dct-iv f32 n = {n}: error {error32:e}");
288+ }
289+ println!("DCT-IV vs reference: worst rel error f64 {worst_f64:e}, f32 {worst_f32:e}");
290+ }
291+
292+ #[test]
293+ fn dct2_round_trips_through_dct3() {
294+ let n = 1024;
295+ let input: Vec<f32> = noise(n, 5150);
296+ let mut data = input.clone();
297+ let mut dct = Dct::new(n);
298+ dct.dct2(&mut data);
299+ dct.dct3(&mut data);
300+ crate::scale(&mut data, 2.0 / n as f32);
301+ let error = rel_error(&data, &input);
302+ assert!(error < 1e-6, "round-trip error {error:e}");
303+ println!("f32 DCT-II/III round trip (n = {n}): rel error {error:e}");
304+ }
305+}
crates/ec-dsp/src/fft.rsadded+776 -0
@@ -0,0 +1,776 @@
1+//! Power-of-two complex FFT, plus a real-input wrapper.
2+//!
3+//! The kernel is a Stockham auto-sort decimation-in-frequency transform,
4+//! radix-4 wherever the remaining size allows and radix-2 for the odd stage.
5+//! Stockham was chosen over the textbook bit-reversed Cooley-Tukey for one
6+//! reason: every read and write inside a stage is unit stride, which is what
7+//! makes the inner loop vectorise with no shuffles at all.
8+//!
9+//! Data is held **split** — real parts in one slice, imaginary in another —
10+//! because that is the layout SIMD wants. [`Fft::forward`] and
11+//! [`Fft::inverse`] accept the interleaved [`Complex`] form for callers who
12+//! prefer it and de-interleave internally; the DCT and MDCT plans call the
13+//! split entry points and never pay that pass.
14+
15+use core::ops::{Add, Mul, Sub};
16+
17+use crate::Real;
18+
19+/// The largest transform the plans accept, matching the largest window any
20+/// codec in the family uses with room to spare.
21+pub const MAX_LEN: usize = 1 << 16;
22+
23+/// A complex number in the crate's own minimal form (no `num-complex` dep).
24+#[derive(Clone, Copy, Debug, Default, PartialEq)]
25+pub struct Complex<T> {
26+ /// Real part.
27+ pub re: T,
28+ /// Imaginary part.
29+ pub im: T,
30+}
31+
32+impl<T> Complex<T> {
33+ /// A complex number from its parts.
34+ pub const fn new(re: T, im: T) -> Complex<T> {
35+ Complex { re, im }
36+ }
37+}
38+
39+impl<T: Real> Complex<T> {
40+ /// Zero.
41+ pub const ZERO: Complex<T> = Complex {
42+ re: T::ZERO,
43+ im: T::ZERO,
44+ };
45+
46+ /// Complex conjugate.
47+ #[inline]
48+ pub fn conj(self) -> Complex<T> {
49+ Complex::new(self.re, -self.im)
50+ }
51+
52+ /// Multiplication by a real scalar.
53+ #[inline]
54+ pub fn scale(self, k: T) -> Complex<T> {
55+ Complex::new(self.re * k, self.im * k)
56+ }
57+
58+ /// Multiplication by `-i`, i.e. a quarter turn clockwise.
59+ #[inline]
60+ pub fn mul_neg_i(self) -> Complex<T> {
61+ Complex::new(self.im, -self.re)
62+ }
63+
64+ /// Squared magnitude.
65+ #[inline]
66+ pub fn norm_sqr(self) -> T {
67+ self.re * self.re + self.im * self.im
68+ }
69+}
70+
71+impl<T: Real> Add for Complex<T> {
72+ type Output = Complex<T>;
73+ #[inline]
74+ fn add(self, rhs: Complex<T>) -> Complex<T> {
75+ Complex::new(self.re + rhs.re, self.im + rhs.im)
76+ }
77+}
78+
79+impl<T: Real> Sub for Complex<T> {
80+ type Output = Complex<T>;
81+ #[inline]
82+ fn sub(self, rhs: Complex<T>) -> Complex<T> {
83+ Complex::new(self.re - rhs.re, self.im - rhs.im)
84+ }
85+}
86+
87+impl<T: Real> Mul for Complex<T> {
88+ type Output = Complex<T>;
89+ #[inline]
90+ fn mul(self, rhs: Complex<T>) -> Complex<T> {
91+ Complex::new(
92+ self.re * rhs.re - self.im * rhs.im,
93+ self.re * rhs.im + self.im * rhs.re,
94+ )
95+ }
96+}
97+
98+/// A complex FFT plan for one power-of-two size, in `f32` or `f64`.
99+///
100+/// Holds the twiddle table and the ping-pong scratch the Stockham passes need,
101+/// so a transform allocates nothing. Because the scratch lives in the plan the
102+/// transform methods take `&mut self`; share across threads by cloning.
103+///
104+/// ```
105+/// use ec_dsp::{Complex, Fft};
106+///
107+/// let mut fft = Fft::<f32>::new(8);
108+/// let mut data = [Complex::new(1.0, 0.0); 8];
109+/// fft.forward(&mut data);
110+/// // A constant signal has all its energy in bin 0.
111+/// assert!((data[0].re - 8.0).abs() < 1e-5);
112+/// assert!(data[1].norm_sqr() < 1e-10);
113+/// fft.inverse(&mut data);
114+/// assert!((data[3].re - 1.0).abs() < 1e-6);
115+/// ```
116+#[derive(Clone, Debug)]
117+pub struct Fft<T: Real> {
118+ n: usize,
119+ twiddle_re: Vec<T>,
120+ twiddle_im: Vec<T>,
121+ scratch_re: Vec<T>,
122+ scratch_im: Vec<T>,
123+ split_re: Vec<T>,
124+ split_im: Vec<T>,
125+}
126+
127+impl<T: Real> Fft<T> {
128+ /// A plan for `n` points.
129+ ///
130+ /// # Panics
131+ /// If `n` is not a power of two in `1..=`[`MAX_LEN`]. Sizes are a
132+ /// compile-time property of a codec, so a bad one is API misuse.
133+ pub fn new(n: usize) -> Fft<T> {
134+ assert!(
135+ n.is_power_of_two() && n <= MAX_LEN,
136+ "fft length must be a power of two up to {MAX_LEN}, got {n}"
137+ );
138+ let mut twiddle_re = Vec::with_capacity(n);
139+ let mut twiddle_im = Vec::with_capacity(n);
140+ for k in 0..n {
141+ // exp(-2*pi*i*k/n), always evaluated in f64 and rounded once.
142+ let angle = -2.0 * core::f64::consts::PI * k as f64 / n as f64;
143+ twiddle_re.push(T::from_f64(angle.cos()));
144+ twiddle_im.push(T::from_f64(angle.sin()));
145+ }
146+ Fft {
147+ n,
148+ twiddle_re,
149+ twiddle_im,
150+ scratch_re: vec![T::ZERO; n],
151+ scratch_im: vec![T::ZERO; n],
152+ split_re: vec![T::ZERO; n],
153+ split_im: vec![T::ZERO; n],
154+ }
155+ }
156+
157+ /// Points per transform.
158+ pub fn size(&self) -> usize {
159+ self.n
160+ }
161+
162+ /// Forward transform, `exp(-2*pi*i*k*n/N)`, in place.
163+ ///
164+ /// # Panics
165+ /// If `data.len() != self.size()`.
166+ pub fn forward(&mut self, data: &mut [Complex<T>]) {
167+ self.interleaved(data, false);
168+ }
169+
170+ /// Inverse transform **including** the `1/n` scaling, in place, so that
171+ /// `inverse(forward(x)) == x`.
172+ ///
173+ /// # Panics
174+ /// If `data.len() != self.size()`.
175+ pub fn inverse(&mut self, data: &mut [Complex<T>]) {
176+ self.interleaved(data, true);
177+ }
178+
179+ fn interleaved(&mut self, data: &mut [Complex<T>], inverse: bool) {
180+ assert_eq!(data.len(), self.n, "fft input length must equal plan size");
181+ for ((re, im), c) in self
182+ .split_re
183+ .iter_mut()
184+ .zip(self.split_im.iter_mut())
185+ .zip(data.iter())
186+ {
187+ *re = c.re;
188+ *im = c.im;
189+ }
190+ let (mut re, mut im) = (
191+ core::mem::take(&mut self.split_re),
192+ core::mem::take(&mut self.split_im),
193+ );
194+ if inverse {
195+ self.inverse_split(&mut re, &mut im);
196+ } else {
197+ self.forward_split(&mut re, &mut im);
198+ }
199+ for (c, (re, im)) in data.iter_mut().zip(re.iter().zip(im.iter())) {
200+ *c = Complex::new(*re, *im);
201+ }
202+ self.split_re = re;
203+ self.split_im = im;
204+ }
205+
206+ /// Forward transform of split-layout data, in place. The allocation-free
207+ /// entry point the other transforms in this crate use.
208+ ///
209+ /// # Panics
210+ /// If either slice length differs from [`Fft::size`].
211+ pub fn forward_split(&mut self, re: &mut [T], im: &mut [T]) {
212+ self.stockham(re, im);
213+ }
214+
215+ /// Inverse transform of split-layout data, in place, including `1/n`.
216+ ///
217+ /// Uses the identity `ifft(x) = swap(fft(swap(x)))/n`, where `swap`
218+ /// exchanges real and imaginary parts — one kernel serves both directions.
219+ ///
220+ /// # Panics
221+ /// If either slice length differs from [`Fft::size`].
222+ pub fn inverse_split(&mut self, re: &mut [T], im: &mut [T]) {
223+ self.stockham(im, re);
224+ let norm = T::ONE / T::from_f64(self.n as f64);
225+ crate::scale(re, norm);
226+ crate::scale(im, norm);
227+ }
228+
229+ fn stockham(&mut self, re: &mut [T], im: &mut [T]) {
230+ assert_eq!(re.len(), self.n, "fft input length must equal plan size");
231+ assert_eq!(im.len(), self.n, "fft input length must equal plan size");
232+ let Fft {
233+ n: total,
234+ twiddle_re,
235+ twiddle_im,
236+ scratch_re,
237+ scratch_im,
238+ ..
239+ } = self;
240+
241+ let mut xr: &mut [T] = re;
242+ let mut xi: &mut [T] = im;
243+ let mut yr: &mut [T] = scratch_re;
244+ let mut yi: &mut [T] = scratch_im;
245+
246+ // Invariant across the loop: n * stride == total, so the twiddle for
247+ // stage angle exp(-2*pi*i*p/n) is table entry p*stride.
248+ let mut n = *total;
249+ let mut stride = 1usize;
250+ let mut in_scratch = false;
251+ while n > 1 {
252+ if n % 4 == 0 {
253+ pass4(stride, xr, xi, yr, yi, twiddle_re, twiddle_im);
254+ n /= 4;
255+ stride *= 4;
256+ } else {
257+ pass2(stride, xr, xi, yr, yi, twiddle_re, twiddle_im);
258+ n /= 2;
259+ stride *= 2;
260+ }
261+ core::mem::swap(&mut xr, &mut yr);
262+ core::mem::swap(&mut xi, &mut yi);
263+ in_scratch = !in_scratch;
264+ }
265+ if in_scratch {
266+ // Odd number of passes: the result sits in the scratch (`x` now),
267+ // the caller's buffers are `y`.
268+ yr.copy_from_slice(xr);
269+ yi.copy_from_slice(xi);
270+ }
271+ }
272+}
273+
274+/// One radix-2 Stockham pass. `stride` is the run length; the input holds two
275+/// halves and the output two interleaved runs per block.
276+///
277+/// Every loop here walks `chunks_exact`, never an index: that is what makes
278+/// the bounds checks fold away, and it is worth 10x — measured against the
279+/// same code written with indices, which spent more instructions on checks
280+/// than on arithmetic.
281+#[inline]
282+fn pass2<T: Real>(
283+ stride: usize,
284+ xr: &[T],
285+ xi: &[T],
286+ yr: &mut [T],
287+ yi: &mut [T],
288+ twiddle_re: &[T],
289+ twiddle_im: &[T],
290+) {
291+ let half = xr.len() / 2;
292+ let (a_re, b_re) = xr.split_at(half);
293+ let (a_im, b_im) = xi.split_at(half);
294+ let lanes = T::LANES;
295+
296+ let blocks = a_re
297+ .chunks_exact(stride)
298+ .zip(a_im.chunks_exact(stride))
299+ .zip(b_re.chunks_exact(stride).zip(b_im.chunks_exact(stride)))
300+ .zip(
301+ yr.chunks_exact_mut(2 * stride)
302+ .zip(yi.chunks_exact_mut(2 * stride)),
303+ );
304+ for (p, (((ar, ai), (br, bi)), (out_re, out_im))) in blocks.enumerate() {
305+ let (wr, wi) = (twiddle_re[p * stride], twiddle_im[p * stride]);
306+ let (o0r, o1r) = out_re.split_at_mut(stride);
307+ let (o0i, o1i) = out_im.split_at_mut(stride);
308+ if stride >= lanes {
309+ let (wrv, wiv) = (wr.splat(), wi.splat());
310+ let ins = ar
311+ .chunks_exact(lanes)
312+ .zip(ai.chunks_exact(lanes))
313+ .zip(br.chunks_exact(lanes).zip(bi.chunks_exact(lanes)));
314+ let outs = o0r
315+ .chunks_exact_mut(lanes)
316+ .zip(o0i.chunks_exact_mut(lanes))
317+ .zip(o1r.chunks_exact_mut(lanes).zip(o1i.chunks_exact_mut(lanes)));
318+ for (input, output) in ins.zip(outs) {
319+ let ((a_lane_re, a_lane_im), (b_lane_re, b_lane_im)) = input;
320+ let ((y0r, y0i), (y1r, y1i)) = output;
321+ let (arv, aiv) = (T::load(a_lane_re), T::load(a_lane_im));
322+ let (brv, biv) = (T::load(b_lane_re), T::load(b_lane_im));
323+ T::store(arv + brv, y0r);
324+ T::store(aiv + biv, y0i);
325+ let (dr, di) = (arv - brv, aiv - biv);
326+ T::store(dr * wrv - di * wiv, y1r);
327+ T::store(dr * wiv + di * wrv, y1i);
328+ }
329+ } else {
330+ for q in 0..stride {
331+ let (arq, aiq) = (ar[q], ai[q]);
332+ let (brq, biq) = (br[q], bi[q]);
333+ o0r[q] = arq + brq;
334+ o0i[q] = aiq + biq;
335+ let (dr, di) = (arq - brq, aiq - biq);
336+ o1r[q] = dr * wr - di * wi;
337+ o1i[q] = dr * wi + di * wr;
338+ }
339+ }
340+ }
341+}
342+
343+/// One radix-4 Stockham pass — half the passes of radix-2 for the same size,
344+/// which is where most of the speed comes from. Same chunk discipline as
345+/// [`pass2`].
346+#[inline]
347+fn pass4<T: Real>(
348+ stride: usize,
349+ xr: &[T],
350+ xi: &[T],
351+ yr: &mut [T],
352+ yi: &mut [T],
353+ twiddle_re: &[T],
354+ twiddle_im: &[T],
355+) {
356+ let quarter = xr.len() / 4;
357+ let (a_re, rest) = xr.split_at(quarter);
358+ let (b_re, rest) = rest.split_at(quarter);
359+ let (c_re, d_re) = rest.split_at(quarter);
360+ let (a_im, rest) = xi.split_at(quarter);
361+ let (b_im, rest) = rest.split_at(quarter);
362+ let (c_im, d_im) = rest.split_at(quarter);
363+ let lanes = T::LANES;
364+
365+ let blocks = a_re
366+ .chunks_exact(stride)
367+ .zip(a_im.chunks_exact(stride))
368+ .zip(b_re.chunks_exact(stride).zip(b_im.chunks_exact(stride)))
369+ .zip(
370+ c_re.chunks_exact(stride)
371+ .zip(c_im.chunks_exact(stride))
372+ .zip(d_re.chunks_exact(stride).zip(d_im.chunks_exact(stride))),
373+ )
374+ .zip(
375+ yr.chunks_exact_mut(4 * stride)
376+ .zip(yi.chunks_exact_mut(4 * stride)),
377+ );
378+ for (p, ((((ar, ai), (br, bi)), ((cr, ci), (dr, di))), (out_re, out_im))) in blocks.enumerate()
379+ {
380+ let step = p * stride;
381+ let (w1r, w1i) = (twiddle_re[step], twiddle_im[step]);
382+ let (w2r, w2i) = (twiddle_re[2 * step], twiddle_im[2 * step]);
383+ let (w3r, w3i) = (twiddle_re[3 * step], twiddle_im[3 * step]);
384+ let mut runs_re = out_re.chunks_exact_mut(stride);
385+ let (o0r, o1r, o2r, o3r) = (
386+ runs_re.next().expect("four output runs"),
387+ runs_re.next().expect("four output runs"),
388+ runs_re.next().expect("four output runs"),
389+ runs_re.next().expect("four output runs"),
390+ );
391+ let mut runs_im = out_im.chunks_exact_mut(stride);
392+ let (o0i, o1i, o2i, o3i) = (
393+ runs_im.next().expect("four output runs"),
394+ runs_im.next().expect("four output runs"),
395+ runs_im.next().expect("four output runs"),
396+ runs_im.next().expect("four output runs"),
397+ );
398+ if stride >= lanes {
399+ let (w1rv, w1iv) = (w1r.splat(), w1i.splat());
400+ let (w2rv, w2iv) = (w2r.splat(), w2i.splat());
401+ let (w3rv, w3iv) = (w3r.splat(), w3i.splat());
402+ let ins = ar
403+ .chunks_exact(lanes)
404+ .zip(ai.chunks_exact(lanes))
405+ .zip(br.chunks_exact(lanes).zip(bi.chunks_exact(lanes)))
406+ .zip(
407+ cr.chunks_exact(lanes)
408+ .zip(ci.chunks_exact(lanes))
409+ .zip(dr.chunks_exact(lanes).zip(di.chunks_exact(lanes))),
410+ );
411+ let outs = o0r
412+ .chunks_exact_mut(lanes)
413+ .zip(o0i.chunks_exact_mut(lanes))
414+ .zip(o1r.chunks_exact_mut(lanes).zip(o1i.chunks_exact_mut(lanes)))
415+ .zip(
416+ o2r.chunks_exact_mut(lanes)
417+ .zip(o2i.chunks_exact_mut(lanes))
418+ .zip(o3r.chunks_exact_mut(lanes).zip(o3i.chunks_exact_mut(lanes))),
419+ );
420+ for (input, output) in ins.zip(outs) {
421+ let (((a_lr, a_li), (b_lr, b_li)), ((c_lr, c_li), (d_lr, d_li))) = input;
422+ let (((y0r, y0i), (y1r, y1i)), ((y2r, y2i), (y3r, y3i))) = output;
423+ let (arv, aiv) = (T::load(a_lr), T::load(a_li));
424+ let (brv, biv) = (T::load(b_lr), T::load(b_li));
425+ let (crv, civ) = (T::load(c_lr), T::load(c_li));
426+ let (drv, div) = (T::load(d_lr), T::load(d_li));
427+ let (apc_r, apc_i) = (arv + crv, aiv + civ);
428+ let (amc_r, amc_i) = (arv - crv, aiv - civ);
429+ let (bpd_r, bpd_i) = (brv + drv, biv + div);
430+ let (bmd_r, bmd_i) = (brv - drv, biv - div);
431+ // t0 = (a+c) + (b+d)
432+ T::store(apc_r + bpd_r, y0r);
433+ T::store(apc_i + bpd_i, y0i);
434+ // t1 = (a-c) - i(b-d), times w^p
435+ let (t1r, t1i) = (amc_r + bmd_i, amc_i - bmd_r);
436+ T::store(t1r * w1rv - t1i * w1iv, y1r);
437+ T::store(t1r * w1iv + t1i * w1rv, y1i);
438+ // t2 = (a+c) - (b+d), times w^2p
439+ let (t2r, t2i) = (apc_r - bpd_r, apc_i - bpd_i);
440+ T::store(t2r * w2rv - t2i * w2iv, y2r);
441+ T::store(t2r * w2iv + t2i * w2rv, y2i);
442+ // t3 = (a-c) + i(b-d), times w^3p
443+ let (t3r, t3i) = (amc_r - bmd_i, amc_i + bmd_r);
444+ T::store(t3r * w3rv - t3i * w3iv, y3r);
445+ T::store(t3r * w3iv + t3i * w3rv, y3i);
446+ }
447+ } else {
448+ for q in 0..stride {
449+ let (arq, aiq) = (ar[q], ai[q]);
450+ let (brq, biq) = (br[q], bi[q]);
451+ let (crq, ciq) = (cr[q], ci[q]);
452+ let (drq, diq) = (dr[q], di[q]);
453+ let (apc_r, apc_i) = (arq + crq, aiq + ciq);
454+ let (amc_r, amc_i) = (arq - crq, aiq - ciq);
455+ let (bpd_r, bpd_i) = (brq + drq, biq + diq);
456+ let (bmd_r, bmd_i) = (brq - drq, biq - diq);
457+ o0r[q] = apc_r + bpd_r;
458+ o0i[q] = apc_i + bpd_i;
459+ let (t1r, t1i) = (amc_r + bmd_i, amc_i - bmd_r);
460+ o1r[q] = t1r * w1r - t1i * w1i;
461+ o1i[q] = t1r * w1i + t1i * w1r;
462+ let (t2r, t2i) = (apc_r - bpd_r, apc_i - bpd_i);
463+ o2r[q] = t2r * w2r - t2i * w2i;
464+ o2i[q] = t2r * w2i + t2i * w2r;
465+ let (t3r, t3i) = (amc_r - bmd_i, amc_i + bmd_r);
466+ o3r[q] = t3r * w3r - t3i * w3i;
467+ o3i[q] = t3r * w3i + t3i * w3r;
468+ }
469+ }
470+ }
471+}
472+
473+/// Real-input FFT: an `n`-point real transform on an `n/2`-point complex one.
474+///
475+/// Half the work and half the memory of stuffing zeros into a complex FFT.
476+/// The spectrum is the `n/2 + 1` non-redundant bins; bins `0` and `n/2` are
477+/// real, and the caller gets the conjugate half back for free by symmetry.
478+///
479+/// ```
480+/// use ec_dsp::RealFft;
481+///
482+/// let mut rfft = RealFft::<f64>::new(16);
483+/// let signal: Vec<f64> = (0..16).map(|n| (n as f64).sin()).collect();
484+/// let mut spectrum = vec![Default::default(); 9];
485+/// rfft.forward(&signal, &mut spectrum);
486+/// let mut back = vec![0.0; 16];
487+/// rfft.inverse(&spectrum, &mut back);
488+/// assert!(back.iter().zip(&signal).all(|(a, b)| (a - b).abs() < 1e-12));
489+/// ```
490+#[derive(Clone, Debug)]
491+pub struct RealFft<T: Real> {
492+ n: usize,
493+ half: Fft<T>,
494+ twiddle_re: Vec<T>,
495+ twiddle_im: Vec<T>,
496+ buf_re: Vec<T>,
497+ buf_im: Vec<T>,
498+}
499+
500+impl<T: Real> RealFft<T> {
501+ /// A plan for `n` real points.
502+ ///
503+ /// # Panics
504+ /// If `n` is not a power of two of at least 4, or exceeds [`MAX_LEN`].
505+ pub fn new(n: usize) -> RealFft<T> {
506+ assert!(
507+ n.is_power_of_two() && (4..=MAX_LEN).contains(&n),
508+ "real fft length must be a power of two in 4..={MAX_LEN}, got {n}"
509+ );
510+ let half = n / 2;
511+ let mut twiddle_re = Vec::with_capacity(half + 1);
512+ let mut twiddle_im = Vec::with_capacity(half + 1);
513+ for k in 0..=half {
514+ let angle = -2.0 * core::f64::consts::PI * k as f64 / n as f64;
515+ twiddle_re.push(T::from_f64(angle.cos()));
516+ twiddle_im.push(T::from_f64(angle.sin()));
517+ }
518+ RealFft {
519+ n,
520+ half: Fft::new(half),
521+ twiddle_re,
522+ twiddle_im,
523+ buf_re: vec![T::ZERO; half],
524+ buf_im: vec![T::ZERO; half],
525+ }
526+ }
527+
528+ /// Points per transform (the real-domain length).
529+ pub fn size(&self) -> usize {
530+ self.n
531+ }
532+
533+ /// Bins in the spectrum, `size()/2 + 1`.
534+ pub fn spectrum_len(&self) -> usize {
535+ self.n / 2 + 1
536+ }
537+
538+ /// Transforms `input` into `spectrum`.
539+ ///
540+ /// # Panics
541+ /// If `input.len() != size()` or `spectrum.len() != spectrum_len()`.
542+ pub fn forward(&mut self, input: &[T], spectrum: &mut [Complex<T>]) {
543+ assert_eq!(input.len(), self.n, "real fft input length must equal size");
544+ assert_eq!(
545+ spectrum.len(),
546+ self.spectrum_len(),
547+ "spectrum length must be size()/2 + 1"
548+ );
549+ let m = self.n / 2;
550+ for j in 0..m {
551+ self.buf_re[j] = input[2 * j];
552+ self.buf_im[j] = input[2 * j + 1];
553+ }
554+ self.half.forward_split(&mut self.buf_re, &mut self.buf_im);
555+
556+ let half_scale = T::from_f64(0.5);
557+ for (k, bin) in spectrum.iter_mut().enumerate() {
558+ let z = Complex::new(self.buf_re[k % m], self.buf_im[k % m]);
559+ let zc = Complex::new(self.buf_re[(m - k) % m], self.buf_im[(m - k) % m]).conj();
560+ let even = (z + zc).scale(half_scale);
561+ let odd = (z - zc).scale(half_scale);
562+ let tw = Complex::new(self.twiddle_re[k], self.twiddle_im[k]);
563+ *bin = even + (tw * odd).mul_neg_i();
564+ }
565+ }
566+
567+ /// Reconstructs `output` from `spectrum`, scaled so that
568+ /// `inverse(forward(x)) == x`.
569+ ///
570+ /// # Panics
571+ /// If `output.len() != size()` or `spectrum.len() != spectrum_len()`.
572+ pub fn inverse(&mut self, spectrum: &[Complex<T>], output: &mut [T]) {
573+ assert_eq!(
574+ output.len(),
575+ self.n,
576+ "real fft output length must equal size"
577+ );
578+ assert_eq!(
579+ spectrum.len(),
580+ self.spectrum_len(),
581+ "spectrum length must be size()/2 + 1"
582+ );
583+ let m = self.n / 2;
584+ let half_scale = T::from_f64(0.5);
585+ for k in 0..m {
586+ let a = spectrum[k];
587+ let b = spectrum[m - k].conj();
588+ let even = (a + b).scale(half_scale);
589+ let odd = (a - b).scale(half_scale);
590+ // Conjugate twiddle, and +i instead of -i: the forward step run backwards.
591+ let tw = Complex::new(self.twiddle_re[k], self.twiddle_im[k]).conj();
592+ let z = even - (tw * odd).mul_neg_i();
593+ self.buf_re[k] = z.re;
594+ self.buf_im[k] = z.im;
595+ }
596+ self.half.inverse_split(&mut self.buf_re, &mut self.buf_im);
597+ for j in 0..m {
598+ output[2 * j] = self.buf_re[j];
599+ output[2 * j + 1] = self.buf_im[j];
600+ }
601+ }
602+}
603+
604+#[cfg(test)]
605+mod tests {
606+ use super::*;
607+ use crate::tests::{noise, rel_error};
608+
609+ /// O(n^2) DFT in `f64` — the reference the fast path is judged against.
610+ /// Test-only by construction: nothing outside `#[cfg(test)]` can call it,
611+ /// which is the family rule about naive transforms in shipping paths.
612+ fn reference_dft(input: &[Complex<f64>], inverse: bool) -> Vec<Complex<f64>> {
613+ let n = input.len();
614+ let sign = if inverse { 1.0 } else { -1.0 };
615+ (0..n)
616+ .map(|k| {
617+ let mut acc = Complex::new(0.0, 0.0);
618+ for (j, x) in input.iter().enumerate() {
619+ let angle = sign * 2.0 * core::f64::consts::PI * (j * k % n) as f64 / n as f64;
620+ acc = acc + *x * Complex::new(angle.cos(), angle.sin());
621+ }
622+ acc
623+ })
624+ .collect()
625+ }
626+
627+ fn complex_noise(n: usize, seed: u64) -> Vec<Complex<f64>> {
628+ let re: Vec<f64> = noise(n, seed);
629+ let im: Vec<f64> = noise(n, seed ^ 0x9e37_79b9);
630+ re.iter()
631+ .zip(&im)
632+ .map(|(r, i)| Complex::new(*r, *i))
633+ .collect()
634+ }
635+
636+ #[test]
637+ fn agrees_with_reference_dft_f64() {
638+ let mut worst = 0.0f64;
639+ let mut size = 0;
640+ for shift in 3..=13 {
641+ let n = 1usize << shift;
642+ let input = complex_noise(n, 0x1234 + n as u64);
643+ let want = reference_dft(&input, false);
644+ let mut got = input.clone();
645+ Fft::new(n).forward(&mut got);
646+ let error = complex_error(&got, &want);
647+ if error > worst {
648+ worst = error;
649+ size = n;
650+ }
651+ assert!(error < 1e-12, "n = {n}: f64 error {error:e}");
652+ }
653+ println!("f64 FFT vs reference DFT: worst rel error {worst:e} (n = {size})");
654+ }
655+
656+ #[test]
657+ fn agrees_with_reference_dft_f32() {
658+ let mut worst = 0.0f64;
659+ let mut size = 0;
660+ for shift in 3..=13 {
661+ let n = 1usize << shift;
662+ let input = complex_noise(n, 0x5678 + n as u64);
663+ let want = reference_dft(&input, false);
664+ let mut got: Vec<Complex<f32>> = input
665+ .iter()
666+ .map(|c| Complex::new(c.re as f32, c.im as f32))
667+ .collect();
668+ Fft::new(n).forward(&mut got);
669+ let widened: Vec<Complex<f64>> = got
670+ .iter()
671+ .map(|c| Complex::new(c.re as f64, c.im as f64))
672+ .collect();
673+ let error = complex_error(&widened, &want);
674+ if error > worst {
675+ worst = error;
676+ size = n;
677+ }
678+ assert!(error < 1e-5, "n = {n}: f32 error {error:e}");
679+ }
680+ println!("f32 FFT vs reference DFT: worst rel error {worst:e} (n = {size})");
681+ }
682+
683+ #[test]
684+ fn inverse_reference_matches_plan() {
685+ let n = 64;
686+ let input = complex_noise(n, 99);
687+ let want = reference_dft(&input, true);
688+ let mut got = input.clone();
689+ let mut fft = Fft::new(n);
690+ fft.inverse(&mut got);
691+ // The plan normalises by n; the reference does not.
692+ let scaled: Vec<Complex<f64>> = want.iter().map(|c| c.scale(1.0 / n as f64)).collect();
693+ assert!(complex_error(&got, &scaled) < 1e-12);
694+ }
695+
696+ #[test]
697+ fn round_trips_f32_every_size() {
698+ let mut worst = 0.0f64;
699+ let mut size = 0;
700+ for shift in 3..=15 {
701+ let n = 1usize << shift;
702+ let input: Vec<f32> = noise(n, 0xabc + n as u64);
703+ let mut data: Vec<Complex<f32>> = input.iter().map(|v| Complex::new(*v, 0.0)).collect();
704+ let mut fft = Fft::new(n);
705+ fft.forward(&mut data);
706+ fft.inverse(&mut data);
707+ let got: Vec<f32> = data.iter().map(|c| c.re).collect();
708+ let error = rel_error(&got, &input);
709+ if error > worst {
710+ worst = error;
711+ size = n;
712+ }
713+ assert!(error < 1e-6, "n = {n}: round-trip error {error:e}");
714+ }
715+ println!("f32 FFT round trip: worst rel error {worst:e} (n = {size})");
716+ }
717+
718+ #[test]
719+ fn split_and_interleaved_agree() {
720+ let n = 256;
721+ let input = complex_noise(n, 4242);
722+ let mut fft = Fft::new(n);
723+ let mut interleaved = input.clone();
724+ fft.forward(&mut interleaved);
725+ let mut re: Vec<f64> = input.iter().map(|c| c.re).collect();
726+ let mut im: Vec<f64> = input.iter().map(|c| c.im).collect();
727+ fft.forward_split(&mut re, &mut im);
728+ for (k, c) in interleaved.iter().enumerate() {
729+ assert!((c.re - re[k]).abs() < 1e-12 && (c.im - im[k]).abs() < 1e-12);
730+ }
731+ }
732+
733+ #[test]
734+ fn real_fft_matches_complex_fft() {
735+ for shift in 2..=12 {
736+ let n = 1usize << shift;
737+ let signal: Vec<f64> = noise(n, 0xfeed + n as u64);
738+ let mut rfft = RealFft::new(n);
739+ let mut spectrum = vec![Complex::new(0.0, 0.0); n / 2 + 1];
740+ rfft.forward(&signal, &mut spectrum);
741+
742+ let mut want: Vec<Complex<f64>> =
743+ signal.iter().map(|v| Complex::new(*v, 0.0)).collect();
744+ Fft::new(n).forward(&mut want);
745+ for k in 0..=n / 2 {
746+ assert!(
747+ (spectrum[k].re - want[k].re).abs() < 1e-10
748+ && (spectrum[k].im - want[k].im).abs() < 1e-10,
749+ "n = {n}, bin {k}: {:?} vs {:?}",
750+ spectrum[k],
751+ want[k]
752+ );
753+ }
754+
755+ let mut back = vec![0.0; n];
756+ rfft.inverse(&spectrum, &mut back);
757+ assert!(rel_error(&back, &signal) < 1e-12, "n = {n} real round trip");
758+ }
759+ }
760+
761+ #[test]
762+ #[should_panic(expected = "power of two")]
763+ fn rejects_non_power_of_two() {
764+ let _ = Fft::<f32>::new(48);
765+ }
766+
767+ fn complex_error(got: &[Complex<f64>], want: &[Complex<f64>]) -> f64 {
768+ let mut num = 0.0;
769+ let mut den = 0.0;
770+ for (g, w) in got.iter().zip(want) {
771+ num += (*g - *w).norm_sqr();
772+ den += w.norm_sqr();
773+ }
774+ (num / den).sqrt()
775+ }
776+}
crates/ec-dsp/src/lib.rsadded+321 -0
@@ -0,0 +1,321 @@
1+//! The one set of transforms every edith_codecs audio and video coder uses.
2+//!
3+//! AAC, Vorbis, Opus/CELT, MP3 and the JPEG-class video paths all reduce to the
4+//! same three kernels, so they live here once: a power-of-two complex [`Fft`]
5+//! (with a real-input wrapper), the DCT family built on top of it, and
6+//! [`Mdct`] — the lapped transform those codecs actually call — routed through
7+//! an `N/4`-point FFT.
8+//!
9+//! Contracts worth knowing before implementing against this crate:
10+//!
11+//! - **The FFT is never optional.** There is no feature flag, no fallback, no
12+//! `O(n²)` path anywhere: a codec that links this crate gets the fast
13+//! transform or does not compile. Two incumbent crates shipped an `O(n²)`
14+//! transform behind a default-off feature and ran 40x slower than the
15+//! product needed; that failure mode is designed out rather than tested for.
16+//! - **Plans own their scratch.** [`Fft`], [`Dct`], [`Dct4`] and [`Mdct`] are
17+//! built once per size and then reused; the transform methods take `&mut
18+//! self` and allocate nothing. Clone a plan to use it from another thread.
19+//! - **Sizes are checked at construction, not per call.** A bad size is API
20+//! misuse and panics in the constructor; the hot path has no error branch.
21+//! - **`f32` and `f64` are the same code.** Twiddles are always computed in
22+//! `f64` and rounded once, so the `f32` plans keep the accuracy their table
23+//! allows.
24+//! - **Inverses are scaled.** [`Fft::inverse`] divides by `n`, so a forward
25+//! followed by an inverse returns the input. [`Mdct`] follows the usual
26+//! codec convention (`2/N` on the inverse) and reconstructs exactly under
27+//! overlap-add with any Princen-Bradley window from [`window`].
28+//!
29+//! Hot loops are vectorised with the `wide` crate through [`Real`]; the scalar
30+//! and SIMD paths are the same expressions over the same data layout, so
31+//! neither can drift from the other in correctness.
32+//!
33+//! No unsafe, no allocation on the transform path, no other dependencies.
34+
35+#![forbid(unsafe_code)]
36+#![warn(missing_docs)]
37+
38+pub mod dct;
39+pub mod fft;
40+pub mod mdct;
41+pub mod window;
42+
43+pub use dct::{Dct, Dct4};
44+pub use fft::{Complex, Fft, RealFft};
45+pub use mdct::Mdct;
46+pub use window::Window;
47+
48+use core::fmt::Debug;
49+use core::ops::{Add, Div, Mul, Neg, Sub};
50+
51+/// The sample types the transforms are generic over: `f32` and `f64`.
52+///
53+/// The trait exists to give one implementation of each transform for both
54+/// precisions *including* its SIMD form: [`Real::Lanes`] is the widest `wide`
55+/// vector for the type, and the kernels fall back to scalar code on the
56+/// remainder of a row. Implementing it for anything else is not supported —
57+/// the transforms assume IEEE-754 binary arithmetic.
58+pub trait Real:
59+ Copy
60+ + Debug
61+ + Default
62+ + PartialOrd
63+ + Add<Output = Self>
64+ + Sub<Output = Self>
65+ + Mul<Output = Self>
66+ + Div<Output = Self>
67+ + Neg<Output = Self>
68+ + Send
69+ + Sync
70+ + 'static
71+{
72+ /// A vector of [`Real::LANES`] values, backed by `wide`.
73+ type Lanes: Copy
74+ + Add<Output = Self::Lanes>
75+ + Sub<Output = Self::Lanes>
76+ + Mul<Output = Self::Lanes>;
77+
78+ /// Values per [`Real::Lanes`] vector (8 for `f32`, 4 for `f64`).
79+ const LANES: usize;
80+ /// Additive identity.
81+ const ZERO: Self;
82+ /// Multiplicative identity.
83+ const ONE: Self;
84+
85+ /// Rounds an `f64` — how every table entry in this crate is produced.
86+ fn from_f64(v: f64) -> Self;
87+ /// Widens to `f64`, for reference computations and reporting.
88+ fn to_f64(self) -> f64;
89+ /// Square root.
90+ fn sqrt(self) -> Self;
91+ /// Absolute value.
92+ fn abs(self) -> Self;
93+ /// Broadcasts one value across a vector.
94+ fn splat(self) -> Self::Lanes;
95+ /// Loads exactly [`Real::LANES`] values. Panics if `src` is another
96+ /// length — callers feed it `chunks_exact(LANES)`, which is what lets the
97+ /// bounds check fold away in the transform inner loops.
98+ fn load(src: &[Self]) -> Self::Lanes;
99+ /// Stores exactly [`Real::LANES`] values. Panics if `dst` is another length.
100+ fn store(v: Self::Lanes, dst: &mut [Self]);
101+}
102+
103+impl Real for f32 {
104+ type Lanes = wide::f32x8;
105+
106+ const LANES: usize = 8;
107+ const ZERO: f32 = 0.0;
108+ const ONE: f32 = 1.0;
109+
110+ #[inline]
111+ fn from_f64(v: f64) -> f32 {
112+ v as f32
113+ }
114+ #[inline]
115+ fn to_f64(self) -> f64 {
116+ self as f64
117+ }
118+ #[inline]
119+ fn sqrt(self) -> f32 {
120+ f32::sqrt(self)
121+ }
122+ #[inline]
123+ fn abs(self) -> f32 {
124+ f32::abs(self)
125+ }
126+ #[inline]
127+ fn splat(self) -> wide::f32x8 {
128+ wide::f32x8::splat(self)
129+ }
130+ #[inline]
131+ fn load(src: &[f32]) -> wide::f32x8 {
132+ let chunk: [f32; 8] = src.try_into().expect("load needs exactly 8 values");
133+ wide::bytemuck::cast(chunk)
134+ }
135+ #[inline]
136+ fn store(v: wide::f32x8, dst: &mut [f32]) {
137+ dst.copy_from_slice(&v.to_array());
138+ }
139+}
140+
141+impl Real for f64 {
142+ type Lanes = wide::f64x4;
143+
144+ const LANES: usize = 4;
145+ const ZERO: f64 = 0.0;
146+ const ONE: f64 = 1.0;
147+
148+ #[inline]
149+ fn from_f64(v: f64) -> f64 {
150+ v
151+ }
152+ #[inline]
153+ fn to_f64(self) -> f64 {
154+ self
155+ }
156+ #[inline]
157+ fn sqrt(self) -> f64 {
158+ f64::sqrt(self)
159+ }
160+ #[inline]
161+ fn abs(self) -> f64 {
162+ f64::abs(self)
163+ }
164+ #[inline]
165+ fn splat(self) -> wide::f64x4 {
166+ wide::f64x4::splat(self)
167+ }
168+ #[inline]
169+ fn load(src: &[f64]) -> wide::f64x4 {
170+ let chunk: [f64; 4] = src.try_into().expect("load needs exactly 4 values");
171+ wide::bytemuck::cast(chunk)
172+ }
173+ #[inline]
174+ fn store(v: wide::f64x4, dst: &mut [f64]) {
175+ dst.copy_from_slice(&v.to_array());
176+ }
177+}
178+
179+/// Multiplies `data` by `factor` in place, vectorised.
180+pub(crate) fn scale<T: Real>(data: &mut [T], factor: T) {
181+ let fv = factor.splat();
182+ let mut chunks = data.chunks_exact_mut(T::LANES);
183+ for chunk in &mut chunks {
184+ T::store(T::load(chunk) * fv, chunk);
185+ }
186+ for v in chunks.into_remainder() {
187+ *v = *v * factor;
188+ }
189+}
190+
191+#[cfg(test)]
192+mod tests {
193+ use super::*;
194+
195+ /// Deterministic test signal — no `rand` dependency in a DSP crate.
196+ pub(crate) fn noise<T: Real>(n: usize, seed: u64) -> Vec<T> {
197+ let mut state = seed | 1;
198+ (0..n)
199+ .map(|_| {
200+ state ^= state << 13;
201+ state ^= state >> 7;
202+ state ^= state << 17;
203+ let unit = (state >> 11) as f64 / (1u64 << 53) as f64;
204+ T::from_f64(unit * 2.0 - 1.0)
205+ })
206+ .collect()
207+ }
208+
209+ /// Relative L2 error of `got` against `want`, both read as `f64`.
210+ pub(crate) fn rel_error<T: Real>(got: &[T], want: &[T]) -> f64 {
211+ let mut num = 0.0;
212+ let mut den = 0.0;
213+ for (g, w) in got.iter().zip(want) {
214+ let d = g.to_f64() - w.to_f64();
215+ num += d * d;
216+ den += w.to_f64() * w.to_f64();
217+ }
218+ (num / den.max(f64::MIN_POSITIVE)).sqrt()
219+ }
220+
221+ /// Throughput, printed rather than asserted: the numbers are machine
222+ /// specific, but a regression of the *order of magnitude* is what the
223+ /// family cares about (an incumbent shipped an O(n^2) transform and lost
224+ /// 40x). Run with:
225+ ///
226+ /// `cargo test -p ec-dsp --release -- --ignored --nocapture throughput`
227+ #[test]
228+ #[ignore = "timing; run in release with --ignored --nocapture"]
229+ fn throughput() {
230+ use crate::{Complex, Fft, Mdct, RealFft, Window};
231+ use std::time::Instant;
232+
233+ let n = 2048;
234+ let signal: Vec<f32> = noise(n, 0xdeadbeef);
235+ let mut guard = 0.0f32;
236+
237+ let mut fft = Fft::<f32>::new(n);
238+ let mut data: Vec<Complex<f32>> = signal.iter().map(|v| Complex::new(*v, 0.0)).collect();
239+ let iters = 50_000;
240+ // Alternating directions keeps the in-place data bounded, so the
241+ // numbers are not measured on infinities; the inverse costs one extra
242+ // scaling pass, which makes this average slightly pessimistic.
243+ let t0 = Instant::now();
244+ for i in 0..iters {
245+ if i % 2 == 0 {
246+ fft.forward(&mut data);
247+ } else {
248+ fft.inverse(&mut data);
249+ }
250+ }
251+ report("complex FFT f32 2048 fwd/inv", t0.elapsed(), iters, n);
252+ guard += data[0].re;
253+
254+ let mut re: Vec<f32> = signal.clone();
255+ let mut im: Vec<f32> = vec![0.0; n];
256+ let t0 = Instant::now();
257+ for i in 0..iters {
258+ if i % 2 == 0 {
259+ fft.forward_split(&mut re, &mut im);
260+ } else {
261+ fft.inverse_split(&mut re, &mut im);
262+ }
263+ }
264+ report("split FFT f32 2048 fwd/inv", t0.elapsed(), iters, n);
265+ guard += re[0];
266+
267+ let mut rfft = RealFft::<f32>::new(n);
268+ let mut spectrum = vec![Complex::new(0.0f32, 0.0); n / 2 + 1];
269+ let t0 = Instant::now();
270+ for _ in 0..iters {
271+ rfft.forward(&signal, &mut spectrum);
272+ }
273+ report("real FFT f32 2048 fwd", t0.elapsed(), iters, n);
274+ guard += spectrum[0].re;
275+
276+ let mut mdct = Mdct::<f32>::new(n);
277+ let window = Window::<f32>::kbd(n, 4.0);
278+ let mut coeffs = vec![0.0f32; n / 2];
279+ let t0 = Instant::now();
280+ for _ in 0..iters {
281+ mdct.forward_windowed(&signal, window.as_slice(), &mut coeffs);
282+ }
283+ report("MDCT f32 2048 fwd (windowed)", t0.elapsed(), iters, n);
284+ guard += coeffs[0];
285+
286+ let mut frame = vec![0.0f32; n];
287+ let t0 = Instant::now();
288+ for _ in 0..iters {
289+ mdct.inverse_windowed(&coeffs, window.as_slice(), &mut frame);
290+ }
291+ report("IMDCT f32 2048 inv (windowed)", t0.elapsed(), iters, n);
292+ guard += frame[0];
293+
294+ // 48 kHz stereo AAC: 2 channels * 46.875 long blocks per second.
295+ let per_block = t0.elapsed().as_secs_f64() / iters as f64;
296+ println!("guard {guard:e}");
297+ println!(
298+ "one 2048 IMDCT = {:.2} us; a 5.1 48 kHz stream needs 6*46.9 = 281 per second",
299+ per_block * 1e6
300+ );
301+ }
302+
303+ fn report(label: &str, elapsed: std::time::Duration, iters: u32, n: usize) {
304+ let per = elapsed.as_secs_f64() / iters as f64;
305+ println!(
306+ "{label:<32} {:>8.0} ns/transform {:>7.1} Mpoint/s",
307+ per * 1e9,
308+ n as f64 / per / 1e6
309+ );
310+ }
311+
312+ #[test]
313+ fn scale_matches_scalar_across_the_lane_boundary() {
314+ for n in [1usize, 3, 8, 9, 17, 64] {
315+ let mut data: Vec<f32> = noise(n, 7);
316+ let want: Vec<f32> = data.iter().map(|v| v * 0.25).collect();
317+ scale(&mut data, 0.25);
318+ assert_eq!(data, want, "n = {n}");
319+ }
320+ }
321+}
crates/ec-dsp/src/mdct.rsadded+338 -0
@@ -0,0 +1,338 @@
1+//! MDCT and IMDCT — the lapped transform AAC, Vorbis, MP3 and CELT code with.
2+//!
3+//! Definition, for a window of `2N` samples producing `N` coefficients:
4+//!
5+//! ```text
6+//! X[k] = sum_{n=0}^{2N-1} x[n] cos(pi/N (n + 1/2 + N/2)(k + 1/2))
7+//! y[n] = (2/N) sum_{k=0}^{N-1} X[k] cos(pi/N (n + 1/2 + N/2)(k + 1/2))
8+//! ```
9+//!
10+//! The `2/N` on the inverse is the codec convention: with any
11+//! Princen-Bradley window from [`crate::window`], applied on both analysis and
12+//! synthesis, 50 %-overlapped frames add up to the original signal exactly
13+//! (TDAC). [`Mdct::perfect_reconstruction_error`] is that claim as a
14+//! runnable check.
15+//!
16+//! Implementation is the standard fold-then-DCT-IV: the `2N` window folds to
17+//! `N` points by the transform's own symmetries, and the DCT-IV runs on an
18+//! `N/2`-point complex FFT. So an AAC long block (2048 samples, 1024
19+//! coefficients) costs one 512-point FFT — not a 2048x1024 matrix product.
20+
21+use crate::Real;
22+use crate::dct::Dct4;
23+
24+/// An MDCT/IMDCT plan for one window size.
25+///
26+/// ```
27+/// use ec_dsp::{Mdct, Window};
28+///
29+/// // AAC long block.
30+/// let mut mdct = Mdct::<f32>::new(2048);
31+/// assert_eq!(mdct.spectrum_len(), 1024);
32+/// let window = Window::<f32>::sine(2048);
33+/// let error = mdct.perfect_reconstruction_error(&window, 0x51de);
34+/// assert!(error < 1e-6, "TDAC error {error}");
35+/// ```
36+#[derive(Clone, Debug)]
37+pub struct Mdct<T: Real> {
38+ half: usize,
39+ dct: Dct4<T>,
40+ fold: Vec<T>,
41+}
42+
43+impl<T: Real> Mdct<T> {
44+ /// A plan for a window of `window_len` samples, producing `window_len/2`
45+ /// coefficients. AAC uses 2048 and 256; Vorbis and CELT sizes are the same
46+ /// shape.
47+ ///
48+ /// # Panics
49+ /// If `window_len` is not a power of two of at least 4.
50+ pub fn new(window_len: usize) -> Mdct<T> {
51+ assert!(
52+ window_len.is_power_of_two() && window_len >= 4,
53+ "mdct window must be a power of two of at least 4, got {window_len}"
54+ );
55+ let half = window_len / 2;
56+ Mdct {
57+ half,
58+ dct: Dct4::new(half),
59+ fold: vec![T::ZERO; half],
60+ }
61+ }
62+
63+ /// Samples per window (`2N`).
64+ pub fn window_len(&self) -> usize {
65+ self.half * 2
66+ }
67+
68+ /// Coefficients per window (`N`).
69+ pub fn spectrum_len(&self) -> usize {
70+ self.half
71+ }
72+
73+ /// Transforms one window of samples into coefficients.
74+ ///
75+ /// # Panics
76+ /// If `input.len() != window_len()` or `output.len() != spectrum_len()`.
77+ pub fn forward(&mut self, input: &[T], output: &mut [T]) {
78+ self.fold_input(input, None);
79+ output.copy_from_slice(&self.fold);
80+ self.dct.transform(output);
81+ }
82+
83+ /// [`Mdct::forward`] with the analysis window applied in the same pass —
84+ /// the fold reads each sample once, so windowing here costs one multiply
85+ /// and no extra buffer.
86+ ///
87+ /// # Panics
88+ /// If any length is wrong, including `window.len() != window_len()`.
89+ pub fn forward_windowed(&mut self, input: &[T], window: &[T], output: &mut [T]) {
90+ assert_eq!(
91+ window.len(),
92+ self.window_len(),
93+ "window length must equal the mdct window"
94+ );
95+ self.fold_input(input, Some(window));
96+ output.copy_from_slice(&self.fold);
97+ self.dct.transform(output);
98+ }
99+
100+ /// Transforms coefficients back into one window of samples, ready for
101+ /// overlap-add. Includes the `2/N` scaling.
102+ ///
103+ /// # Panics
104+ /// If `spectrum.len() != spectrum_len()` or `output.len() != window_len()`.
105+ pub fn inverse(&mut self, spectrum: &[T], output: &mut [T]) {
106+ self.unfold(spectrum, output, None);
107+ }
108+
109+ /// [`Mdct::inverse`] with the synthesis window applied as the samples are
110+ /// written out.
111+ ///
112+ /// # Panics
113+ /// If any length is wrong, including `window.len() != window_len()`.
114+ pub fn inverse_windowed(&mut self, spectrum: &[T], window: &[T], output: &mut [T]) {
115+ assert_eq!(
116+ window.len(),
117+ self.window_len(),
118+ "window length must equal the mdct window"
119+ );
120+ self.unfold(spectrum, output, Some(window));
121+ }
122+
123+ /// Folds `2N` samples down to the `N` points DCT-IV acts on, optionally
124+ /// windowing on the way in.
125+ fn fold_input(&mut self, input: &[T], window: Option<&[T]>) {
126+ assert_eq!(
127+ input.len(),
128+ self.window_len(),
129+ "mdct input must be one full window"
130+ );
131+ let n = self.half;
132+ let quarter = n / 2;
133+ let at = |i: usize| match window {
134+ Some(w) => input[i] * w[i],
135+ None => input[i],
136+ };
137+ for i in 0..quarter {
138+ // First half: -c reversed - d. Second half: a - b reversed.
139+ self.fold[i] = -at(3 * quarter - 1 - i) - at(3 * quarter + i);
140+ self.fold[quarter + i] = at(i) - at(n - 1 - i);
141+ }
142+ }
143+
144+ /// Runs DCT-IV and unfolds back to `2N` samples with the transform's
145+ /// symmetries, optionally windowing on the way out.
146+ fn unfold(&mut self, spectrum: &[T], output: &mut [T], window: Option<&[T]>) {
147+ assert_eq!(
148+ spectrum.len(),
149+ self.half,
150+ "mdct spectrum must be one full block"
151+ );
152+ assert_eq!(
153+ output.len(),
154+ self.window_len(),
155+ "mdct output must be one full window"
156+ );
157+ let n = self.half;
158+ let quarter = n / 2;
159+ self.fold.copy_from_slice(spectrum);
160+ self.dct.transform(&mut self.fold);
161+ let gain = T::from_f64(2.0 / n as f64);
162+ let mut put = |i: usize, v: T| {
163+ output[i] = match window {
164+ Some(w) => v * gain * w[i],
165+ None => v * gain,
166+ };
167+ };
168+ for i in 0..quarter {
169+ put(i, self.fold[quarter + i]);
170+ put(quarter + i, -self.fold[n - 1 - i]);
171+ put(n + i, -self.fold[quarter - 1 - i]);
172+ put(n + quarter + i, -self.fold[i]);
173+ }
174+ }
175+
176+ /// Runs three overlapped frames of pseudo-random audio through
177+ /// analysis and synthesis with `window` and returns the worst absolute
178+ /// reconstruction error in the fully overlapped region.
179+ ///
180+ /// This is the property a codec actually depends on — the transform pair
181+ /// and the window are only correct *together* — so it is exposed rather
182+ /// than hidden in a test: a codec's own suite can assert it for whatever
183+ /// window it ships.
184+ ///
185+ /// # Panics
186+ /// If `window.len() != window_len()`.
187+ pub fn perfect_reconstruction_error(&mut self, window: &crate::Window<T>, seed: u64) -> f64 {
188+ let n = self.half;
189+ let win = window.as_slice();
190+ assert_eq!(win.len(), 2 * n, "window length must equal the mdct window");
191+
192+ // 4 hops of N samples; frames 0..2 cover [0, 4N) with 50 % overlap.
193+ let mut state = seed | 1;
194+ let signal: Vec<T> = (0..4 * n)
195+ .map(|_| {
196+ state ^= state << 13;
197+ state ^= state >> 7;
198+ state ^= state << 17;
199+ T::from_f64((state >> 11) as f64 / (1u64 << 53) as f64 * 2.0 - 1.0)
200+ })
201+ .collect();
202+
203+ let mut sum = vec![T::ZERO; 4 * n];
204+ let mut spectrum = vec![T::ZERO; n];
205+ let mut frame = vec![T::ZERO; 2 * n];
206+ for f in 0..3 {
207+ let start = f * n;
208+ self.forward_windowed(&signal[start..start + 2 * n], win, &mut spectrum);
209+ self.inverse_windowed(&spectrum, win, &mut frame);
210+ for (i, v) in frame.iter().enumerate() {
211+ sum[start + i] = sum[start + i] + *v;
212+ }
213+ }
214+ // Only [N, 3N) sees both of its overlapping frames.
215+ (n..3 * n)
216+ .map(|i| (sum[i].to_f64() - signal[i].to_f64()).abs())
217+ .fold(0.0, f64::max)
218+ }
219+}
220+
221+#[cfg(test)]
222+mod tests {
223+ use super::*;
224+ use crate::Window;
225+ use crate::tests::{noise, rel_error};
226+ use core::f64::consts::PI;
227+
228+ /// O(n^2) reference MDCT, test-only.
229+ fn reference_mdct(x: &[f64]) -> Vec<f64> {
230+ let n = x.len() / 2;
231+ (0..n)
232+ .map(|k| {
233+ (0..2 * n)
234+ .map(|j| {
235+ x[j] * (PI / n as f64
236+ * (j as f64 + 0.5 + n as f64 / 2.0)
237+ * (k as f64 + 0.5))
238+ .cos()
239+ })
240+ .sum()
241+ })
242+ .collect()
243+ }
244+
245+ /// O(n^2) reference IMDCT including the 2/N convention, test-only.
246+ fn reference_imdct(x: &[f64]) -> Vec<f64> {
247+ let n = x.len();
248+ (0..2 * n)
249+ .map(|j| {
250+ 2.0 / n as f64
251+ * (0..n)
252+ .map(|k| {
253+ x[k] * (PI / n as f64
254+ * (j as f64 + 0.5 + n as f64 / 2.0)
255+ * (k as f64 + 0.5))
256+ .cos()
257+ })
258+ .sum::<f64>()
259+ })
260+ .collect()
261+ }
262+
263+ #[test]
264+ fn forward_matches_reference() {
265+ let mut worst = 0.0f64;
266+ // 2048 and 256 are the AAC long and short blocks; 512/1024 cover
267+ // Vorbis and CELT shapes.
268+ for window_len in [8usize, 64, 256, 512, 1024, 2048] {
269+ let input: Vec<f64> = noise(window_len, 0x4444 + window_len as u64);
270+ let want = reference_mdct(&input);
271+ let mut got = vec![0.0; window_len / 2];
272+ Mdct::new(window_len).forward(&input, &mut got);
273+ let error = rel_error(&got, &want);
274+ worst = worst.max(error);
275+ assert!(error < 1e-12, "mdct {window_len}: error {error:e}");
276+ }
277+ println!("MDCT vs reference: worst rel error {worst:e}");
278+ }
279+
280+ #[test]
281+ fn inverse_matches_reference() {
282+ let mut worst = 0.0f64;
283+ for window_len in [8usize, 64, 256, 2048] {
284+ let spectrum: Vec<f64> = noise(window_len / 2, 0x5555 + window_len as u64);
285+ let want = reference_imdct(&spectrum);
286+ let mut got = vec![0.0; window_len];
287+ Mdct::new(window_len).inverse(&spectrum, &mut got);
288+ let error = rel_error(&got, &want);
289+ worst = worst.max(error);
290+ assert!(error < 1e-12, "imdct {window_len}: error {error:e}");
291+ }
292+ println!("IMDCT vs reference: worst rel error {worst:e}");
293+ }
294+
295+ #[test]
296+ fn tdac_reconstructs_with_every_window() {
297+ for window_len in [256usize, 2048] {
298+ let mut mdct = Mdct::<f64>::new(window_len);
299+ for (name, window) in [
300+ ("sine", Window::<f64>::sine(window_len)),
301+ ("vorbis", Window::<f64>::vorbis(window_len)),
302+ ("kbd-4", Window::<f64>::kbd(window_len, 4.0)),
303+ ("kbd-6", Window::<f64>::kbd(window_len, 6.0)),
304+ ] {
305+ let error = mdct.perfect_reconstruction_error(&window, 0x6666);
306+ assert!(error < 1e-12, "{name} {window_len}: TDAC error {error:e}");
307+ println!("TDAC {name} {window_len}: max abs error {error:e}");
308+ }
309+ }
310+ }
311+
312+ #[test]
313+ fn tdac_reconstructs_in_f32() {
314+ let mut mdct = Mdct::<f32>::new(2048);
315+ let window = Window::<f32>::kbd(2048, 4.0);
316+ let error = mdct.perfect_reconstruction_error(&window, 0x7777);
317+ assert!(error < 1e-5, "f32 TDAC error {error:e}");
318+ println!("TDAC f32 kbd-4 2048: max abs error {error:e}");
319+ }
320+
321+ #[test]
322+ fn windowed_forward_equals_manual_windowing() {
323+ let window_len = 256;
324+ let input: Vec<f32> = noise(window_len, 0x8888);
325+ let window = Window::<f32>::sine(window_len);
326+ let manual: Vec<f32> = input
327+ .iter()
328+ .zip(window.as_slice())
329+ .map(|(x, w)| x * w)
330+ .collect();
331+ let mut mdct = Mdct::new(window_len);
332+ let mut a = vec![0.0f32; window_len / 2];
333+ let mut b = vec![0.0f32; window_len / 2];
334+ mdct.forward(&manual, &mut a);
335+ mdct.forward_windowed(&input, window.as_slice(), &mut b);
336+ assert_eq!(a, b);
337+ }
338+}
crates/ec-dsp/src/window.rsadded+258 -0
@@ -0,0 +1,258 @@
1+//! Analysis/synthesis windows for the lapped transforms.
2+//!
3+//! All three shapes here satisfy the Princen-Bradley condition
4+//! `w[n]^2 + w[n + N]^2 == 1`, which is what makes MDCT overlap-add
5+//! reconstruct exactly; [`Window::princen_bradley_error`] measures it.
6+//!
7+//! - [`Window::sine`] — MP3, AAC's other long window, CELT's basis.
8+//! - [`Window::kbd`] — AAC's Kaiser-Bessel-derived window (alpha 4 for long
9+//! blocks, 6 for short, per ISO/IEC 14496-3).
10+//! - [`Window::vorbis`] — the Vorbis I "slope" window, also used by Opus.
11+//!
12+//! Codecs that need asymmetric start/stop windows build them from the halves
13+//! of two of these; nothing here presumes a symmetric block.
14+
15+use crate::Real;
16+
17+/// A precomputed window, one value per sample of the transform block.
18+///
19+/// ```
20+/// use ec_dsp::Window;
21+///
22+/// let w = Window::<f64>::kbd(2048, 4.0);
23+/// assert_eq!(w.len(), 2048);
24+/// assert!(w.princen_bradley_error() < 1e-12);
25+/// ```
26+#[derive(Clone, Debug, PartialEq)]
27+pub struct Window<T: Real> {
28+ samples: Vec<T>,
29+}
30+
31+impl<T: Real> Window<T> {
32+ /// Wraps precomputed values, for shapes this module does not provide
33+ /// (asymmetric transition windows, for instance).
34+ ///
35+ /// # Panics
36+ /// If `samples` is empty or has odd length.
37+ pub fn from_samples(samples: Vec<T>) -> Window<T> {
38+ assert!(
39+ !samples.is_empty() && samples.len().is_multiple_of(2),
40+ "a window must have an even, non-zero length"
41+ );
42+ Window { samples }
43+ }
44+
45+ /// Sine window: `w[n] = sin(pi/L (n + 1/2))`, `L` the full window length.
46+ ///
47+ /// # Panics
48+ /// If `len` is zero or odd.
49+ pub fn sine(len: usize) -> Window<T> {
50+ Window::from_samples(
51+ (0..len)
52+ .map(|n| {
53+ let a = core::f64::consts::PI / len as f64 * (n as f64 + 0.5);
54+ T::from_f64(a.sin())
55+ })
56+ .collect(),
57+ )
58+ }
59+
60+ /// Vorbis window: `w[n] = sin(pi/2 * sin^2(pi/L (n + 1/2)))`.
61+ ///
62+ /// # Panics
63+ /// If `len` is zero or odd.
64+ pub fn vorbis(len: usize) -> Window<T> {
65+ Window::from_samples(
66+ (0..len)
67+ .map(|n| {
68+ let inner = (core::f64::consts::PI / len as f64 * (n as f64 + 0.5)).sin();
69+ T::from_f64((core::f64::consts::FRAC_PI_2 * inner * inner).sin())
70+ })
71+ .collect(),
72+ )
73+ }
74+
75+ /// Kaiser-Bessel-derived window with shape parameter `alpha` (AAC uses 4
76+ /// for 2048-sample blocks and 6 for 256-sample blocks).
77+ ///
78+ /// Built the defining way: a Kaiser window of `len/2 + 1` points,
79+ /// cumulatively summed and square-rooted, then mirrored — which is what
80+ /// makes the Princen-Bradley identity hold by construction rather than by
81+ /// numerical luck.
82+ ///
83+ /// # Panics
84+ /// If `len` is not a positive multiple of 4, or `alpha` is negative.
85+ pub fn kbd(len: usize, alpha: f64) -> Window<T> {
86+ assert!(
87+ len >= 4 && len.is_multiple_of(4),
88+ "a kbd window needs a length that is a positive multiple of 4, got {len}"
89+ );
90+ assert!(alpha >= 0.0, "kbd alpha must be non-negative, got {alpha}");
91+ let half = len / 2;
92+ let beta = core::f64::consts::PI * alpha;
93+ let denom = bessel_i0(beta);
94+ let mut cumulative = Vec::with_capacity(half + 1);
95+ let mut running = 0.0;
96+ for m in 0..=half {
97+ let ratio = 2.0 * m as f64 / half as f64 - 1.0;
98+ running += bessel_i0(beta * (1.0 - ratio * ratio).max(0.0).sqrt()) / denom;
99+ cumulative.push(running);
100+ }
101+ let total = running;
102+ let mut samples = vec![T::ZERO; len];
103+ for n in 0..half {
104+ let v = T::from_f64((cumulative[n] / total).sqrt());
105+ samples[n] = v;
106+ samples[len - 1 - n] = v;
107+ }
108+ Window::from_samples(samples)
109+ }
110+
111+ /// The window values.
112+ pub fn as_slice(&self) -> &[T] {
113+ &self.samples
114+ }
115+
116+ /// Samples in the window.
117+ pub fn len(&self) -> usize {
118+ self.samples.len()
119+ }
120+
121+ /// Always false — a window cannot be empty (see [`Window::from_samples`]).
122+ pub fn is_empty(&self) -> bool {
123+ false
124+ }
125+
126+ /// Multiplies `block` by the window in place, vectorised.
127+ ///
128+ /// # Panics
129+ /// If `block.len() != self.len()`.
130+ pub fn apply(&self, block: &mut [T]) {
131+ assert_eq!(
132+ block.len(),
133+ self.samples.len(),
134+ "block length must equal window length"
135+ );
136+ let lanes = T::LANES;
137+ let mut chunks = block.chunks_exact_mut(lanes);
138+ for (chunk, w) in (&mut chunks).zip(self.samples.chunks_exact(lanes)) {
139+ T::store(T::load(chunk) * T::load(w), chunk);
140+ }
141+ let done = self.samples.len() - self.samples.len() % lanes;
142+ for (v, w) in chunks
143+ .into_remainder()
144+ .iter_mut()
145+ .zip(&self.samples[done..])
146+ {
147+ *v = *v * *w;
148+ }
149+ }
150+
151+ /// Worst deviation from the Princen-Bradley condition
152+ /// `w[n]^2 + w[n + len/2]^2 == 1`, the property MDCT overlap-add needs.
153+ pub fn princen_bradley_error(&self) -> f64 {
154+ let half = self.samples.len() / 2;
155+ (0..half)
156+ .map(|n| {
157+ let a = self.samples[n].to_f64();
158+ let b = self.samples[n + half].to_f64();
159+ (a * a + b * b - 1.0).abs()
160+ })
161+ .fold(0.0, f64::max)
162+ }
163+}
164+
165+/// Modified Bessel function of the first kind, order zero, by its power
166+/// series — accurate to `f64` for the arguments a KBD window uses (`beta` up
167+/// to about 20).
168+fn bessel_i0(x: f64) -> f64 {
169+ let half = x / 2.0;
170+ let mut term = 1.0;
171+ let mut sum = 1.0;
172+ let mut k = 1.0;
173+ while term > 1e-18 * sum {
174+ term *= (half / k) * (half / k);
175+ sum += term;
176+ k += 1.0;
177+ if k > 200.0 {
178+ break;
179+ }
180+ }
181+ sum
182+}
183+
184+#[cfg(test)]
185+mod tests {
186+ use super::*;
187+
188+ #[test]
189+ fn all_shapes_satisfy_princen_bradley() {
190+ for len in [64usize, 256, 2048] {
191+ for (name, w) in [
192+ ("sine", Window::<f64>::sine(len)),
193+ ("vorbis", Window::<f64>::vorbis(len)),
194+ ("kbd-4", Window::<f64>::kbd(len, 4.0)),
195+ ("kbd-6", Window::<f64>::kbd(len, 6.0)),
196+ ("kbd-0", Window::<f64>::kbd(len, 0.0)),
197+ ] {
198+ let error = w.princen_bradley_error();
199+ assert!(error < 1e-12, "{name} {len}: PB error {error:e}");
200+ }
201+ }
202+ }
203+
204+ #[test]
205+ fn windows_are_symmetric_and_bounded() {
206+ let len = 512;
207+ for w in [
208+ Window::<f64>::sine(len),
209+ Window::<f64>::vorbis(len),
210+ Window::<f64>::kbd(len, 4.0),
211+ ] {
212+ let s = w.as_slice();
213+ for n in 0..len {
214+ assert!((0.0..=1.0).contains(&s[n]), "value out of range: {}", s[n]);
215+ assert!(
216+ (s[n] - s[len - 1 - n]).abs() < 1e-12,
217+ "asymmetric at {n}: {} vs {}",
218+ s[n],
219+ s[len - 1 - n]
220+ );
221+ }
222+ }
223+ }
224+
225+ #[test]
226+ fn bessel_i0_matches_known_values() {
227+ // Abramowitz & Stegun table values.
228+ for (x, want) in [
229+ (0.0, 1.0),
230+ (1.0, 1.266_065_877_752_008_4),
231+ (5.0, 27.239_871_823_604_44),
232+ (10.0, 2_815.716_628_466_254),
233+ ] {
234+ let got = bessel_i0(x);
235+ assert!(
236+ (got - want).abs() <= 1e-9 * want.abs().max(1.0),
237+ "I0({x}) = {got}, want {want}"
238+ );
239+ }
240+ }
241+
242+ #[test]
243+ fn apply_matches_scalar_multiply() {
244+ let len = 262; // not a multiple of the f64 lane count
245+ let w = Window::<f64>::sine(len);
246+ let block: Vec<f64> = (0..len).map(|n| n as f64 * 0.5 - 3.0).collect();
247+ let want: Vec<f64> = block.iter().zip(w.as_slice()).map(|(b, s)| b * s).collect();
248+ let mut got = block.clone();
249+ w.apply(&mut got);
250+ assert_eq!(got, want);
251+ }
252+
253+ #[test]
254+ #[should_panic(expected = "multiple of 4")]
255+ fn kbd_rejects_odd_lengths() {
256+ let _ = Window::<f32>::kbd(30, 4.0);
257+ }
258+}