Skip to main content

embedded_dsp/
window.rs

1//! Window functions (Hanning, Hamming, Blackman, Bartlett, Welch, Flat-top window generators).
2
3#[allow(unused_imports)]
4use crate::math::FloatMath;
5
6/// Generate Hanning window of length `n`.
7pub fn hanning_f32(dst: &mut [f32]) {
8    let n = dst.len();
9    if n == 0 {
10        return;
11    }
12    if n == 1 {
13        dst[0] = 1.0;
14        return;
15    }
16    let factor = 2.0 * core::f32::consts::PI / ((n - 1) as f32);
17    for i in 0..n {
18        dst[i] = 0.5 * (1.0 - ((i as f32) * factor).cos());
19    }
20}
21
22/// Generate Hamming window of length `n`.
23pub fn hamming_f32(dst: &mut [f32]) {
24    let n = dst.len();
25    if n == 0 {
26        return;
27    }
28    if n == 1 {
29        dst[0] = 1.0;
30        return;
31    }
32    let factor = 2.0 * core::f32::consts::PI / ((n - 1) as f32);
33    for i in 0..n {
34        dst[i] = 0.54 - 0.46 * ((i as f32) * factor).cos();
35    }
36}
37
38/// Generate Blackman window of length `n`.
39pub fn blackman_f32(dst: &mut [f32]) {
40    let n = dst.len();
41    if n == 0 {
42        return;
43    }
44    if n == 1 {
45        dst[0] = 1.0;
46        return;
47    }
48    let factor = 2.0 * core::f32::consts::PI / ((n - 1) as f32);
49    for i in 0..n {
50        let a = (i as f32) * factor;
51        dst[i] = 0.42 - 0.5 * a.cos() + 0.08 * (2.0 * a).cos();
52    }
53}
54
55/// Generate Bartlett (Triangular) window of length `n`.
56pub fn bartlett_f32(dst: &mut [f32]) {
57    let n = dst.len();
58    if n == 0 {
59        return;
60    }
61    if n == 1 {
62        dst[0] = 1.0;
63        return;
64    }
65    let half = ((n - 1) as f32) / 2.0;
66    for i in 0..n {
67        dst[i] = 1.0 - ((i as f32 - half) / half).abs();
68    }
69}
70
71/// Generate Welch parabolic window of length `n`.
72pub fn welch_f32(dst: &mut [f32]) {
73    let n = dst.len();
74    if n == 0 {
75        return;
76    }
77    if n == 1 {
78        dst[0] = 1.0;
79        return;
80    }
81    let half = ((n - 1) as f32) / 2.0;
82    for i in 0..n {
83        let term = (i as f32 - half) / half;
84        dst[i] = 1.0 - term * term;
85    }
86}
87
88/// Generate Flat-top window of length `n`.
89pub fn flattop_f32(dst: &mut [f32]) {
90    let n = dst.len();
91    if n == 0 {
92        return;
93    }
94    if n == 1 {
95        dst[0] = 1.0;
96        return;
97    }
98    let factor = 2.0 * core::f32::consts::PI / ((n - 1) as f32);
99    for i in 0..n {
100        let a = (i as f32) * factor;
101        dst[i] = 0.21557895 - 0.41663158 * a.cos() + 0.277263158 * (2.0 * a).cos()
102            - 0.083578947 * (3.0 * a).cos()
103            + 0.006947368 * (4.0 * a).cos();
104    }
105}
106
107/// Multiply signal elements in-place by window array.
108pub fn apply_window_f32(signal: &mut [f32], window: &[f32]) {
109    let len = signal.len().min(window.len());
110    for i in 0..len {
111        signal[i] *= window[i];
112    }
113}