weirdnet-audio-record 0.2.0

Recording for Weirdnet audio: stems, device outputs and a mix from streams, latency records, take manifests with per-source offsets, gap handling, alignment and re-alignment on export.
Documentation
//! One source's audio, placed by position.
use serde::{Deserialize, Serialize};
use weirdnet_audio_stream::{Frame, StreamInfo};

/// Missing audio, filled with silence.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Gap {
    /// Where, in frames on the session clock.
    pub at: u64,
    /// How long, in frames.
    pub frames: u64,
}

/// A recorded source: interleaved samples starting at a session position.
#[derive(Clone, Debug, PartialEq)]
pub struct Stem {
    /// Channels.
    pub channels: u16,
    /// Sample rate.
    pub sample_rate: u32,
    /// The session position of the first frame.
    pub start: u64,
    /// Interleaved samples.
    pub samples: Vec<f32>,
    /// Gaps filled with silence.
    pub gaps: Vec<Gap>,
}

impl Stem {
    /// Length in frames.
    pub fn frames(&self) -> u64 {
        (self.samples.len() / self.channels.max(1) as usize) as u64
    }

    /// The session position just after the last frame.
    pub fn end(&self) -> u64 {
        self.start + self.frames()
    }
}

/// Builds a [`Stem`] from audio that arrives in blocks.
#[derive(Clone, Debug)]
pub struct StemRecorder {
    stem: Option<Stem>,
    channels: u16,
    sample_rate: u32,
    duplicates: u64,
}

impl StemRecorder {
    /// A recorder for audio of this shape.
    pub fn new(channels: u16, sample_rate: u32) -> Self {
        StemRecorder { stem: None, channels: channels.max(1), sample_rate, duplicates: 0 }
    }

    /// A recorder for a raw PCM f32 stream (its clock rate must be its sample rate).
    pub fn for_stream(info: &StreamInfo) -> Self {
        let ch = info.param("channels").and_then(|c| c.parse().ok()).unwrap_or(2);
        StemRecorder::new(ch, info.clock_rate)
    }

    /// Add interleaved samples whose first frame is at session position `at`. A jump forward is
    /// filled with silence and noted as a gap; frames already recorded are ignored.
    pub fn push(&mut self, at: u64, samples: &[f32]) {
        let ch = self.channels as usize;
        let n = (samples.len() / ch) as u64;
        let stem = self.stem.get_or_insert_with(|| Stem {
            channels: self.channels,
            sample_rate: self.sample_rate,
            start: at,
            samples: Vec::new(),
            gaps: Vec::new(),
        });
        if at < stem.start {
            // before the start: keep only what is new (the start never moves back)
            let skip = (stem.start - at).min(n);
            self.duplicates += skip;
            return Self::push_into(stem, stem.start, &samples[(skip as usize * ch).min(samples.len())..], ch, &mut self.duplicates);
        }
        Self::push_into(stem, at, samples, ch, &mut self.duplicates)
    }

    fn push_into(stem: &mut Stem, at: u64, samples: &[f32], ch: usize, dups: &mut u64) {
        let n = (samples.len() / ch) as u64;
        let end = stem.end();
        if at > end {
            stem.gaps.push(Gap { at: end, frames: at - end });
            stem.samples.resize(stem.samples.len() + ((at - end) as usize * ch), 0.0);
            stem.samples.extend_from_slice(&samples[..n as usize * ch]);
        } else {
            let overlap = (end - at).min(n);
            *dups += overlap;
            stem.samples.extend_from_slice(&samples[overlap as usize * ch..n as usize * ch]);
        }
    }

    /// Add a raw PCM f32 frame; its pts is its session position.
    pub fn push_frame(&mut self, f: &Frame) {
        self.push(f.pts, &f.f32_samples());
    }

    /// Frames ignored because they had been recorded already.
    pub fn duplicates(&self) -> u64 {
        self.duplicates
    }

    /// The stem so far (`None` before any audio).
    pub fn stem(&self) -> Option<&Stem> {
        self.stem.as_ref()
    }

    /// The finished stem (`None` if no audio arrived).
    pub fn finish(self) -> Option<Stem> {
        self.stem
    }
}