1 //! The wav container: RIFF/WAVE, PCM, 16-bit.2 //!3 //! A wav is the one audio container that every device can write without a4 //! codec. The decoder walks the chunk list because a phone adds `LIST` and5 //! `fact` beside the two chunks that matter. A chunk that it does not know is6 //! skipped rather than refused.7 8 use crate::AudioError;9 use crate::pcm::Pcm;10 11 /// The fixed part of a RIFF file before a chunk: `RIFF`, its size, and `WAVE`.12 const RIFF_HEADER_LEN: usize = 12;13 14 /// The RIFF size counts bytes after its own size field, so the listed body15 /// ends eight bytes into the file.16 const RIFF_SIZE_PREFIX: usize = 8;17 18 /// Every chunk starts with a four-byte name and a four-byte body size.19 const CHUNK_HEADER_LEN: usize = 8;20 21 /// The PCM `fmt ` body: tag, channels, rate, byte rate, block align, width.22 const FMT_BODY_LEN: usize = 16;23 24 /// A chunk body is word aligned, so an odd body carries one pad byte.25 const CHUNK_PAD_BYTE: usize = 1;26 27 /// Format tag 1 is uncompressed PCM.28 const PCM_TAG: u16 = 1;29 30 /// The only sample width that this container carries.31 const BITS_PER_SAMPLE: u16 = 16;32 33 /// A 16-bit sample is two bytes on the wire.34 const BYTES_PER_SAMPLE: usize = 2;35 36 /// The bytes before the data body: `WAVE`, the `fmt ` chunk, and the `data`37 /// header. The RIFF size is this plus the data body.38 const RIFF_SIZE_WITHOUT_DATA: u32 = 36;39 40 /// Encodes a block as a RIFF/WAVE file with one `fmt ` chunk and one `data`41 /// chunk. The caller writes the bytes; no sink is involved.42 pub fn encode(pcm: &Pcm) -> Vec<u8> {43 let channels = u16::from(pcm.channels);44 let block_align = channels * BYTES_PER_SAMPLE as u16;45 let byte_rate = pcm.rate * u32::from(channels) * BYTES_PER_SAMPLE as u32;46 let data_bytes = pcm.samples.len() * BYTES_PER_SAMPLE;47 // RIFF records a 32-bit length. A block that large cannot fit a wav.48 let data_len = u32::try_from(data_bytes).unwrap_or(u32::MAX);49 let riff_len = RIFF_SIZE_WITHOUT_DATA.saturating_add(data_len);50 51 let mut out =52 Vec::with_capacity(RIFF_HEADER_LEN + RIFF_SIZE_WITHOUT_DATA as usize + data_bytes);53 out.extend_from_slice(b"RIFF");54 out.extend_from_slice(&riff_len.to_le_bytes());55 out.extend_from_slice(b"WAVE");56 out.extend_from_slice(b"fmt ");57 out.extend_from_slice(&(FMT_BODY_LEN as u32).to_le_bytes());58 out.extend_from_slice(&PCM_TAG.to_le_bytes());59 out.extend_from_slice(&channels.to_le_bytes());60 out.extend_from_slice(&pcm.rate.to_le_bytes());61 out.extend_from_slice(&byte_rate.to_le_bytes());62 out.extend_from_slice(&block_align.to_le_bytes());63 out.extend_from_slice(&BITS_PER_SAMPLE.to_le_bytes());64 out.extend_from_slice(b"data");65 out.extend_from_slice(&data_len.to_le_bytes());66 for sample in &pcm.samples {67 out.extend_from_slice(&sample.to_le_bytes());68 }69 out70 }71 72 /// The fields of `fmt ` that the decoder needs.73 struct Fmt {74 channels: u8,75 rate: u32,76 }77 78 /// Decodes a RIFF/WAVE file. The chunk list may carry chunks that this tree79 /// does not use; the two that it needs are `fmt ` and `data`.80 pub fn decode(bytes: &[u8]) -> Result<Pcm, AudioError> {81 if bytes.len() < RIFF_HEADER_LEN {82 return Err(AudioError::Format("the file is shorter than a riff header"));83 }84 if &bytes[0..4] != b"RIFF" {85 return Err(AudioError::Format("the file does not start with RIFF"));86 }87 if &bytes[8..12] != b"WAVE" {88 return Err(AudioError::Format("the riff form is not WAVE"));89 }90 91 let riff_len = u32_at(bytes, 4).ok_or(AudioError::Format("the riff size is missing"))?;92 let riff_end = (riff_len as usize)93 .checked_add(RIFF_SIZE_PREFIX)94 .ok_or(AudioError::Format("the riff size overflows the file"))?;95 if riff_end > bytes.len() {96 return Err(AudioError::Format("the riff size is longer than the file"));97 }98 99 let mut offset = RIFF_HEADER_LEN;100 let mut fmt = None;101 let mut data = None;102 while offset < bytes.len() {103 if bytes.len() - offset < CHUNK_HEADER_LEN {104 return Err(AudioError::Format("a chunk header is cut short"));105 }106 let name = &bytes[offset..offset + 4];107 let body_len = u32_at(bytes, offset + 4)108 .ok_or(AudioError::Format("a chunk size is missing"))? as usize;109 let body_start = offset + CHUNK_HEADER_LEN;110 let body_end = body_start111 .checked_add(body_len)112 .filter(|end| *end <= bytes.len())113 .ok_or(AudioError::Format("a chunk body is longer than the file"))?;114 let body = &bytes[body_start..body_end];115 116 if name == b"fmt " {117 fmt = Some(parse_fmt(body)?);118 } else if name == b"data" {119 data = Some(body);120 }121 122 offset = body_end;123 if body_len % 2 == 1 {124 offset = offset125 .checked_add(CHUNK_PAD_BYTE)126 .filter(|end| *end <= bytes.len())127 .ok_or(AudioError::Format("a chunk pad is missing"))?;128 }129 }130 131 let fmt = fmt.ok_or(AudioError::Format("the file has no fmt chunk"))?;132 let data = data.ok_or(AudioError::Format("the file has no data chunk"))?;133 if data.len() % BYTES_PER_SAMPLE != 0 {134 return Err(AudioError::Format("the data body ends between samples"));135 }136 let samples = data137 .as_chunks::<BYTES_PER_SAMPLE>()138 .0139 .iter()140 .map(|pair| i16::from_le_bytes(*pair))141 .collect();142 Pcm::new(fmt.rate, fmt.channels, samples)143 }144 145 /// Reads the fields of a `fmt ` body that this container accepts.146 fn parse_fmt(body: &[u8]) -> Result<Fmt, AudioError> {147 if body.len() < FMT_BODY_LEN {148 return Err(AudioError::Format("the fmt chunk is shorter than 16 bytes"));149 }150 let tag = u16_at(body, 0).ok_or(AudioError::Format("the format tag is missing"))?;151 if tag != PCM_TAG {152 return Err(AudioError::Format("the format tag is not PCM"));153 }154 let channels = u16_at(body, 2).ok_or(AudioError::Format("the channel count is missing"))?;155 let channels = u8::try_from(channels).map_err(|_| AudioError::Channels)?;156 let rate = u32_at(body, 4).ok_or(AudioError::Format("the sample rate is missing"))?;157 let bits = u16_at(body, 14).ok_or(AudioError::Format("the sample width is missing"))?;158 if bits != BITS_PER_SAMPLE {159 return Err(AudioError::Format("the sample width is not 16 bits"));160 }161 Ok(Fmt { channels, rate })162 }163 164 /// Reads a little-endian u16 at `at`, when the bytes hold one.165 fn u16_at(bytes: &[u8], at: usize) -> Option<u16> {166 let end = at.checked_add(2)?;167 let slice = bytes.get(at..end)?;168 Some(u16::from_le_bytes([slice[0], slice[1]]))169 }170 171 /// Reads a little-endian u32 at `at`, when the bytes hold one.172 fn u32_at(bytes: &[u8], at: usize) -> Option<u32> {173 let end = at.checked_add(4)?;174 let slice = bytes.get(at..end)?;175 Some(u32::from_le_bytes([slice[0], slice[1], slice[2], slice[3]]))176 }