weirdnet-dsp 0.2.0

Weirdnet DSP building blocks: RBJ biquad filters, level helpers (dB, peak, RMS) and fades. Pure functions over slices, no I/O, no allocation per block.
Documentation
//! Level helpers: dB conversion, peak and RMS.

/// Decibels to a linear gain (`0 dB` is `1.0`, `-6.02 dB` is about `0.5`).
pub fn db_to_linear(db: f32) -> f32 {
    10f32.powf(db / 20.0)
}

/// A linear gain to decibels. Zero is `-inf`; the sign is ignored.
pub fn linear_to_db(gain: f32) -> f32 {
    20.0 * gain.abs().log10()
}

/// The largest absolute sample. Non-finite samples count as zero, so one bad sample cannot hide the rest.
pub fn peak(samples: &[f32]) -> f32 {
    samples.iter().fold(0.0f32, |m, s| if s.is_finite() { m.max(s.abs()) } else { m })
}

/// The root mean square of all samples (accumulated in `f64`). Empty input is zero; non-finite samples count as zero.
pub fn rms(samples: &[f32]) -> f32 {
    if samples.is_empty() {
        return 0.0;
    }
    let sum: f64 = samples.iter().map(|s| if s.is_finite() { f64::from(*s) * f64::from(*s) } else { 0.0 }).sum();
    (sum / samples.len() as f64).sqrt() as f32
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn db_round_trip() {
        for db in [-60.0f32, -12.0, -6.0, 0.0, 3.0, 24.0] {
            assert!((linear_to_db(db_to_linear(db)) - db).abs() < 1e-4, "{db}");
        }
        assert!((db_to_linear(0.0) - 1.0).abs() < 1e-7);
        assert!((db_to_linear(-6.0206) - 0.5).abs() < 1e-4);
        assert!((db_to_linear(20.0) - 10.0).abs() < 1e-4);
    }

    #[test]
    fn zero_is_minus_infinity() {
        assert_eq!(linear_to_db(0.0), f32::NEG_INFINITY);
        assert!((linear_to_db(-0.5) - linear_to_db(0.5)).abs() < 1e-7);
    }

    #[test]
    fn peak_and_rms() {
        assert_eq!(peak(&[]), 0.0);
        assert_eq!(peak(&[0.25, -0.75, 0.5]), 0.75);
        assert_eq!(peak(&[0.5, f32::NAN, f32::INFINITY]), 0.5);
        assert_eq!(rms(&[]), 0.0);
        assert!((rms(&[1.0, -1.0, 1.0, -1.0]) - 1.0).abs() < 1e-7);
        let sine: Vec<f32> = (0..48_000).map(|i| (std::f32::consts::TAU * 440.0 * i as f32 / 48_000.0).sin()).collect();
        assert!((rms(&sine) - std::f32::consts::FRAC_1_SQRT_2).abs() < 1e-3, "a full-scale sine has RMS 1/sqrt(2)");
        assert_eq!(rms(&[f32::NAN, 0.0]), 0.0);
    }
}