forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB86fb0f3Tahinli7 days ago3927 commits

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