weirdnet-media 0.2.0

Weirdnet media processing for clients and nodes: WAV probing and PCM in pure Rust, 16 kHz resampling, silence-aware chunking, long-audio transcription plans, long-text speech plans, SRT/VTT, video frame planning, and a hardened ffmpeg runner with a test fake.
Documentation
//! Gain, fades, normalise, ceiling, pan, channel conversion and slicing. Every operation returns a new [`Waveform`].

use crate::waveform::{Waveform, WaveformError};
use weirdnet_dsp::{FadeCurve, db_to_linear, fade_in, fade_out, linear_to_db};

fn finite(what: &'static str, x: f64) -> Result<(), WaveformError> {
    if x.is_finite() { Ok(()) } else { Err(WaveformError::NotFinite(what)) }
}

impl Waveform {
    /// Multiplies every sample by `gain` (negative inverts the polarity). Gain `1.0` returns a clone that shares the samples.
    pub fn gain_linear(&self, gain: f32) -> Result<Waveform, WaveformError> {
        finite("the gain", f64::from(gain))?;
        if gain == 1.0 {
            return Ok(self.clone());
        }
        Ok(self.with_samples(self.samples().iter().map(|s| s * gain).collect()))
    }

    /// Gain in decibels. `0 dB` returns a clone that shares the samples.
    pub fn gain_db(&self, db: f32) -> Result<Waveform, WaveformError> {
        finite("the gain", f64::from(db))?;
        self.gain_linear(db_to_linear(db))
    }

    /// Fades the first `frames` frames in.
    pub fn fade_in(&self, frames: usize, curve: FadeCurve) -> Waveform {
        let mut s = self.samples().to_vec();
        fade_in(&mut s, self.channels(), frames, curve);
        self.with_samples(s)
    }

    /// Fades the last `frames` frames out.
    pub fn fade_out(&self, frames: usize, curve: FadeCurve) -> Waveform {
        let mut s = self.samples().to_vec();
        fade_out(&mut s, self.channels(), frames, curve);
        self.with_samples(s)
    }

    /// Scales so the peak is `target_db` dBFS. Silence (and a waveform with no finite non-zero sample) cannot be scaled and is returned unchanged.
    pub fn normalize_peak(&self, target_db: f32) -> Result<Waveform, WaveformError> {
        finite("the target", f64::from(target_db))?;
        let peak = self.peak();
        if peak == 0.0 {
            return Ok(self.clone());
        }
        self.gain_linear(db_to_linear(target_db) / peak)
    }

    /// Scales so the RMS is `target_db` dBFS. Silence is returned unchanged. The peak may exceed full scale afterwards; follow with [`Waveform::limit_peak`].
    pub fn normalize_rms(&self, target_db: f32) -> Result<Waveform, WaveformError> {
        finite("the target", f64::from(target_db))?;
        let rms = self.rms();
        if rms == 0.0 {
            return Ok(self.clone());
        }
        self.gain_linear(db_to_linear(target_db) / rms)
    }

    /// The ceiling: if the peak is above `ceiling_db` dBFS the whole waveform is scaled down so its peak sits on it, otherwise it is returned
    /// unchanged. This is gain reduction, not clipping, so the shape is kept.
    pub fn limit_peak(&self, ceiling_db: f32) -> Result<Waveform, WaveformError> {
        finite("the ceiling", f64::from(ceiling_db))?;
        let ceiling = db_to_linear(ceiling_db);
        let peak = self.peak();
        if peak <= ceiling {
            return Ok(self.clone());
        }
        self.gain_linear(ceiling / peak)
    }

    /// The peak in dBFS (`-inf` for silence).
    pub fn peak_db(&self) -> f32 {
        linear_to_db(self.peak())
    }

    /// The RMS in dBFS (`-inf` for silence).
    pub fn rms_db(&self) -> f32 {
        linear_to_db(self.rms())
    }

    /// Constant-power balance for a stereo waveform: `pan` from `-1.0` (left) to `1.0` (right). Centre (`0.0`) returns a clone that shares the
    /// samples; off-centre, each side is scaled by `sqrt(2) * cos` or `sin` of the pan angle, so a centred sound keeps unity gain and the total power
    /// stays constant across the sweep. Mono and multichannel waveforms are an error.
    pub fn pan(&self, pan: f32) -> Result<Waveform, WaveformError> {
        finite("the pan", f64::from(pan))?;
        if !(-1.0..=1.0).contains(&pan) {
            return Err(WaveformError::OutOfRange { what: "the pan", min: -1.0, max: 1.0, got: f64::from(pan) });
        }
        if self.channels() != 2 {
            return Err(WaveformError::UnsupportedChannels { operation: "pan", channels: self.channels() });
        }
        if pan == 0.0 {
            return Ok(self.clone());
        }
        let angle = (f64::from(pan) + 1.0) * std::f64::consts::FRAC_PI_4;
        let left = (std::f64::consts::SQRT_2 * angle.cos()) as f32;
        let right = (std::f64::consts::SQRT_2 * angle.sin()) as f32;
        let samples = self.samples().as_chunks::<2>().0.iter().flat_map(|f| [f[0] * left, f[1] * right]).collect::<Vec<f32>>();
        Ok(self.with_samples(samples))
    }

    /// The channels averaged into one. A mono waveform returns a clone.
    pub fn to_mono(&self) -> Waveform {
        let ch = usize::from(self.channels());
        if ch == 1 {
            return self.clone();
        }
        let samples: Vec<f32> = self.samples().chunks_exact(ch).map(|f| f.iter().sum::<f32>() / ch as f32).collect();
        Waveform { sample_rate: self.sample_rate(), channels: 1, samples: std::sync::Arc::from(samples) }
    }

    /// Mono to stereo by copying the channel to both sides. Stereo returns a clone. More than two channels is an error.
    pub fn to_stereo(&self) -> Result<Waveform, WaveformError> {
        match self.channels() {
            2 => Ok(self.clone()),
            1 => {
                let samples: Vec<f32> = self.samples().iter().flat_map(|s| [*s, *s]).collect();
                Ok(Waveform { sample_rate: self.sample_rate(), channels: 2, samples: samples.into() })
            }
            n => Err(WaveformError::UnsupportedChannels { operation: "to_stereo", channels: n }),
        }
    }

    /// The frames in `[start, end)`, clamped to the waveform.
    pub fn slice_frames(&self, start: usize, end: usize) -> Waveform {
        let ch = usize::from(self.channels());
        let total = self.frames();
        let a = start.min(total);
        let b = end.clamp(a, total);
        self.with_samples(self.samples()[a * ch..b * ch].to_vec())
    }
}

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

    fn tone() -> Waveform {
        Waveform::tone(48_000, 440.0, 4800, 0.5).unwrap()
    }

    fn stereo(l: f32, r: f32, frames: usize) -> Waveform {
        Waveform::new(48_000, 2, [l, r].repeat(frames)).unwrap()
    }

    #[test]
    fn gain_scales_and_unity_shares() {
        let w = tone();
        let half = w.gain_linear(0.5).unwrap();
        assert!((half.peak() - w.peak() * 0.5).abs() < 1e-6);
        let same = w.gain_db(0.0).unwrap();
        assert!(std::ptr::eq(w.samples().as_ptr(), same.samples().as_ptr()), "0 dB shares the samples");
        let minus6 = w.gain_db(-6.0206).unwrap();
        assert!((minus6.peak() / w.peak() - 0.5).abs() < 1e-4);
        let inv = w.gain_linear(-1.0).unwrap();
        assert_eq!(inv.samples()[100], -w.samples()[100]);
    }

    #[test]
    fn gain_rejects_non_finite() {
        assert_eq!(tone().gain_linear(f32::NAN), Err(WaveformError::NotFinite("the gain")));
        assert_eq!(tone().gain_db(f32::INFINITY), Err(WaveformError::NotFinite("the gain")));
        assert!(tone().normalize_peak(f32::NAN).is_err());
        assert!(tone().normalize_rms(f32::NAN).is_err());
        assert!(tone().limit_peak(f32::NAN).is_err());
        assert!(stereo(1.0, 1.0, 2).pan(f32::NAN).is_err());
    }

    #[test]
    fn normalize_peak_hits_the_target() {
        let n = tone().normalize_peak(-1.0).unwrap();
        assert!((n.peak_db() + 1.0).abs() < 1e-4);
        let loud = tone().gain_db(12.0).unwrap().normalize_peak(-6.0).unwrap();
        assert!((loud.peak_db() + 6.0).abs() < 1e-4);
    }

    #[test]
    fn normalize_rms_hits_the_target() {
        let n = tone().normalize_rms(-18.0).unwrap();
        assert!((n.rms_db() + 18.0).abs() < 1e-3);
    }

    #[test]
    fn normalising_silence_returns_it_unchanged() {
        let s = Waveform::silence(48_000, 2, 100).unwrap();
        assert_eq!(s.normalize_peak(-1.0).unwrap(), s);
        assert_eq!(s.normalize_rms(-18.0).unwrap(), s);
        assert_eq!(s.peak_db(), f32::NEG_INFINITY);
    }

    #[test]
    fn limit_peak_only_reduces() {
        let loud = tone().gain_db(12.0).unwrap();
        assert!(loud.peak() > 1.0);
        let l = loud.limit_peak(-1.0).unwrap();
        assert!((l.peak_db() + 1.0).abs() < 1e-4);
        let quiet = tone();
        let same = quiet.limit_peak(0.0).unwrap();
        assert!(std::ptr::eq(quiet.samples().as_ptr(), same.samples().as_ptr()), "under the ceiling nothing changes");
        // The shape is kept: the ratio between two samples does not change.
        let r0 = loud.samples()[10] / loud.samples()[20];
        let r1 = l.samples()[10] / l.samples()[20];
        assert!((r0 - r1).abs() < 1e-4);
    }

    #[test]
    fn fades_return_new_waveforms_and_keep_the_original() {
        let w = Waveform::new(48_000, 1, vec![1.0; 8]).unwrap();
        let f = w.fade_in(4, FadeCurve::Linear).fade_out(4, FadeCurve::Linear);
        assert_eq!(w.samples(), &[1.0; 8]);
        assert_eq!(f.samples(), &[0.0, 0.25, 0.5, 0.75, 0.75, 0.5, 0.25, 0.0]);
    }

    #[test]
    fn pan_is_constant_power_with_unity_centre() {
        let w = stereo(0.5, 0.5, 4);
        let centre = w.pan(0.0).unwrap();
        assert!(std::ptr::eq(w.samples().as_ptr(), centre.samples().as_ptr()));
        let hard_left = w.pan(-1.0).unwrap();
        assert!((hard_left.samples()[0] - 0.5 * std::f32::consts::SQRT_2).abs() < 1e-6);
        assert!(hard_left.samples()[1].abs() < 1e-6);
        let hard_right = w.pan(1.0).unwrap();
        assert!(hard_right.samples()[0].abs() < 1e-6);
        assert!((hard_right.samples()[1] - 0.5 * std::f32::consts::SQRT_2).abs() < 1e-6);
        for p in [-0.75f32, -0.3, 0.2, 0.9] {
            let o = w.pan(p).unwrap();
            let power = o.samples()[0].powi(2) + o.samples()[1].powi(2);
            assert!((power - 0.5).abs() < 1e-5, "total power is constant at pan {p}");
        }
    }

    #[test]
    fn pan_needs_stereo_and_a_valid_position() {
        assert_eq!(tone().pan(0.5), Err(WaveformError::UnsupportedChannels { operation: "pan", channels: 1 }));
        assert!(matches!(stereo(1.0, 1.0, 2).pan(1.5), Err(WaveformError::OutOfRange { .. })));
        assert!(matches!(stereo(1.0, 1.0, 2).pan(-1.01), Err(WaveformError::OutOfRange { .. })));
    }

    #[test]
    fn mono_stereo_conversion() {
        let m = tone();
        let s = m.to_stereo().unwrap();
        assert_eq!((s.channels(), s.frames()), (2, m.frames()));
        assert_eq!(s.frame(5), Some(&[m.samples()[5], m.samples()[5]][..]));
        assert_eq!(s.to_mono().samples(), m.samples());
        let lr = Waveform::new(48_000, 2, vec![1.0, -1.0, 0.5, 0.0]).unwrap().to_mono();
        assert_eq!(lr.samples(), &[0.0, 0.25]);
        let three = Waveform::new(48_000, 3, vec![0.0; 6]).unwrap();
        assert_eq!(three.to_stereo(), Err(WaveformError::UnsupportedChannels { operation: "to_stereo", channels: 3 }));
        assert_eq!(three.to_mono().channels(), 1);
    }

    #[test]
    fn slicing_clamps() {
        let w = Waveform::new(48_000, 2, (0..10).map(|i| i as f32).collect::<Vec<_>>()).unwrap();
        assert_eq!(w.slice_frames(1, 3).samples(), &[2.0, 3.0, 4.0, 5.0]);
        assert_eq!(w.slice_frames(3, 100).frames(), 2);
        assert_eq!(w.slice_frames(100, 200).frames(), 0);
        assert_eq!(w.slice_frames(4, 2).frames(), 0, "an end before the start is empty");
    }
}