forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBcfa93c0Tahinli3 months ago1659 commits

window.rs258 lines, 8.2 KiBHistoryRawDownload
1//! Analysis/synthesis windows for the lapped transforms.
2//!
3//! All three shapes here satisfy the Princen-Bradley condition
4//! `w[n]^2 + w[n + N]^2 == 1`, which is what makes MDCT overlap-add
5//! reconstruct exactly; [`Window::princen_bradley_error`] measures it.
6//!
7//! - [`Window::sine`] — MP3, AAC's other long window, CELT's basis.
8//! - [`Window::kbd`] — AAC's Kaiser-Bessel-derived window (alpha 4 for long
9//! blocks, 6 for short, per ISO/IEC 14496-3).
10//! - [`Window::vorbis`] — the Vorbis I "slope" window, also used by Opus.
11//!
12//! Codecs that need asymmetric start/stop windows build them from the halves
13//! of two of these; nothing here presumes a symmetric block.
14
15use crate::Real;
16
17/// A precomputed window, one value per sample of the transform block.
18///
19/// ```
20/// use ec_dsp::Window;
21///
22/// let w = Window::<f64>::kbd(2048, 4.0);
23/// assert_eq!(w.len(), 2048);
24/// assert!(w.princen_bradley_error() < 1e-12);
25/// ```
26#[derive(Clone, Debug, PartialEq)]
27pub struct Window<T: Real> {
28 samples: Vec<T>,
29}
30
31impl<T: Real> Window<T> {
32 /// Wraps precomputed values, for shapes this module does not provide
33 /// (asymmetric transition windows, for instance).
34 ///
35 /// # Panics
36 /// If `samples` is empty or has odd length.
37 pub fn from_samples(samples: Vec<T>) -> Window<T> {
38 assert!(
39 !samples.is_empty() && samples.len().is_multiple_of(2),
40 "a window must have an even, non-zero length"
41 );
42 Window { samples }
43 }
44
45 /// Sine window: `w[n] = sin(pi/L (n + 1/2))`, `L` the full window length.
46 ///
47 /// # Panics
48 /// If `len` is zero or odd.
49 pub fn sine(len: usize) -> Window<T> {
50 Window::from_samples(
51 (0..len)
52 .map(|n| {
53 let a = core::f64::consts::PI / len as f64 * (n as f64 + 0.5);
54 T::from_f64(a.sin())
55 })
56 .collect(),
57 )
58 }
59
60 /// Vorbis window: `w[n] = sin(pi/2 * sin^2(pi/L (n + 1/2)))`.
61 ///
62 /// # Panics
63 /// If `len` is zero or odd.
64 pub fn vorbis(len: usize) -> Window<T> {
65 Window::from_samples(
66 (0..len)
67 .map(|n| {
68 let inner = (core::f64::consts::PI / len as f64 * (n as f64 + 0.5)).sin();
69 T::from_f64((core::f64::consts::FRAC_PI_2 * inner * inner).sin())
70 })
71 .collect(),
72 )
73 }
74
75 /// Kaiser-Bessel-derived window with shape parameter `alpha` (AAC uses 4
76 /// for 2048-sample blocks and 6 for 256-sample blocks).
77 ///
78 /// Built the defining way: a Kaiser window of `len/2 + 1` points,
79 /// cumulatively summed and square-rooted, then mirrored — which is what
80 /// makes the Princen-Bradley identity hold by construction rather than by
81 /// numerical luck.
82 ///
83 /// # Panics
84 /// If `len` is not a positive multiple of 4, or `alpha` is negative.
85 pub fn kbd(len: usize, alpha: f64) -> Window<T> {
86 assert!(
87 len >= 4 && len.is_multiple_of(4),
88 "a kbd window needs a length that is a positive multiple of 4, got {len}"
89 );
90 assert!(alpha >= 0.0, "kbd alpha must be non-negative, got {alpha}");
91 let half = len / 2;
92 let beta = core::f64::consts::PI * alpha;
93 let denom = bessel_i0(beta);
94 let mut cumulative = Vec::with_capacity(half + 1);
95 let mut running = 0.0;
96 for m in 0..=half {
97 let ratio = 2.0 * m as f64 / half as f64 - 1.0;
98 running += bessel_i0(beta * (1.0 - ratio * ratio).max(0.0).sqrt()) / denom;
99 cumulative.push(running);
100 }
101 let total = running;
102 let mut samples = vec![T::ZERO; len];
103 for n in 0..half {
104 let v = T::from_f64((cumulative[n] / total).sqrt());
105 samples[n] = v;
106 samples[len - 1 - n] = v;
107 }
108 Window::from_samples(samples)
109 }
110
111 /// The window values.
112 pub fn as_slice(&self) -> &[T] {
113 &self.samples
114 }
115
116 /// Samples in the window.
117 pub fn len(&self) -> usize {
118 self.samples.len()
119 }
120
121 /// Always false — a window cannot be empty (see [`Window::from_samples`]).
122 pub fn is_empty(&self) -> bool {
123 false
124 }
125
126 /// Multiplies `block` by the window in place, vectorised.
127 ///
128 /// # Panics
129 /// If `block.len() != self.len()`.
130 pub fn apply(&self, block: &mut [T]) {
131 assert_eq!(
132 block.len(),
133 self.samples.len(),
134 "block length must equal window length"
135 );
136 let lanes = T::LANES;
137 let mut chunks = block.chunks_exact_mut(lanes);
138 for (chunk, w) in (&mut chunks).zip(self.samples.chunks_exact(lanes)) {
139 T::store(T::load(chunk) * T::load(w), chunk);
140 }
141 let done = self.samples.len() - self.samples.len() % lanes;
142 for (v, w) in chunks
143 .into_remainder()
144 .iter_mut()
145 .zip(&self.samples[done..])
146 {
147 *v = *v * *w;
148 }
149 }
150
151 /// Worst deviation from the Princen-Bradley condition
152 /// `w[n]^2 + w[n + len/2]^2 == 1`, the property MDCT overlap-add needs.
153 pub fn princen_bradley_error(&self) -> f64 {
154 let half = self.samples.len() / 2;
155 (0..half)
156 .map(|n| {
157 let a = self.samples[n].to_f64();
158 let b = self.samples[n + half].to_f64();
159 (a * a + b * b - 1.0).abs()
160 })
161 .fold(0.0, f64::max)
162 }
163}
164
165/// Modified Bessel function of the first kind, order zero, by its power
166/// series — accurate to `f64` for the arguments a KBD window uses (`beta` up
167/// to about 20).
168fn bessel_i0(x: f64) -> f64 {
169 let half = x / 2.0;
170 let mut term = 1.0;
171 let mut sum = 1.0;
172 let mut k = 1.0;
173 while term > 1e-18 * sum {
174 term *= (half / k) * (half / k);
175 sum += term;
176 k += 1.0;
177 if k > 200.0 {
178 break;
179 }
180 }
181 sum
182}
183
184#[cfg(test)]
185mod tests {
186 use super::*;
187
188 #[test]
189 fn all_shapes_satisfy_princen_bradley() {
190 for len in [64usize, 256, 2048] {
191 for (name, w) in [
192 ("sine", Window::<f64>::sine(len)),
193 ("vorbis", Window::<f64>::vorbis(len)),
194 ("kbd-4", Window::<f64>::kbd(len, 4.0)),
195 ("kbd-6", Window::<f64>::kbd(len, 6.0)),
196 ("kbd-0", Window::<f64>::kbd(len, 0.0)),
197 ] {
198 let error = w.princen_bradley_error();
199 assert!(error < 1e-12, "{name} {len}: PB error {error:e}");
200 }
201 }
202 }
203
204 #[test]
205 fn windows_are_symmetric_and_bounded() {
206 let len = 512;
207 for w in [
208 Window::<f64>::sine(len),
209 Window::<f64>::vorbis(len),
210 Window::<f64>::kbd(len, 4.0),
211 ] {
212 let s = w.as_slice();
213 for n in 0..len {
214 assert!((0.0..=1.0).contains(&s[n]), "value out of range: {}", s[n]);
215 assert!(
216 (s[n] - s[len - 1 - n]).abs() < 1e-12,
217 "asymmetric at {n}: {} vs {}",
218 s[n],
219 s[len - 1 - n]
220 );
221 }
222 }
223 }
224
225 #[test]
226 fn bessel_i0_matches_known_values() {
227 // Abramowitz & Stegun table values.
228 for (x, want) in [
229 (0.0, 1.0),
230 (1.0, 1.266_065_877_752_008_4),
231 (5.0, 27.239_871_823_604_44),
232 (10.0, 2_815.716_628_466_254),
233 ] {
234 let got = bessel_i0(x);
235 assert!(
236 (got - want).abs() <= 1e-9 * want.abs().max(1.0),
237 "I0({x}) = {got}, want {want}"
238 );
239 }
240 }
241
242 #[test]
243 fn apply_matches_scalar_multiply() {
244 let len = 262; // not a multiple of the f64 lane count
245 let w = Window::<f64>::sine(len);
246 let block: Vec<f64> = (0..len).map(|n| n as f64 * 0.5 - 3.0).collect();
247 let want: Vec<f64> = block.iter().zip(w.as_slice()).map(|(b, s)| b * s).collect();
248 let mut got = block.clone();
249 w.apply(&mut got);
250 assert_eq!(got, want);
251 }
252
253 #[test]
254 #[should_panic(expected = "multiple of 4")]
255 fn kbd_rejects_odd_lengths() {
256 let _ = Window::<f32>::kbd(30, 4.0);
257 }
258}