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
//! A take: stems, their latency records and offsets, alignment and files.
use crate::align::mix;
use crate::stem::{Gap, Stem};
use crate::wav;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::path::Path;
use weirdnet_audio_route::PortLatency;

/// What a source is.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum SourceKind {
    /// A source's own (dry) output.
    Stem,
    /// What a device actually played (a device-output tap).
    DeviceOutput,
    /// A mix recorded as it was heard.
    Mix,
    /// A person's talkback voice: kept beside the music, never in the mix.
    Talkback,
}

/// One source in the manifest.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SourceEntry {
    /// The source's id (for example a port id).
    pub id: String,
    /// What it is.
    pub kind: SourceKind,
    /// Its file in the take folder.
    pub file: String,
    /// Channels.
    pub channels: u16,
    /// Where the raw recording starts on the session clock, frames.
    pub start: u64,
    /// Raw length, frames.
    pub frames: u64,
    /// The latency the source reported or that was measured.
    pub latency: PortLatency,
    /// A manual correction, frames; positive moves the source earlier.
    pub trim: i64,
    /// Gaps filled with silence.
    pub gaps: Vec<Gap>,
    /// An optional group, for example to pair a source's stem with its device output.
    pub group: Option<String>,
}

impl SourceEntry {
    /// How far the source is moved earlier when aligned: its latency plus its trim.
    pub fn offset(&self) -> i64 {
        i64::from(self.latency.frames) + self.trim
    }

    /// Where the aligned source starts on the session clock.
    pub fn aligned_start(&self) -> i64 {
        self.start as i64 - self.offset()
    }
}

/// The take's description, saved as `manifest.json`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Manifest {
    /// The take's name.
    pub take: String,
    /// The sample rate of every source.
    pub sample_rate: u32,
    /// The sources, in the order they were added.
    pub sources: Vec<SourceEntry>,
}

/// Why a take operation failed.
#[derive(Debug, thiserror::Error)]
pub enum RecordError {
    /// A source with this id exists already.
    #[error("source {0} exists")]
    Duplicate(String),
    /// No source with this id.
    #[error("unknown source {0}")]
    Unknown(String),
    /// A source's sample rate differs from the take's.
    #[error("sample rate differs from the take's")]
    SampleRate,
    /// Sources to be mixed have different channel counts.
    #[error("channel counts differ")]
    Channels,
    /// A file problem.
    #[error("file: {0}")]
    Io(#[from] std::io::Error),
    /// A manifest problem.
    #[error("manifest: {0}")]
    Manifest(#[from] serde_json::Error),
}

/// One recording: sources and their manifest.
#[derive(Clone, Debug)]
pub struct Take {
    manifest: Manifest,
    audio: BTreeMap<String, Stem>,
}

fn file_name(id: &str) -> String {
    let s: String = id.chars().map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '_' }).collect();
    format!("{s}.wav")
}

impl Take {
    /// An empty take.
    pub fn new(take: &str, sample_rate: u32) -> Self {
        Take { manifest: Manifest { take: take.to_string(), sample_rate, sources: Vec::new() }, audio: BTreeMap::new() }
    }

    /// The manifest.
    pub fn manifest(&self) -> &Manifest {
        &self.manifest
    }

    /// A source's raw audio.
    pub fn raw(&self, id: &str) -> Option<&Stem> {
        self.audio.get(id)
    }

    /// Add a recorded source with its latency record.
    pub fn add(&mut self, id: &str, kind: SourceKind, stem: Stem, latency: PortLatency, group: Option<&str>) -> Result<(), RecordError> {
        if self.audio.contains_key(id) {
            return Err(RecordError::Duplicate(id.to_string()));
        }
        if stem.sample_rate != self.manifest.sample_rate {
            return Err(RecordError::SampleRate);
        }
        let mut file = file_name(id);
        while self.manifest.sources.iter().any(|s| s.file == file) {
            file = format!("_{file}");
        }
        self.manifest.sources.push(SourceEntry {
            id: id.to_string(),
            kind,
            file,
            channels: stem.channels,
            start: stem.start,
            frames: stem.frames(),
            latency,
            trim: 0,
            gaps: stem.gaps.clone(),
            group: group.map(str::to_string),
        });
        self.audio.insert(id.to_string(), stem);
        Ok(())
    }

    fn entry(&self, id: &str) -> Result<&SourceEntry, RecordError> {
        self.manifest.sources.iter().find(|s| s.id == id).ok_or_else(|| RecordError::Unknown(id.to_string()))
    }

    /// Set a source's manual trim (frames; positive moves it earlier).
    pub fn set_trim(&mut self, id: &str, trim: i64) -> Result<(), RecordError> {
        let e = self.manifest.sources.iter_mut().find(|s| s.id == id).ok_or_else(|| RecordError::Unknown(id.to_string()))?;
        e.trim = trim;
        Ok(())
    }

    /// The aligned range of the take on the session clock: from the earliest aligned start to
    /// the latest aligned end over all sources.
    pub fn range(&self) -> (i64, i64) {
        let starts = self.manifest.sources.iter().map(|s| s.aligned_start());
        let ends = self.manifest.sources.iter().map(|s| s.aligned_start() + s.frames as i64);
        (starts.min().unwrap_or(0), ends.max().unwrap_or(0))
    }

    /// A source cut to the take's range and shifted by its offset; silence where it has no
    /// audio. Every source comes out the same number of frames long.
    pub fn aligned(&self, id: &str) -> Result<Vec<f32>, RecordError> {
        let e = self.entry(id)?;
        let stem = &self.audio[id];
        let (start, end) = self.range();
        let ch = e.channels as usize;
        let len = (end - start) as usize;
        let mut out = vec![0.0f32; len * ch];
        let first = (e.aligned_start() - start) as usize;
        let n = (stem.frames() as usize).min(len.saturating_sub(first));
        out[first * ch..(first + n) * ch].copy_from_slice(&stem.samples[..n * ch]);
        Ok(out)
    }

    /// The mix of every [`SourceKind::Stem`] source, aligned, at unity gain.
    pub fn render_mix(&self) -> Result<Vec<f32>, RecordError> {
        let stems: Vec<&SourceEntry> = self.manifest.sources.iter().filter(|s| s.kind == SourceKind::Stem).collect();
        if stems.windows(2).any(|w| w[0].channels != w[1].channels) {
            return Err(RecordError::Channels);
        }
        let aligned: Vec<Vec<f32>> = stems.iter().map(|s| self.aligned(&s.id)).collect::<Result<_, _>>()?;
        let refs: Vec<(&[f32], f32)> = aligned.iter().map(|a| (a.as_slice(), 1.0)).collect();
        Ok(mix(&refs))
    }

    /// Write the raw sources, `manifest.json` and the rendered `mix.wav` to `dir` (created if
    /// missing). [`Take::load`] reads it back; changing a trim and writing again re-aligns.
    pub fn write(&self, dir: &Path) -> Result<(), RecordError> {
        std::fs::create_dir_all(dir)?;
        for e in &self.manifest.sources {
            let s = &self.audio[&e.id];
            wav::save(&dir.join(&e.file), s.sample_rate, s.channels, &s.samples)?;
        }
        if let Some(first) = self.manifest.sources.iter().find(|s| s.kind == SourceKind::Stem) {
            wav::save(&dir.join("mix.wav"), self.manifest.sample_rate, first.channels, &self.render_mix()?)?;
        }
        std::fs::write(dir.join("manifest.json"), serde_json::to_vec_pretty(&self.manifest)?)?;
        Ok(())
    }

    /// Write every source aligned to the take's range as `<file>` in `dir`, plus `mix.wav`.
    pub fn export_aligned(&self, dir: &Path) -> Result<(), RecordError> {
        std::fs::create_dir_all(dir)?;
        for e in &self.manifest.sources {
            wav::save(&dir.join(&e.file), self.manifest.sample_rate, e.channels, &self.aligned(&e.id)?)?;
        }
        if let Some(first) = self.manifest.sources.iter().find(|s| s.kind == SourceKind::Stem) {
            wav::save(&dir.join("mix.wav"), self.manifest.sample_rate, first.channels, &self.render_mix()?)?;
        }
        Ok(())
    }

    /// Read a take written by [`Take::write`].
    pub fn load(dir: &Path) -> Result<Take, RecordError> {
        let manifest: Manifest = serde_json::from_slice(&std::fs::read(dir.join("manifest.json"))?)?;
        let mut audio = BTreeMap::new();
        for e in &manifest.sources {
            let (rate, ch, samples) = wav::load(&dir.join(&e.file))?;
            audio.insert(e.id.clone(), Stem { channels: ch, sample_rate: rate, start: e.start, samples, gaps: e.gaps.clone() });
        }
        Ok(Take { manifest, audio })
    }
}