From 518d94bdf59d496d370cc3237f8afcfc119d9d8b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 19:32:39 -0800 Subject: [PATCH] audio-dsp: a NaN frequency or gain designs a finite biquad Coeffs::design clamped a NaN frequency to NaN, so every coefficient was NaN and the section's output stayed NaN after the next finite sample. A NaN frequency now designs at 1000 Hz, as design::realize does, and a NaN gain at 0 dB. --- crates/audio-dsp/src/biquad.rs | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/crates/audio-dsp/src/biquad.rs b/crates/audio-dsp/src/biquad.rs index 668af6bb5..9adbe9650 100644 --- a/crates/audio-dsp/src/biquad.rs +++ b/crates/audio-dsp/src/biquad.rs @@ -62,9 +62,12 @@ impl Coeffs { /// RBJ cookbook design. `freq` in Hz (clamped below Nyquist), `q` > 0, `gain_db` used by /// peaking and shelving types (shelves use `q` as the shelf "Q", S=1 ≙ Q=1/√2). An unusable - /// rate is replaced as [`crate::sane_sample_rate`] describes. + /// rate is replaced as [`crate::sane_sample_rate`] describes. A NaN `freq` designs at 1000 Hz, + /// as [`crate::design::realize`] does, and a NaN `gain_db` designs at 0 dB. pub fn design(kind: FilterType, sample_rate: f64, freq: f64, q: f64, gain_db: f64) -> Coeffs { let sample_rate = f64::from(crate::sane_sample_rate(sample_rate as f32)); + let freq = if freq.is_nan() { 1000.0 } else { freq }; + let gain_db = if gain_db.is_nan() { 0.0 } else { gain_db }; let f = freq.clamp(1.0, sample_rate * 0.49); let q = q.max(1e-3); let w0 = 2.0 * PI * f / sample_rate; @@ -189,6 +192,20 @@ mod tests { } } + #[test] + fn a_nan_frequency_or_gain_gives_finite_coefficients_and_output() { + for kind in [FilterType::LowPass, FilterType::Peaking, FilterType::HighShelf] { + for (freq, gain) in [(f64::NAN, 6.0), (1000.0, f64::NAN), (f64::NAN, f64::NAN)] { + let c = Coeffs::design(kind, SR, freq, 0.7, gain); + assert!([c.b0, c.b1, c.b2, c.a1, c.a2].iter().all(|v| v.is_finite()), "{kind:?} {freq} {gain}: {c:?}"); + let mut bq = Biquad::new(); + let mut x = sine(440.0, 0.5, SR, 256, 0.0); + bq.process(&c, &mut x); + assert!(x.iter().all(|v| v.is_finite()), "{kind:?} {freq} {gain}: output is not finite"); + } + } + } + #[test] fn peaking_hits_gain_at_center() { let c = Coeffs::design(FilterType::Peaking, SR, 1000.0, 1.0, 6.0);