Debian Codegraph @

src/lib.rs

raw symbols SCIP
1 //! # biquad
2 //!
3 //! `biquad` is a library for creating second order IIR filters for signal processing based on
4 //! [Biquads](https://en.wikipedia.org/wiki/Digital_biquad_filter). Both a
5 //! Direct Form 1 (DF1) and Direct Form 2 Transposed (DF2T) implementation is
6 //! available, where the DF1 is better used when the filter needs retuning
7 //! online, as it has the property to introduce minimal artifacts under retuning,
8 //! while the DF2T is best used for static filters as it has the least
9 //! computational complexity and best numerical stability.
10 //!
11 //! # Examples
12 //!
13 //! ```
14 //! fn main() {
15 //! use biquad::*;
16 //!
17 //! // Cutoff and sampling frequencies
18 //! let f0 = 10.hz();
19 //! let fs = 1.khz();
20 //!
21 //! // Create coefficients for the biquads
22 //! let coeffs = Coefficients::<f32>::from_params(Type::LowPass, fs, f0, Q_BUTTERWORTH_F32).unwrap();
23 //!
24 //! // Create two different biquads
25 //! let mut biquad1 = DirectForm1::<f32>::new(coeffs);
26 //! let mut biquad2 = DirectForm2Transposed::<f32>::new(coeffs);
27 //!
28 //! let input_vec = vec![0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0];
29 //! let mut output_vec1 = Vec::new();
30 //! let mut output_vec2 = Vec::new();
31 //!
32 //! // Run for all the inputs
33 //! for elem in input_vec {
34 //! output_vec1.push(biquad1.run(elem));
35 //! output_vec2.push(biquad2.run(elem));
36 //! }
37 //! }
38 //! ```
39 //!
40 //! # Errors
41 //!
42 //! `Coefficients::from_params(...)` can error if the cutoff frequency does not adhere to the
43 //! [Nyquist Frequency](https://en.wikipedia.org/wiki/Nyquist_frequency), or if the Q value is
44 //! negative.
45 //!
46 //! `Hertz::from_hz(...)` and `Hertz::from_dt(...)` will error if the frequency is negative.
47 //!
48 //! # Panics
49 //!
50 //! `x.hz()`, `x.khz()`, `x.mhz()`, `x.dt()` will panic for `f32`/`f64` if they are negative.
51 //!
52
53 #![no_std]
54
55 pub mod coefficients;
56 pub mod frequency;
57
58 pub use crate::coefficients::*;
59 pub use crate::frequency::*;
60
61 /// The required functions of a biquad implementation
62 pub trait Biquad<T> {
63 /// A single iteration of a biquad, applying the filtering on the input
64 fn run(&mut self, input: T) -> T;
65
66 /// Updating of coefficients
67 fn update_coefficients(&mut self, new_coefficients: Coefficients<T>);
68
69 /// Updating coefficients and returning the old ones. This is useful to avoid deallocating on the audio thread, since
70 /// the `Coefficients` can then be sent to another thread for deallocation.
71 fn replace_coefficients(&mut self, new_coefficients: Coefficients<T>) -> Coefficients<T>;
72
73 /// Set the internal state of the biquad to 0 without allocation.
74 fn reset_state(&mut self);
75 }
76
77 /// Possible errors
78 #[derive(Copy, Clone, Debug, PartialEq)]
79 pub enum Errors {
80 OutsideNyquist,
81 NegativeQ,
82 NegativeFrequency,
83 }
84
85 /// Internal states and coefficients of the Direct Form 1 form
86 #[derive(Copy, Clone, Debug)]
87 pub struct DirectForm1<T> {
88 y1: T,
89 y2: T,
90 x1: T,
91 x2: T,
92 coeffs: Coefficients<T>,
93 }
94
95 /// Internal states and coefficients of the Direct Form 2 Transposed form
96 #[derive(Copy, Clone, Debug)]
97 pub struct DirectForm2Transposed<T> {
98 pub s1: T,
99 pub s2: T,
100 coeffs: Coefficients<T>,
101 }
102
103 impl DirectForm1<f32> {
104 /// Creates a Direct Form 1 biquad from a set of filter coefficients
105 pub fn new(coefficients: Coefficients<f32>) -> Self {
106 DirectForm1 {
107 y1: 0.0_f32,
108 y2: 0.0_f32,
109 x1: 0.0_f32,
110 x2: 0.0_f32,
111 coeffs: coefficients,
112 }
113 }
114 }
115
116 impl Biquad<f32> for DirectForm1<f32> {
117 fn run(&mut self, input: f32) -> f32 {
118 let out = self.coeffs.b0 * input + self.coeffs.b1 * self.x1 + self.coeffs.b2 * self.x2
119 - self.coeffs.a1 * self.y1
120 - self.coeffs.a2 * self.y2;
121
122 self.x2 = self.x1;
123 self.x1 = input;
124 self.y2 = self.y1;
125 self.y1 = out;
126
127 out
128 }
129
130 fn update_coefficients(&mut self, new_coefficients: Coefficients<f32>) {
131 self.coeffs = new_coefficients;
132 }
133
134 fn replace_coefficients(&mut self, new_coefficients: Coefficients<f32>) -> Coefficients<f32> {
135 core::mem::replace(&mut self.coeffs, new_coefficients)
136 }
137
138 fn reset_state(&mut self) {
139 self.x1 = 0.;
140 self.x2 = 0.;
141 self.y1 = 0.;
142 self.y2 = 0.;
143 }
144 }
145
146 impl DirectForm1<f64> {
147 /// Creates a Direct Form 1 biquad from a set of filter coefficients
148 pub fn new(coefficients: Coefficients<f64>) -> Self {
149 DirectForm1 {
150 y1: 0.0_f64,
151 y2: 0.0_f64,
152 x1: 0.0_f64,
153 x2: 0.0_f64,
154 coeffs: coefficients,
155 }
156 }
157 }
158
159 impl Biquad<f64> for DirectForm1<f64> {
160 fn run(&mut self, input: f64) -> f64 {
161 let out = self.coeffs.b0 * input + self.coeffs.b1 * self.x1 + self.coeffs.b2 * self.x2
162 - self.coeffs.a1 * self.y1
163 - self.coeffs.a2 * self.y2;
164
165 self.x2 = self.x1;
166 self.x1 = input;
167 self.y2 = self.y1;
168 self.y1 = out;
169
170 out
171 }
172
173 fn update_coefficients(&mut self, new_coefficients: Coefficients<f64>) {
174 self.coeffs = new_coefficients;
175 }
176
177 fn replace_coefficients(&mut self, new_coefficients: Coefficients<f64>) -> Coefficients<f64> {
178 core::mem::replace(&mut self.coeffs, new_coefficients)
179 }
180
181 fn reset_state(&mut self) {
182 self.x1 = 0.;
183 self.x2 = 0.;
184 self.y1 = 0.;
185 self.y2 = 0.;
186 }
187 }
188
189 impl DirectForm2Transposed<f32> {
190 /// Creates a Direct Form 2 Transposed biquad from a set of filter coefficients
191 pub fn new(coefficients: Coefficients<f32>) -> Self {
192 DirectForm2Transposed {
193 s1: 0.0_f32,
194 s2: 0.0_f32,
195 coeffs: coefficients,
196 }
197 }
198 }
199
200 impl Biquad<f32> for DirectForm2Transposed<f32> {
201 fn run(&mut self, input: f32) -> f32 {
202 let out = self.s1 + self.coeffs.b0 * input;
203 self.s1 = self.s2 + self.coeffs.b1 * input - self.coeffs.a1 * out;
204 self.s2 = self.coeffs.b2 * input - self.coeffs.a2 * out;
205
206 out
207 }
208
209 fn update_coefficients(&mut self, new_coefficients: Coefficients<f32>) {
210 self.coeffs = new_coefficients;
211 }
212
213 fn replace_coefficients(&mut self, new_coefficients: Coefficients<f32>) -> Coefficients<f32> {
214 core::mem::replace(&mut self.coeffs, new_coefficients)
215 }
216
217 fn reset_state(&mut self) {
218 self.s1 = 0.;
219 self.s2 = 0.;
220 }
221 }
222
223 impl DirectForm2Transposed<f64> {
224 /// Creates a Direct Form 2 Transposed biquad from a set of filter coefficients
225 pub fn new(coefficients: Coefficients<f64>) -> Self {
226 DirectForm2Transposed {
227 s1: 0.0_f64,
228 s2: 0.0_f64,
229 coeffs: coefficients,
230 }
231 }
232 }
233
234 impl Biquad<f64> for DirectForm2Transposed<f64> {
235 fn run(&mut self, input: f64) -> f64 {
236 let out = self.s1 + self.coeffs.b0 * input;
237 self.s1 = self.s2 + self.coeffs.b1 * input - self.coeffs.a1 * out;
238 self.s2 = self.coeffs.b2 * input - self.coeffs.a2 * out;
239
240 out
241 }
242
243 fn update_coefficients(&mut self, new_coefficients: Coefficients<f64>) {
244 self.coeffs = new_coefficients;
245 }
246
247 fn replace_coefficients(&mut self, new_coefficients: Coefficients<f64>) -> Coefficients<f64> {
248 core::mem::replace(&mut self.coeffs, new_coefficients)
249 }
250
251 fn reset_state(&mut self) {
252 self.s1 = 0.;
253 self.s2 = 0.;
254 }
255 }
256
257
258 #[cfg(test)]
259 #[macro_use]
260 extern crate std;
261
262 #[cfg(test)]
263 mod tests {
264 use crate::*;
265
266 #[test]
267 fn test_frequency_f32() {
268 let f1 = 10.hz();
269 let f2 = 10.khz();
270 let f3 = 10.mhz();
271 let f4 = 10.dt();
272
273 assert_eq!(f1, Hertz::<f32>::from_hz(10.).unwrap());
274 assert_eq!(f2, Hertz::<f32>::from_hz(10000.).unwrap());
275 assert_eq!(f3, Hertz::<f32>::from_hz(10000000.).unwrap());
276 assert_eq!(f4, Hertz::<f32>::from_hz(0.1).unwrap());
277
278 assert!(f1 < f2);
279 assert!(f3 > f2);
280 assert!(f1 == f1);
281 assert!(f1 != f2);
282 }
283
284 #[test]
285 fn test_frequency_f64() {
286 let f1 = 10.hz();
287 let f2 = 10.khz();
288 let f3 = 10.mhz();
289 let f4 = 10.dt();
290
291 assert_eq!(f1, Hertz::<f64>::from_hz(10.).unwrap());
292 assert_eq!(f2, Hertz::<f64>::from_hz(10000.).unwrap());
293 assert_eq!(f3, Hertz::<f64>::from_hz(10000000.).unwrap());
294 assert_eq!(f4, Hertz::<f64>::from_hz(0.1).unwrap());
295
296 assert!(f1 < f2);
297 assert!(f3 > f2);
298 assert!(f1 == f1);
299 assert!(f1 != f2);
300 }
301
302 #[test]
303 #[should_panic]
304 fn test_frequency_panic() {
305 let _f1 = (-10.0).hz();
306 }
307
308 #[test]
309 fn test_hertz_from_f32() {
310 assert_eq!(
311 Hertz::<f32>::from_dt(1.0).unwrap(),
312 Hertz::<f32>::from_hz(1.0).unwrap()
313 );
314 }
315
316 #[test]
317 fn test_hertz_from_f64() {
318 assert_eq!(
319 Hertz::<f64>::from_dt(1.0).unwrap(),
320 Hertz::<f64>::from_hz(1.0).unwrap()
321 );
322 }
323
324 #[test]
325 fn test_coefficients_normal_f32() {
326 let f0 = 10.hz();
327 let fs = 1.khz();
328
329 let coeffs = Coefficients::<f32>::from_params(Type::LowPass, fs, f0, Q_BUTTERWORTH_F32);
330
331 match coeffs {
332 Ok(_) => {}
333 Err(_) => {
334 panic!("Coefficients creation failed!");
335 }
336 }
337 }
338
339 #[test]
340 fn test_coefficients_normal_f64() {
341 let f0 = 10.hz();
342 let fs = 1.khz();
343
344 let coeffs = Coefficients::<f64>::from_params(Type::LowPass, fs, f0, Q_BUTTERWORTH_F64);
345
346 match coeffs {
347 Ok(_) => {}
348 Err(_) => {
349 panic!("Coefficients creation failed!");
350 }
351 }
352 }
353
354 #[test]
355 fn test_coefficients_fail_flipped_frequencies_f32() {
356 let f0 = 10.hz();
357 let fs = 1.khz();
358
359 let coeffs = Coefficients::<f32>::from_params(Type::LowPass, f0, fs, Q_BUTTERWORTH_F32);
360
361 match coeffs {
362 Ok(_) => {
363 panic!("Should not come here");
364 }
365 Err(e) => {
366 assert_eq!(e, Errors::OutsideNyquist);
367 }
368 }
369 }
370
371 #[test]
372 fn test_coefficients_fail_flipped_frequencies_f64() {
373 let f0 = 10.hz();
374 let fs = 1.khz();
375
376 let coeffs = Coefficients::<f64>::from_params(Type::LowPass, f0, fs, Q_BUTTERWORTH_F64);
377
378 match coeffs {
379 Ok(_) => {
380 panic!("Should not come here");
381 }
382 Err(e) => {
383 assert_eq!(e, Errors::OutsideNyquist);
384 }
385 }
386 }
387
388 #[test]
389 fn test_coefficients_fail_negative_q_f32() {
390 let f0 = 10.hz();
391 let fs = 1.khz();
392
393 let coeffs = Coefficients::<f32>::from_params(Type::LowPass, fs, f0, -1.0);
394
395 match coeffs {
396 Ok(_) => {
397 panic!("Should not come here");
398 }
399 Err(e) => {
400 assert_eq!(e, Errors::NegativeQ);
401 }
402 }
403 }
404
405 #[test]
406 fn test_coefficients_fail_negative_q_f64() {
407 let f0 = 10.hz();
408 let fs = 1.khz();
409
410 let coeffs = Coefficients::<f64>::from_params(Type::LowPass, fs, f0, -1.0);
411
412 match coeffs {
413 Ok(_) => {
414 panic!("Should not come here");
415 }
416 Err(e) => {
417 assert_eq!(e, Errors::NegativeQ);
418 }
419 }
420 }
421
422 #[test]
423 fn test_biquad_zeros_f32() {
424 use std::vec::Vec;
425 //use std::vec::Vec::*;
426
427 let f0 = 10.hz();
428 let fs = 1.khz();
429
430 let coeffs =
431 Coefficients::<f32>::from_params(Type::LowPass, fs, f0, Q_BUTTERWORTH_F32).unwrap();
432
433 let mut biquad1 = DirectForm1::<f32>::new(coeffs);
434 let mut biquad2 = DirectForm2Transposed::<f32>::new(coeffs);
435
436 let input_vec = vec![0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0];
437 let mut output_vec1 = Vec::new();
438 let mut output_vec2 = Vec::new();
439
440 for elem in input_vec {
441 output_vec1.push(biquad1.run(elem));
442 output_vec2.push(biquad2.run(elem));
443 }
444 }
445
446 #[test]
447 fn test_biquad_zeros_f64() {
448 use std::vec::Vec;
449 //use std::vec::Vec::*;
450
451 let f0 = 10.hz();
452 let fs = 1.khz();
453
454 let coeffs =
455 Coefficients::<f64>::from_params(Type::LowPass, fs, f0, Q_BUTTERWORTH_F64).unwrap();
456
457 let mut biquad1 = DirectForm1::<f64>::new(coeffs);
458 let mut biquad2 = DirectForm2Transposed::<f64>::new(coeffs);
459
460 let input_vec = vec![0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0];
461 let mut output_vec1 = Vec::new();
462 let mut output_vec2 = Vec::new();
463
464 for elem in input_vec {
465 output_vec1.push(biquad1.run(elem));
466 output_vec2.push(biquad2.run(elem));
467 }
468 }
469 }