forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBcd61dc0Tahinli3 months ago728 commits

lib.rs344 lines, 12.3 KiBHistoryRawDownload
1//! `hound` 3.5.1's WAV 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`, `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.
10//!
11//! Behaviour differences from the incumbent. Writing is stricter only: files
12//! 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. Reading diverges in shape, not in verdict —
15//! the refusals are hound's, the reporting is not:
16//!
17//! * [`WavReader::samples`] reads the `data` chunk whole before yielding, so a
18//! file that ends early yields one [`Error::IoError`] and nothing else,
19//! where hound yields the samples it did read and then the `UnexpectedEof`.
20//! [`Error::TooWide`] and [`Error::InvalidSampleFormat`] are single-item for
21//! the same reason; hound repeats them per sample.
22//! * `bits_per_sample` outside 8/16/24/32 is [`Error::FormatError`] when it is
23//! not a whole number of bytes and [`Error::Unsupported`] otherwise, which
24//! splits hound's refusals along the same line but not with its wording.
25
26#![forbid(unsafe_code)]
27#![warn(missing_docs)]
28
29use std::fmt;
30use std::fs::File;
31use std::io::{self, BufReader, BufWriter, Read, Seek, Write};
32use std::path::Path;
33
34/// A sample type a [`WavWriter`] accepts and a [`WavReader`] yields.
35///
36/// The write half is [`ec_riff::Sample`]; the two constructors and the width
37/// are what reading adds, and they are what makes hound's `TooWide` and
38/// `InvalidSampleFormat` decidable before a single sample is converted.
39pub trait Sample: ec_riff::Sample {
40 /// Bits this type carries. A file deeper than this is [`Error::TooWide`].
41 const BITS: u16;
42 /// Narrow the reader's integer carrier. Called for integer files only.
43 fn from_i32(v: i32) -> Self;
44 /// Take the reader's float carrier. Called for float files only.
45 fn from_f32(v: f32) -> Self;
46}
47
48macro_rules! int_sample {
49 ($($t:ty => $bits:expr),*) => {$(
50 impl Sample for $t {
51 const BITS: u16 = $bits;
52 fn from_i32(v: i32) -> Self {
53 v as $t
54 }
55 fn from_f32(v: f32) -> Self {
56 v as $t
57 }
58 }
59 )*};
60}
61int_sample!(i8 => 8, i16 => 16, i32 => 32);
62
63impl Sample for f32 {
64 const BITS: u16 = 32;
65 fn from_i32(v: i32) -> Self {
66 v as f32
67 }
68 fn from_f32(v: f32) -> Self {
69 v
70 }
71}
72
73/// Whether samples are stored as floats or integers.
74#[derive(Clone, Copy, Debug, PartialEq, Eq)]
75pub enum SampleFormat {
76 /// `WAVE_FORMAT_IEEE_FLOAT`, nominal range -1.0..=1.0.
77 Float,
78 /// `WAVE_FORMAT_PCM`.
79 Int,
80}
81
82/// Properties of the audio data.
83#[derive(Clone, Copy, Debug, PartialEq, Eq)]
84pub struct WavSpec {
85 /// The number of channels.
86 pub channels: u16,
87 /// The number of samples per second.
88 pub sample_rate: u32,
89 /// The number of bits per sample.
90 pub bits_per_sample: u16,
91 /// Whether the samples are float or integer values.
92 pub sample_format: SampleFormat,
93}
94
95impl From<WavSpec> for ec_riff::WavSpec {
96 fn from(s: WavSpec) -> ec_riff::WavSpec {
97 ec_riff::WavSpec {
98 channels: s.channels,
99 sample_rate: s.sample_rate,
100 bits_per_sample: s.bits_per_sample,
101 sample_format: match s.sample_format {
102 SampleFormat::Float => ec_riff::SampleType::Float,
103 SampleFormat::Int => ec_riff::SampleType::Int,
104 },
105 }
106 }
107}
108
109/// The error type for operations on `WavWriter`.
110#[derive(Debug)]
111pub enum Error {
112 /// An IO error occured in the underlying writer.
113 IoError(io::Error),
114 /// Ill-formed WAVE data was encountered.
115 FormatError(&'static str),
116 /// The sample has more bits than the destination format allows.
117 TooWide,
118 /// The number of samples written is not a multiple of the number of channels.
119 UnfinishedSample,
120 /// The format is not supported.
121 Unsupported,
122 /// The sample format is different than the destination format.
123 InvalidSampleFormat,
124}
125
126impl fmt::Display for Error {
127 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
128 match self {
129 Error::IoError(e) => e.fmt(f),
130 Error::FormatError(reason) => write!(f, "Ill-formed WAVE file: {reason}"),
131 Error::TooWide => f.write_str("The sample has more bits than the destination type."),
132 Error::UnfinishedSample => f.write_str(
133 "The number of samples written is not a multiple of the number of channels.",
134 ),
135 Error::Unsupported => f.write_str("The wave format of the file is not supported."),
136 Error::InvalidSampleFormat => {
137 f.write_str("The sample format differs from the destination format.")
138 }
139 }
140 }
141}
142
143impl std::error::Error for Error {
144 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
145 match self {
146 Error::IoError(e) => Some(e),
147 _ => None,
148 }
149 }
150}
151
152impl From<io::Error> for Error {
153 fn from(e: io::Error) -> Error {
154 Error::IoError(e)
155 }
156}
157
158/// A type for results generated by this crate.
159pub type Result<T> = std::result::Result<T, Error>;
160
161/// I/O failures keep their identity; everything else becomes `other`, which the
162/// call site chooses, since the same `ec-riff` variant means different things
163/// when writing a header, a sample, or the final sizes.
164fn map(e: ec_riff::Error, corrupt_as: Error) -> Error {
165 match e {
166 ec_riff::Error::Io(e) => Error::IoError(e),
167 ec_riff::Error::Unsupported { .. } => Error::Unsupported,
168 _ => corrupt_as,
169 }
170}
171
172/// Writes a WAVE file sample by sample.
173pub struct WavWriter<W: Write + Seek> {
174 inner: ec_riff::WavWriter<W>,
175}
176
177impl WavWriter<BufWriter<File>> {
178 /// Create a new wav file at `path` with the given spec.
179 pub fn create<P: AsRef<Path>>(path: P, spec: WavSpec) -> Result<Self> {
180 let file = File::create(path)?;
181 WavWriter::new(BufWriter::new(file), spec)
182 }
183}
184
185impl<W: Write + Seek> WavWriter<W> {
186 /// Create a new writer over `writer`, writing the header immediately.
187 pub fn new(writer: W, spec: WavSpec) -> Result<Self> {
188 ec_riff::WavWriter::new(writer, spec.into())
189 .map(|inner| WavWriter { inner })
190 .map_err(|e| {
191 map(
192 e,
193 Error::FormatError("unusable channel count or sample rate"),
194 )
195 })
196 }
197
198 /// Write a single sample for one channel.
199 pub fn write_sample<S: Sample>(&mut self, sample: S) -> Result<()> {
200 self.inner.write_sample(sample).map_err(|e| match e {
201 // A value the declared depth cannot hold, versus a sample type the
202 // declared format cannot hold: hound's TooWide and
203 // InvalidSampleFormat respectively.
204 ec_riff::Error::Io(e) => Error::IoError(e),
205 ec_riff::Error::Unsupported { .. } => Error::InvalidSampleFormat,
206 _ => Error::TooWide,
207 })
208 }
209
210 /// Number of samples (per channel) written so far.
211 pub fn duration(&self) -> u32 {
212 self.inner.duration() as u32
213 }
214
215 /// The spec the file was created with.
216 pub fn spec(&self) -> WavSpec {
217 let s = self.inner.spec();
218 WavSpec {
219 channels: s.channels,
220 sample_rate: s.sample_rate,
221 bits_per_sample: s.bits_per_sample,
222 sample_format: match s.sample_format {
223 ec_riff::SampleType::Float => SampleFormat::Float,
224 ec_riff::SampleType::Int => SampleFormat::Int,
225 },
226 }
227 }
228
229 /// Update the header with the written length and flush.
230 ///
231 /// Failing here is the difference between a finished file and a truncated
232 /// one, which is why it is called instead of dropping the writer.
233 pub fn finalize(self) -> Result<()> {
234 self.inner
235 .finalize()
236 .map(|_| ())
237 .map_err(|e| map(e, Error::UnfinishedSample))
238 }
239}
240
241/// Reads a WAVE file's header, then its samples.
242pub struct WavReader<R: Read> {
243 inner: ec_riff::WavReader<R>,
244}
245
246impl WavReader<BufReader<File>> {
247 /// Open `path` and parse its header.
248 pub fn open<P: AsRef<Path>>(path: P) -> Result<Self> {
249 WavReader::new(BufReader::new(File::open(path)?))
250 }
251}
252
253impl<R: Read> WavReader<R> {
254 /// Parse the header of an already-open stream.
255 pub fn new(reader: R) -> Result<Self> {
256 ec_riff::WavReader::new(reader)
257 .map(|inner| WavReader { inner })
258 .map_err(|e| map(e, Error::FormatError("not a WAVE file this reader accepts")))
259 }
260
261 /// The `fmt ` chunk as parsed.
262 pub fn spec(&self) -> WavSpec {
263 let s = self.inner.spec();
264 WavSpec {
265 channels: s.channels,
266 sample_rate: s.sample_rate,
267 bits_per_sample: s.bits_per_sample,
268 sample_format: match s.sample_format {
269 ec_riff::SampleType::Float => SampleFormat::Float,
270 ec_riff::SampleType::Int => SampleFormat::Int,
271 },
272 }
273 }
274
275 /// Every sample, interleaved in channel order, as the incumbent's fallible
276 /// iterator: a file whose format or depth `S` cannot carry yields one
277 /// [`Error::InvalidSampleFormat`] or [`Error::TooWide`] rather than a
278 /// converted value, which is where hound puts the same refusals.
279 ///
280 /// corner-cut: `ec-riff` reads the `data` chunk whole, so this buffers the
281 /// file where hound streams it — ~10 MB per minute of 48 kHz stereo, fine
282 /// for the export round-trips edith checks and wrong for an hour of audio.
283 /// Upgrade path is a streaming `read_samples` on `ec_riff::WavReader`,
284 /// which this then forwards to unchanged.
285 pub fn samples<S: Sample>(&mut self) -> WavSamples<S> {
286 let spec = self.inner.spec();
287 let float_file = spec.sample_format == ec_riff::SampleType::Float;
288 // What the `data` header promised. `ec-riff` stops at the end of the
289 // file without complaint; hound hands the caller the `UnexpectedEof`,
290 // so the promise is compared against what arrived.
291 let promised = self
292 .inner
293 .duration()
294 .map(|frames| frames as usize * usize::from(spec.channels));
295 let items = if float_file != S::FLOAT {
296 vec![Err(Error::InvalidSampleFormat)]
297 } else if spec.bits_per_sample > S::BITS {
298 vec![Err(Error::TooWide)]
299 } else if float_file {
300 match self.inner.read_all_f32() {
301 Ok(v) => match short_read(v.len(), promised) {
302 Some(e) => vec![Err(e)],
303 None => v.into_iter().map(|s| Ok(S::from_f32(s))).collect(),
304 },
305 Err(e) => vec![Err(map(e, Error::FormatError("truncated WAVE data")))],
306 }
307 } else {
308 match self.inner.read_all_i32() {
309 Ok(v) => match short_read(v.len(), promised) {
310 Some(e) => vec![Err(e)],
311 None => v.into_iter().map(|s| Ok(S::from_i32(s))).collect(),
312 },
313 Err(e) => vec![Err(map(e, Error::FormatError("truncated WAVE data")))],
314 }
315 };
316 WavSamples(items.into_iter())
317 }
318}
319
320/// The `UnexpectedEof` hound reports when the `data` chunk ends before the
321/// length its header declares, or `None` when the file kept its promise (or
322/// made none: a streamed placeholder size leaves the file itself the bound).
323fn short_read(got: usize, promised: Option<usize>) -> Option<Error> {
324 let want = promised.filter(|&n| got < n)?;
325 Some(Error::IoError(io::Error::new(
326 io::ErrorKind::UnexpectedEof,
327 format!("WAVE data chunk ends after {got} of {want} samples"),
328 )))
329}
330
331/// The iterator [`WavReader::samples`] returns.
332pub struct WavSamples<S>(std::vec::IntoIter<Result<S>>);
333
334impl<S> Iterator for WavSamples<S> {
335 type Item = Result<S>;
336
337 fn next(&mut self) -> Option<Self::Item> {
338 self.0.next()
339 }
340
341 fn size_hint(&self) -> (usize, Option<usize>) {
342 self.0.size_hint()
343 }
344}