Skip to main content

lib_jsl_file_io/
wav.rs

1//! Reading and writing RIFF/WAVE audio files.
2//!
3//! See the book entry [Audio files](https://jwkunz.github.io/lib_jsl/book/foundations/audio.html#wav-files).
4
5use lib_jsl_core::ErrorsJSL;
6use std::path::Path;
7
8/// Sample encodings that can be written (and are understood when reading).
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub enum WavSampleFormat {
11    /// 8-bit unsigned PCM.
12    Pcm8,
13    /// 16-bit signed PCM.
14    Pcm16,
15    /// 24-bit signed PCM.
16    Pcm24,
17    /// 32-bit signed PCM.
18    Pcm32,
19    /// 32-bit IEEE float.
20    Float32,
21    /// 64-bit IEEE float.
22    Float64,
23}
24
25impl WavSampleFormat {
26    fn bits(self) -> u16 {
27        match self {
28            WavSampleFormat::Pcm8 => 8,
29            WavSampleFormat::Pcm16 => 16,
30            WavSampleFormat::Pcm24 => 24,
31            WavSampleFormat::Pcm32 | WavSampleFormat::Float32 => 32,
32            WavSampleFormat::Float64 => 64,
33        }
34    }
35    fn is_float(self) -> bool {
36        matches!(self, WavSampleFormat::Float32 | WavSampleFormat::Float64)
37    }
38}
39
40/// Decoded audio: interleaved samples normalised to `[-1, 1)` (integer formats) or as stored (float).
41#[derive(Debug, Clone, PartialEq)]
42pub struct WavAudio {
43    pub sample_rate: u32,
44    pub channels: u16,
45    /// Frame-interleaved samples (`frames * channels` values).
46    pub samples: Vec<f32>,
47}
48
49impl WavAudio {
50    /// Number of sample frames.
51    pub fn frames(&self) -> usize {
52        self.samples.len() / self.channels.max(1) as usize
53    }
54
55    /// Samples of one channel.
56    pub fn channel(&self, index: usize) -> Vec<f32> {
57        self.samples.iter().skip(index).step_by(self.channels as usize).copied().collect()
58    }
59}
60
61const ERR_FORMAT: ErrorsJSL = ErrorsJSL::InvalidInputRange("Malformed or unsupported WAV file.");
62
63fn u16_at(d: &[u8], p: usize) -> Result<u16, ErrorsJSL> {
64    d.get(p..p + 2).map(|b| u16::from_le_bytes([b[0], b[1]])).ok_or(ERR_FORMAT)
65}
66fn u32_at(d: &[u8], p: usize) -> Result<u32, ErrorsJSL> {
67    d.get(p..p + 4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])).ok_or(ERR_FORMAT)
68}
69
70/// Parses a WAV byte stream (PCM 8/16/24/32-bit, IEEE float 32/64-bit, plain or extensible headers).
71// ANCHOR: parse_wav
72pub fn parse_wav(data: &[u8]) -> Result<WavAudio, ErrorsJSL> {
73    if data.get(0..4) != Some(b"RIFF") || data.get(8..12) != Some(b"WAVE") {
74        return Err(ERR_FORMAT);
75    }
76    let mut pos = 12;
77    let mut fmt: Option<(u16, u16, u32, u16)> = None; // (tag, channels, rate, bits)
78    let mut payload: Option<&[u8]> = None;
79    while pos + 8 <= data.len() {
80        let id = &data[pos..pos + 4];
81        let size = u32_at(data, pos + 4)? as usize;
82        let body_end = (pos + 8 + size).min(data.len()); // tolerate a truncated final chunk
83        let body = &data[pos + 8..body_end];
84        match id {
85            b"fmt " => {
86                let mut tag = u16_at(body, 0)?;
87                let channels = u16_at(body, 2)?;
88                let rate = u32_at(body, 4)?;
89                let bits = u16_at(body, 14)?;
90                if tag == 0xFFFE {
91                    tag = u16_at(body, 24)?; // first two bytes of the sub-format GUID
92                }
93                fmt = Some((tag, channels, rate, bits));
94            }
95            b"data" => payload = Some(body),
96            _ => {}
97        }
98        pos += 8 + size + (size & 1);
99    }
100    let (tag, channels, sample_rate, bits) = fmt.ok_or(ERR_FORMAT)?;
101    let body = payload.ok_or(ERR_FORMAT)?;
102    if channels == 0 {
103        return Err(ERR_FORMAT);
104    }
105    let bytes = (bits / 8) as usize;
106    let samples: Vec<f32> = match (tag, bits) {
107        (1, 8) => body.iter().map(|&b| (b as f32 - 128.0) / 128.0).collect(),
108        (1, 16) => body.as_chunks::<2>().0.iter().map(|b| i16::from_le_bytes(*b) as f32 / 32768.0).collect(),
109        (1, 24) => body
110            .as_chunks::<3>()
111            .0
112            .iter()
113            .map(|b| (i32::from_le_bytes([0, b[0], b[1], b[2]]) >> 8) as f32 / 8_388_608.0)
114            .collect(),
115        (1, 32) => body.as_chunks::<4>().0.iter().map(|b| (i32::from_le_bytes(*b) as f64 / 2_147_483_648.0) as f32).collect(),
116        (3, 32) => body.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b)).collect(),
117        (3, 64) => body.as_chunks::<8>().0.iter().map(|b| f64::from_le_bytes(*b) as f32).collect(),
118        _ => return Err(ErrorsJSL::InvalidInputRange("Unsupported WAV sample format.")),
119    };
120    debug_assert!(bytes > 0);
121    let whole = samples.len() / channels as usize * channels as usize;
122    Ok(WavAudio { sample_rate, channels, samples: samples[..whole].to_vec() })
123}
124// ANCHOR_END: parse_wav
125
126/// Serialises audio as a canonical WAV file in the requested sample format. Samples outside
127/// `[-1, 1)` are clipped for the integer formats (scale is 2^(bits-1)).
128pub fn encode_wav(audio: &WavAudio, format: WavSampleFormat) -> Result<Vec<u8>, ErrorsJSL> {
129    if audio.channels == 0 || !audio.samples.len().is_multiple_of(audio.channels as usize) {
130        return Err(ErrorsJSL::InvalidInputRange("Sample count must be a multiple of the channel count."));
131    }
132    let bits = format.bits();
133    let block = audio.channels * bits / 8;
134    let data_len = audio.samples.len() * (bits / 8) as usize;
135    if data_len > u32::MAX as usize - 44 {
136        return Err(ErrorsJSL::InvalidInputRange("Audio too large for a WAV file."));
137    }
138    let mut out = Vec::with_capacity(44 + data_len + 1);
139    out.extend_from_slice(b"RIFF");
140    out.extend_from_slice(&((36 + data_len + (data_len & 1)) as u32).to_le_bytes());
141    out.extend_from_slice(b"WAVEfmt ");
142    out.extend_from_slice(&16u32.to_le_bytes());
143    out.extend_from_slice(&(if format.is_float() { 3u16 } else { 1u16 }).to_le_bytes());
144    out.extend_from_slice(&audio.channels.to_le_bytes());
145    out.extend_from_slice(&audio.sample_rate.to_le_bytes());
146    out.extend_from_slice(&(audio.sample_rate * block as u32).to_le_bytes());
147    out.extend_from_slice(&block.to_le_bytes());
148    out.extend_from_slice(&bits.to_le_bytes());
149    out.extend_from_slice(b"data");
150    out.extend_from_slice(&(data_len as u32).to_le_bytes());
151    for &s in &audio.samples {
152        let c = s.clamp(-1.0, 1.0) as f64;
153        match format {
154            WavSampleFormat::Pcm8 => out.push((c * 128.0 + 128.0).round().clamp(0.0, 255.0) as u8),
155            WavSampleFormat::Pcm16 => out.extend_from_slice(&((c * 32768.0).round().clamp(-32768.0, 32767.0) as i16).to_le_bytes()),
156            WavSampleFormat::Pcm24 => out.extend_from_slice(&((c * 8_388_608.0).round().clamp(-8_388_608.0, 8_388_607.0) as i32).to_le_bytes()[..3]),
157            WavSampleFormat::Pcm32 => out.extend_from_slice(&((c * 2_147_483_648.0).round().clamp(-2_147_483_648.0, 2_147_483_647.0) as i32).to_le_bytes()),
158            WavSampleFormat::Float32 => out.extend_from_slice(&s.to_le_bytes()),
159            WavSampleFormat::Float64 => out.extend_from_slice(&(s as f64).to_le_bytes()),
160        }
161    }
162    if data_len & 1 == 1 {
163        out.push(0);
164    }
165    Ok(out)
166}
167
168/// Reads a WAV file from disk.
169pub fn read_wav_file(path: impl AsRef<Path>) -> Result<WavAudio, ErrorsJSL> {
170    let data = std::fs::read(path).map_err(|_| ErrorsJSL::RuntimeError("Could not read the WAV file."))?;
171    parse_wav(&data)
172}
173
174/// Writes a WAV file to disk.
175pub fn write_wav_file(path: impl AsRef<Path>, audio: &WavAudio, format: WavSampleFormat) -> Result<(), ErrorsJSL> {
176    std::fs::write(path, encode_wav(audio, format)?).map_err(|_| ErrorsJSL::RuntimeError("Could not write the WAV file."))
177}
178
179#[cfg(test)]
180mod tests {
181    use super::*;
182
183    fn sine(frames: usize, channels: u16) -> WavAudio {
184        let samples = (0..frames * channels as usize)
185            .map(|i| 0.8 * ((i / channels as usize) as f32 * 0.05 * (1 + i as u32 % channels as u32) as f32).sin())
186            .collect();
187        WavAudio { sample_rate: 44_100, channels, samples }
188    }
189
190    #[test]
191    fn round_trips_every_format_within_quantisation() {
192        let a = sine(500, 2);
193        for (fmt, tol) in [
194            (WavSampleFormat::Pcm8, 1.0 / 128.0),
195            (WavSampleFormat::Pcm16, 1.0 / 32768.0),
196            (WavSampleFormat::Pcm24, 1.0 / 8_388_608.0),
197            (WavSampleFormat::Pcm32, 1e-6),
198            (WavSampleFormat::Float32, 0.0),
199            (WavSampleFormat::Float64, 0.0),
200        ] {
201            let bytes = encode_wav(&a, fmt).unwrap();
202            let b = parse_wav(&bytes).unwrap();
203            assert_eq!((b.sample_rate, b.channels, b.samples.len()), (44_100, 2, a.samples.len()), "{fmt:?}");
204            let worst = a.samples.iter().zip(&b.samples).map(|(x, y)| (x - y).abs()).fold(0.0f32, f32::max);
205            assert!(worst <= tol, "{fmt:?} worst {worst}");
206        }
207    }
208
209    #[test]
210    fn header_layout_and_channel_access() {
211        let a = WavAudio { sample_rate: 8000, channels: 2, samples: vec![0.5, -0.5, 0.25, -0.25] };
212        let bytes = encode_wav(&a, WavSampleFormat::Pcm16).unwrap();
213        assert_eq!(&bytes[0..4], b"RIFF");
214        assert_eq!(&bytes[8..16], b"WAVEfmt ");
215        assert_eq!(u32::from_le_bytes(bytes[4..8].try_into().unwrap()) as usize, bytes.len() - 8);
216        let b = parse_wav(&bytes).unwrap();
217        assert_eq!(b.frames(), 2);
218        assert_eq!(b.channel(1).len(), 2);
219        assert!((b.channel(1)[0] + 0.5).abs() < 1e-4);
220    }
221
222    #[test]
223    fn skips_unknown_chunks_and_rejects_garbage() {
224        let a = sine(10, 1);
225        let mut bytes = encode_wav(&a, WavSampleFormat::Pcm16).unwrap();
226        // Insert an odd-sized LIST chunk (with pad byte) before "data".
227        let data_at = bytes.windows(4).position(|w| w == b"data").unwrap();
228        let mut extra = b"LIST".to_vec();
229        extra.extend_from_slice(&3u32.to_le_bytes());
230        extra.extend_from_slice(&[1, 2, 3, 0]);
231        bytes.splice(data_at..data_at, extra);
232        assert_eq!(parse_wav(&bytes).unwrap().samples.len(), 10);
233        assert!(parse_wav(b"not a wav file at all").is_err());
234        assert!(parse_wav(&bytes[..30]).is_err());
235        assert!(encode_wav(&WavAudio { sample_rate: 1, channels: 2, samples: vec![0.0; 3] }, WavSampleFormat::Pcm16).is_err());
236    }
237
238    #[test]
239    fn file_round_trip() {
240        let path = std::env::temp_dir().join(format!("lib_jsl_wav_test_{}.wav", std::process::id()));
241        let a = sine(100, 1);
242        write_wav_file(&path, &a, WavSampleFormat::Float32).unwrap();
243        assert_eq!(read_wav_file(&path).unwrap(), a);
244        std::fs::remove_file(&path).ok();
245        assert!(read_wav_file(&path).is_err());
246    }
247}