forge
Explore
Log in

Don't you dare go Hollow

Hound WavReader, the read half edith's tests call

Browse files at this commit

babff90c298128b49e697877b3b7265c65fe666eAhmet Kaan GümüşParent: ee46976
  • feat
    • hound WavReader, the read half edith's tests call
Show full message
feat(shim): hound WavReader, the read half edith's tests call

The W1 replica swap found the gap: engine's own suite reopens a WAV
export with hound::WavReader and iterates samples::<i16>(), which the
write-only shim could not compile. WavReader/spec/samples now wrap
ec_riff::WavReader, and Sample gains the reader's two constructors and a
width so TooWide and InvalidSampleFormat are decided the way the
incumbent decides them, not by a silent conversion.
shims/hound/src/lib.rsmodified+125 -7
@@ -1,12 +1,12 @@
1-//! `hound` 3.5.1's WAV-writing surface, over [`ec_riff`].
1+//! `hound` 3.5.1's WAV surface, over [`ec_riff`].
22 //!
33 //! This crate exists to be swapped in by `[patch.crates-io]`: it carries the
44 //! incumbent's name and version so a consumer's `use hound::…` compiles
55 //! unchanged. Only what edith consumes is here — `WavWriter::create`,
6-//! `write_sample`, `finalize`, [`WavSpec`], [`SampleFormat`] and an [`Error`]
7-//! with the incumbent's variants — because a shim that grows a surface nobody
8-//! calls is a second implementation to keep honest. Reading is `ec-riff`'s
9-//! [`ec_riff::WavReader`]; the shim does not wrap it.
6+//! `write_sample`, `finalize`, `WavReader::open`, `spec`, `samples`,
7+//! [`WavSpec`], [`SampleFormat`] and an [`Error`] with the incumbent's variants
8+//! — because a shim that grows a surface nobody calls is a second
9+//! implementation to keep honest.
1010 //!
1111 //! Behaviour differences from the incumbent, all in the strict direction:
1212 //! files with more than two channels or more than 16 bits get a
@@ -18,10 +18,47 @@
1818
1919 use std::fmt;
2020 use std::fs::File;
21-use std::io::{self, BufWriter, Seek, Write};
21+use std::io::{self, BufReader, BufWriter, Read, Seek, Write};
2222 use std::path::Path;
2323
24-pub use ec_riff::Sample;
24+/// A sample type a [`WavWriter`] accepts and a [`WavReader`] yields.
25+///
26+/// The write half is [`ec_riff::Sample`]; the two constructors and the width
27+/// are what reading adds, and they are what makes hound's `TooWide` and
28+/// `InvalidSampleFormat` decidable before a single sample is converted.
29+pub trait Sample: ec_riff::Sample {
30+ /// Bits this type carries. A file deeper than this is [`Error::TooWide`].
31+ const BITS: u16;
32+ /// Narrow the reader's integer carrier. Called for integer files only.
33+ fn from_i32(v: i32) -> Self;
34+ /// Take the reader's float carrier. Called for float files only.
35+ fn from_f32(v: f32) -> Self;
36+}
37+
38+macro_rules! int_sample {
39+ ($($t:ty => $bits:expr),*) => {$(
40+ impl Sample for $t {
41+ const BITS: u16 = $bits;
42+ fn from_i32(v: i32) -> Self {
43+ v as $t
44+ }
45+ fn from_f32(v: f32) -> Self {
46+ v as $t
47+ }
48+ }
49+ )*};
50+}
51+int_sample!(i8 => 8, i16 => 16, i32 => 32);
52+
53+impl Sample for f32 {
54+ const BITS: u16 = 32;
55+ fn from_i32(v: i32) -> Self {
56+ v as f32
57+ }
58+ fn from_f32(v: f32) -> Self {
59+ v
60+ }
61+}
2562
2663 /// Whether samples are stored as floats or integers.
2764 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -190,3 +227,84 @@ impl<W: Write + Seek> WavWriter<W> {
190227 .map_err(|e| map(e, Error::UnfinishedSample))
191228 }
192229 }
230+
231+/// Reads a WAVE file's header, then its samples.
232+pub struct WavReader<R: Read> {
233+ inner: ec_riff::WavReader<R>,
234+}
235+
236+impl WavReader<BufReader<File>> {
237+ /// Open `path` and parse its header.
238+ pub fn open<P: AsRef<Path>>(path: P) -> Result<Self> {
239+ WavReader::new(BufReader::new(File::open(path)?))
240+ }
241+}
242+
243+impl<R: Read> WavReader<R> {
244+ /// Parse the header of an already-open stream.
245+ pub fn new(reader: R) -> Result<Self> {
246+ ec_riff::WavReader::new(reader)
247+ .map(|inner| WavReader { inner })
248+ .map_err(|e| map(e, Error::FormatError("not a WAVE file this reader accepts")))
249+ }
250+
251+ /// The `fmt ` chunk as parsed.
252+ pub fn spec(&self) -> WavSpec {
253+ let s = self.inner.spec();
254+ WavSpec {
255+ channels: s.channels,
256+ sample_rate: s.sample_rate,
257+ bits_per_sample: s.bits_per_sample,
258+ sample_format: match s.sample_format {
259+ ec_riff::SampleType::Float => SampleFormat::Float,
260+ ec_riff::SampleType::Int => SampleFormat::Int,
261+ },
262+ }
263+ }
264+
265+ /// Every sample, interleaved in channel order, as the incumbent's fallible
266+ /// iterator: a file whose format or depth `S` cannot carry yields one
267+ /// [`Error::InvalidSampleFormat`] or [`Error::TooWide`] rather than a
268+ /// converted value, which is where hound puts the same refusals.
269+ ///
270+ /// corner-cut: `ec-riff` reads the `data` chunk whole, so this buffers the
271+ /// file where hound streams it — ~10 MB per minute of 48 kHz stereo, fine
272+ /// for the export round-trips edith checks and wrong for an hour of audio.
273+ /// Upgrade path is a streaming `read_samples` on `ec_riff::WavReader`,
274+ /// which this then forwards to unchanged.
275+ pub fn samples<S: Sample>(&mut self) -> WavSamples<S> {
276+ let spec = self.inner.spec();
277+ let float_file = spec.sample_format == ec_riff::SampleType::Float;
278+ let items = if float_file != S::FLOAT {
279+ vec![Err(Error::InvalidSampleFormat)]
280+ } else if spec.bits_per_sample > S::BITS {
281+ vec![Err(Error::TooWide)]
282+ } else if float_file {
283+ match self.inner.read_all_f32() {
284+ Ok(v) => v.into_iter().map(|s| Ok(S::from_f32(s))).collect(),
285+ Err(e) => vec![Err(map(e, Error::FormatError("truncated WAVE data")))],
286+ }
287+ } else {
288+ match self.inner.read_all_i32() {
289+ Ok(v) => v.into_iter().map(|s| Ok(S::from_i32(s))).collect(),
290+ Err(e) => vec![Err(map(e, Error::FormatError("truncated WAVE data")))],
291+ }
292+ };
293+ WavSamples(items.into_iter())
294+ }
295+}
296+
297+/// The iterator [`WavReader::samples`] returns.
298+pub struct WavSamples<S>(std::vec::IntoIter<Result<S>>);
299+
300+impl<S> Iterator for WavSamples<S> {
301+ type Item = Result<S>;
302+
303+ fn next(&mut self) -> Option<Self::Item> {
304+ self.0.next()
305+ }
306+
307+ fn size_hint(&self) -> (usize, Option<usize>) {
308+ self.0.size_hint()
309+ }
310+}
shims/hound/tests/edith_surface.rsmodified+37 -0
@@ -48,6 +48,43 @@ fn edith_write_wav_round_trips() {
4848 }
4949 }
5050
51+/// The read half edith's tests make: `WavReader::open`, `spec()`, and
52+/// `samples::<i16>()` collected — plus the two refusals hound answers with
53+/// when the requested type cannot carry the file.
54+#[test]
55+fn edith_read_wav_round_trips() {
56+ let dir = std::path::Path::new(env!("CARGO_TARGET_TMPDIR"));
57+ std::fs::create_dir_all(dir).unwrap();
58+ let path = dir.join("read-back.wav");
59+ let samples: Vec<i32> = (0..2048).map(|i| ((i * 733) % 65536) - 32768).collect();
60+ write_wav(&path, &samples, 2, 48000).unwrap();
61+
62+ let mut r = hound::WavReader::open(&path).unwrap();
63+ let spec = r.spec();
64+ assert_eq!(spec.channels, 2);
65+ assert_eq!(spec.sample_rate, 48000);
66+ assert_eq!(spec.bits_per_sample, 16);
67+ assert_eq!(spec.sample_format, hound::SampleFormat::Int);
68+ let read: Vec<i32> = r
69+ .samples::<i16>()
70+ .map(|s| i32::from(s.expect("a sample")))
71+ .collect();
72+ assert_eq!(read, samples);
73+
74+ // An integer file read as floats, and a 16-bit file read as 8: the two
75+ // refusals, not silent conversions.
76+ let mut r = hound::WavReader::open(&path).unwrap();
77+ assert!(matches!(
78+ r.samples::<f32>().next(),
79+ Some(Err(hound::Error::InvalidSampleFormat))
80+ ));
81+ let mut r = hound::WavReader::open(&path).unwrap();
82+ assert!(matches!(
83+ r.samples::<i8>().next(),
84+ Some(Err(hound::Error::TooWide))
85+ ));
86+}
87+
5188 #[test]
5289 fn errors_carry_the_incumbent_variants() {
5390 let dir = std::path::Path::new(env!("CARGO_TARGET_TMPDIR"));