//! `hound` 3.5.1's WAV surface, over [`ec_riff`]. //! //! This crate exists to be swapped in by `[patch.crates-io]`: it carries the //! incumbent's name and version so a consumer's `use hound::…` compiles //! unchanged. Only what edith consumes is here — `WavWriter::create`, //! `write_sample`, `finalize`, `WavReader::open`, `spec`, `samples`, //! [`WavSpec`], [`SampleFormat`] and an [`Error`] with the incumbent's variants //! — because a shim that grows a surface nobody calls is a second //! implementation to keep honest. //! //! Behaviour differences from the incumbent, all in the strict direction: //! files with more than two channels or more than 16 bits get a //! `WAVE_FORMAT_EXTENSIBLE` header (hound writes one only above 16 bits), and //! a `fact` chunk goes with it. #![forbid(unsafe_code)] #![warn(missing_docs)] use std::fmt; use std::fs::File; use std::io::{self, BufReader, BufWriter, Read, Seek, Write}; use std::path::Path; /// A sample type a [`WavWriter`] accepts and a [`WavReader`] yields. /// /// The write half is [`ec_riff::Sample`]; the two constructors and the width /// are what reading adds, and they are what makes hound's `TooWide` and /// `InvalidSampleFormat` decidable before a single sample is converted. pub trait Sample: ec_riff::Sample { /// Bits this type carries. A file deeper than this is [`Error::TooWide`]. const BITS: u16; /// Narrow the reader's integer carrier. Called for integer files only. fn from_i32(v: i32) -> Self; /// Take the reader's float carrier. Called for float files only. fn from_f32(v: f32) -> Self; } macro_rules! int_sample { ($($t:ty => $bits:expr),*) => {$( impl Sample for $t { const BITS: u16 = $bits; fn from_i32(v: i32) -> Self { v as $t } fn from_f32(v: f32) -> Self { v as $t } } )*}; } int_sample!(i8 => 8, i16 => 16, i32 => 32); impl Sample for f32 { const BITS: u16 = 32; fn from_i32(v: i32) -> Self { v as f32 } fn from_f32(v: f32) -> Self { v } } /// Whether samples are stored as floats or integers. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum SampleFormat { /// `WAVE_FORMAT_IEEE_FLOAT`, nominal range -1.0..=1.0. Float, /// `WAVE_FORMAT_PCM`. Int, } /// Properties of the audio data. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct WavSpec { /// The number of channels. pub channels: u16, /// The number of samples per second. pub sample_rate: u32, /// The number of bits per sample. pub bits_per_sample: u16, /// Whether the samples are float or integer values. pub sample_format: SampleFormat, } impl From for ec_riff::WavSpec { fn from(s: WavSpec) -> ec_riff::WavSpec { ec_riff::WavSpec { channels: s.channels, sample_rate: s.sample_rate, bits_per_sample: s.bits_per_sample, sample_format: match s.sample_format { SampleFormat::Float => ec_riff::SampleType::Float, SampleFormat::Int => ec_riff::SampleType::Int, }, } } } /// The error type for operations on `WavWriter`. #[derive(Debug)] pub enum Error { /// An IO error occured in the underlying writer. IoError(io::Error), /// Ill-formed WAVE data was encountered. FormatError(&'static str), /// The sample has more bits than the destination format allows. TooWide, /// The number of samples written is not a multiple of the number of channels. UnfinishedSample, /// The format is not supported. Unsupported, /// The sample format is different than the destination format. InvalidSampleFormat, } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Error::IoError(e) => e.fmt(f), Error::FormatError(reason) => write!(f, "Ill-formed WAVE file: {reason}"), Error::TooWide => f.write_str("The sample has more bits than the destination type."), Error::UnfinishedSample => f.write_str( "The number of samples written is not a multiple of the number of channels.", ), Error::Unsupported => f.write_str("The wave format of the file is not supported."), Error::InvalidSampleFormat => { f.write_str("The sample format differs from the destination format.") } } } } impl std::error::Error for Error { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match self { Error::IoError(e) => Some(e), _ => None, } } } impl From for Error { fn from(e: io::Error) -> Error { Error::IoError(e) } } /// A type for results generated by this crate. pub type Result = std::result::Result; /// I/O failures keep their identity; everything else becomes `other`, which the /// call site chooses, since the same `ec-riff` variant means different things /// when writing a header, a sample, or the final sizes. fn map(e: ec_riff::Error, corrupt_as: Error) -> Error { match e { ec_riff::Error::Io(e) => Error::IoError(e), ec_riff::Error::Unsupported { .. } => Error::Unsupported, _ => corrupt_as, } } /// Writes a WAVE file sample by sample. pub struct WavWriter { inner: ec_riff::WavWriter, } impl WavWriter> { /// Create a new wav file at `path` with the given spec. pub fn create>(path: P, spec: WavSpec) -> Result { let file = File::create(path)?; WavWriter::new(BufWriter::new(file), spec) } } impl WavWriter { /// Create a new writer over `writer`, writing the header immediately. pub fn new(writer: W, spec: WavSpec) -> Result { ec_riff::WavWriter::new(writer, spec.into()) .map(|inner| WavWriter { inner }) .map_err(|e| { map( e, Error::FormatError("unusable channel count or sample rate"), ) }) } /// Write a single sample for one channel. pub fn write_sample(&mut self, sample: S) -> Result<()> { self.inner.write_sample(sample).map_err(|e| match e { // A value the declared depth cannot hold, versus a sample type the // declared format cannot hold: hound's TooWide and // InvalidSampleFormat respectively. ec_riff::Error::Io(e) => Error::IoError(e), ec_riff::Error::Unsupported { .. } => Error::InvalidSampleFormat, _ => Error::TooWide, }) } /// Number of samples (per channel) written so far. pub fn duration(&self) -> u32 { self.inner.duration() as u32 } /// The spec the file was created with. pub fn spec(&self) -> WavSpec { let s = self.inner.spec(); WavSpec { channels: s.channels, sample_rate: s.sample_rate, bits_per_sample: s.bits_per_sample, sample_format: match s.sample_format { ec_riff::SampleType::Float => SampleFormat::Float, ec_riff::SampleType::Int => SampleFormat::Int, }, } } /// Update the header with the written length and flush. /// /// Failing here is the difference between a finished file and a truncated /// one, which is why it is called instead of dropping the writer. pub fn finalize(self) -> Result<()> { self.inner .finalize() .map(|_| ()) .map_err(|e| map(e, Error::UnfinishedSample)) } } /// Reads a WAVE file's header, then its samples. pub struct WavReader { inner: ec_riff::WavReader, } impl WavReader> { /// Open `path` and parse its header. pub fn open>(path: P) -> Result { WavReader::new(BufReader::new(File::open(path)?)) } } impl WavReader { /// Parse the header of an already-open stream. pub fn new(reader: R) -> Result { ec_riff::WavReader::new(reader) .map(|inner| WavReader { inner }) .map_err(|e| map(e, Error::FormatError("not a WAVE file this reader accepts"))) } /// The `fmt ` chunk as parsed. pub fn spec(&self) -> WavSpec { let s = self.inner.spec(); WavSpec { channels: s.channels, sample_rate: s.sample_rate, bits_per_sample: s.bits_per_sample, sample_format: match s.sample_format { ec_riff::SampleType::Float => SampleFormat::Float, ec_riff::SampleType::Int => SampleFormat::Int, }, } } /// Every sample, interleaved in channel order, as the incumbent's fallible /// iterator: a file whose format or depth `S` cannot carry yields one /// [`Error::InvalidSampleFormat`] or [`Error::TooWide`] rather than a /// converted value, which is where hound puts the same refusals. /// /// corner-cut: `ec-riff` reads the `data` chunk whole, so this buffers the /// file where hound streams it — ~10 MB per minute of 48 kHz stereo, fine /// for the export round-trips edith checks and wrong for an hour of audio. /// Upgrade path is a streaming `read_samples` on `ec_riff::WavReader`, /// which this then forwards to unchanged. pub fn samples(&mut self) -> WavSamples { let spec = self.inner.spec(); let float_file = spec.sample_format == ec_riff::SampleType::Float; let items = if float_file != S::FLOAT { vec![Err(Error::InvalidSampleFormat)] } else if spec.bits_per_sample > S::BITS { vec![Err(Error::TooWide)] } else if float_file { match self.inner.read_all_f32() { Ok(v) => v.into_iter().map(|s| Ok(S::from_f32(s))).collect(), Err(e) => vec![Err(map(e, Error::FormatError("truncated WAVE data")))], } } else { match self.inner.read_all_i32() { Ok(v) => v.into_iter().map(|s| Ok(S::from_i32(s))).collect(), Err(e) => vec![Err(map(e, Error::FormatError("truncated WAVE data")))], } }; WavSamples(items.into_iter()) } } /// The iterator [`WavReader::samples`] returns. pub struct WavSamples(std::vec::IntoIter>); impl Iterator for WavSamples { type Item = Result; fn next(&mut self) -> Option { self.0.next() } fn size_hint(&self) -> (usize, Option) { self.0.size_hint() } }