Skip to main content

lactea_host/
wav.rs

1//! Minimal WAV reader (float32 / int16 PCM, mono duplicated to stereo): same rules as the oracle's
2//! `refrender`.
3
4use std::path::Path;
5
6/// Interleaved stereo float audio.
7pub struct Audio {
8    pub data: Vec<f32>,
9    pub frames: u64,
10    pub rate: u32,
11}
12
13fn rd32(b: &[u8]) -> u32 {
14    u32::from_le_bytes([b[0], b[1], b[2], b[3]])
15}
16
17fn rd16(b: &[u8]) -> u16 {
18    u16::from_le_bytes([b[0], b[1]])
19}
20
21/// Read the file at `path`; see [`parse_wav`].
22pub fn load_wav(path: &Path) -> Result<Audio, String> {
23    let buf =
24        std::fs::read(path).map_err(|e| format!("cannot open audio {}: {e}", path.display()))?;
25    parse_wav(&buf)
26}
27
28/// Decode a RIFF/WAVE image: float32 or int16 PCM (also inside `WAVE_FORMAT_EXTENSIBLE`).
29pub fn parse_wav(buf: &[u8]) -> Result<Audio, String> {
30    if buf.len() < 12 || &buf[..4] != b"RIFF" || &buf[8..12] != b"WAVE" {
31        return Err("not a RIFF/WAVE file".into());
32    }
33    let (mut fmt, mut ch, mut bits, mut rate) = (0u16, 0u16, 0u16, 0u32);
34    let mut data: Option<&[u8]> = None;
35    let mut p = 12usize;
36    while p + 8 <= buf.len() {
37        let cl = rd32(&buf[p + 4..]) as usize;
38        let c = &buf[p + 8..];
39        match &buf[p..p + 4] {
40            b"fmt " => {
41                // channels, rate and bits live in the first 16 bytes of the chunk
42                if cl < 16 || c.len() < 16 {
43                    return Err("WAV: fmt chunk shorter than 16 bytes".into());
44                }
45                fmt = rd16(c);
46                ch = rd16(&c[2..]);
47                rate = rd32(&c[4..]);
48                bits = rd16(&c[14..]);
49                if fmt == 0xFFFE {
50                    // the sub-format GUID starts at byte 24 of the extensible chunk
51                    if cl < 26 || c.len() < 26 {
52                        return Err("WAV: extensible fmt chunk shorter than 26 bytes".into());
53                    }
54                    fmt = rd16(&c[24..]);
55                }
56            }
57            b"data" => {
58                data = Some(&c[..cl.min(c.len())]);
59                break;
60            }
61            _ => {}
62        }
63        p += 8 + cl + (cl & 1);
64    }
65    let Some(data) = data else {
66        return Err("WAV: missing fmt/data".into());
67    };
68    if ch < 1 {
69        return Err("WAV: no channels".into());
70    }
71    if !((fmt == 3 && bits == 32) || (fmt == 1 && bits == 16)) {
72        return Err("WAV: only float32 and int16 PCM supported".into());
73    }
74    let bytes = (bits / 8) as usize;
75    let n = data.len() / (ch as usize * bytes);
76    let mut out = Vec::with_capacity(n * 2);
77    for i in 0..n {
78        for c in 0..2usize {
79            let cc = if c < ch as usize { c } else { 0 };
80            let q = &data[(i * ch as usize + cc) * bytes..];
81            out.push(if fmt == 3 {
82                f32::from_bits(rd32(q))
83            } else {
84                f32::from(rd16(q) as i16) / 32768.0
85            });
86        }
87    }
88    Ok(Audio {
89        data: out,
90        frames: n as u64,
91        rate,
92    })
93}
94
95#[cfg(test)]
96mod tests {
97    use super::*;
98
99    fn wav_with_fmt(fmt: &[u8]) -> Vec<u8> {
100        let mut b = b"RIFF\0\0\0\0WAVEfmt ".to_vec();
101        b.extend_from_slice(&(fmt.len() as u32).to_le_bytes());
102        b.extend_from_slice(fmt);
103        b
104    }
105
106    #[test]
107    fn short_fmt_chunk_is_an_error_not_a_panic() {
108        for len in [0usize, 2, 15] {
109            let e = parse_wav(&wav_with_fmt(&vec![0u8; len]))
110                .err()
111                .expect("error");
112            assert!(e.contains("fmt"), "{e}");
113        }
114        // extensible marker without the sub-format bytes
115        let mut fmt = vec![0u8; 16];
116        fmt[..2].copy_from_slice(&0xFFFEu16.to_le_bytes());
117        let e = parse_wav(&wav_with_fmt(&fmt)).err().expect("error");
118        assert!(e.contains("extensible"), "{e}");
119    }
120
121    #[test]
122    fn int16_mono_is_duplicated_to_stereo() {
123        let mut fmt = Vec::new();
124        for v in [1u16, 1] {
125            fmt.extend_from_slice(&v.to_le_bytes());
126        }
127        fmt.extend_from_slice(&8000u32.to_le_bytes());
128        fmt.extend_from_slice(&16000u32.to_le_bytes());
129        fmt.extend_from_slice(&2u16.to_le_bytes());
130        fmt.extend_from_slice(&16u16.to_le_bytes());
131        let mut b = wav_with_fmt(&fmt);
132        b.extend_from_slice(b"data\x04\0\0\0");
133        b.extend_from_slice(&16384i16.to_le_bytes());
134        b.extend_from_slice(&(-32768i16).to_le_bytes());
135        let a = parse_wav(&b).unwrap();
136        assert_eq!((a.frames, a.rate), (2, 8000));
137        assert_eq!(a.data, vec![0.5, 0.5, -1.0, -1.0]);
138    }
139}