Skip to main content

weirdnet_audio_record/
take.rs

1//! A take: stems, their latency records and offsets, alignment and files.
2use crate::align::mix;
3use crate::stem::{Gap, Stem};
4use crate::wav;
5use serde::{Deserialize, Serialize};
6use std::collections::BTreeMap;
7use std::path::Path;
8use weirdnet_audio_route::PortLatency;
9
10/// What a source is.
11#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
12pub enum SourceKind {
13    /// A source's own (dry) output.
14    Stem,
15    /// What a device actually played (a device-output tap).
16    DeviceOutput,
17    /// A mix recorded as it was heard.
18    Mix,
19    /// A person's talkback voice: kept beside the music, never in the mix.
20    Talkback,
21}
22
23/// One source in the manifest.
24#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
25pub struct SourceEntry {
26    /// The source's id (for example a port id).
27    pub id: String,
28    /// What it is.
29    pub kind: SourceKind,
30    /// Its file in the take folder.
31    pub file: String,
32    /// Channels.
33    pub channels: u16,
34    /// Where the raw recording starts on the session clock, frames.
35    pub start: u64,
36    /// Raw length, frames.
37    pub frames: u64,
38    /// The latency the source reported or that was measured.
39    pub latency: PortLatency,
40    /// A manual correction, frames; positive moves the source earlier.
41    pub trim: i64,
42    /// Gaps filled with silence.
43    pub gaps: Vec<Gap>,
44    /// An optional group, for example to pair a source's stem with its device output.
45    pub group: Option<String>,
46}
47
48impl SourceEntry {
49    /// How far the source is moved earlier when aligned: its latency plus its trim.
50    pub fn offset(&self) -> i64 {
51        i64::from(self.latency.frames) + self.trim
52    }
53
54    /// Where the aligned source starts on the session clock.
55    pub fn aligned_start(&self) -> i64 {
56        self.start as i64 - self.offset()
57    }
58}
59
60/// The take's description, saved as `manifest.json`.
61#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
62pub struct Manifest {
63    /// The take's name.
64    pub take: String,
65    /// The sample rate of every source.
66    pub sample_rate: u32,
67    /// The sources, in the order they were added.
68    pub sources: Vec<SourceEntry>,
69}
70
71/// Why a take operation failed.
72#[derive(Debug, thiserror::Error)]
73pub enum RecordError {
74    /// A source with this id exists already.
75    #[error("source {0} exists")]
76    Duplicate(String),
77    /// No source with this id.
78    #[error("unknown source {0}")]
79    Unknown(String),
80    /// A source's sample rate differs from the take's.
81    #[error("sample rate differs from the take's")]
82    SampleRate,
83    /// Sources to be mixed have different channel counts.
84    #[error("channel counts differ")]
85    Channels,
86    /// A file problem.
87    #[error("file: {0}")]
88    Io(#[from] std::io::Error),
89    /// A manifest problem.
90    #[error("manifest: {0}")]
91    Manifest(#[from] serde_json::Error),
92}
93
94/// One recording: sources and their manifest.
95#[derive(Clone, Debug)]
96pub struct Take {
97    manifest: Manifest,
98    audio: BTreeMap<String, Stem>,
99}
100
101fn file_name(id: &str) -> String {
102    let s: String = id.chars().map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '_' }).collect();
103    format!("{s}.wav")
104}
105
106impl Take {
107    /// An empty take.
108    pub fn new(take: &str, sample_rate: u32) -> Self {
109        Take { manifest: Manifest { take: take.to_string(), sample_rate, sources: Vec::new() }, audio: BTreeMap::new() }
110    }
111
112    /// The manifest.
113    pub fn manifest(&self) -> &Manifest {
114        &self.manifest
115    }
116
117    /// A source's raw audio.
118    pub fn raw(&self, id: &str) -> Option<&Stem> {
119        self.audio.get(id)
120    }
121
122    /// Add a recorded source with its latency record.
123    pub fn add(&mut self, id: &str, kind: SourceKind, stem: Stem, latency: PortLatency, group: Option<&str>) -> Result<(), RecordError> {
124        if self.audio.contains_key(id) {
125            return Err(RecordError::Duplicate(id.to_string()));
126        }
127        if stem.sample_rate != self.manifest.sample_rate {
128            return Err(RecordError::SampleRate);
129        }
130        let mut file = file_name(id);
131        while self.manifest.sources.iter().any(|s| s.file == file) {
132            file = format!("_{file}");
133        }
134        self.manifest.sources.push(SourceEntry {
135            id: id.to_string(),
136            kind,
137            file,
138            channels: stem.channels,
139            start: stem.start,
140            frames: stem.frames(),
141            latency,
142            trim: 0,
143            gaps: stem.gaps.clone(),
144            group: group.map(str::to_string),
145        });
146        self.audio.insert(id.to_string(), stem);
147        Ok(())
148    }
149
150    fn entry(&self, id: &str) -> Result<&SourceEntry, RecordError> {
151        self.manifest.sources.iter().find(|s| s.id == id).ok_or_else(|| RecordError::Unknown(id.to_string()))
152    }
153
154    /// Set a source's manual trim (frames; positive moves it earlier).
155    pub fn set_trim(&mut self, id: &str, trim: i64) -> Result<(), RecordError> {
156        let e = self.manifest.sources.iter_mut().find(|s| s.id == id).ok_or_else(|| RecordError::Unknown(id.to_string()))?;
157        e.trim = trim;
158        Ok(())
159    }
160
161    /// The aligned range of the take on the session clock: from the earliest aligned start to
162    /// the latest aligned end over all sources.
163    pub fn range(&self) -> (i64, i64) {
164        let starts = self.manifest.sources.iter().map(|s| s.aligned_start());
165        let ends = self.manifest.sources.iter().map(|s| s.aligned_start() + s.frames as i64);
166        (starts.min().unwrap_or(0), ends.max().unwrap_or(0))
167    }
168
169    /// A source cut to the take's range and shifted by its offset; silence where it has no
170    /// audio. Every source comes out the same number of frames long.
171    pub fn aligned(&self, id: &str) -> Result<Vec<f32>, RecordError> {
172        let e = self.entry(id)?;
173        let stem = &self.audio[id];
174        let (start, end) = self.range();
175        let ch = e.channels as usize;
176        let len = (end - start) as usize;
177        let mut out = vec![0.0f32; len * ch];
178        let first = (e.aligned_start() - start) as usize;
179        let n = (stem.frames() as usize).min(len.saturating_sub(first));
180        out[first * ch..(first + n) * ch].copy_from_slice(&stem.samples[..n * ch]);
181        Ok(out)
182    }
183
184    /// The mix of every [`SourceKind::Stem`] source, aligned, at unity gain.
185    pub fn render_mix(&self) -> Result<Vec<f32>, RecordError> {
186        let stems: Vec<&SourceEntry> = self.manifest.sources.iter().filter(|s| s.kind == SourceKind::Stem).collect();
187        if stems.windows(2).any(|w| w[0].channels != w[1].channels) {
188            return Err(RecordError::Channels);
189        }
190        let aligned: Vec<Vec<f32>> = stems.iter().map(|s| self.aligned(&s.id)).collect::<Result<_, _>>()?;
191        let refs: Vec<(&[f32], f32)> = aligned.iter().map(|a| (a.as_slice(), 1.0)).collect();
192        Ok(mix(&refs))
193    }
194
195    /// Write the raw sources, `manifest.json` and the rendered `mix.wav` to `dir` (created if
196    /// missing). [`Take::load`] reads it back; changing a trim and writing again re-aligns.
197    pub fn write(&self, dir: &Path) -> Result<(), RecordError> {
198        std::fs::create_dir_all(dir)?;
199        for e in &self.manifest.sources {
200            let s = &self.audio[&e.id];
201            wav::save(&dir.join(&e.file), s.sample_rate, s.channels, &s.samples)?;
202        }
203        if let Some(first) = self.manifest.sources.iter().find(|s| s.kind == SourceKind::Stem) {
204            wav::save(&dir.join("mix.wav"), self.manifest.sample_rate, first.channels, &self.render_mix()?)?;
205        }
206        std::fs::write(dir.join("manifest.json"), serde_json::to_vec_pretty(&self.manifest)?)?;
207        Ok(())
208    }
209
210    /// Write every source aligned to the take's range as `<file>` in `dir`, plus `mix.wav`.
211    pub fn export_aligned(&self, dir: &Path) -> Result<(), RecordError> {
212        std::fs::create_dir_all(dir)?;
213        for e in &self.manifest.sources {
214            wav::save(&dir.join(&e.file), self.manifest.sample_rate, e.channels, &self.aligned(&e.id)?)?;
215        }
216        if let Some(first) = self.manifest.sources.iter().find(|s| s.kind == SourceKind::Stem) {
217            wav::save(&dir.join("mix.wav"), self.manifest.sample_rate, first.channels, &self.render_mix()?)?;
218        }
219        Ok(())
220    }
221
222    /// Read a take written by [`Take::write`].
223    pub fn load(dir: &Path) -> Result<Take, RecordError> {
224        let manifest: Manifest = serde_json::from_slice(&std::fs::read(dir.join("manifest.json"))?)?;
225        let mut audio = BTreeMap::new();
226        for e in &manifest.sources {
227            let (rate, ch, samples) = wav::load(&dir.join(&e.file))?;
228            audio.insert(e.id.clone(), Stem { channels: ch, sample_rate: rate, start: e.start, samples, gaps: e.gaps.clone() });
229        }
230        Ok(Take { manifest, audio })
231    }
232}