diff --git a/crates/ec-riff/src/read.rs b/crates/ec-riff/src/read.rs index fd3532e4..40f9e7ad 100644 --- a/crates/ec-riff/src/read.rs +++ b/crates/ec-riff/src/read.rs @@ -175,6 +175,7 @@ fn parse_fmt(r: &mut R, size: u64) -> Result { 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 block_align = u16::from_le_bytes([f[12], f[13]]); let bits_per_sample = u16::from_le_bytes([f[14], f[15]]); let mut rest = size - 16; @@ -203,6 +204,14 @@ fn parse_fmt(r: &mut R, size: u64) -> Result { )); } }; + // A depth that is not a whole number of bytes (12-bit, 20-bit) is + // ill-formed for these tags, not merely unimplemented: nothing in the + // header says how the odd bits sit in their container. + if bits_per_sample % 8 != 0 { + return Err(Error::corrupt(format!( + "WAVE fmt: {bits_per_sample} bits per sample is not a multiple of eight" + ))); + } let spec = WavSpec { channels, sample_rate, @@ -210,5 +219,14 @@ fn parse_fmt(r: &mut R, size: u64) -> Result { sample_format, }; spec.validate()?; + // The stride the file declares must be the stride the depth implies — + // otherwise every frame after the first is read from the wrong offset. + // Padded containers (8-bit samples in 2-byte slots) live here. + if usize::from(block_align) != spec.block_align() { + return Err(Error::unsupported( + format!("a WAVE block align of {block_align} for {channels}x{bits_per_sample}-bit"), + "ec-riff reads samples packed at their declared depth, without container padding", + )); + } Ok(spec) } diff --git a/shims/hound/src/lib.rs b/shims/hound/src/lib.rs index fb006c36..84d02d2e 100644 --- a/shims/hound/src/lib.rs +++ b/shims/hound/src/lib.rs @@ -8,10 +8,20 @@ //! — 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 +//! Behaviour differences from the incumbent. Writing is stricter only: 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. +//! a `fact` chunk goes with it. Reading diverges in shape, not in verdict — +//! the refusals are hound's, the reporting is not: +//! +//! * [`WavReader::samples`] reads the `data` chunk whole before yielding, so a +//! file that ends early yields one [`Error::IoError`] and nothing else, +//! where hound yields the samples it did read and then the `UnexpectedEof`. +//! [`Error::TooWide`] and [`Error::InvalidSampleFormat`] are single-item for +//! the same reason; hound repeats them per sample. +//! * `bits_per_sample` outside 8/16/24/32 is [`Error::FormatError`] when it is +//! not a whole number of bytes and [`Error::Unsupported`] otherwise, which +//! splits hound's refusals along the same line but not with its wording. #![forbid(unsafe_code)] #![warn(missing_docs)] @@ -275,18 +285,31 @@ impl WavReader { pub fn samples(&mut self) -> WavSamples { let spec = self.inner.spec(); let float_file = spec.sample_format == ec_riff::SampleType::Float; + // What the `data` header promised. `ec-riff` stops at the end of the + // file without complaint; hound hands the caller the `UnexpectedEof`, + // so the promise is compared against what arrived. + let promised = self + .inner + .duration() + .map(|frames| frames as usize * usize::from(spec.channels)); 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(), + Ok(v) => match short_read(v.len(), promised) { + Some(e) => vec![Err(e)], + None => 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(), + Ok(v) => match short_read(v.len(), promised) { + Some(e) => vec![Err(e)], + None => v.into_iter().map(|s| Ok(S::from_i32(s))).collect(), + }, Err(e) => vec![Err(map(e, Error::FormatError("truncated WAVE data")))], } }; @@ -294,6 +317,17 @@ impl WavReader { } } +/// The `UnexpectedEof` hound reports when the `data` chunk ends before the +/// length its header declares, or `None` when the file kept its promise (or +/// made none: a streamed placeholder size leaves the file itself the bound). +fn short_read(got: usize, promised: Option) -> Option { + let want = promised.filter(|&n| got < n)?; + Some(Error::IoError(io::Error::new( + io::ErrorKind::UnexpectedEof, + format!("WAVE data chunk ends after {got} of {want} samples"), + ))) +} + /// The iterator [`WavReader::samples`] returns. pub struct WavSamples(std::vec::IntoIter>); diff --git a/shims/hound/tests/edith_surface.rs b/shims/hound/tests/edith_surface.rs index 18bb8556..d8a846e1 100644 --- a/shims/hound/tests/edith_surface.rs +++ b/shims/hound/tests/edith_surface.rs @@ -85,6 +85,81 @@ fn edith_read_wav_round_trips() { )); } +/// A `data` chunk that ends before its header said is hound's `IoError` +/// (`UnexpectedEof`), never a short read the caller mistakes for the whole file. +#[test] +fn truncated_data_chunk_errors() { + let dir = std::path::Path::new(env!("CARGO_TARGET_TMPDIR")); + std::fs::create_dir_all(dir).unwrap(); + let path = dir.join("truncated.wav"); + let samples: Vec = (0..1024).map(|i| (i * 17) % 4096).collect(); + write_wav(&path, &samples, 2, 48000).unwrap(); + + // Half the samples away, the header still promising all of them. + let bytes = std::fs::read(&path).unwrap(); + std::fs::write(&path, &bytes[..bytes.len() - 1024]).unwrap(); + + let mut r = hound::WavReader::open(&path).unwrap(); + let first = r.samples::().next(); + assert!( + matches!(&first, Some(Err(hound::Error::IoError(e))) if e.kind() == std::io::ErrorKind::UnexpectedEof), + "expected UnexpectedEof, got {first:?}" + ); +} + +/// A minimal PCM WAVE header with `block_align` and `bits_per_sample` stated +/// independently, so a padded container can be handed to the reader. +fn wav_bytes(channels: u16, bits: u16, block_align: u16, data: &[u8]) -> Vec { + let mut v = Vec::new(); + v.extend_from_slice(b"RIFF"); + v.extend_from_slice(&(36 + data.len() as u32).to_le_bytes()); + v.extend_from_slice(b"WAVEfmt "); + v.extend_from_slice(&16u32.to_le_bytes()); + v.extend_from_slice(&1u16.to_le_bytes()); // WAVE_FORMAT_PCM + v.extend_from_slice(&channels.to_le_bytes()); + v.extend_from_slice(&48000u32.to_le_bytes()); + v.extend_from_slice(&(48000 * u32::from(block_align)).to_le_bytes()); + v.extend_from_slice(&block_align.to_le_bytes()); + v.extend_from_slice(&bits.to_le_bytes()); + v.extend_from_slice(b"data"); + v.extend_from_slice(&(data.len() as u32).to_le_bytes()); + v.extend_from_slice(data); + v +} + +/// The header pair the reader must not paper over: a container wider than the +/// depth (hound: `Unsupported`) and a depth that is not whole bytes (hound: +/// `FormatError`). Reading either as if it were packed would silently double +/// the sample count and halve the duration. +#[test] +fn container_width_and_odd_depths_are_refused() { + let padded = wav_bytes(1, 8, 2, &[0x80, 0x00, 0x90, 0x00]); + assert!( + matches!( + hound::WavReader::new(std::io::Cursor::new(padded)), + Err(hound::Error::Unsupported) + ), + "8-bit samples in a 2-byte container must be refused" + ); + + for bits in [12u16, 20] { + let odd = wav_bytes(1, bits, bits.div_ceil(8), &[0; 8]); + assert!( + matches!( + hound::WavReader::new(std::io::Cursor::new(odd)), + Err(hound::Error::FormatError(_)) + ), + "{bits}-bit must be a FormatError" + ); + } + + // The well-formed shape of the same helper still opens, so the refusals + // above are about the fields under test and not about the fixture. + let ok = wav_bytes(2, 16, 4, &[0; 16]); + let r = hound::WavReader::new(std::io::Cursor::new(ok)).expect("a packed 16-bit stereo header"); + assert_eq!(r.spec().bits_per_sample, 16); +} + #[test] fn errors_carry_the_incumbent_variants() { let dir = std::path::Path::new(env!("CARGO_TARGET_TMPDIR"));