forge
Explore
Log in

Don't you dare go Hollow

WAV reader/writer and the hound shim over it

Browse files at this commit

5dd56cfe9f4bab8db77c7447adab0425cb447faaAhmet Kaan GümüşParent: b05a16e
  • feat
    • WAV reader/writer and the hound shim over it
Show full message
feat(riff): WAV reader/writer and the hound shim over it

ec-riff writes and reads RIFF/WAVE: 8/16/24/32-bit integer PCM and 32-bit
float, mono through 7.1, any sample rate. The writer streams and patches the
RIFF, data and fact sizes in finalize (best-effort on drop), and emits
WAVE_FORMAT_EXTENSIBLE with a channel mask whenever a file has more than two
channels or more than 16 bits. The reader walks the chunk list rather than
assuming fmt-then-data, so LIST/INFO, fact and odd-sized chunks with their pad
byte are skipped, and a truncated or unpatched data size yields what is
actually there. RF64, ADPCM and 64-bit float are refused by name.

shims/hound carries package name hound 3.5.1 over ec-riff, covering exactly
what edith consumes: WavWriter::create/write_sample/finalize, WavSpec,
SampleFormat and an Error with the incumbent's variants.

Checks: cargo test -p ec-riff -p hound (10 tests), and the emitted oracle
artifacts compared against ffmpeg's own decode - 5 written formats and the 6
wav fixtures all PASS at corr 1.000000, RMS delta 0.
Cargo.lockmodified+14 -0
@@ -19,6 +19,20 @@ dependencies = [
1919 "wide",
2020 ]
2121
22+[[package]]
23+name = "ec-riff"
24+version = "0.1.0"
25+dependencies = [
26+ "ec-core",
27+]
28+
29+[[package]]
30+name = "hound"
31+version = "3.5.1"
32+dependencies = [
33+ "ec-riff",
34+]
35+
2236 [[package]]
2337 name = "oracle"
2438 version = "0.1.0"
Cargo.tomlmodified+1 -0
@@ -10,6 +10,7 @@ authors = ["Ahmet Kaan Gümüş"]
1010
1111 [workspace.dependencies]
1212 ec-core = { path = "crates/ec-core", version = "0.1.0" }
13+ec-riff = { path = "crates/ec-riff", version = "0.1.0" }
1314 ec-dsp = { path = "crates/ec-dsp", version = "0.1.0" }
1415 # Portable SIMD without asm or build-time tooling (family rule: pure Rust only).
1516 wide = "1.5"
crates/ec-riff/Cargo.tomladded+10 -0
@@ -0,0 +1,10 @@
1+[package]
2+name = "ec-riff"
3+description = "RIFF/WAVE reader and writer: integer and float PCM, mono through 7.1, WAVE_FORMAT_EXTENSIBLE."
4+version.workspace = true
5+edition.workspace = true
6+license.workspace = true
7+authors.workspace = true
8+
9+[dependencies]
10+ec-core.workspace = true
crates/ec-riff/src/lib.rsadded+152 -0
@@ -0,0 +1,152 @@
1+//! RIFF/WAVE: the container edith writes PCM into and reads PCM back from.
2+//!
3+//! [`WavWriter`] streams samples as they arrive and patches the RIFF, `data`
4+//! and `fact` sizes in [`WavWriter::finalize`] — a dropped writer therefore
5+//! leaves a file whose header lies, which is why finalizing is fallible and
6+//! explicit. [`WavReader`] walks the chunk list rather than assuming
7+//! `fmt `-then-`data`, so `LIST`/`INFO`, `fact`, `bext` and any other chunk a
8+//! recorder inserted are skipped, odd-sized chunks included (RIFF pads them to
9+//! an even boundary and the padding byte is not part of the chunk).
10+//!
11+//! Covered: 8/16/24/32-bit integer PCM and 32-bit float, 1 to 8 channels
12+//! (mono through 7.1), any sample rate. `WAVE_FORMAT_EXTENSIBLE` is written
13+//! whenever the file has more than two channels or more than 16 bits per
14+//! sample — the depth/layout combinations where players are entitled to
15+//! distrust a plain `WAVE_FORMAT_PCM` header — and is read whatever the file
16+//! declares.
17+//!
18+//! Not covered: RF64/BW64 (>4 GiB), ADPCM and other compressed WAVE tags,
19+//! 64-bit float. Each is [`Error::Unsupported`] naming itself, never a silent
20+//! misread.
21+//!
22+//! The crate stands alone — [`WavSpec`] is its own type — but converts into the
23+//! family IR on request: [`WavSpec::sample_format`] and [`WavSpec::layout`].
24+
25+#![forbid(unsafe_code)]
26+#![warn(missing_docs)]
27+
28+mod read;
29+mod write;
30+
31+pub use ec_core::{Error, Result};
32+pub use read::WavReader;
33+pub use write::{Sample, WavWriter};
34+
35+/// Whether samples are stored as integers (`WAVE_FORMAT_PCM`) or as floats
36+/// (`WAVE_FORMAT_IEEE_FLOAT`).
37+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
38+pub enum SampleType {
39+ /// Signed integers, except 8-bit which RIFF stores unsigned and biased.
40+ Int,
41+ /// IEEE floats, nominal range -1.0..=1.0.
42+ Float,
43+}
44+
45+/// What the `fmt ` chunk says about the audio.
46+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
47+pub struct WavSpec {
48+ /// Channel count, 1..=8 for the layouts this crate names.
49+ pub channels: u16,
50+ /// Sample rate in Hz; any rate the source states.
51+ pub sample_rate: u32,
52+ /// Bits per sample: 8, 16, 24 or 32 for [`SampleType::Int`], 32 for float.
53+ pub bits_per_sample: u16,
54+ /// Integer or float storage.
55+ pub sample_format: SampleType,
56+}
57+
58+/// `WAVE_FORMAT_PCM`.
59+const FORMAT_PCM: u16 = 1;
60+/// `WAVE_FORMAT_IEEE_FLOAT`.
61+const FORMAT_FLOAT: u16 = 3;
62+/// `WAVE_FORMAT_EXTENSIBLE`.
63+const FORMAT_EXTENSIBLE: u16 = 0xFFFE;
64+
65+impl WavSpec {
66+ /// Bytes one sample of one channel occupies in the file.
67+ pub fn bytes_per_sample(&self) -> usize {
68+ usize::from(self.bits_per_sample).div_ceil(8)
69+ }
70+
71+ /// Bytes one frame (one sample of every channel) occupies.
72+ pub fn block_align(&self) -> usize {
73+ self.bytes_per_sample() * usize::from(self.channels)
74+ }
75+
76+ /// The equivalent family sample format. 24-bit widens to
77+ /// [`ec_core::SampleFormat::S32`], as the IR documents.
78+ pub fn sample_format(&self) -> Result<ec_core::SampleFormat> {
79+ use ec_core::SampleFormat as F;
80+ match (self.sample_format, self.bits_per_sample) {
81+ (SampleType::Int, 8) => Ok(F::U8),
82+ (SampleType::Int, 16) => Ok(F::S16),
83+ (SampleType::Int, 24 | 32) => Ok(F::S32),
84+ (SampleType::Float, 32) => Ok(F::F32),
85+ (t, b) => Err(Error::unsupported(
86+ format!("{b}-bit {t:?} WAVE samples"),
87+ "ec-riff carries 8/16/24/32-bit integer and 32-bit float PCM",
88+ )),
89+ }
90+ }
91+
92+ /// The channel layout a bare channel count implies (mono, stereo, 5.1, 7.1).
93+ pub fn layout(&self) -> ec_core::ChannelLayout {
94+ ec_core::ChannelLayout::from_count(usize::from(self.channels))
95+ }
96+
97+ /// Validate what a header must satisfy before either direction trusts it.
98+ fn validate(&self) -> Result<()> {
99+ if self.channels == 0 {
100+ return Err(Error::corrupt("WAVE fmt: zero channels"));
101+ }
102+ if self.sample_rate == 0 {
103+ return Err(Error::corrupt("WAVE fmt: zero sample rate"));
104+ }
105+ self.sample_format().map(|_| ())
106+ }
107+
108+ /// `WAVE_FORMAT_EXTENSIBLE` is due for more than two channels or more than
109+ /// 16 bits — the cases where a bare PCM tag is ambiguous about layout.
110+ fn is_extensible(&self) -> bool {
111+ self.channels > 2 || self.bits_per_sample > 16
112+ }
113+
114+ /// The `dwChannelMask` for the implied layout; 0 when the count has no
115+ /// standard mask, which is legal and means "unassigned".
116+ fn channel_mask(&self) -> u32 {
117+ use ec_core::ChannelPosition as P;
118+ let layout = self.layout();
119+ let mut mask = 0u32;
120+ for p in layout.positions() {
121+ mask |= match p {
122+ P::FrontLeft => 0x1,
123+ P::FrontRight => 0x2,
124+ P::FrontCenter => 0x4,
125+ P::Lfe => 0x8,
126+ P::BackLeft => 0x10,
127+ P::BackRight => 0x20,
128+ P::FrontLeftOfCenter => 0x40,
129+ P::FrontRightOfCenter => 0x80,
130+ P::BackCenter => 0x100,
131+ P::SideLeft => 0x200,
132+ P::SideRight => 0x400,
133+ };
134+ }
135+ // `ChannelLayout::from_count` fills unknown counts with repeated
136+ // FrontCenter, which would collapse to a one-bit mask claiming fewer
137+ // channels than the header. Unassigned is the honest answer there.
138+ if mask.count_ones() as u16 != self.channels {
139+ 0
140+ } else {
141+ mask
142+ }
143+ }
144+
145+ /// The `wFormatTag` (or extensible sub-format tag) for this spec.
146+ fn format_tag(&self) -> u16 {
147+ match self.sample_format {
148+ SampleType::Int => FORMAT_PCM,
149+ SampleType::Float => FORMAT_FLOAT,
150+ }
151+ }
152+}
crates/ec-riff/src/read.rsadded+214 -0
@@ -0,0 +1,214 @@
1+//! WAVE reader: chunk-walking, tolerant of everything but a broken `fmt `.
2+
3+use std::fs::File;
4+use std::io::{BufReader, Read};
5+use std::path::Path;
6+
7+use ec_core::{Error, Result};
8+
9+use 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.
16+pub 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+
24+impl 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+
31+impl<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 ffmpeg'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.
148+fn 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.
161+fn 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.
170+fn 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 bits_per_sample = u16::from_le_bytes([f[14], f[15]]);
179+ let mut rest = size - 16;
180+
181+ if tag == FORMAT_EXTENSIBLE {
182+ if rest < 24 {
183+ return Err(Error::corrupt(
184+ "WAVE_FORMAT_EXTENSIBLE fmt chunk without its 22-byte extension",
185+ ));
186+ }
187+ let ext = read_exact::<24, _>(r)?;
188+ rest -= 24;
189+ // Only the first two bytes of the sub-format GUID name the encoding;
190+ // the rest is the fixed WAVE tail, and drivers in the wild vary it
191+ // enough that rejecting on it would refuse valid files.
192+ tag = u16::from_le_bytes([ext[8], ext[9]]);
193+ }
194+ skip(r, rest + size % 2)?;
195+
196+ let sample_format = match tag {
197+ FORMAT_PCM => SampleType::Int,
198+ FORMAT_FLOAT => SampleType::Float,
199+ other => {
200+ return Err(Error::unsupported(
201+ format!("WAVE format tag {other:#06x}"),
202+ "ec-riff carries integer and IEEE-float PCM only",
203+ ));
204+ }
205+ };
206+ let spec = WavSpec {
207+ channels,
208+ sample_rate,
209+ bits_per_sample,
210+ sample_format,
211+ };
212+ spec.validate()?;
213+ Ok(spec)
214+}
crates/ec-riff/src/write.rsadded+274 -0
@@ -0,0 +1,274 @@
1+//! Streaming WAVE writer.
2+
3+use std::fs::File;
4+use std::io::{BufWriter, Seek, SeekFrom, Write};
5+use std::path::Path;
6+
7+use ec_core::{Error, Result};
8+
9+use crate::{FORMAT_EXTENSIBLE, SampleType, WavSpec};
10+
11+/// A sample a [`WavWriter`] accepts.
12+///
13+/// Integer types write to integer files and `f32` writes to float files; the
14+/// crossing combinations are refused rather than guessed at, because the scale
15+/// factor between them is a decision the caller owns.
16+pub trait Sample: Copy {
17+ /// True for the float carriers.
18+ const FLOAT: bool;
19+ /// The value as a 32-bit integer, at the file's own depth.
20+ fn as_i32(self) -> i32;
21+ /// The value as an `f32`.
22+ fn as_f32(self) -> f32;
23+}
24+
25+macro_rules! int_sample {
26+ ($($t:ty),*) => {$(
27+ impl Sample for $t {
28+ const FLOAT: bool = false;
29+ fn as_i32(self) -> i32 {
30+ i32::from(self)
31+ }
32+ fn as_f32(self) -> f32 {
33+ self as f32
34+ }
35+ }
36+ )*};
37+}
38+int_sample!(i8, i16);
39+
40+impl Sample for i32 {
41+ const FLOAT: bool = false;
42+ fn as_i32(self) -> i32 {
43+ self
44+ }
45+ fn as_f32(self) -> f32 {
46+ self as f32
47+ }
48+}
49+
50+impl Sample for f32 {
51+ const FLOAT: bool = true;
52+ fn as_i32(self) -> i32 {
53+ self as i32
54+ }
55+ fn as_f32(self) -> f32 {
56+ self
57+ }
58+}
59+
60+/// Writes a WAVE file sample by sample, patching the sizes in [`Self::finalize`].
61+///
62+/// Samples are interleaved in channel order: one call per channel per frame.
63+pub struct WavWriter<W: Write + Seek> {
64+ /// `None` only after [`WavWriter::finalize`] has taken it, which is also
65+ /// what tells `Drop` there is nothing left to patch.
66+ inner: Option<W>,
67+ spec: WavSpec,
68+ /// Absolute offset of the `RIFF` size field.
69+ riff_size_pos: u64,
70+ /// Absolute offset of the `fact` sample-count field, when one was written.
71+ fact_pos: Option<u64>,
72+ /// Absolute offset of the `data` size field.
73+ data_size_pos: u64,
74+ /// Samples (not frames) written so far.
75+ samples: u64,
76+}
77+
78+impl WavWriter<BufWriter<File>> {
79+ /// Create `path`, truncating it, and write the header for `spec`.
80+ pub fn create<P: AsRef<Path>>(path: P, spec: WavSpec) -> Result<Self> {
81+ WavWriter::new(BufWriter::new(File::create(path)?), spec)
82+ }
83+}
84+
85+impl<W: Write + Seek> WavWriter<W> {
86+ /// Write the header for `spec` at the writer's current position.
87+ pub fn new(mut inner: W, spec: WavSpec) -> Result<Self> {
88+ spec.validate()?;
89+ let start = inner.stream_position()?;
90+ let extensible = spec.is_extensible();
91+ let fmt_len: u32 = if extensible { 40 } else { 16 };
92+ let mut h: Vec<u8> = Vec::with_capacity(60);
93+
94+ h.extend_from_slice(b"RIFF");
95+ let riff_size_pos = start + h.len() as u64;
96+ h.extend_from_slice(&0u32.to_le_bytes()); // patched by finalize
97+ h.extend_from_slice(b"WAVE");
98+
99+ h.extend_from_slice(b"fmt ");
100+ h.extend_from_slice(&fmt_len.to_le_bytes());
101+ let tag = if extensible {
102+ FORMAT_EXTENSIBLE
103+ } else {
104+ spec.format_tag()
105+ };
106+ let block_align = spec.block_align() as u32;
107+ h.extend_from_slice(&tag.to_le_bytes());
108+ h.extend_from_slice(&spec.channels.to_le_bytes());
109+ h.extend_from_slice(&spec.sample_rate.to_le_bytes());
110+ h.extend_from_slice(&(spec.sample_rate * block_align).to_le_bytes());
111+ h.extend_from_slice(&(block_align as u16).to_le_bytes());
112+ h.extend_from_slice(&spec.bits_per_sample.to_le_bytes());
113+ if extensible {
114+ h.extend_from_slice(&22u16.to_le_bytes()); // cbSize
115+ h.extend_from_slice(&spec.bits_per_sample.to_le_bytes()); // valid bits
116+ h.extend_from_slice(&spec.channel_mask().to_le_bytes());
117+ // KSDATAFORMAT_SUBTYPE_{PCM,IEEE_FLOAT}: the tag, then the fixed
118+ // `0000-0010-8000-00aa00389b71` tail every WAVE sub-format shares.
119+ h.extend_from_slice(&spec.format_tag().to_le_bytes());
120+ h.extend_from_slice(&[0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00]);
121+ h.extend_from_slice(&[0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71]);
122+ }
123+
124+ // A `fact` chunk is required for every non-PCM tag and harmless for the
125+ // extensible PCM one; it holds the frame count, which finalize knows.
126+ let fact_pos = if extensible || spec.sample_format == SampleType::Float {
127+ h.extend_from_slice(b"fact");
128+ h.extend_from_slice(&4u32.to_le_bytes());
129+ let pos = start + h.len() as u64;
130+ h.extend_from_slice(&0u32.to_le_bytes());
131+ Some(pos)
132+ } else {
133+ None
134+ };
135+
136+ h.extend_from_slice(b"data");
137+ let data_size_pos = start + h.len() as u64;
138+ h.extend_from_slice(&0u32.to_le_bytes());
139+ inner.write_all(&h)?;
140+
141+ Ok(WavWriter {
142+ inner: Some(inner),
143+ spec,
144+ riff_size_pos,
145+ fact_pos,
146+ data_size_pos,
147+ samples: 0,
148+ })
149+ }
150+
151+ /// The stream being written; present until `finalize` takes it.
152+ fn w(&mut self) -> &mut W {
153+ self.inner.as_mut().expect("WavWriter used after finalize")
154+ }
155+
156+ /// The spec the header was written with.
157+ pub fn spec(&self) -> WavSpec {
158+ self.spec
159+ }
160+
161+ /// Frames (one sample per channel) written so far.
162+ pub fn duration(&self) -> u64 {
163+ self.samples / u64::from(self.spec.channels)
164+ }
165+
166+ /// Write one sample of one channel.
167+ pub fn write_sample<S: Sample>(&mut self, sample: S) -> Result<()> {
168+ let bits = self.spec.bits_per_sample;
169+ match self.spec.sample_format {
170+ SampleType::Float => {
171+ if !S::FLOAT {
172+ return Err(Error::unsupported(
173+ "integer samples into a float WAVE file",
174+ "the integer-to-float scale factor is the caller's decision",
175+ ));
176+ }
177+ self.w().write_all(&sample.as_f32().to_le_bytes())?;
178+ }
179+ SampleType::Int => {
180+ if S::FLOAT {
181+ return Err(Error::unsupported(
182+ "float samples into an integer WAVE file",
183+ "the float-to-integer scale factor is the caller's decision",
184+ ));
185+ }
186+ let v = sample.as_i32();
187+ let limit = 1i64 << (bits - 1);
188+ if i64::from(v) < -limit || i64::from(v) >= limit {
189+ return Err(Error::corrupt(format!(
190+ "sample {v} does not fit {bits} bits"
191+ )));
192+ }
193+ match bits {
194+ // 8-bit WAVE is unsigned, biased by 128.
195+ 8 => self.w().write_all(&[(v + 128) as u8])?,
196+ 16 => self.w().write_all(&(v as i16).to_le_bytes())?,
197+ 24 => self.w().write_all(&v.to_le_bytes()[..3])?,
198+ _ => self.w().write_all(&v.to_le_bytes())?,
199+ }
200+ }
201+ }
202+ self.samples += 1;
203+ Ok(())
204+ }
205+
206+ /// Write a run of interleaved samples.
207+ pub fn write_samples<S: Sample>(&mut self, samples: &[S]) -> Result<()> {
208+ for &s in samples {
209+ self.write_sample(s)?;
210+ }
211+ Ok(())
212+ }
213+
214+ /// Pad to an even boundary, patch the sizes, flush, and hand the stream back.
215+ ///
216+ /// Dropping instead patches on a best-effort basis and swallows the error;
217+ /// only this reports the difference between a finished file and a truncated
218+ /// one, which is why it exists next to `Drop`.
219+ pub fn finalize(mut self) -> Result<W> {
220+ if !self.samples.is_multiple_of(u64::from(self.spec.channels)) {
221+ return Err(Error::corrupt(format!(
222+ "{} samples is not a whole number of {}-channel frames",
223+ self.samples, self.spec.channels
224+ )));
225+ }
226+ self.patch()?;
227+ self.w().flush()?;
228+ Ok(self.inner.take().expect("WavWriter finalized twice"))
229+ }
230+
231+ /// The size patching both `finalize` and `Drop` go through.
232+ fn patch(&mut self) -> Result<()> {
233+ let data_bytes = self.samples * self.spec.bytes_per_sample() as u64;
234+ let end = self.data_size_pos + 4 + data_bytes;
235+ // RIFF chunks are word-aligned: an odd `data` gets a pad byte that its
236+ // own size field does not count.
237+ let pad = data_bytes % 2;
238+ let riff_size = end + pad - (self.riff_size_pos + 4);
239+ if riff_size > u64::from(u32::MAX) {
240+ return Err(Error::unsupported(
241+ "a WAVE file larger than 4 GiB",
242+ "the 64-bit RF64/BW64 extension is not implemented",
243+ ));
244+ }
245+ let (riff_pos, data_pos) = (self.riff_size_pos, self.data_size_pos);
246+ let fact = self
247+ .fact_pos
248+ .map(|pos| (pos, (self.samples / u64::from(self.spec.channels)) as u32));
249+ let w = self.w();
250+ if pad == 1 {
251+ w.seek(SeekFrom::Start(end))?;
252+ w.write_all(&[0])?;
253+ }
254+ w.seek(SeekFrom::Start(riff_pos))?;
255+ w.write_all(&(riff_size as u32).to_le_bytes())?;
256+ if let Some((pos, frames)) = fact {
257+ w.seek(SeekFrom::Start(pos))?;
258+ w.write_all(&frames.to_le_bytes())?;
259+ }
260+ w.seek(SeekFrom::Start(data_pos))?;
261+ w.write_all(&(data_bytes as u32).to_le_bytes())?;
262+ w.seek(SeekFrom::Start(end + pad))?;
263+ Ok(())
264+ }
265+}
266+
267+impl<W: Write + Seek> Drop for WavWriter<W> {
268+ fn drop(&mut self) {
269+ if self.inner.is_some() {
270+ let _ = self.patch();
271+ let _ = self.w().flush();
272+ }
273+ }
274+}
crates/ec-riff/tests/wav.rsadded+314 -0
@@ -0,0 +1,314 @@
1+//! Round-trip, header and tolerance checks, plus the fixtures on disk.
2+//!
3+//! The oracle artifacts this writes into `CARGO_TARGET_TMPDIR/oracle` are the
4+//! ffmpeg half of the story: after `cargo test -p ec-riff`, each `<name>.wav`
5+//! is compared against its `<name>.raw` (the samples that went in, as f32le)
6+//! with `oracle audio-compare <name>.raw <name>.wav`.
7+
8+use std::io::Cursor;
9+
10+use ec_riff::{SampleType, WavReader, WavSpec, WavWriter};
11+
12+/// Deterministic samples in `bits`-bit range: a walking pattern that exercises
13+/// both signs and the extremes of the depth.
14+fn int_samples(n: usize, bits: u16) -> Vec<i32> {
15+ let limit = 1i64 << (bits - 1);
16+ (0..n)
17+ .map(|i| match i % 5 {
18+ 0 => (limit - 1) as i32,
19+ 1 => (-limit) as i32,
20+ 2 => 0,
21+ 3 => ((i as i64 * 2_654_435_761) % limit) as i32,
22+ _ => -(((i as i64 * 40_503) % limit) as i32),
23+ })
24+ .collect()
25+}
26+
27+fn float_samples(n: usize) -> Vec<f32> {
28+ (0..n)
29+ .map(|i| match i % 4 {
30+ 0 => 1.0,
31+ 1 => -1.0,
32+ 2 => 0.0,
33+ _ => (i as f32 * 0.017).sin(),
34+ })
35+ .collect()
36+}
37+
38+fn spec(channels: u16, rate: u32, bits: u16, sample_format: SampleType) -> WavSpec {
39+ WavSpec {
40+ channels,
41+ sample_rate: rate,
42+ bits_per_sample: bits,
43+ sample_format,
44+ }
45+}
46+
47+#[test]
48+fn int_round_trip_is_bit_exact_every_depth_layout_and_rate() {
49+ for bits in [8u16, 16, 24, 32] {
50+ for channels in [1u16, 2, 6, 8] {
51+ for rate in [8000u32, 44100, 48000, 192_000] {
52+ let s = spec(channels, rate, bits, SampleType::Int);
53+ let samples = int_samples(usize::from(channels) * 97, bits);
54+ let mut w = WavWriter::new(Cursor::new(Vec::new()), s).unwrap();
55+ w.write_samples(&samples).unwrap();
56+ let bytes = w.finalize().unwrap().into_inner();
57+ let mut r = WavReader::new(Cursor::new(&bytes[..])).unwrap();
58+ assert_eq!(r.spec(), s, "spec round-trip {bits}b {channels}ch {rate}Hz");
59+ assert_eq!(
60+ r.duration(),
61+ Some(97),
62+ "frame count {bits}b {channels}ch {rate}Hz"
63+ );
64+ assert_eq!(
65+ r.read_all_i32().unwrap(),
66+ samples,
67+ "samples {bits}b {channels}ch {rate}Hz"
68+ );
69+ assert_eq!(bytes.len() % 2, 0, "RIFF stays word-aligned");
70+ }
71+ }
72+ }
73+}
74+
75+#[test]
76+fn float_round_trip_is_bit_exact() {
77+ for channels in [1u16, 2, 6, 8] {
78+ let s = spec(channels, 48000, 32, SampleType::Float);
79+ let samples = float_samples(usize::from(channels) * 64);
80+ let mut w = WavWriter::new(Cursor::new(Vec::new()), s).unwrap();
81+ w.write_samples(&samples).unwrap();
82+ let bytes = w.finalize().unwrap().into_inner();
83+ let mut r = WavReader::new(Cursor::new(&bytes[..])).unwrap();
84+ assert_eq!(r.spec(), s);
85+ assert_eq!(r.read_all_f32().unwrap(), samples, "{channels}ch float");
86+ }
87+}
88+
89+#[test]
90+fn header_says_extensible_exactly_when_it_must() {
91+ // <=2 channels and <=16 bits: plain WAVE_FORMAT_PCM, 16-byte fmt.
92+ for (channels, bits, extensible) in [
93+ (1u16, 8u16, false),
94+ (2, 16, false),
95+ (1, 24, true),
96+ (2, 32, true),
97+ (6, 16, true),
98+ (8, 16, true),
99+ ] {
100+ let s = spec(channels, 48000, bits, SampleType::Int);
101+ let mut w = WavWriter::new(Cursor::new(Vec::new()), s).unwrap();
102+ w.write_samples(&vec![0i32; usize::from(channels)]).unwrap();
103+ let bytes = w.finalize().unwrap().into_inner();
104+
105+ let fmt_size = u32::from_le_bytes(bytes[16..20].try_into().unwrap());
106+ let tag = u16::from_le_bytes(bytes[20..22].try_into().unwrap());
107+ let block_align = u16::from_le_bytes(bytes[32..34].try_into().unwrap());
108+ let byte_rate = u32::from_le_bytes(bytes[28..32].try_into().unwrap());
109+ assert_eq!(
110+ fmt_size,
111+ if extensible { 40 } else { 16 },
112+ "{channels}ch {bits}b"
113+ );
114+ assert_eq!(
115+ tag,
116+ if extensible { 0xFFFE } else { 1 },
117+ "{channels}ch {bits}b"
118+ );
119+ assert_eq!(u32::from(block_align), (bits as u32 / 8) * channels as u32);
120+ assert_eq!(byte_rate, 48000 * u32::from(block_align));
121+ if extensible {
122+ let mask = u32::from_le_bytes(bytes[40..44].try_into().unwrap());
123+ let expect = match channels {
124+ 1 => 0x4, // FC
125+ 2 => 0x3, // FL FR
126+ 6 => 0x3F, // FL FR FC LFE BL BR
127+ 8 => 0x63F, // + SL SR
128+ _ => unreachable!(),
129+ };
130+ assert_eq!(mask, expect, "channel mask {channels}ch");
131+ // Sub-format GUID starts with the real tag, then the WAVE tail.
132+ assert_eq!(&bytes[44..46], &1u16.to_le_bytes());
133+ assert_eq!(&bytes[54..60], &[0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71]);
134+ }
135+ // Every file the writer produces reads back as itself.
136+ assert_eq!(WavReader::new(Cursor::new(&bytes[..])).unwrap().spec(), s);
137+ }
138+}
139+
140+#[test]
141+fn reader_skips_junk_odd_and_list_chunks() {
142+ // A hand-built file: LIST/INFO before fmt, an odd-sized chunk with its pad
143+ // byte between fmt and data, and a trailing chunk after data.
144+ let mut f: Vec<u8> = Vec::new();
145+ f.extend_from_slice(b"RIFF\0\0\0\0WAVE");
146+ f.extend_from_slice(b"LIST");
147+ f.extend_from_slice(&12u32.to_le_bytes());
148+ f.extend_from_slice(b"INFOISFT\x04\0\0\0");
149+ f.extend_from_slice(b"fmt ");
150+ f.extend_from_slice(&16u32.to_le_bytes());
151+ f.extend_from_slice(&1u16.to_le_bytes()); // PCM
152+ f.extend_from_slice(&2u16.to_le_bytes()); // stereo
153+ f.extend_from_slice(&44100u32.to_le_bytes());
154+ f.extend_from_slice(&(44100u32 * 4).to_le_bytes());
155+ f.extend_from_slice(&4u16.to_le_bytes());
156+ f.extend_from_slice(&16u16.to_le_bytes());
157+ f.extend_from_slice(b"junk");
158+ f.extend_from_slice(&3u32.to_le_bytes());
159+ f.extend_from_slice(&[1, 2, 3, 0]); // 3 bytes + RIFF pad
160+ f.extend_from_slice(b"data");
161+ f.extend_from_slice(&8u32.to_le_bytes());
162+ for v in [1i16, -1, 32767, -32768] {
163+ f.extend_from_slice(&v.to_le_bytes());
164+ }
165+ f.extend_from_slice(b"id3 ");
166+ f.extend_from_slice(&2u32.to_le_bytes());
167+ f.extend_from_slice(&[0, 0]);
168+
169+ let mut r = WavReader::new(Cursor::new(&f[..])).unwrap();
170+ assert_eq!(r.spec().channels, 2);
171+ assert_eq!(r.spec().sample_rate, 44100);
172+ assert_eq!(r.duration(), Some(2));
173+ // The trailing chunk is not audio: exactly the declared 4 samples come out.
174+ assert_eq!(r.read_all_i32().unwrap(), vec![1, -1, 32767, -32768]);
175+}
176+
177+#[test]
178+fn truncated_and_placeholder_sizes_read_what_is_there() {
179+ let s = spec(2, 48000, 16, SampleType::Int);
180+ let samples = int_samples(20, 16);
181+ let mut w = WavWriter::new(Cursor::new(Vec::new()), s).unwrap();
182+ w.write_samples(&samples).unwrap();
183+ let good = w.finalize().unwrap().into_inner();
184+
185+ // Header claims the full length, file is cut in half.
186+ let cut = good[..good.len() - 20].to_vec();
187+ let mut r = WavReader::new(Cursor::new(&cut[..])).unwrap();
188+ assert_eq!(r.read_all_i32().unwrap(), samples[..10].to_vec());
189+
190+ // A streaming writer that never patched: 0xFFFFFFFF means "to the end".
191+ let mut stream = good.clone();
192+ let n = stream.len();
193+ stream[n - 40 - 4..n - 40].copy_from_slice(&u32::MAX.to_le_bytes());
194+ let mut r = WavReader::new(Cursor::new(&stream[..])).unwrap();
195+ assert_eq!(r.duration(), None);
196+ assert_eq!(r.read_all_i32().unwrap(), samples);
197+}
198+
199+#[test]
200+fn refusals_name_a_real_absence() {
201+ // Not RIFF at all.
202+ assert!(WavReader::new(Cursor::new(&b"OggS\0\0\0\0\0\0\0\0"[..])).is_err());
203+ // ADPCM: a tag we genuinely do not decode.
204+ let mut f: Vec<u8> = Vec::new();
205+ f.extend_from_slice(b"RIFF\0\0\0\0WAVEfmt ");
206+ f.extend_from_slice(&16u32.to_le_bytes());
207+ f.extend_from_slice(&2u16.to_le_bytes()); // WAVE_FORMAT_ADPCM
208+ f.extend_from_slice(&1u16.to_le_bytes());
209+ f.extend_from_slice(&8000u32.to_le_bytes());
210+ f.extend_from_slice(&8000u32.to_le_bytes());
211+ f.extend_from_slice(&1u16.to_le_bytes());
212+ f.extend_from_slice(&4u16.to_le_bytes());
213+ let e = WavReader::new(Cursor::new(&f[..]))
214+ .err()
215+ .expect("ADPCM was accepted")
216+ .to_string();
217+ assert!(e.contains("0x0002"), "{e}");
218+
219+ // Writing a sample too wide for the declared depth is caught, not clipped.
220+ let mut w =
221+ WavWriter::new(Cursor::new(Vec::new()), spec(1, 48000, 16, SampleType::Int)).unwrap();
222+ assert!(w.write_sample(32768i32).is_err());
223+ assert!(w.write_sample(1.0f32).is_err(), "float into an int file");
224+ // A half-written frame is a truncated file, and finalize says so.
225+ let mut w =
226+ WavWriter::new(Cursor::new(Vec::new()), spec(2, 48000, 16, SampleType::Int)).unwrap();
227+ w.write_sample(1i16).unwrap();
228+ assert!(w.finalize().is_err());
229+}
230+
231+#[test]
232+fn reads_every_wav_fixture() {
233+ let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/../../fixtures/audio");
234+ let Ok(entries) = std::fs::read_dir(dir) else {
235+ eprintln!("fixtures/audio absent (gitignored) — skipping");
236+ return;
237+ };
238+ let mut seen = 0;
239+ for e in entries.flatten() {
240+ let path = e.path();
241+ if path.extension().and_then(|s| s.to_str()) != Some("wav") {
242+ continue;
243+ }
244+ let name = path.file_name().unwrap().to_string_lossy().to_string();
245+ let mut r = WavReader::open(&path).unwrap_or_else(|e| panic!("{name}: {e}"));
246+ let spec = r.spec();
247+ // The generator names layout and rate in the file name; the header must agree.
248+ let channels = if name.contains("mono") {
249+ 1
250+ } else if name.contains("stereo") {
251+ 2
252+ } else {
253+ 6
254+ };
255+ assert_eq!(spec.channels, channels, "{name}");
256+ assert!(name.contains(&spec.sample_rate.to_string()), "{name}");
257+ assert_eq!(spec.sample_format, SampleType::Int, "{name}");
258+ let samples = r.read_all_i32().unwrap();
259+ assert!(!samples.is_empty(), "{name} decoded nothing");
260+ assert_eq!(samples.len() % usize::from(channels), 0, "{name}");
261+ assert!(
262+ samples.iter().any(|&v| v != 0),
263+ "{name} is silence — the fixture or the reader is wrong"
264+ );
265+ // What we read, as f32le, for `oracle audio-compare <name>.raw <fixture>`:
266+ // ffmpeg decodes the same file and the two must agree sample for sample.
267+ let mut r = WavReader::open(&path).unwrap();
268+ let raw: Vec<u8> = r
269+ .read_all_f32()
270+ .unwrap()
271+ .iter()
272+ .flat_map(|v| v.to_le_bytes())
273+ .collect();
274+ let dir = std::path::Path::new(env!("CARGO_TARGET_TMPDIR")).join("oracle");
275+ std::fs::create_dir_all(&dir).unwrap();
276+ std::fs::write(dir.join(format!("{name}.raw")), raw).unwrap();
277+ seen += 1;
278+ }
279+ assert!(seen >= 6, "expected the six wav16 fixtures, saw {seen}");
280+}
281+
282+/// Write the pairs the `oracle` binary compares: our WAV, and the samples that
283+/// went into it as f32le. Not an assertion — the assertion is the oracle run.
284+#[test]
285+fn emit_oracle_artifacts() {
286+ let dir = std::path::Path::new(env!("CARGO_TARGET_TMPDIR")).join("oracle");
287+ std::fs::create_dir_all(&dir).unwrap();
288+ for (name, channels, rate, bits, format) in [
289+ ("i16-stereo-48000", 2u16, 48000u32, 16u16, SampleType::Int),
290+ ("i24-5_1-44100", 6, 44100, 24, SampleType::Int),
291+ ("i32-mono-48000", 1, 48000, 32, SampleType::Int),
292+ ("i8-stereo-44100", 2, 44100, 8, SampleType::Int),
293+ ("f32-7_1-48000", 8, 48000, 32, SampleType::Float),
294+ ] {
295+ let s = spec(channels, rate, bits, format);
296+ let frames = 4096;
297+ let n = frames * usize::from(channels);
298+ let mut w = WavWriter::create(dir.join(format!("{name}.wav")), s).unwrap();
299+ let raw: Vec<f32> = if format == SampleType::Float {
300+ let samples = float_samples(n);
301+ w.write_samples(&samples).unwrap();
302+ samples
303+ } else {
304+ let samples = int_samples(n, bits);
305+ w.write_samples(&samples).unwrap();
306+ let scale = 1.0f32 / (1i64 << (bits - 1)) as f32;
307+ samples.iter().map(|&v| v as f32 * scale).collect()
308+ };
309+ w.finalize().unwrap();
310+ let bytes: Vec<u8> = raw.iter().flat_map(|v| v.to_le_bytes()).collect();
311+ std::fs::write(dir.join(format!("{name}.raw")), bytes).unwrap();
312+ }
313+ eprintln!("oracle artifacts in {}", dir.display());
314+}
shims/hound/Cargo.tomladded+10 -0
@@ -0,0 +1,10 @@
1+[package]
2+name = "hound"
3+description = "Compatibility shim: the hound 3.5.1 WAV-writing surface, implemented over ec-riff."
4+version = "3.5.1"
5+edition.workspace = true
6+license.workspace = true
7+authors.workspace = true
8+
9+[dependencies]
10+ec-riff.workspace = true
shims/hound/src/lib.rsadded+192 -0
@@ -0,0 +1,192 @@
1+//! `hound` 3.5.1's WAV-writing surface, over [`ec_riff`].
2+//!
3+//! This crate exists to be swapped in by `[patch.crates-io]`: it carries the
4+//! incumbent's name and version so a consumer's `use hound::…` compiles
5+//! 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.
10+//!
11+//! Behaviour differences from the incumbent, all in the strict direction:
12+//! files with more than two channels or more than 16 bits get a
13+//! `WAVE_FORMAT_EXTENSIBLE` header (hound writes one only above 16 bits), and
14+//! a `fact` chunk goes with it.
15+
16+#![forbid(unsafe_code)]
17+#![warn(missing_docs)]
18+
19+use std::fmt;
20+use std::fs::File;
21+use std::io::{self, BufWriter, Seek, Write};
22+use std::path::Path;
23+
24+pub use ec_riff::Sample;
25+
26+/// Whether samples are stored as floats or integers.
27+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
28+pub enum SampleFormat {
29+ /// `WAVE_FORMAT_IEEE_FLOAT`, nominal range -1.0..=1.0.
30+ Float,
31+ /// `WAVE_FORMAT_PCM`.
32+ Int,
33+}
34+
35+/// Properties of the audio data.
36+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
37+pub struct WavSpec {
38+ /// The number of channels.
39+ pub channels: u16,
40+ /// The number of samples per second.
41+ pub sample_rate: u32,
42+ /// The number of bits per sample.
43+ pub bits_per_sample: u16,
44+ /// Whether the samples are float or integer values.
45+ pub sample_format: SampleFormat,
46+}
47+
48+impl From<WavSpec> for ec_riff::WavSpec {
49+ fn from(s: WavSpec) -> ec_riff::WavSpec {
50+ ec_riff::WavSpec {
51+ channels: s.channels,
52+ sample_rate: s.sample_rate,
53+ bits_per_sample: s.bits_per_sample,
54+ sample_format: match s.sample_format {
55+ SampleFormat::Float => ec_riff::SampleType::Float,
56+ SampleFormat::Int => ec_riff::SampleType::Int,
57+ },
58+ }
59+ }
60+}
61+
62+/// The error type for operations on `WavWriter`.
63+#[derive(Debug)]
64+pub enum Error {
65+ /// An IO error occured in the underlying writer.
66+ IoError(io::Error),
67+ /// Ill-formed WAVE data was encountered.
68+ FormatError(&'static str),
69+ /// The sample has more bits than the destination format allows.
70+ TooWide,
71+ /// The number of samples written is not a multiple of the number of channels.
72+ UnfinishedSample,
73+ /// The format is not supported.
74+ Unsupported,
75+ /// The sample format is different than the destination format.
76+ InvalidSampleFormat,
77+}
78+
79+impl fmt::Display for Error {
80+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81+ match self {
82+ Error::IoError(e) => e.fmt(f),
83+ Error::FormatError(reason) => write!(f, "Ill-formed WAVE file: {reason}"),
84+ Error::TooWide => f.write_str("The sample has more bits than the destination type."),
85+ Error::UnfinishedSample => f.write_str(
86+ "The number of samples written is not a multiple of the number of channels.",
87+ ),
88+ Error::Unsupported => f.write_str("The wave format of the file is not supported."),
89+ Error::InvalidSampleFormat => {
90+ f.write_str("The sample format differs from the destination format.")
91+ }
92+ }
93+ }
94+}
95+
96+impl std::error::Error for Error {
97+ fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
98+ match self {
99+ Error::IoError(e) => Some(e),
100+ _ => None,
101+ }
102+ }
103+}
104+
105+impl From<io::Error> for Error {
106+ fn from(e: io::Error) -> Error {
107+ Error::IoError(e)
108+ }
109+}
110+
111+/// A type for results generated by this crate.
112+pub type Result<T> = std::result::Result<T, Error>;
113+
114+/// I/O failures keep their identity; everything else becomes `other`, which the
115+/// call site chooses, since the same `ec-riff` variant means different things
116+/// when writing a header, a sample, or the final sizes.
117+fn map(e: ec_riff::Error, corrupt_as: Error) -> Error {
118+ match e {
119+ ec_riff::Error::Io(e) => Error::IoError(e),
120+ ec_riff::Error::Unsupported { .. } => Error::Unsupported,
121+ _ => corrupt_as,
122+ }
123+}
124+
125+/// Writes a WAVE file sample by sample.
126+pub struct WavWriter<W: Write + Seek> {
127+ inner: ec_riff::WavWriter<W>,
128+}
129+
130+impl WavWriter<BufWriter<File>> {
131+ /// Create a new wav file at `path` with the given spec.
132+ pub fn create<P: AsRef<Path>>(path: P, spec: WavSpec) -> Result<Self> {
133+ let file = File::create(path)?;
134+ WavWriter::new(BufWriter::new(file), spec)
135+ }
136+}
137+
138+impl<W: Write + Seek> WavWriter<W> {
139+ /// Create a new writer over `writer`, writing the header immediately.
140+ pub fn new(writer: W, spec: WavSpec) -> Result<Self> {
141+ ec_riff::WavWriter::new(writer, spec.into())
142+ .map(|inner| WavWriter { inner })
143+ .map_err(|e| {
144+ map(
145+ e,
146+ Error::FormatError("unusable channel count or sample rate"),
147+ )
148+ })
149+ }
150+
151+ /// Write a single sample for one channel.
152+ pub fn write_sample<S: Sample>(&mut self, sample: S) -> Result<()> {
153+ self.inner.write_sample(sample).map_err(|e| match e {
154+ // A value the declared depth cannot hold, versus a sample type the
155+ // declared format cannot hold: hound's TooWide and
156+ // InvalidSampleFormat respectively.
157+ ec_riff::Error::Io(e) => Error::IoError(e),
158+ ec_riff::Error::Unsupported { .. } => Error::InvalidSampleFormat,
159+ _ => Error::TooWide,
160+ })
161+ }
162+
163+ /// Number of samples (per channel) written so far.
164+ pub fn duration(&self) -> u32 {
165+ self.inner.duration() as u32
166+ }
167+
168+ /// The spec the file was created with.
169+ pub fn spec(&self) -> WavSpec {
170+ let s = self.inner.spec();
171+ WavSpec {
172+ channels: s.channels,
173+ sample_rate: s.sample_rate,
174+ bits_per_sample: s.bits_per_sample,
175+ sample_format: match s.sample_format {
176+ ec_riff::SampleType::Float => SampleFormat::Float,
177+ ec_riff::SampleType::Int => SampleFormat::Int,
178+ },
179+ }
180+ }
181+
182+ /// Update the header with the written length and flush.
183+ ///
184+ /// Failing here is the difference between a finished file and a truncated
185+ /// one, which is why it is called instead of dropping the writer.
186+ pub fn finalize(self) -> Result<()> {
187+ self.inner
188+ .finalize()
189+ .map(|_| ())
190+ .map_err(|e| map(e, Error::UnfinishedSample))
191+ }
192+}
shims/hound/tests/edith_surface.rsadded+78 -0
@@ -0,0 +1,78 @@
1+//! The call edith makes, verbatim in shape (engine/src/export.rs `write_wav`):
2+//! `WavWriter::create(path, WavSpec { .. sample_format: Int })`, a run of
3+//! `write_sample(x as i16)`, then `finalize()` — with the `?` conversion into
4+//! edith's `Box<dyn Error + Send + Sync>` exercised too.
5+
6+type EdithError = Box<dyn std::error::Error + Send + Sync>;
7+
8+fn write_wav(
9+ out: &std::path::Path,
10+ samples: &[i32],
11+ channels: u16,
12+ rate: u32,
13+) -> Result<(), EdithError> {
14+ let mut writer = hound::WavWriter::create(
15+ out,
16+ hound::WavSpec {
17+ channels,
18+ sample_rate: rate,
19+ bits_per_sample: 16,
20+ sample_format: hound::SampleFormat::Int,
21+ },
22+ )?;
23+ for &sample in samples {
24+ writer.write_sample(sample as i16)?;
25+ }
26+ writer.finalize()?;
27+ Ok(())
28+}
29+
30+#[test]
31+fn edith_write_wav_round_trips() {
32+ let dir = std::path::Path::new(env!("CARGO_TARGET_TMPDIR"));
33+ std::fs::create_dir_all(dir).unwrap();
34+ for (channels, rate) in [(1u16, 44100u32), (2, 48000), (6, 48000)] {
35+ let path = dir.join(format!("edith-{channels}ch-{rate}.wav"));
36+ let samples: Vec<i32> = (0..usize::from(channels) * 512)
37+ .map(|i| ((i as i32 * 733) % 65536) - 32768)
38+ .collect();
39+ write_wav(&path, &samples, channels, rate).unwrap();
40+
41+ let mut r = ec_riff::WavReader::open(&path).unwrap();
42+ let spec = r.spec();
43+ assert_eq!(spec.channels, channels);
44+ assert_eq!(spec.sample_rate, rate);
45+ assert_eq!(spec.bits_per_sample, 16);
46+ assert_eq!(spec.sample_format, ec_riff::SampleType::Int);
47+ assert_eq!(r.read_all_i32().unwrap(), samples);
48+ }
49+}
50+
51+#[test]
52+fn errors_carry_the_incumbent_variants() {
53+ let dir = std::path::Path::new(env!("CARGO_TARGET_TMPDIR"));
54+ let spec = hound::WavSpec {
55+ channels: 2,
56+ sample_rate: 48000,
57+ bits_per_sample: 16,
58+ sample_format: hound::SampleFormat::Int,
59+ };
60+ let mut w = hound::WavWriter::create(dir.join("errors.wav"), spec).unwrap();
61+ // Wider than the declared depth, and the wrong sample family: the two
62+ // failures callers of hound match on.
63+ assert!(matches!(
64+ w.write_sample(40_000i32),
65+ Err(hound::Error::TooWide)
66+ ));
67+ assert!(matches!(
68+ w.write_sample(0.5f32),
69+ Err(hound::Error::InvalidSampleFormat)
70+ ));
71+ w.write_sample(1i16).unwrap();
72+ assert!(matches!(w.finalize(), Err(hound::Error::UnfinishedSample)));
73+ // A directory is not a file: I/O keeps its identity through the shim.
74+ assert!(matches!(
75+ hound::WavWriter::create(dir, spec),
76+ Err(hound::Error::IoError(_))
77+ ));
78+}