| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | use std::fs::File; |
| 7 | use std::io::{self, BufWriter, Seek, SeekFrom, Write}; |
| 8 | use std::path::{Path, PathBuf}; |
| 9 | use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}; |
| 10 | use std::sync::Arc; |
| 11 | use std::thread::JoinHandle; |
| 12 | use std::time::Duration; |
| 13 | |
| 14 | use crate::pulse::Recording; |
| 15 | |
| 16 | |
| 17 | pub const RATE: u32 = 48_000; |
| 18 | |
| 19 | pub const CHANNELS: u16 = 2; |
| 20 | |
| 21 | const POLL: Duration = Duration::from_millis(10); |
| 22 | |
| 23 | const MAX_DATA_BYTES: u64 = u32::MAX as u64 - 36; |
| 24 | |
| 25 | pub const SILENCE_DB: f32 = -120.0; |
| 26 | |
| 27 | |
| 28 | |
| 29 | pub struct WavWriter { |
| 30 | file: BufWriter<File>, |
| 31 | data_bytes: u64, |
| 32 | } |
| 33 | |
| 34 | impl 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 | |
| 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 | |
| 54 | pub fn data_bytes(&self) -> u64 { |
| 55 | self.data_bytes |
| 56 | } |
| 57 | |
| 58 | |
| 59 | |
| 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 | |
| 71 | fn 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 | |
| 91 | #[derive(Clone, Debug, PartialEq)] |
| 92 | pub struct Status { |
| 93 | pub path: PathBuf, |
| 94 | |
| 95 | pub elapsed_secs: f64, |
| 96 | |
| 97 | pub level_db: f32, |
| 98 | } |
| 99 | |
| 100 | |
| 101 | #[derive(Clone, Debug, PartialEq)] |
| 102 | pub struct Take { |
| 103 | pub path: PathBuf, |
| 104 | pub frames: u64, |
| 105 | pub duration_secs: f64, |
| 106 | } |
| 107 | |
| 108 | |
| 109 | fn 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 | |
| 117 | |
| 118 | pub struct Recorder { |
| 119 | path: PathBuf, |
| 120 | frames: Arc<AtomicU64>, |
| 121 | |
| 122 | |
| 123 | peak: Arc<AtomicU32>, |
| 124 | stop: Arc<AtomicBool>, |
| 125 | worker: Option<JoinHandle<Result<u64, String>>>, |
| 126 | } |
| 127 | |
| 128 | impl Recorder { |
| 129 | |
| 130 | |
| 131 | |
| 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 | |
| 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 | |
| 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 | |
| 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 | |
| 191 | impl Drop for Recorder { |
| 192 | fn drop(&mut self) { |
| 193 | let _ = self.finish(); |
| 194 | } |
| 195 | } |
| 196 | |
| 197 | |
| 198 | |
| 199 | fn 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)] |
| 247 | mod tests { |
| 248 | use super::*; |
| 249 | |
| 250 | |
| 251 | |
| 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 | } |