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
//! Fades on interleaved audio, in place.

/// The shape of a fade.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum FadeCurve {
    /// Gain moves in a straight line. Fine for declicking.
    #[default]
    Linear,
    /// Constant power: the gain follows a quarter sine, so two crossfaded sounds keep their summed level.
    EqualPower,
}

impl FadeCurve {
    /// The gain at position `t` through a rising fade, `0.0` at the start to `1.0` at the end. `t` is clamped to `0..=1`.
    pub fn gain(self, t: f32) -> f32 {
        let t = if t.is_nan() { 0.0 } else { t.clamp(0.0, 1.0) };
        match self {
            FadeCurve::Linear => t,
            FadeCurve::EqualPower => (t * std::f32::consts::FRAC_PI_2).sin(),
        }
    }
}

/// Fades the first `frames` frames in from silence. `samples` is interleaved with `channels` per frame. A fade longer than the
/// audio covers all of it (and reaches less than full gain); zero frames or zero channels change nothing.
pub fn fade_in(samples: &mut [f32], channels: u16, frames: usize, curve: FadeCurve) {
    let ch = usize::from(channels);
    if ch == 0 || frames == 0 {
        return;
    }
    let total = samples.len() / ch;
    let n = frames.min(total);
    for i in 0..n {
        // Frame i of a fade of `frames` frames: reaches 1.0 on the frame after the last one.
        let g = curve.gain(i as f32 / frames as f32);
        for s in &mut samples[i * ch..(i + 1) * ch] {
            *s *= g;
        }
    }
}

/// Fades the last `frames` frames out to silence. Frame `total - 1` is the quietest and ends at zero gain only for a
/// fade of one frame; otherwise the last frame has gain `1 / frames` (linear), so the sound ends just above silence.
pub fn fade_out(samples: &mut [f32], channels: u16, frames: usize, curve: FadeCurve) {
    let ch = usize::from(channels);
    if ch == 0 || frames == 0 {
        return;
    }
    let total = samples.len() / ch;
    let n = frames.min(total);
    for k in 0..n {
        // k = 0 is the last frame, k = n - 1 the first frame of the fade.
        let frame = total - 1 - k;
        let g = curve.gain(k as f32 / frames as f32);
        for s in &mut samples[frame * ch..(frame + 1) * ch] {
            *s *= g;
        }
    }
}

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

    #[test]
    fn curves_hit_their_ends() {
        for c in [FadeCurve::Linear, FadeCurve::EqualPower] {
            assert_eq!(c.gain(0.0), 0.0);
            assert!((c.gain(1.0) - 1.0).abs() < 1e-6);
            assert_eq!(c.gain(-1.0), 0.0, "clamped");
            assert!((c.gain(2.0) - 1.0).abs() < 1e-6, "clamped");
            assert_eq!(c.gain(f32::NAN), 0.0);
        }
        assert!((FadeCurve::Linear.gain(0.25) - 0.25).abs() < 1e-7);
        assert!((FadeCurve::EqualPower.gain(0.5) - std::f32::consts::FRAC_1_SQRT_2).abs() < 1e-6);
    }

    #[test]
    fn equal_power_crossfade_keeps_power() {
        for i in 0..=20 {
            let t = i as f32 / 20.0;
            let up = FadeCurve::EqualPower.gain(t);
            let down = FadeCurve::EqualPower.gain(1.0 - t);
            assert!((up * up + down * down - 1.0).abs() < 1e-5);
        }
    }

    #[test]
    fn fade_in_ramps_mono() {
        let mut s = vec![1.0f32; 8];
        fade_in(&mut s, 1, 4, FadeCurve::Linear);
        assert_eq!(&s[..4], &[0.0, 0.25, 0.5, 0.75]);
        assert_eq!(&s[4..], &[1.0; 4], "after the fade the sound is untouched");
    }

    #[test]
    fn fade_out_ramps_mono_to_just_above_silence() {
        let mut s = vec![1.0f32; 8];
        fade_out(&mut s, 1, 4, FadeCurve::Linear);
        assert_eq!(&s[..4], &[1.0; 4]);
        assert_eq!(&s[4..], &[0.75, 0.5, 0.25, 0.0]);
    }

    #[test]
    fn fades_move_both_channels_together() {
        let mut s = vec![1.0f32; 8]; // 4 stereo frames
        fade_in(&mut s, 2, 2, FadeCurve::Linear);
        assert_eq!(&s[..4], &[0.0, 0.0, 0.5, 0.5]);
        assert_eq!(&s[4..], &[1.0; 4]);
    }

    #[test]
    fn fade_longer_than_the_audio_covers_it_all() {
        let mut s = vec![1.0f32; 4];
        fade_in(&mut s, 1, 100, FadeCurve::Linear);
        assert!((s[3] - 0.03).abs() < 1e-6);
        let mut e = vec![1.0f32; 0];
        fade_in(&mut e, 1, 10, FadeCurve::Linear);
        fade_out(&mut e, 1, 10, FadeCurve::Linear);
    }

    #[test]
    fn zero_frames_or_channels_change_nothing() {
        let mut s = vec![1.0f32; 4];
        fade_in(&mut s, 1, 0, FadeCurve::Linear);
        fade_out(&mut s, 0, 4, FadeCurve::Linear);
        fade_in(&mut s, 0, 4, FadeCurve::Linear);
        assert_eq!(s, vec![1.0; 4]);
    }
}