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
//! An immutable `f32` [`Waveform`] for editing and mixing, next to the 16-bit [`crate::pcm::Pcm`] the speech paths use.
//!
//! * [`Waveform`]: shared, immutable, interleaved `f32` audio. Cloning shares the samples.
//! * Operations return a new waveform: gain, fades, normalise (peak or RMS), ceiling, pan, mono and stereo conversion, slicing.
//! * [`mod@mix`]: sums waveforms with gain and a start offset (the offline mixer's building block).
//! * [`wav`]: read 8, 16, 24 and 32-bit integer and 32 and 64-bit float WAV; write 16-bit, 24-bit and 32-bit float WAV.
//!
//! ```
//! use weirdnet_media::waveform::{FadeCurve, MixSource, WavFormat, Waveform, mix};
//!
//! let kick = Waveform::tone(48_000, 60.0, 4_800, 0.8)?.fade_out(2_400, FadeCurve::EqualPower);
//! let hat = Waveform::tone(48_000, 8_000.0, 1_200, 0.3)?;
//! let bar = mix(&[MixSource::new(&kick), MixSource::new(&hat).with_gain(0.5).at(2_400)])?;
//! let wav = bar.normalize_peak(-1.0)?.to_wav(WavFormat::Float32);
//! assert_eq!(Waveform::from_wav(&wav)?.frames(), bar.frames());
//! # Ok::<(), weirdnet_media::waveform::WaveformError>(())
//! ```
//!
//! Nothing here allocates on a device callback: it is control-thread and offline code.

mod error;
pub mod mix;
mod ops;
mod pcm;
pub mod wav;

pub use error::WaveformError;
pub use mix::{MixSource, add_scaled, mix};
pub use wav::WavFormat;
pub use weirdnet_dsp::FadeCurve;

use std::sync::Arc;

/// Interleaved `f32` audio, nominal range `-1.0..=1.0`. Immutable and cheap to clone, so it is safe to hand to the audio thread.
#[derive(Debug, Clone, PartialEq)]
pub struct Waveform {
    sample_rate: u32,
    channels: u16,
    samples: Arc<[f32]>,
}

impl Waveform {
    /// A waveform from interleaved samples. The sample rate and channel count must be above zero and the sample count a whole
    /// number of frames. Samples are not clamped: a sum can exceed 1.0 until a ceiling is applied.
    pub fn new(sample_rate: u32, channels: u16, samples: impl Into<Arc<[f32]>>) -> Result<Self, WaveformError> {
        let samples = samples.into();
        if sample_rate == 0 {
            return Err(WaveformError::ZeroSampleRate);
        }
        if channels == 0 {
            return Err(WaveformError::ZeroChannels);
        }
        if samples.len() % usize::from(channels) != 0 {
            return Err(WaveformError::UnalignedSamples { samples: samples.len(), channels });
        }
        Ok(Waveform { sample_rate, channels, samples })
    }

    /// `frames` frames of silence.
    pub fn silence(sample_rate: u32, channels: u16, frames: usize) -> Result<Self, WaveformError> {
        Waveform::new(sample_rate, channels, vec![0.0f32; frames * usize::from(channels)])
    }

    /// A mono sine tone, for tests and fixtures. `amplitude` is clamped to `0..=1`.
    pub fn tone(sample_rate: u32, hz: f64, frames: usize, amplitude: f32) -> Result<Self, WaveformError> {
        if !hz.is_finite() {
            return Err(WaveformError::NotFinite("the frequency"));
        }
        let amp = f64::from(amplitude.clamp(0.0, 1.0));
        let samples: Vec<f32> =
            (0..frames).map(|i| (amp * (std::f64::consts::TAU * hz * i as f64 / f64::from(sample_rate.max(1))).sin()) as f32).collect();
        Waveform::new(sample_rate, 1, samples)
    }

    /// Frames per second.
    pub fn sample_rate(&self) -> u32 {
        self.sample_rate
    }

    /// Samples per frame.
    pub fn channels(&self) -> u16 {
        self.channels
    }

    /// The interleaved samples.
    pub fn samples(&self) -> &[f32] {
        &self.samples
    }

    /// The samples, shared (a reference-count bump, no copy).
    pub fn shared_samples(&self) -> Arc<[f32]> {
        Arc::clone(&self.samples)
    }

    /// The number of frames.
    pub fn frames(&self) -> usize {
        self.samples.len() / usize::from(self.channels)
    }

    /// Whether there are no frames.
    pub fn is_empty(&self) -> bool {
        self.samples.is_empty()
    }

    /// The length in seconds.
    pub fn duration_secs(&self) -> f64 {
        self.frames() as f64 / f64::from(self.sample_rate)
    }

    /// Frame `index` (one sample per channel), or `None` past the end.
    pub fn frame(&self, index: usize) -> Option<&[f32]> {
        let ch = usize::from(self.channels);
        self.samples.get(index * ch..(index + 1) * ch)
    }

    /// Whether `other` has the same sample rate and channel count.
    pub fn same_format(&self, other: &Waveform) -> bool {
        self.sample_rate == other.sample_rate && self.channels == other.channels
    }

    /// The largest absolute sample over all channels (linear).
    pub fn peak(&self) -> f32 {
        weirdnet_dsp::peak(&self.samples)
    }

    /// The RMS over all samples of all channels (linear).
    pub fn rms(&self) -> f32 {
        weirdnet_dsp::rms(&self.samples)
    }

    /// The largest absolute sample of one channel, or `None` if the channel does not exist.
    pub fn channel_peak(&self, channel: u16) -> Option<f32> {
        if channel >= self.channels {
            return None;
        }
        let ch = usize::from(self.channels);
        let c = usize::from(channel);
        Some(self.samples.iter().skip(c).step_by(ch).fold(0.0f32, |m, s| if s.is_finite() { m.max(s.abs()) } else { m }))
    }

    /// The same format with new samples (the caller keeps the length a whole number of frames).
    pub(crate) fn with_samples(&self, samples: Vec<f32>) -> Waveform {
        debug_assert_eq!(samples.len() % usize::from(self.channels), 0);
        Waveform { sample_rate: self.sample_rate, channels: self.channels, samples: samples.into() }
    }
}

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

    #[test]
    fn new_checks_the_shape() {
        assert_eq!(Waveform::new(0, 1, vec![0.0]), Err(WaveformError::ZeroSampleRate));
        assert_eq!(Waveform::new(48_000, 0, vec![0.0]), Err(WaveformError::ZeroChannels));
        assert_eq!(Waveform::new(48_000, 2, vec![0.0; 3]), Err(WaveformError::UnalignedSamples { samples: 3, channels: 2 }));
        let w = Waveform::new(48_000, 2, vec![0.0; 4]).unwrap();
        assert_eq!((w.frames(), w.channels(), w.sample_rate()), (2, 2, 48_000));
        assert!(Waveform::new(8000, 1, Vec::<f32>::new()).unwrap().is_empty());
    }

    #[test]
    fn clones_share_the_samples() {
        let w = Waveform::tone(48_000, 440.0, 480, 0.5).unwrap();
        let c = w.clone();
        assert!(std::ptr::eq(w.samples().as_ptr(), c.samples().as_ptr()));
        assert!(Arc::ptr_eq(&w.shared_samples(), &c.shared_samples()));
    }

    #[test]
    fn frames_duration_and_frame_access() {
        let w = Waveform::new(1000, 2, vec![0.1, 0.2, 0.3, 0.4, 0.5, 0.6]).unwrap();
        assert_eq!(w.frames(), 3);
        assert!((w.duration_secs() - 0.003).abs() < 1e-12);
        assert_eq!(w.frame(1), Some(&[0.3, 0.4][..]));
        assert_eq!(w.frame(3), None);
    }

    #[test]
    fn tone_has_the_requested_level_and_frequency() {
        let w = Waveform::tone(48_000, 1000.0, 48_000, 0.5).unwrap();
        assert!((w.peak() - 0.5).abs() < 1e-3);
        assert!((w.rms() - 0.5 * std::f32::consts::FRAC_1_SQRT_2).abs() < 1e-3);
        let crossings = w.samples().windows(2).filter(|p| p[0] < 0.0 && p[1] >= 0.0).count();
        assert!((999..=1001).contains(&crossings), "{crossings} rising zero crossings in one second at 1 kHz");
        assert_eq!(Waveform::tone(48_000, f64::NAN, 10, 1.0), Err(WaveformError::NotFinite("the frequency")));
    }

    #[test]
    fn channel_peak_reads_one_channel() {
        let w = Waveform::new(48_000, 2, vec![0.1, -0.9, 0.5, 0.2]).unwrap();
        assert_eq!(w.channel_peak(0), Some(0.5));
        assert_eq!(w.channel_peak(1), Some(0.9));
        assert_eq!(w.channel_peak(2), None);
        assert_eq!(w.peak(), 0.9);
    }

    #[test]
    fn same_format_compares_rate_and_channels() {
        let a = Waveform::silence(48_000, 2, 4).unwrap();
        assert!(a.same_format(&Waveform::silence(48_000, 2, 9).unwrap()));
        assert!(!a.same_format(&Waveform::silence(44_100, 2, 4).unwrap()));
        assert!(!a.same_format(&Waveform::silence(48_000, 1, 4).unwrap()));
    }
}