forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB8dbd683Tahinli3 months ago856 commits

read.rs232 lines, 8.7 KiBHistoryRawDownload
1//! WAVE reader: chunk-walking, tolerant of everything but a broken `fmt `.
2
3use std::fs::File;
4use std::io::{BufReader, Read};
5use std::path::Path;
6
7use ec_core::{Error, Result};
8
9use crate::{FORMAT_EXTENSIBLE, FORMAT_FLOAT, FORMAT_PCM, SampleType, WavSpec};
10
11/// Reads the header of a WAVE stream, then its samples.
12///
13/// Construction stops at the `data` chunk, so the reader needs only [`Read`]:
14/// chunks before `data` (`LIST`, `INFO`, `fact`, `bext`, anything) are skipped
15/// with their pad byte, and chunks after it are never looked at.
16pub struct WavReader<R: Read> {
17 inner: R,
18 spec: WavSpec,
19 /// Bytes the `data` header claimed, or `None` when it claimed a streaming
20 /// placeholder and the file itself is the bound.
21 data_bytes: Option<u64>,
22}
23
24impl WavReader<BufReader<File>> {
25 /// Open `path` and parse its header.
26 pub fn open<P: AsRef<Path>>(path: P) -> Result<Self> {
27 WavReader::new(BufReader::new(File::open(path)?))
28 }
29}
30
31impl<R: Read> WavReader<R> {
32 /// Parse the header of an already-open stream, leaving it at the samples.
33 pub fn new(mut inner: R) -> Result<Self> {
34 let riff = read_exact::<12, _>(&mut inner)?;
35 if &riff[0..4] != b"RIFF" || &riff[8..12] != b"WAVE" {
36 if &riff[0..4] == b"RF64" {
37 return Err(Error::unsupported(
38 "an RF64/BW64 file",
39 "the 64-bit RIFF extension is not implemented",
40 ));
41 }
42 return Err(Error::corrupt("not a RIFF/WAVE file"));
43 }
44
45 let mut spec = None;
46 loop {
47 let head = read_exact::<8, _>(&mut inner)?;
48 let id = [head[0], head[1], head[2], head[3]];
49 let size = u32::from_le_bytes([head[4], head[5], head[6], head[7]]) as u64;
50 match &id {
51 b"fmt " => spec = Some(parse_fmt(&mut inner, size)?),
52 b"data" => {
53 let spec = spec.ok_or_else(|| {
54 Error::corrupt("WAVE data chunk arrived before any fmt chunk")
55 })?;
56 // 0 and 0xFFFFFFFF are both used by streamed writers that
57 // never came back to patch the size.
58 let data_bytes = (size != 0 && size != u64::from(u32::MAX)).then_some(size);
59 return Ok(WavReader {
60 inner,
61 spec,
62 data_bytes,
63 });
64 }
65 _ => skip(&mut inner, size + size % 2)?,
66 }
67 }
68 }
69
70 /// The `fmt ` chunk as parsed.
71 pub fn spec(&self) -> WavSpec {
72 self.spec
73 }
74
75 /// Frames (one sample per channel) the `data` header claims, when it claims
76 /// one. A truncated file reports fewer from [`Self::read_all_i32`].
77 pub fn duration(&self) -> Option<u64> {
78 self.data_bytes.map(|b| b / self.spec.block_align() as u64)
79 }
80
81 /// Read the whole `data` chunk as interleaved bytes, stopping at whichever
82 /// comes first: the declared size or the end of the stream.
83 fn read_data(&mut self) -> Result<Vec<u8>> {
84 let mut buf = Vec::new();
85 match self.data_bytes {
86 Some(n) => {
87 // `take` + `read_to_end` grows as data actually arrives, so a
88 // header claiming 4 GiB over a 1 KiB file allocates 1 KiB.
89 (&mut self.inner).take(n).read_to_end(&mut buf)?;
90 }
91 None => {
92 self.inner.read_to_end(&mut buf)?;
93 }
94 }
95 let align = self.spec.block_align();
96 buf.truncate(buf.len() / align * align);
97 Ok(buf)
98 }
99
100 /// Read every integer sample, interleaved, sign-extended to `i32`.
101 ///
102 /// Refuses float files: [`Self::read_all_f32`] is their reader.
103 pub fn read_all_i32(&mut self) -> Result<Vec<i32>> {
104 if self.spec.sample_format == SampleType::Float {
105 return Err(Error::unsupported(
106 "reading a float WAVE file as integers",
107 "use read_all_f32; the scale factor is the caller's decision",
108 ));
109 }
110 let bits = self.spec.bits_per_sample;
111 let width = self.spec.bytes_per_sample();
112 let buf = self.read_data()?;
113 Ok(buf
114 .chunks_exact(width)
115 .map(|c| match bits {
116 // Unsigned and biased, alone among the depths.
117 8 => i32::from(c[0]) - 128,
118 16 => i32::from(i16::from_le_bytes([c[0], c[1]])),
119 24 => i32::from_le_bytes([0, c[0], c[1], c[2]]) >> 8,
120 _ => i32::from_le_bytes([c[0], c[1], c[2], c[3]]),
121 })
122 .collect())
123 }
124
125 /// Read every sample as `f32`, interleaved.
126 ///
127 /// Float files pass through untouched; integer files are normalised by
128 /// `2^(bits-1)` — the same scaling the oracle's `pcm_f32le` conversion applies,
129 /// so the two outputs are comparable sample for sample.
130 pub fn read_all_f32(&mut self) -> Result<Vec<f32>> {
131 if self.spec.sample_format == SampleType::Float {
132 let buf = self.read_data()?;
133 return Ok(buf
134 .chunks_exact(4)
135 .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
136 .collect());
137 }
138 let scale = 1.0f32 / (1i64 << (self.spec.bits_per_sample - 1)) as f32;
139 Ok(self
140 .read_all_i32()?
141 .into_iter()
142 .map(|v| v as f32 * scale)
143 .collect())
144 }
145}
146
147/// Read exactly `N` bytes; a short read is a truncated file, not a panic.
148fn read_exact<const N: usize, R: Read>(r: &mut R) -> Result<[u8; N]> {
149 let mut buf = [0u8; N];
150 r.read_exact(&mut buf).map_err(|e| {
151 if e.kind() == std::io::ErrorKind::UnexpectedEof {
152 Error::corrupt("WAVE header ends mid-chunk")
153 } else {
154 Error::Io(e)
155 }
156 })?;
157 Ok(buf)
158}
159
160/// Discard `n` bytes without seeking, so the reader works over pipes too.
161fn skip<R: Read>(r: &mut R, n: u64) -> Result<()> {
162 let copied = std::io::copy(&mut r.take(n), &mut std::io::sink())?;
163 if copied != n {
164 return Err(Error::corrupt("WAVE chunk ends past the end of the file"));
165 }
166 Ok(())
167}
168
169/// Parse a `fmt ` chunk body of `size` bytes, extensible or not.
170fn parse_fmt<R: Read>(r: &mut R, size: u64) -> Result<WavSpec> {
171 if size < 16 {
172 return Err(Error::corrupt(format!("WAVE fmt chunk is {size} bytes")));
173 }
174 let f = read_exact::<16, _>(r)?;
175 let mut tag = u16::from_le_bytes([f[0], f[1]]);
176 let channels = u16::from_le_bytes([f[2], f[3]]);
177 let sample_rate = u32::from_le_bytes([f[4], f[5], f[6], f[7]]);
178 let block_align = u16::from_le_bytes([f[12], f[13]]);
179 let bits_per_sample = u16::from_le_bytes([f[14], f[15]]);
180 let mut rest = size - 16;
181
182 if tag == FORMAT_EXTENSIBLE {
183 if rest < 24 {
184 return Err(Error::corrupt(
185 "WAVE_FORMAT_EXTENSIBLE fmt chunk without its 22-byte extension",
186 ));
187 }
188 let ext = read_exact::<24, _>(r)?;
189 rest -= 24;
190 // Only the first two bytes of the sub-format GUID name the encoding;
191 // the rest is the fixed WAVE tail, and drivers in the wild vary it
192 // enough that rejecting on it would refuse valid files.
193 tag = u16::from_le_bytes([ext[8], ext[9]]);
194 }
195 skip(r, rest + size % 2)?;
196
197 let sample_format = match tag {
198 FORMAT_PCM => SampleType::Int,
199 FORMAT_FLOAT => SampleType::Float,
200 other => {
201 return Err(Error::unsupported(
202 format!("WAVE format tag {other:#06x}"),
203 "ec-riff carries integer and IEEE-float PCM only",
204 ));
205 }
206 };
207 // A depth that is not a whole number of bytes (12-bit, 20-bit) is
208 // ill-formed for these tags, not merely unimplemented: nothing in the
209 // header says how the odd bits sit in their container.
210 if bits_per_sample % 8 != 0 {
211 return Err(Error::corrupt(format!(
212 "WAVE fmt: {bits_per_sample} bits per sample is not a multiple of eight"
213 )));
214 }
215 let spec = WavSpec {
216 channels,
217 sample_rate,
218 bits_per_sample,
219 sample_format,
220 };
221 spec.validate()?;
222 // The stride the file declares must be the stride the depth implies —
223 // otherwise every frame after the first is read from the wrong offset.
224 // Padded containers (8-bit samples in 2-byte slots) live here.
225 if usize::from(block_align) != spec.block_align() {
226 return Err(Error::unsupported(
227 format!("a WAVE block align of {block_align} for {channels}x{bits_per_sample}-bit"),
228 "ec-riff reads samples packed at their declared depth, without container padding",
229 ));
230 }
231 Ok(spec)
232}