forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBabd41b6Tahinli3 months ago75 commits

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