Skip to main content

decibri_decode/
aiff.rs

1//! AIFF and AIFF-C: the second container this crate reads and writes, and the
2//! first big-endian one. [`AiffWriter`] writes every encoding the readers
3//! accept, including the 80-bit extended-float *encoding* side of the sample
4//! rate, so no format here is supported in one direction only.
5//!
6//! # AIFF is not WAV with the bytes swapped
7//!
8//! The chunk walk really is shared (EA IFF 85 chunks are RIFF chunks with a
9//! big-endian size field, and [`ChunkWalker`] takes the byte order as an
10//! argument) but everything the chunks *mean* differs, and five differences
11//! in particular are traps that produce silently wrong audio rather than an
12//! error:
13//!
14//! - **Eight-bit samples are signed.** The exact inverse of WAV's unsigned
15//!   convention, and not negotiable: it is what the two specifications say.
16//!   Getting it wrong offsets the audio by half full scale. See
17//!   [`SampleFormat::I8`]. The one exception is AIFF-C's `raw `, which names
18//!   offset-binary unsigned 8-bit and is [`SampleFormat::U8`].
19//! - **The sample rate is an 80-bit IEEE 754 extended-precision float.** Sign
20//!   bit, 15-bit exponent, and a 64-bit significand whose integer bit is
21//!   explicit, unlike a double's. No Rust primitive holds it, so it is parsed
22//!   by hand in [`extended_to_f64`]. Rates are integers in practice and the
23//!   field is a float regardless; the parser handles fractional values
24//!   correctly and the reader then rejects a non-integral rate with a typed
25//!   error rather than rounding it, because a rounded rate is a wrong rate
26//!   delivered silently.
27//! - **`sowt` is little-endian data inside a big-endian container.** AIFF-C
28//!   names its encoding in a compression four-CC: `NONE` and `twos` are
29//!   big-endian two's complement, and `sowt`, `twos` spelled backwards, is
30//!   little-endian, which Apple used heavily. The container's byte order says
31//!   nothing about the payload's.
32//! - **`SSND` does not start with samples.** Its body opens with two 32-bit
33//!   fields, `offset` and `blockSize`, and the sample data begins `offset`
34//!   bytes after them. Both are almost always zero, which is exactly why a
35//!   parser that ignores them passes every test until it meets a file where
36//!   they are not.
37//! - **There are two sources of truth for length.** `COMM` declares
38//!   `numSampleFrames` and `SSND` has a chunk size, and they can disagree.
39//!   This reader requires them to agree exactly and answers a typed error
40//!   when they do not: [`DecodeError::Truncated`] when `SSND` holds fewer
41//!   bytes than the declared frames need, [`DecodeError::Malformed`] when it
42//!   holds more. Silently preferring either source is how audio gets
43//!   truncated or extended without anybody noticing, which is the failure
44//!   class this crate exists to avoid.
45//!
46//! # Dispatch is on the form type and the compression four-CC
47//!
48//! A `FORM` of type `AIFF` is uncompressed big-endian PCM by definition; a
49//! `FORM` of type `AIFC` names its encoding in `COMM`'s compression type.
50//! `alaw`/`ALAW` and `ulaw`/`ULAW` dispatch to the same G.711 tables WAV uses;
51//! `fl32`/`FL32` and `fl64`/`FL64` are IEEE float; `raw ` is unsigned 8-bit
52//! linear PCM. Every other compression type (`ima4`, `MAC3`, `MAC6`, `QDMC`
53//! and the rest) is [`DecodeError::UnsupportedCodec`], reported as the
54//! four-CC it was. Nothing anywhere looks at a file name.
55//!
56//! For the linear widths, dispatch is on the **(compression, sampleSize)
57//! pair**, the same rule as WAV's `(tag, bits)`: `NONE` covers four widths and
58//! reading one at another's stride produces noise rather than an error. The
59//! companded types are the exception, deliberately: G.711's wire stride is one
60//! byte whatever `sampleSize` claims, and AIFF-C writers disagree about
61//! whether the field should carry 8 (the wire width) or 16 (the decoded
62//! width), so for `alaw` and `ulaw` the field is recorded and not dispatched
63//! on.
64//!
65//! # A size in a file is a claim, not a fact
66//!
67//! The same discipline as [`wav`](crate::wav): malformed input is a typed
68//! [`DecodeError`], never a panic, and no allocation is proportional to a
69//! declared size. The streaming reader buffers chunk headers, the `COMM` body
70//! (capped at [`MAX_COMM_BYTES`], the format's own ceiling) and `SSND`'s
71//! eight-byte prefix, and nothing else. All chunk arithmetic is 64-bit and
72//! checked.
73//!
74//! # Two readers, and the one difference between them
75//!
76//! [`AiffReader`] holds the whole file and accepts `COMM` and `SSND` in
77//! either order. [`AiffStreamDecoder`] requires `COMM` first, for the reason
78//! recorded on [`WavStreamDecoder`](crate::WavStreamDecoder): a payload that
79//! arrives before the header describing it would have to be buffered in full,
80//! and an unbounded buffer is the thing the streaming reader exists to avoid.
81//! A file that opens fine can therefore fail when streamed; that is forced by
82//! streaming, not chosen.
83
84use crate::audio::{AudioBuffer, AudioSpec};
85use crate::codec::{CodecId, FourCc};
86use crate::error::DecodeError;
87use crate::g711::G711Law;
88use crate::payload::Payload;
89use crate::riff::{self, ByteOrder, ChunkWalker};
90use crate::sample::SampleFormat;
91use crate::source::StreamSource;
92
93/// The magic of every EA IFF 85 file.
94///
95/// Visible to the crate because [`probe`](crate::probe) has to tell a `FORM`
96/// that is an AIFF from one that is an `8SVX`, and the three form four-CCs are
97/// written down once for both readers of them.
98pub(crate) const FORM: FourCc = FourCc(*b"FORM");
99
100/// The form type of a plain AIFF file: uncompressed big-endian PCM.
101pub(crate) const AIFF: FourCc = FourCc(*b"AIFF");
102
103/// The form type of an AIFF-C file: the encoding is in `COMM`.
104pub(crate) const AIFC: FourCc = FourCc(*b"AIFC");
105
106/// The chunk describing the payload: channels, frames, width, rate and, in
107/// AIFF-C, the compression type.
108const COMM: FourCc = FourCc(*b"COMM");
109
110/// The chunk carrying the payload, behind its `offset` and `blockSize`
111/// fields.
112const SSND: FourCc = FourCc(*b"SSND");
113
114/// AIFF-C's `FVER` chunk. The *readers* deliberately treat it as unknown,
115/// read past rather than validated, because it has carried the same timestamp
116/// since 1991 and a file whose audio parses is not worth rejecting over a
117/// bookkeeping field. The writer writes it, because the AIFF-C specification
118/// requires one and omitting it costs compatibility for nothing.
119const FVER: FourCc = FourCc(*b"FVER");
120
121/// The one `FVER` version timestamp that has ever existed: AIFC Version 1,
122/// May 23, 1990, as an Apple timestamp.
123const FVER_TIMESTAMP: u32 = 0xA280_5140;
124
125/// `NONE`: uncompressed big-endian two's-complement PCM.
126const NONE: FourCc = FourCc(*b"NONE");
127
128/// `twos`: the same thing `NONE` is, under the name QuickTime gave it.
129const TWOS: FourCc = FourCc(*b"twos");
130
131/// `sowt`: `twos` backwards, and little-endian two's-complement PCM.
132const SOWT: FourCc = FourCc(*b"sowt");
133
134/// `raw `: offset-binary, meaning unsigned, 8-bit linear PCM. The trailing
135/// space is part of the four-CC.
136const RAW: FourCc = FourCc(*b"raw ");
137
138/// The two spellings of IEEE 754 binary32.
139const FL32: [FourCc; 2] = [FourCc(*b"fl32"), FourCc(*b"FL32")];
140
141/// The two spellings of IEEE 754 binary64.
142const FL64: [FourCc; 2] = [FourCc(*b"fl64"), FourCc(*b"FL64")];
143
144/// The two spellings of G.711 A-law.
145const ALAW: [FourCc; 2] = [FourCc(*b"alaw"), FourCc(*b"ALAW")];
146
147/// The two spellings of G.711 mu-law.
148const ULAW: [FourCc; 2] = [FourCc(*b"ulaw"), FourCc(*b"ULAW")];
149
150/// The largest channel count `COMM`'s `numChannels` can state.
151///
152/// The field is a signed 16-bit integer, so 32,768 and above are negative
153/// numbers when read as the specification defines them. This crate's reader
154/// reads the field unsigned and accepts what it finds; the writer will not
155/// produce one.
156const MAX_WRITABLE_CHANNELS: u16 = i16::MAX as u16;
157
158/// The `COMM` body a plain AIFF file carries: channels, frames, width, rate.
159const COMM_BYTES_AIFF: u64 = 18;
160
161/// The smallest `COMM` body an AIFF-C file can carry: the AIFF fields plus
162/// the compression four-CC.
163///
164/// The specification also requires a compressionName pascal string after the
165/// four-CC, but writers that omit it entirely exist and the audio in their
166/// files is complete, so a 22-byte body is read rather than rejected.
167const COMM_BYTES_AIFC: u64 = 22;
168
169/// The largest `COMM` body this crate will read.
170///
171/// The format's own ceiling rather than a number picked here: the
172/// compressionName is a pascal string whose length byte bounds it at 255
173/// characters, padded to an even total, so 22 + 256 is the most a conforming
174/// `COMM` can occupy. It matters because `COMM` is the one chunk body the
175/// streaming reader buffers rather than skips, so its declared size governs a
176/// buffer.
177const MAX_COMM_BYTES: u64 = COMM_BYTES_AIFC + 256;
178
179/// The two fields at the start of every `SSND` body, before `offset` bytes of
180/// alignment padding and then the sample data.
181const SSND_PREFIX_BYTES: u64 = 8;
182
183/// How many decoded samples the streaming reader holds before it stops taking
184/// bytes. The same figure, for the same reason, as every other bounded reader
185/// in the crate.
186const READY_LIMIT: usize = 65_536;
187
188// -- The 80-bit extended-precision sample rate --------------------------------
189
190/// Parses the 80-bit IEEE 754 extended-precision float `COMM` stores its
191/// sample rate in.
192///
193/// Sign bit, 15-bit exponent biased by 16383, then a 64-bit significand whose
194/// integer bit is **explicit**, unlike a double, where it is implied. The
195/// value is `(-1)^sign * significand * 2^(exponent - 16383 - 63)`.
196///
197/// The conversion is exact wherever `f64` can hold the answer: the
198/// significand-to-`f64` conversion rounds to nearest (ties to even) only when
199/// more than 53 bits are set, and the scaling multiplies by exact powers of
200/// two. Values beyond `f64`'s range become infinity or zero, which the caller
201/// rejects the same way it rejects any other impossible rate. Deterministic
202/// on every target: nothing here depends on the platform's `long double`.
203fn extended_to_f64(bytes: [u8; 10]) -> f64 {
204    let negative = bytes[0] & 0x80 != 0;
205    let exponent = (u16::from(bytes[0] & 0x7F) << 8) | u16::from(bytes[1]);
206    let significand = u64::from_be_bytes([
207        bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7], bytes[8], bytes[9],
208    ]);
209    let sign = if negative { -1.0 } else { 1.0 };
210
211    if exponent == 0x7FFF {
212        // Infinity when the fraction below the integer bit is clear, NaN
213        // otherwise. Neither is a rate, and the caller says so.
214        return if significand << 1 == 0 {
215            sign * f64::INFINITY
216        } else {
217            f64::NAN
218        };
219    }
220    if significand == 0 {
221        return sign * 0.0;
222    }
223    // A zero exponent with a non-zero significand is the denormal range,
224    // whose values are 2^-16446 at the largest: zero in f64 and zero as a
225    // sample rate. The `max(1)` gives them the exponent the format defines
226    // for them and the scaling below underflows them to zero deterministically.
227    let shift = i32::from(exponent.max(1)) - 16383 - 63;
228    sign * scale_by_power_of_two(significand as f64, shift)
229}
230
231/// `value * 2^shift`, for shifts far beyond what a single `f64` multiply can
232/// express.
233///
234/// Stepping by at most 1000 keeps every intermediate scale factor a normal,
235/// exactly-representable power of two, so each multiplication is exact until
236/// the result itself overflows to infinity or underflows to zero, both of
237/// which are the correct destination for an 80-bit exponent `f64` cannot
238/// hold.
239fn scale_by_power_of_two(value: f64, shift: i32) -> f64 {
240    const STEP: i32 = 1000;
241    let mut value = value;
242    let mut shift = shift;
243    while shift != 0 && value != 0.0 && value.is_finite() {
244        let step = shift.clamp(-STEP, STEP);
245        // 2^step as bits: biased exponent in the top eleven bits of an f64.
246        value *= f64::from_bits(((step + 1023) as u64) << 52);
247        shift -= step;
248    }
249    value
250}
251
252/// The declared rate as the `u32` an [`AudioSpec`] carries, or a typed
253/// rejection.
254///
255/// A rate of zero, a negative rate, infinity, NaN, a fraction and a value
256/// past `u32::MAX` are all rejected with [`DecodeError::Malformed`] naming
257/// the field's offset. Rounding a fractional rate instead would deliver a
258/// wrong rate silently, which is the exact failure [`AudioSpec`] exists to
259/// prevent; no real writer produces one, so the rejection costs nothing.
260fn rate_to_spec_rate(rate: f64, offset: u64) -> Result<u32, DecodeError> {
261    // NaN fails the first two comparisons and differs from its own
262    // truncation, so it takes the same door as every other impossible rate.
263    if rate < 1.0 || rate > f64::from(u32::MAX) || rate != rate.trunc() {
264        return Err(DecodeError::Malformed {
265            expected: "a positive integral sample rate that fits in 32 bits",
266            offset,
267        });
268    }
269    Ok(rate as u32)
270}
271
272/// Encodes an integer sample rate as the 80-bit extended-precision float
273/// `COMM` stores.
274///
275/// The encode half of [`extended_to_f64`]: sign bit clear, the exponent
276/// biased by 16383, and the significand normalised so its **explicit**
277/// integer bit, the bit a double leaves implied, is set. Normalising means
278/// shifting the rate's leading one up to bit 63 and recording how far below
279/// 63 it started, so every non-zero `u32` is represented exactly: the
280/// significand holds the rate's own bits and nothing is rounded. `rate` is
281/// never zero here, since the writer rejects a zero rate before encoding it,
282/// and zero is the one value this normalisation cannot spell.
283fn rate_to_extended(rate: u32) -> [u8; 10] {
284    debug_assert_ne!(rate, 0, "a zero rate has no normalised form");
285    let high_bit = 31 - rate.leading_zeros();
286    let exponent = 16383 + high_bit as u16;
287    let significand = u64::from(rate) << (63 - high_bit);
288    let mut bytes = [0u8; 10];
289    bytes[0] = (exponent >> 8) as u8;
290    bytes[1] = exponent as u8;
291    bytes[2..].copy_from_slice(&significand.to_be_bytes());
292    bytes
293}
294
295// -- What an AIFF file can carry ----------------------------------------------
296
297/// Which of the two form types the file declared.
298///
299/// `#[non_exhaustive]` for the same reason the other container enums are: a
300/// consumer matching on it keeps a `_` arm.
301#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
302#[non_exhaustive]
303pub enum AiffForm {
304    /// A plain `AIFF` form: uncompressed big-endian PCM, no compression
305    /// field.
306    Aiff,
307    /// An `AIFC` form: the encoding is named by `COMM`'s compression four-CC.
308    Aifc,
309}
310
311/// An encoding an AIFF or AIFF-C file can carry and this crate can decode.
312///
313/// The variants are exactly the `(compression, sampleSize)` pairs this crate
314/// reads, the same shape as [`WavCodec`](crate::WavCodec) and for the same
315/// reason: a type that carried an arbitrary [`SampleFormat`] could name files
316/// that cannot exist. The three `...Sowt` variants are the same integer widths
317/// as their big-endian twins with the bytes the other way round: `sowt` data
318/// inside the big-endian container.
319///
320/// `#[non_exhaustive]`: a consumer matching on it needs a `_` arm.
321#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
322#[non_exhaustive]
323pub enum AiffCodec {
324    /// Signed 8-bit PCM, signed unlike WAV's. `NONE`, `twos` or `sowt` at
325    /// 8 bits: one byte has no byte order.
326    PcmI8,
327    /// Unsigned 8-bit PCM, offset binary. `raw ` at 8 bits, which the
328    /// compression field makes an AIFF-C encoding only. The same convention
329    /// WAV's 8-bit carries, under a four-CC that names it explicitly rather
330    /// than the implicit signedness of `NONE`.
331    PcmU8,
332    /// Signed 16-bit big-endian PCM. `NONE` or `twos` at 16 bits.
333    PcmI16,
334    /// Signed 24-bit big-endian PCM. `NONE` or `twos` at 24 bits.
335    PcmI24,
336    /// Signed 32-bit big-endian PCM. `NONE` or `twos` at 32 bits.
337    PcmI32,
338    /// Signed 16-bit **little-endian** PCM. `sowt` at 16 bits.
339    PcmI16Sowt,
340    /// Signed 24-bit **little-endian** PCM. `sowt` at 24 bits.
341    PcmI24Sowt,
342    /// Signed 32-bit **little-endian** PCM. `sowt` at 32 bits.
343    PcmI32Sowt,
344    /// IEEE 754 binary32, big-endian. `fl32` or `FL32`.
345    Float32,
346    /// IEEE 754 binary64, big-endian. `fl64` or `FL64`.
347    Float64,
348    /// ITU-T G.711 A-law. `alaw` or `ALAW`.
349    ALaw,
350    /// ITU-T G.711 mu-law. `ulaw` or `ULAW`.
351    MuLaw,
352}
353
354impl AiffCodec {
355    /// The encoding a `(compression, sampleSize)` pair names.
356    ///
357    /// A plain `AIFF` form has no compression field; its `NONE` is implicit,
358    /// and the `COMM` parser passes it explicitly so a width rejection can
359    /// name it. That is also what confines the compression-only encodings to
360    /// `AIFC`: a plain `AIFF` form resolves as `NONE` whatever bytes follow
361    /// the four fixed `COMM` fields, so `raw `, `sowt`, the floats and G.711
362    /// are reachable from an `AIFC` form and from no other.
363    ///
364    /// For the linear types the dispatch is on the pair, never the four-CC
365    /// alone. `NONE` covers four widths, and decoding one at another's
366    /// stride is noise rather than an error. For the companded types the
367    /// four-CC alone decides: G.711's wire stride is one byte whatever
368    /// `sampleSize` says, and real writers put both 8 and 16 in the field.
369    ///
370    /// ```
371    /// use decibri_decode::{AiffCodec, FourCc};
372    ///
373    /// assert_eq!(AiffCodec::resolve(FourCc(*b"NONE"), 24).unwrap(), AiffCodec::PcmI24);
374    /// assert_eq!(AiffCodec::resolve(FourCc(*b"sowt"), 16).unwrap(), AiffCodec::PcmI16Sowt);
375    /// // `raw ` is unsigned 8-bit, and only at 8 bits.
376    /// assert_eq!(AiffCodec::resolve(FourCc(*b"raw "), 8).unwrap(), AiffCodec::PcmU8);
377    /// assert!(AiffCodec::resolve(FourCc(*b"raw "), 16).is_err());
378    /// // Same compression, unsupported width: rejected, and it says which.
379    /// assert!(AiffCodec::resolve(FourCc(*b"NONE"), 20).is_err());
380    /// ```
381    ///
382    /// # Errors
383    ///
384    /// [`DecodeError::UnsupportedSampleFormat`] for a carried compression
385    /// type at a width this crate does not read, and
386    /// [`DecodeError::UnsupportedCodec`] for a compression type it does not
387    /// carry at all, `ima4`, `MAC3` and the rest.
388    pub fn resolve(compression: FourCc, bits_per_sample: u16) -> Result<Self, DecodeError> {
389        if compression == NONE || compression == TWOS || compression == SOWT {
390            let sowt = compression == SOWT;
391            return match (bits_per_sample, sowt) {
392                (8, _) => Ok(Self::PcmI8),
393                (16, false) => Ok(Self::PcmI16),
394                (24, false) => Ok(Self::PcmI24),
395                (32, false) => Ok(Self::PcmI32),
396                (16, true) => Ok(Self::PcmI16Sowt),
397                (24, true) => Ok(Self::PcmI24Sowt),
398                (32, true) => Ok(Self::PcmI32Sowt),
399                _ => Err(DecodeError::UnsupportedSampleFormat {
400                    format: CodecId::FourCc(compression),
401                    bits_per_sample,
402                }),
403            };
404        }
405        if compression == RAW {
406            return if bits_per_sample == 8 {
407                Ok(Self::PcmU8)
408            } else {
409                Err(DecodeError::UnsupportedSampleFormat {
410                    format: CodecId::FourCc(compression),
411                    bits_per_sample,
412                })
413            };
414        }
415        if FL32.contains(&compression) {
416            return if bits_per_sample == 32 {
417                Ok(Self::Float32)
418            } else {
419                Err(DecodeError::UnsupportedSampleFormat {
420                    format: CodecId::FourCc(compression),
421                    bits_per_sample,
422                })
423            };
424        }
425        if FL64.contains(&compression) {
426            return if bits_per_sample == 64 {
427                Ok(Self::Float64)
428            } else {
429                Err(DecodeError::UnsupportedSampleFormat {
430                    format: CodecId::FourCc(compression),
431                    bits_per_sample,
432                })
433            };
434        }
435        if ALAW.contains(&compression) {
436            return Ok(Self::ALaw);
437        }
438        if ULAW.contains(&compression) {
439            return Ok(Self::MuLaw);
440        }
441        Err(DecodeError::UnsupportedCodec {
442            codec: CodecId::FourCc(compression),
443        })
444    }
445
446    /// How many bytes one sample occupies in the payload.
447    pub const fn bytes_per_sample(self) -> usize {
448        match self {
449            Self::PcmI8 | Self::PcmU8 | Self::ALaw | Self::MuLaw => 1,
450            Self::PcmI16 | Self::PcmI16Sowt => 2,
451            Self::PcmI24 | Self::PcmI24Sowt => 3,
452            Self::PcmI32 | Self::PcmI32Sowt | Self::Float32 => 4,
453            Self::Float64 => 8,
454        }
455    }
456
457    /// The linear PCM format this encoding is, or `None` for the companded
458    /// ones.
459    pub const fn sample_format(self) -> Option<SampleFormat> {
460        match self {
461            Self::PcmI8 => Some(SampleFormat::I8),
462            Self::PcmU8 => Some(SampleFormat::U8),
463            Self::PcmI16 => Some(SampleFormat::I16Be),
464            Self::PcmI24 => Some(SampleFormat::I24Be),
465            Self::PcmI32 => Some(SampleFormat::I32Be),
466            Self::PcmI16Sowt => Some(SampleFormat::I16Le),
467            Self::PcmI24Sowt => Some(SampleFormat::I24Le),
468            Self::PcmI32Sowt => Some(SampleFormat::I32Le),
469            Self::Float32 => Some(SampleFormat::F32Be),
470            Self::Float64 => Some(SampleFormat::F64Be),
471            Self::ALaw | Self::MuLaw => None,
472        }
473    }
474
475    /// The G.711 companding law this encoding is, or `None` for the linear
476    /// ones.
477    pub const fn law(self) -> Option<G711Law> {
478        match self {
479            Self::ALaw => Some(G711Law::ALaw),
480            Self::MuLaw => Some(G711Law::MuLaw),
481            _ => None,
482        }
483    }
484
485    /// The `sampleSize` a file written with this encoding declares.
486    ///
487    /// For the linear and float types this is the real sample width. For the
488    /// companded types it is 16, the decoded width, which is how the AIFF-C
489    /// specification's compression registry describes G.711, while the wire
490    /// stride stays one byte. Real writers put both 8 and 16 in the field and
491    /// the readers here dispatch on the four-CC alone, so either spelling
492    /// reads back; 16 is written because it is the specification's own.
493    pub const fn bits_per_sample(self) -> u16 {
494        match self {
495            Self::PcmI8 | Self::PcmU8 => 8,
496            Self::PcmI16 | Self::PcmI16Sowt | Self::ALaw | Self::MuLaw => 16,
497            Self::PcmI24 | Self::PcmI24Sowt => 24,
498            Self::PcmI32 | Self::PcmI32Sowt | Self::Float32 => 32,
499            Self::Float64 => 64,
500        }
501    }
502
503    /// The compression four-CC a written AIFF-C file carrying this encoding
504    /// declares.
505    ///
506    /// One canonical spelling per encoding: the readers accept `twos` for
507    /// big-endian PCM and the uppercase float and G.711 spellings as well,
508    /// but a writer that varied its spelling would produce two different
509    /// files for one encoding, and determinism is the crate's first claim.
510    /// The big-endian PCM types answer `NONE`, which is also what a plain
511    /// `AIFF` form means implicitly. See [`form`](Self::form) for why those
512    /// types are not written as `AIFC` at all.
513    pub const fn compression_type(self) -> FourCc {
514        match self {
515            Self::PcmI8 | Self::PcmI16 | Self::PcmI24 | Self::PcmI32 => NONE,
516            Self::PcmU8 => RAW,
517            Self::PcmI16Sowt | Self::PcmI24Sowt | Self::PcmI32Sowt => SOWT,
518            Self::Float32 => FL32[0],
519            Self::Float64 => FL64[0],
520            Self::ALaw => ALAW[0],
521            Self::MuLaw => ULAW[0],
522        }
523    }
524
525    /// The form type a file written with this encoding uses.
526    ///
527    /// This is the writer's whole selection rule: plain `AIFF` carries only
528    /// uncompressed big-endian two's-complement PCM, so the four codecs that
529    /// *are* that, [`PcmI8`](Self::PcmI8) through [`PcmI32`](Self::PcmI32),
530    /// are written as plain `AIFF`, the more widely readable of the two
531    /// forms. Everything else, `raw `, `sowt`, the floats and G.711, needs
532    /// the compression field that only `AIFC` has, and is written as `AIFC`
533    /// with the `FVER` chunk the specification requires.
534    pub const fn form(self) -> AiffForm {
535        match self {
536            Self::PcmI8 | Self::PcmI16 | Self::PcmI24 | Self::PcmI32 => AiffForm::Aiff,
537            Self::PcmU8
538            | Self::PcmI16Sowt
539            | Self::PcmI24Sowt
540            | Self::PcmI32Sowt
541            | Self::Float32
542            | Self::Float64
543            | Self::ALaw
544            | Self::MuLaw => AiffForm::Aifc,
545        }
546    }
547
548    /// Appends every whole sample in `bytes` to `output`, and returns how
549    /// many it appended.
550    ///
551    /// Straight through to [`SampleFormat::decode`] or [`G711Law::decode`]:
552    /// there is no AIFF-specific conversion anywhere in this crate, so the
553    /// same payload decoded through this container and through WAV gives the
554    /// same samples by construction rather than by agreement.
555    pub fn decode(self, bytes: &[u8], output: &mut Vec<f32>) -> usize {
556        match (self.sample_format(), self.law()) {
557            (Some(format), _) => format.decode(bytes, output),
558            (_, Some(law)) => law.decode(bytes, output),
559            // Unreachable: every variant is one or the other.
560            _ => 0,
561        }
562    }
563
564    /// Appends `samples` to `output` in this encoding, and returns how many
565    /// bytes it appended.
566    ///
567    /// The encode half of [`decode`](Self::decode), through the same two
568    /// layers, so the writer cannot have a conversion the reader lacks.
569    pub fn encode(self, samples: &[f32], output: &mut Vec<u8>) -> usize {
570        match (self.sample_format(), self.law()) {
571            (Some(format), _) => format.encode(samples, output),
572            (_, Some(law)) => law.encode(samples, output),
573            _ => 0,
574        }
575    }
576}
577
578/// A resolved `COMM` chunk: what the file declared, and what it resolved to.
579#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
580#[non_exhaustive]
581pub struct AiffFormat {
582    /// The rate and layout the payload decodes to.
583    pub spec: AudioSpec,
584    /// What the payload is encoded as, from the form type, the compression
585    /// four-CC and `sampleSize`.
586    pub codec: AiffCodec,
587    /// Which form type the file declared: `AIFF` or `AIFC`.
588    pub form: AiffForm,
589    /// The compression four-CC exactly as declared, `NONE` for a plain
590    /// `AIFF` form, which has no field to read it from.
591    pub compression: FourCc,
592    /// `sampleSize` as declared.
593    ///
594    /// For the companded types this is recorded and not dispatched on:
595    /// writers put both the wire width and the decoded width here, and the
596    /// stride is one byte either way.
597    pub bits_per_sample: u16,
598    /// `numSampleFrames` as declared.
599    ///
600    /// Not advisory: the `SSND` chunk is required to hold exactly this many
601    /// frames, and a file where the two disagree is rejected rather than
602    /// silently resolved in either direction.
603    pub sample_frames: u32,
604}
605
606impl AiffFormat {
607    /// How many bytes one whole frame occupies in the payload.
608    ///
609    /// At least one: the channel count is rejected at zero, so this never
610    /// divides by nothing.
611    pub const fn frame_bytes(&self) -> usize {
612        self.spec.channels as usize * self.codec.bytes_per_sample()
613    }
614
615    /// How many bytes of sample data `numSampleFrames` requires.
616    fn data_bytes(&self) -> u64 {
617        u64::from(self.sample_frames) * self.frame_bytes() as u64
618    }
619}
620
621// -- Reading the `COMM` chunk -------------------------------------------------
622
623/// Rejects a `COMM` chunk whose declared size the format cannot mean.
624///
625/// Called on both paths with the same numbers so the whole-file and streaming
626/// readers agree: on the whole-file path the body is already bounded by the
627/// input, and on the streaming path this is what bounds the buffer.
628fn check_comm_size(form: AiffForm, size: u64, offset: u64) -> Result<(), DecodeError> {
629    let minimum = match form {
630        AiffForm::Aiff => COMM_BYTES_AIFF,
631        AiffForm::Aifc => COMM_BYTES_AIFC,
632    };
633    if size < minimum {
634        return Err(DecodeError::Malformed {
635            expected: "a COMM chunk of at least 18 bytes, 22 in AIFF-C",
636            offset,
637        });
638    }
639    if size > MAX_COMM_BYTES {
640        return Err(DecodeError::Malformed {
641            expected: "a COMM chunk of at most 278 bytes, which is all a compressionName can need",
642            offset,
643        });
644    }
645    Ok(())
646}
647
648/// Reads a `COMM` chunk body that has already been checked with
649/// [`check_comm_size`].
650///
651/// `offset` is where the chunk *header* sits in the input, so the offsets in
652/// any [`DecodeError::Malformed`] this returns are absolute.
653fn parse_comm(body: &[u8], offset: u64, form: AiffForm) -> Result<AiffFormat, DecodeError> {
654    let body_at = offset + riff::CHUNK_HEADER_BYTES;
655    let (Some(channels), Some(sample_frames), Some(bits_per_sample), Some(rate_field)) = (
656        riff::u16_be_at(body, 0),
657        riff::u32_be_at(body, 2),
658        riff::u16_be_at(body, 6),
659        body.get(8..18),
660    ) else {
661        return Err(DecodeError::Malformed {
662            expected: "a COMM chunk of at least 18 bytes, 22 in AIFF-C",
663            offset,
664        });
665    };
666
667    if channels == 0 {
668        return Err(DecodeError::UnsupportedChannelLayout { channels });
669    }
670    let mut rate_bytes = [0u8; 10];
671    rate_bytes.copy_from_slice(rate_field);
672    let sample_rate = rate_to_spec_rate(extended_to_f64(rate_bytes), body_at + 8)?;
673
674    let compression = match form {
675        AiffForm::Aiff => NONE,
676        AiffForm::Aifc => {
677            let Some(compression) = riff::four_cc_at(body, 18) else {
678                return Err(DecodeError::Malformed {
679                    expected: "a COMM chunk of at least 18 bytes, 22 in AIFF-C",
680                    offset,
681                });
682            };
683            // The compressionName pascal string: a length byte, that many
684            // characters, padded to an even total. It is the last field in
685            // the chunk, so nothing needs its value, but a length byte
686            // counting past the chunk's end is a miscounted chunk, and a
687            // parser that shrugged here would be trusting a length it never
688            // checked.
689            if let Some(&name_len) = body.get(22) {
690                if 23 + usize::from(name_len) > body.len() {
691                    return Err(DecodeError::Malformed {
692                        expected: "a compressionName that fits its COMM chunk",
693                        offset: body_at + 22,
694                    });
695                }
696            }
697            compression
698        }
699    };
700
701    Ok(AiffFormat {
702        spec: AudioSpec::new(sample_rate, channels),
703        codec: AiffCodec::resolve(compression, bits_per_sample)?,
704        form,
705        compression,
706        bits_per_sample,
707        sample_frames,
708    })
709}
710
711/// Reads the twelve-byte `FORM` header and answers which form type it is.
712///
713/// # Errors
714///
715/// [`DecodeError::Truncated`] for an input shorter than twelve bytes, and
716/// [`DecodeError::UnsupportedContainer`] naming the bytes seen for a magic
717/// that is not `FORM` or a form type that is neither `AIFF` nor `AIFC`.
718fn read_form_header(bytes: &[u8]) -> Result<AiffForm, DecodeError> {
719    let (Some(magic), Some(form)) = (riff::four_cc_at(bytes, 0), riff::four_cc_at(bytes, 8)) else {
720        return Err(DecodeError::Truncated {
721            expected: riff::HEADER_BYTES,
722            available: bytes.len() as u64,
723        });
724    };
725    if magic != FORM {
726        return Err(DecodeError::UnsupportedContainer { tag: magic });
727    }
728    match form {
729        _ if form == AIFF => Ok(AiffForm::Aiff),
730        _ if form == AIFC => Ok(AiffForm::Aifc),
731        _ => Err(DecodeError::UnsupportedContainer { tag: form }),
732    }
733}
734
735/// Validates an `SSND` body against the `COMM` that describes it, and returns
736/// the sample data region's start within the body.
737///
738/// This is where the two sources of truth meet. `available` is what the chunk
739/// actually holds past its prefix and its `offset` padding; `needed` is what
740/// `numSampleFrames` requires. They must be equal: fewer is
741/// [`DecodeError::Truncated`] naming both numbers, more is
742/// [`DecodeError::Malformed`], and neither is silently resolved.
743fn check_ssnd(
744    format: &AiffFormat,
745    body_len: u64,
746    data_offset: u32,
747    chunk_offset: u64,
748) -> Result<(), DecodeError> {
749    if body_len < SSND_PREFIX_BYTES {
750        return Err(DecodeError::Malformed {
751            expected: "an SSND chunk of at least 8 bytes",
752            offset: chunk_offset,
753        });
754    }
755    // u64 throughout: offset is a u32 the file chose, and adding it to the
756    // prefix in u32 could wrap on a crafted value.
757    let data_start = SSND_PREFIX_BYTES + u64::from(data_offset);
758    if data_start > body_len {
759        return Err(DecodeError::Malformed {
760            expected: "an SSND offset that fits inside the SSND chunk",
761            offset: chunk_offset,
762        });
763    }
764    let available = body_len - data_start;
765    let needed = format.data_bytes();
766    if available < needed {
767        return Err(DecodeError::Truncated {
768            expected: needed,
769            available,
770        });
771    }
772    if available > needed {
773        return Err(DecodeError::Malformed {
774            expected: "an SSND chunk holding exactly numSampleFrames frames",
775            offset: chunk_offset,
776        });
777    }
778    Ok(())
779}
780
781// -- The whole-file reader ----------------------------------------------------
782
783/// An AIFF or AIFF-C file held whole in memory.
784///
785/// [`new`](Self::new) does all the parsing and all the rejecting; a reader
786/// that exists is a file that has been fully validated, which is why
787/// [`decode_to_end`](Self::decode_to_end) returns an [`AudioBuffer`] rather
788/// than a `Result`, the same property, for the same payload encodings, as
789/// [`WavReader`](crate::WavReader).
790///
791/// # Example
792///
793/// ```
794/// use decibri_decode::{AiffCodec, AiffReader, AudioSpec};
795///
796/// // A minimal AIFF built by hand: 8 kHz mono signed 8-bit, three frames.
797/// let mut file = Vec::new();
798/// file.extend_from_slice(b"FORM");
799/// file.extend_from_slice(&50u32.to_be_bytes());
800/// file.extend_from_slice(b"AIFF");
801/// file.extend_from_slice(b"COMM");
802/// file.extend_from_slice(&18u32.to_be_bytes());
803/// file.extend_from_slice(&1u16.to_be_bytes()); // channels
804/// file.extend_from_slice(&3u32.to_be_bytes()); // frames
805/// file.extend_from_slice(&8u16.to_be_bytes()); // bits
806/// // 8000 as an 80-bit extended float.
807/// file.extend_from_slice(&[0x40, 0x0B, 0xFA, 0, 0, 0, 0, 0, 0, 0]);
808/// file.extend_from_slice(b"SSND");
809/// file.extend_from_slice(&11u32.to_be_bytes());
810/// file.extend_from_slice(&[0; 8]); // offset, blockSize
811/// file.extend_from_slice(&[0x00, 0x40, 0x80]); // 0.0, 0.5, -1.0
812/// file.push(0); // the pad byte after an odd chunk
813///
814/// let reader = AiffReader::new(&file)?;
815/// assert_eq!(reader.format().codec, AiffCodec::PcmI8);
816/// assert_eq!(reader.spec(), AudioSpec::mono(8_000));
817/// assert_eq!(reader.frames(), 3);
818/// assert_eq!(reader.decode_to_end().samples(), [0.0, 0.5, -1.0]);
819/// # Ok::<(), decibri_decode::DecodeError>(())
820/// ```
821#[derive(Debug, Clone, Copy, PartialEq)]
822pub struct AiffReader<'a> {
823    format: AiffFormat,
824    data: &'a [u8],
825}
826
827impl<'a> AiffReader<'a> {
828    /// Parses `bytes` as an AIFF or AIFF-C file.
829    ///
830    /// `COMM` and `SSND` may arrive in either order and unknown chunks
831    /// anywhere are skipped, `FVER` included. The walk stops once both have
832    /// been found, so trailing chunks are not examined.
833    ///
834    /// **"Either order" includes `SSND` before `COMM`, which
835    /// [`AiffStreamDecoder`] cannot accept**: a file that opens here can
836    /// fail when streamed, for the reason recorded on the module.
837    ///
838    /// A file whose `COMM` declares zero frames may omit `SSND` entirely, as
839    /// the specification allows, and decodes to nothing.
840    ///
841    /// # Errors
842    ///
843    /// - [`DecodeError::Truncated`] for an input under twelve bytes, a chunk
844    ///   declaring more than the input holds, and an `SSND` holding fewer
845    ///   bytes than `numSampleFrames` requires.
846    /// - [`DecodeError::UnsupportedContainer`] for a magic that is not
847    ///   `FORM` and a form type that is neither `AIFF` nor `AIFC`.
848    /// - [`DecodeError::Malformed`] for a missing or structurally wrong
849    ///   `COMM`, a missing `SSND` when frames are declared, an `SSND` whose
850    ///   `offset` does not fit its chunk or which holds more than
851    ///   `numSampleFrames` requires, a zero or non-integral sample rate, and
852    ///   a compressionName that overruns its chunk.
853    /// - [`DecodeError::UnsupportedChannelLayout`] for a zero channel count.
854    /// - [`DecodeError::UnsupportedCodec`] and
855    ///   [`DecodeError::UnsupportedSampleFormat`] from
856    ///   [`AiffCodec::resolve`].
857    pub fn new(bytes: &'a [u8]) -> Result<Self, DecodeError> {
858        let form = read_form_header(bytes)?;
859
860        let mut walker = ChunkWalker::new(bytes, ByteOrder::Big);
861        let mut comm: Option<(AiffFormat, u64)> = None;
862        let mut ssnd: Option<(&[u8], u64)> = None;
863        while comm.is_none() || ssnd.is_none() {
864            let Some(chunk) = walker.next().transpose()? else {
865                break;
866            };
867            if chunk.id == COMM && comm.is_none() {
868                check_comm_size(form, chunk.body.len() as u64, chunk.offset)?;
869                comm = Some((parse_comm(chunk.body, chunk.offset, form)?, chunk.offset));
870            } else if chunk.id == SSND && ssnd.is_none() {
871                ssnd = Some((chunk.body, chunk.offset));
872            }
873        }
874
875        let Some((format, _)) = comm else {
876            return Err(DecodeError::Malformed {
877                expected: "a COMM chunk",
878                offset: riff::HEADER_BYTES,
879            });
880        };
881        let Some((body, chunk_offset)) = ssnd else {
882            // The specification lets a zero-frame file omit SSND, and a
883            // zero-frame file with no SSND holds exactly the audio it
884            // declares: none.
885            if format.sample_frames == 0 {
886                return Ok(Self { format, data: &[] });
887            }
888            return Err(DecodeError::Malformed {
889                expected: "an SSND chunk",
890                offset: riff::HEADER_BYTES,
891            });
892        };
893
894        let data_offset = riff::u32_be_at(body, 0).unwrap_or(0);
895        check_ssnd(&format, body.len() as u64, data_offset, chunk_offset)?;
896        let data_start = SSND_PREFIX_BYTES as usize + data_offset as usize;
897        Ok(Self {
898            format,
899            data: &body[data_start..],
900        })
901    }
902
903    /// What the `COMM` chunk declared and resolved to.
904    pub const fn format(&self) -> &AiffFormat {
905        &self.format
906    }
907
908    /// The rate and layout the payload decodes to.
909    pub const fn spec(&self) -> AudioSpec {
910        self.format.spec
911    }
912
913    /// The sample data, undecoded: the `SSND` body past its prefix and its
914    /// `offset` padding.
915    pub const fn data(&self) -> &'a [u8] {
916        self.data
917    }
918
919    /// How many whole frames the payload holds.
920    ///
921    /// Exact and doubly attested: the payload's real length was required to
922    /// equal `numSampleFrames * frame size` at parse time, so the declaration
923    /// and the bytes agree by construction.
924    pub const fn frames(&self) -> u64 {
925        self.data.len() as u64 / self.format.frame_bytes() as u64
926    }
927
928    /// Appends every interleaved sample of the payload to `output`, and
929    /// returns how many it appended.
930    ///
931    /// Interleaved samples, frames times channels, not the frames
932    /// [`frames`](Self::frames) counts.
933    pub fn decode(&self, output: &mut Vec<f32>) -> usize {
934        self.format.codec.decode(self.data, output)
935    }
936
937    /// Decodes the whole payload, bound to the spec that describes it.
938    ///
939    /// The reservation is from the payload's real length, never from a size
940    /// the file declared.
941    ///
942    /// The channel count of the returned buffer is never zero: a file
943    /// declaring none is refused by [`new`](Self::new) with
944    /// [`DecodeError::UnsupportedChannelLayout`].
945    pub fn decode_to_end(&self) -> AudioBuffer {
946        let mut samples =
947            Vec::with_capacity(self.data.len() / self.format.codec.bytes_per_sample());
948        self.decode(&mut samples);
949        AudioBuffer::from_samples(self.format.spec, samples)
950    }
951}
952
953// -- The streaming reader -----------------------------------------------------
954
955/// Where the streaming reader is in the file.
956#[derive(Debug, Clone, Copy, PartialEq, Eq)]
957enum State {
958    /// Waiting for the twelve-byte `FORM` header.
959    Form,
960    /// Waiting for an eight-byte chunk header.
961    ChunkHeader,
962    /// Buffering the body of the `COMM` chunk, the one body that has to be
963    /// read.
964    CommBody { size: usize, offset: u64 },
965    /// Buffering `SSND`'s eight-byte `offset`/`blockSize` prefix.
966    SsndPrefix { size: u64, offset: u64 },
967    /// Discarding the `offset` bytes of alignment padding before the sample
968    /// data. Nothing is buffered here.
969    SsndGap { size: u64, left: u64 },
970    /// Discarding the body of a chunk that does not have to be read.
971    Skip { size: u64, left: u64 },
972    /// Discarding the one pad byte after an odd-length chunk.
973    Pad,
974    /// Streaming the sample data.
975    Data,
976    /// Past the end of the audio. Everything after it is discarded.
977    Done,
978}
979
980/// Reads an AIFF or AIFF-C file that arrives in pieces.
981///
982/// The [`StreamSource`] half of this module, with the same shape and the same
983/// bounds as [`WavStreamDecoder`](crate::WavStreamDecoder): bytes are pushed
984/// in whatever sizes they turn up in, samples are pulled out, and nothing is
985/// buffered in proportion to a size the file declared. Chunk headers, the
986/// `COMM` body (capped at the format's own 278-byte ceiling) and `SSND`'s
987/// eight-byte prefix are buffered, every other chunk body is discarded as it
988/// flows past, and the payload decodes into a bounded ready buffer.
989///
990/// # `COMM` has to come first
991///
992/// [`AiffReader`] accepts `SSND` before `COMM`; this does not, and answers
993/// [`DecodeError::Malformed`] when it meets one, for the reason recorded on
994/// the module: decoding a payload that arrives before the header describing
995/// it would mean holding all of it. Every other chunk order, and unknown
996/// chunks in any position, are the same on both paths.
997///
998/// # Example
999///
1000/// ```
1001/// use decibri_decode::{AiffStreamDecoder, AudioSpec, StreamSource};
1002///
1003/// // The same minimal file as the `AiffReader` example.
1004/// let mut file = Vec::new();
1005/// file.extend_from_slice(b"FORM");
1006/// file.extend_from_slice(&50u32.to_be_bytes());
1007/// file.extend_from_slice(b"AIFF");
1008/// file.extend_from_slice(b"COMM");
1009/// file.extend_from_slice(&18u32.to_be_bytes());
1010/// file.extend_from_slice(&1u16.to_be_bytes());
1011/// file.extend_from_slice(&3u32.to_be_bytes());
1012/// file.extend_from_slice(&8u16.to_be_bytes());
1013/// file.extend_from_slice(&[0x40, 0x0B, 0xFA, 0, 0, 0, 0, 0, 0, 0]);
1014/// file.extend_from_slice(b"SSND");
1015/// file.extend_from_slice(&11u32.to_be_bytes());
1016/// file.extend_from_slice(&[0; 8]);
1017/// file.extend_from_slice(&[0x00, 0x40, 0x80]);
1018/// file.push(0);
1019///
1020/// let mut stream = AiffStreamDecoder::new();
1021/// let mut samples = Vec::new();
1022/// for piece in file.chunks(7) {
1023///     let mut offset = 0;
1024///     while offset < piece.len() {
1025///         offset += stream.push(&piece[offset..])?;
1026///         while stream.pull(&mut samples, usize::MAX)? > 0 {}
1027///     }
1028/// }
1029/// stream.finish(&mut samples)?;
1030///
1031/// assert_eq!(stream.spec(), Some(AudioSpec::mono(8_000)));
1032/// assert_eq!(samples, [0.0, 0.5, -1.0]);
1033/// # Ok::<(), decibri_decode::DecodeError>(())
1034/// ```
1035#[derive(Debug)]
1036pub struct AiffStreamDecoder {
1037    state: State,
1038    /// Bytes of a header, the `COMM` body or the `SSND` prefix that have not
1039    /// fully arrived. Bounded by [`MAX_COMM_BYTES`].
1040    pending: Vec<u8>,
1041    /// Byte offset of the next byte to arrive, for error reporting.
1042    offset: u64,
1043    /// The form type, once the header has arrived.
1044    form: Option<AiffForm>,
1045    format: Option<AiffFormat>,
1046    payload: Option<Payload>,
1047    /// Decoded samples not yet pulled, and how far into them the caller is.
1048    ready: Vec<f32>,
1049    ready_read: usize,
1050    /// The sample data's size, and how much of it is still to arrive.
1051    data_size: u64,
1052    data_left: u64,
1053    finished: bool,
1054}
1055
1056impl Default for AiffStreamDecoder {
1057    fn default() -> Self {
1058        Self::new()
1059    }
1060}
1061
1062impl AiffStreamDecoder {
1063    /// A reader waiting for the first byte of a file.
1064    pub fn new() -> Self {
1065        Self {
1066            state: State::Form,
1067            pending: Vec::new(),
1068            offset: 0,
1069            form: None,
1070            format: None,
1071            payload: None,
1072            ready: Vec::new(),
1073            ready_read: 0,
1074            data_size: 0,
1075            data_left: 0,
1076            finished: false,
1077        }
1078    }
1079
1080    /// What the `COMM` chunk declared, once it has arrived.
1081    pub const fn format(&self) -> Option<AiffFormat> {
1082        self.format
1083    }
1084
1085    /// How many interleaved samples are decoded and waiting to be pulled:
1086    /// frames times channels, which is the length a caller's output vector
1087    /// grows by when they are.
1088    ///
1089    /// Interleaved samples, not the frames [`pull`](StreamSource::pull)
1090    /// counts; the two figures differ by the channel count.
1091    pub fn ready_samples(&self) -> usize {
1092        self.ready.len() - self.ready_read
1093    }
1094
1095    /// Buffers `bytes` into `pending` until it holds `need` of them, and says
1096    /// whether it now does.
1097    fn accumulate(&mut self, bytes: &[u8], need: usize, taken: &mut usize) -> bool {
1098        let want = need.saturating_sub(self.pending.len()).min(bytes.len());
1099        self.pending.extend_from_slice(&bytes[..want]);
1100        *taken += want;
1101        self.offset += want as u64;
1102        self.pending.len() >= need
1103    }
1104
1105    /// Reads the twelve-byte `FORM` header out of `pending`.
1106    fn start_file(&mut self) -> Result<(), DecodeError> {
1107        self.form = Some(read_form_header(&self.pending)?);
1108        self.pending.clear();
1109        self.state = State::ChunkHeader;
1110        Ok(())
1111    }
1112
1113    /// Reads an eight-byte chunk header out of `pending` and decides what to
1114    /// do with the body.
1115    fn start_chunk(&mut self) -> Result<(), DecodeError> {
1116        let offset = self.offset - riff::CHUNK_HEADER_BYTES;
1117        let (Some(id), Some(declared)) = (
1118            riff::four_cc_at(&self.pending, 0),
1119            riff::u32_be_at(&self.pending, 4),
1120        ) else {
1121            return Err(DecodeError::Truncated {
1122                expected: riff::CHUNK_HEADER_BYTES,
1123                available: self.pending.len() as u64,
1124            });
1125        };
1126        self.pending.clear();
1127        let size = u64::from(declared);
1128        // Set at construction and at every header since, so this is always
1129        // present here; answered rather than unwrapped because a panic on
1130        // untrusted input is the failure class this crate refuses.
1131        let form = self.form.unwrap_or(AiffForm::Aiff);
1132
1133        if id == COMM && self.format.is_none() {
1134            check_comm_size(form, size, offset)?;
1135            self.state = State::CommBody {
1136                size: size as usize,
1137                offset,
1138            };
1139            return Ok(());
1140        }
1141
1142        if id == SSND {
1143            if self.format.is_none() {
1144                // The one thing the streaming path cannot do that the
1145                // whole-file path can.
1146                return Err(DecodeError::Malformed {
1147                    expected: "a COMM chunk before the SSND chunk",
1148                    offset,
1149                });
1150            }
1151            if size < SSND_PREFIX_BYTES {
1152                return Err(DecodeError::Malformed {
1153                    expected: "an SSND chunk of at least 8 bytes",
1154                    offset,
1155                });
1156            }
1157            self.state = State::SsndPrefix { size, offset };
1158            return Ok(());
1159        }
1160
1161        // FVER and every unknown chunk: skipped, on both paths alike.
1162        self.state = if size == 0 {
1163            State::ChunkHeader
1164        } else {
1165            State::Skip { size, left: size }
1166        };
1167        Ok(())
1168    }
1169
1170    /// Reads a buffered `COMM` body out of `pending`.
1171    fn finish_comm(&mut self, size: usize, offset: u64) -> Result<(), DecodeError> {
1172        let form = self.form.unwrap_or(AiffForm::Aiff);
1173        self.format = Some(parse_comm(&self.pending, offset, form)?);
1174        self.pending.clear();
1175        self.state = if riff::pad_len(size as u64) == 1 {
1176            State::Pad
1177        } else {
1178            State::ChunkHeader
1179        };
1180        Ok(())
1181    }
1182
1183    /// Reads `SSND`'s buffered eight-byte prefix out of `pending` and lines
1184    /// up the gap, the data and the decoder.
1185    fn finish_ssnd_prefix(&mut self, size: u64, offset: u64) -> Result<(), DecodeError> {
1186        let Some(format) = self.format else {
1187            // Guarded at start_chunk; kept as an answer rather than a panic.
1188            return Err(DecodeError::Malformed {
1189                expected: "a COMM chunk before the SSND chunk",
1190                offset,
1191            });
1192        };
1193        let data_offset = riff::u32_be_at(&self.pending, 0).unwrap_or(0);
1194        self.pending.clear();
1195        check_ssnd(&format, size, data_offset, offset)?;
1196
1197        self.payload = Some(Payload::from_parts(
1198            format.codec.sample_format(),
1199            format.codec.law(),
1200            format.spec,
1201        ));
1202        self.data_size = format.data_bytes();
1203        self.data_left = self.data_size;
1204
1205        let gap = u64::from(data_offset);
1206        self.state = if gap > 0 {
1207            State::SsndGap {
1208                size: gap,
1209                left: gap,
1210            }
1211        } else if self.data_size == 0 {
1212            State::Done
1213        } else {
1214            State::Data
1215        };
1216        Ok(())
1217    }
1218
1219    /// Moves decoded samples out of the payload decoder.
1220    fn drain_payload(&mut self) -> Result<(), DecodeError> {
1221        if let Some(payload) = self.payload.as_mut() {
1222            payload.decode(&mut self.ready)?;
1223        }
1224        Ok(())
1225    }
1226}
1227
1228impl StreamSource for AiffStreamDecoder {
1229    fn push(&mut self, bytes: &[u8]) -> Result<usize, DecodeError> {
1230        if self.finished {
1231            return Ok(0);
1232        }
1233        let mut taken = 0;
1234        let result = self.push_inner(bytes, &mut taken);
1235        if result.is_err() {
1236            // A stream that has failed structurally is over, for the reason
1237            // recorded on the WAV reader: a caller who keeps pushing must not
1238            // get a second, different answer from the same file.
1239            self.finished = true;
1240        }
1241        result.map(|()| taken)
1242    }
1243
1244    fn pull(&mut self, output: &mut Vec<f32>, max_frames: usize) -> Result<usize, DecodeError> {
1245        let Some(format) = self.format else {
1246            return Ok(0);
1247        };
1248        let channels = usize::from(format.spec.channels);
1249        let available = self.ready.len() - self.ready_read;
1250        let frames = (available / channels).min(max_frames);
1251        let count = frames * channels;
1252        output.extend_from_slice(&self.ready[self.ready_read..self.ready_read + count]);
1253        self.ready_read += count;
1254        // Amortised compaction, exactly as the WAV reader does it.
1255        if self.ready_read == self.ready.len() {
1256            self.ready.clear();
1257            self.ready_read = 0;
1258        } else if self.ready_read >= self.ready.len() / 2 {
1259            self.ready.drain(..self.ready_read);
1260            self.ready_read = 0;
1261        }
1262        Ok(frames)
1263    }
1264
1265    fn spec(&self) -> Option<AudioSpec> {
1266        self.format.map(|format| format.spec)
1267    }
1268
1269    fn buffered_bytes(&self) -> usize {
1270        self.pending.len()
1271            + self
1272                .payload
1273                .as_ref()
1274                .map_or(0, |payload| payload.buffered_bytes())
1275    }
1276
1277    fn finish(&mut self, output: &mut Vec<f32>) -> Result<usize, DecodeError> {
1278        if self.finished {
1279            return Ok(0);
1280        }
1281        self.finished = true;
1282
1283        // Structural completeness first: an item half-arrived is Truncated,
1284        // and a file that ended on a chunk boundary without carrying the
1285        // audio it declared is Malformed. The one clean early end is a
1286        // zero-frame file, whose SSND the specification lets it omit.
1287        match self.state {
1288            State::Done => {}
1289            State::ChunkHeader
1290                if self.pending.is_empty()
1291                    && self.format.is_some_and(|format| format.sample_frames == 0) => {}
1292            State::Form => {
1293                return Err(DecodeError::Truncated {
1294                    expected: riff::HEADER_BYTES,
1295                    available: self.pending.len() as u64,
1296                })
1297            }
1298            State::Pad | State::ChunkHeader if self.pending.is_empty() => {
1299                return Err(DecodeError::Malformed {
1300                    expected: if self.format.is_some() {
1301                        "an SSND chunk"
1302                    } else {
1303                        "a COMM chunk"
1304                    },
1305                    offset: self.offset,
1306                })
1307            }
1308            State::ChunkHeader | State::Pad => {
1309                return Err(DecodeError::Truncated {
1310                    expected: riff::CHUNK_HEADER_BYTES,
1311                    available: self.pending.len() as u64,
1312                })
1313            }
1314            State::CommBody { size, .. } => {
1315                return Err(DecodeError::Truncated {
1316                    expected: size as u64,
1317                    available: self.pending.len() as u64,
1318                })
1319            }
1320            State::SsndPrefix { .. } => {
1321                return Err(DecodeError::Truncated {
1322                    expected: SSND_PREFIX_BYTES,
1323                    available: self.pending.len() as u64,
1324                })
1325            }
1326            State::SsndGap { size, left } | State::Skip { size, left } => {
1327                return Err(DecodeError::Truncated {
1328                    expected: size,
1329                    available: size - left,
1330                })
1331            }
1332            State::Data => {
1333                return Err(DecodeError::Truncated {
1334                    expected: self.data_size,
1335                    available: self.data_size - self.data_left,
1336                })
1337            }
1338        }
1339
1340        if let Some(payload) = self.payload.as_mut() {
1341            payload.flush(&mut self.ready)?;
1342        }
1343        let Some(format) = self.format else {
1344            return Ok(0);
1345        };
1346        let channels = usize::from(format.spec.channels);
1347        let frames = (self.ready.len() - self.ready_read) / channels;
1348        output.extend_from_slice(&self.ready[self.ready_read..self.ready_read + frames * channels]);
1349        self.ready.clear();
1350        self.ready_read = 0;
1351        Ok(frames)
1352    }
1353
1354    fn reset(&mut self) {
1355        *self = Self::new();
1356    }
1357}
1358
1359impl AiffStreamDecoder {
1360    /// The body of [`push`](StreamSource::push), split out so a failure can
1361    /// set the finished flag in one place.
1362    fn push_inner(&mut self, bytes: &[u8], taken: &mut usize) -> Result<(), DecodeError> {
1363        while *taken < bytes.len() {
1364            let rest = &bytes[*taken..];
1365            match self.state {
1366                State::Form => {
1367                    if !self.accumulate(rest, riff::HEADER_BYTES as usize, taken) {
1368                        break;
1369                    }
1370                    self.start_file()?;
1371                }
1372                State::ChunkHeader => {
1373                    if !self.accumulate(rest, riff::CHUNK_HEADER_BYTES as usize, taken) {
1374                        break;
1375                    }
1376                    self.start_chunk()?;
1377                }
1378                State::CommBody { size, offset } => {
1379                    if !self.accumulate(rest, size, taken) {
1380                        break;
1381                    }
1382                    self.finish_comm(size, offset)?;
1383                }
1384                State::SsndPrefix { size, offset } => {
1385                    if !self.accumulate(rest, SSND_PREFIX_BYTES as usize, taken) {
1386                        break;
1387                    }
1388                    self.finish_ssnd_prefix(size, offset)?;
1389                }
1390                State::SsndGap { size, left } => {
1391                    let step = left.min(rest.len() as u64);
1392                    *taken += step as usize;
1393                    self.offset += step;
1394                    let left = left - step;
1395                    self.state = if left == 0 {
1396                        if self.data_size == 0 {
1397                            State::Done
1398                        } else {
1399                            State::Data
1400                        }
1401                    } else {
1402                        State::SsndGap { size, left }
1403                    };
1404                }
1405                State::Skip { size, left } => {
1406                    let step = left.min(rest.len() as u64);
1407                    *taken += step as usize;
1408                    self.offset += step;
1409                    let left = left - step;
1410                    self.state = if left == 0 {
1411                        if riff::pad_len(size) == 1 {
1412                            State::Pad
1413                        } else {
1414                            State::ChunkHeader
1415                        }
1416                    } else {
1417                        State::Skip { size, left }
1418                    };
1419                }
1420                State::Pad => {
1421                    *taken += 1;
1422                    self.offset += 1;
1423                    self.state = State::ChunkHeader;
1424                }
1425                State::Data => {
1426                    if self.ready.len() - self.ready_read >= READY_LIMIT {
1427                        // Back-pressure: the caller has to pull before the
1428                        // reader will take more.
1429                        break;
1430                    }
1431                    let limit = self.data_left.min(rest.len() as u64) as usize;
1432                    let fed = match self.payload.as_mut() {
1433                        Some(payload) => payload.feed(&rest[..limit])?,
1434                        None => 0,
1435                    };
1436                    self.drain_payload()?;
1437                    *taken += fed;
1438                    self.offset += fed as u64;
1439                    self.data_left -= fed as u64;
1440                    if self.data_left == 0 {
1441                        self.state = State::Done;
1442                    } else if fed == 0 {
1443                        break;
1444                    }
1445                }
1446                State::Done => {
1447                    // Trailing chunks are not this reader's business; the
1448                    // audio it was promised is complete.
1449                    self.offset += (bytes.len() - *taken) as u64;
1450                    *taken = bytes.len();
1451                }
1452            }
1453        }
1454        Ok(())
1455    }
1456}
1457
1458// -- The writer ---------------------------------------------------------------
1459
1460/// The `COMM` body a written plain `AIFF` file carries: the four fixed
1461/// fields, nothing else, because the form has no compression field.
1462const COMM_WRITE_AIFF: u64 = COMM_BYTES_AIFF;
1463
1464/// The `COMM` body a written `AIFC` file carries: the fixed fields, the
1465/// compression four-CC, and a zero-length compressionName pascal string:
1466/// its length byte plus the one pad byte that takes the string to an even
1467/// total. The name is empty because it is display text the specification
1468/// does not constrain, and an empty name is one fewer thing to keep
1469/// byte-identical across releases.
1470const COMM_WRITE_AIFC: u64 = COMM_BYTES_AIFC + 2;
1471
1472/// The whole `FVER` chunk a written `AIFC` file carries: header plus the
1473/// four-byte timestamp.
1474const FVER_CHUNK_BYTES: u64 = riff::CHUNK_HEADER_BYTES + 4;
1475
1476/// The value of the `FORM` header's size field for a written file:
1477/// everything after the first eight bytes. `None` when that does not fit in
1478/// 64 bits, which no caller can reach but the arithmetic should not pretend
1479/// about, the same posture as the WAV writer's `riff_size`.
1480fn aiff_form_size(form: AiffForm, data_bytes: u64) -> Option<u64> {
1481    let mut size: u64 = 4; // the form type
1482    let comm_bytes = match form {
1483        AiffForm::Aiff => COMM_WRITE_AIFF,
1484        AiffForm::Aifc => {
1485            size = size.checked_add(FVER_CHUNK_BYTES)?;
1486            COMM_WRITE_AIFC
1487        }
1488    };
1489    size = size
1490        .checked_add(riff::CHUNK_HEADER_BYTES)?
1491        .checked_add(comm_bytes)?;
1492    let ssnd_body = SSND_PREFIX_BYTES.checked_add(data_bytes)?;
1493    size = size
1494        .checked_add(riff::CHUNK_HEADER_BYTES)?
1495        .checked_add(ssnd_body)?
1496        // The pad byte after an odd SSND body belongs to the enclosing form
1497        // even though it is outside the chunk's own declared size.
1498        .checked_add(riff::pad_len(ssnd_body))?;
1499    Some(size)
1500}
1501
1502/// Writes AIFF and AIFF-C files.
1503///
1504/// The same shape as [`WavWriter`](crate::WavWriter): construct with a spec
1505/// and a codec, then [`write`](Self::write) or [`to_bytes`](Self::to_bytes)
1506/// so that the two are learnable as a pair. It writes every encoding
1507/// [`AiffReader`] accepts: [`AiffCodec`] has no variant that is readable and
1508/// not writable.
1509///
1510/// # Which form type a file gets
1511///
1512/// The rule lives on [`AiffCodec::form`] and the writer follows it: plain
1513/// `AIFF` for big-endian two's-complement PCM, which is the only thing that
1514/// form can carry and the more widely readable of the two; `AIFC`, with the
1515/// `FVER` chunk and compression field the specification requires, for
1516/// everything else. There is no override, because forcing `AIFF` around an
1517/// encoding it cannot name would write a file that lies about its payload.
1518///
1519/// # No RF64 equivalent
1520///
1521/// RIFF outgrows its 32-bit size fields into RF64; AIFF has no such escape
1522/// hatch. A write whose `FORM` size would not fit 32 bits is refused with a
1523/// typed error rather than written with wrapped sizes, unlike
1524/// [`WavWriter`](crate::WavWriter), which upgrades instead of refusing,
1525/// because it has somewhere to upgrade to.
1526///
1527/// # Samples outside full scale, and samples that are not finite
1528///
1529/// **The integer encodings clamp and the float encodings do not.** A sample
1530/// outside `-1.0..=1.0` written to an integer or G.711 encoding becomes the
1531/// extreme value rather than wrapping, an infinity becomes the same extreme,
1532/// and a NaN becomes silence. A sample written to [`AiffCodec::Float32`] or
1533/// [`AiffCodec::Float64`] is written through as it is, overshoot, infinities
1534/// and NaN included. A count of clipped samples is therefore a number about
1535/// an integer encoding and not about a float one.
1536///
1537/// Read back through this crate, a NaN written to [`AiffCodec::Float32`]
1538/// returns the same bit pattern, and a NaN written to [`AiffCodec::Float64`]
1539/// returns silence, because narrowing a NaN from `f64` to `f32` normalises
1540/// it. Both infinities return unchanged at either width.
1541///
1542/// # Example
1543///
1544/// ```
1545/// use decibri_decode::{AiffCodec, AiffReader, AiffWriter, AudioSpec};
1546///
1547/// let file = AiffWriter::new(AudioSpec::new(44_100, 2), AiffCodec::PcmI24)
1548///     .to_bytes(&[0.5, -0.5, 0.25, -0.25])?;
1549///
1550/// let reader = AiffReader::new(&file)?;
1551/// assert_eq!(reader.format().codec, AiffCodec::PcmI24);
1552/// assert_eq!(reader.frames(), 2);
1553/// assert_eq!(reader.decode_to_end().samples(), [0.5, -0.5, 0.25, -0.25]);
1554/// # Ok::<(), decibri_decode::DecodeError>(())
1555/// ```
1556#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1557pub struct AiffWriter {
1558    spec: AudioSpec,
1559    codec: AiffCodec,
1560}
1561
1562impl AiffWriter {
1563    /// A writer for `codec` audio at `spec`.
1564    pub const fn new(spec: AudioSpec, codec: AiffCodec) -> Self {
1565        Self { spec, codec }
1566    }
1567
1568    /// The rate and layout written into the `COMM` chunk.
1569    pub const fn spec(&self) -> AudioSpec {
1570        self.spec
1571    }
1572
1573    /// The encoding the payload is written in.
1574    pub const fn codec(&self) -> AiffCodec {
1575        self.codec
1576    }
1577
1578    /// The form type this writer's files declare, from [`AiffCodec::form`].
1579    ///
1580    /// Exposed so a caller can see which of the two forms an encoding
1581    /// selects without writing a file to find out.
1582    pub const fn form(&self) -> AiffForm {
1583        self.codec.form()
1584    }
1585
1586    /// Appends a complete file to `output`, and returns how many bytes it
1587    /// appended.
1588    ///
1589    /// `output` is appended to, never cleared, the same convention as
1590    /// everything else in this crate that writes into a caller's buffer.
1591    ///
1592    /// `numSampleFrames` and the `SSND` length agree by construction: both
1593    /// are computed from the one frame count `samples` implies, so the
1594    /// agreement the readers enforce cannot be broken from here. `SSND`'s
1595    /// `offset` and `blockSize` are written, as zero: present because the
1596    /// fields are not optional, zero because nothing here needs block
1597    /// alignment.
1598    ///
1599    /// # Errors
1600    ///
1601    /// - [`DecodeError::UnsupportedChannelLayout`] for no channels, and for
1602    ///   more than the 32,767 `numChannels` can state. That field is a signed
1603    ///   16-bit integer, so a larger count is a negative number to every
1604    ///   reader that reads it as the specification defines it. This crate's
1605    ///   own reader reads it unsigned and accepts such a file if one turns up;
1606    ///   the writer will not produce one.
1607    /// - [`DecodeError::Malformed`] for a zero sample rate, and for audio
1608    ///   whose file would exceed AIFF's 32-bit size fields. The `FORM` size
1609    ///   is checked in 64-bit arithmetic and a file that would wrap it is
1610    ///   refused, because AIFF has no RF64 to upgrade into. That one check
1611    ///   also bounds `numSampleFrames`: the payload holds at least one byte
1612    ///   per frame, so a frame count past `u32::MAX` cannot reach the field
1613    ///   that would truncate it.
1614    /// - [`DecodeError::Truncated`] when `samples` does not divide into
1615    ///   whole frames, for the reason recorded on
1616    ///   [`WavWriter::write`](crate::WavWriter::write): writing a partial
1617    ///   frame would produce a file this crate's own readers reject.
1618    pub fn write(&self, samples: &[f32], output: &mut Vec<u8>) -> Result<usize, DecodeError> {
1619        let channels = usize::from(self.spec.channels);
1620        if channels == 0 || self.spec.channels > MAX_WRITABLE_CHANNELS {
1621            return Err(DecodeError::UnsupportedChannelLayout {
1622                channels: self.spec.channels,
1623            });
1624        }
1625        let form = self.codec.form();
1626        if self.spec.sample_rate == 0 {
1627            // The offset names where the unencodable rate field would sit:
1628            // after the header, the AIFC form's FVER chunk, the COMM header
1629            // and COMM's first eight bytes.
1630            let comm_at = riff::HEADER_BYTES
1631                + match form {
1632                    AiffForm::Aiff => 0,
1633                    AiffForm::Aifc => FVER_CHUNK_BYTES,
1634                };
1635            return Err(DecodeError::Malformed {
1636                expected: "a non-zero sample rate",
1637                offset: comm_at + riff::CHUNK_HEADER_BYTES + 8,
1638            });
1639        }
1640        let bytes_per_sample = self.codec.bytes_per_sample();
1641        let frame_bytes = channels * bytes_per_sample;
1642        let leftover = samples.len() % channels;
1643        if leftover != 0 {
1644            return Err(DecodeError::Truncated {
1645                expected: frame_bytes as u64,
1646                available: (leftover * bytes_per_sample) as u64,
1647            });
1648        }
1649
1650        let data_bytes = (samples.len() as u64).checked_mul(bytes_per_sample as u64);
1651        let declared_form = data_bytes.and_then(|data| aiff_form_size(form, data));
1652        let (Some(data_bytes), Some(declared_form)) = (data_bytes, declared_form) else {
1653            return Err(size_refusal());
1654        };
1655        if declared_form > u64::from(u32::MAX) {
1656            return Err(size_refusal());
1657        }
1658        // In range now: the payload holds at least one byte per frame, so
1659        // `frames <= data_bytes <= declared_form <= u32::MAX`.
1660        let frames = (samples.len() / channels) as u32;
1661
1662        let start = output.len();
1663        output.extend_from_slice(FORM.as_bytes());
1664        output.extend_from_slice(&(declared_form as u32).to_be_bytes());
1665        let comm_bytes = match form {
1666            AiffForm::Aiff => {
1667                output.extend_from_slice(AIFF.as_bytes());
1668                COMM_WRITE_AIFF
1669            }
1670            AiffForm::Aifc => {
1671                output.extend_from_slice(AIFC.as_bytes());
1672                output.extend_from_slice(FVER.as_bytes());
1673                output.extend_from_slice(&4u32.to_be_bytes());
1674                output.extend_from_slice(&FVER_TIMESTAMP.to_be_bytes());
1675                COMM_WRITE_AIFC
1676            }
1677        };
1678
1679        output.extend_from_slice(COMM.as_bytes());
1680        output.extend_from_slice(&(comm_bytes as u32).to_be_bytes());
1681        output.extend_from_slice(&self.spec.channels.to_be_bytes());
1682        output.extend_from_slice(&frames.to_be_bytes());
1683        output.extend_from_slice(&self.codec.bits_per_sample().to_be_bytes());
1684        output.extend_from_slice(&rate_to_extended(self.spec.sample_rate));
1685        if form == AiffForm::Aifc {
1686            output.extend_from_slice(self.codec.compression_type().as_bytes());
1687            // The zero-length compressionName: a length byte of zero, then
1688            // the pad byte that takes the pascal string to an even total.
1689            output.extend_from_slice(&[0, 0]);
1690        }
1691
1692        output.extend_from_slice(SSND.as_bytes());
1693        output.extend_from_slice(&((SSND_PREFIX_BYTES + data_bytes) as u32).to_be_bytes());
1694        output.extend_from_slice(&0u32.to_be_bytes()); // offset
1695        output.extend_from_slice(&0u32.to_be_bytes()); // blockSize
1696        self.codec.encode(samples, output);
1697        if riff::pad_len(SSND_PREFIX_BYTES + data_bytes) == 1 {
1698            // The IFF pad byte after an odd chunk body, outside the chunk's
1699            // declared size and inside the form's.
1700            output.push(0);
1701        }
1702        Ok(output.len() - start)
1703    }
1704
1705    /// A complete file as a new `Vec<u8>`.
1706    ///
1707    /// # Errors
1708    ///
1709    /// As [`write`](Self::write).
1710    pub fn to_bytes(&self, samples: &[f32]) -> Result<Vec<u8>, DecodeError> {
1711        let mut output = Vec::new();
1712        self.write(samples, &mut output)?;
1713        Ok(output)
1714    }
1715}
1716
1717/// The one refusal for audio AIFF's 32-bit size fields cannot hold.
1718///
1719/// A function rather than a constant expression at each site so the message
1720/// exists once; the offset names the `FORM` size field the number would not
1721/// fit.
1722fn size_refusal() -> DecodeError {
1723    DecodeError::Malformed {
1724        expected: "audio that fits within AIFF's 32-bit size fields",
1725        offset: 4,
1726    }
1727}
1728
1729#[cfg(test)]
1730mod tests {
1731    use super::*;
1732
1733    // -- Gate 7: the 80-bit extended float, against hand-computed bytes ---
1734
1735    /// Every byte string here was worked out by hand from the format
1736    /// definition, sign, 15-bit biased exponent, explicit-integer-bit
1737    /// significand, not produced by an encoder that could share a mistake
1738    /// with the parser.
1739    #[test]
1740    fn the_extended_float_parser_matches_hand_computed_values() {
1741        // 8000 = 0.9765625 * 2^13: exponent 16383+12 = 0x400B with the
1742        // significand normalised to its integer bit, 8000 << 51 = 0xFA00...
1743        let cases: [([u8; 10], f64); 7] = [
1744            ([0x40, 0x0B, 0xFA, 0, 0, 0, 0, 0, 0, 0], 8_000.0),
1745            ([0x40, 0x0C, 0xFA, 0, 0, 0, 0, 0, 0, 0], 16_000.0),
1746            // 44100 = 0xAC44 * 2^0; normalised: exponent 16383+15, 0xAC44 << 48.
1747            ([0x40, 0x0E, 0xAC, 0x44, 0, 0, 0, 0, 0, 0], 44_100.0),
1748            ([0x40, 0x0E, 0xBB, 0x80, 0, 0, 0, 0, 0, 0], 48_000.0),
1749            ([0x40, 0x0D, 0xAC, 0x44, 0, 0, 0, 0, 0, 0], 22_050.0),
1750            // A non-zero fractional part: 11025.5 = 22051 * 2^-1, and 22051
1751            // = 0x5623 normalises to 0xAC46 << 48 at exponent 16383+13.
1752            ([0x40, 0x0C, 0xAC, 0x46, 0, 0, 0, 0, 0, 0], 11_025.5),
1753            // One: integer bit alone at exponent 16383.
1754            ([0x3F, 0xFF, 0x80, 0, 0, 0, 0, 0, 0, 0], 1.0),
1755        ];
1756        for (bytes, expected) in cases {
1757            assert_eq!(
1758                extended_to_f64(bytes),
1759                expected,
1760                "{bytes:02X?} did not parse to {expected}"
1761            );
1762        }
1763    }
1764
1765    #[test]
1766    fn the_extended_float_parser_handles_the_edges_deterministically() {
1767        // Zero, and negative zero.
1768        assert_eq!(extended_to_f64([0; 10]), 0.0);
1769        assert_eq!(extended_to_f64([0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0]), 0.0);
1770        // A negative rate parses as negative; rejecting it is the caller's
1771        // job, not the parser's.
1772        assert_eq!(
1773            extended_to_f64([0xC0, 0x0B, 0xFA, 0, 0, 0, 0, 0, 0, 0]),
1774            -8_000.0
1775        );
1776        // Infinity: the 0x7FFF exponent with a clear fraction.
1777        assert_eq!(
1778            extended_to_f64([0x7F, 0xFF, 0x80, 0, 0, 0, 0, 0, 0, 0]),
1779            f64::INFINITY
1780        );
1781        assert_eq!(
1782            extended_to_f64([0xFF, 0xFF, 0x80, 0, 0, 0, 0, 0, 0, 0]),
1783            f64::NEG_INFINITY
1784        );
1785        // NaN: the same exponent with fraction bits set.
1786        assert!(extended_to_f64([0x7F, 0xFF, 0xC0, 0, 0, 0, 0, 0, 0, 1]).is_nan());
1787        // An exponent past f64's range overflows to infinity rather than
1788        // wrapping or panicking.
1789        assert_eq!(
1790            extended_to_f64([0x7F, 0xFE, 0x80, 0, 0, 0, 0, 0, 0, 0]),
1791            f64::INFINITY
1792        );
1793        // And a denormal underflows to zero rather than misparsing.
1794        assert_eq!(extended_to_f64([0, 0, 0, 0, 0, 0, 0, 0, 0, 1]), 0.0);
1795    }
1796
1797    #[test]
1798    fn a_rate_the_spec_cannot_carry_is_rejected_with_its_offset() {
1799        for wrong in [
1800            0.0,
1801            -8_000.0,
1802            11_025.5,
1803            f64::INFINITY,
1804            f64::NEG_INFINITY,
1805            f64::NAN,
1806            f64::from(u32::MAX) + 1.0,
1807            0.25,
1808        ] {
1809            let error = rate_to_spec_rate(wrong, 20).expect_err("must reject");
1810            assert!(
1811                matches!(
1812                    error,
1813                    DecodeError::Malformed {
1814                        expected: "a positive integral sample rate that fits in 32 bits",
1815                        offset: 20
1816                    }
1817                ),
1818                "{wrong}: unexpected error: {error}"
1819            );
1820        }
1821        for right in [1.0, 8_000.0, 44_100.0, 192_000.0, f64::from(u32::MAX)] {
1822            assert_eq!(rate_to_spec_rate(right, 20).expect("accept"), right as u32);
1823        }
1824    }
1825
1826    // -- Dispatch on the (compression, sampleSize) pair -------------------
1827
1828    #[test]
1829    fn dispatch_is_on_the_compression_and_the_width_together() {
1830        use AiffCodec::*;
1831        let accepted: [(&[u8; 4], u16, AiffCodec); 16] = [
1832            (b"NONE", 8, PcmI8),
1833            (b"raw ", 8, PcmU8),
1834            (b"NONE", 16, PcmI16),
1835            (b"NONE", 24, PcmI24),
1836            (b"NONE", 32, PcmI32),
1837            (b"twos", 8, PcmI8),
1838            (b"twos", 16, PcmI16),
1839            (b"sowt", 8, PcmI8),
1840            (b"sowt", 16, PcmI16Sowt),
1841            (b"sowt", 24, PcmI24Sowt),
1842            (b"sowt", 32, PcmI32Sowt),
1843            (b"fl32", 32, Float32),
1844            (b"FL32", 32, Float32),
1845            (b"fl64", 64, Float64),
1846            (b"FL64", 64, Float64),
1847            (b"alaw", 16, ALaw),
1848        ];
1849        for (compression, bits, codec) in accepted {
1850            assert_eq!(
1851                AiffCodec::resolve(FourCc(*compression), bits).expect("accepted"),
1852                codec,
1853                "{compression:?} at {bits} bits"
1854            );
1855        }
1856
1857        // The companded types dispatch on the four-CC alone: both the wire
1858        // width and the decoded width appear in real files.
1859        for law_cc in [b"alaw", b"ALAW"] {
1860            for bits in [8u16, 16] {
1861                assert_eq!(
1862                    AiffCodec::resolve(FourCc(*law_cc), bits).expect("alaw"),
1863                    ALaw
1864                );
1865            }
1866        }
1867        for law_cc in [b"ulaw", b"ULAW"] {
1868            for bits in [8u16, 16] {
1869                assert_eq!(
1870                    AiffCodec::resolve(FourCc(*law_cc), bits).expect("ulaw"),
1871                    MuLaw
1872                );
1873            }
1874        }
1875
1876        // A carried compression at a width this crate does not read names
1877        // both halves of the rejection.
1878        for (compression, bits) in [
1879            (b"NONE", 12u16),
1880            (b"NONE", 64),
1881            (b"sowt", 20),
1882            (b"fl32", 16),
1883            (b"fl64", 32),
1884            // `raw ` is the one unsigned encoding and exists at one width.
1885            // Any other width is a width rejection, never a silent accept.
1886            (b"raw ", 1),
1887            (b"raw ", 16),
1888            (b"raw ", 24),
1889            (b"raw ", 32),
1890        ] {
1891            let error = AiffCodec::resolve(FourCc(*compression), bits).expect_err("must reject");
1892            assert!(
1893                matches!(
1894                    &error,
1895                    DecodeError::UnsupportedSampleFormat { format, bits_per_sample }
1896                        if *format == CodecId::FourCc(FourCc(*compression))
1897                            && *bits_per_sample == bits
1898                ),
1899                "{compression:?} at {bits}: unexpected error: {error}"
1900            );
1901        }
1902
1903        // A compression this crate does not carry names the four-CC it was.
1904        // Each of these five is a compression scheme, so carrying one would
1905        // mean a decoder for it. `raw ` was in this list until 0.1.2 and is
1906        // not a compression scheme; it is asserted above, accepted at 8 bits
1907        // and rejected on width everywhere else.
1908        for compression in [b"ima4", b"MAC3", b"MAC6", b"QDMC", b"GSM "] {
1909            let error = AiffCodec::resolve(FourCc(*compression), 16).expect_err("must reject");
1910            assert!(
1911                matches!(&error, DecodeError::UnsupportedCodec { codec }
1912                    if *codec == CodecId::FourCc(FourCc(*compression))),
1913                "{compression:?}: unexpected error: {error}"
1914            );
1915        }
1916    }
1917
1918    #[test]
1919    fn every_codec_is_linear_or_companded_and_never_both() {
1920        const ALL: [AiffCodec; 12] = [
1921            AiffCodec::PcmI8,
1922            AiffCodec::PcmU8,
1923            AiffCodec::PcmI16,
1924            AiffCodec::PcmI24,
1925            AiffCodec::PcmI32,
1926            AiffCodec::PcmI16Sowt,
1927            AiffCodec::PcmI24Sowt,
1928            AiffCodec::PcmI32Sowt,
1929            AiffCodec::Float32,
1930            AiffCodec::Float64,
1931            AiffCodec::ALaw,
1932            AiffCodec::MuLaw,
1933        ];
1934        // The exhaustive match is the assertion: a variant added to the enum
1935        // without a line in ALL fails to compile here.
1936        for codec in ALL {
1937            match codec {
1938                AiffCodec::PcmI8
1939                | AiffCodec::PcmU8
1940                | AiffCodec::PcmI16
1941                | AiffCodec::PcmI24
1942                | AiffCodec::PcmI32
1943                | AiffCodec::PcmI16Sowt
1944                | AiffCodec::PcmI24Sowt
1945                | AiffCodec::PcmI32Sowt
1946                | AiffCodec::Float32
1947                | AiffCodec::Float64
1948                | AiffCodec::ALaw
1949                | AiffCodec::MuLaw => {}
1950            }
1951            assert_ne!(
1952                codec.sample_format().is_some(),
1953                codec.law().is_some(),
1954                "{codec:?} is on both sides or neither"
1955            );
1956            if let Some(format) = codec.sample_format() {
1957                assert_eq!(format.bytes_per_sample(), codec.bytes_per_sample());
1958            } else {
1959                assert_eq!(codec.bytes_per_sample(), 1);
1960            }
1961        }
1962    }
1963
1964    // -- COMM parsing -----------------------------------------------------
1965
1966    fn comm_aiff(channels: u16, frames: u32, bits: u16, rate: [u8; 10]) -> Vec<u8> {
1967        let mut body = Vec::new();
1968        body.extend_from_slice(&channels.to_be_bytes());
1969        body.extend_from_slice(&frames.to_be_bytes());
1970        body.extend_from_slice(&bits.to_be_bytes());
1971        body.extend_from_slice(&rate);
1972        body
1973    }
1974
1975    const RATE_8K: [u8; 10] = [0x40, 0x0B, 0xFA, 0, 0, 0, 0, 0, 0, 0];
1976
1977    #[test]
1978    fn a_comm_chunk_parses_to_what_it_declared() {
1979        let body = comm_aiff(2, 100, 16, RATE_8K);
1980        let format = parse_comm(&body, 12, AiffForm::Aiff).expect("parse");
1981        assert_eq!(format.spec, AudioSpec::new(8_000, 2));
1982        assert_eq!(format.codec, AiffCodec::PcmI16);
1983        assert_eq!(format.form, AiffForm::Aiff);
1984        assert_eq!(format.compression, NONE);
1985        assert_eq!(format.bits_per_sample, 16);
1986        assert_eq!(format.sample_frames, 100);
1987        assert_eq!(format.frame_bytes(), 4);
1988    }
1989
1990    #[test]
1991    fn a_compression_name_that_overruns_its_chunk_is_malformed() {
1992        let mut body = comm_aiff(1, 4, 16, RATE_8K);
1993        body.extend_from_slice(b"sowt");
1994        // The length byte claims eleven characters; only four follow.
1995        body.push(11);
1996        body.extend_from_slice(b"four");
1997        let error = parse_comm(&body, 12, AiffForm::Aifc).expect_err("must reject");
1998        assert!(
1999            matches!(
2000                error,
2001                DecodeError::Malformed {
2002                    expected: "a compressionName that fits its COMM chunk",
2003                    ..
2004                }
2005            ),
2006            "unexpected error: {error}"
2007        );
2008
2009        // The same name, counted truthfully, parses.
2010        let mut body = comm_aiff(1, 4, 16, RATE_8K);
2011        body.extend_from_slice(b"sowt");
2012        body.push(4);
2013        body.extend_from_slice(b"four");
2014        body.push(0); // the pstring's own even-total pad
2015        let format = parse_comm(&body, 12, AiffForm::Aifc).expect("parse");
2016        assert_eq!(format.codec, AiffCodec::PcmI16Sowt);
2017    }
2018
2019    #[test]
2020    fn zero_channels_and_impossible_rates_are_typed_rejections() {
2021        let body = comm_aiff(0, 4, 16, RATE_8K);
2022        assert!(matches!(
2023            parse_comm(&body, 12, AiffForm::Aiff),
2024            Err(DecodeError::UnsupportedChannelLayout { channels: 0 })
2025        ));
2026
2027        for bad_rate in [
2028            [0u8; 10],                                  // zero
2029            [0xC0, 0x0B, 0xFA, 0, 0, 0, 0, 0, 0, 0],    // negative
2030            [0x40, 0x0C, 0xAC, 0x46, 0, 0, 0, 0, 0, 0], // 11025.5
2031            [0x7F, 0xFF, 0x80, 0, 0, 0, 0, 0, 0, 0],    // infinity
2032            [0x7F, 0xFF, 0xC0, 0, 0, 0, 0, 0, 0, 1],    // NaN
2033        ] {
2034            let body = comm_aiff(1, 4, 16, bad_rate);
2035            let error = parse_comm(&body, 12, AiffForm::Aiff).expect_err("must reject");
2036            assert!(
2037                matches!(
2038                    error,
2039                    DecodeError::Malformed {
2040                        expected: "a positive integral sample rate that fits in 32 bits",
2041                        offset: 28
2042                    }
2043                ),
2044                "{bad_rate:02X?}: unexpected error: {error}"
2045            );
2046        }
2047    }
2048
2049    // -- The SSND agreement rule ------------------------------------------
2050
2051    #[test]
2052    fn the_ssnd_length_must_equal_what_comm_declared() {
2053        let format = parse_comm(&comm_aiff(2, 10, 16, RATE_8K), 12, AiffForm::Aiff).expect("parse");
2054        // 10 frames * 4 bytes: the body needs exactly 8 + 40 bytes.
2055        assert!(check_ssnd(&format, 48, 0, 30).is_ok());
2056        // Under: Truncated, naming both numbers.
2057        let error = check_ssnd(&format, 40, 0, 30).expect_err("under");
2058        assert!(
2059            matches!(
2060                error,
2061                DecodeError::Truncated {
2062                    expected: 40,
2063                    available: 32
2064                }
2065            ),
2066            "unexpected error: {error}"
2067        );
2068        // Over: Malformed, not a silent preference for either source.
2069        let error = check_ssnd(&format, 50, 0, 30).expect_err("over");
2070        assert!(
2071            matches!(
2072                error,
2073                DecodeError::Malformed {
2074                    expected: "an SSND chunk holding exactly numSampleFrames frames",
2075                    offset: 30
2076                }
2077            ),
2078            "unexpected error: {error}"
2079        );
2080        // A non-zero offset moves the data and the arithmetic follows it.
2081        assert!(check_ssnd(&format, 52, 4, 30).is_ok());
2082        // An offset past the chunk cannot wrap the arithmetic into a pass.
2083        let error = check_ssnd(&format, 48, u32::MAX, 30).expect_err("offset");
2084        assert!(
2085            matches!(
2086                error,
2087                DecodeError::Malformed {
2088                    expected: "an SSND offset that fits inside the SSND chunk",
2089                    ..
2090                }
2091            ),
2092            "unexpected error: {error}"
2093        );
2094    }
2095
2096    // -- The 80-bit extended float, on the encode side --------------------
2097
2098    /// Every byte string here was worked out by hand from the format
2099    /// definition, the same derivations as the parser's gate above, so the
2100    /// two directions are anchored to the same independent bytes rather
2101    /// than to each other.
2102    #[test]
2103    fn the_extended_float_encoder_matches_hand_computed_values() {
2104        let cases: [(u32, [u8; 10]); 5] = [
2105            // 8000 = 0x1F40, leading one at bit 12: exponent 16383+12 =
2106            // 0x400B, significand 8000 << 51 = 0xFA00...
2107            (8_000, [0x40, 0x0B, 0xFA, 0, 0, 0, 0, 0, 0, 0]),
2108            // 16000: one bit higher, same significand pattern.
2109            (16_000, [0x40, 0x0C, 0xFA, 0, 0, 0, 0, 0, 0, 0]),
2110            // 22050 = 0x5622, leading one at bit 14: exponent 16383+14 =
2111            // 0x400D, significand 0x5622 << 49 = 0xAC44...
2112            (22_050, [0x40, 0x0D, 0xAC, 0x44, 0, 0, 0, 0, 0, 0]),
2113            // 44100 = 0xAC44, leading one at bit 15: exponent 0x400E,
2114            // significand 0xAC44 << 48.
2115            (44_100, [0x40, 0x0E, 0xAC, 0x44, 0, 0, 0, 0, 0, 0]),
2116            // 48000 = 0xBB80, leading one at bit 15: exponent 0x400E,
2117            // significand 0xBB80 << 48.
2118            (48_000, [0x40, 0x0E, 0xBB, 0x80, 0, 0, 0, 0, 0, 0]),
2119        ];
2120        for (rate, expected) in cases {
2121            assert_eq!(
2122                rate_to_extended(rate),
2123                expected,
2124                "{rate} did not encode to {expected:02X?}"
2125            );
2126        }
2127    }
2128
2129    /// The encoder round-trips through the existing parser for every rate
2130    /// shape: the common rates, a dense low sweep, every power of two, and
2131    /// the extremes of the field.
2132    #[test]
2133    fn the_extended_float_encoder_round_trips_through_the_parser() {
2134        let common = [
2135            8_000u32, 11_025, 16_000, 22_050, 32_000, 44_100, 48_000, 88_200, 96_000, 176_400,
2136            192_000,
2137        ];
2138        let sweep = 1..=1_000;
2139        let powers = (0..32).map(|shift| 1u32 << shift);
2140        let extremes = [3u32, u32::MAX - 1, u32::MAX];
2141        for rate in common
2142            .into_iter()
2143            .chain(sweep)
2144            .chain(powers)
2145            .chain(extremes)
2146        {
2147            let parsed = extended_to_f64(rate_to_extended(rate));
2148            assert_eq!(parsed, f64::from(rate), "{rate} did not round-trip");
2149            // And the parsed value passes the same acceptance the reader
2150            // applies, landing on the same u32.
2151            assert_eq!(rate_to_spec_rate(parsed, 0).expect("integral"), rate);
2152        }
2153    }
2154
2155    // -- The writer's size arithmetic -------------------------------------
2156
2157    /// The refusal point, tested as arithmetic rather than by materialising
2158    /// four gigabytes to cross it with, the same posture as the WAV
2159    /// writer's RF64 threshold test.
2160    #[test]
2161    fn the_size_refusal_happens_exactly_at_the_32_bit_form_limit() {
2162        let ceiling = u64::from(u32::MAX);
2163
2164        // Plain AIFF over an 18-byte COMM: 4 (form type) + 8 + 18 (COMM)
2165        // + 8 (SSND header) + 8 (SSND prefix) = 46 bytes the payload has to
2166        // share u32::MAX with.
2167        const AIFF_OVERHEAD: u64 = 46;
2168        assert_eq!(aiff_form_size(AiffForm::Aiff, 0), Some(AIFF_OVERHEAD));
2169        // `u32::MAX - 46` is odd, so its pad byte is what tips it over: the
2170        // largest fitting payload is one byte smaller and even.
2171        let largest = ceiling - AIFF_OVERHEAD - 1;
2172        assert_eq!(largest % 2, 0);
2173        assert_eq!(aiff_form_size(AiffForm::Aiff, largest), Some(ceiling - 1));
2174        assert!(aiff_form_size(AiffForm::Aiff, largest).unwrap() <= ceiling);
2175        // One byte more is odd, pads, and lands one past the ceiling.
2176        assert_eq!(
2177            aiff_form_size(AiffForm::Aiff, largest + 1),
2178            Some(ceiling + 1)
2179        );
2180        // The odd payload one byte *smaller* fits only because its pad byte
2181        // still lands on ceiling - 1: the pad is genuinely counted.
2182        assert_eq!(
2183            aiff_form_size(AiffForm::Aiff, largest - 1),
2184            Some(ceiling - 1)
2185        );
2186
2187        // AIFC adds FVER (12) and the longer COMM (24 + 8 against 18 + 8):
2188        // 64 bytes of overhead.
2189        const AIFC_OVERHEAD: u64 = 64;
2190        assert_eq!(aiff_form_size(AiffForm::Aifc, 0), Some(AIFC_OVERHEAD));
2191        let largest = ceiling - AIFC_OVERHEAD - 1;
2192        assert_eq!(largest % 2, 0);
2193        assert_eq!(aiff_form_size(AiffForm::Aifc, largest), Some(ceiling - 1));
2194        assert_eq!(
2195            aiff_form_size(AiffForm::Aifc, largest + 1),
2196            Some(ceiling + 1)
2197        );
2198
2199        // And the arithmetic answers None rather than wrapping at the top of
2200        // u64 itself.
2201        assert_eq!(aiff_form_size(AiffForm::Aiff, u64::MAX), None);
2202        assert_eq!(aiff_form_size(AiffForm::Aifc, u64::MAX - 20), None);
2203
2204        // The refusal the writer hands back for everything past the limit.
2205        let error = size_refusal();
2206        assert!(
2207            matches!(
2208                error,
2209                DecodeError::Malformed {
2210                    expected: "audio that fits within AIFF's 32-bit size fields",
2211                    offset: 4
2212                }
2213            ),
2214            "unexpected error: {error}"
2215        );
2216    }
2217
2218    // -- The writer's rejections ------------------------------------------
2219
2220    #[test]
2221    fn the_writer_rejects_a_partial_trailing_frame() {
2222        let writer = AiffWriter::new(AudioSpec::new(48_000, 3), AiffCodec::PcmI16);
2223        let error = writer.to_bytes(&[0.0; 7]).expect_err("must reject");
2224        assert!(
2225            matches!(
2226                error,
2227                DecodeError::Truncated {
2228                    expected: 6,
2229                    available: 2
2230                }
2231            ),
2232            "unexpected error: {error}"
2233        );
2234        // Seven is one sample past two frames; six and nine are whole.
2235        assert!(writer.to_bytes(&[0.0; 6]).is_ok());
2236        assert!(writer.to_bytes(&[0.0; 9]).is_ok());
2237    }
2238
2239    #[test]
2240    fn the_writer_rejects_what_the_header_cannot_express() {
2241        let no_channels = AiffWriter::new(AudioSpec::new(48_000, 0), AiffCodec::PcmI16);
2242        assert!(matches!(
2243            no_channels.to_bytes(&[]),
2244            Err(DecodeError::UnsupportedChannelLayout { channels: 0 })
2245        ));
2246
2247        // `numChannels` is a signed 16-bit integer, so 32,767 is the largest
2248        // count it states as itself. 32,768 is the first that would be read
2249        // back negative.
2250        let widest = AiffWriter::new(AudioSpec::new(48_000, 32_767), AiffCodec::PcmI8);
2251        assert!(widest.to_bytes(&vec![0.0; 32_767]).is_ok());
2252        for channels in [32_768u16, 40_000, u16::MAX] {
2253            let too_wide = AiffWriter::new(AudioSpec::new(48_000, channels), AiffCodec::PcmI8);
2254            let error = too_wide
2255                .to_bytes(&vec![0.0; usize::from(channels)])
2256                .expect_err("a count numChannels cannot state must be refused");
2257            assert!(
2258                matches!(
2259                    error,
2260                    DecodeError::UnsupportedChannelLayout { channels: found }
2261                        if found == channels
2262                ),
2263                "unexpected error for {channels} channels: {error}"
2264            );
2265        }
2266
2267        // A zero rate is refused before the encoder that cannot spell it,
2268        // and the offset names the rate field of the form being written:
2269        // byte 28 in plain AIFF, byte 40 in AIFC behind FVER.
2270        for (codec, rate_at) in [(AiffCodec::PcmI16, 28), (AiffCodec::Float32, 40)] {
2271            let no_rate = AiffWriter::new(AudioSpec::mono(0), codec);
2272            assert!(matches!(
2273                no_rate.to_bytes(&[]),
2274                Err(DecodeError::Malformed {
2275                    expected: "a non-zero sample rate",
2276                    offset
2277                }) if offset == rate_at
2278            ));
2279        }
2280    }
2281
2282    #[test]
2283    fn the_writer_appends_rather_than_clearing() {
2284        let writer = AiffWriter::new(AudioSpec::mono(8_000), AiffCodec::PcmI8);
2285        let mut output = vec![0xAA];
2286        let written = writer.write(&[0.0, 0.0], &mut output).expect("write");
2287        assert_eq!(output[0], 0xAA);
2288        assert_eq!(output.len(), 1 + written);
2289        // Header, COMM, SSND header and prefix, two bytes of payload.
2290        assert_eq!(written, 12 + 8 + 18 + 8 + 8 + 2);
2291    }
2292
2293    // -- The AIFF against AIFC selection rule, every branch ---------------
2294
2295    /// Each codec lands on the form the rule states, and the written bytes
2296    /// agree with the answer: the form type at bytes 8..12, and FVER present
2297    /// exactly when the form is AIFC.
2298    #[test]
2299    fn each_codec_selects_the_form_the_rule_states() {
2300        let cases: [(AiffCodec, AiffForm); 12] = [
2301            (AiffCodec::PcmI8, AiffForm::Aiff),
2302            (AiffCodec::PcmU8, AiffForm::Aifc),
2303            (AiffCodec::PcmI16, AiffForm::Aiff),
2304            (AiffCodec::PcmI24, AiffForm::Aiff),
2305            (AiffCodec::PcmI32, AiffForm::Aiff),
2306            (AiffCodec::PcmI16Sowt, AiffForm::Aifc),
2307            (AiffCodec::PcmI24Sowt, AiffForm::Aifc),
2308            (AiffCodec::PcmI32Sowt, AiffForm::Aifc),
2309            (AiffCodec::Float32, AiffForm::Aifc),
2310            (AiffCodec::Float64, AiffForm::Aifc),
2311            (AiffCodec::ALaw, AiffForm::Aifc),
2312            (AiffCodec::MuLaw, AiffForm::Aifc),
2313        ];
2314        for (codec, expected_form) in cases {
2315            let writer = AiffWriter::new(AudioSpec::new(16_000, 2), codec);
2316            assert_eq!(writer.form(), expected_form, "{codec:?}");
2317            let bytes = writer.to_bytes(&[0.0, 0.0]).expect("write");
2318            let form_type = &bytes[8..12];
2319            let has_fver = bytes.windows(4).any(|window| window == b"FVER");
2320            match expected_form {
2321                AiffForm::Aiff => {
2322                    assert_eq!(form_type, b"AIFF", "{codec:?}");
2323                    assert!(!has_fver, "{codec:?} wrote FVER into a plain AIFF");
2324                }
2325                AiffForm::Aifc => {
2326                    assert_eq!(form_type, b"AIFC", "{codec:?}");
2327                    assert!(has_fver, "{codec:?} omitted the FVER chunk");
2328                }
2329            }
2330            // And the file reads back under the codec it was written as.
2331            let reader = AiffReader::new(&bytes).expect("read back");
2332            assert_eq!(reader.format().codec, codec, "{codec:?}");
2333            assert_eq!(reader.format().form, expected_form, "{codec:?}");
2334        }
2335    }
2336}