alpha2-audio 0.10.0

Platform-independent audio DSP core for alpha2.
Documentation
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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
#![allow(clippy::cast_possible_truncation, clippy::cast_precision_loss)]

use core::f64::consts::PI;

use crate::{ProcessCtx, Processor, StateBlob, StateError};

/// Lowest frequency a filter renders, in hertz.
pub const MIN_FREQUENCY_HZ: f32 = 10.0;

/// Highest frequency a filter renders, as a fraction of the sample rate.
pub const MAX_FREQUENCY_FRACTION: f32 = 0.49;

/// The resonances a filter renders.
pub const Q_RANGE: core::ops::RangeInclusive<f32> = 0.05..=50.0;

/// Largest gain a peaking or shelving filter renders, in decibels either way.
pub const MAX_PEAKING_GAIN_DB: f32 = 36.0;

/// Common parametric equalizer shapes, by the Audio EQ Cookbook's formulas. The gain belongs to
/// the peaking and shelving shapes; the others ignore it.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum BiquadKind {
    /// Bell-shaped parametric band.
    Peaking,
    /// Second-order low-pass.
    LowPass,
    /// Second-order high-pass.
    HighPass,
    /// Raises or lowers everything below the corner by the gain; half of it at the corner.
    LowShelf,
    /// Raises or lowers everything above the corner by the gain; half of it at the corner.
    HighShelf,
    /// Removes the centre frequency and passes the rest.
    Notch,
    /// Passes the centre frequency at unity and falls away on both sides.
    BandPass,
    /// Passes every frequency at unity and turns the phase through 180 degrees at the centre.
    AllPass,
}

/// Two-channel transposed-direct-form-II biquad.
///
/// Coefficients and recursion are `f64`; samples are `f32`. Low-band poles sit within about
/// `2 * pi * f / rate` of the unit circle, which `f32` cannot resolve (a 10 Hz low-pass at 96 kHz
/// passes DC at +1.2 dB, and at 384 kHz the poles reach the circle). In `f64` every band up to
/// 768 kHz is stable and within 0.1 dB of its design.
///
/// Retuned ([`Processor::control`]), it moves its coefficients in a straight line from those of
/// one control point's settings to those of the next. Every filter on that line is stable.
#[derive(Clone, Debug)]
pub struct Biquad {
    kind: BiquadKind,
    frequency: f32,
    q: f32,
    gain_db: f32,
    sample_rate: u32,
    /// `b0, b1, b2, a1, a2`, normalized by `a0`.
    coefficients: [f64; 5],
    ramp: Option<CoefficientRamp>,
    recent: [Tuning; 2],
    z1: [f64; 2],
    z2: [f64; 2],
}

#[derive(Clone, Copy, Debug)]
struct CoefficientRamp {
    from: [f64; 5],
    change: [f64; 5],
    phase: usize,
}

impl CoefficientRamp {
    fn at(&self, frame: usize) -> [f64; 5] {
        let progress = f64::from(crate::control::progress(self.phase, frame));
        core::array::from_fn(|index| self.from[index] + self.change[index] * progress)
    }
}

#[derive(Clone, Copy, Debug)]
struct Tuning {
    settings: [u32; 3],
    coefficients: [f64; 5],
}

const UNTUNED: Tuning = Tuning {
    settings: [u32::MAX; 3],
    coefficients: [1.0, 0.0, 0.0, 0.0, 0.0],
};

impl Biquad {
    /// Creates a parametric filter.
    ///
    /// [`Processor::prepare`] replaces non-finite parameters with 1 kHz, Q 0.707 and 0 dB, then
    /// clamps them to this module's ranges.
    #[must_use]
    pub fn new(kind: BiquadKind, frequency: f32, q: f32, gain_db: f32) -> Self {
        Self {
            kind,
            frequency,
            q,
            gain_db,
            sample_rate: 0,
            coefficients: [1.0, 0.0, 0.0, 0.0, 0.0],
            ramp: None,
            recent: [UNTUNED; 2],
            z1: [0.0; 2],
            z2: [0.0; 2],
        }
    }

    fn tuned(&mut self, settings: &[f32]) -> [f64; 5] {
        let key = [settings[0], settings[1], settings[2]].map(f32::to_bits);
        if let Some(tuning) = self.recent.iter().find(|tuning| tuning.settings == key) {
            return tuning.coefficients;
        }
        let coefficients = coefficients(
            self.kind,
            settings[0],
            settings[1],
            settings[2],
            self.sample_rate,
        );
        self.recent = [
            self.recent[1],
            Tuning {
                settings: key,
                coefficients,
            },
        ];
        coefficients
    }
}

fn coefficients(
    kind: BiquadKind,
    frequency: f32,
    q: f32,
    gain_db: f32,
    sample_rate: u32,
) -> [f64; 5] {
    // Below about 21 Hz the Nyquist cap falls under the floor; the floor wins so `clamp`
    // cannot panic.
    let ceiling = (sample_rate as f32 * MAX_FREQUENCY_FRACTION).max(MIN_FREQUENCY_HZ);
    let frequency = finite(frequency, 1_000.0).clamp(MIN_FREQUENCY_HZ, ceiling);
    let q = finite(q, 0.707).clamp(*Q_RANGE.start(), *Q_RANGE.end());
    let omega = 2.0 * PI * f64::from(frequency) / f64::from(sample_rate.max(1));
    let (sin, cos) = libm::sincos(omega);
    // 1 - cos(omega) = 2 sin^2(omega / 2), avoiding cancellation at low frequencies.
    let half_sin = libm::sin(omega / 2.0);
    let one_minus_cos = 2.0 * half_sin * half_sin;
    let alpha = sin / (2.0 * f64::from(q));
    let (b0, b1, b2, a0, a1, a2) = match kind {
        BiquadKind::LowPass => (
            one_minus_cos / 2.0,
            one_minus_cos,
            one_minus_cos / 2.0,
            1.0 + alpha,
            -2.0 * cos,
            1.0 - alpha,
        ),
        BiquadKind::HighPass => (
            1.0_f64.midpoint(cos),
            -(1.0 + cos),
            1.0_f64.midpoint(cos),
            1.0 + alpha,
            -2.0 * cos,
            1.0 - alpha,
        ),
        BiquadKind::Peaking => {
            let amplitude = amplitude(gain_db);
            (
                1.0 + alpha * amplitude,
                -2.0 * cos,
                1.0 - alpha * amplitude,
                1.0 + alpha / amplitude,
                -2.0 * cos,
                1.0 - alpha / amplitude,
            )
        }
        BiquadKind::LowShelf => {
            let amplitude = amplitude(gain_db);
            let (above, below) = (amplitude + 1.0, amplitude - 1.0);
            let slope = 2.0 * libm::sqrt(amplitude) * alpha;
            (
                amplitude * (above - below * cos + slope),
                2.0 * amplitude * (below - above * cos),
                amplitude * (above - below * cos - slope),
                above + below * cos + slope,
                -2.0 * (below + above * cos),
                above + below * cos - slope,
            )
        }
        BiquadKind::HighShelf => {
            let amplitude = amplitude(gain_db);
            let (above, below) = (amplitude + 1.0, amplitude - 1.0);
            let slope = 2.0 * libm::sqrt(amplitude) * alpha;
            (
                amplitude * (above + below * cos + slope),
                -2.0 * amplitude * (below + above * cos),
                amplitude * (above + below * cos - slope),
                above - below * cos + slope,
                2.0 * (below - above * cos),
                above - below * cos - slope,
            )
        }
        BiquadKind::Notch => (1.0, -2.0 * cos, 1.0, 1.0 + alpha, -2.0 * cos, 1.0 - alpha),
        BiquadKind::BandPass => (alpha, 0.0, -alpha, 1.0 + alpha, -2.0 * cos, 1.0 - alpha),
        BiquadKind::AllPass => (
            1.0 - alpha,
            -2.0 * cos,
            1.0 + alpha,
            1.0 + alpha,
            -2.0 * cos,
            1.0 - alpha,
        ),
    };
    [b0 / a0, b1 / a0, b2 / a0, a1 / a0, a2 / a0]
}

fn amplitude(gain_db: f32) -> f64 {
    libm::pow(
        10.0,
        f64::from(finite(gain_db, 0.0).clamp(-MAX_PEAKING_GAIN_DB, MAX_PEAKING_GAIN_DB)) / 40.0,
    )
}

impl Biquad {
    pub(crate) fn detect(&mut self, channel: usize, input: f32) -> f32 {
        self.step(channel, input, self.coefficients, true)
    }

    #[inline]
    fn step(&mut self, channel: usize, input: f32, coefficients: [f64; 5], guarded: bool) -> f32 {
        let [b0, b1, b2, a1, a2] = coefficients;
        let input = f64::from(if guarded { finite(input, 0.0) } else { input });
        let value = flush_denormal_f64(input * b0 + self.z1[channel]);
        let z1 = flush_denormal_f64(input * b1 + self.z2[channel] - a1 * value);
        let z2 = flush_denormal_f64(input * b2 - a2 * value);
        let sample = value as f32;
        if guarded && !(sample.is_finite() && z1.is_finite() && z2.is_finite()) {
            self.z1[channel] = 0.0;
            self.z2[channel] = 0.0;
            0.0
        } else {
            self.z1[channel] = z1;
            self.z2[channel] = z2;
            sample
        }
    }

    fn run(&mut self, channel: usize, input: &[f32], output: &mut [f32], guarded: bool) {
        let coefficients = self.coefficients;
        for (&input, output) in input.iter().zip(output.iter_mut()) {
            *output = self.step(channel, input, coefficients, guarded);
        }
    }

    fn run_ramped(
        &mut self,
        ramp: &CoefficientRamp,
        inputs: &[&[f32]],
        outputs: &mut [&mut [f32]],
        (channels, frames): (usize, usize),
        guarded: bool,
    ) {
        for frame in 0..frames {
            let coefficients = ramp.at(frame);
            for channel in 0..channels {
                outputs[channel][frame] =
                    self.step(channel, inputs[channel][frame], coefficients, guarded);
            }
        }
    }

    fn settled(&self, outputs: &[&mut [f32]], channel: usize, frames: usize) -> bool {
        outputs[channel][..frames]
            .iter()
            .all(|sample| sample.is_finite())
            && self.z1[channel].is_finite()
            && self.z2[channel].is_finite()
    }
}

impl Processor for Biquad {
    fn history_samples(&self) -> u32 {
        let a1 = self.coefficients[3];
        let a2 = self.coefficients[4];
        let discriminant = a1 * a1 - 4.0 * a2;
        let radius = if discriminant < 0.0 {
            libm::sqrt(a2.abs())
        } else {
            a1.abs().midpoint(libm::sqrt(discriminant))
        };
        // Extra margin for the polynomial term of a repeated pole.
        crate::processor::settling_samples(radius).saturating_mul(2)
    }

    fn prepare(&mut self, sample_rate: u32, _max_block: usize) {
        self.sample_rate = sample_rate;
        self.coefficients =
            coefficients(self.kind, self.frequency, self.q, self.gain_db, sample_rate);
        self.ramp = None;
        self.recent = [UNTUNED; 2];
    }

    /// The frequency in hertz, the resonance and the gain in decibels.
    fn control_params(&self) -> usize {
        3
    }

    fn control(&mut self, span: &crate::ControlSpan<'_>) {
        if span.from.len() != 3 || span.to.len() != 3 {
            return;
        }
        let from = self.tuned(span.from);
        if span.is_steady() {
            self.coefficients = from;
            self.ramp = None;
            return;
        }
        let to = self.tuned(span.to);
        self.ramp = Some(CoefficientRamp {
            from,
            change: core::array::from_fn(|index| to[index] - from[index]),
            phase: span.phase,
        });
    }

    fn process(&mut self, _ctx: &ProcessCtx, inputs: &[&[f32]], outputs: &mut [&mut [f32]]) {
        let channels = inputs.len().min(outputs.len()).min(2);
        let Some(ramp) = self.ramp else {
            for channel in 0..channels {
                let state = (self.z1[channel], self.z2[channel]);
                self.run(channel, inputs[channel], outputs[channel], false);
                let frames = inputs[channel].len().min(outputs[channel].len());
                // A non-finite or overflowing sample would poison the recursion, so rerun the
                // block with such samples silenced.
                if !self.settled(outputs, channel, frames) {
                    (self.z1[channel], self.z2[channel]) = state;
                    self.run(channel, inputs[channel], outputs[channel], true);
                }
            }
            return;
        };
        let frames = inputs
            .iter()
            .take(channels)
            .map(|input| input.len())
            .chain(outputs.iter().take(channels).map(|output| output.len()))
            .min()
            .unwrap_or(0);
        let state = (self.z1, self.z2);
        self.run_ramped(&ramp, inputs, outputs, (channels, frames), false);
        if !(0..channels).all(|channel| self.settled(outputs, channel, frames)) {
            (self.z1, self.z2) = state;
            self.run_ramped(&ramp, inputs, outputs, (channels, frames), true);
        }
        self.ramp = Some(CoefficientRamp {
            phase: ramp.phase.saturating_add(frames),
            ..ramp
        });
    }

    fn reset(&mut self) {
        self.z1 = [0.0; 2];
        self.z2 = [0.0; 2];
    }
    fn save_state(&self) -> StateBlob {
        let mut bytes = Vec::with_capacity(32);
        for value in self.z1.into_iter().chain(self.z2) {
            bytes.extend_from_slice(&value.to_le_bytes());
        }
        StateBlob::new(bytes)
    }
    fn load_state(&mut self, state: &StateBlob) -> Result<(), StateError> {
        let bytes: &[u8; 32] = state
            .as_bytes()
            .try_into()
            .map_err(|_| StateError::Mismatch)?;
        let values: [f64; 4] = core::array::from_fn(|index| {
            f64::from_le_bytes(
                bytes[index * 8..index * 8 + 8]
                    .try_into()
                    .expect("fixed range"),
            )
        });
        if values.iter().any(|value| !value.is_finite()) {
            return Err(StateError::Invalid);
        }
        self.z1 = [values[0], values[1]];
        self.z2 = [values[2], values[3]];
        Ok(())
    }
}

fn finite(value: f32, fallback: f32) -> f32 {
    if value.is_finite() { value } else { fallback }
}
pub(crate) fn flush_denormal(value: f32) -> f32 {
    if value.abs() < 1.0e-30 { 0.0 } else { value }
}
/// [`flush_denormal`] for the `f64` state, so a decayed tail never reaches subnormal values.
fn flush_denormal_f64(value: f64) -> f64 {
    if value.abs() < 1.0e-30 { 0.0 } else { value }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]

    use super::{Biquad, BiquadKind};
    use crate::{ProcessCtx, Processor, TransportState};

    /// Project rates (8 to 96 kHz) and `AudioWorklet` rates (3 to 768 kHz).
    const RATES: [u32; 11] = [
        3_000, 8_000, 11_025, 22_050, 44_100, 48_000, 88_200, 96_000, 192_000, 384_000, 768_000,
    ];

    /// The radius of the filter's larger pole.
    fn pole_radius(filter: &Biquad) -> f64 {
        let a1 = filter.coefficients[3];
        let a2 = filter.coefficients[4];
        let discriminant = a1 * a1 - 4.0 * a2;
        if discriminant < 0.0 {
            libm::sqrt(a2.abs())
        } else {
            a1.abs().midpoint(libm::sqrt(discriminant))
        }
    }

    fn run(filter: &mut Biquad, rate: u32, input: &[f32]) -> Vec<f32> {
        let mut output = vec![0.0; input.len()];
        for (block, (input, output)) in input.chunks(128).zip(output.chunks_mut(128)).enumerate() {
            let sample_position = i64::try_from(block * 128).expect("position");
            let ctx = ProcessCtx {
                position: alpha2_time::MediaTime(0),
                sample_position,
                sample_rate: rate,
                transport: TransportState::Playing,
            };
            filter.process(&ctx, &[input], &mut [output]);
        }
        output
    }

    /// Measured gain in dB where the ideal is exact: low-pass at DC, high-pass at Nyquist, and a
    /// peaking band at its centre.
    fn measured_gain_db(kind: BiquadKind, frequency: f32, q: f32, gain_db: f32, rate: u32) -> f64 {
        let mut filter = Biquad::new(kind, frequency, q, gain_db);
        filter.prepare(rate, 128);
        // Long enough for the slower pole to fall by e^-20, then a second of signal to measure.
        let settle = libm::ceil(20.0 / -libm::log(pole_radius(&filter))) as usize;
        let measure = rate as usize;
        let input: Vec<f32> = (0..settle + measure)
            .map(|index| match kind {
                BiquadKind::LowPass => 0.25,
                BiquadKind::HighPass => {
                    if index % 2 == 0 {
                        0.25
                    } else {
                        -0.25
                    }
                }
                _ => {
                    let phase = core::f64::consts::TAU * f64::from(frequency) * index as f64
                        / f64::from(rate);
                    (0.25 * libm::sin(phase)) as f32
                }
            })
            .collect();
        let output = run(&mut filter, rate, &input);
        let energy = |samples: &[f32]| {
            samples
                .iter()
                .map(|sample| f64::from(*sample) * f64::from(*sample))
                .sum::<f64>()
        };
        // No phase shift at a peaking band's centre, so energies compare exactly.
        10.0 * libm::log10(energy(&output[settle..]) / energy(&input[settle..]))
    }

    #[test]
    fn every_filter_is_stable_and_accurate_at_every_rate() {
        let mut failures = Vec::new();
        for rate in RATES {
            for kind in [
                BiquadKind::LowPass,
                BiquadKind::HighPass,
                BiquadKind::Peaking,
            ] {
                for frequency in [10.0, 20.0, 40.0] {
                    for q in [0.05, 0.5, 0.707, 1.0, 4.0, 50.0] {
                        let mut filter = Biquad::new(kind, frequency, q, 12.0);
                        filter.prepare(rate, 128);
                        let radius = pole_radius(&filter);
                        if radius >= 1.0 {
                            failures.push(format!(
                                "{rate} Hz {kind:?} {frequency} Hz Q {q}: pole radius {radius}"
                            ));
                            continue;
                        }
                        // Extreme resonances settle too slowly; their poles are checked above.
                        if !(0.5..=4.0).contains(&q) {
                            continue;
                        }
                        let expected = if kind == BiquadKind::Peaking {
                            12.0
                        } else {
                            0.0
                        };
                        let gain = measured_gain_db(kind, frequency, q, 12.0, rate);
                        if (gain - expected).abs() > 0.1 {
                            failures.push(format!(
                                "{rate} Hz {kind:?} {frequency} Hz Q {q}: {gain:.3} dB, not {expected} dB"
                            ));
                        }
                    }
                }
            }
        }
        assert!(failures.is_empty(), "{}", failures.join("\n"));
    }
    const NEW_KINDS: [BiquadKind; 5] = [
        BiquadKind::LowShelf,
        BiquadKind::HighShelf,
        BiquadKind::Notch,
        BiquadKind::BandPass,
        BiquadKind::AllPass,
    ];

    fn magnitude_and_phase(filter: &Biquad, omega: f64) -> (f64, f64) {
        let [b0, b1, b2, a1, a2] = filter.coefficients;
        let (sin, cos) = libm::sincos(omega);
        let (sin2, cos2) = libm::sincos(2.0 * omega);
        let numerator = (b0 + b1 * cos + b2 * cos2, -(b1 * sin + b2 * sin2));
        let denominator = (1.0 + a1 * cos + a2 * cos2, -(a1 * sin + a2 * sin2));
        let size = |value: (f64, f64)| libm::sqrt(value.0 * value.0 + value.1 * value.1);
        let angle = |value: (f64, f64)| libm::atan2(value.1, value.0);
        (
            size(numerator) / size(denominator),
            angle(numerator) - angle(denominator),
        )
    }

    fn db(magnitude: f64) -> f64 {
        20.0 * libm::log10(magnitude)
    }

    fn settled_gain_db_at_a_48th_of_the_rate(filter: &mut Biquad, rate: u32) -> f64 {
        let settle = (filter.history_samples() as usize).div_ceil(48) * 48;
        let input: Vec<f32> = (0..settle + 4_800)
            .map(|index| {
                let phase = core::f64::consts::TAU * (index % 48) as f64 / 48.0;
                (0.25 * libm::sin(phase)) as f32
            })
            .collect();
        let output = run(filter, rate, &input);
        let energy = |samples: &[f32]| {
            samples
                .iter()
                .map(|sample| f64::from(*sample) * f64::from(*sample))
                .sum::<f64>()
        };
        10.0 * libm::log10(energy(&output[settle..]) / energy(&input[settle..]))
    }

    #[test]
    fn each_filter_shape_has_its_response() {
        const GAIN_DB: f64 = 9.0;
        let mut failures = Vec::new();
        for rate in [44_100_u32, 48_000, 96_000] {
            let corner = rate as f32 / 48.0;
            let omega = core::f64::consts::TAU / 48.0;
            for kind in NEW_KINDS {
                let mut filter = Biquad::new(kind, corner, core::f32::consts::FRAC_1_SQRT_2, 9.0);
                filter.prepare(rate, 128);
                let at = |omega: f64| db(magnitude_and_phase(&filter, omega).0);
                let (dc, centre, nyquist) = (at(0.0), at(omega), at(core::f64::consts::PI));
                let close = |found: f64, expected: f64| (found - expected).abs() <= 0.01;
                let shaped = match kind {
                    BiquadKind::LowShelf => {
                        close(dc, GAIN_DB) && close(centre, GAIN_DB / 2.0) && close(nyquist, 0.0)
                    }
                    BiquadKind::HighShelf => {
                        close(dc, 0.0) && close(centre, GAIN_DB / 2.0) && close(nyquist, GAIN_DB)
                    }
                    BiquadKind::Notch => close(dc, 0.0) && centre < -100.0 && close(nyquist, 0.0),
                    BiquadKind::BandPass => {
                        dc < -100.0
                            && close(centre, 0.0)
                            && nyquist < -100.0
                            && at(omega / 2.0) < -1.0
                            && at(omega * 2.0) < -1.0
                    }
                    _ => [0.0, omega / 3.0, omega, 2.0, core::f64::consts::PI]
                        .into_iter()
                        .all(|omega| (magnitude_and_phase(&filter, omega).0 - 1.0).abs() <= 1e-9),
                };
                if !shaped {
                    failures.push(format!(
                        "{rate} Hz {kind:?}: {dc:.3} dB at DC, {centre:.3} dB at the corner, \
                         {nyquist:.3} dB at Nyquist"
                    ));
                }
                if kind != BiquadKind::Notch {
                    let measured = settled_gain_db_at_a_48th_of_the_rate(&mut filter, rate);
                    if (measured - centre).abs() > 0.01 {
                        failures.push(format!(
                            "{rate} Hz {kind:?}: the running filter gives {measured:.4} dB at \
                             its corner, its transfer function {centre:.4} dB"
                        ));
                    }
                }
            }
        }
        assert!(failures.is_empty(), "{}", failures.join("\n"));
    }

    #[test]
    fn an_all_pass_changes_phase_only() {
        for rate in [44_100_u32, 48_000, 96_000] {
            let mut filter = Biquad::new(BiquadKind::AllPass, 1_000.0, 0.7, 0.0);
            filter.prepare(rate, 128);
            let omega_of = |hertz: f64| core::f64::consts::TAU * hertz / f64::from(rate);
            let mut hertz = 20.0;
            while hertz <= 20_000.0 {
                let magnitude = magnitude_and_phase(&filter, omega_of(hertz)).0;
                assert!(
                    (magnitude - 1.0).abs() <= 1e-9,
                    "{rate} Hz: magnitude {magnitude} at {hertz} Hz"
                );
                hertz *= 1.1;
            }
            let phase = magnitude_and_phase(&filter, omega_of(1_000.0))
                .1
                .to_degrees();
            let turned = (phase + 180.0).rem_euclid(360.0);
            assert!(
                turned.min(360.0 - turned) <= 1e-6,
                "{rate} Hz: phase {phase} degrees at the corner"
            );
        }
    }

    #[test]
    fn a_notch_at_mains_frequency_removes_a_hum() {
        let rate = 48_000_u32;
        for mains in [50.0_f32, 60.0] {
            let tone = |hertz: f64, frames: usize| -> Vec<f32> {
                (0..frames)
                    .map(|index| {
                        let phase = core::f64::consts::TAU * hertz * index as f64 / f64::from(rate);
                        (0.25 * libm::sin(phase)) as f32
                    })
                    .collect()
            };
            let level_db = |filter: &mut Biquad, hertz: f64| {
                let settle = filter.history_samples() as usize;
                let input = tone(hertz, settle + rate as usize);
                let output = run(filter, rate, &input);
                let energy = |samples: &[f32]| {
                    samples
                        .iter()
                        .map(|sample| f64::from(*sample) * f64::from(*sample))
                        .sum::<f64>()
                };
                10.0 * libm::log10(energy(&output[settle..]) / energy(&input[settle..]))
            };
            let notch = || {
                let mut filter = Biquad::new(BiquadKind::Notch, mains, 10.0, 0.0);
                filter.prepare(rate, 128);
                filter
            };
            let hum = level_db(&mut notch(), f64::from(mains));
            let speech = level_db(&mut notch(), 1_000.0);
            assert!(hum <= -60.0, "{mains} Hz hum is at {hum:.1} dB");
            assert!(
                speech.abs() <= 0.01,
                "1 kHz is at {speech:.4} dB past a {mains} Hz notch"
            );
        }
    }

    #[test]
    fn every_new_shape_is_stable_at_every_rate() {
        for rate in RATES {
            for kind in NEW_KINDS {
                for frequency in [10.0, 1_000.0, 20_000.0] {
                    for q in [0.05, 0.707, 50.0] {
                        for gain_db in [-36.0, 0.0, 36.0] {
                            let mut filter = Biquad::new(kind, frequency, q, gain_db);
                            filter.prepare(rate, 128);
                            let radius = pole_radius(&filter);
                            assert!(
                                radius < 1.0,
                                "{rate} Hz {kind:?} {frequency} Hz Q {q} {gain_db} dB: pole \
                                 radius {radius}"
                            );
                        }
                    }
                }
            }
        }
    }
}