mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-26 11:38:08 +00:00
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.
This commit is contained in:
@@ -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);
|
||||
|
||||
Reference in New Issue
Block a user