forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBcbbd6e2Tahinli2 months ago2369 commits

mdct.rs338 lines, 11.9 KiBHistoryRawDownload
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
21use crate::Real;
22use 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)]
37pub struct Mdct<T: Real> {
38 half: usize,
39 dct: Dct4<T>,
40 fold: Vec<T>,
41}
42
43impl<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)]
222mod 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}