| 1 | |
| 2 | |
| 3 | use std::fs::File; |
| 4 | use std::io::{BufReader, Read}; |
| 5 | use std::path::Path; |
| 6 | |
| 7 | use ec_core::{Error, Result}; |
| 8 | |
| 9 | use crate::{FORMAT_EXTENSIBLE, FORMAT_FLOAT, FORMAT_PCM, SampleType, WavSpec}; |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | pub struct WavReader<R: Read> { |
| 17 | inner: R, |
| 18 | spec: WavSpec, |
| 19 | |
| 20 | |
| 21 | data_bytes: Option<u64>, |
| 22 | } |
| 23 | |
| 24 | impl WavReader<BufReader<File>> { |
| 25 | |
| 26 | pub fn open<P: AsRef<Path>>(path: P) -> Result<Self> { |
| 27 | WavReader::new(BufReader::new(File::open(path)?)) |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | impl<R: Read> WavReader<R> { |
| 32 | |
| 33 | pub fn new(mut inner: R) -> Result<Self> { |
| 34 | let riff = read_exact::<12, _>(&mut inner)?; |
| 35 | if &riff[0..4] != b"RIFF" || &riff[8..12] != b"WAVE" { |
| 36 | if &riff[0..4] == b"RF64" { |
| 37 | return Err(Error::unsupported( |
| 38 | "an RF64/BW64 file", |
| 39 | "the 64-bit RIFF extension is not implemented", |
| 40 | )); |
| 41 | } |
| 42 | return Err(Error::corrupt("not a RIFF/WAVE file")); |
| 43 | } |
| 44 | |
| 45 | let mut spec = None; |
| 46 | loop { |
| 47 | let head = read_exact::<8, _>(&mut inner)?; |
| 48 | let id = [head[0], head[1], head[2], head[3]]; |
| 49 | let size = u32::from_le_bytes([head[4], head[5], head[6], head[7]]) as u64; |
| 50 | match &id { |
| 51 | b"fmt " => spec = Some(parse_fmt(&mut inner, size)?), |
| 52 | b"data" => { |
| 53 | let spec = spec.ok_or_else(|| { |
| 54 | Error::corrupt("WAVE data chunk arrived before any fmt chunk") |
| 55 | })?; |
| 56 | |
| 57 | |
| 58 | let data_bytes = (size != 0 && size != u64::from(u32::MAX)).then_some(size); |
| 59 | return Ok(WavReader { |
| 60 | inner, |
| 61 | spec, |
| 62 | data_bytes, |
| 63 | }); |
| 64 | } |
| 65 | _ => skip(&mut inner, size + size % 2)?, |
| 66 | } |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | |
| 71 | pub fn spec(&self) -> WavSpec { |
| 72 | self.spec |
| 73 | } |
| 74 | |
| 75 | |
| 76 | |
| 77 | pub fn duration(&self) -> Option<u64> { |
| 78 | self.data_bytes.map(|b| b / self.spec.block_align() as u64) |
| 79 | } |
| 80 | |
| 81 | |
| 82 | |
| 83 | fn read_data(&mut self) -> Result<Vec<u8>> { |
| 84 | let mut buf = Vec::new(); |
| 85 | match self.data_bytes { |
| 86 | Some(n) => { |
| 87 | |
| 88 | |
| 89 | (&mut self.inner).take(n).read_to_end(&mut buf)?; |
| 90 | } |
| 91 | None => { |
| 92 | self.inner.read_to_end(&mut buf)?; |
| 93 | } |
| 94 | } |
| 95 | let align = self.spec.block_align(); |
| 96 | buf.truncate(buf.len() / align * align); |
| 97 | Ok(buf) |
| 98 | } |
| 99 | |
| 100 | |
| 101 | |
| 102 | |
| 103 | pub fn read_all_i32(&mut self) -> Result<Vec<i32>> { |
| 104 | if self.spec.sample_format == SampleType::Float { |
| 105 | return Err(Error::unsupported( |
| 106 | "reading a float WAVE file as integers", |
| 107 | "use read_all_f32; the scale factor is the caller's decision", |
| 108 | )); |
| 109 | } |
| 110 | let bits = self.spec.bits_per_sample; |
| 111 | let width = self.spec.bytes_per_sample(); |
| 112 | let buf = self.read_data()?; |
| 113 | Ok(buf |
| 114 | .chunks_exact(width) |
| 115 | .map(|c| match bits { |
| 116 | |
| 117 | 8 => i32::from(c[0]) - 128, |
| 118 | 16 => i32::from(i16::from_le_bytes([c[0], c[1]])), |
| 119 | 24 => i32::from_le_bytes([0, c[0], c[1], c[2]]) >> 8, |
| 120 | _ => i32::from_le_bytes([c[0], c[1], c[2], c[3]]), |
| 121 | }) |
| 122 | .collect()) |
| 123 | } |
| 124 | |
| 125 | |
| 126 | |
| 127 | |
| 128 | |
| 129 | |
| 130 | pub fn read_all_f32(&mut self) -> Result<Vec<f32>> { |
| 131 | if self.spec.sample_format == SampleType::Float { |
| 132 | let buf = self.read_data()?; |
| 133 | return Ok(buf |
| 134 | .chunks_exact(4) |
| 135 | .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])) |
| 136 | .collect()); |
| 137 | } |
| 138 | let scale = 1.0f32 / (1i64 << (self.spec.bits_per_sample - 1)) as f32; |
| 139 | Ok(self |
| 140 | .read_all_i32()? |
| 141 | .into_iter() |
| 142 | .map(|v| v as f32 * scale) |
| 143 | .collect()) |
| 144 | } |
| 145 | } |
| 146 | |
| 147 | |
| 148 | fn read_exact<const N: usize, R: Read>(r: &mut R) -> Result<[u8; N]> { |
| 149 | let mut buf = [0u8; N]; |
| 150 | r.read_exact(&mut buf).map_err(|e| { |
| 151 | if e.kind() == std::io::ErrorKind::UnexpectedEof { |
| 152 | Error::corrupt("WAVE header ends mid-chunk") |
| 153 | } else { |
| 154 | Error::Io(e) |
| 155 | } |
| 156 | })?; |
| 157 | Ok(buf) |
| 158 | } |
| 159 | |
| 160 | |
| 161 | fn skip<R: Read>(r: &mut R, n: u64) -> Result<()> { |
| 162 | let copied = std::io::copy(&mut r.take(n), &mut std::io::sink())?; |
| 163 | if copied != n { |
| 164 | return Err(Error::corrupt("WAVE chunk ends past the end of the file")); |
| 165 | } |
| 166 | Ok(()) |
| 167 | } |
| 168 | |
| 169 | |
| 170 | fn parse_fmt<R: Read>(r: &mut R, size: u64) -> Result<WavSpec> { |
| 171 | if size < 16 { |
| 172 | return Err(Error::corrupt(format!("WAVE fmt chunk is {size} bytes"))); |
| 173 | } |
| 174 | let f = read_exact::<16, _>(r)?; |
| 175 | let mut tag = u16::from_le_bytes([f[0], f[1]]); |
| 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]]); |
| 178 | let block_align = u16::from_le_bytes([f[12], f[13]]); |
| 179 | let bits_per_sample = u16::from_le_bytes([f[14], f[15]]); |
| 180 | let mut rest = size - 16; |
| 181 | |
| 182 | if tag == FORMAT_EXTENSIBLE { |
| 183 | if rest < 24 { |
| 184 | return Err(Error::corrupt( |
| 185 | "WAVE_FORMAT_EXTENSIBLE fmt chunk without its 22-byte extension", |
| 186 | )); |
| 187 | } |
| 188 | let ext = read_exact::<24, _>(r)?; |
| 189 | rest -= 24; |
| 190 | |
| 191 | |
| 192 | |
| 193 | tag = u16::from_le_bytes([ext[8], ext[9]]); |
| 194 | } |
| 195 | skip(r, rest + size % 2)?; |
| 196 | |
| 197 | let sample_format = match tag { |
| 198 | FORMAT_PCM => SampleType::Int, |
| 199 | FORMAT_FLOAT => SampleType::Float, |
| 200 | other => { |
| 201 | return Err(Error::unsupported( |
| 202 | format!("WAVE format tag {other:#06x}"), |
| 203 | "ec-riff carries integer and IEEE-float PCM only", |
| 204 | )); |
| 205 | } |
| 206 | }; |
| 207 | |
| 208 | |
| 209 | |
| 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 | } |
| 215 | let spec = WavSpec { |
| 216 | channels, |
| 217 | sample_rate, |
| 218 | bits_per_sample, |
| 219 | sample_format, |
| 220 | }; |
| 221 | spec.validate()?; |
| 222 | |
| 223 | |
| 224 | |
| 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 | } |
| 231 | Ok(spec) |
| 232 | } |