forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB2edeb94Tahinli3 months ago599 commits

transform.rs239 lines, 9.2 KiBHistoryRawDownload
1//! The inverse transform of A/52 §7.9.4: one 512-sample IMDCT, or two
2//! 256-sample IMDCTs when the block switch flag is set, followed by the window
3//! and overlap-add of §7.9.4 step 6.
4//!
5//! Both cases are the standard's own factorisation — pre-twiddle, an `N/4` (or
6//! `N/8`) point complex inverse FFT from `ec_dsp`, post-twiddle, then the
7//! interleaved windowing step. Writing it that way rather than calling a
8//! generic MDCT keeps the sign and ordering conventions the standard's, so
9//! there is nothing to reconcile when reading the two side by side.
10
11use ec_dsp::Fft;
12use ec_dsp::fft::Complex;
13
14use crate::tables::WINDOW;
15
16/// Samples produced per audio block, per channel.
17pub const BLOCK_SAMPLES: usize = 256;
18
19/// The plans and twiddles for both transform lengths.
20#[derive(Clone)]
21pub struct Imdct {
22 long: Fft<f32>,
23 short: Fft<f32>,
24 /// Pre-twiddle for N = 512: `-cos/-sin(2π(8k+1)/4096)`, k < 128.
25 pre_long: Vec<Complex<f32>>,
26 /// Post-twiddle for N = 512: the same, scaled by 128 to undo the `1/n`
27 /// that [`Fft::inverse`] applies but the standard's IFFT step does not.
28 post_long: Vec<Complex<f32>>,
29 /// Pre-twiddle for the 256-sample halves: `-cos/-sin(2π(8k+1)/2048)`.
30 pre_short: Vec<Complex<f32>>,
31 /// Post-twiddle for the halves, scaled by 64.
32 post_short: Vec<Complex<f32>>,
33 z: Vec<Complex<f32>>,
34 z2: Vec<Complex<f32>>,
35 x: Vec<f32>,
36}
37
38impl Default for Imdct {
39 fn default() -> Imdct {
40 Imdct::new()
41 }
42}
43
44fn twiddles(count: usize, denom: f64, scale: f64) -> Vec<Complex<f32>> {
45 (0..count)
46 .map(|k| {
47 let angle = 2.0 * std::f64::consts::PI * (8.0 * k as f64 + 1.0) / denom;
48 Complex::new((-angle.cos() * scale) as f32, (-angle.sin() * scale) as f32)
49 })
50 .collect()
51}
52
53impl Imdct {
54 /// Build both plans. Allocates once; [`Imdct::block`] allocates nothing.
55 pub fn new() -> Imdct {
56 const N: f64 = 512.0;
57 Imdct {
58 long: Fft::new(128),
59 short: Fft::new(64),
60 pre_long: twiddles(128, 8.0 * N, 1.0),
61 post_long: twiddles(128, 8.0 * N, 128.0),
62 pre_short: twiddles(64, 4.0 * N, 1.0),
63 post_short: twiddles(64, 4.0 * N, 64.0),
64 z: vec![Complex::new(0.0, 0.0); 128],
65 z2: vec![Complex::new(0.0, 0.0); 64],
66 x: vec![0.0; 512],
67 }
68 }
69
70 /// One audio block: `coeffs` (256 spectral values) in, 256 PCM samples out,
71 /// carrying `delay` across the call as the overlap-add tail.
72 ///
73 /// `block_switch` selects the two 256-sample transforms of §7.9.4.2.
74 pub fn block(
75 &mut self,
76 coeffs: &[f32],
77 block_switch: bool,
78 delay: &mut [f32],
79 out: &mut [f32],
80 ) {
81 debug_assert!(coeffs.len() >= 256 && delay.len() >= 256 && out.len() >= 256);
82 if block_switch {
83 self.short_transform(coeffs);
84 } else {
85 self.long_transform(coeffs);
86 }
87 // §7.9.4 step 6. The factor of 2 undoes the encoder's headroom scaling.
88 for n in 0..BLOCK_SAMPLES {
89 out[n] = 2.0 * (self.x[n] + delay[n]);
90 delay[n] = self.x[BLOCK_SAMPLES + n];
91 }
92 }
93
94 /// Drop the overlap-add tail; a seek makes it belong to frames that were
95 /// never decoded.
96 pub fn reset(delay: &mut [f32]) {
97 delay.fill(0.0);
98 }
99
100 fn long_transform(&mut self, coeffs: &[f32]) {
101 // Step 2: pre-IFFT complex multiply.
102 for k in 0..128 {
103 let (a, b) = (coeffs[255 - 2 * k], coeffs[2 * k]);
104 let t = self.pre_long[k];
105 self.z[k] = Complex::new(a * t.re - b * t.im, b * t.re + a * t.im);
106 }
107 // Step 3: N/4-point complex IFFT.
108 self.long.inverse(&mut self.z);
109 // Step 4: post-IFFT complex multiply (with the 1/n undone).
110 for n in 0..128 {
111 let (zr, zi) = (self.z[n].re, self.z[n].im);
112 let t = self.post_long[n];
113 self.z[n] = Complex::new(zr * t.re - zi * t.im, zi * t.re + zr * t.im);
114 }
115 // Step 5: windowing and de-interleaving.
116 let (y, x) = (&self.z, &mut self.x);
117 for n in 0..64 {
118 x[2 * n] = -y[64 + n].im * WINDOW[2 * n];
119 x[2 * n + 1] = y[63 - n].re * WINDOW[2 * n + 1];
120 x[128 + 2 * n] = -y[n].re * WINDOW[128 + 2 * n];
121 x[128 + 2 * n + 1] = y[127 - n].im * WINDOW[128 + 2 * n + 1];
122 x[256 + 2 * n] = -y[64 + n].re * WINDOW[255 - 2 * n];
123 x[256 + 2 * n + 1] = y[63 - n].im * WINDOW[254 - 2 * n];
124 x[384 + 2 * n] = y[n].im * WINDOW[127 - 2 * n];
125 x[384 + 2 * n + 1] = -y[127 - n].re * WINDOW[126 - 2 * n];
126 }
127 }
128
129 fn short_transform(&mut self, coeffs: &[f32]) {
130 // Step 1-2: split the coefficients even/odd, then pre-twiddle each.
131 for k in 0..64 {
132 let (a1, b1) = (coeffs[2 * (127 - 2 * k)], coeffs[2 * (2 * k)]);
133 let (a2, b2) = (coeffs[2 * (127 - 2 * k) + 1], coeffs[2 * (2 * k) + 1]);
134 let t = self.pre_short[k];
135 self.z[k] = Complex::new(a1 * t.re - b1 * t.im, b1 * t.re + a1 * t.im);
136 self.z2[k] = Complex::new(a2 * t.re - b2 * t.im, b2 * t.re + a2 * t.im);
137 }
138 // Step 3: two N/8-point complex IFFTs.
139 self.short.inverse(&mut self.z[..64]);
140 self.short.inverse(&mut self.z2);
141 // Step 4: post-twiddle both.
142 for n in 0..64 {
143 let t = self.post_short[n];
144 let (zr, zi) = (self.z[n].re, self.z[n].im);
145 self.z[n] = Complex::new(zr * t.re - zi * t.im, zi * t.re + zr * t.im);
146 let (zr, zi) = (self.z2[n].re, self.z2[n].im);
147 self.z2[n] = Complex::new(zr * t.re - zi * t.im, zi * t.re + zr * t.im);
148 }
149 // Step 5: windowing and de-interleaving.
150 let (y1, y2, x) = (&self.z, &self.z2, &mut self.x);
151 for n in 0..64 {
152 x[2 * n] = -y1[n].im * WINDOW[2 * n];
153 x[2 * n + 1] = y1[63 - n].re * WINDOW[2 * n + 1];
154 x[128 + 2 * n] = -y1[n].re * WINDOW[128 + 2 * n];
155 x[128 + 2 * n + 1] = y1[63 - n].im * WINDOW[128 + 2 * n + 1];
156 x[256 + 2 * n] = -y2[n].re * WINDOW[255 - 2 * n];
157 x[256 + 2 * n + 1] = y2[63 - n].im * WINDOW[254 - 2 * n];
158 x[384 + 2 * n] = y2[n].im * WINDOW[127 - 2 * n];
159 x[384 + 2 * n + 1] = -y2[63 - n].re * WINDOW[126 - 2 * n];
160 }
161 }
162}
163
164/// A single MDCT coefficient's worth of energy, used by the round-trip test
165/// below and by nothing else: the forward transform the standard's encoder
166/// side describes, at the one length the test needs.
167#[cfg(test)]
168fn forward_mdct_512(input: &[f32], out: &mut [f32]) {
169 use std::f64::consts::PI;
170 let n = 512.0;
171 for (k, o) in out.iter_mut().enumerate().take(256) {
172 let mut acc = 0.0f64;
173 for (i, &s) in input.iter().enumerate().take(512) {
174 let angle = 2.0 * PI / n * (i as f64 + 0.5 + n / 4.0) * (k as f64 + 0.5);
175 acc += f64::from(s) * f64::from(WINDOW[window_index(i)]) * angle.cos();
176 }
177 *o = (-acc * 2.0 / n) as f32;
178 }
179}
180
181#[cfg(test)]
182fn window_index(i: usize) -> usize {
183 if i < 256 { i } else { 511 - i }
184}
185
186#[cfg(test)]
187mod tests {
188 use super::*;
189
190 #[test]
191 fn long_blocks_reconstruct_under_overlap_add() {
192 // Feed two overlapping windowed transforms of one signal and check the
193 // overlap-add of their inverses returns the middle 256 samples. This is
194 // the property the whole §7.9.4 factorisation exists to have; getting a
195 // sign or an index wrong in step 5 destroys it.
196 let signal: Vec<f32> = (0..768)
197 .map(|n| (n as f32 * 0.077).sin() * 0.4 + (n as f32 * 0.31).cos() * 0.2)
198 .collect();
199 let mut spec_a = [0.0f32; 256];
200 let mut spec_b = [0.0f32; 256];
201 forward_mdct_512(&signal[0..512], &mut spec_a);
202 forward_mdct_512(&signal[256..768], &mut spec_b);
203
204 let mut imdct = Imdct::new();
205 let mut delay = [0.0f32; 256];
206 let mut out = [0.0f32; 256];
207 imdct.block(&spec_a, false, &mut delay, &mut out);
208 imdct.block(&spec_b, false, &mut delay, &mut out);
209 for n in 0..256 {
210 let want = signal[256 + n];
211 assert!(
212 (out[n] - want).abs() < 2e-3,
213 "n = {n}: {} vs {want}",
214 out[n]
215 );
216 }
217 }
218
219 #[test]
220 fn short_blocks_produce_the_same_energy_as_the_signal() {
221 // A block-switched pair of 256-point transforms has no closed-form
222 // reference here, so the check is the weaker but still load-bearing
223 // one: a single non-zero coefficient must produce a bounded, non-silent
224 // output, and silence must stay silent.
225 let mut imdct = Imdct::new();
226 let mut delay = [0.0f32; 256];
227 let mut out = [0.0f32; 256];
228 let mut spec = [0.0f32; 256];
229 spec[40] = 0.5;
230 imdct.block(&spec, true, &mut delay, &mut out);
231 let energy: f32 = out.iter().map(|v| v * v).sum();
232 assert!(energy > 1e-6, "block-switched output is silent");
233 assert!(out.iter().all(|v| v.abs() < 4.0));
234
235 let mut silent_delay = [0.0f32; 256];
236 imdct.block(&[0.0; 256], true, &mut silent_delay, &mut out);
237 assert!(out.iter().all(|v| *v == 0.0));
238 }
239}