diff --git a/Cargo.lock b/Cargo.lock index 61347d99..25c71d54 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -19,6 +19,20 @@ dependencies = [ "wide", ] +[[package]] +name = "ec-riff" +version = "0.1.0" +dependencies = [ + "ec-core", +] + +[[package]] +name = "hound" +version = "3.5.1" +dependencies = [ + "ec-riff", +] + [[package]] name = "oracle" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 951aa589..2a43a31f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,6 +10,7 @@ authors = ["Ahmet Kaan Gümüş"] [workspace.dependencies] ec-core = { path = "crates/ec-core", version = "0.1.0" } +ec-riff = { path = "crates/ec-riff", version = "0.1.0" } ec-dsp = { path = "crates/ec-dsp", version = "0.1.0" } # Portable SIMD without asm or build-time tooling (family rule: pure Rust only). wide = "1.5" diff --git a/crates/ec-riff/Cargo.toml b/crates/ec-riff/Cargo.toml new file mode 100644 index 00000000..697b3fc8 --- /dev/null +++ b/crates/ec-riff/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "ec-riff" +description = "RIFF/WAVE reader and writer: integer and float PCM, mono through 7.1, WAVE_FORMAT_EXTENSIBLE." +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true + +[dependencies] +ec-core.workspace = true diff --git a/crates/ec-riff/src/lib.rs b/crates/ec-riff/src/lib.rs new file mode 100644 index 00000000..3f6f6cb7 --- /dev/null +++ b/crates/ec-riff/src/lib.rs @@ -0,0 +1,152 @@ +//! RIFF/WAVE: the container edith writes PCM into and reads PCM back from. +//! +//! [`WavWriter`] streams samples as they arrive and patches the RIFF, `data` +//! and `fact` sizes in [`WavWriter::finalize`] — a dropped writer therefore +//! leaves a file whose header lies, which is why finalizing is fallible and +//! explicit. [`WavReader`] walks the chunk list rather than assuming +//! `fmt `-then-`data`, so `LIST`/`INFO`, `fact`, `bext` and any other chunk a +//! recorder inserted are skipped, odd-sized chunks included (RIFF pads them to +//! an even boundary and the padding byte is not part of the chunk). +//! +//! Covered: 8/16/24/32-bit integer PCM and 32-bit float, 1 to 8 channels +//! (mono through 7.1), any sample rate. `WAVE_FORMAT_EXTENSIBLE` is written +//! whenever the file has more than two channels or more than 16 bits per +//! sample — the depth/layout combinations where players are entitled to +//! distrust a plain `WAVE_FORMAT_PCM` header — and is read whatever the file +//! declares. +//! +//! Not covered: RF64/BW64 (>4 GiB), ADPCM and other compressed WAVE tags, +//! 64-bit float. Each is [`Error::Unsupported`] naming itself, never a silent +//! misread. +//! +//! The crate stands alone — [`WavSpec`] is its own type — but converts into the +//! family IR on request: [`WavSpec::sample_format`] and [`WavSpec::layout`]. + +#![forbid(unsafe_code)] +#![warn(missing_docs)] + +mod read; +mod write; + +pub use ec_core::{Error, Result}; +pub use read::WavReader; +pub use write::{Sample, WavWriter}; + +/// Whether samples are stored as integers (`WAVE_FORMAT_PCM`) or as floats +/// (`WAVE_FORMAT_IEEE_FLOAT`). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum SampleType { + /// Signed integers, except 8-bit which RIFF stores unsigned and biased. + Int, + /// IEEE floats, nominal range -1.0..=1.0. + Float, +} + +/// What the `fmt ` chunk says about the audio. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct WavSpec { + /// Channel count, 1..=8 for the layouts this crate names. + pub channels: u16, + /// Sample rate in Hz; any rate the source states. + pub sample_rate: u32, + /// Bits per sample: 8, 16, 24 or 32 for [`SampleType::Int`], 32 for float. + pub bits_per_sample: u16, + /// Integer or float storage. + pub sample_format: SampleType, +} + +/// `WAVE_FORMAT_PCM`. +const FORMAT_PCM: u16 = 1; +/// `WAVE_FORMAT_IEEE_FLOAT`. +const FORMAT_FLOAT: u16 = 3; +/// `WAVE_FORMAT_EXTENSIBLE`. +const FORMAT_EXTENSIBLE: u16 = 0xFFFE; + +impl WavSpec { + /// Bytes one sample of one channel occupies in the file. + pub fn bytes_per_sample(&self) -> usize { + usize::from(self.bits_per_sample).div_ceil(8) + } + + /// Bytes one frame (one sample of every channel) occupies. + pub fn block_align(&self) -> usize { + self.bytes_per_sample() * usize::from(self.channels) + } + + /// The equivalent family sample format. 24-bit widens to + /// [`ec_core::SampleFormat::S32`], as the IR documents. + pub fn sample_format(&self) -> Result { + use ec_core::SampleFormat as F; + match (self.sample_format, self.bits_per_sample) { + (SampleType::Int, 8) => Ok(F::U8), + (SampleType::Int, 16) => Ok(F::S16), + (SampleType::Int, 24 | 32) => Ok(F::S32), + (SampleType::Float, 32) => Ok(F::F32), + (t, b) => Err(Error::unsupported( + format!("{b}-bit {t:?} WAVE samples"), + "ec-riff carries 8/16/24/32-bit integer and 32-bit float PCM", + )), + } + } + + /// The channel layout a bare channel count implies (mono, stereo, 5.1, 7.1). + pub fn layout(&self) -> ec_core::ChannelLayout { + ec_core::ChannelLayout::from_count(usize::from(self.channels)) + } + + /// Validate what a header must satisfy before either direction trusts it. + fn validate(&self) -> Result<()> { + if self.channels == 0 { + return Err(Error::corrupt("WAVE fmt: zero channels")); + } + if self.sample_rate == 0 { + return Err(Error::corrupt("WAVE fmt: zero sample rate")); + } + self.sample_format().map(|_| ()) + } + + /// `WAVE_FORMAT_EXTENSIBLE` is due for more than two channels or more than + /// 16 bits — the cases where a bare PCM tag is ambiguous about layout. + fn is_extensible(&self) -> bool { + self.channels > 2 || self.bits_per_sample > 16 + } + + /// The `dwChannelMask` for the implied layout; 0 when the count has no + /// standard mask, which is legal and means "unassigned". + fn channel_mask(&self) -> u32 { + use ec_core::ChannelPosition as P; + let layout = self.layout(); + let mut mask = 0u32; + for p in layout.positions() { + mask |= match p { + P::FrontLeft => 0x1, + P::FrontRight => 0x2, + P::FrontCenter => 0x4, + P::Lfe => 0x8, + P::BackLeft => 0x10, + P::BackRight => 0x20, + P::FrontLeftOfCenter => 0x40, + P::FrontRightOfCenter => 0x80, + P::BackCenter => 0x100, + P::SideLeft => 0x200, + P::SideRight => 0x400, + }; + } + // `ChannelLayout::from_count` fills unknown counts with repeated + // FrontCenter, which would collapse to a one-bit mask claiming fewer + // channels than the header. Unassigned is the honest answer there. + if mask.count_ones() as u16 != self.channels { + 0 + } else { + mask + } + } + + /// The `wFormatTag` (or extensible sub-format tag) for this spec. + fn format_tag(&self) -> u16 { + match self.sample_format { + SampleType::Int => FORMAT_PCM, + SampleType::Float => FORMAT_FLOAT, + } + } +} diff --git a/crates/ec-riff/src/read.rs b/crates/ec-riff/src/read.rs new file mode 100644 index 00000000..fd3532e4 --- /dev/null +++ b/crates/ec-riff/src/read.rs @@ -0,0 +1,214 @@ +//! WAVE reader: chunk-walking, tolerant of everything but a broken `fmt `. + +use std::fs::File; +use std::io::{BufReader, Read}; +use std::path::Path; + +use ec_core::{Error, Result}; + +use crate::{FORMAT_EXTENSIBLE, FORMAT_FLOAT, FORMAT_PCM, SampleType, WavSpec}; + +/// Reads the header of a WAVE stream, then its samples. +/// +/// Construction stops at the `data` chunk, so the reader needs only [`Read`]: +/// chunks before `data` (`LIST`, `INFO`, `fact`, `bext`, anything) are skipped +/// with their pad byte, and chunks after it are never looked at. +pub struct WavReader { + inner: R, + spec: WavSpec, + /// Bytes the `data` header claimed, or `None` when it claimed a streaming + /// placeholder and the file itself is the bound. + data_bytes: Option, +} + +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, leaving it at the samples. + pub fn new(mut inner: R) -> Result { + let riff = read_exact::<12, _>(&mut inner)?; + if &riff[0..4] != b"RIFF" || &riff[8..12] != b"WAVE" { + if &riff[0..4] == b"RF64" { + return Err(Error::unsupported( + "an RF64/BW64 file", + "the 64-bit RIFF extension is not implemented", + )); + } + return Err(Error::corrupt("not a RIFF/WAVE file")); + } + + let mut spec = None; + loop { + let head = read_exact::<8, _>(&mut inner)?; + let id = [head[0], head[1], head[2], head[3]]; + let size = u32::from_le_bytes([head[4], head[5], head[6], head[7]]) as u64; + match &id { + b"fmt " => spec = Some(parse_fmt(&mut inner, size)?), + b"data" => { + let spec = spec.ok_or_else(|| { + Error::corrupt("WAVE data chunk arrived before any fmt chunk") + })?; + // 0 and 0xFFFFFFFF are both used by streamed writers that + // never came back to patch the size. + let data_bytes = (size != 0 && size != u64::from(u32::MAX)).then_some(size); + return Ok(WavReader { + inner, + spec, + data_bytes, + }); + } + _ => skip(&mut inner, size + size % 2)?, + } + } + } + + /// The `fmt ` chunk as parsed. + pub fn spec(&self) -> WavSpec { + self.spec + } + + /// Frames (one sample per channel) the `data` header claims, when it claims + /// one. A truncated file reports fewer from [`Self::read_all_i32`]. + pub fn duration(&self) -> Option { + self.data_bytes.map(|b| b / self.spec.block_align() as u64) + } + + /// Read the whole `data` chunk as interleaved bytes, stopping at whichever + /// comes first: the declared size or the end of the stream. + fn read_data(&mut self) -> Result> { + let mut buf = Vec::new(); + match self.data_bytes { + Some(n) => { + // `take` + `read_to_end` grows as data actually arrives, so a + // header claiming 4 GiB over a 1 KiB file allocates 1 KiB. + (&mut self.inner).take(n).read_to_end(&mut buf)?; + } + None => { + self.inner.read_to_end(&mut buf)?; + } + } + let align = self.spec.block_align(); + buf.truncate(buf.len() / align * align); + Ok(buf) + } + + /// Read every integer sample, interleaved, sign-extended to `i32`. + /// + /// Refuses float files: [`Self::read_all_f32`] is their reader. + pub fn read_all_i32(&mut self) -> Result> { + if self.spec.sample_format == SampleType::Float { + return Err(Error::unsupported( + "reading a float WAVE file as integers", + "use read_all_f32; the scale factor is the caller's decision", + )); + } + let bits = self.spec.bits_per_sample; + let width = self.spec.bytes_per_sample(); + let buf = self.read_data()?; + Ok(buf + .chunks_exact(width) + .map(|c| match bits { + // Unsigned and biased, alone among the depths. + 8 => i32::from(c[0]) - 128, + 16 => i32::from(i16::from_le_bytes([c[0], c[1]])), + 24 => i32::from_le_bytes([0, c[0], c[1], c[2]]) >> 8, + _ => i32::from_le_bytes([c[0], c[1], c[2], c[3]]), + }) + .collect()) + } + + /// Read every sample as `f32`, interleaved. + /// + /// Float files pass through untouched; integer files are normalised by + /// `2^(bits-1)` — the same scaling ffmpeg's `pcm_f32le` conversion applies, + /// so the two outputs are comparable sample for sample. + pub fn read_all_f32(&mut self) -> Result> { + if self.spec.sample_format == SampleType::Float { + let buf = self.read_data()?; + return Ok(buf + .chunks_exact(4) + .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])) + .collect()); + } + let scale = 1.0f32 / (1i64 << (self.spec.bits_per_sample - 1)) as f32; + Ok(self + .read_all_i32()? + .into_iter() + .map(|v| v as f32 * scale) + .collect()) + } +} + +/// Read exactly `N` bytes; a short read is a truncated file, not a panic. +fn read_exact(r: &mut R) -> Result<[u8; N]> { + let mut buf = [0u8; N]; + r.read_exact(&mut buf).map_err(|e| { + if e.kind() == std::io::ErrorKind::UnexpectedEof { + Error::corrupt("WAVE header ends mid-chunk") + } else { + Error::Io(e) + } + })?; + Ok(buf) +} + +/// Discard `n` bytes without seeking, so the reader works over pipes too. +fn skip(r: &mut R, n: u64) -> Result<()> { + let copied = std::io::copy(&mut r.take(n), &mut std::io::sink())?; + if copied != n { + return Err(Error::corrupt("WAVE chunk ends past the end of the file")); + } + Ok(()) +} + +/// Parse a `fmt ` chunk body of `size` bytes, extensible or not. +fn parse_fmt(r: &mut R, size: u64) -> Result { + if size < 16 { + return Err(Error::corrupt(format!("WAVE fmt chunk is {size} bytes"))); + } + let f = read_exact::<16, _>(r)?; + let mut tag = u16::from_le_bytes([f[0], f[1]]); + let channels = u16::from_le_bytes([f[2], f[3]]); + let sample_rate = u32::from_le_bytes([f[4], f[5], f[6], f[7]]); + let bits_per_sample = u16::from_le_bytes([f[14], f[15]]); + let mut rest = size - 16; + + if tag == FORMAT_EXTENSIBLE { + if rest < 24 { + return Err(Error::corrupt( + "WAVE_FORMAT_EXTENSIBLE fmt chunk without its 22-byte extension", + )); + } + let ext = read_exact::<24, _>(r)?; + rest -= 24; + // Only the first two bytes of the sub-format GUID name the encoding; + // the rest is the fixed WAVE tail, and drivers in the wild vary it + // enough that rejecting on it would refuse valid files. + tag = u16::from_le_bytes([ext[8], ext[9]]); + } + skip(r, rest + size % 2)?; + + let sample_format = match tag { + FORMAT_PCM => SampleType::Int, + FORMAT_FLOAT => SampleType::Float, + other => { + return Err(Error::unsupported( + format!("WAVE format tag {other:#06x}"), + "ec-riff carries integer and IEEE-float PCM only", + )); + } + }; + let spec = WavSpec { + channels, + sample_rate, + bits_per_sample, + sample_format, + }; + spec.validate()?; + Ok(spec) +} diff --git a/crates/ec-riff/src/write.rs b/crates/ec-riff/src/write.rs new file mode 100644 index 00000000..2324ccb4 --- /dev/null +++ b/crates/ec-riff/src/write.rs @@ -0,0 +1,274 @@ +//! Streaming WAVE writer. + +use std::fs::File; +use std::io::{BufWriter, Seek, SeekFrom, Write}; +use std::path::Path; + +use ec_core::{Error, Result}; + +use crate::{FORMAT_EXTENSIBLE, SampleType, WavSpec}; + +/// A sample a [`WavWriter`] accepts. +/// +/// Integer types write to integer files and `f32` writes to float files; the +/// crossing combinations are refused rather than guessed at, because the scale +/// factor between them is a decision the caller owns. +pub trait Sample: Copy { + /// True for the float carriers. + const FLOAT: bool; + /// The value as a 32-bit integer, at the file's own depth. + fn as_i32(self) -> i32; + /// The value as an `f32`. + fn as_f32(self) -> f32; +} + +macro_rules! int_sample { + ($($t:ty),*) => {$( + impl Sample for $t { + const FLOAT: bool = false; + fn as_i32(self) -> i32 { + i32::from(self) + } + fn as_f32(self) -> f32 { + self as f32 + } + } + )*}; +} +int_sample!(i8, i16); + +impl Sample for i32 { + const FLOAT: bool = false; + fn as_i32(self) -> i32 { + self + } + fn as_f32(self) -> f32 { + self as f32 + } +} + +impl Sample for f32 { + const FLOAT: bool = true; + fn as_i32(self) -> i32 { + self as i32 + } + fn as_f32(self) -> f32 { + self + } +} + +/// Writes a WAVE file sample by sample, patching the sizes in [`Self::finalize`]. +/// +/// Samples are interleaved in channel order: one call per channel per frame. +pub struct WavWriter { + /// `None` only after [`WavWriter::finalize`] has taken it, which is also + /// what tells `Drop` there is nothing left to patch. + inner: Option, + spec: WavSpec, + /// Absolute offset of the `RIFF` size field. + riff_size_pos: u64, + /// Absolute offset of the `fact` sample-count field, when one was written. + fact_pos: Option, + /// Absolute offset of the `data` size field. + data_size_pos: u64, + /// Samples (not frames) written so far. + samples: u64, +} + +impl WavWriter> { + /// Create `path`, truncating it, and write the header for `spec`. + pub fn create>(path: P, spec: WavSpec) -> Result { + WavWriter::new(BufWriter::new(File::create(path)?), spec) + } +} + +impl WavWriter { + /// Write the header for `spec` at the writer's current position. + pub fn new(mut inner: W, spec: WavSpec) -> Result { + spec.validate()?; + let start = inner.stream_position()?; + let extensible = spec.is_extensible(); + let fmt_len: u32 = if extensible { 40 } else { 16 }; + let mut h: Vec = Vec::with_capacity(60); + + h.extend_from_slice(b"RIFF"); + let riff_size_pos = start + h.len() as u64; + h.extend_from_slice(&0u32.to_le_bytes()); // patched by finalize + h.extend_from_slice(b"WAVE"); + + h.extend_from_slice(b"fmt "); + h.extend_from_slice(&fmt_len.to_le_bytes()); + let tag = if extensible { + FORMAT_EXTENSIBLE + } else { + spec.format_tag() + }; + let block_align = spec.block_align() as u32; + h.extend_from_slice(&tag.to_le_bytes()); + h.extend_from_slice(&spec.channels.to_le_bytes()); + h.extend_from_slice(&spec.sample_rate.to_le_bytes()); + h.extend_from_slice(&(spec.sample_rate * block_align).to_le_bytes()); + h.extend_from_slice(&(block_align as u16).to_le_bytes()); + h.extend_from_slice(&spec.bits_per_sample.to_le_bytes()); + if extensible { + h.extend_from_slice(&22u16.to_le_bytes()); // cbSize + h.extend_from_slice(&spec.bits_per_sample.to_le_bytes()); // valid bits + h.extend_from_slice(&spec.channel_mask().to_le_bytes()); + // KSDATAFORMAT_SUBTYPE_{PCM,IEEE_FLOAT}: the tag, then the fixed + // `0000-0010-8000-00aa00389b71` tail every WAVE sub-format shares. + h.extend_from_slice(&spec.format_tag().to_le_bytes()); + h.extend_from_slice(&[0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00]); + h.extend_from_slice(&[0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71]); + } + + // A `fact` chunk is required for every non-PCM tag and harmless for the + // extensible PCM one; it holds the frame count, which finalize knows. + let fact_pos = if extensible || spec.sample_format == SampleType::Float { + h.extend_from_slice(b"fact"); + h.extend_from_slice(&4u32.to_le_bytes()); + let pos = start + h.len() as u64; + h.extend_from_slice(&0u32.to_le_bytes()); + Some(pos) + } else { + None + }; + + h.extend_from_slice(b"data"); + let data_size_pos = start + h.len() as u64; + h.extend_from_slice(&0u32.to_le_bytes()); + inner.write_all(&h)?; + + Ok(WavWriter { + inner: Some(inner), + spec, + riff_size_pos, + fact_pos, + data_size_pos, + samples: 0, + }) + } + + /// The stream being written; present until `finalize` takes it. + fn w(&mut self) -> &mut W { + self.inner.as_mut().expect("WavWriter used after finalize") + } + + /// The spec the header was written with. + pub fn spec(&self) -> WavSpec { + self.spec + } + + /// Frames (one sample per channel) written so far. + pub fn duration(&self) -> u64 { + self.samples / u64::from(self.spec.channels) + } + + /// Write one sample of one channel. + pub fn write_sample(&mut self, sample: S) -> Result<()> { + let bits = self.spec.bits_per_sample; + match self.spec.sample_format { + SampleType::Float => { + if !S::FLOAT { + return Err(Error::unsupported( + "integer samples into a float WAVE file", + "the integer-to-float scale factor is the caller's decision", + )); + } + self.w().write_all(&sample.as_f32().to_le_bytes())?; + } + SampleType::Int => { + if S::FLOAT { + return Err(Error::unsupported( + "float samples into an integer WAVE file", + "the float-to-integer scale factor is the caller's decision", + )); + } + let v = sample.as_i32(); + let limit = 1i64 << (bits - 1); + if i64::from(v) < -limit || i64::from(v) >= limit { + return Err(Error::corrupt(format!( + "sample {v} does not fit {bits} bits" + ))); + } + match bits { + // 8-bit WAVE is unsigned, biased by 128. + 8 => self.w().write_all(&[(v + 128) as u8])?, + 16 => self.w().write_all(&(v as i16).to_le_bytes())?, + 24 => self.w().write_all(&v.to_le_bytes()[..3])?, + _ => self.w().write_all(&v.to_le_bytes())?, + } + } + } + self.samples += 1; + Ok(()) + } + + /// Write a run of interleaved samples. + pub fn write_samples(&mut self, samples: &[S]) -> Result<()> { + for &s in samples { + self.write_sample(s)?; + } + Ok(()) + } + + /// Pad to an even boundary, patch the sizes, flush, and hand the stream back. + /// + /// Dropping instead patches on a best-effort basis and swallows the error; + /// only this reports the difference between a finished file and a truncated + /// one, which is why it exists next to `Drop`. + pub fn finalize(mut self) -> Result { + if !self.samples.is_multiple_of(u64::from(self.spec.channels)) { + return Err(Error::corrupt(format!( + "{} samples is not a whole number of {}-channel frames", + self.samples, self.spec.channels + ))); + } + self.patch()?; + self.w().flush()?; + Ok(self.inner.take().expect("WavWriter finalized twice")) + } + + /// The size patching both `finalize` and `Drop` go through. + fn patch(&mut self) -> Result<()> { + let data_bytes = self.samples * self.spec.bytes_per_sample() as u64; + let end = self.data_size_pos + 4 + data_bytes; + // RIFF chunks are word-aligned: an odd `data` gets a pad byte that its + // own size field does not count. + let pad = data_bytes % 2; + let riff_size = end + pad - (self.riff_size_pos + 4); + if riff_size > u64::from(u32::MAX) { + return Err(Error::unsupported( + "a WAVE file larger than 4 GiB", + "the 64-bit RF64/BW64 extension is not implemented", + )); + } + let (riff_pos, data_pos) = (self.riff_size_pos, self.data_size_pos); + let fact = self + .fact_pos + .map(|pos| (pos, (self.samples / u64::from(self.spec.channels)) as u32)); + let w = self.w(); + if pad == 1 { + w.seek(SeekFrom::Start(end))?; + w.write_all(&[0])?; + } + w.seek(SeekFrom::Start(riff_pos))?; + w.write_all(&(riff_size as u32).to_le_bytes())?; + if let Some((pos, frames)) = fact { + w.seek(SeekFrom::Start(pos))?; + w.write_all(&frames.to_le_bytes())?; + } + w.seek(SeekFrom::Start(data_pos))?; + w.write_all(&(data_bytes as u32).to_le_bytes())?; + w.seek(SeekFrom::Start(end + pad))?; + Ok(()) + } +} + +impl Drop for WavWriter { + fn drop(&mut self) { + if self.inner.is_some() { + let _ = self.patch(); + let _ = self.w().flush(); + } + } +} diff --git a/crates/ec-riff/tests/wav.rs b/crates/ec-riff/tests/wav.rs new file mode 100644 index 00000000..49434ab3 --- /dev/null +++ b/crates/ec-riff/tests/wav.rs @@ -0,0 +1,314 @@ +//! Round-trip, header and tolerance checks, plus the fixtures on disk. +//! +//! The oracle artifacts this writes into `CARGO_TARGET_TMPDIR/oracle` are the +//! ffmpeg half of the story: after `cargo test -p ec-riff`, each `.wav` +//! is compared against its `.raw` (the samples that went in, as f32le) +//! with `oracle audio-compare .raw .wav`. + +use std::io::Cursor; + +use ec_riff::{SampleType, WavReader, WavSpec, WavWriter}; + +/// Deterministic samples in `bits`-bit range: a walking pattern that exercises +/// both signs and the extremes of the depth. +fn int_samples(n: usize, bits: u16) -> Vec { + let limit = 1i64 << (bits - 1); + (0..n) + .map(|i| match i % 5 { + 0 => (limit - 1) as i32, + 1 => (-limit) as i32, + 2 => 0, + 3 => ((i as i64 * 2_654_435_761) % limit) as i32, + _ => -(((i as i64 * 40_503) % limit) as i32), + }) + .collect() +} + +fn float_samples(n: usize) -> Vec { + (0..n) + .map(|i| match i % 4 { + 0 => 1.0, + 1 => -1.0, + 2 => 0.0, + _ => (i as f32 * 0.017).sin(), + }) + .collect() +} + +fn spec(channels: u16, rate: u32, bits: u16, sample_format: SampleType) -> WavSpec { + WavSpec { + channels, + sample_rate: rate, + bits_per_sample: bits, + sample_format, + } +} + +#[test] +fn int_round_trip_is_bit_exact_every_depth_layout_and_rate() { + for bits in [8u16, 16, 24, 32] { + for channels in [1u16, 2, 6, 8] { + for rate in [8000u32, 44100, 48000, 192_000] { + let s = spec(channels, rate, bits, SampleType::Int); + let samples = int_samples(usize::from(channels) * 97, bits); + let mut w = WavWriter::new(Cursor::new(Vec::new()), s).unwrap(); + w.write_samples(&samples).unwrap(); + let bytes = w.finalize().unwrap().into_inner(); + let mut r = WavReader::new(Cursor::new(&bytes[..])).unwrap(); + assert_eq!(r.spec(), s, "spec round-trip {bits}b {channels}ch {rate}Hz"); + assert_eq!( + r.duration(), + Some(97), + "frame count {bits}b {channels}ch {rate}Hz" + ); + assert_eq!( + r.read_all_i32().unwrap(), + samples, + "samples {bits}b {channels}ch {rate}Hz" + ); + assert_eq!(bytes.len() % 2, 0, "RIFF stays word-aligned"); + } + } + } +} + +#[test] +fn float_round_trip_is_bit_exact() { + for channels in [1u16, 2, 6, 8] { + let s = spec(channels, 48000, 32, SampleType::Float); + let samples = float_samples(usize::from(channels) * 64); + let mut w = WavWriter::new(Cursor::new(Vec::new()), s).unwrap(); + w.write_samples(&samples).unwrap(); + let bytes = w.finalize().unwrap().into_inner(); + let mut r = WavReader::new(Cursor::new(&bytes[..])).unwrap(); + assert_eq!(r.spec(), s); + assert_eq!(r.read_all_f32().unwrap(), samples, "{channels}ch float"); + } +} + +#[test] +fn header_says_extensible_exactly_when_it_must() { + // <=2 channels and <=16 bits: plain WAVE_FORMAT_PCM, 16-byte fmt. + for (channels, bits, extensible) in [ + (1u16, 8u16, false), + (2, 16, false), + (1, 24, true), + (2, 32, true), + (6, 16, true), + (8, 16, true), + ] { + let s = spec(channels, 48000, bits, SampleType::Int); + let mut w = WavWriter::new(Cursor::new(Vec::new()), s).unwrap(); + w.write_samples(&vec![0i32; usize::from(channels)]).unwrap(); + let bytes = w.finalize().unwrap().into_inner(); + + let fmt_size = u32::from_le_bytes(bytes[16..20].try_into().unwrap()); + let tag = u16::from_le_bytes(bytes[20..22].try_into().unwrap()); + let block_align = u16::from_le_bytes(bytes[32..34].try_into().unwrap()); + let byte_rate = u32::from_le_bytes(bytes[28..32].try_into().unwrap()); + assert_eq!( + fmt_size, + if extensible { 40 } else { 16 }, + "{channels}ch {bits}b" + ); + assert_eq!( + tag, + if extensible { 0xFFFE } else { 1 }, + "{channels}ch {bits}b" + ); + assert_eq!(u32::from(block_align), (bits as u32 / 8) * channels as u32); + assert_eq!(byte_rate, 48000 * u32::from(block_align)); + if extensible { + let mask = u32::from_le_bytes(bytes[40..44].try_into().unwrap()); + let expect = match channels { + 1 => 0x4, // FC + 2 => 0x3, // FL FR + 6 => 0x3F, // FL FR FC LFE BL BR + 8 => 0x63F, // + SL SR + _ => unreachable!(), + }; + assert_eq!(mask, expect, "channel mask {channels}ch"); + // Sub-format GUID starts with the real tag, then the WAVE tail. + assert_eq!(&bytes[44..46], &1u16.to_le_bytes()); + assert_eq!(&bytes[54..60], &[0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71]); + } + // Every file the writer produces reads back as itself. + assert_eq!(WavReader::new(Cursor::new(&bytes[..])).unwrap().spec(), s); + } +} + +#[test] +fn reader_skips_junk_odd_and_list_chunks() { + // A hand-built file: LIST/INFO before fmt, an odd-sized chunk with its pad + // byte between fmt and data, and a trailing chunk after data. + let mut f: Vec = Vec::new(); + f.extend_from_slice(b"RIFF\0\0\0\0WAVE"); + f.extend_from_slice(b"LIST"); + f.extend_from_slice(&12u32.to_le_bytes()); + f.extend_from_slice(b"INFOISFT\x04\0\0\0"); + f.extend_from_slice(b"fmt "); + f.extend_from_slice(&16u32.to_le_bytes()); + f.extend_from_slice(&1u16.to_le_bytes()); // PCM + f.extend_from_slice(&2u16.to_le_bytes()); // stereo + f.extend_from_slice(&44100u32.to_le_bytes()); + f.extend_from_slice(&(44100u32 * 4).to_le_bytes()); + f.extend_from_slice(&4u16.to_le_bytes()); + f.extend_from_slice(&16u16.to_le_bytes()); + f.extend_from_slice(b"junk"); + f.extend_from_slice(&3u32.to_le_bytes()); + f.extend_from_slice(&[1, 2, 3, 0]); // 3 bytes + RIFF pad + f.extend_from_slice(b"data"); + f.extend_from_slice(&8u32.to_le_bytes()); + for v in [1i16, -1, 32767, -32768] { + f.extend_from_slice(&v.to_le_bytes()); + } + f.extend_from_slice(b"id3 "); + f.extend_from_slice(&2u32.to_le_bytes()); + f.extend_from_slice(&[0, 0]); + + let mut r = WavReader::new(Cursor::new(&f[..])).unwrap(); + assert_eq!(r.spec().channels, 2); + assert_eq!(r.spec().sample_rate, 44100); + assert_eq!(r.duration(), Some(2)); + // The trailing chunk is not audio: exactly the declared 4 samples come out. + assert_eq!(r.read_all_i32().unwrap(), vec![1, -1, 32767, -32768]); +} + +#[test] +fn truncated_and_placeholder_sizes_read_what_is_there() { + let s = spec(2, 48000, 16, SampleType::Int); + let samples = int_samples(20, 16); + let mut w = WavWriter::new(Cursor::new(Vec::new()), s).unwrap(); + w.write_samples(&samples).unwrap(); + let good = w.finalize().unwrap().into_inner(); + + // Header claims the full length, file is cut in half. + let cut = good[..good.len() - 20].to_vec(); + let mut r = WavReader::new(Cursor::new(&cut[..])).unwrap(); + assert_eq!(r.read_all_i32().unwrap(), samples[..10].to_vec()); + + // A streaming writer that never patched: 0xFFFFFFFF means "to the end". + let mut stream = good.clone(); + let n = stream.len(); + stream[n - 40 - 4..n - 40].copy_from_slice(&u32::MAX.to_le_bytes()); + let mut r = WavReader::new(Cursor::new(&stream[..])).unwrap(); + assert_eq!(r.duration(), None); + assert_eq!(r.read_all_i32().unwrap(), samples); +} + +#[test] +fn refusals_name_a_real_absence() { + // Not RIFF at all. + assert!(WavReader::new(Cursor::new(&b"OggS\0\0\0\0\0\0\0\0"[..])).is_err()); + // ADPCM: a tag we genuinely do not decode. + let mut f: Vec = Vec::new(); + f.extend_from_slice(b"RIFF\0\0\0\0WAVEfmt "); + f.extend_from_slice(&16u32.to_le_bytes()); + f.extend_from_slice(&2u16.to_le_bytes()); // WAVE_FORMAT_ADPCM + f.extend_from_slice(&1u16.to_le_bytes()); + f.extend_from_slice(&8000u32.to_le_bytes()); + f.extend_from_slice(&8000u32.to_le_bytes()); + f.extend_from_slice(&1u16.to_le_bytes()); + f.extend_from_slice(&4u16.to_le_bytes()); + let e = WavReader::new(Cursor::new(&f[..])) + .err() + .expect("ADPCM was accepted") + .to_string(); + assert!(e.contains("0x0002"), "{e}"); + + // Writing a sample too wide for the declared depth is caught, not clipped. + let mut w = + WavWriter::new(Cursor::new(Vec::new()), spec(1, 48000, 16, SampleType::Int)).unwrap(); + assert!(w.write_sample(32768i32).is_err()); + assert!(w.write_sample(1.0f32).is_err(), "float into an int file"); + // A half-written frame is a truncated file, and finalize says so. + let mut w = + WavWriter::new(Cursor::new(Vec::new()), spec(2, 48000, 16, SampleType::Int)).unwrap(); + w.write_sample(1i16).unwrap(); + assert!(w.finalize().is_err()); +} + +#[test] +fn reads_every_wav_fixture() { + let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/../../fixtures/audio"); + let Ok(entries) = std::fs::read_dir(dir) else { + eprintln!("fixtures/audio absent (gitignored) — skipping"); + return; + }; + let mut seen = 0; + for e in entries.flatten() { + let path = e.path(); + if path.extension().and_then(|s| s.to_str()) != Some("wav") { + continue; + } + let name = path.file_name().unwrap().to_string_lossy().to_string(); + let mut r = WavReader::open(&path).unwrap_or_else(|e| panic!("{name}: {e}")); + let spec = r.spec(); + // The generator names layout and rate in the file name; the header must agree. + let channels = if name.contains("mono") { + 1 + } else if name.contains("stereo") { + 2 + } else { + 6 + }; + assert_eq!(spec.channels, channels, "{name}"); + assert!(name.contains(&spec.sample_rate.to_string()), "{name}"); + assert_eq!(spec.sample_format, SampleType::Int, "{name}"); + let samples = r.read_all_i32().unwrap(); + assert!(!samples.is_empty(), "{name} decoded nothing"); + assert_eq!(samples.len() % usize::from(channels), 0, "{name}"); + assert!( + samples.iter().any(|&v| v != 0), + "{name} is silence — the fixture or the reader is wrong" + ); + // What we read, as f32le, for `oracle audio-compare .raw `: + // ffmpeg decodes the same file and the two must agree sample for sample. + let mut r = WavReader::open(&path).unwrap(); + let raw: Vec = r + .read_all_f32() + .unwrap() + .iter() + .flat_map(|v| v.to_le_bytes()) + .collect(); + let dir = std::path::Path::new(env!("CARGO_TARGET_TMPDIR")).join("oracle"); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join(format!("{name}.raw")), raw).unwrap(); + seen += 1; + } + assert!(seen >= 6, "expected the six wav16 fixtures, saw {seen}"); +} + +/// Write the pairs the `oracle` binary compares: our WAV, and the samples that +/// went into it as f32le. Not an assertion — the assertion is the oracle run. +#[test] +fn emit_oracle_artifacts() { + let dir = std::path::Path::new(env!("CARGO_TARGET_TMPDIR")).join("oracle"); + std::fs::create_dir_all(&dir).unwrap(); + for (name, channels, rate, bits, format) in [ + ("i16-stereo-48000", 2u16, 48000u32, 16u16, SampleType::Int), + ("i24-5_1-44100", 6, 44100, 24, SampleType::Int), + ("i32-mono-48000", 1, 48000, 32, SampleType::Int), + ("i8-stereo-44100", 2, 44100, 8, SampleType::Int), + ("f32-7_1-48000", 8, 48000, 32, SampleType::Float), + ] { + let s = spec(channels, rate, bits, format); + let frames = 4096; + let n = frames * usize::from(channels); + let mut w = WavWriter::create(dir.join(format!("{name}.wav")), s).unwrap(); + let raw: Vec = if format == SampleType::Float { + let samples = float_samples(n); + w.write_samples(&samples).unwrap(); + samples + } else { + let samples = int_samples(n, bits); + w.write_samples(&samples).unwrap(); + let scale = 1.0f32 / (1i64 << (bits - 1)) as f32; + samples.iter().map(|&v| v as f32 * scale).collect() + }; + w.finalize().unwrap(); + let bytes: Vec = raw.iter().flat_map(|v| v.to_le_bytes()).collect(); + std::fs::write(dir.join(format!("{name}.raw")), bytes).unwrap(); + } + eprintln!("oracle artifacts in {}", dir.display()); +} diff --git a/shims/hound/Cargo.toml b/shims/hound/Cargo.toml new file mode 100644 index 00000000..e8a65261 --- /dev/null +++ b/shims/hound/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "hound" +description = "Compatibility shim: the hound 3.5.1 WAV-writing surface, implemented over ec-riff." +version = "3.5.1" +edition.workspace = true +license.workspace = true +authors.workspace = true + +[dependencies] +ec-riff.workspace = true diff --git a/shims/hound/src/lib.rs b/shims/hound/src/lib.rs new file mode 100644 index 00000000..ca708783 --- /dev/null +++ b/shims/hound/src/lib.rs @@ -0,0 +1,192 @@ +//! `hound` 3.5.1's WAV-writing 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`, [`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. Reading is `ec-riff`'s +//! [`ec_riff::WavReader`]; the shim does not wrap it. +//! +//! 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, BufWriter, Seek, Write}; +use std::path::Path; + +pub use ec_riff::Sample; + +/// 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)) + } +} diff --git a/shims/hound/tests/edith_surface.rs b/shims/hound/tests/edith_surface.rs new file mode 100644 index 00000000..0f79610e --- /dev/null +++ b/shims/hound/tests/edith_surface.rs @@ -0,0 +1,78 @@ +//! The call edith makes, verbatim in shape (engine/src/export.rs `write_wav`): +//! `WavWriter::create(path, WavSpec { .. sample_format: Int })`, a run of +//! `write_sample(x as i16)`, then `finalize()` — with the `?` conversion into +//! edith's `Box` exercised too. + +type EdithError = Box; + +fn write_wav( + out: &std::path::Path, + samples: &[i32], + channels: u16, + rate: u32, +) -> Result<(), EdithError> { + let mut writer = hound::WavWriter::create( + out, + hound::WavSpec { + channels, + sample_rate: rate, + bits_per_sample: 16, + sample_format: hound::SampleFormat::Int, + }, + )?; + for &sample in samples { + writer.write_sample(sample as i16)?; + } + writer.finalize()?; + Ok(()) +} + +#[test] +fn edith_write_wav_round_trips() { + let dir = std::path::Path::new(env!("CARGO_TARGET_TMPDIR")); + std::fs::create_dir_all(dir).unwrap(); + for (channels, rate) in [(1u16, 44100u32), (2, 48000), (6, 48000)] { + let path = dir.join(format!("edith-{channels}ch-{rate}.wav")); + let samples: Vec = (0..usize::from(channels) * 512) + .map(|i| ((i as i32 * 733) % 65536) - 32768) + .collect(); + write_wav(&path, &samples, channels, rate).unwrap(); + + let mut r = ec_riff::WavReader::open(&path).unwrap(); + let spec = r.spec(); + assert_eq!(spec.channels, channels); + assert_eq!(spec.sample_rate, rate); + assert_eq!(spec.bits_per_sample, 16); + assert_eq!(spec.sample_format, ec_riff::SampleType::Int); + assert_eq!(r.read_all_i32().unwrap(), samples); + } +} + +#[test] +fn errors_carry_the_incumbent_variants() { + let dir = std::path::Path::new(env!("CARGO_TARGET_TMPDIR")); + let spec = hound::WavSpec { + channels: 2, + sample_rate: 48000, + bits_per_sample: 16, + sample_format: hound::SampleFormat::Int, + }; + let mut w = hound::WavWriter::create(dir.join("errors.wav"), spec).unwrap(); + // Wider than the declared depth, and the wrong sample family: the two + // failures callers of hound match on. + assert!(matches!( + w.write_sample(40_000i32), + Err(hound::Error::TooWide) + )); + assert!(matches!( + w.write_sample(0.5f32), + Err(hound::Error::InvalidSampleFormat) + )); + w.write_sample(1i16).unwrap(); + assert!(matches!(w.finalize(), Err(hound::Error::UnfinishedSample))); + // A directory is not a file: I/O keeps its identity through the shim. + assert!(matches!( + hound::WavWriter::create(dir, spec), + Err(hound::Error::IoError(_)) + )); +}