| 1 | use std::fs::File; |
| 2 | use std::io::{BufWriter, Seek, SeekFrom, Write}; |
| 3 | use std::path::{Path, PathBuf}; |
| 4 | |
| 5 | use crate::audio::SAMPLE_RATE; |
| 6 | |
| 7 | pub const AUDIO_DUMP_ENV: &str = "CALLING_AUDIO_DUMP"; |
| 8 | const HEADER_BYTES: u32 = 44; |
| 9 | |
| 10 | /// Mono 16-bit WAV writer for checking each mic processing stage; the header gets its sizes on drop. |
| 11 | pub struct WavDump { |
| 12 | writer: BufWriter<File>, |
| 13 | data_bytes: u32, |
| 14 | } |
| 15 | |
| 16 | impl WavDump { |
| 17 | pub fn create(path: &Path) -> std::io::Result<WavDump> { |
| 18 | let mut writer = BufWriter::new(File::create(path)?); |
| 19 | writer.write_all(&header(0))?; |
| 20 | Ok(WavDump { writer, data_bytes: 0 }) |
| 21 | } |
| 22 | |
| 23 | pub fn write(&mut self, samples: &[i16]) { |
| 24 | for sample in samples { |
| 25 | if self.writer.write_all(&sample.to_le_bytes()).is_err() { |
| 26 | return; |
| 27 | } |
| 28 | self.data_bytes += 2; |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | fn finish(&mut self) -> std::io::Result<()> { |
| 33 | self.writer.seek(SeekFrom::Start(0))?; |
| 34 | self.writer.write_all(&header(self.data_bytes))?; |
| 35 | self.writer.flush() |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | impl Drop for WavDump { |
| 40 | fn drop(&mut self) { |
| 41 | let _ = self.finish(); |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | fn header(data_bytes: u32) -> Vec<u8> { |
| 46 | let byte_rate = SAMPLE_RATE * 2; |
| 47 | let mut header = Vec::with_capacity(HEADER_BYTES as usize); |
| 48 | header.extend_from_slice(b"RIFF"); |
| 49 | header.extend_from_slice(&(HEADER_BYTES - 8 + data_bytes).to_le_bytes()); |
| 50 | header.extend_from_slice(b"WAVEfmt "); |
| 51 | header.extend_from_slice(&16u32.to_le_bytes()); |
| 52 | header.extend_from_slice(&1u16.to_le_bytes()); |
| 53 | header.extend_from_slice(&1u16.to_le_bytes()); |
| 54 | header.extend_from_slice(&SAMPLE_RATE.to_le_bytes()); |
| 55 | header.extend_from_slice(&byte_rate.to_le_bytes()); |
| 56 | header.extend_from_slice(&2u16.to_le_bytes()); |
| 57 | header.extend_from_slice(&16u16.to_le_bytes()); |
| 58 | header.extend_from_slice(b"data"); |
| 59 | header.extend_from_slice(&data_bytes.to_le_bytes()); |
| 60 | header |
| 61 | } |
| 62 | |
| 63 | /// One WAV per stage of the mic chain, written only when `CALLING_AUDIO_DUMP` names a directory. |
| 64 | pub struct StageDumps { |
| 65 | stages: Vec<WavDump>, |
| 66 | } |
| 67 | |
| 68 | impl StageDumps { |
| 69 | pub const STAGES: [&str; 5] = ["0-far-end", "1-raw", "2-echo-highpass", "3-gain", "4-noise-gain"]; |
| 70 | |
| 71 | pub fn from_env() -> Option<StageDumps> { |
| 72 | let directory = PathBuf::from(std::env::var_os(AUDIO_DUMP_ENV)?); |
| 73 | StageDumps::create(&directory).ok() |
| 74 | } |
| 75 | |
| 76 | pub fn create(directory: &Path) -> std::io::Result<StageDumps> { |
| 77 | std::fs::create_dir_all(directory)?; |
| 78 | let stamp = chrono::Local::now().format("%Y%m%d-%H%M%S"); |
| 79 | let stages = StageDumps::STAGES |
| 80 | .iter() |
| 81 | .map(|stage| WavDump::create(&directory.join(format!("mic-{stamp}-{stage}.wav")))) |
| 82 | .collect::<std::io::Result<Vec<_>>>()?; |
| 83 | Ok(StageDumps { stages }) |
| 84 | } |
| 85 | |
| 86 | pub fn write(&mut self, stage_index: usize, samples: &[i16]) { |
| 87 | if let Some(stage) = self.stages.get_mut(stage_index) { |
| 88 | stage.write(samples); |
| 89 | } |
| 90 | } |
| 91 | } |
| 92 | |
| 93 | #[cfg(test)] |
| 94 | mod tests { |
| 95 | use super::*; |
| 96 | |
| 97 | #[test] |
| 98 | fn a_dump_is_a_readable_wav_with_the_written_samples() { |
| 99 | let directory = tempfile::tempdir().unwrap(); |
| 100 | let path = directory.path().join("dump.wav"); |
| 101 | { |
| 102 | let mut dump = WavDump::create(&path).unwrap(); |
| 103 | dump.write(&[1, -2, 3]); |
| 104 | } |
| 105 | let bytes = std::fs::read(&path).unwrap(); |
| 106 | assert_eq!(&bytes[0..4], b"RIFF"); |
| 107 | assert_eq!(u32::from_le_bytes(bytes[24..28].try_into().unwrap()), SAMPLE_RATE); |
| 108 | assert_eq!(u32::from_le_bytes(bytes[40..44].try_into().unwrap()), 6); |
| 109 | assert_eq!(&bytes[44..], &[1, 0, 254, 255, 3, 0]); |
| 110 | } |
| 111 | |
| 112 | #[test] |
| 113 | fn every_stage_gets_its_own_file() { |
| 114 | let directory = tempfile::tempdir().unwrap(); |
| 115 | let mut dumps = StageDumps::create(directory.path()).unwrap(); |
| 116 | dumps.write(4, &[5]); |
| 117 | drop(dumps); |
| 118 | let names: Vec<String> = |
| 119 | std::fs::read_dir(directory.path()).unwrap().map(|entry| entry.unwrap().file_name().into_string().unwrap()).collect(); |
| 120 | assert_eq!(names.len(), StageDumps::STAGES.len()); |
| 121 | assert!(names.iter().any(|name| name.ends_with("4-noise-gain.wav"))); |
| 122 | } |
| 123 | } |