Skip to main content

decibri_decode/
wav.rs

1//! RIFF/WAVE and RF64: the first container this crate reads, and the first
2//! bytes it parses that it did not produce.
3//!
4//! # Dispatch is on content, and on the pair
5//!
6//! `wFormatTag` alone does not say what the payload is. Tag 1 is "integer PCM"
7//! at 8, 16, 24 or 32 bits, and reading a 24-bit file as 16-bit produces
8//! plausible-looking noise at the wrong stride rather than an error. So every
9//! decision here is on the **`(tag, bits)` pair**, in [`WavCodec::resolve`],
10//! and never on the tag alone.
11//!
12//! Nothing in this crate looks at a file name. A `.wav` extension is a claim
13//! made by whoever renamed the file; the first four bytes are a claim made by
14//! whoever wrote it, and only the second one is checkable.
15//!
16//! # The two defects this reader was written not to repeat
17//!
18//! Both were measured in decibri's own `parse_wav` during an earlier pass and
19//! left in place there under a read-only rule.
20//!
21//! **A partial trailing frame is an error, not a rounding.** decibri's reader
22//! hands its `data` payload to a `chunks_exact` conversion and never compares
23//! the payload length against the frame size, so a `data` chunk holding two and
24//! a half stereo frames decodes as two and the half frame disappears. Silent
25//! truncation of audio is the failure class this crate exists to avoid.
26//! [`WavReader::new`] rejects it with [`DecodeError::Truncated`].
27//!
28//! **Size arithmetic is checked and 64-bit.** decibri's reader computes
29//! `body + size > bytes.len()` in `usize` (`crates/decibri/src/file.rs:880`).
30//! On a 32-bit target that sum wraps for a crafted chunk size, the range check
31//! passes, and the slice that follows panics. Everything here is `u64` and
32//! compares `size > available`, which cannot wrap on any target; see
33//! [`riff`](crate::riff).
34//!
35//! # A size in a file is a claim, not a fact
36//!
37//! No allocation anywhere in this module is proportional to a number the file
38//! declared. A `data` chunk announcing four gigabytes inside a two-kilobyte
39//! file is rejected by the chunk walk before a byte is reserved, and the
40//! whole-file decode reserves from the payload slice's real length. The
41//! streaming reader buffers only chunk headers and the two chunk bodies it has
42//! to read (`fmt ` and `ds64`), both of which are capped at a size the format
43//! itself bounds.
44//!
45//! # RF64
46//!
47//! RIFF's 32-bit size fields stop at four gigabytes, which is about six and a
48//! half hours of 16-bit stereo at 44.1 kHz. RF64 (EBU Tech 3306) keeps RIFF's
49//! structure and moves the oversized numbers into a `ds64` chunk, leaving
50//! `0xFFFFFFFF` behind in the fields it replaced. Both reading and writing are
51//! supported here.
52//!
53//! # Two readers, and why they differ
54//!
55//! [`WavReader`] holds the whole file and can therefore accept the chunks in
56//! any order, `data` before `fmt ` included. [`WavStreamDecoder`] cannot: a
57//! payload that arrives before the header describing it would have to be
58//! buffered in full to be decoded later, and buffering an unbounded payload is
59//! the thing this module refuses to do. So the streaming reader requires
60//! `fmt ` first and says so with a typed error when it does not get it. That is
61//! the one behavioural difference between the two paths, and it is a property
62//! of streaming rather than a shortcut.
63
64use crate::audio::{AudioBuffer, AudioSpec};
65use crate::codec::{CodecId, FourCc};
66use crate::error::DecodeError;
67use crate::g711::G711Law;
68use crate::payload::Payload;
69use crate::riff::{self, ChunkWalker};
70use crate::sample::SampleFormat;
71use crate::source::StreamSource;
72
73/// `WAVE_FORMAT_PCM`.
74const TAG_PCM: u16 = 1;
75/// `WAVE_FORMAT_IEEE_FLOAT`.
76const TAG_FLOAT: u16 = 3;
77/// `WAVE_FORMAT_ALAW`.
78const TAG_ALAW: u16 = 6;
79/// `WAVE_FORMAT_MULAW`.
80const TAG_MULAW: u16 = 7;
81/// `WAVE_FORMAT_EXTENSIBLE`: the real format is in the SubFormat GUID.
82const TAG_EXTENSIBLE: u16 = 0xFFFE;
83
84/// The fourteen bytes every `KSDATAFORMAT_SUBTYPE_*` GUID ends with.
85///
86/// The GUIDs Microsoft assigned to the `WAVEFORMATEX` tags are the tag itself
87/// in the first little-endian word followed by this fixed tail, so
88/// `KSDATAFORMAT_SUBTYPE_PCM` is `00000001-0000-0010-8000-00aa00389b71`. A GUID
89/// carrying this tail names a `wFormatTag`; a GUID that does not is a format
90/// with no tag at all, and is reported as the GUID it was.
91const SUBFORMAT_TAIL: [u8; 14] = [
92    0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71,
93];
94
95/// The smallest `fmt ` chunk `WAVEFORMATEX` defines.
96const FMT_BYTES_PLAIN: u64 = 16;
97
98/// The `fmt ` chunk a `WAVE_FORMAT_EXTENSIBLE` file carries: the sixteen fixed
99/// bytes, `cbSize`, and the twenty-two-byte extension it counts.
100const FMT_BYTES_EXTENSIBLE: u64 = 40;
101
102/// The largest `fmt ` chunk `WAVEFORMATEX` can describe.
103///
104/// The sixteen fixed bytes, the `cbSize` field, and the extension `cbSize`
105/// counts, and `cbSize` is a `u16`, so 65,553 bytes is the format's own
106/// ceiling rather than a number picked here. It matters because `fmt ` is one
107/// of the two chunk bodies the streaming reader buffers instead of skipping.
108const MAX_FMT_BYTES: u64 = 18 + u16::MAX as u64;
109
110/// The `ds64` body this crate writes: sixteen bytes of sizes, eight of sample
111/// count, four of table length, and no table.
112const DS64_BODY_BYTES: u64 = 28;
113
114/// How many decoded samples the streaming reader holds before it stops taking
115/// bytes.
116///
117/// The same figure [`PcmDecoder`](crate::PcmDecoder) and
118/// [`G711Decoder`](crate::G711Decoder) hold, for the same
119/// reason: a caller handing over a whole file in one call gets back-pressure
120/// and a bounded reader rather than a buffer the size of the file.
121const READY_LIMIT: usize = 65_536;
122
123// -- What a WAV file can carry ------------------------------------------------
124
125/// An encoding a WAV file can carry and this crate can decode.
126///
127/// Deliberately not "a [`SampleFormat`] plus a law". WAV is little-endian and
128/// carries six of the twelve `SampleFormat`s, so a type parameterised on
129/// `SampleFormat` would be able to name `I16Be`, a file that cannot exist,
130/// and every function taking one would need a failure case for it. The eight
131/// variants here are exactly the eight `(wFormatTag, wBitsPerSample)` pairs
132/// this crate reads and writes, so [`format_tag`](Self::format_tag),
133/// [`bits_per_sample`](Self::bits_per_sample) and the writer are total.
134///
135/// `#[non_exhaustive]`: a consumer matching on it needs a `_` arm.
136#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
137#[non_exhaustive]
138pub enum WavCodec {
139    /// Unsigned 8-bit PCM, offset by 128. `wFormatTag` 1, 8 bits.
140    PcmU8,
141    /// Signed 16-bit little-endian PCM. `wFormatTag` 1, 16 bits.
142    PcmI16,
143    /// Signed 24-bit little-endian PCM, packed into three bytes.
144    /// `wFormatTag` 1, 24 bits.
145    PcmI24,
146    /// Signed 32-bit little-endian PCM. `wFormatTag` 1, 32 bits.
147    PcmI32,
148    /// IEEE 754 binary32, little-endian. `wFormatTag` 3, 32 bits.
149    Float32,
150    /// IEEE 754 binary64, little-endian. `wFormatTag` 3, 64 bits.
151    Float64,
152    /// ITU-T G.711 A-law. `wFormatTag` 6, 8 bits.
153    ALaw,
154    /// ITU-T G.711 mu-law. `wFormatTag` 7, 8 bits.
155    MuLaw,
156}
157
158impl WavCodec {
159    /// The encoding a `(wFormatTag, wBitsPerSample)` pair names.
160    ///
161    /// **On the pair, never on the tag.** Tag 1 covers four widths and tag 3
162    /// covers two; a reader that dispatched on the tag alone would decode a
163    /// 24-bit file at a 16-bit stride and produce noise rather than an error.
164    /// The step-0 audit found decibri already doing this correctly and named it
165    /// the thing most implementations get wrong.
166    ///
167    /// ```
168    /// use decibri_decode::WavCodec;
169    ///
170    /// assert_eq!(WavCodec::resolve(1, 24).unwrap(), WavCodec::PcmI24);
171    /// assert_eq!(WavCodec::resolve(7, 8).unwrap(), WavCodec::MuLaw);
172    /// // Same tag, unsupported width: rejected, and the rejection says which.
173    /// assert!(WavCodec::resolve(1, 20).is_err());
174    /// ```
175    ///
176    /// # Errors
177    ///
178    /// [`DecodeError::UnsupportedSampleFormat`] for a tag this crate carries at
179    /// a width it does not, and [`DecodeError::UnsupportedCodec`] for a tag it
180    /// does not carry at all. The two are separate because they tell a caller
181    /// different things: the first says the file is PCM and this build cannot
182    /// read that width, the second says the file is not PCM.
183    pub fn resolve(tag: u16, bits_per_sample: u16) -> Result<Self, DecodeError> {
184        match (tag, bits_per_sample) {
185            (TAG_PCM, 8) => Ok(Self::PcmU8),
186            (TAG_PCM, 16) => Ok(Self::PcmI16),
187            (TAG_PCM, 24) => Ok(Self::PcmI24),
188            (TAG_PCM, 32) => Ok(Self::PcmI32),
189            (TAG_FLOAT, 32) => Ok(Self::Float32),
190            (TAG_FLOAT, 64) => Ok(Self::Float64),
191            (TAG_ALAW, 8) => Ok(Self::ALaw),
192            (TAG_MULAW, 8) => Ok(Self::MuLaw),
193            (TAG_PCM | TAG_FLOAT | TAG_ALAW | TAG_MULAW, _) => {
194                Err(DecodeError::UnsupportedSampleFormat {
195                    format: CodecId::WaveFormatTag(tag),
196                    bits_per_sample,
197                })
198            }
199            _ => Err(DecodeError::UnsupportedCodec {
200                codec: CodecId::WaveFormatTag(tag),
201            }),
202        }
203    }
204
205    /// The `wFormatTag` a file carrying this encoding declares.
206    ///
207    /// Total: every variant is one a WAV file can name and this crate can
208    /// write.
209    pub const fn format_tag(self) -> u16 {
210        match self {
211            Self::PcmU8 | Self::PcmI16 | Self::PcmI24 | Self::PcmI32 => TAG_PCM,
212            Self::Float32 | Self::Float64 => TAG_FLOAT,
213            Self::ALaw => TAG_ALAW,
214            Self::MuLaw => TAG_MULAW,
215        }
216    }
217
218    /// The `wBitsPerSample` a file carrying this encoding declares.
219    pub const fn bits_per_sample(self) -> u16 {
220        match self {
221            Self::PcmU8 | Self::ALaw | Self::MuLaw => 8,
222            Self::PcmI16 => 16,
223            Self::PcmI24 => 24,
224            Self::PcmI32 | Self::Float32 => 32,
225            Self::Float64 => 64,
226        }
227    }
228
229    /// How many bytes one sample occupies in the payload.
230    pub const fn bytes_per_sample(self) -> usize {
231        match self {
232            Self::PcmU8 | Self::ALaw | Self::MuLaw => 1,
233            Self::PcmI16 => 2,
234            Self::PcmI24 => 3,
235            Self::PcmI32 | Self::Float32 => 4,
236            Self::Float64 => 8,
237        }
238    }
239
240    /// The linear PCM format this encoding is, or `None` for the companded
241    /// ones.
242    pub const fn sample_format(self) -> Option<SampleFormat> {
243        match self {
244            Self::PcmU8 => Some(SampleFormat::U8),
245            Self::PcmI16 => Some(SampleFormat::I16Le),
246            Self::PcmI24 => Some(SampleFormat::I24Le),
247            Self::PcmI32 => Some(SampleFormat::I32Le),
248            Self::Float32 => Some(SampleFormat::F32Le),
249            Self::Float64 => Some(SampleFormat::F64Le),
250            Self::ALaw | Self::MuLaw => None,
251        }
252    }
253
254    /// The G.711 companding law this encoding is, or `None` for the linear
255    /// ones.
256    pub const fn law(self) -> Option<G711Law> {
257        match self {
258            Self::ALaw => Some(G711Law::ALaw),
259            Self::MuLaw => Some(G711Law::MuLaw),
260            _ => None,
261        }
262    }
263
264    /// Appends every whole sample in `bytes` to `output`, and returns how many
265    /// it appended.
266    ///
267    /// Straight through to [`SampleFormat::decode`] or [`G711Law::decode`]:
268    /// there is no WAV-specific conversion anywhere in this crate, so a file
269    /// decoded through the container and a headerless stream decoded through
270    /// [`PcmDecoder`](crate::PcmDecoder) give the same samples by construction rather than by
271    /// agreement.
272    pub fn decode(self, bytes: &[u8], output: &mut Vec<f32>) -> usize {
273        match (self.sample_format(), self.law()) {
274            (Some(format), _) => format.decode(bytes, output),
275            (_, Some(law)) => law.decode(bytes, output),
276            // Unreachable: every variant is one or the other, and the match in
277            // `sample_format` and `law` is exhaustive over the enum.
278            _ => 0,
279        }
280    }
281
282    /// Appends `samples` to `output` in this encoding, and returns how many
283    /// bytes it appended.
284    pub fn encode(self, samples: &[f32], output: &mut Vec<u8>) -> usize {
285        match (self.sample_format(), self.law()) {
286            (Some(format), _) => format.encode(samples, output),
287            (_, Some(law)) => law.encode(samples, output),
288            _ => 0,
289        }
290    }
291}
292
293/// A resolved `fmt ` chunk: what the file declared, and what it resolved to.
294///
295/// The declared fields are kept beside the resolution rather than discarded,
296/// because a caller reporting on a file wants what the file said and a caller
297/// decoding it wants what that means.
298#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
299#[non_exhaustive]
300pub struct WavFormat {
301    /// The rate and layout the payload decodes to.
302    pub spec: AudioSpec,
303    /// What the payload is encoded as, from the `(tag, bits)` pair.
304    pub codec: WavCodec,
305    /// `wFormatTag` exactly as the file declared it: `0xFFFE` for an
306    /// extensible header, whatever its SubFormat GUID resolved to.
307    pub format_tag: u16,
308    /// `wBitsPerSample` as declared.
309    pub bits_per_sample: u16,
310    /// `nBlockAlign` as declared, in bytes per frame.
311    ///
312    /// **Advisory.** The frame size this crate decodes at comes from the
313    /// resolved codec and the channel count, never from this field. Writers
314    /// that get it wrong are common, and a file whose audio is perfectly
315    /// decodable is not worth rejecting over a redundant field; a file whose
316    /// `nBlockAlign` disagrees with `nChannels * wBitsPerSample / 8` still
317    /// decodes, and the disagreement is visible here to anyone who wants it.
318    pub block_align: u16,
319    /// `nAvgBytesPerSec` as declared, in bytes per second. Advisory, as
320    /// [`block_align`](Self::block_align) is.
321    pub byte_rate: u32,
322}
323
324impl WavFormat {
325    /// How many bytes one whole frame occupies in the payload.
326    ///
327    /// At least one: the channel count is rejected at zero, so this never
328    /// divides by nothing.
329    pub const fn frame_bytes(&self) -> usize {
330        self.spec.channels as usize * self.codec.bytes_per_sample()
331    }
332
333    /// `true` when the file declared `WAVE_FORMAT_EXTENSIBLE`.
334    pub const fn is_extensible(&self) -> bool {
335        self.format_tag == TAG_EXTENSIBLE
336    }
337}
338
339// -- Reading the `fmt ` chunk -------------------------------------------------
340
341/// Rejects a `fmt ` chunk whose declared size the format cannot mean.
342///
343/// Called on both paths with the same number so the whole-file and streaming
344/// readers agree: on the whole-file path the body is already bounded by the
345/// input, and on the streaming path this is what bounds the buffer.
346fn check_fmt_size(size: u64, offset: u64) -> Result<(), DecodeError> {
347    if size < FMT_BYTES_PLAIN {
348        return Err(DecodeError::Malformed {
349            expected: "a fmt chunk of at least 16 bytes",
350            offset,
351        });
352    }
353    if size > MAX_FMT_BYTES {
354        return Err(DecodeError::Malformed {
355            expected: "a fmt chunk of at most 65553 bytes, which is all cbSize can count",
356            offset,
357        });
358    }
359    Ok(())
360}
361
362/// A GUID in the text form Microsoft writes it in, for a rejection to name.
363///
364/// The first three groups are little-endian and the last two are byte order as
365/// stored, which is why the rendering is written out rather than done with a
366/// hex formatter over the sixteen bytes.
367fn format_guid(guid: &[u8; 16]) -> String {
368    const HEX: [u8; 16] = *b"0123456789abcdef";
369    let data1 = u32::from_le_bytes([guid[0], guid[1], guid[2], guid[3]]);
370    let data2 = u16::from_le_bytes([guid[4], guid[5]]);
371    let data3 = u16::from_le_bytes([guid[6], guid[7]]);
372    let mut text = format!("{data1:08x}-{data2:04x}-{data3:04x}-");
373    for (index, byte) in guid[8..].iter().enumerate() {
374        if index == 2 {
375            text.push('-');
376        }
377        text.push(HEX[usize::from(byte >> 4)] as char);
378        text.push(HEX[usize::from(byte & 0x0F)] as char);
379    }
380    text
381}
382
383/// Reads a `fmt ` chunk body that has already been checked with
384/// [`check_fmt_size`].
385///
386/// `offset` is where the chunk *header* sits in the input, so the offsets in
387/// any [`DecodeError::Malformed`] this returns are absolute.
388fn parse_fmt(body: &[u8], offset: u64) -> Result<WavFormat, DecodeError> {
389    let body_at = offset + riff::CHUNK_HEADER_BYTES;
390    let (
391        Some(declared_tag),
392        Some(channels),
393        Some(sample_rate),
394        Some(byte_rate),
395        Some(block_align),
396        Some(bits_per_sample),
397    ) = (
398        riff::u16_at(body, 0),
399        riff::u16_at(body, 2),
400        riff::u32_at(body, 4),
401        riff::u32_at(body, 8),
402        riff::u16_at(body, 12),
403        riff::u16_at(body, 14),
404    )
405    else {
406        return Err(DecodeError::Malformed {
407            expected: "a fmt chunk of at least 16 bytes",
408            offset,
409        });
410    };
411
412    if channels == 0 {
413        return Err(DecodeError::UnsupportedChannelLayout { channels });
414    }
415    if sample_rate == 0 {
416        // No `UnsupportedSampleRate` variant exists and `DecodeError` is
417        // closed, so this is a structural rejection: a rate of zero is not a
418        // rate this file could have meant.
419        return Err(DecodeError::Malformed {
420            expected: "a non-zero sample rate",
421            offset: body_at + 4,
422        });
423    }
424
425    // WAVE_FORMAT_EXTENSIBLE names the real encoding in a GUID, and the tag
426    // only says to go and look.
427    let tag = if declared_tag == TAG_EXTENSIBLE {
428        resolve_subformat(body, body_at)?
429    } else {
430        declared_tag
431    };
432
433    Ok(WavFormat {
434        spec: AudioSpec::new(sample_rate, channels),
435        codec: WavCodec::resolve(tag, bits_per_sample)?,
436        format_tag: declared_tag,
437        bits_per_sample,
438        block_align,
439        byte_rate,
440    })
441}
442
443/// The `wFormatTag` a `WAVE_FORMAT_EXTENSIBLE` header's SubFormat GUID names.
444///
445/// The extension has to be there and has to be big enough: `cbSize` under 22,
446/// or a body without room for the twenty-two bytes it counts, is a header that
447/// says "the format is in the extension" and then does not carry one.
448fn resolve_subformat(body: &[u8], body_at: u64) -> Result<u16, DecodeError> {
449    const MIN_EXTENSION: u16 = 22;
450    let inconsistent = DecodeError::Malformed {
451        expected: "a 22-byte WAVE_FORMAT_EXTENSIBLE extension after cbSize",
452        offset: body_at + 16,
453    };
454    let Some(cb_size) = riff::u16_at(body, 16) else {
455        return Err(inconsistent);
456    };
457    if cb_size < MIN_EXTENSION {
458        return Err(inconsistent);
459    }
460    let Some(guid) = body.get(24..40) else {
461        return Err(inconsistent);
462    };
463    let mut bytes = [0u8; 16];
464    bytes.copy_from_slice(guid);
465    if bytes[2..] == SUBFORMAT_TAIL {
466        Ok(u16::from_le_bytes([bytes[0], bytes[1]]))
467    } else {
468        // A GUID outside the `WAVEFORMATEX` family names a codec that has no
469        // tag at all, so the rejection carries the GUID rather than inventing
470        // a number for it.
471        Err(DecodeError::UnsupportedCodec {
472            codec: CodecId::Name(format_guid(&bytes)),
473        })
474    }
475}
476
477/// Rejects a `data` chunk whose length is not a whole number of frames.
478///
479/// The first of the two decibri defects this reader exists not to repeat.
480/// `chunks_exact` drops the remainder silently, so a payload of two and a half
481/// stereo frames decodes as two frames and the caller is never told.
482fn check_whole_frames(data_len: u64, frame_bytes: usize) -> Result<(), DecodeError> {
483    let remainder = data_len % frame_bytes as u64;
484    if remainder != 0 {
485        return Err(DecodeError::Truncated {
486            expected: frame_bytes as u64,
487            available: remainder,
488        });
489    }
490    Ok(())
491}
492
493// -- The whole-file reader ----------------------------------------------------
494
495/// A WAV file held whole in memory.
496///
497/// [`new`](Self::new) does all the parsing and all the rejecting; a reader that
498/// exists is a file that has been fully validated, which is why
499/// [`decode_to_end`](Self::decode_to_end) returns an [`AudioBuffer`] rather
500/// than a `Result`. That is a property of the two payload encodings this crate
501/// carries (linear PCM and G.711 both decode every byte sequence to a sample)
502/// and is stated here rather than assumed: a codec that can fail part-way
503/// through its payload does not go behind this API.
504///
505/// # Example
506///
507/// ```
508/// use decibri_decode::{AudioSpec, WavCodec, WavReader, WavWriter};
509///
510/// let bytes = WavWriter::new(AudioSpec::new(8_000, 2), WavCodec::MuLaw)
511///     .to_bytes(&[0.0, 0.5, -0.5, 0.25])?;
512///
513/// let reader = WavReader::new(&bytes)?;
514/// assert_eq!(reader.format().codec, WavCodec::MuLaw);
515/// assert_eq!(reader.spec(), AudioSpec::new(8_000, 2));
516/// assert_eq!(reader.frames(), 2);
517/// assert_eq!(reader.decode_to_end().samples().len(), 4);
518/// # Ok::<(), decibri_decode::DecodeError>(())
519/// ```
520#[derive(Debug, Clone, Copy, PartialEq)]
521pub struct WavReader<'a> {
522    format: WavFormat,
523    data: &'a [u8],
524    rf64: bool,
525}
526
527impl<'a> WavReader<'a> {
528    /// Parses `bytes` as a RIFF/WAVE or RF64 file.
529    ///
530    /// Chunks may arrive in any order and unknown chunks anywhere are skipped,
531    /// including between `fmt ` and `data`. The walk stops once both have been
532    /// found, so trailing chunks are not examined and a file with junk after
533    /// its audio still reads.
534    ///
535    /// **"Any order" includes `data` before `fmt `, which
536    /// [`WavStreamDecoder`] cannot accept.** A file that opens here can
537    /// therefore fail when streamed. That difference is forced, not chosen: a
538    /// streaming reader meeting the payload before the header describing it
539    /// would have to buffer the whole payload to decode it later, and an
540    /// unbounded buffer is the thing the streaming reader exists to avoid.
541    /// This reader holds the whole file already, so it has nothing to buffer
542    /// and accepts either order.
543    ///
544    /// # Errors
545    ///
546    /// - [`DecodeError::Truncated`] for an input under twelve bytes, a chunk
547    ///   declaring more than the input holds, and a `data` chunk whose length
548    ///   is not a whole number of frames.
549    /// - [`DecodeError::UnsupportedContainer`] for a magic that is neither
550    ///   `RIFF` nor `RF64`, and for a form type other than `WAVE`.
551    /// - [`DecodeError::Malformed`] for a missing or structurally wrong
552    ///   `fmt `, a missing `data`, a zero sample rate, and an inconsistent
553    ///   `WAVE_FORMAT_EXTENSIBLE` extension.
554    /// - [`DecodeError::UnsupportedChannelLayout`] for a zero channel count.
555    /// - [`DecodeError::UnsupportedCodec`] and
556    ///   [`DecodeError::UnsupportedSampleFormat`] from
557    ///   [`WavCodec::resolve`].
558    pub fn new(bytes: &'a [u8]) -> Result<Self, DecodeError> {
559        let header = riff::read_riff_header(bytes)?;
560        if header.form != riff::WAVE {
561            return Err(DecodeError::UnsupportedContainer { tag: header.form });
562        }
563
564        let mut walker = ChunkWalker::new(bytes, riff::ByteOrder::Little);
565        let rf64 = header.magic == riff::RF64;
566        if rf64 {
567            // EBU Tech 3306 puts `ds64` immediately after the form type, and it
568            // has to be there: every oversized field in the file is a sentinel
569            // pointing at it.
570            let Some(first) = walker.next().transpose()? else {
571                return Err(DecodeError::Truncated {
572                    expected: riff::HEADER_BYTES + riff::CHUNK_HEADER_BYTES,
573                    available: bytes.len() as u64,
574                });
575            };
576            if first.id != riff::DS64 {
577                return Err(DecodeError::Malformed {
578                    expected: "a ds64 chunk immediately after the RF64 form type",
579                    offset: first.offset,
580                });
581            }
582            if first.body.len() as u64 > riff::MAX_DS64_BYTES {
583                return Err(DecodeError::Malformed {
584                    expected: "a ds64 chunk of at most 65536 bytes",
585                    offset: first.offset,
586                });
587            }
588            walker.set_overrides(riff::parse_ds64(first.body, first.offset)?);
589        }
590
591        let mut format: Option<WavFormat> = None;
592        let mut data: Option<&[u8]> = None;
593        while format.is_none() || data.is_none() {
594            let Some(chunk) = walker.next().transpose()? else {
595                break;
596            };
597            if chunk.id == riff::FMT && format.is_none() {
598                check_fmt_size(chunk.body.len() as u64, chunk.offset)?;
599                format = Some(parse_fmt(chunk.body, chunk.offset)?);
600            } else if chunk.id == riff::DATA && data.is_none() {
601                data = Some(chunk.body);
602            }
603        }
604
605        let Some(format) = format else {
606            return Err(DecodeError::Malformed {
607                expected: "a fmt chunk",
608                offset: riff::HEADER_BYTES,
609            });
610        };
611        let Some(data) = data else {
612            return Err(DecodeError::Malformed {
613                expected: "a data chunk",
614                offset: riff::HEADER_BYTES,
615            });
616        };
617        check_whole_frames(data.len() as u64, format.frame_bytes())?;
618
619        Ok(Self { format, data, rf64 })
620    }
621
622    /// What the `fmt ` chunk declared and resolved to.
623    pub const fn format(&self) -> &WavFormat {
624        &self.format
625    }
626
627    /// The rate and layout the payload decodes to.
628    pub const fn spec(&self) -> AudioSpec {
629        self.format.spec
630    }
631
632    /// The `data` payload, undecoded.
633    pub const fn data(&self) -> &'a [u8] {
634        self.data
635    }
636
637    /// How many whole frames the payload holds.
638    ///
639    /// Exact rather than declared: the payload is a real subslice of the input
640    /// and its length was checked against the frame size at parse time, so this
641    /// is a count of frames that are present, not a count the file claimed.
642    pub const fn frames(&self) -> u64 {
643        self.data.len() as u64 / self.format.frame_bytes() as u64
644    }
645
646    /// `true` when the file was RF64 rather than plain RIFF.
647    pub const fn is_rf64(&self) -> bool {
648        self.rf64
649    }
650
651    /// Appends every interleaved sample of the payload to `output`, and
652    /// returns how many it appended.
653    ///
654    /// Interleaved samples, frames times channels, not the frames
655    /// [`frames`](Self::frames) counts.
656    pub fn decode(&self, output: &mut Vec<f32>) -> usize {
657        self.format.codec.decode(self.data, output)
658    }
659
660    /// Decodes the whole payload, bound to the spec that describes it.
661    ///
662    /// The reservation is from the payload's real length, never from a size the
663    /// file declared.
664    ///
665    /// The channel count of the returned buffer is never zero: a file
666    /// declaring none is refused by [`new`](Self::new) with
667    /// [`DecodeError::UnsupportedChannelLayout`].
668    pub fn decode_to_end(&self) -> AudioBuffer {
669        let mut samples =
670            Vec::with_capacity(self.data.len() / self.format.codec.bytes_per_sample());
671        self.decode(&mut samples);
672        AudioBuffer::from_samples(self.format.spec, samples)
673    }
674}
675
676// -- The streaming reader -----------------------------------------------------
677
678/// Where the streaming reader is in the file.
679#[derive(Debug, Clone, Copy, PartialEq, Eq)]
680enum State {
681    /// Waiting for the twelve-byte RIFF header.
682    Riff,
683    /// Waiting for an eight-byte chunk header.
684    ChunkHeader,
685    /// Buffering the body of a chunk that has to be read: `fmt ` or `ds64`.
686    Body {
687        id: FourCc,
688        size: usize,
689        offset: u64,
690    },
691    /// Discarding the body of a chunk that does not have to be read. Nothing is
692    /// buffered here, which is what keeps an enormous `LIST` chunk free.
693    Skip { size: u64, left: u64 },
694    /// Discarding the one pad byte after an odd-length chunk.
695    Pad,
696    /// Streaming the `data` payload.
697    Data,
698    /// Past the end of `data`. Everything after it is discarded.
699    Done,
700}
701
702/// Reads a WAV file that arrives in pieces.
703///
704/// The [`StreamSource`] half of this module. Bytes are pushed in whatever sizes
705/// they turn up in, samples are pulled out, and nothing is buffered in
706/// proportion to a size the file declared: chunk headers and the `fmt ` and
707/// `ds64` bodies are buffered, every other chunk body is discarded as it flows
708/// past, and the payload is decoded straight into a bounded ready buffer.
709///
710/// # `fmt ` has to come first
711///
712/// [`WavReader`] accepts `data` before `fmt `; this does not, and answers
713/// [`DecodeError::Malformed`] when it meets one. Decoding a payload that
714/// arrives before the header describing it would mean holding all of it, and an
715/// unbounded buffer is exactly what this type is arranged to avoid. Every other
716/// chunk order, and unknown chunks in any position, are the same on both paths.
717///
718/// # Example
719///
720/// ```
721/// use decibri_decode::{AudioSpec, StreamSource, WavCodec, WavStreamDecoder, WavWriter};
722///
723/// let file = WavWriter::new(AudioSpec::mono(16_000), WavCodec::PcmI16)
724///     .to_bytes(&[0.0, 0.5, -0.5])?;
725///
726/// let mut stream = WavStreamDecoder::new();
727/// let mut samples = Vec::new();
728/// for piece in file.chunks(7) {
729///     let mut offset = 0;
730///     while offset < piece.len() {
731///         offset += stream.push(&piece[offset..])?;
732///         while stream.pull(&mut samples, usize::MAX)? > 0 {}
733///     }
734/// }
735/// stream.finish(&mut samples)?;
736///
737/// assert_eq!(stream.spec(), Some(AudioSpec::mono(16_000)));
738/// assert_eq!(samples, [0.0, 0.5, -0.5]);
739/// # Ok::<(), decibri_decode::DecodeError>(())
740/// ```
741#[derive(Debug)]
742pub struct WavStreamDecoder {
743    state: State,
744    /// Bytes of a header or of a `fmt `/`ds64` body that has not fully
745    /// arrived. Bounded by [`MAX_FMT_BYTES`] and
746    /// [`riff::MAX_DS64_BYTES`](crate::riff).
747    pending: Vec<u8>,
748    /// Byte offset of the next byte to arrive, for error reporting.
749    offset: u64,
750    /// Sizes a `ds64` chunk overrides.
751    overrides: Vec<(FourCc, u64)>,
752    /// Set while the RF64 header's mandatory `ds64` chunk is still expected.
753    expect_ds64: bool,
754    format: Option<WavFormat>,
755    payload: Option<Payload>,
756    /// Decoded samples not yet pulled, and how far into them the caller is.
757    ready: Vec<f32>,
758    ready_read: usize,
759    /// The `data` chunk's size, and how much of it is still to arrive.
760    data_size: u64,
761    data_left: u64,
762    finished: bool,
763}
764
765impl Default for WavStreamDecoder {
766    fn default() -> Self {
767        Self::new()
768    }
769}
770
771impl WavStreamDecoder {
772    /// A reader waiting for the first byte of a file.
773    pub fn new() -> Self {
774        Self {
775            state: State::Riff,
776            pending: Vec::new(),
777            offset: 0,
778            overrides: Vec::new(),
779            expect_ds64: false,
780            format: None,
781            payload: None,
782            ready: Vec::new(),
783            ready_read: 0,
784            data_size: 0,
785            data_left: 0,
786            finished: false,
787        }
788    }
789
790    /// What the `fmt ` chunk declared, once it has arrived.
791    pub const fn format(&self) -> Option<WavFormat> {
792        self.format
793    }
794
795    /// How many interleaved samples are decoded and waiting to be pulled:
796    /// frames times channels, which is the length a caller's output vector
797    /// grows by when they are.
798    ///
799    /// Interleaved samples, not the frames [`pull`](StreamSource::pull)
800    /// counts; the two figures differ by the channel count.
801    pub fn ready_samples(&self) -> usize {
802        self.ready.len() - self.ready_read
803    }
804
805    /// Buffers `bytes` into `pending` until it holds `need` of them, and says
806    /// whether it now does.
807    fn accumulate(&mut self, bytes: &[u8], need: usize, taken: &mut usize) -> bool {
808        let want = need.saturating_sub(self.pending.len()).min(bytes.len());
809        self.pending.extend_from_slice(&bytes[..want]);
810        *taken += want;
811        self.offset += want as u64;
812        self.pending.len() >= need
813    }
814
815    /// Reads the twelve-byte RIFF header out of `pending`.
816    fn start_file(&mut self) -> Result<(), DecodeError> {
817        let header = riff::read_riff_header(&self.pending)?;
818        if header.form != riff::WAVE {
819            return Err(DecodeError::UnsupportedContainer { tag: header.form });
820        }
821        self.expect_ds64 = header.magic == riff::RF64;
822        self.pending.clear();
823        self.state = State::ChunkHeader;
824        Ok(())
825    }
826
827    /// Reads an eight-byte chunk header out of `pending` and decides what to do
828    /// with the body.
829    fn start_chunk(&mut self) -> Result<(), DecodeError> {
830        let offset = self.offset - riff::CHUNK_HEADER_BYTES;
831        let (Some(id), Some(declared)) = (
832            riff::four_cc_at(&self.pending, 0),
833            riff::u32_at(&self.pending, 4),
834        ) else {
835            return Err(DecodeError::Truncated {
836                expected: riff::CHUNK_HEADER_BYTES,
837                available: self.pending.len() as u64,
838            });
839        };
840        self.pending.clear();
841        let size = riff::resolve_size(&self.overrides, id, declared);
842
843        if self.expect_ds64 && id != riff::DS64 {
844            return Err(DecodeError::Malformed {
845                expected: "a ds64 chunk immediately after the RF64 form type",
846                offset,
847            });
848        }
849
850        if id == riff::DS64 && self.expect_ds64 {
851            if size > riff::MAX_DS64_BYTES {
852                return Err(DecodeError::Malformed {
853                    expected: "a ds64 chunk of at most 65536 bytes",
854                    offset,
855                });
856            }
857            self.state = State::Body {
858                id,
859                size: size as usize,
860                offset,
861            };
862            return Ok(());
863        }
864
865        if id == riff::FMT && self.format.is_none() {
866            check_fmt_size(size, offset)?;
867            self.state = State::Body {
868                id,
869                size: size as usize,
870                offset,
871            };
872            return Ok(());
873        }
874
875        if id == riff::DATA {
876            let Some(format) = self.format else {
877                // The one thing the streaming path cannot do that the
878                // whole-file path can.
879                return Err(DecodeError::Malformed {
880                    expected: "a fmt chunk before the data chunk",
881                    offset,
882                });
883            };
884            check_whole_frames(size, format.frame_bytes())?;
885            self.payload = Some(Payload::from_parts(
886                format.codec.sample_format(),
887                format.codec.law(),
888                format.spec,
889            ));
890            self.data_size = size;
891            self.data_left = size;
892            self.state = if size == 0 { State::Done } else { State::Data };
893            return Ok(());
894        }
895
896        self.state = if size == 0 {
897            State::ChunkHeader
898        } else {
899            State::Skip { size, left: size }
900        };
901        Ok(())
902    }
903
904    /// Reads a buffered `fmt ` or `ds64` body out of `pending`.
905    fn finish_body(&mut self, id: FourCc, size: usize, offset: u64) -> Result<(), DecodeError> {
906        if id == riff::FMT {
907            self.format = Some(parse_fmt(&self.pending, offset)?);
908        } else {
909            self.overrides = riff::parse_ds64(&self.pending, offset)?;
910            self.expect_ds64 = false;
911        }
912        self.pending.clear();
913        self.state = if riff::pad_len(size as u64) == 1 {
914            State::Pad
915        } else {
916            State::ChunkHeader
917        };
918        Ok(())
919    }
920
921    /// Moves decoded samples out of the payload decoder and keeps the ready
922    /// buffer from growing without bound.
923    fn drain_payload(&mut self) -> Result<(), DecodeError> {
924        if let Some(payload) = self.payload.as_mut() {
925            payload.decode(&mut self.ready)?;
926        }
927        Ok(())
928    }
929}
930
931impl StreamSource for WavStreamDecoder {
932    fn push(&mut self, bytes: &[u8]) -> Result<usize, DecodeError> {
933        if self.finished {
934            return Ok(0);
935        }
936        let mut taken = 0;
937        let result = self.push_inner(bytes, &mut taken);
938        if result.is_err() {
939            // A stream that has failed structurally is over. Leaving it live
940            // would mean a caller who keeps pushing gets a second, different
941            // answer from the same file.
942            self.finished = true;
943        }
944        result.map(|()| taken)
945    }
946
947    fn pull(&mut self, output: &mut Vec<f32>, max_frames: usize) -> Result<usize, DecodeError> {
948        let Some(format) = self.format else {
949            return Ok(0);
950        };
951        let channels = usize::from(format.spec.channels);
952        let available = self.ready.len() - self.ready_read;
953        let frames = (available / channels).min(max_frames);
954        let count = frames * channels;
955        output.extend_from_slice(&self.ready[self.ready_read..self.ready_read + count]);
956        self.ready_read += count;
957        // Amortised compaction: the consumed prefix is dropped once it is at
958        // least half the buffer, so a caller pulling one frame at a time does
959        // not leave the whole file's worth of consumed samples behind it.
960        if self.ready_read == self.ready.len() {
961            self.ready.clear();
962            self.ready_read = 0;
963        } else if self.ready_read >= self.ready.len() / 2 {
964            self.ready.drain(..self.ready_read);
965            self.ready_read = 0;
966        }
967        Ok(frames)
968    }
969
970    fn spec(&self) -> Option<AudioSpec> {
971        self.format.map(|format| format.spec)
972    }
973
974    fn buffered_bytes(&self) -> usize {
975        self.pending.len()
976            + self
977                .payload
978                .as_ref()
979                .map_or(0, |payload| payload.buffered_bytes())
980    }
981
982    fn finish(&mut self, output: &mut Vec<f32>) -> Result<usize, DecodeError> {
983        if self.finished {
984            return Ok(0);
985        }
986        self.finished = true;
987
988        // Structural completeness first: an item half-arrived is Truncated, and
989        // a file that ended on a chunk boundary without ever naming its audio
990        // is Malformed.
991        match self.state {
992            State::Done => {}
993            State::Riff => {
994                return Err(DecodeError::Truncated {
995                    expected: riff::HEADER_BYTES,
996                    available: self.pending.len() as u64,
997                })
998            }
999            // A stream that ended on a chunk boundary never named its audio.
1000            // The missing pad byte after a final odd-length chunk lands here
1001            // too, and for the same reason: the chunk was complete, the file
1002            // was not.
1003            State::Pad => {
1004                return Err(DecodeError::Malformed {
1005                    expected: "a data chunk",
1006                    offset: self.offset,
1007                })
1008            }
1009            State::ChunkHeader if self.pending.is_empty() => {
1010                return Err(DecodeError::Malformed {
1011                    expected: "a data chunk",
1012                    offset: self.offset,
1013                })
1014            }
1015            State::ChunkHeader => {
1016                return Err(DecodeError::Truncated {
1017                    expected: riff::CHUNK_HEADER_BYTES,
1018                    available: self.pending.len() as u64,
1019                })
1020            }
1021            State::Body { size, .. } => {
1022                return Err(DecodeError::Truncated {
1023                    expected: size as u64,
1024                    available: self.pending.len() as u64,
1025                })
1026            }
1027            State::Skip { size, left } => {
1028                return Err(DecodeError::Truncated {
1029                    expected: size,
1030                    available: size - left,
1031                })
1032            }
1033            State::Data => {
1034                return Err(DecodeError::Truncated {
1035                    expected: self.data_size,
1036                    available: self.data_size - self.data_left,
1037                })
1038            }
1039        }
1040
1041        if let Some(payload) = self.payload.as_mut() {
1042            payload.flush(&mut self.ready)?;
1043        }
1044        let Some(format) = self.format else {
1045            return Ok(0);
1046        };
1047        let channels = usize::from(format.spec.channels);
1048        let frames = (self.ready.len() - self.ready_read) / channels;
1049        output.extend_from_slice(&self.ready[self.ready_read..self.ready_read + frames * channels]);
1050        self.ready.clear();
1051        self.ready_read = 0;
1052        Ok(frames)
1053    }
1054
1055    fn reset(&mut self) {
1056        *self = Self::new();
1057    }
1058}
1059
1060impl WavStreamDecoder {
1061    /// The body of [`push`](StreamSource::push), split out so a failure can set
1062    /// the finished flag in one place.
1063    fn push_inner(&mut self, bytes: &[u8], taken: &mut usize) -> Result<(), DecodeError> {
1064        while *taken < bytes.len() {
1065            let rest = &bytes[*taken..];
1066            match self.state {
1067                State::Riff => {
1068                    if !self.accumulate(rest, riff::HEADER_BYTES as usize, taken) {
1069                        break;
1070                    }
1071                    self.start_file()?;
1072                }
1073                State::ChunkHeader => {
1074                    if !self.accumulate(rest, riff::CHUNK_HEADER_BYTES as usize, taken) {
1075                        break;
1076                    }
1077                    self.start_chunk()?;
1078                }
1079                State::Body { id, size, offset } => {
1080                    if !self.accumulate(rest, size, taken) {
1081                        break;
1082                    }
1083                    self.finish_body(id, size, offset)?;
1084                }
1085                State::Skip { size, left } => {
1086                    let step = left.min(rest.len() as u64);
1087                    *taken += step as usize;
1088                    self.offset += step;
1089                    let left = left - step;
1090                    self.state = if left == 0 {
1091                        if riff::pad_len(size) == 1 {
1092                            State::Pad
1093                        } else {
1094                            State::ChunkHeader
1095                        }
1096                    } else {
1097                        State::Skip { size, left }
1098                    };
1099                }
1100                State::Pad => {
1101                    *taken += 1;
1102                    self.offset += 1;
1103                    self.state = State::ChunkHeader;
1104                }
1105                State::Data => {
1106                    if self.ready.len() - self.ready_read >= READY_LIMIT {
1107                        // Back-pressure: the caller has to pull before the
1108                        // reader will take more.
1109                        break;
1110                    }
1111                    let limit = self.data_left.min(rest.len() as u64) as usize;
1112                    let fed = match self.payload.as_mut() {
1113                        Some(payload) => payload.feed(&rest[..limit])?,
1114                        None => 0,
1115                    };
1116                    self.drain_payload()?;
1117                    *taken += fed;
1118                    self.offset += fed as u64;
1119                    self.data_left -= fed as u64;
1120                    if self.data_left == 0 {
1121                        self.state = State::Done;
1122                    } else if fed == 0 {
1123                        break;
1124                    }
1125                }
1126                State::Done => {
1127                    // Chunks after `data` are not this reader's business, and
1128                    // discarding them is what makes a file with metadata at the
1129                    // end readable rather than an error.
1130                    self.offset += (bytes.len() - *taken) as u64;
1131                    *taken = bytes.len();
1132                }
1133            }
1134        }
1135        Ok(())
1136    }
1137}
1138
1139// -- The writer ---------------------------------------------------------------
1140
1141/// How a written file names its format.
1142#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
1143#[non_exhaustive]
1144pub enum WavHeaderStyle {
1145    /// The plain `wFormatTag`, 1, 3, 6 or 7, in a sixteen-byte `fmt ` chunk.
1146    ///
1147    /// What every reader understands, and the default for that reason.
1148    #[default]
1149    Plain,
1150    /// `wFormatTag` 0xFFFE with a forty-byte `fmt ` chunk naming the format in
1151    /// a SubFormat GUID.
1152    ///
1153    /// What Windows writes for anything above two channels or sixteen bits.
1154    Extensible,
1155}
1156
1157/// Which RIFF flavour a written file uses.
1158#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
1159#[non_exhaustive]
1160pub enum RiffFlavour {
1161    /// Plain `RIFF`, upgrading to `RF64` only when the file would not fit in
1162    /// RIFF's 32-bit size fields.
1163    ///
1164    /// There is no third option where the writer refuses: a caller with five
1165    /// gigabytes of audio wants a file, and `RF64` is what a file of that size
1166    /// is. Keeping the upgrade automatic is what lets
1167    /// [`WavWriter::write`] fail only on things the caller can fix.
1168    #[default]
1169    Automatic,
1170    /// `RF64` with a `ds64` chunk whatever the size.
1171    Rf64,
1172}
1173
1174/// Whether a file of this shape needs RF64's 64-bit sizes.
1175///
1176/// Split out as a function of two numbers so the threshold can be tested
1177/// without materialising four gigabytes to test it with.
1178fn needs_rf64(fmt_bytes: u64, data_bytes: u64) -> bool {
1179    riff_size(fmt_bytes, data_bytes, false).is_none_or(|size| size > u64::from(u32::MAX))
1180}
1181
1182/// The value of the RIFF header's size field: everything after the first eight
1183/// bytes. `None` when that does not fit in 64 bits, which no caller can reach
1184/// but the arithmetic should not pretend about.
1185fn riff_size(fmt_bytes: u64, data_bytes: u64, ds64: bool) -> Option<u64> {
1186    let mut size: u64 = 4; // the form type
1187    if ds64 {
1188        size = size.checked_add(riff::CHUNK_HEADER_BYTES + DS64_BODY_BYTES)?;
1189    }
1190    size = size
1191        .checked_add(riff::CHUNK_HEADER_BYTES)?
1192        .checked_add(fmt_bytes)?;
1193    size = size
1194        .checked_add(riff::CHUNK_HEADER_BYTES)?
1195        .checked_add(data_bytes)?
1196        // The pad byte belongs to the enclosing form even though it is outside
1197        // the `data` chunk's own declared size.
1198        .checked_add(data_bytes & 1)?;
1199    Some(size)
1200}
1201
1202/// Writes RIFF/WAVE and RF64 files.
1203///
1204/// The writer exists in the same step as the reader because round-trip identity
1205/// is the cheapest strong gate available for a container, and it needs both
1206/// halves. It writes every encoding the reader accepts, and [`WavCodec`] has
1207/// no variant that is readable and not writable, with the pad
1208/// byte on an odd-length `data` chunk and a correct `RIFF` size field.
1209///
1210/// # Samples outside full scale, and samples that are not finite
1211///
1212/// **The integer encodings clamp and the float encodings do not.** A sample
1213/// outside `-1.0..=1.0` written to an integer encoding becomes the extreme
1214/// value rather than wrapping, an infinity becomes the same extreme, and a
1215/// NaN becomes silence. A sample written to [`WavCodec::Float32`] or
1216/// [`WavCodec::Float64`] is written through as it is, overshoot, infinities
1217/// and NaN included. A count of clipped samples is therefore a number about
1218/// an integer encoding and not about a float one.
1219///
1220/// Read back through this crate, a NaN written to [`WavCodec::Float32`]
1221/// returns the same bit pattern, and a NaN written to [`WavCodec::Float64`]
1222/// returns silence, because narrowing a NaN from `f64` to `f32` normalises
1223/// it. Both infinities return unchanged at either width.
1224///
1225/// # Example
1226///
1227/// ```
1228/// use decibri_decode::{AudioSpec, WavCodec, WavHeaderStyle, WavReader, WavWriter};
1229///
1230/// let file = WavWriter::new(AudioSpec::new(44_100, 2), WavCodec::PcmI24)
1231///     .with_header_style(WavHeaderStyle::Extensible)
1232///     .to_bytes(&[0.5, -0.5, 0.25, -0.25])?;
1233///
1234/// let reader = WavReader::new(&file)?;
1235/// assert!(reader.format().is_extensible());
1236/// assert_eq!(reader.format().codec, WavCodec::PcmI24);
1237/// assert_eq!(reader.decode_to_end().samples(), [0.5, -0.5, 0.25, -0.25]);
1238/// # Ok::<(), decibri_decode::DecodeError>(())
1239/// ```
1240#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1241pub struct WavWriter {
1242    spec: AudioSpec,
1243    codec: WavCodec,
1244    header: WavHeaderStyle,
1245    flavour: RiffFlavour,
1246}
1247
1248impl WavWriter {
1249    /// A writer for `codec` audio at `spec`, in a plain `RIFF` header.
1250    pub const fn new(spec: AudioSpec, codec: WavCodec) -> Self {
1251        Self {
1252            spec,
1253            codec,
1254            header: WavHeaderStyle::Plain,
1255            flavour: RiffFlavour::Automatic,
1256        }
1257    }
1258
1259    /// Sets whether the `fmt ` chunk is plain or `WAVE_FORMAT_EXTENSIBLE`.
1260    pub const fn with_header_style(mut self, header: WavHeaderStyle) -> Self {
1261        self.header = header;
1262        self
1263    }
1264
1265    /// Sets whether the file is `RIFF` or `RF64`.
1266    pub const fn with_flavour(mut self, flavour: RiffFlavour) -> Self {
1267        self.flavour = flavour;
1268        self
1269    }
1270
1271    /// The rate and layout written into the header.
1272    pub const fn spec(&self) -> AudioSpec {
1273        self.spec
1274    }
1275
1276    /// The encoding the payload is written in.
1277    pub const fn codec(&self) -> WavCodec {
1278        self.codec
1279    }
1280
1281    /// Appends a complete file to `output`, and returns how many bytes it
1282    /// appended.
1283    ///
1284    /// `output` is appended to, never cleared, the same convention as
1285    /// everything else in this crate that writes into a caller's buffer.
1286    ///
1287    /// # Errors
1288    ///
1289    /// - [`DecodeError::UnsupportedChannelLayout`] for no channels, and for a
1290    ///   layout whose frame does not fit `nBlockAlign`. That second one is a
1291    ///   limit of `WAVEFORMATEX` rather than of this crate: the field is a
1292    ///   `u16`, so 8,191 channels of `f64` is the widest frame a WAV file can
1293    ///   describe. The reader accepts such a file if one turns up, because
1294    ///   `nBlockAlign` is advisory there; the writer will not produce one,
1295    ///   because it would have to write a field it knows is wrong.
1296    /// - [`DecodeError::Malformed`] for a zero sample rate.
1297    /// - [`DecodeError::Truncated`] when `samples` does not divide into whole
1298    ///   frames. Writing a partial trailing frame would produce a file this
1299    ///   crate's own reader rejects, and dropping it would be the silent
1300    ///   truncation the reader exists to catch.
1301    pub fn write(&self, samples: &[f32], output: &mut Vec<u8>) -> Result<usize, DecodeError> {
1302        let channels = usize::from(self.spec.channels);
1303        if channels == 0 {
1304            return Err(DecodeError::UnsupportedChannelLayout {
1305                channels: self.spec.channels,
1306            });
1307        }
1308        let frame_bytes = channels * self.codec.bytes_per_sample();
1309        let Ok(block_align) = u16::try_from(frame_bytes) else {
1310            return Err(DecodeError::UnsupportedChannelLayout {
1311                channels: self.spec.channels,
1312            });
1313        };
1314        if self.spec.sample_rate == 0 {
1315            return Err(DecodeError::Malformed {
1316                expected: "a non-zero sample rate",
1317                offset: riff::HEADER_BYTES + riff::CHUNK_HEADER_BYTES + 4,
1318            });
1319        }
1320        let leftover = samples.len() % channels;
1321        if leftover != 0 {
1322            return Err(DecodeError::Truncated {
1323                expected: frame_bytes as u64,
1324                available: (leftover * self.codec.bytes_per_sample()) as u64,
1325            });
1326        }
1327
1328        let fmt_bytes = match self.header {
1329            WavHeaderStyle::Plain => FMT_BYTES_PLAIN,
1330            WavHeaderStyle::Extensible => FMT_BYTES_EXTENSIBLE,
1331        };
1332        let data_bytes = (samples.len() * self.codec.bytes_per_sample()) as u64;
1333        let ds64 = match self.flavour {
1334            RiffFlavour::Rf64 => true,
1335            RiffFlavour::Automatic => needs_rf64(fmt_bytes, data_bytes),
1336        };
1337        let declared_riff = riff_size(fmt_bytes, data_bytes, ds64);
1338
1339        let start = output.len();
1340        output.extend_from_slice(if ds64 {
1341            riff::RF64.as_bytes()
1342        } else {
1343            riff::RIFF.as_bytes()
1344        });
1345        // RF64 leaves every oversized field at the sentinel and states the real
1346        // number in `ds64`, so that a plain RIFF reader meeting the file fails
1347        // on the size rather than reading four gigabytes of nothing.
1348        let riff_field = match (ds64, declared_riff) {
1349            (true, _) => riff::SIZE_SENTINEL,
1350            (false, Some(size)) => size as u32,
1351            (false, None) => riff::SIZE_SENTINEL,
1352        };
1353        output.extend_from_slice(&riff_field.to_le_bytes());
1354        output.extend_from_slice(riff::WAVE.as_bytes());
1355
1356        if ds64 {
1357            output.extend_from_slice(riff::DS64.as_bytes());
1358            output.extend_from_slice(&(DS64_BODY_BYTES as u32).to_le_bytes());
1359            output.extend_from_slice(&declared_riff.unwrap_or(u64::MAX).to_le_bytes());
1360            output.extend_from_slice(&data_bytes.to_le_bytes());
1361            output.extend_from_slice(&((samples.len() / channels) as u64).to_le_bytes());
1362            output.extend_from_slice(&0u32.to_le_bytes()); // no override table
1363        }
1364
1365        output.extend_from_slice(riff::FMT.as_bytes());
1366        output.extend_from_slice(&(fmt_bytes as u32).to_le_bytes());
1367        let tag = match self.header {
1368            WavHeaderStyle::Extensible => TAG_EXTENSIBLE,
1369            WavHeaderStyle::Plain => self.codec.format_tag(),
1370        };
1371        let bits = self.codec.bits_per_sample();
1372        output.extend_from_slice(&tag.to_le_bytes());
1373        output.extend_from_slice(&self.spec.channels.to_le_bytes());
1374        output.extend_from_slice(&self.spec.sample_rate.to_le_bytes());
1375        // `nAvgBytesPerSec` is a `u32` and the product need not fit one at an
1376        // absurd rate. Saturating keeps the field advisory rather than making
1377        // the writer fail on a number nothing reads.
1378        let byte_rate = u64::from(self.spec.sample_rate) * u64::from(block_align);
1379        output.extend_from_slice(&(byte_rate.min(u64::from(u32::MAX)) as u32).to_le_bytes());
1380        output.extend_from_slice(&block_align.to_le_bytes());
1381        output.extend_from_slice(&bits.to_le_bytes());
1382        if matches!(self.header, WavHeaderStyle::Extensible) {
1383            output.extend_from_slice(&22u16.to_le_bytes()); // cbSize
1384            output.extend_from_slice(&bits.to_le_bytes()); // wValidBitsPerSample
1385                                                           // A channel mask of zero says the channels have no assigned
1386                                                           // speaker positions, which is the truth: nothing told this writer
1387                                                           // where they go, and inventing a layout is how a rear channel ends
1388                                                           // up labelled as a centre one.
1389            output.extend_from_slice(&0u32.to_le_bytes());
1390            output.extend_from_slice(&self.codec.format_tag().to_le_bytes());
1391            output.extend_from_slice(&SUBFORMAT_TAIL);
1392        }
1393
1394        output.extend_from_slice(riff::DATA.as_bytes());
1395        let data_field = if ds64 {
1396            riff::SIZE_SENTINEL
1397        } else {
1398            data_bytes as u32
1399        };
1400        output.extend_from_slice(&data_field.to_le_bytes());
1401        self.codec.encode(samples, output);
1402        if riff::pad_len(data_bytes) == 1 {
1403            // RIFF pads an odd body to an even boundary. The pad is outside the
1404            // chunk's declared size and inside the form's.
1405            output.push(0);
1406        }
1407        Ok(output.len() - start)
1408    }
1409
1410    /// A complete file as a new `Vec<u8>`.
1411    ///
1412    /// # Errors
1413    ///
1414    /// As [`write`](Self::write).
1415    pub fn to_bytes(&self, samples: &[f32]) -> Result<Vec<u8>, DecodeError> {
1416        let mut output = Vec::new();
1417        self.write(samples, &mut output)?;
1418        Ok(output)
1419    }
1420}
1421
1422#[cfg(test)]
1423mod tests {
1424    use super::*;
1425
1426    /// Every encoding, for the tests that have to cover all of them rather than
1427    /// the one that was being thought about.
1428    pub(crate) const ALL: [WavCodec; 8] = [
1429        WavCodec::PcmU8,
1430        WavCodec::PcmI16,
1431        WavCodec::PcmI24,
1432        WavCodec::PcmI32,
1433        WavCodec::Float32,
1434        WavCodec::Float64,
1435        WavCodec::ALaw,
1436        WavCodec::MuLaw,
1437    ];
1438
1439    /// The exhaustive match is the assertion: a variant added to [`WavCodec`]
1440    /// without a line in [`ALL`] fails to compile here, so no later encoding
1441    /// can be added and quietly left out of every "every codec" gate in the
1442    /// suite.
1443    #[test]
1444    fn all_lists_every_codec() {
1445        for codec in ALL {
1446            match codec {
1447                WavCodec::PcmU8
1448                | WavCodec::PcmI16
1449                | WavCodec::PcmI24
1450                | WavCodec::PcmI32
1451                | WavCodec::Float32
1452                | WavCodec::Float64
1453                | WavCodec::ALaw
1454                | WavCodec::MuLaw => {}
1455            }
1456        }
1457        assert_eq!(ALL.len(), 8);
1458    }
1459
1460    // -- Dispatch, on the pair --------------------------------------------
1461
1462    /// The whole `(tag, bits)` space this crate accepts, and the shape of every
1463    /// rejection outside it.
1464    #[test]
1465    fn dispatch_is_on_the_tag_and_the_width_together() {
1466        let accepted: [(u16, u16, WavCodec); 8] = [
1467            (1, 8, WavCodec::PcmU8),
1468            (1, 16, WavCodec::PcmI16),
1469            (1, 24, WavCodec::PcmI24),
1470            (1, 32, WavCodec::PcmI32),
1471            (3, 32, WavCodec::Float32),
1472            (3, 64, WavCodec::Float64),
1473            (6, 8, WavCodec::ALaw),
1474            (7, 8, WavCodec::MuLaw),
1475        ];
1476        for (tag, bits, codec) in accepted {
1477            assert_eq!(WavCodec::resolve(tag, bits).expect("accepted"), codec);
1478            // And the codec names the pair it came from, so the writer cannot
1479            // disagree with the reader about what it just wrote.
1480            assert_eq!(codec.format_tag(), tag);
1481            assert_eq!(codec.bits_per_sample(), bits);
1482        }
1483
1484        // A carried tag at a width this build does not have is a sample-format
1485        // rejection, and it names the width.
1486        for (tag, bits) in [
1487            (1u16, 4u16),
1488            (1, 12),
1489            (1, 20),
1490            (1, 64),
1491            (3, 16),
1492            (6, 16),
1493            (7, 4),
1494        ] {
1495            let error = WavCodec::resolve(tag, bits).expect_err("must reject");
1496            assert!(
1497                matches!(
1498                    &error,
1499                    DecodeError::UnsupportedSampleFormat { format, bits_per_sample }
1500                        if *format == CodecId::WaveFormatTag(tag) && *bits_per_sample == bits
1501                ),
1502                "({tag}, {bits}): unexpected error: {error}"
1503            );
1504        }
1505
1506        // A tag this build does not carry is a codec rejection, and it names
1507        // the tag.
1508        for tag in [0u16, 2, 0x11, 0x31, 0x50, 0x161, 0xFFFE] {
1509            let error = WavCodec::resolve(tag, 16).expect_err("must reject");
1510            assert!(
1511                matches!(&error, DecodeError::UnsupportedCodec { codec }
1512                    if *codec == CodecId::WaveFormatTag(tag)),
1513                "tag {tag:#x}: unexpected error: {error}"
1514            );
1515        }
1516    }
1517
1518    /// Every width tag 1 carries decodes at its own stride. This is the
1519    /// assertion a reader dispatching on the tag alone fails: it would read all
1520    /// four of these as whichever width it picked.
1521    #[test]
1522    fn each_width_of_tag_one_has_its_own_stride() {
1523        let widths: [(u16, usize); 4] = [(8, 1), (16, 2), (24, 3), (32, 4)];
1524        for (bits, bytes) in widths {
1525            let codec = WavCodec::resolve(1, bits).expect("accepted");
1526            assert_eq!(codec.bytes_per_sample(), bytes, "{bits} bits");
1527            let mut out = Vec::new();
1528            assert_eq!(codec.decode(&[0u8; 24], &mut out), 24 / bytes);
1529        }
1530    }
1531
1532    #[test]
1533    fn every_codec_is_linear_or_companded_and_never_both() {
1534        for codec in ALL {
1535            assert_ne!(
1536                codec.sample_format().is_some(),
1537                codec.law().is_some(),
1538                "{codec:?} is on both sides or neither"
1539            );
1540            if let Some(format) = codec.sample_format() {
1541                assert_eq!(format.bytes_per_sample(), codec.bytes_per_sample());
1542                assert_eq!(format.bits_per_sample(), codec.bits_per_sample());
1543            } else {
1544                // G.711 is one byte per sample and eight bits per sample, and
1545                // the two statements are about different things: the code is a
1546                // byte, the sample it stands for is 13 or 14 bits wide.
1547                assert_eq!(codec.bytes_per_sample(), 1);
1548            }
1549        }
1550    }
1551
1552    // -- The extensible header --------------------------------------------
1553
1554    /// The GUID text form, against the two values Microsoft publishes.
1555    #[test]
1556    fn a_guid_is_reported_in_the_form_it_is_documented_in() {
1557        let mut pcm = [0u8; 16];
1558        pcm[0] = 1;
1559        pcm[2..].copy_from_slice(&SUBFORMAT_TAIL);
1560        assert_eq!(format_guid(&pcm), "00000001-0000-0010-8000-00aa00389b71");
1561
1562        let ambisonic = [
1563            0x01, 0x00, 0x00, 0x00, 0x21, 0x07, 0xd3, 0x11, 0x86, 0x44, 0xc8, 0xc1, 0xca, 0x00,
1564            0x00, 0x00,
1565        ];
1566        assert_eq!(
1567            format_guid(&ambisonic),
1568            "00000001-0721-11d3-8644-c8c1ca000000"
1569        );
1570    }
1571
1572    /// A `fmt ` body for the tests below: sixteen fixed bytes plus whatever
1573    /// extension is named. Written here rather than reached for from the
1574    /// writer, so parsing is tested against bytes the writer did not produce.
1575    fn fmt_body(tag: u16, channels: u16, rate: u32, bits: u16, extension: &[u8]) -> Vec<u8> {
1576        let block_align = channels * bits.div_ceil(8);
1577        let mut body = Vec::new();
1578        body.extend_from_slice(&tag.to_le_bytes());
1579        body.extend_from_slice(&channels.to_le_bytes());
1580        body.extend_from_slice(&rate.to_le_bytes());
1581        body.extend_from_slice(&(rate * u32::from(block_align)).to_le_bytes());
1582        body.extend_from_slice(&block_align.to_le_bytes());
1583        body.extend_from_slice(&bits.to_le_bytes());
1584        body.extend_from_slice(extension);
1585        body
1586    }
1587
1588    /// A `WAVE_FORMAT_EXTENSIBLE` extension naming `tag`, with `cb_size` as
1589    /// declared so an inconsistent one can be built deliberately.
1590    fn extension(tag: u16, cb_size: u16) -> Vec<u8> {
1591        let mut bytes = Vec::new();
1592        bytes.extend_from_slice(&cb_size.to_le_bytes());
1593        bytes.extend_from_slice(&16u16.to_le_bytes()); // wValidBitsPerSample
1594        bytes.extend_from_slice(&0u32.to_le_bytes()); // dwChannelMask
1595        bytes.extend_from_slice(&tag.to_le_bytes());
1596        bytes.extend_from_slice(&SUBFORMAT_TAIL);
1597        bytes
1598    }
1599
1600    #[test]
1601    fn an_extensible_header_resolves_through_its_subformat_guid() {
1602        for (tag, bits, codec) in [
1603            (1u16, 16u16, WavCodec::PcmI16),
1604            (1, 24, WavCodec::PcmI24),
1605            (3, 32, WavCodec::Float32),
1606            (6, 8, WavCodec::ALaw),
1607            (7, 8, WavCodec::MuLaw),
1608        ] {
1609            let body = fmt_body(TAG_EXTENSIBLE, 2, 48_000, bits, &extension(tag, 22));
1610            let format = parse_fmt(&body, 12).expect("extensible header");
1611            assert_eq!(format.codec, codec);
1612            // The declared tag is kept as the file wrote it.
1613            assert_eq!(format.format_tag, TAG_EXTENSIBLE);
1614            assert!(format.is_extensible());
1615        }
1616    }
1617
1618    #[test]
1619    fn an_inconsistent_cb_size_is_malformed_rather_than_read_past() {
1620        // cbSize under 22 says there is no room for a GUID.
1621        for cb_size in [0u16, 1, 21] {
1622            let body = fmt_body(TAG_EXTENSIBLE, 1, 8_000, 16, &extension(1, cb_size));
1623            let error = parse_fmt(&body, 12).expect_err("must reject");
1624            assert!(
1625                matches!(
1626                    error,
1627                    DecodeError::Malformed {
1628                        expected: "a 22-byte WAVE_FORMAT_EXTENSIBLE extension after cbSize",
1629                        ..
1630                    }
1631                ),
1632                "cbSize {cb_size}: unexpected error: {error}"
1633            );
1634        }
1635        // cbSize says 22 and the body does not carry them.
1636        for truncate_to in [16usize, 18, 24, 39] {
1637            let mut body = fmt_body(TAG_EXTENSIBLE, 1, 8_000, 16, &extension(1, 22));
1638            body.truncate(truncate_to);
1639            let error = parse_fmt(&body, 12).expect_err("must reject");
1640            assert!(
1641                matches!(error, DecodeError::Malformed { .. }),
1642                "{truncate_to} bytes: unexpected error: {error}"
1643            );
1644        }
1645    }
1646
1647    #[test]
1648    fn an_unrecognised_subformat_guid_is_reported_as_the_guid_it_was() {
1649        let mut ext = extension(1, 22);
1650        // Break the first byte of the fixed tail, so the GUID is outside the
1651        // WAVEFORMATEX family and names a codec with no tag at all.
1652        ext[10] = 0xAB;
1653        let body = fmt_body(TAG_EXTENSIBLE, 1, 8_000, 16, &ext);
1654        let error = parse_fmt(&body, 12).expect_err("must reject");
1655        match error {
1656            DecodeError::UnsupportedCodec {
1657                codec: CodecId::Name(name),
1658            } => assert_eq!(name, "00ab0001-0000-0010-8000-00aa00389b71"),
1659            other => panic!("unexpected error: {other}"),
1660        }
1661    }
1662
1663    /// An extensible header whose GUID names a codec this build does not carry
1664    /// reports the tag the GUID named, not `0xFFFE`. `0xFFFE` says only "look
1665    /// in the extension", so reporting it back tells a caller nothing.
1666    #[test]
1667    fn an_extensible_header_naming_an_unsupported_codec_reports_the_resolved_tag() {
1668        let body = fmt_body(TAG_EXTENSIBLE, 1, 8_000, 4, &extension(0x0011, 22));
1669        let error = parse_fmt(&body, 12).expect_err("must reject");
1670        assert!(
1671            matches!(&error, DecodeError::UnsupportedCodec { codec }
1672                if *codec == CodecId::WaveFormatTag(0x0011)),
1673            "unexpected error: {error}"
1674        );
1675    }
1676
1677    // -- `fmt ` validation ------------------------------------------------
1678
1679    #[test]
1680    fn a_zero_channel_count_is_an_unsupported_layout() {
1681        let body = fmt_body(1, 0, 8_000, 16, &[]);
1682        let error = parse_fmt(&body, 12).expect_err("must reject");
1683        assert!(
1684            matches!(error, DecodeError::UnsupportedChannelLayout { channels: 0 }),
1685            "unexpected error: {error}"
1686        );
1687    }
1688
1689    #[test]
1690    fn a_zero_sample_rate_is_malformed_and_names_where_it_was() {
1691        let body = fmt_body(1, 1, 0, 16, &[]);
1692        let error = parse_fmt(&body, 12).expect_err("must reject");
1693        assert!(
1694            matches!(
1695                error,
1696                DecodeError::Malformed {
1697                    expected: "a non-zero sample rate",
1698                    offset: 24
1699                }
1700            ),
1701            "unexpected error: {error}"
1702        );
1703    }
1704
1705    #[test]
1706    fn a_fmt_chunk_size_outside_what_waveformatex_can_mean_is_malformed() {
1707        for size in [0u64, 1, 15] {
1708            assert!(check_fmt_size(size, 12).is_err(), "{size} bytes accepted");
1709        }
1710        for size in [16u64, 18, 40, MAX_FMT_BYTES] {
1711            assert!(check_fmt_size(size, 12).is_ok(), "{size} bytes rejected");
1712        }
1713        // cbSize is a u16, so this is the format's ceiling and not a number
1714        // chosen here.
1715        assert_eq!(MAX_FMT_BYTES, 65_553);
1716        assert!(check_fmt_size(MAX_FMT_BYTES + 1, 12).is_err());
1717    }
1718
1719    #[test]
1720    fn a_block_align_that_disagrees_with_the_format_does_not_stop_the_decode() {
1721        let mut body = fmt_body(1, 2, 44_100, 16, &[]);
1722        body[12..14].copy_from_slice(&999u16.to_le_bytes());
1723        let format = parse_fmt(&body, 12).expect("advisory field");
1724        assert_eq!(format.block_align, 999, "the declaration is kept");
1725        assert_eq!(format.frame_bytes(), 4, "and the frame size is computed");
1726    }
1727
1728    // -- Whole frames -----------------------------------------------------
1729
1730    #[test]
1731    fn a_data_length_that_is_not_whole_frames_is_truncated() {
1732        // Four-byte frames: two channels of sixteen-bit.
1733        assert!(check_whole_frames(8, 4).is_ok());
1734        for (len, remainder) in [(9u64, 1u64), (10, 2), (11, 3), (1, 1)] {
1735            let error = check_whole_frames(len, 4).expect_err("must reject");
1736            assert!(
1737                matches!(error, DecodeError::Truncated { expected: 4, available }
1738                    if available == remainder),
1739                "{len} bytes: unexpected error: {error}"
1740            );
1741        }
1742        // Zero frames is a whole number of frames.
1743        assert!(check_whole_frames(0, 4).is_ok());
1744    }
1745
1746    // -- The RF64 threshold -----------------------------------------------
1747
1748    /// The upgrade point, tested as arithmetic rather than by materialising
1749    /// four gigabytes to cross it with.
1750    #[test]
1751    fn the_rf64_upgrade_happens_exactly_at_the_riff_size_limit() {
1752        // A plain RIFF header over a sixteen-byte `fmt `: 4 for the form type,
1753        // 8 + 16 for the `fmt ` chunk and 8 for the `data` header, 36 bytes
1754        // the payload has to share `u32::MAX` with.
1755        const OVERHEAD: u64 =
1756            4 + riff::CHUNK_HEADER_BYTES + FMT_BYTES_PLAIN + riff::CHUNK_HEADER_BYTES;
1757        assert_eq!(OVERHEAD, 36);
1758        let ceiling = u64::from(u32::MAX);
1759
1760        // `u32::MAX - 36` is odd, so its pad byte is what tips it over: the
1761        // largest payload that fits is one less than that, and even.
1762        let largest = ceiling - OVERHEAD - 1;
1763        assert_eq!(largest % 2, 0);
1764        assert_eq!(
1765            riff_size(FMT_BYTES_PLAIN, largest, false),
1766            Some(ceiling - 1)
1767        );
1768        assert!(
1769            !needs_rf64(FMT_BYTES_PLAIN, largest),
1770            "the last fitting size"
1771        );
1772        assert!(needs_rf64(FMT_BYTES_PLAIN, largest + 1), "one byte past it");
1773        assert!(needs_rf64(FMT_BYTES_PLAIN, largest + 2));
1774
1775        // The pad byte is genuinely counted: the odd payload one byte smaller
1776        // fits only because 36 + payload + 1 still lands on the ceiling.
1777        assert_eq!(
1778            riff_size(FMT_BYTES_PLAIN, largest - 1, false),
1779            Some(ceiling - 1)
1780        );
1781        assert!(!needs_rf64(FMT_BYTES_PLAIN, largest - 1));
1782
1783        // A larger `fmt ` chunk brings the limit down by exactly its extra
1784        // twenty-four bytes.
1785        assert!(needs_rf64(FMT_BYTES_EXTENSIBLE, largest));
1786        assert!(!needs_rf64(FMT_BYTES_EXTENSIBLE, largest - 24));
1787        assert!(needs_rf64(FMT_BYTES_EXTENSIBLE, largest - 23));
1788
1789        // And nothing small is upgraded.
1790        assert!(!needs_rf64(FMT_BYTES_PLAIN, 0));
1791        assert!(!needs_rf64(FMT_BYTES_PLAIN, 1_000_000));
1792    }
1793
1794    #[test]
1795    fn the_riff_size_field_counts_everything_after_the_first_eight_bytes() {
1796        // 4 (WAVE) + 8 + 16 (fmt) + 8 + 4 (data) = 40.
1797        assert_eq!(riff_size(FMT_BYTES_PLAIN, 4, false), Some(40));
1798        // An odd payload adds its pad byte to the form's size.
1799        assert_eq!(riff_size(FMT_BYTES_PLAIN, 5, false), Some(42));
1800        // And ds64 adds its own header and body.
1801        assert_eq!(riff_size(FMT_BYTES_PLAIN, 4, true), Some(76));
1802    }
1803
1804    // -- The writer's rejections ------------------------------------------
1805
1806    #[test]
1807    fn the_writer_rejects_a_partial_trailing_frame() {
1808        let writer = WavWriter::new(AudioSpec::new(48_000, 3), WavCodec::PcmI16);
1809        let error = writer.to_bytes(&[0.0; 7]).expect_err("must reject");
1810        assert!(
1811            matches!(
1812                error,
1813                DecodeError::Truncated {
1814                    expected: 6,
1815                    available: 2
1816                }
1817            ),
1818            "unexpected error: {error}"
1819        );
1820        // Seven is one sample past two frames; six and nine are whole.
1821        assert!(writer.to_bytes(&[0.0; 6]).is_ok());
1822        assert!(writer.to_bytes(&[0.0; 9]).is_ok());
1823    }
1824
1825    #[test]
1826    fn the_writer_rejects_what_the_header_cannot_express() {
1827        let no_channels = WavWriter::new(AudioSpec::new(48_000, 0), WavCodec::PcmI16);
1828        assert!(matches!(
1829            no_channels.to_bytes(&[]),
1830            Err(DecodeError::UnsupportedChannelLayout { channels: 0 })
1831        ));
1832
1833        let no_rate = WavWriter::new(AudioSpec::mono(0), WavCodec::PcmI16);
1834        assert!(matches!(
1835            no_rate.to_bytes(&[]),
1836            Err(DecodeError::Malformed {
1837                expected: "a non-zero sample rate",
1838                ..
1839            })
1840        ));
1841
1842        // nBlockAlign is a u16, so a frame wider than 65,535 bytes cannot be
1843        // described. 8,192 channels of f64 is 65,536.
1844        let too_wide = WavWriter::new(AudioSpec::new(48_000, 8_192), WavCodec::Float64);
1845        assert!(matches!(
1846            too_wide.to_bytes(&[]),
1847            Err(DecodeError::UnsupportedChannelLayout { channels: 8_192 })
1848        ));
1849        // And one channel fewer fits exactly.
1850        let widest = WavWriter::new(AudioSpec::new(48_000, 8_191), WavCodec::Float64);
1851        assert!(widest.to_bytes(&[]).is_ok());
1852    }
1853
1854    #[test]
1855    fn the_writer_appends_rather_than_clearing() {
1856        let writer = WavWriter::new(AudioSpec::mono(8_000), WavCodec::PcmU8);
1857        let mut output = vec![0xAA];
1858        let written = writer.write(&[0.0, 0.0], &mut output).expect("write");
1859        assert_eq!(output[0], 0xAA);
1860        assert_eq!(output.len(), 1 + written);
1861        assert_eq!(written, 12 + 8 + 16 + 8 + 2);
1862    }
1863}