aboutsummaryrefslogtreecommitdiffstats
path: root/nihav-codec-support/src/dsp/window.rs
blob: eb350e3ecbd319208e8b9312a90cecaad6f31358 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
//! Window generating functions.
use std::f32::consts;

/// Known window types.
#[derive(Debug,Clone,Copy,PartialEq)]
pub enum WindowType {
    /// Simple square window.
    Square,
    /// Simple sine window.
    Sine,
    /// Kaiser-Bessel derived window.
    KaiserBessel(f32),
}

/// Calculates window coefficients for the requested window type and size.
///
/// Set `half` flag to calculate only the first half of the window.
pub fn generate_window(mode: WindowType, scale: f32, size: usize, half: bool, dst: &mut [f32]) {
    match mode {
        WindowType::Square => {
                for n in 0..size { dst[n] = scale; }
            },
        WindowType::Sine => {
                let param = if half {
                        consts::PI / ((2 * size) as f32)
                    } else {
                        consts::PI / (size as f32)
                    };
                for n in 0..size {
                    dst[n] = (((n as f32) + 0.5) * param).sin() * scale;
                }
            },
        WindowType::KaiserBessel(alpha) => {
                let dlen = if half { size as f32 } else { (size as f32) * 0.5 };
                let alpha2 = f64::from((alpha * consts::PI / dlen) * (alpha * consts::PI / dlen));

                let mut kb: Vec<f64> = Vec::with_capacity(size);
                let mut sum = 0.0;
                for n in 0..size {
                    let b = bessel_i0(((n * (size - n)) as f64) * alpha2);
                    sum += b;
                    kb.push(sum);
                }
                sum += 1.0;
                for n in 0..size {
                    dst[n] = (kb[n] / sum).sqrt() as f32;
                }
            },
    };
}

fn bessel_i0(inval: f64) -> f64 {
    let mut val: f64 = 1.0;
    for n in (1..64).rev() {
        val *= inval / f64::from(n * n);
        val += 1.0;
    }
    val
}