forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB7cdaf34Tahinli3 months ago29 commits

lib.rs310 lines, 10.6 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, 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
19use std::fmt;
20use std::fs::File;
21use std::io::{self, BufReader, BufWriter, Read, Seek, Write};
22use std::path::Path;
23
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.
29pub 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
38macro_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}
51int_sample!(i8 => 8, i16 => 16, i32 => 32);
52
53impl 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}
62
63/// Whether samples are stored as floats or integers.
64#[derive(Clone, Copy, Debug, PartialEq, Eq)]
65pub enum SampleFormat {
66 /// `WAVE_FORMAT_IEEE_FLOAT`, nominal range -1.0..=1.0.
67 Float,
68 /// `WAVE_FORMAT_PCM`.
69 Int,
70}
71
72/// Properties of the audio data.
73#[derive(Clone, Copy, Debug, PartialEq, Eq)]
74pub struct WavSpec {
75 /// The number of channels.
76 pub channels: u16,
77 /// The number of samples per second.
78 pub sample_rate: u32,
79 /// The number of bits per sample.
80 pub bits_per_sample: u16,
81 /// Whether the samples are float or integer values.
82 pub sample_format: SampleFormat,
83}
84
85impl From<WavSpec> for ec_riff::WavSpec {
86 fn from(s: WavSpec) -> ec_riff::WavSpec {
87 ec_riff::WavSpec {
88 channels: s.channels,
89 sample_rate: s.sample_rate,
90 bits_per_sample: s.bits_per_sample,
91 sample_format: match s.sample_format {
92 SampleFormat::Float => ec_riff::SampleType::Float,
93 SampleFormat::Int => ec_riff::SampleType::Int,
94 },
95 }
96 }
97}
98
99/// The error type for operations on `WavWriter`.
100#[derive(Debug)]
101pub enum Error {
102 /// An IO error occured in the underlying writer.
103 IoError(io::Error),
104 /// Ill-formed WAVE data was encountered.
105 FormatError(&'static str),
106 /// The sample has more bits than the destination format allows.
107 TooWide,
108 /// The number of samples written is not a multiple of the number of channels.
109 UnfinishedSample,
110 /// The format is not supported.
111 Unsupported,
112 /// The sample format is different than the destination format.
113 InvalidSampleFormat,
114}
115
116impl fmt::Display for Error {
117 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118 match self {
119 Error::IoError(e) => e.fmt(f),
120 Error::FormatError(reason) => write!(f, "Ill-formed WAVE file: {reason}"),
121 Error::TooWide => f.write_str("The sample has more bits than the destination type."),
122 Error::UnfinishedSample => f.write_str(
123 "The number of samples written is not a multiple of the number of channels.",
124 ),
125 Error::Unsupported => f.write_str("The wave format of the file is not supported."),
126 Error::InvalidSampleFormat => {
127 f.write_str("The sample format differs from the destination format.")
128 }
129 }
130 }
131}
132
133impl std::error::Error for Error {
134 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
135 match self {
136 Error::IoError(e) => Some(e),
137 _ => None,
138 }
139 }
140}
141
142impl From<io::Error> for Error {
143 fn from(e: io::Error) -> Error {
144 Error::IoError(e)
145 }
146}
147
148/// A type for results generated by this crate.
149pub type Result<T> = std::result::Result<T, Error>;
150
151/// I/O failures keep their identity; everything else becomes `other`, which the
152/// call site chooses, since the same `ec-riff` variant means different things
153/// when writing a header, a sample, or the final sizes.
154fn map(e: ec_riff::Error, corrupt_as: Error) -> Error {
155 match e {
156 ec_riff::Error::Io(e) => Error::IoError(e),
157 ec_riff::Error::Unsupported { .. } => Error::Unsupported,
158 _ => corrupt_as,
159 }
160}
161
162/// Writes a WAVE file sample by sample.
163pub struct WavWriter<W: Write + Seek> {
164 inner: ec_riff::WavWriter<W>,
165}
166
167impl WavWriter<BufWriter<File>> {
168 /// Create a new wav file at `path` with the given spec.
169 pub fn create<P: AsRef<Path>>(path: P, spec: WavSpec) -> Result<Self> {
170 let file = File::create(path)?;
171 WavWriter::new(BufWriter::new(file), spec)
172 }
173}
174
175impl<W: Write + Seek> WavWriter<W> {
176 /// Create a new writer over `writer`, writing the header immediately.
177 pub fn new(writer: W, spec: WavSpec) -> Result<Self> {
178 ec_riff::WavWriter::new(writer, spec.into())
179 .map(|inner| WavWriter { inner })
180 .map_err(|e| {
181 map(
182 e,
183 Error::FormatError("unusable channel count or sample rate"),
184 )
185 })
186 }
187
188 /// Write a single sample for one channel.
189 pub fn write_sample<S: Sample>(&mut self, sample: S) -> Result<()> {
190 self.inner.write_sample(sample).map_err(|e| match e {
191 // A value the declared depth cannot hold, versus a sample type the
192 // declared format cannot hold: hound's TooWide and
193 // InvalidSampleFormat respectively.
194 ec_riff::Error::Io(e) => Error::IoError(e),
195 ec_riff::Error::Unsupported { .. } => Error::InvalidSampleFormat,
196 _ => Error::TooWide,
197 })
198 }
199
200 /// Number of samples (per channel) written so far.
201 pub fn duration(&self) -> u32 {
202 self.inner.duration() as u32
203 }
204
205 /// The spec the file was created with.
206 pub fn spec(&self) -> WavSpec {
207 let s = self.inner.spec();
208 WavSpec {
209 channels: s.channels,
210 sample_rate: s.sample_rate,
211 bits_per_sample: s.bits_per_sample,
212 sample_format: match s.sample_format {
213 ec_riff::SampleType::Float => SampleFormat::Float,
214 ec_riff::SampleType::Int => SampleFormat::Int,
215 },
216 }
217 }
218
219 /// Update the header with the written length and flush.
220 ///
221 /// Failing here is the difference between a finished file and a truncated
222 /// one, which is why it is called instead of dropping the writer.
223 pub fn finalize(self) -> Result<()> {
224 self.inner
225 .finalize()
226 .map(|_| ())
227 .map_err(|e| map(e, Error::UnfinishedSample))
228 }
229}
230
231/// Reads a WAVE file's header, then its samples.
232pub struct WavReader<R: Read> {
233 inner: ec_riff::WavReader<R>,
234}
235
236impl 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
243impl<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.
298pub struct WavSamples<S>(std::vec::IntoIter<Result<S>>);
299
300impl<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}