forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust382.4 MiBe18142dTahinli10 hours ago4543 commits

lib.rs325 lines, 10.7 KiBHistoryRawDownload
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, and no dependencies beyond
34//! `wide`.
35
36#![forbid(unsafe_code)]
37#![warn(missing_docs)]
38
39pub mod dct;
40pub mod fft;
41pub mod mdct;
42pub mod rgb;
43pub mod window;
44
45pub use dct::{Dct, Dct4};
46pub use fft::{Complex, Fft, RealFft};
47pub use mdct::Mdct;
48pub use window::Window;
49
50use core::fmt::Debug;
51use core::ops::{Add, Div, Mul, Neg, Sub};
52
53/// The sample types the transforms are generic over: `f32` and `f64`.
54///
55/// The trait exists to give one implementation of each transform for both
56/// precisions *including* its SIMD form: [`Real::Lanes`] is the widest `wide`
57/// vector for the type, and the kernels fall back to scalar code on the
58/// remainder of a row. Implementing it for anything else is not supported —
59/// the transforms assume IEEE-754 binary arithmetic.
60pub trait Real:
61 Copy
62 + Debug
63 + Default
64 + PartialOrd
65 + Add<Output = Self>
66 + Sub<Output = Self>
67 + Mul<Output = Self>
68 + Div<Output = Self>
69 + Neg<Output = Self>
70 + Send
71 + Sync
72 + 'static
73{
74 /// A vector of [`Real::LANES`] values, backed by `wide`.
75 type Lanes: Copy
76 + Add<Output = Self::Lanes>
77 + Sub<Output = Self::Lanes>
78 + Mul<Output = Self::Lanes>;
79
80 /// Values per [`Real::Lanes`] vector (8 for `f32`, 4 for `f64`).
81 const LANES: usize;
82 /// Additive identity.
83 const ZERO: Self;
84 /// Multiplicative identity.
85 const ONE: Self;
86
87 /// Rounds an `f64` — how every table entry in this crate is produced.
88 fn from_f64(v: f64) -> Self;
89 /// Widens to `f64`, for reference computations and reporting.
90 fn to_f64(self) -> f64;
91 /// Square root.
92 fn sqrt(self) -> Self;
93 /// Absolute value.
94 fn abs(self) -> Self;
95 /// Broadcasts one value across a vector.
96 fn splat(self) -> Self::Lanes;
97 /// Loads exactly [`Real::LANES`] values. Panics if `src` is another
98 /// length — callers feed it `chunks_exact(LANES)`, which is what lets the
99 /// bounds check fold away in the transform inner loops.
100 fn load(src: &[Self]) -> Self::Lanes;
101 /// Stores exactly [`Real::LANES`] values. Panics if `dst` is another length.
102 fn store(v: Self::Lanes, dst: &mut [Self]);
103}
104
105impl Real for f32 {
106 type Lanes = wide::f32x8;
107
108 const LANES: usize = 8;
109 const ZERO: f32 = 0.0;
110 const ONE: f32 = 1.0;
111
112 #[inline]
113 fn from_f64(v: f64) -> f32 {
114 v as f32
115 }
116 #[inline]
117 fn to_f64(self) -> f64 {
118 self as f64
119 }
120 #[inline]
121 fn sqrt(self) -> f32 {
122 f32::sqrt(self)
123 }
124 #[inline]
125 fn abs(self) -> f32 {
126 f32::abs(self)
127 }
128 #[inline]
129 fn splat(self) -> wide::f32x8 {
130 wide::f32x8::splat(self)
131 }
132 #[inline]
133 fn load(src: &[f32]) -> wide::f32x8 {
134 let chunk: [f32; 8] = src.try_into().expect("load needs exactly 8 values");
135 wide::bytemuck::cast(chunk)
136 }
137 #[inline]
138 fn store(v: wide::f32x8, dst: &mut [f32]) {
139 dst.copy_from_slice(&v.to_array());
140 }
141}
142
143impl Real for f64 {
144 type Lanes = wide::f64x4;
145
146 const LANES: usize = 4;
147 const ZERO: f64 = 0.0;
148 const ONE: f64 = 1.0;
149
150 #[inline]
151 fn from_f64(v: f64) -> f64 {
152 v
153 }
154 #[inline]
155 fn to_f64(self) -> f64 {
156 self
157 }
158 #[inline]
159 fn sqrt(self) -> f64 {
160 f64::sqrt(self)
161 }
162 #[inline]
163 fn abs(self) -> f64 {
164 f64::abs(self)
165 }
166 #[inline]
167 fn splat(self) -> wide::f64x4 {
168 wide::f64x4::splat(self)
169 }
170 #[inline]
171 fn load(src: &[f64]) -> wide::f64x4 {
172 let chunk: [f64; 4] = src.try_into().expect("load needs exactly 4 values");
173 wide::bytemuck::cast(chunk)
174 }
175 #[inline]
176 fn store(v: wide::f64x4, dst: &mut [f64]) {
177 dst.copy_from_slice(&v.to_array());
178 }
179}
180
181/// Multiplies `data` by `factor` in place, vectorised.
182pub(crate) fn scale<T: Real>(data: &mut [T], factor: T) {
183 let fv = factor.splat();
184 // Split off the whole-lane prefix; `chunks_mut` over it yields only full chunks.
185 let full = data.len() / T::LANES * T::LANES;
186 let (head, tail) = data.split_at_mut(full);
187 for chunk in head.chunks_mut(T::LANES) {
188 T::store(T::load(chunk) * fv, chunk);
189 }
190 for v in tail {
191 *v = *v * factor;
192 }
193}
194
195#[cfg(test)]
196mod tests {
197 use super::*;
198
199 /// Deterministic test signal — no `rand` dependency in a DSP crate.
200 pub(crate) fn noise<T: Real>(n: usize, seed: u64) -> Vec<T> {
201 let mut state = seed | 1;
202 (0..n)
203 .map(|_| {
204 state ^= state << 13;
205 state ^= state >> 7;
206 state ^= state << 17;
207 let unit = (state >> 11) as f64 / (1u64 << 53) as f64;
208 T::from_f64(unit * 2.0 - 1.0)
209 })
210 .collect()
211 }
212
213 /// Relative L2 error of `got` against `want`, both read as `f64`.
214 pub(crate) fn rel_error<T: Real>(got: &[T], want: &[T]) -> f64 {
215 let mut num = 0.0;
216 let mut den = 0.0;
217 for (g, w) in got.iter().zip(want) {
218 let d = g.to_f64() - w.to_f64();
219 num += d * d;
220 den += w.to_f64() * w.to_f64();
221 }
222 (num / den.max(f64::MIN_POSITIVE)).sqrt()
223 }
224
225 /// Throughput, printed rather than asserted: the numbers are machine
226 /// specific, but a regression of the *order of magnitude* is what the
227 /// family cares about (an incumbent shipped an O(n^2) transform and lost
228 /// 40x). Run with:
229 ///
230 /// `cargo test -p ec-dsp --release -- --ignored --nocapture throughput`
231 #[test]
232 #[ignore = "timing; run in release with --ignored --nocapture"]
233 fn throughput() {
234 use crate::{Complex, Fft, Mdct, RealFft, Window};
235 use std::time::Instant;
236
237 let n = 2048;
238 let signal: Vec<f32> = noise(n, 0xdeadbeef);
239 let mut guard = 0.0f32;
240
241 let mut fft = Fft::<f32>::new(n);
242 let mut data: Vec<Complex<f32>> = signal.iter().map(|v| Complex::new(*v, 0.0)).collect();
243 let iters = 50_000;
244 // Alternating directions keeps the in-place data bounded, so the
245 // numbers are not measured on infinities; the inverse costs one extra
246 // scaling pass, which makes this average slightly pessimistic.
247 let t0 = Instant::now();
248 for i in 0..iters {
249 if i % 2 == 0 {
250 fft.forward(&mut data);
251 } else {
252 fft.inverse(&mut data);
253 }
254 }
255 report("complex FFT f32 2048 fwd/inv", t0.elapsed(), iters, n);
256 guard += data[0].re;
257
258 let mut re: Vec<f32> = signal.clone();
259 let mut im: Vec<f32> = vec![0.0; n];
260 let t0 = Instant::now();
261 for i in 0..iters {
262 if i % 2 == 0 {
263 fft.forward_split(&mut re, &mut im);
264 } else {
265 fft.inverse_split(&mut re, &mut im);
266 }
267 }
268 report("split FFT f32 2048 fwd/inv", t0.elapsed(), iters, n);
269 guard += re[0];
270
271 let mut rfft = RealFft::<f32>::new(n);
272 let mut spectrum = vec![Complex::new(0.0f32, 0.0); n / 2 + 1];
273 let t0 = Instant::now();
274 for _ in 0..iters {
275 rfft.forward(&signal, &mut spectrum);
276 }
277 report("real FFT f32 2048 fwd", t0.elapsed(), iters, n);
278 guard += spectrum[0].re;
279
280 let mut mdct = Mdct::<f32>::new(n);
281 let window = Window::<f32>::kbd(n, 4.0);
282 let mut coeffs = vec![0.0f32; n / 2];
283 let t0 = Instant::now();
284 for _ in 0..iters {
285 mdct.forward_windowed(&signal, window.as_slice(), &mut coeffs);
286 }
287 report("MDCT f32 2048 fwd (windowed)", t0.elapsed(), iters, n);
288 guard += coeffs[0];
289
290 let mut frame = vec![0.0f32; n];
291 let t0 = Instant::now();
292 for _ in 0..iters {
293 mdct.inverse_windowed(&coeffs, window.as_slice(), &mut frame);
294 }
295 report("IMDCT f32 2048 inv (windowed)", t0.elapsed(), iters, n);
296 guard += frame[0];
297
298 // 48 kHz stereo AAC: 2 channels * 46.875 long blocks per second.
299 let per_block = t0.elapsed().as_secs_f64() / iters as f64;
300 println!("guard {guard:e}");
301 println!(
302 "one 2048 IMDCT = {:.2} us; a 5.1 48 kHz stream needs 6*46.9 = 281 per second",
303 per_block * 1e6
304 );
305 }
306
307 fn report(label: &str, elapsed: std::time::Duration, iters: u32, n: usize) {
308 let per = elapsed.as_secs_f64() / iters as f64;
309 println!(
310 "{label:<32} {:>8.0} ns/transform {:>7.1} Mpoint/s",
311 per * 1e9,
312 n as f64 / per / 1e6
313 );
314 }
315
316 #[test]
317 fn scale_matches_scalar_across_the_lane_boundary() {
318 for n in [1usize, 3, 8, 9, 17, 64] {
319 let mut data: Vec<f32> = noise(n, 7);
320 let want: Vec<f32> = data.iter().map(|v| v * 0.25).collect();
321 scale(&mut data, 0.25);
322 assert_eq!(data, want, "n = {n}");
323 }
324 }
325}