Skip to main content

alpha2_audio/
biquad.rs

1#![allow(clippy::cast_possible_truncation, clippy::cast_precision_loss)]
2
3use core::f64::consts::PI;
4
5use crate::{ProcessCtx, Processor, StateBlob, StateError};
6
7/// Lowest frequency a filter renders, in hertz.
8pub const MIN_FREQUENCY_HZ: f32 = 10.0;
9
10/// Highest frequency a filter renders, as a fraction of the sample rate.
11pub const MAX_FREQUENCY_FRACTION: f32 = 0.49;
12
13/// The resonances a filter renders.
14pub const Q_RANGE: core::ops::RangeInclusive<f32> = 0.05..=50.0;
15
16/// Largest gain a peaking or shelving filter renders, in decibels either way.
17pub const MAX_PEAKING_GAIN_DB: f32 = 36.0;
18
19/// Common parametric equalizer shapes, by the Audio EQ Cookbook's formulas. The gain belongs to
20/// the peaking and shelving shapes; the others ignore it.
21#[derive(Copy, Clone, Debug, Eq, PartialEq)]
22pub enum BiquadKind {
23    /// Bell-shaped parametric band.
24    Peaking,
25    /// Second-order low-pass.
26    LowPass,
27    /// Second-order high-pass.
28    HighPass,
29    /// Raises or lowers everything below the corner by the gain; half of it at the corner.
30    LowShelf,
31    /// Raises or lowers everything above the corner by the gain; half of it at the corner.
32    HighShelf,
33    /// Removes the centre frequency and passes the rest.
34    Notch,
35    /// Passes the centre frequency at unity and falls away on both sides.
36    BandPass,
37    /// Passes every frequency at unity and turns the phase through 180 degrees at the centre.
38    AllPass,
39}
40
41/// Two-channel transposed-direct-form-II biquad.
42///
43/// Coefficients and recursion are `f64`; samples are `f32`. Low-band poles sit within about
44/// `2 * pi * f / rate` of the unit circle, which `f32` cannot resolve (a 10 Hz low-pass at 96 kHz
45/// passes DC at +1.2 dB, and at 384 kHz the poles reach the circle). In `f64` every band up to
46/// 768 kHz is stable and within 0.1 dB of its design.
47///
48/// Retuned ([`Processor::control`]), it moves its coefficients in a straight line from those of
49/// one control point's settings to those of the next. Every filter on that line is stable.
50#[derive(Clone, Debug)]
51pub struct Biquad {
52    kind: BiquadKind,
53    frequency: f32,
54    q: f32,
55    gain_db: f32,
56    sample_rate: u32,
57    /// `b0, b1, b2, a1, a2`, normalized by `a0`.
58    coefficients: [f64; 5],
59    ramp: Option<CoefficientRamp>,
60    recent: [Tuning; 2],
61    z1: [f64; 2],
62    z2: [f64; 2],
63}
64
65#[derive(Clone, Copy, Debug)]
66struct CoefficientRamp {
67    from: [f64; 5],
68    change: [f64; 5],
69    phase: usize,
70}
71
72impl CoefficientRamp {
73    fn at(&self, frame: usize) -> [f64; 5] {
74        let progress = f64::from(crate::control::progress(self.phase, frame));
75        core::array::from_fn(|index| self.from[index] + self.change[index] * progress)
76    }
77}
78
79#[derive(Clone, Copy, Debug)]
80struct Tuning {
81    settings: [u32; 3],
82    coefficients: [f64; 5],
83}
84
85const UNTUNED: Tuning = Tuning {
86    settings: [u32::MAX; 3],
87    coefficients: [1.0, 0.0, 0.0, 0.0, 0.0],
88};
89
90impl Biquad {
91    /// Creates a parametric filter.
92    ///
93    /// [`Processor::prepare`] replaces non-finite parameters with 1 kHz, Q 0.707 and 0 dB, then
94    /// clamps them to this module's ranges.
95    #[must_use]
96    pub fn new(kind: BiquadKind, frequency: f32, q: f32, gain_db: f32) -> Self {
97        Self {
98            kind,
99            frequency,
100            q,
101            gain_db,
102            sample_rate: 0,
103            coefficients: [1.0, 0.0, 0.0, 0.0, 0.0],
104            ramp: None,
105            recent: [UNTUNED; 2],
106            z1: [0.0; 2],
107            z2: [0.0; 2],
108        }
109    }
110
111    fn tuned(&mut self, settings: &[f32]) -> [f64; 5] {
112        let key = [settings[0], settings[1], settings[2]].map(f32::to_bits);
113        if let Some(tuning) = self.recent.iter().find(|tuning| tuning.settings == key) {
114            return tuning.coefficients;
115        }
116        let coefficients = coefficients(
117            self.kind,
118            settings[0],
119            settings[1],
120            settings[2],
121            self.sample_rate,
122        );
123        self.recent = [
124            self.recent[1],
125            Tuning {
126                settings: key,
127                coefficients,
128            },
129        ];
130        coefficients
131    }
132}
133
134fn coefficients(
135    kind: BiquadKind,
136    frequency: f32,
137    q: f32,
138    gain_db: f32,
139    sample_rate: u32,
140) -> [f64; 5] {
141    // Below about 21 Hz the Nyquist cap falls under the floor; the floor wins so `clamp`
142    // cannot panic.
143    let ceiling = (sample_rate as f32 * MAX_FREQUENCY_FRACTION).max(MIN_FREQUENCY_HZ);
144    let frequency = finite(frequency, 1_000.0).clamp(MIN_FREQUENCY_HZ, ceiling);
145    let q = finite(q, 0.707).clamp(*Q_RANGE.start(), *Q_RANGE.end());
146    let omega = 2.0 * PI * f64::from(frequency) / f64::from(sample_rate.max(1));
147    let (sin, cos) = libm::sincos(omega);
148    // 1 - cos(omega) = 2 sin^2(omega / 2), avoiding cancellation at low frequencies.
149    let half_sin = libm::sin(omega / 2.0);
150    let one_minus_cos = 2.0 * half_sin * half_sin;
151    let alpha = sin / (2.0 * f64::from(q));
152    let (b0, b1, b2, a0, a1, a2) = match kind {
153        BiquadKind::LowPass => (
154            one_minus_cos / 2.0,
155            one_minus_cos,
156            one_minus_cos / 2.0,
157            1.0 + alpha,
158            -2.0 * cos,
159            1.0 - alpha,
160        ),
161        BiquadKind::HighPass => (
162            1.0_f64.midpoint(cos),
163            -(1.0 + cos),
164            1.0_f64.midpoint(cos),
165            1.0 + alpha,
166            -2.0 * cos,
167            1.0 - alpha,
168        ),
169        BiquadKind::Peaking => {
170            let amplitude = amplitude(gain_db);
171            (
172                1.0 + alpha * amplitude,
173                -2.0 * cos,
174                1.0 - alpha * amplitude,
175                1.0 + alpha / amplitude,
176                -2.0 * cos,
177                1.0 - alpha / amplitude,
178            )
179        }
180        BiquadKind::LowShelf => {
181            let amplitude = amplitude(gain_db);
182            let (above, below) = (amplitude + 1.0, amplitude - 1.0);
183            let slope = 2.0 * libm::sqrt(amplitude) * alpha;
184            (
185                amplitude * (above - below * cos + slope),
186                2.0 * amplitude * (below - above * cos),
187                amplitude * (above - below * cos - slope),
188                above + below * cos + slope,
189                -2.0 * (below + above * cos),
190                above + below * cos - slope,
191            )
192        }
193        BiquadKind::HighShelf => {
194            let amplitude = amplitude(gain_db);
195            let (above, below) = (amplitude + 1.0, amplitude - 1.0);
196            let slope = 2.0 * libm::sqrt(amplitude) * alpha;
197            (
198                amplitude * (above + below * cos + slope),
199                -2.0 * amplitude * (below + above * cos),
200                amplitude * (above + below * cos - slope),
201                above - below * cos + slope,
202                2.0 * (below - above * cos),
203                above - below * cos - slope,
204            )
205        }
206        BiquadKind::Notch => (1.0, -2.0 * cos, 1.0, 1.0 + alpha, -2.0 * cos, 1.0 - alpha),
207        BiquadKind::BandPass => (alpha, 0.0, -alpha, 1.0 + alpha, -2.0 * cos, 1.0 - alpha),
208        BiquadKind::AllPass => (
209            1.0 - alpha,
210            -2.0 * cos,
211            1.0 + alpha,
212            1.0 + alpha,
213            -2.0 * cos,
214            1.0 - alpha,
215        ),
216    };
217    [b0 / a0, b1 / a0, b2 / a0, a1 / a0, a2 / a0]
218}
219
220fn amplitude(gain_db: f32) -> f64 {
221    libm::pow(
222        10.0,
223        f64::from(finite(gain_db, 0.0).clamp(-MAX_PEAKING_GAIN_DB, MAX_PEAKING_GAIN_DB)) / 40.0,
224    )
225}
226
227impl Biquad {
228    pub(crate) fn detect(&mut self, channel: usize, input: f32) -> f32 {
229        self.step(channel, input, self.coefficients, true)
230    }
231
232    #[inline]
233    fn step(&mut self, channel: usize, input: f32, coefficients: [f64; 5], guarded: bool) -> f32 {
234        let [b0, b1, b2, a1, a2] = coefficients;
235        let input = f64::from(if guarded { finite(input, 0.0) } else { input });
236        let value = flush_denormal_f64(input * b0 + self.z1[channel]);
237        let z1 = flush_denormal_f64(input * b1 + self.z2[channel] - a1 * value);
238        let z2 = flush_denormal_f64(input * b2 - a2 * value);
239        let sample = value as f32;
240        if guarded && !(sample.is_finite() && z1.is_finite() && z2.is_finite()) {
241            self.z1[channel] = 0.0;
242            self.z2[channel] = 0.0;
243            0.0
244        } else {
245            self.z1[channel] = z1;
246            self.z2[channel] = z2;
247            sample
248        }
249    }
250
251    fn run(&mut self, channel: usize, input: &[f32], output: &mut [f32], guarded: bool) {
252        let coefficients = self.coefficients;
253        for (&input, output) in input.iter().zip(output.iter_mut()) {
254            *output = self.step(channel, input, coefficients, guarded);
255        }
256    }
257
258    fn run_ramped(
259        &mut self,
260        ramp: &CoefficientRamp,
261        inputs: &[&[f32]],
262        outputs: &mut [&mut [f32]],
263        (channels, frames): (usize, usize),
264        guarded: bool,
265    ) {
266        for frame in 0..frames {
267            let coefficients = ramp.at(frame);
268            for channel in 0..channels {
269                outputs[channel][frame] =
270                    self.step(channel, inputs[channel][frame], coefficients, guarded);
271            }
272        }
273    }
274
275    fn settled(&self, outputs: &[&mut [f32]], channel: usize, frames: usize) -> bool {
276        outputs[channel][..frames]
277            .iter()
278            .all(|sample| sample.is_finite())
279            && self.z1[channel].is_finite()
280            && self.z2[channel].is_finite()
281    }
282}
283
284impl Processor for Biquad {
285    fn history_samples(&self) -> u32 {
286        let a1 = self.coefficients[3];
287        let a2 = self.coefficients[4];
288        let discriminant = a1 * a1 - 4.0 * a2;
289        let radius = if discriminant < 0.0 {
290            libm::sqrt(a2.abs())
291        } else {
292            a1.abs().midpoint(libm::sqrt(discriminant))
293        };
294        // Extra margin for the polynomial term of a repeated pole.
295        crate::processor::settling_samples(radius).saturating_mul(2)
296    }
297
298    fn prepare(&mut self, sample_rate: u32, _max_block: usize) {
299        self.sample_rate = sample_rate;
300        self.coefficients =
301            coefficients(self.kind, self.frequency, self.q, self.gain_db, sample_rate);
302        self.ramp = None;
303        self.recent = [UNTUNED; 2];
304    }
305
306    /// The frequency in hertz, the resonance and the gain in decibels.
307    fn control_params(&self) -> usize {
308        3
309    }
310
311    fn control(&mut self, span: &crate::ControlSpan<'_>) {
312        if span.from.len() != 3 || span.to.len() != 3 {
313            return;
314        }
315        let from = self.tuned(span.from);
316        if span.is_steady() {
317            self.coefficients = from;
318            self.ramp = None;
319            return;
320        }
321        let to = self.tuned(span.to);
322        self.ramp = Some(CoefficientRamp {
323            from,
324            change: core::array::from_fn(|index| to[index] - from[index]),
325            phase: span.phase,
326        });
327    }
328
329    fn process(&mut self, _ctx: &ProcessCtx, inputs: &[&[f32]], outputs: &mut [&mut [f32]]) {
330        let channels = inputs.len().min(outputs.len()).min(2);
331        let Some(ramp) = self.ramp else {
332            for channel in 0..channels {
333                let state = (self.z1[channel], self.z2[channel]);
334                self.run(channel, inputs[channel], outputs[channel], false);
335                let frames = inputs[channel].len().min(outputs[channel].len());
336                // A non-finite or overflowing sample would poison the recursion, so rerun the
337                // block with such samples silenced.
338                if !self.settled(outputs, channel, frames) {
339                    (self.z1[channel], self.z2[channel]) = state;
340                    self.run(channel, inputs[channel], outputs[channel], true);
341                }
342            }
343            return;
344        };
345        let frames = inputs
346            .iter()
347            .take(channels)
348            .map(|input| input.len())
349            .chain(outputs.iter().take(channels).map(|output| output.len()))
350            .min()
351            .unwrap_or(0);
352        let state = (self.z1, self.z2);
353        self.run_ramped(&ramp, inputs, outputs, (channels, frames), false);
354        if !(0..channels).all(|channel| self.settled(outputs, channel, frames)) {
355            (self.z1, self.z2) = state;
356            self.run_ramped(&ramp, inputs, outputs, (channels, frames), true);
357        }
358        self.ramp = Some(CoefficientRamp {
359            phase: ramp.phase.saturating_add(frames),
360            ..ramp
361        });
362    }
363
364    fn reset(&mut self) {
365        self.z1 = [0.0; 2];
366        self.z2 = [0.0; 2];
367    }
368    fn save_state(&self) -> StateBlob {
369        let mut bytes = Vec::with_capacity(32);
370        for value in self.z1.into_iter().chain(self.z2) {
371            bytes.extend_from_slice(&value.to_le_bytes());
372        }
373        StateBlob::new(bytes)
374    }
375    fn load_state(&mut self, state: &StateBlob) -> Result<(), StateError> {
376        let bytes: &[u8; 32] = state
377            .as_bytes()
378            .try_into()
379            .map_err(|_| StateError::Mismatch)?;
380        let values: [f64; 4] = core::array::from_fn(|index| {
381            f64::from_le_bytes(
382                bytes[index * 8..index * 8 + 8]
383                    .try_into()
384                    .expect("fixed range"),
385            )
386        });
387        if values.iter().any(|value| !value.is_finite()) {
388            return Err(StateError::Invalid);
389        }
390        self.z1 = [values[0], values[1]];
391        self.z2 = [values[2], values[3]];
392        Ok(())
393    }
394}
395
396fn finite(value: f32, fallback: f32) -> f32 {
397    if value.is_finite() { value } else { fallback }
398}
399pub(crate) fn flush_denormal(value: f32) -> f32 {
400    if value.abs() < 1.0e-30 { 0.0 } else { value }
401}
402/// [`flush_denormal`] for the `f64` state, so a decayed tail never reaches subnormal values.
403fn flush_denormal_f64(value: f64) -> f64 {
404    if value.abs() < 1.0e-30 { 0.0 } else { value }
405}
406
407#[cfg(test)]
408mod tests {
409    #![allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
410
411    use super::{Biquad, BiquadKind};
412    use crate::{ProcessCtx, Processor, TransportState};
413
414    /// Project rates (8 to 96 kHz) and `AudioWorklet` rates (3 to 768 kHz).
415    const RATES: [u32; 11] = [
416        3_000, 8_000, 11_025, 22_050, 44_100, 48_000, 88_200, 96_000, 192_000, 384_000, 768_000,
417    ];
418
419    /// The radius of the filter's larger pole.
420    fn pole_radius(filter: &Biquad) -> f64 {
421        let a1 = filter.coefficients[3];
422        let a2 = filter.coefficients[4];
423        let discriminant = a1 * a1 - 4.0 * a2;
424        if discriminant < 0.0 {
425            libm::sqrt(a2.abs())
426        } else {
427            a1.abs().midpoint(libm::sqrt(discriminant))
428        }
429    }
430
431    fn run(filter: &mut Biquad, rate: u32, input: &[f32]) -> Vec<f32> {
432        let mut output = vec![0.0; input.len()];
433        for (block, (input, output)) in input.chunks(128).zip(output.chunks_mut(128)).enumerate() {
434            let sample_position = i64::try_from(block * 128).expect("position");
435            let ctx = ProcessCtx {
436                position: alpha2_time::MediaTime(0),
437                sample_position,
438                sample_rate: rate,
439                transport: TransportState::Playing,
440            };
441            filter.process(&ctx, &[input], &mut [output]);
442        }
443        output
444    }
445
446    /// Measured gain in dB where the ideal is exact: low-pass at DC, high-pass at Nyquist, and a
447    /// peaking band at its centre.
448    fn measured_gain_db(kind: BiquadKind, frequency: f32, q: f32, gain_db: f32, rate: u32) -> f64 {
449        let mut filter = Biquad::new(kind, frequency, q, gain_db);
450        filter.prepare(rate, 128);
451        // Long enough for the slower pole to fall by e^-20, then a second of signal to measure.
452        let settle = libm::ceil(20.0 / -libm::log(pole_radius(&filter))) as usize;
453        let measure = rate as usize;
454        let input: Vec<f32> = (0..settle + measure)
455            .map(|index| match kind {
456                BiquadKind::LowPass => 0.25,
457                BiquadKind::HighPass => {
458                    if index % 2 == 0 {
459                        0.25
460                    } else {
461                        -0.25
462                    }
463                }
464                _ => {
465                    let phase = core::f64::consts::TAU * f64::from(frequency) * index as f64
466                        / f64::from(rate);
467                    (0.25 * libm::sin(phase)) as f32
468                }
469            })
470            .collect();
471        let output = run(&mut filter, rate, &input);
472        let energy = |samples: &[f32]| {
473            samples
474                .iter()
475                .map(|sample| f64::from(*sample) * f64::from(*sample))
476                .sum::<f64>()
477        };
478        // No phase shift at a peaking band's centre, so energies compare exactly.
479        10.0 * libm::log10(energy(&output[settle..]) / energy(&input[settle..]))
480    }
481
482    #[test]
483    fn every_filter_is_stable_and_accurate_at_every_rate() {
484        let mut failures = Vec::new();
485        for rate in RATES {
486            for kind in [
487                BiquadKind::LowPass,
488                BiquadKind::HighPass,
489                BiquadKind::Peaking,
490            ] {
491                for frequency in [10.0, 20.0, 40.0] {
492                    for q in [0.05, 0.5, 0.707, 1.0, 4.0, 50.0] {
493                        let mut filter = Biquad::new(kind, frequency, q, 12.0);
494                        filter.prepare(rate, 128);
495                        let radius = pole_radius(&filter);
496                        if radius >= 1.0 {
497                            failures.push(format!(
498                                "{rate} Hz {kind:?} {frequency} Hz Q {q}: pole radius {radius}"
499                            ));
500                            continue;
501                        }
502                        // Extreme resonances settle too slowly; their poles are checked above.
503                        if !(0.5..=4.0).contains(&q) {
504                            continue;
505                        }
506                        let expected = if kind == BiquadKind::Peaking {
507                            12.0
508                        } else {
509                            0.0
510                        };
511                        let gain = measured_gain_db(kind, frequency, q, 12.0, rate);
512                        if (gain - expected).abs() > 0.1 {
513                            failures.push(format!(
514                                "{rate} Hz {kind:?} {frequency} Hz Q {q}: {gain:.3} dB, not {expected} dB"
515                            ));
516                        }
517                    }
518                }
519            }
520        }
521        assert!(failures.is_empty(), "{}", failures.join("\n"));
522    }
523    const NEW_KINDS: [BiquadKind; 5] = [
524        BiquadKind::LowShelf,
525        BiquadKind::HighShelf,
526        BiquadKind::Notch,
527        BiquadKind::BandPass,
528        BiquadKind::AllPass,
529    ];
530
531    fn magnitude_and_phase(filter: &Biquad, omega: f64) -> (f64, f64) {
532        let [b0, b1, b2, a1, a2] = filter.coefficients;
533        let (sin, cos) = libm::sincos(omega);
534        let (sin2, cos2) = libm::sincos(2.0 * omega);
535        let numerator = (b0 + b1 * cos + b2 * cos2, -(b1 * sin + b2 * sin2));
536        let denominator = (1.0 + a1 * cos + a2 * cos2, -(a1 * sin + a2 * sin2));
537        let size = |value: (f64, f64)| libm::sqrt(value.0 * value.0 + value.1 * value.1);
538        let angle = |value: (f64, f64)| libm::atan2(value.1, value.0);
539        (
540            size(numerator) / size(denominator),
541            angle(numerator) - angle(denominator),
542        )
543    }
544
545    fn db(magnitude: f64) -> f64 {
546        20.0 * libm::log10(magnitude)
547    }
548
549    fn settled_gain_db_at_a_48th_of_the_rate(filter: &mut Biquad, rate: u32) -> f64 {
550        let settle = (filter.history_samples() as usize).div_ceil(48) * 48;
551        let input: Vec<f32> = (0..settle + 4_800)
552            .map(|index| {
553                let phase = core::f64::consts::TAU * (index % 48) as f64 / 48.0;
554                (0.25 * libm::sin(phase)) as f32
555            })
556            .collect();
557        let output = run(filter, rate, &input);
558        let energy = |samples: &[f32]| {
559            samples
560                .iter()
561                .map(|sample| f64::from(*sample) * f64::from(*sample))
562                .sum::<f64>()
563        };
564        10.0 * libm::log10(energy(&output[settle..]) / energy(&input[settle..]))
565    }
566
567    #[test]
568    fn each_filter_shape_has_its_response() {
569        const GAIN_DB: f64 = 9.0;
570        let mut failures = Vec::new();
571        for rate in [44_100_u32, 48_000, 96_000] {
572            let corner = rate as f32 / 48.0;
573            let omega = core::f64::consts::TAU / 48.0;
574            for kind in NEW_KINDS {
575                let mut filter = Biquad::new(kind, corner, core::f32::consts::FRAC_1_SQRT_2, 9.0);
576                filter.prepare(rate, 128);
577                let at = |omega: f64| db(magnitude_and_phase(&filter, omega).0);
578                let (dc, centre, nyquist) = (at(0.0), at(omega), at(core::f64::consts::PI));
579                let close = |found: f64, expected: f64| (found - expected).abs() <= 0.01;
580                let shaped = match kind {
581                    BiquadKind::LowShelf => {
582                        close(dc, GAIN_DB) && close(centre, GAIN_DB / 2.0) && close(nyquist, 0.0)
583                    }
584                    BiquadKind::HighShelf => {
585                        close(dc, 0.0) && close(centre, GAIN_DB / 2.0) && close(nyquist, GAIN_DB)
586                    }
587                    BiquadKind::Notch => close(dc, 0.0) && centre < -100.0 && close(nyquist, 0.0),
588                    BiquadKind::BandPass => {
589                        dc < -100.0
590                            && close(centre, 0.0)
591                            && nyquist < -100.0
592                            && at(omega / 2.0) < -1.0
593                            && at(omega * 2.0) < -1.0
594                    }
595                    _ => [0.0, omega / 3.0, omega, 2.0, core::f64::consts::PI]
596                        .into_iter()
597                        .all(|omega| (magnitude_and_phase(&filter, omega).0 - 1.0).abs() <= 1e-9),
598                };
599                if !shaped {
600                    failures.push(format!(
601                        "{rate} Hz {kind:?}: {dc:.3} dB at DC, {centre:.3} dB at the corner, \
602                         {nyquist:.3} dB at Nyquist"
603                    ));
604                }
605                if kind != BiquadKind::Notch {
606                    let measured = settled_gain_db_at_a_48th_of_the_rate(&mut filter, rate);
607                    if (measured - centre).abs() > 0.01 {
608                        failures.push(format!(
609                            "{rate} Hz {kind:?}: the running filter gives {measured:.4} dB at \
610                             its corner, its transfer function {centre:.4} dB"
611                        ));
612                    }
613                }
614            }
615        }
616        assert!(failures.is_empty(), "{}", failures.join("\n"));
617    }
618
619    #[test]
620    fn an_all_pass_changes_phase_only() {
621        for rate in [44_100_u32, 48_000, 96_000] {
622            let mut filter = Biquad::new(BiquadKind::AllPass, 1_000.0, 0.7, 0.0);
623            filter.prepare(rate, 128);
624            let omega_of = |hertz: f64| core::f64::consts::TAU * hertz / f64::from(rate);
625            let mut hertz = 20.0;
626            while hertz <= 20_000.0 {
627                let magnitude = magnitude_and_phase(&filter, omega_of(hertz)).0;
628                assert!(
629                    (magnitude - 1.0).abs() <= 1e-9,
630                    "{rate} Hz: magnitude {magnitude} at {hertz} Hz"
631                );
632                hertz *= 1.1;
633            }
634            let phase = magnitude_and_phase(&filter, omega_of(1_000.0))
635                .1
636                .to_degrees();
637            let turned = (phase + 180.0).rem_euclid(360.0);
638            assert!(
639                turned.min(360.0 - turned) <= 1e-6,
640                "{rate} Hz: phase {phase} degrees at the corner"
641            );
642        }
643    }
644
645    #[test]
646    fn a_notch_at_mains_frequency_removes_a_hum() {
647        let rate = 48_000_u32;
648        for mains in [50.0_f32, 60.0] {
649            let tone = |hertz: f64, frames: usize| -> Vec<f32> {
650                (0..frames)
651                    .map(|index| {
652                        let phase = core::f64::consts::TAU * hertz * index as f64 / f64::from(rate);
653                        (0.25 * libm::sin(phase)) as f32
654                    })
655                    .collect()
656            };
657            let level_db = |filter: &mut Biquad, hertz: f64| {
658                let settle = filter.history_samples() as usize;
659                let input = tone(hertz, settle + rate as usize);
660                let output = run(filter, rate, &input);
661                let energy = |samples: &[f32]| {
662                    samples
663                        .iter()
664                        .map(|sample| f64::from(*sample) * f64::from(*sample))
665                        .sum::<f64>()
666                };
667                10.0 * libm::log10(energy(&output[settle..]) / energy(&input[settle..]))
668            };
669            let notch = || {
670                let mut filter = Biquad::new(BiquadKind::Notch, mains, 10.0, 0.0);
671                filter.prepare(rate, 128);
672                filter
673            };
674            let hum = level_db(&mut notch(), f64::from(mains));
675            let speech = level_db(&mut notch(), 1_000.0);
676            assert!(hum <= -60.0, "{mains} Hz hum is at {hum:.1} dB");
677            assert!(
678                speech.abs() <= 0.01,
679                "1 kHz is at {speech:.4} dB past a {mains} Hz notch"
680            );
681        }
682    }
683
684    #[test]
685    fn every_new_shape_is_stable_at_every_rate() {
686        for rate in RATES {
687            for kind in NEW_KINDS {
688                for frequency in [10.0, 1_000.0, 20_000.0] {
689                    for q in [0.05, 0.707, 50.0] {
690                        for gain_db in [-36.0, 0.0, 36.0] {
691                            let mut filter = Biquad::new(kind, frequency, q, gain_db);
692                            filter.prepare(rate, 128);
693                            let radius = pole_radius(&filter);
694                            assert!(
695                                radius < 1.0,
696                                "{rate} Hz {kind:?} {frequency} Hz Q {q} {gain_db} dB: pole \
697                                 radius {radius}"
698                            );
699                        }
700                    }
701                }
702            }
703        }
704    }
705}