Refuse the headers hound refuses, and say so honestly
Browse files at this commit30d372e461d4e2e07cec9b2bc0acd2dbf213b646Parent: acb0d04- fix
- refuse the headers hound refuses, and say so honestly
3 changed files +132 -5
- crates/ec-riff/src/read.rs +18 -0
- shims/hound/src/lib.rs +39 -5
- shims/hound/tests/edith_surface.rs +75 -0
crates/ec-riff/src/read.rsmodified+18 -0
| @@ -175,6 +175,7 @@ fn parse_fmt<R: Read>(r: &mut R, size: u64) -> Result<WavSpec> { | |||
| 175 | let mut tag = u16::from_le_bytes([f[0], f[1]]); | 175 | let mut tag = u16::from_le_bytes([f[0], f[1]]); |
| 176 | let channels = u16::from_le_bytes([f[2], f[3]]); | 176 | let channels = u16::from_le_bytes([f[2], f[3]]); |
| 177 | let sample_rate = u32::from_le_bytes([f[4], f[5], f[6], f[7]]); | 177 | let sample_rate = u32::from_le_bytes([f[4], f[5], f[6], f[7]]); |
| 178 | + let block_align = u16::from_le_bytes([f[12], f[13]]); | ||
| 178 | let bits_per_sample = u16::from_le_bytes([f[14], f[15]]); | 179 | let bits_per_sample = u16::from_le_bytes([f[14], f[15]]); |
| 179 | let mut rest = size - 16; | 180 | let mut rest = size - 16; |
| 180 | 181 | ||
| @@ -203,6 +204,14 @@ fn parse_fmt<R: Read>(r: &mut R, size: u64) -> Result<WavSpec> { | |||
| 203 | )); | 204 | )); |
| 204 | } | 205 | } |
| 205 | }; | 206 | }; |
| 207 | + // A depth that is not a whole number of bytes (12-bit, 20-bit) is | ||
| 208 | + // ill-formed for these tags, not merely unimplemented: nothing in the | ||
| 209 | + // header says how the odd bits sit in their container. | ||
| 210 | + if bits_per_sample % 8 != 0 { | ||
| 211 | + return Err(Error::corrupt(format!( | ||
| 212 | + "WAVE fmt: {bits_per_sample} bits per sample is not a multiple of eight" | ||
| 213 | + ))); | ||
| 214 | + } | ||
| 206 | let spec = WavSpec { | 215 | let spec = WavSpec { |
| 207 | channels, | 216 | channels, |
| 208 | sample_rate, | 217 | sample_rate, |
| @@ -210,5 +219,14 @@ fn parse_fmt<R: Read>(r: &mut R, size: u64) -> Result<WavSpec> { | |||
| 210 | sample_format, | 219 | sample_format, |
| 211 | }; | 220 | }; |
| 212 | spec.validate()?; | 221 | spec.validate()?; |
| 222 | + // The stride the file declares must be the stride the depth implies — | ||
| 223 | + // otherwise every frame after the first is read from the wrong offset. | ||
| 224 | + // Padded containers (8-bit samples in 2-byte slots) live here. | ||
| 225 | + if usize::from(block_align) != spec.block_align() { | ||
| 226 | + return Err(Error::unsupported( | ||
| 227 | + format!("a WAVE block align of {block_align} for {channels}x{bits_per_sample}-bit"), | ||
| 228 | + "ec-riff reads samples packed at their declared depth, without container padding", | ||
| 229 | + )); | ||
| 230 | + } | ||
| 213 | Ok(spec) | 231 | Ok(spec) |
| 214 | } | 232 | } |
shims/hound/src/lib.rsmodified+39 -5
| @@ -8,10 +8,20 @@ | |||
| 8 | //! — because a shim that grows a surface nobody calls is a second | 8 | //! — because a shim that grows a surface nobody calls is a second |
| 9 | //! implementation to keep honest. | 9 | //! implementation to keep honest. |
| 10 | //! | 10 | //! |
| 11 | -//! Behaviour differences from the incumbent, all in the strict direction: | 11 | +//! Behaviour differences from the incumbent. Writing is stricter only: files |
| 12 | -//! files with more than two channels or more than 16 bits get a | 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 | 13 | //! `WAVE_FORMAT_EXTENSIBLE` header (hound writes one only above 16 bits), and |
| 14 | -//! a `fact` chunk goes with it. | 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. | ||
| 15 | 25 | ||
| 16 | #![forbid(unsafe_code)] | 26 | #![forbid(unsafe_code)] |
| 17 | #![warn(missing_docs)] | 27 | #![warn(missing_docs)] |
| @@ -275,18 +285,31 @@ impl<R: Read> WavReader<R> { | |||
| 275 | pub fn samples<S: Sample>(&mut self) -> WavSamples<S> { | 285 | pub fn samples<S: Sample>(&mut self) -> WavSamples<S> { |
| 276 | let spec = self.inner.spec(); | 286 | let spec = self.inner.spec(); |
| 277 | let float_file = spec.sample_format == ec_riff::SampleType::Float; | 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)); | ||
| 278 | let items = if float_file != S::FLOAT { | 295 | let items = if float_file != S::FLOAT { |
| 279 | vec![Err(Error::InvalidSampleFormat)] | 296 | vec![Err(Error::InvalidSampleFormat)] |
| 280 | } else if spec.bits_per_sample > S::BITS { | 297 | } else if spec.bits_per_sample > S::BITS { |
| 281 | vec![Err(Error::TooWide)] | 298 | vec![Err(Error::TooWide)] |
| 282 | } else if float_file { | 299 | } else if float_file { |
| 283 | match self.inner.read_all_f32() { | 300 | match self.inner.read_all_f32() { |
| 284 | - Ok(v) => v.into_iter().map(|s| Ok(S::from_f32(s))).collect(), | 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 | + }, | ||
| 285 | Err(e) => vec![Err(map(e, Error::FormatError("truncated WAVE data")))], | 305 | Err(e) => vec![Err(map(e, Error::FormatError("truncated WAVE data")))], |
| 286 | } | 306 | } |
| 287 | } else { | 307 | } else { |
| 288 | match self.inner.read_all_i32() { | 308 | match self.inner.read_all_i32() { |
| 289 | - Ok(v) => v.into_iter().map(|s| Ok(S::from_i32(s))).collect(), | 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 | + }, | ||
| 290 | Err(e) => vec![Err(map(e, Error::FormatError("truncated WAVE data")))], | 313 | Err(e) => vec![Err(map(e, Error::FormatError("truncated WAVE data")))], |
| 291 | } | 314 | } |
| 292 | }; | 315 | }; |
| @@ -294,6 +317,17 @@ impl<R: Read> WavReader<R> { | |||
| 294 | } | 317 | } |
| 295 | } | 318 | } |
| 296 | 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). | ||
| 323 | +fn 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 | + | ||
| 297 | /// The iterator [`WavReader::samples`] returns. | 331 | /// The iterator [`WavReader::samples`] returns. |
| 298 | pub struct WavSamples<S>(std::vec::IntoIter<Result<S>>); | 332 | pub struct WavSamples<S>(std::vec::IntoIter<Result<S>>); |
| 299 | 333 | ||
shims/hound/tests/edith_surface.rsmodified+75 -0
| @@ -85,6 +85,81 @@ fn edith_read_wav_round_trips() { | |||
| 85 | )); | 85 | )); |
| 86 | } | 86 | } |
| 87 | 87 | ||
| 88 | +/// A `data` chunk that ends before its header said is hound's `IoError` | ||
| 89 | +/// (`UnexpectedEof`), never a short read the caller mistakes for the whole file. | ||
| 90 | +#[test] | ||
| 91 | +fn truncated_data_chunk_errors() { | ||
| 92 | + let dir = std::path::Path::new(env!("CARGO_TARGET_TMPDIR")); | ||
| 93 | + std::fs::create_dir_all(dir).unwrap(); | ||
| 94 | + let path = dir.join("truncated.wav"); | ||
| 95 | + let samples: Vec<i32> = (0..1024).map(|i| (i * 17) % 4096).collect(); | ||
| 96 | + write_wav(&path, &samples, 2, 48000).unwrap(); | ||
| 97 | + | ||
| 98 | + // Half the samples away, the header still promising all of them. | ||
| 99 | + let bytes = std::fs::read(&path).unwrap(); | ||
| 100 | + std::fs::write(&path, &bytes[..bytes.len() - 1024]).unwrap(); | ||
| 101 | + | ||
| 102 | + let mut r = hound::WavReader::open(&path).unwrap(); | ||
| 103 | + let first = r.samples::<i16>().next(); | ||
| 104 | + assert!( | ||
| 105 | + matches!(&first, Some(Err(hound::Error::IoError(e))) if e.kind() == std::io::ErrorKind::UnexpectedEof), | ||
| 106 | + "expected UnexpectedEof, got {first:?}" | ||
| 107 | + ); | ||
| 108 | +} | ||
| 109 | + | ||
| 110 | +/// A minimal PCM WAVE header with `block_align` and `bits_per_sample` stated | ||
| 111 | +/// independently, so a padded container can be handed to the reader. | ||
| 112 | +fn wav_bytes(channels: u16, bits: u16, block_align: u16, data: &[u8]) -> Vec<u8> { | ||
| 113 | + let mut v = Vec::new(); | ||
| 114 | + v.extend_from_slice(b"RIFF"); | ||
| 115 | + v.extend_from_slice(&(36 + data.len() as u32).to_le_bytes()); | ||
| 116 | + v.extend_from_slice(b"WAVEfmt "); | ||
| 117 | + v.extend_from_slice(&16u32.to_le_bytes()); | ||
| 118 | + v.extend_from_slice(&1u16.to_le_bytes()); // WAVE_FORMAT_PCM | ||
| 119 | + v.extend_from_slice(&channels.to_le_bytes()); | ||
| 120 | + v.extend_from_slice(&48000u32.to_le_bytes()); | ||
| 121 | + v.extend_from_slice(&(48000 * u32::from(block_align)).to_le_bytes()); | ||
| 122 | + v.extend_from_slice(&block_align.to_le_bytes()); | ||
| 123 | + v.extend_from_slice(&bits.to_le_bytes()); | ||
| 124 | + v.extend_from_slice(b"data"); | ||
| 125 | + v.extend_from_slice(&(data.len() as u32).to_le_bytes()); | ||
| 126 | + v.extend_from_slice(data); | ||
| 127 | + v | ||
| 128 | +} | ||
| 129 | + | ||
| 130 | +/// The header pair the reader must not paper over: a container wider than the | ||
| 131 | +/// depth (hound: `Unsupported`) and a depth that is not whole bytes (hound: | ||
| 132 | +/// `FormatError`). Reading either as if it were packed would silently double | ||
| 133 | +/// the sample count and halve the duration. | ||
| 134 | +#[test] | ||
| 135 | +fn container_width_and_odd_depths_are_refused() { | ||
| 136 | + let padded = wav_bytes(1, 8, 2, &[0x80, 0x00, 0x90, 0x00]); | ||
| 137 | + assert!( | ||
| 138 | + matches!( | ||
| 139 | + hound::WavReader::new(std::io::Cursor::new(padded)), | ||
| 140 | + Err(hound::Error::Unsupported) | ||
| 141 | + ), | ||
| 142 | + "8-bit samples in a 2-byte container must be refused" | ||
| 143 | + ); | ||
| 144 | + | ||
| 145 | + for bits in [12u16, 20] { | ||
| 146 | + let odd = wav_bytes(1, bits, bits.div_ceil(8), &[0; 8]); | ||
| 147 | + assert!( | ||
| 148 | + matches!( | ||
| 149 | + hound::WavReader::new(std::io::Cursor::new(odd)), | ||
| 150 | + Err(hound::Error::FormatError(_)) | ||
| 151 | + ), | ||
| 152 | + "{bits}-bit must be a FormatError" | ||
| 153 | + ); | ||
| 154 | + } | ||
| 155 | + | ||
| 156 | + // The well-formed shape of the same helper still opens, so the refusals | ||
| 157 | + // above are about the fields under test and not about the fixture. | ||
| 158 | + let ok = wav_bytes(2, 16, 4, &[0; 16]); | ||
| 159 | + let r = hound::WavReader::new(std::io::Cursor::new(ok)).expect("a packed 16-bit stereo header"); | ||
| 160 | + assert_eq!(r.spec().bits_per_sample, 16); | ||
| 161 | +} | ||
| 162 | + | ||
| 88 | #[test] | 163 | #[test] |
| 89 | fn errors_carry_the_incumbent_variants() { | 164 | fn errors_carry_the_incumbent_variants() { |
| 90 | let dir = std::path::Path::new(env!("CARGO_TARGET_TMPDIR")); | 165 | let dir = std::path::Path::new(env!("CARGO_TARGET_TMPDIR")); |