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
//! Mixing: summing waveforms with a gain and a start offset.

use crate::waveform::{Waveform, WaveformError};

/// The longest mix [`mix`] builds, in frames (20 minutes at 48 kHz). A guard against an offset typo allocating gigabytes.
pub const MAX_MIX_FRAMES: usize = 48_000 * 60 * 20;

/// One input to [`mix`].
#[derive(Debug, Clone)]
pub struct MixSource<'a> {
    pub waveform: &'a Waveform,
    /// Linear gain applied to this source.
    pub gain: f32,
    /// Where the source starts in the mix, in frames.
    pub offset_frames: usize,
}

impl<'a> MixSource<'a> {
    /// A source at the start of the mix with unity gain.
    pub fn new(waveform: &'a Waveform) -> Self {
        MixSource { waveform, gain: 1.0, offset_frames: 0 }
    }

    /// The same source with a linear gain.
    pub fn with_gain(mut self, gain: f32) -> Self {
        self.gain = gain;
        self
    }

    /// The same source starting `frames` frames in.
    pub fn at(mut self, frames: usize) -> Self {
        self.offset_frames = frames;
        self
    }
}

/// Adds `src * gain` into `dst`, sample by sample over the shorter of the two. No allocation: this is the building block a mixer
/// callback uses. Returns how many samples were added.
pub fn add_scaled(dst: &mut [f32], src: &[f32], gain: f32) -> usize {
    let n = dst.len().min(src.len());
    for (d, s) in dst[..n].iter_mut().zip(&src[..n]) {
        *d += s * gain;
    }
    n
}

/// Sums the sources into one waveform as long as the furthest source end. Sources are added in order, so the result is deterministic.
/// All sources must share the sample rate and channel count; an empty list is an error because the format is unknown. The sum is not
/// clamped (apply a ceiling with [`Waveform::limit_peak`]).
pub fn mix(sources: &[MixSource<'_>]) -> Result<Waveform, WaveformError> {
    let first = sources.first().ok_or(WaveformError::FormatMismatch)?;
    let fmt = first.waveform;
    let mut frames = 0usize;
    for s in sources {
        if !s.waveform.same_format(fmt) {
            return Err(WaveformError::FormatMismatch);
        }
        if !s.gain.is_finite() {
            return Err(WaveformError::NotFinite("a source gain"));
        }
        let end = s.offset_frames.checked_add(s.waveform.frames()).ok_or(WaveformError::TooLong { max_frames: MAX_MIX_FRAMES })?;
        frames = frames.max(end);
    }
    if frames > MAX_MIX_FRAMES {
        return Err(WaveformError::TooLong { max_frames: MAX_MIX_FRAMES });
    }
    let ch = usize::from(fmt.channels());
    let mut out = vec![0.0f32; frames * ch];
    for s in sources {
        let start = s.offset_frames * ch;
        add_scaled(&mut out[start..], s.waveform.samples(), s.gain);
    }
    Waveform::new(fmt.sample_rate(), fmt.channels(), out)
}

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

    fn mono(v: &[f32]) -> Waveform {
        Waveform::new(48_000, 1, v.to_vec()).unwrap()
    }

    #[test]
    fn sums_with_gain_and_offset() {
        let a = mono(&[1.0, 1.0, 1.0]);
        let b = mono(&[0.5, 0.5]);
        let m = mix(&[MixSource::new(&a), MixSource::new(&b).with_gain(2.0).at(2)]).unwrap();
        assert_eq!(m.samples(), &[1.0, 1.0, 2.0, 1.0]);
    }

    #[test]
    fn length_is_the_furthest_end() {
        let a = mono(&[1.0]);
        let m = mix(&[MixSource::new(&a).at(9)]).unwrap();
        assert_eq!(m.frames(), 10);
        assert_eq!(m.samples()[9], 1.0);
        assert_eq!(m.samples()[0], 0.0);
    }

    #[test]
    fn stereo_offsets_are_in_frames() {
        let a = Waveform::new(48_000, 2, vec![1.0, 2.0]).unwrap();
        let m = mix(&[MixSource::new(&a).at(1), MixSource::new(&a)]).unwrap();
        assert_eq!(m.samples(), &[1.0, 2.0, 1.0, 2.0]);
    }

    #[test]
    fn mixing_is_deterministic_and_order_stable() {
        let a = Waveform::tone(48_000, 330.0, 4800, 0.4).unwrap();
        let b = Waveform::tone(48_000, 550.0, 4000, 0.3).unwrap();
        let m1 = mix(&[MixSource::new(&a), MixSource::new(&b).at(100)]).unwrap();
        let m2 = mix(&[MixSource::new(&a), MixSource::new(&b).at(100)]).unwrap();
        assert_eq!(m1, m2);
    }

    #[test]
    fn rejects_mismatches_empty_and_bad_gain() {
        let a = mono(&[1.0]);
        let st = Waveform::new(48_000, 2, vec![0.0, 0.0]).unwrap();
        let slow = Waveform::new(44_100, 1, vec![0.0]).unwrap();
        assert_eq!(mix(&[MixSource::new(&a), MixSource::new(&st)]), Err(WaveformError::FormatMismatch));
        assert_eq!(mix(&[MixSource::new(&a), MixSource::new(&slow)]), Err(WaveformError::FormatMismatch));
        assert_eq!(mix(&[]), Err(WaveformError::FormatMismatch));
        assert_eq!(mix(&[MixSource::new(&a).with_gain(f32::NAN)]), Err(WaveformError::NotFinite("a source gain")));
    }

    #[test]
    fn huge_offsets_are_refused_not_allocated() {
        let a = mono(&[1.0]);
        assert!(matches!(mix(&[MixSource::new(&a).at(usize::MAX)]), Err(WaveformError::TooLong { .. })));
        assert!(matches!(mix(&[MixSource::new(&a).at(MAX_MIX_FRAMES)]), Err(WaveformError::TooLong { .. })));
    }

    #[test]
    fn add_scaled_stops_at_the_shorter_side() {
        let mut dst = [1.0f32, 1.0, 1.0];
        assert_eq!(add_scaled(&mut dst, &[1.0, 1.0], 0.5), 2);
        assert_eq!(dst, [1.5, 1.5, 1.0]);
        assert_eq!(add_scaled(&mut dst, &[], 1.0), 0);
    }
}