Debian Codegraph @

.cargo/vendor/rustdct/src/twiddles.rs

raw
1 use rustfft::num_complex::Complex;
2 use std::f64;
3
4 use crate::DctNum;
5
6 #[inline(always)]
7 pub fn single_twiddle<T: DctNum>(i: usize, fft_len: usize) -> Complex<T> {
8 let angle_constant = f64::consts::PI * -2f64 / fft_len as f64;
9
10 let c = Complex::from_polar(1f64, angle_constant * i as f64);
11
12 Complex {
13 re: T::from_f64(c.re).unwrap(),
14 im: T::from_f64(c.im).unwrap(),
15 }
16 }
17
18 // Same as above, but only return the real portion, not the imaginary portion
19 #[inline(always)]
20 pub fn single_twiddle_re<T: DctNum>(i: usize, fft_len: usize) -> T {
21 let angle_constant = f64::consts::PI * -2f64 / fft_len as f64;
22
23 let c = (angle_constant * i as f64).cos();
24
25 T::from_f64(c).unwrap()
26 }
27
28 // Same as above, but we add 0.5 to 0 before
29 #[inline(always)]
30 pub fn single_twiddle_halfoffset<T: DctNum>(i: usize, fft_len: usize) -> Complex<T> {
31 let angle_constant = f64::consts::PI * -2f64 / fft_len as f64;
32
33 let c = Complex::from_polar(1f64, angle_constant * (i as f64 + 0.5f64));
34
35 Complex {
36 re: T::from_f64(c.re).unwrap(),
37 im: T::from_f64(c.im).unwrap(),
38 }
39 }
40
41 #[cfg(test)]
42 mod unit_tests {
43 use super::*;
44 use std::f32;
45
46 use crate::test_utils::fuzzy_cmp;
47
48 #[test]
49 fn test_single() {
50 let len = 20;
51
52 for i in 0..len {
53 let single: Complex<f32> = single_twiddle(i, len);
54 let single_inverse: Complex<f32> = single_twiddle(i, len).conj();
55
56 let expected =
57 Complex::from_polar(1f32, -2f32 * f32::consts::PI * i as f32 / len as f32);
58 let expected_inverse =
59 Complex::from_polar(1f32, 2f32 * f32::consts::PI * i as f32 / len as f32);
60
61 assert!(
62 fuzzy_cmp(single.re, expected.re, 0.001f32),
63 "forwards, i = {}",
64 i
65 );
66 assert!(
67 fuzzy_cmp(single.im, expected.im, 0.001f32),
68 "forwards, i = {}",
69 i
70 );
71 assert!(
72 fuzzy_cmp(single_inverse.re, expected_inverse.re, 0.001f32),
73 "inverse, i = {}",
74 i
75 );
76 assert!(
77 fuzzy_cmp(single_inverse.im, expected_inverse.im, 0.001f32),
78 "inverse, i = {}",
79 i
80 );
81 }
82 }
83 }