Skip to main content

qualia_audio/features/window/
hann.rs

1//! Hann window (periodic / DFT-even convention).
2
3use crate::types::AudioError;
4
5/// Fill `out` with a Hann window of length `out.len()`.
6///
7/// Uses the **periodic** (DFT-even) convention `w[n] = 0.5·(1 − cos(2πn/N))`
8/// with denominator `N = out.len()` (not `N−1`). This is the correct convention
9/// for spectral analysis / overlap-add STFT, where the window tiles seamlessly.
10/// Consequently `w[0] = 0` and, for even `N`, the centre sample `w[N/2] = 1`;
11/// the final sample `w[N−1]` is **not** zero (that is the symmetric convention).
12///
13/// Returns [`AudioError::InvalidParameter`] if `out` is empty.
14#[inline]
15pub fn hann_window(out: &mut [f32]) -> Result<(), AudioError> {
16    etalon_signal::window::hann_window(out).map_err(|_| AudioError::InvalidParameter)
17}
18
19#[cfg(test)]
20mod tests {
21    use super::*;
22
23    #[test]
24    fn endpoint_zero_centre_one() {
25        let mut w = vec![0.0f32; 64];
26        hann_window(&mut w).unwrap();
27        assert!(w[0].abs() < 1e-6, "w[0] = {}", w[0]);
28        assert!((w[32] - 1.0).abs() < 1e-6, "centre = {}", w[32]);
29    }
30
31    #[test]
32    fn symmetric_about_centre() {
33        let mut w = vec![0.0f32; 32];
34        hann_window(&mut w).unwrap();
35        // Periodic window is symmetric about N/2 for n in 1..N.
36        for i in 1..16 {
37            assert!((w[i] - w[32 - i]).abs() < 1e-6);
38        }
39    }
40
41    #[test]
42    fn rejects_empty() {
43        let mut w: [f32; 0] = [];
44        assert_eq!(hann_window(&mut w), Err(AudioError::InvalidParameter));
45    }
46}