forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB052d1d3Tahinli2 months ago3627 commits

dct.rs305 lines, 10.2 KiBHistoryRawDownload
1//! DCT-II, DCT-III and DCT-IV, all routed through an FFT.
2//!
3//! Every one of these is `O(n log n)` here. Definitions, unnormalised, for
4//! length `N`:
5//!
6//! - DCT-II: `X[k] = sum_n x[n] cos(pi/N (n + 1/2) k)`
7//! - DCT-III: `X[k] = x[0]/2 + sum_{n>=1} x[n] cos(pi/N n (k + 1/2))`
8//! - DCT-IV: `X[k] = sum_n x[n] cos(pi/N (n + 1/2)(k + 1/2))`
9//!
10//! DCT-III is the inverse of DCT-II up to the usual `2/N`, i.e.
11//! `x == (2/N) * dct3(dct2(x))`. DCT-IV is its own inverse up to the same
12//! factor, which is why [`crate::Mdct`] needs only the one plan for both
13//! directions.
14//!
15//! II and III use an `N`-point real FFT (Makhoul's method); IV uses an
16//! `N/2`-point complex FFT with a quarter-sample twiddle on each side.
17
18use crate::Real;
19use crate::fft::{Complex, Fft, RealFft};
20
21/// DCT-II / DCT-III plan for one size.
22///
23/// ```
24/// use ec_dsp::Dct;
25///
26/// let mut dct = Dct::<f64>::new(8);
27/// let mut data = [1.0, 2.0, 3.0, 4.0, 4.0, 3.0, 2.0, 1.0];
28/// let original = data;
29/// dct.dct2(&mut data);
30/// dct.dct3(&mut data);
31/// // dct3 . dct2 = (N/2) * identity
32/// assert!(data.iter().zip(&original).all(|(a, b)| (a / 4.0 - b).abs() < 1e-12));
33/// ```
34#[derive(Clone, Debug)]
35pub struct Dct<T: Real> {
36 n: usize,
37 rfft: RealFft<T>,
38 twiddle_re: Vec<T>,
39 twiddle_im: Vec<T>,
40 shuffled: Vec<T>,
41 spectrum: Vec<Complex<T>>,
42}
43
44impl<T: Real> Dct<T> {
45 /// A plan for `n` points.
46 ///
47 /// # Panics
48 /// If `n` is not a power of two of at least 4 (see [`crate::fft::MAX_LEN`]).
49 pub fn new(n: usize) -> Dct<T> {
50 let rfft = RealFft::new(n);
51 let mut twiddle_re = Vec::with_capacity(n);
52 let mut twiddle_im = Vec::with_capacity(n);
53 for k in 0..n {
54 // exp(-i*pi*k/(2N)): the half-sample shift that turns a DFT of the
55 // even/odd-shuffled signal into a DCT.
56 let angle = -core::f64::consts::PI * k as f64 / (2.0 * n as f64);
57 twiddle_re.push(T::from_f64(angle.cos()));
58 twiddle_im.push(T::from_f64(angle.sin()));
59 }
60 Dct {
61 n,
62 rfft,
63 twiddle_re,
64 twiddle_im,
65 shuffled: vec![T::ZERO; n],
66 spectrum: vec![Complex::ZERO; n / 2 + 1],
67 }
68 }
69
70 /// Points per transform.
71 pub fn size(&self) -> usize {
72 self.n
73 }
74
75 /// DCT-II in place.
76 ///
77 /// # Panics
78 /// If `data.len() != self.size()`.
79 pub fn dct2(&mut self, data: &mut [T]) {
80 assert_eq!(data.len(), self.n, "dct input length must equal plan size");
81 let n = self.n;
82 // Even samples in order, odd samples reversed: a real DFT of this
83 // sequence carries the DCT-II in its real part after a twiddle.
84 for j in 0..n / 2 {
85 self.shuffled[j] = data[2 * j];
86 self.shuffled[n - 1 - j] = data[2 * j + 1];
87 }
88 self.rfft.forward(&self.shuffled, &mut self.spectrum);
89 for (k, out) in data.iter_mut().enumerate() {
90 let bin = if k <= n / 2 {
91 self.spectrum[k]
92 } else {
93 self.spectrum[n - k].conj()
94 };
95 let tw = Complex::new(self.twiddle_re[k], self.twiddle_im[k]);
96 *out = (tw * bin).re;
97 }
98 }
99
100 /// DCT-III in place — [`Dct::dct2`] run backwards, times `N/2`.
101 ///
102 /// # Panics
103 /// If `data.len() != self.size()`.
104 pub fn dct3(&mut self, data: &mut [T]) {
105 assert_eq!(data.len(), self.n, "dct input length must equal plan size");
106 let n = self.n;
107 for k in 0..=n / 2 {
108 // The spectrum whose real part is `data`: G[k] = X[k] - i X[N-k].
109 let hi = if k == 0 { T::ZERO } else { data[n - k] };
110 let g = Complex::new(data[k], -hi);
111 let tw = Complex::new(self.twiddle_re[k], self.twiddle_im[k]).conj();
112 self.spectrum[k] = tw * g;
113 }
114 self.rfft.inverse(&self.spectrum, &mut self.shuffled);
115 let gain = T::from_f64(n as f64 / 2.0);
116 for j in 0..n / 2 {
117 data[2 * j] = self.shuffled[j] * gain;
118 data[2 * j + 1] = self.shuffled[n - 1 - j] * gain;
119 }
120 }
121}
122
123/// DCT-IV plan for one size — the kernel [`crate::Mdct`] is built on.
124///
125/// ```
126/// use ec_dsp::Dct4;
127///
128/// let mut dct = Dct4::<f64>::new(8);
129/// let mut data = [1.0, -2.0, 3.0, 0.5, 0.0, 1.5, -1.0, 2.0];
130/// let original = data;
131/// dct.transform(&mut data);
132/// dct.transform(&mut data);
133/// // DCT-IV is an involution up to N/2.
134/// assert!(data.iter().zip(&original).all(|(a, b)| (a / 4.0 - b).abs() < 1e-12));
135/// ```
136#[derive(Clone, Debug)]
137pub struct Dct4<T: Real> {
138 n: usize,
139 fft: Fft<T>,
140 pre_re: Vec<T>,
141 pre_im: Vec<T>,
142 post_re: Vec<T>,
143 post_im: Vec<T>,
144 buf_re: Vec<T>,
145 buf_im: Vec<T>,
146}
147
148impl<T: Real> Dct4<T> {
149 /// A plan for `n` points, `n` a power of two of at least 2.
150 ///
151 /// # Panics
152 /// If `n` is not a power of two, or `n/2` is not a legal FFT size.
153 pub fn new(n: usize) -> Dct4<T> {
154 assert!(
155 n.is_power_of_two() && n >= 2,
156 "dct-iv length must be a power of two of at least 2, got {n}"
157 );
158 let half = n / 2;
159 let mut pre_re = Vec::with_capacity(half);
160 let mut pre_im = Vec::with_capacity(half);
161 let mut post_re = Vec::with_capacity(half);
162 let mut post_im = Vec::with_capacity(half);
163 for j in 0..half {
164 // exp(-i*pi*(4j+1)/(4N)) before the FFT, exp(-i*pi*k/N) after:
165 // together they supply the (n+1/2)(k+1/2) phase of a DCT-IV.
166 let pre = -core::f64::consts::PI * (4 * j + 1) as f64 / (4.0 * n as f64);
167 pre_re.push(T::from_f64(pre.cos()));
168 pre_im.push(T::from_f64(pre.sin()));
169 let post = -core::f64::consts::PI * j as f64 / n as f64;
170 post_re.push(T::from_f64(post.cos()));
171 post_im.push(T::from_f64(post.sin()));
172 }
173 Dct4 {
174 n,
175 fft: Fft::new(half),
176 pre_re,
177 pre_im,
178 post_re,
179 post_im,
180 buf_re: vec![T::ZERO; half],
181 buf_im: vec![T::ZERO; half],
182 }
183 }
184
185 /// Points per transform.
186 pub fn size(&self) -> usize {
187 self.n
188 }
189
190 /// DCT-IV in place.
191 ///
192 /// # Panics
193 /// If `data.len() != self.size()`.
194 pub fn transform(&mut self, data: &mut [T]) {
195 assert_eq!(
196 data.len(),
197 self.n,
198 "dct-iv input length must equal plan size"
199 );
200 let n = self.n;
201 let half = n / 2;
202 for j in 0..half {
203 let (re, im) = (data[2 * j], data[n - 1 - 2 * j]);
204 self.buf_re[j] = re * self.pre_re[j] - im * self.pre_im[j];
205 self.buf_im[j] = re * self.pre_im[j] + im * self.pre_re[j];
206 }
207 self.fft.forward_split(&mut self.buf_re, &mut self.buf_im);
208 for k in 0..half {
209 let (re, im) = (self.buf_re[k], self.buf_im[k]);
210 let (wr, wi) = (self.post_re[k], self.post_im[k]);
211 data[2 * k] = re * wr - im * wi;
212 data[n - 1 - 2 * k] = -(re * wi + im * wr);
213 }
214 }
215}
216
217#[cfg(test)]
218mod tests {
219 use super::*;
220 use crate::tests::{noise, rel_error};
221 use core::f64::consts::PI;
222
223 /// O(n^2) reference DCTs, test-only.
224 fn reference(kind: u8, x: &[f64]) -> Vec<f64> {
225 let n = x.len();
226 (0..n)
227 .map(|k| match kind {
228 2 => (0..n)
229 .map(|j| x[j] * (PI / n as f64 * (j as f64 + 0.5) * k as f64).cos())
230 .sum(),
231 3 => {
232 x[0] / 2.0
233 + (1..n)
234 .map(|j| x[j] * (PI / n as f64 * j as f64 * (k as f64 + 0.5)).cos())
235 .sum::<f64>()
236 }
237 _ => (0..n)
238 .map(|j| x[j] * (PI / n as f64 * (j as f64 + 0.5) * (k as f64 + 0.5)).cos())
239 .sum(),
240 })
241 .collect()
242 }
243
244 #[test]
245 fn dct2_and_dct3_agree_with_reference() {
246 let mut worst = 0.0f64;
247 for shift in 2..=13 {
248 let n = 1usize << shift;
249 let input: Vec<f64> = noise(n, 0x2222 + n as u64);
250 for kind in [2u8, 3] {
251 let want = reference(kind, &input);
252 let mut got = input.clone();
253 let mut dct = Dct::new(n);
254 if kind == 2 {
255 dct.dct2(&mut got);
256 } else {
257 dct.dct3(&mut got);
258 }
259 let error = rel_error(&got, &want);
260 worst = worst.max(error);
261 assert!(error < 1e-12, "dct-{kind} n = {n}: error {error:e}");
262 }
263 }
264 println!("f64 DCT-II/III vs reference: worst rel error {worst:e}");
265 }
266
267 #[test]
268 fn dct4_agrees_with_reference() {
269 let mut worst_f64 = 0.0f64;
270 let mut worst_f32 = 0.0f64;
271 for shift in 1..=13 {
272 let n = 1usize << shift;
273 let input: Vec<f64> = noise(n, 0x3333 + n as u64);
274 let want = reference(4, &input);
275
276 let mut got = input.clone();
277 Dct4::new(n).transform(&mut got);
278 let error = rel_error(&got, &want);
279 worst_f64 = worst_f64.max(error);
280 assert!(error < 1e-12, "dct-iv f64 n = {n}: error {error:e}");
281
282 let mut got32: Vec<f32> = input.iter().map(|v| *v as f32).collect();
283 Dct4::new(n).transform(&mut got32);
284 let widened: Vec<f64> = got32.iter().map(|v| *v as f64).collect();
285 let error32 = rel_error(&widened, &want);
286 worst_f32 = worst_f32.max(error32);
287 assert!(error32 < 1e-5, "dct-iv f32 n = {n}: error {error32:e}");
288 }
289 println!("DCT-IV vs reference: worst rel error f64 {worst_f64:e}, f32 {worst_f32:e}");
290 }
291
292 #[test]
293 fn dct2_round_trips_through_dct3() {
294 let n = 1024;
295 let input: Vec<f32> = noise(n, 5150);
296 let mut data = input.clone();
297 let mut dct = Dct::new(n);
298 dct.dct2(&mut data);
299 dct.dct3(&mut data);
300 crate::scale(&mut data, 2.0 / n as f32);
301 let error = rel_error(&data, &input);
302 assert!(error < 1e-6, "round-trip error {error:e}");
303 println!("f32 DCT-II/III round trip (n = {n}): rel error {error:e}");
304 }
305}