forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

recorder.rs278 lines, 10.4 KiBHistoryRawDownload
1//! Voice-over recording: the server's input written to a WAV in the project's
2//! media folder as it arrives. A worker thread drains [`crate::pulse::Recording`]
3//! into a 16-bit PCM file; the caller reads the meter and the clock, and stops
4//! it to finalise the header.
5
6use std::fs::File;
7use std::io::{self, BufWriter, Seek, SeekFrom, Write};
8use std::path::{Path, PathBuf};
9use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
10use std::sync::Arc;
11use std::thread::JoinHandle;
12use std::time::Duration;
13
14use crate::pulse::Recording;
15
16/// Sample rate of every recording.
17pub const RATE: u32 = 48_000;
18/// Channels of every recording: the server remixes a mono input to both.
19pub const CHANNELS: u16 = 2;
20/// How often the worker takes what the server has captured.
21const POLL: Duration = Duration::from_millis(10);
22/// The most a WAV's data chunk can hold: its size is a u32.
23const MAX_DATA_BYTES: u64 = u32::MAX as u64 - 36;
24/// The meter's floor, in dBFS: silence reads as this.
25pub const SILENCE_DB: f32 = -120.0;
26
27/// Writes a 16-bit PCM WAV. The header goes first with zero sizes and `finish`
28/// patches them in once the data is known.
29pub struct WavWriter {
30 file: BufWriter<File>,
31 data_bytes: u64,
32}
33
34impl WavWriter {
35 pub fn create(path: &Path, rate: u32, channels: u16) -> io::Result<Self> {
36 let mut file = BufWriter::new(File::create(path)?);
37 file.write_all(&header(rate, channels, 0))?;
38 Ok(Self { file, data_bytes: 0 })
39 }
40
41 /// Appends interleaved f32 samples, clamped to -1..1, as 16-bit PCM.
42 pub fn write(&mut self, samples: &[f32]) -> io::Result<()> {
43 let mut bytes = Vec::with_capacity(samples.len() * 2);
44 for &sample in samples {
45 let value = (sample.clamp(-1.0, 1.0) * 32767.0).round() as i16;
46 bytes.extend_from_slice(&value.to_le_bytes());
47 }
48 self.file.write_all(&bytes)?;
49 self.data_bytes += bytes.len() as u64;
50 Ok(())
51 }
52
53 /// Bytes of audio written so far.
54 pub fn data_bytes(&self) -> u64 {
55 self.data_bytes
56 }
57
58 /// Patches the sizes into the header and closes the file. Returns the sample
59 /// frames written.
60 pub fn finish(self, rate: u32, channels: u16) -> io::Result<u64> {
61 let data_bytes = self.data_bytes;
62 let mut file = self.file.into_inner().map_err(io::Error::other)?;
63 file.seek(SeekFrom::Start(0))?;
64 file.write_all(&header(rate, channels, data_bytes))?;
65 file.flush()?;
66 Ok(data_bytes / (2 * u64::from(channels)))
67 }
68}
69
70/// The 44-byte RIFF header of a PCM WAV holding `data_bytes` of samples.
71fn header(rate: u32, channels: u16, data_bytes: u64) -> [u8; 44] {
72 let block = u32::from(channels) * 2;
73 let mut h = [0u8; 44];
74 h[0..4].copy_from_slice(b"RIFF");
75 h[4..8].copy_from_slice(&((36 + data_bytes) as u32).to_le_bytes());
76 h[8..12].copy_from_slice(b"WAVE");
77 h[12..16].copy_from_slice(b"fmt ");
78 h[16..20].copy_from_slice(&16u32.to_le_bytes());
79 h[20..22].copy_from_slice(&1u16.to_le_bytes());
80 h[22..24].copy_from_slice(&channels.to_le_bytes());
81 h[24..28].copy_from_slice(&rate.to_le_bytes());
82 h[28..32].copy_from_slice(&(rate * block).to_le_bytes());
83 h[32..34].copy_from_slice(&(block as u16).to_le_bytes());
84 h[34..36].copy_from_slice(&16u16.to_le_bytes());
85 h[36..40].copy_from_slice(b"data");
86 h[40..44].copy_from_slice(&(data_bytes as u32).to_le_bytes());
87 h
88}
89
90/// What the meter and the clock show while a recording runs.
91#[derive(Clone, Debug, PartialEq)]
92pub struct Status {
93 pub path: PathBuf,
94 /// Seconds of audio written so far.
95 pub elapsed_secs: f64,
96 /// The loudest sample since the last [`Recorder::level_db`], in dBFS.
97 pub level_db: f32,
98}
99
100/// A finished recording, its header final.
101#[derive(Clone, Debug, PartialEq)]
102pub struct Take {
103 pub path: PathBuf,
104 pub frames: u64,
105 pub duration_secs: f64,
106}
107
108/// The first `voiceover-<n>.wav` in `folder` that is not there yet.
109fn next_take_path(folder: &Path) -> PathBuf {
110 (1..)
111 .map(|n| folder.join(format!("voiceover-{n}.wav")))
112 .find(|path| !path.exists())
113 .expect("a free take name")
114}
115
116/// A recording in progress. [`Recorder::stop`] finishes it; dropping one stops
117/// it too, keeping what was written.
118pub struct Recorder {
119 path: PathBuf,
120 frames: Arc<AtomicU64>,
121 /// The loudest sample since the meter was last read, as f32 bits. Positive
122 /// floats order the same as their bits, so `fetch_max` keeps the peak.
123 peak: Arc<AtomicU32>,
124 stop: Arc<AtomicBool>,
125 worker: Option<JoinHandle<Result<u64, String>>>,
126}
127
128impl Recorder {
129 /// Starts recording from `source` (a source name, or the server's default
130 /// input when `None`) into a new take in `folder`, which is created if it is
131 /// not there. Fails when there is no audio server or the file cannot be made.
132 pub fn start(folder: &Path, source: Option<&str>) -> Result<Self, String> {
133 std::fs::create_dir_all(folder).map_err(|e| format!("cannot make {}: {e}", folder.display()))?;
134 let path = next_take_path(folder);
135 let recording = Recording::open(RATE, u32::from(CHANNELS), source)
136 .ok_or_else(|| "no audio input: the audio server would not record".to_string())?;
137 let writer = WavWriter::create(&path, RATE, CHANNELS).map_err(|e| format!("cannot write {}: {e}", path.display()))?;
138 let frames = Arc::new(AtomicU64::new(0));
139 let peak = Arc::new(AtomicU32::new(0));
140 let stop = Arc::new(AtomicBool::new(false));
141 let worker = {
142 let (frames, peak, stop) = (frames.clone(), peak.clone(), stop.clone());
143 std::thread::spawn(move || work(recording, writer, &frames, &peak, &stop))
144 };
145 Ok(Self {
146 path,
147 frames,
148 peak,
149 stop,
150 worker: Some(worker),
151 })
152 }
153
154 /// The take's path, the clock and the level since the last call.
155 pub fn status(&self) -> Status {
156 Status {
157 path: self.path.clone(),
158 elapsed_secs: self.frames.load(Ordering::Relaxed) as f64 / f64::from(RATE),
159 level_db: self.level_db(),
160 }
161 }
162
163 /// The peak sample since the last call, in dBFS, and resets the peak.
164 pub fn level_db(&self) -> f32 {
165 let peak = f32::from_bits(self.peak.swap(0, Ordering::Relaxed));
166 if peak <= 0.0 {
167 return SILENCE_DB;
168 }
169 (20.0 * peak.log10()).max(SILENCE_DB)
170 }
171
172 /// Stops the recording, finalises the WAV and returns it.
173 pub fn stop(mut self) -> Result<Take, String> {
174 self.finish()
175 }
176
177 fn finish(&mut self) -> Result<Take, String> {
178 self.stop.store(true, Ordering::Release);
179 let Some(worker) = self.worker.take() else {
180 return Err("the recording has already stopped".to_string());
181 };
182 let frames = worker.join().map_err(|_| "the recording thread panicked".to_string())??;
183 Ok(Take {
184 path: self.path.clone(),
185 frames,
186 duration_secs: frames as f64 / f64::from(RATE),
187 })
188 }
189}
190
191impl Drop for Recorder {
192 fn drop(&mut self) {
193 let _ = self.finish();
194 }
195}
196
197/// The worker: drains the server every [`POLL`] until asked to stop or the
198/// input dies, then stops the stream, takes the rest and finalises the file.
199fn work(
200 recording: Recording,
201 mut writer: WavWriter,
202 frames: &AtomicU64,
203 peak: &AtomicU32,
204 stop: &AtomicBool,
205) -> Result<u64, String> {
206 let mut failure = None;
207 let take = |writer: &mut WavWriter, samples: Vec<f32>| -> Result<(), String> {
208 if samples.is_empty() {
209 return Ok(());
210 }
211 let loudest = samples.iter().fold(0.0f32, |m, s| m.max(s.abs()));
212 peak.fetch_max(loudest.to_bits(), Ordering::Relaxed);
213 writer.write(&samples).map_err(|e| format!("cannot write the take: {e}"))?;
214 frames.store(writer.data_bytes() / (2 * u64::from(CHANNELS)), Ordering::Relaxed);
215 Ok(())
216 };
217 loop {
218 if stop.load(Ordering::Acquire) || !recording.alive() {
219 break;
220 }
221 if writer.data_bytes() + 4 * u64::from(CHANNELS) > MAX_DATA_BYTES {
222 failure = Some("the take reached the longest a WAV can hold".to_string());
223 break;
224 }
225 if let Err(e) = take(&mut writer, recording.read()) {
226 failure = Some(e);
227 break;
228 }
229 std::thread::sleep(POLL);
230 }
231 recording.set_active(false);
232 if failure.is_none()
233 && let Err(e) = take(&mut writer, recording.read())
234 {
235 failure = Some(e);
236 }
237 drop(recording);
238 let frames_out = writer.finish(RATE, CHANNELS).map_err(|e| format!("cannot finish the take: {e}"))?;
239 match failure {
240 Some(e) => Err(e),
241 None if !stop.load(Ordering::Acquire) => Err("the audio input stopped".to_string()),
242 None => Ok(frames_out),
243 }
244}
245
246#[cfg(test)]
247mod tests {
248 use super::*;
249
250 /// The header of a finished take is exact, and the samples come back as
251 /// 16-bit PCM, clamped.
252 #[test]
253 fn a_wav_round_trips_with_its_header_final() {
254 let dir = std::env::temp_dir().join(format!("edith-wav-{}", std::process::id()));
255 std::fs::create_dir_all(&dir).unwrap();
256 let path = dir.join("take.wav");
257 let mut writer = WavWriter::create(&path, RATE, CHANNELS).unwrap();
258 writer.write(&[0.5, -0.5, 2.0, -2.0]).unwrap();
259 let frames = writer.finish(RATE, CHANNELS).unwrap();
260 assert_eq!(frames, 2);
261
262 let bytes = std::fs::read(&path).unwrap();
263 let _ = std::fs::remove_dir_all(&dir);
264 assert_eq!(bytes.len(), 44 + 8);
265 assert_eq!(&bytes[0..4], b"RIFF");
266 assert_eq!(u32::from_le_bytes(bytes[4..8].try_into().unwrap()), 36 + 8);
267 assert_eq!(&bytes[8..16], b"WAVEfmt ");
268 assert_eq!(u16::from_le_bytes(bytes[20..22].try_into().unwrap()), 1, "PCM");
269 assert_eq!(u16::from_le_bytes(bytes[22..24].try_into().unwrap()), 2, "stereo");
270 assert_eq!(u32::from_le_bytes(bytes[24..28].try_into().unwrap()), RATE);
271 assert_eq!(u16::from_le_bytes(bytes[34..36].try_into().unwrap()), 16, "16 bits");
272 assert_eq!(&bytes[36..40], b"data");
273 assert_eq!(u32::from_le_bytes(bytes[40..44].try_into().unwrap()), 8);
274 let (pairs, _) = bytes[44..].as_chunks::<2>();
275 let samples: Vec<i16> = pairs.iter().map(|b| i16::from_le_bytes(*b)).collect();
276 assert_eq!(samples, vec![16384, -16384, 32767, -32767]);
277 }
278}