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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
use block::Chunk;
use log::warn;
use node::{AudioNodeEngine, AudioNodeType, BlockInfo, ChannelInfo};
use num_complex::Complex64;
use std::collections::VecDeque;
use std::sync::Arc;

const MAX_COEFFS: usize = 20;

#[derive(Debug)]
pub struct IIRFilterNodeOptions {
    pub feedforward: Arc<Vec<f64>>,
    pub feedback: Arc<Vec<f64>>,
}

#[derive(Clone)]
struct IIRFilter {
    feedforward: Arc<Vec<f64>>,
    feedback: Arc<Vec<f64>>,
    inputs: VecDeque<f64>,
    outputs: VecDeque<f64>,
}

impl IIRFilter {
    fn new(feedforward: Arc<Vec<f64>>, feedback: Arc<Vec<f64>>) -> Self {
        Self {
            feedforward,
            feedback,
            inputs: VecDeque::with_capacity(MAX_COEFFS),
            outputs: VecDeque::with_capacity(MAX_COEFFS),
        }
    }

    fn calculate_output(&mut self, input: f32) -> f32 {
        self.inputs.push_front(input as f64);

        if self.inputs.len() > MAX_COEFFS {
            self.inputs.pop_back();
        }

        let inputs_sum = self
            .feedforward
            .iter()
            .zip(self.inputs.iter())
            .fold(0.0, |acc, (c, v)| acc + c * v);

        let outputs_sum = self
            .feedback
            .iter()
            .skip(1)
            .zip(self.outputs.iter())
            .fold(0.0, |acc, (c, v)| acc + c * v);

        let output = (inputs_sum - outputs_sum) / self.feedback[0];

        if output.is_nan() {
            // Per spec:
            // Note: The UA may produce a warning to notify the user that NaN values have occurred in the filter state.
            // This is usually indicative of an unstable filter.
            //
            // But idk how to produce warnings
            warn!("NaN in IIRFilter state");
        }

        self.outputs.push_front(output);

        if self.outputs.len() > MAX_COEFFS {
            self.outputs.pop_back();
        }

        output as f32
    }
}

#[derive(AudioNodeCommon)]
pub struct IIRFilterNode {
    channel_info: ChannelInfo,
    filters: Vec<IIRFilter>,
}

impl IIRFilterNode {
    pub fn new(options: IIRFilterNodeOptions, channel_info: ChannelInfo) -> Self {
        debug_assert!(
            options.feedforward.len() > 0,
            "NotSupportedError: feedforward must have at least one coeff"
        );

        debug_assert!(
            options.feedforward.len() <= MAX_COEFFS,
            "NotSupportedError: feedforward max length is {}",
            MAX_COEFFS
        );

        debug_assert!(
            options.feedforward.iter().any(|&v| v != 0.0_f64),
            "InvalidStateError: all coeffs are zero"
        );

        debug_assert!(
            options.feedback.len() > 0,
            "NotSupportedError: feedback must have at least one coeff"
        );

        debug_assert!(
            options.feedback.len() <= MAX_COEFFS,
            "NotSupportedError: feedback max length is {}",
            MAX_COEFFS
        );

        debug_assert!(
            options.feedback[0] != 0.0,
            "InvalidStateError: first feedback coeff must not be zero"
        );

        let filter = IIRFilter::new(options.feedforward.clone(), options.feedback.clone());

        Self {
            filters: vec![filter; channel_info.computed_number_of_channels() as usize],
            channel_info,
        }
    }

    pub fn get_frequency_response(
        feedforward: &[f64],
        feedback: &[f64],
        frequency_hz: &[f32],
        mag_response: &mut [f32],
        phase_response: &mut [f32],
    ) {
        debug_assert!(
            frequency_hz.len() == mag_response.len() && frequency_hz.len() == phase_response.len(),
            "get_frequency_response params are of different length"
        );

        frequency_hz.iter().enumerate().for_each(|(idx, &f)| {
            if f < 0.0 || f >= 1.0 {
                mag_response[idx] = std::f32::NAN;
                phase_response[idx] = std::f32::NAN;
            } else {
                let f = (-f as f64) * std::f64::consts::PI;
                let z = Complex64::new(f64::cos(f), f64::sin(f));
                let numerator = Self::sum(feedforward, z);
                let denominator = Self::sum(feedback, z);

                let response = numerator / denominator;
                mag_response[idx] = response.norm() as f32;
                phase_response[idx] = response.arg() as f32;
            }
        });
    }

    fn sum(coeffs: &[f64], z: Complex64) -> Complex64 {
        coeffs.iter().fold(Complex64::new(0.0, 0.0), |acc, &coeff| {
            acc * z + Complex64::new(coeff, 0.0)
        })
    }
}

impl AudioNodeEngine for IIRFilterNode {
    fn node_type(&self) -> AudioNodeType {
        AudioNodeType::IIRFilterNode
    }

    fn process(&mut self, inputs: Chunk, _info: &BlockInfo) -> Chunk {
        debug_assert!(inputs.len() == 1);

        let mut inputs = if inputs.blocks[0].is_silence() {
            Chunk::explicit_silence()
        } else {
            inputs
        };

        let mut iter = inputs.blocks[0].iter();

        while let Some(mut frame) = iter.next() {
            frame.mutate_with(|sample, chan_idx| {
                *sample = self.filters[chan_idx as usize].calculate_output(*sample);
            });
        }
        inputs
    }
}