forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

read.rs288 lines, 11.1 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, WavCompressed, 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 compressed: Option<WavCompressed>,
20 /// Bytes the `data` header claimed, or `None` when it claimed a streaming
21 /// placeholder and the file itself is the bound.
22 data_bytes: Option<u64>,
23}
24
25impl WavReader<BufReader<File>> {
26 /// Open `path` and parse its header.
27 pub fn open<P: AsRef<Path>>(path: P) -> Result<Self> {
28 WavReader::new(BufReader::new(File::open(path)?))
29 }
30}
31
32impl<R: Read> WavReader<R> {
33 /// Parse the header of an already-open stream, leaving it at the samples.
34 pub fn new(mut inner: R) -> Result<Self> {
35 let riff = read_exact::<12, _>(&mut inner)?;
36 let is_rf64 = &riff[0..4] == b"RF64" || &riff[0..4] == b"BW64";
37 if !(is_rf64 || &riff[0..4] == b"RIFF") || &riff[8..12] != b"WAVE" {
38 return Err(Error::corrupt("not a RIFF/WAVE file"));
39 }
40
41 let mut spec: Option<(WavSpec, Option<WavCompressed>)> = None;
42 // The `ds64` chunk's data size, which an RF64 `data` chunk defers to.
43 let mut ds64_data: Option<u64> = None;
44 loop {
45 let head = read_exact::<8, _>(&mut inner)?;
46 let id = [head[0], head[1], head[2], head[3]];
47 let size = u32::from_le_bytes([head[4], head[5], head[6], head[7]]) as u64;
48 match &id {
49 b"fmt " => spec = Some(parse_fmt(&mut inner, size)?),
50 b"ds64" if is_rf64 => {
51 // riffSize, dataSize, sampleCount, then a table we do not need.
52 if size < 24 {
53 return Err(Error::corrupt(format!("RF64 ds64 chunk is {size} bytes")));
54 }
55 let body = read_exact::<24, _>(&mut inner)?;
56 ds64_data = Some(u64::from_le_bytes(body[8..16].try_into().unwrap_or([0; 8])));
57 skip(&mut inner, size - 24 + size % 2)?;
58 }
59 b"data" => {
60 let (spec, compressed) = spec.ok_or_else(|| {
61 Error::corrupt("WAVE data chunk arrived before any fmt chunk")
62 })?;
63 // 0 and 0xFFFFFFFF are both used by streamed writers that
64 // never came back to patch the size. In RF64 the 0xFFFFFFFF
65 // is a sentinel for the ds64 value; without one it is
66 // the same placeholder as in RIFF.
67 let data_bytes = if size == u64::from(u32::MAX) && is_rf64 {
68 ds64_data
69 } else if size == 0 || size == u64::from(u32::MAX) {
70 None
71 } else {
72 Some(size)
73 };
74 return Ok(WavReader {
75 inner,
76 spec,
77 compressed,
78 data_bytes: data_bytes.filter(|&n| n != 0),
79 });
80 }
81 _ => skip(&mut inner, size + size % 2)?,
82 }
83 }
84 }
85
86 /// The `fmt ` chunk as parsed.
87 pub fn spec(&self) -> WavSpec {
88 self.spec
89 }
90
91 /// Frames (one sample per channel) the `data` header claims, when it claims
92 /// one. A truncated file reports fewer from [`Self::read_all_i32`].
93 pub fn duration(&self) -> Option<u64> {
94 match &self.compressed {
95 Some(c) => self.data_bytes.map(|b| c.frames_in(b)),
96 None => self.data_bytes.map(|b| b / self.spec.block_align() as u64),
97 }
98 }
99
100 /// The format, when it is one of the compressed tags (IMA/MS ADPCM,
101 /// A-law, mu-law) rather than PCM. [`Self::spec`] then describes the
102 /// decoded 16-bit output.
103 pub fn compressed(&self) -> Option<&WavCompressed> {
104 self.compressed.as_ref()
105 }
106
107 /// The `data` chunk's raw bytes, whatever the format.
108 pub fn read_data_bytes(&mut self) -> Result<Vec<u8>> {
109 self.read_data()
110 }
111
112 /// Read the whole `data` chunk as interleaved bytes, stopping at whichever
113 /// comes first: the declared size or the end of the stream.
114 fn read_data(&mut self) -> Result<Vec<u8>> {
115 let mut buf = Vec::new();
116 match self.data_bytes {
117 Some(n) => {
118 // `take` + `read_to_end` grows as data actually arrives, so a
119 // header claiming 4 GiB over a 1 KiB file allocates 1 KiB.
120 (&mut self.inner).take(n).read_to_end(&mut buf)?;
121 }
122 None => {
123 self.inner.read_to_end(&mut buf)?;
124 }
125 }
126 let align = match &self.compressed {
127 Some(c) if c.tag == 0x0006 || c.tag == 0x0007 => usize::from(c.channels.max(1)),
128 Some(_) => 1,
129 None => self.spec.block_align(),
130 };
131 buf.truncate(buf.len() / align * align);
132 Ok(buf)
133 }
134
135 /// Read every integer sample, interleaved, sign-extended to `i32`.
136 ///
137 /// Refuses float files: [`Self::read_all_f32`] is their reader.
138 pub fn read_all_i32(&mut self) -> Result<Vec<i32>> {
139 if self.spec.sample_format == SampleType::Float {
140 return Err(Error::unsupported(
141 "reading a float WAVE file as integers",
142 "use read_all_f32; the scale factor is the caller's decision",
143 ));
144 }
145 let bits = self.spec.bits_per_sample;
146 let width = self.spec.bytes_per_sample();
147 let buf = self.read_data()?;
148 Ok(buf
149 .chunks_exact(width)
150 .map(|c| match bits {
151 // Unsigned and biased, alone among the depths.
152 8 => i32::from(c[0]) - 128,
153 16 => i32::from(i16::from_le_bytes([c[0], c[1]])),
154 24 => i32::from_le_bytes([0, c[0], c[1], c[2]]) >> 8,
155 _ => i32::from_le_bytes([c[0], c[1], c[2], c[3]]),
156 })
157 .collect())
158 }
159
160 /// Read every sample as `f32`, interleaved.
161 ///
162 /// Float files pass through untouched; integer files are normalised by
163 /// `2^(bits-1)` — the same scaling the oracle's `pcm_f32le` conversion applies,
164 /// so the two outputs are comparable sample for sample.
165 pub fn read_all_f32(&mut self) -> Result<Vec<f32>> {
166 if self.spec.sample_format == SampleType::Float {
167 let buf = self.read_data()?;
168 return Ok(buf
169 .as_chunks::<4>().0.iter()
170 .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
171 .collect());
172 }
173 let scale = 1.0f32 / (1i64 << (self.spec.bits_per_sample - 1)) as f32;
174 Ok(self
175 .read_all_i32()?
176 .into_iter()
177 .map(|v| v as f32 * scale)
178 .collect())
179 }
180}
181
182/// Read exactly `N` bytes; a short read is a truncated file, not a panic.
183fn read_exact<const N: usize, R: Read>(r: &mut R) -> Result<[u8; N]> {
184 let mut buf = [0u8; N];
185 r.read_exact(&mut buf).map_err(|e| {
186 if e.kind() == std::io::ErrorKind::UnexpectedEof {
187 Error::corrupt("WAVE header ends mid-chunk")
188 } else {
189 Error::Io(e)
190 }
191 })?;
192 Ok(buf)
193}
194
195/// Discard `n` bytes without seeking, so the reader works over pipes too.
196fn skip<R: Read>(r: &mut R, n: u64) -> Result<()> {
197 let copied = std::io::copy(&mut r.take(n), &mut std::io::sink())?;
198 if copied != n {
199 return Err(Error::corrupt("WAVE chunk ends past the end of the file"));
200 }
201 Ok(())
202}
203
204/// Parse a `fmt ` chunk body of `size` bytes, extensible or not.
205fn parse_fmt<R: Read>(r: &mut R, size: u64) -> Result<(WavSpec, Option<WavCompressed>)> {
206 if size < 16 {
207 return Err(Error::corrupt(format!("WAVE fmt chunk is {size} bytes")));
208 }
209 let f = read_exact::<16, _>(r)?;
210 let mut tag = u16::from_le_bytes([f[0], f[1]]);
211 let channels = u16::from_le_bytes([f[2], f[3]]);
212 let sample_rate = u32::from_le_bytes([f[4], f[5], f[6], f[7]]);
213 let block_align = u16::from_le_bytes([f[12], f[13]]);
214 let bits_per_sample = u16::from_le_bytes([f[14], f[15]]);
215 let mut rest = size - 16;
216 let was_extensible = tag == FORMAT_EXTENSIBLE;
217
218 if tag == FORMAT_EXTENSIBLE {
219 if rest < 24 {
220 return Err(Error::corrupt(
221 "WAVE_FORMAT_EXTENSIBLE fmt chunk without its 22-byte extension",
222 ));
223 }
224 let ext = read_exact::<24, _>(r)?;
225 rest -= 24;
226 // Only the first two bytes of the sub-format GUID name the encoding;
227 // the rest is the fixed WAVE tail, and drivers in the wild vary it
228 // enough that rejecting on it would refuse valid files.
229 tag = u16::from_le_bytes([ext[8], ext[9]]);
230 }
231 let mut extra = Vec::new();
232 if !was_extensible && matches!(tag, 0x0011 | 0x0002 | 0x0006 | 0x0007) && rest >= 2 {
233 // cbSize then its payload.
234 let cb = read_exact::<2, _>(r)?;
235 rest -= 2;
236 let cb = u64::from(u16::from_le_bytes(cb)).min(rest);
237 extra.resize(cb as usize, 0);
238 r.read_exact(&mut extra)?;
239 rest -= cb;
240 }
241 skip(r, rest + size % 2)?;
242 if let Some(c) = WavCompressed::new(tag, channels, block_align, &extra) {
243 let spec = WavSpec {
244 channels,
245 sample_rate,
246 bits_per_sample: 16,
247 sample_format: SampleType::Int,
248 };
249 spec.validate()?;
250 return Ok((spec, Some(c)));
251 }
252
253 let sample_format = match tag {
254 FORMAT_PCM => SampleType::Int,
255 FORMAT_FLOAT => SampleType::Float,
256 other => {
257 return Err(Error::unsupported(
258 format!("WAVE format tag {other:#06x}"),
259 "ec-riff carries integer and IEEE-float PCM only",
260 ));
261 }
262 };
263 // A depth that is not a whole number of bytes (12-bit, 20-bit) is
264 // ill-formed for these tags, not merely unimplemented: nothing in the
265 // header says how the odd bits sit in their container.
266 if bits_per_sample % 8 != 0 {
267 return Err(Error::corrupt(format!(
268 "WAVE fmt: {bits_per_sample} bits per sample is not a multiple of eight"
269 )));
270 }
271 let spec = WavSpec {
272 channels,
273 sample_rate,
274 bits_per_sample,
275 sample_format,
276 };
277 spec.validate()?;
278 // The stride the file declares must be the stride the depth implies —
279 // otherwise every frame after the first is read from the wrong offset.
280 // Padded containers (8-bit samples in 2-byte slots) live here.
281 if usize::from(block_align) != spec.block_align() {
282 return Err(Error::unsupported(
283 format!("a WAVE block align of {block_align} for {channels}x{bits_per_sample}-bit"),
284 "ec-riff reads samples packed at their declared depth, without container padding",
285 ));
286 }
287 Ok((spec, None))
288}