Skip to main content

decibri_decode/
probe.rs

1//! One entry point that picks the reader out of the bytes.
2//!
3//! # Why this exists
4//!
5//! Before it, every caller of this crate wrote the same magic-byte check. That
6//! is one rule with as many implementations as there are users, and the moment
7//! FLAC landed the crate's own README was wrong: its first example dispatched
8//! between two containers and there were three. A rule that has to be restated
9//! at every call site is a rule that will be restated wrongly somewhere, which
10//! is the same reasoning that put the IFF pad byte in a single function.
11//!
12//! So identification lives here, once, and three entry points are built on it:
13//! [`identify`] says what the bytes are, [`decode`] reads a whole input, and
14//! [`AudioStreamDecoder`] reads one that arrives in pieces. The streaming one
15//! matters as much as the whole-file one: without it a streaming caller still
16//! hand-rolls the dispatch and the defect is only half fixed.
17//!
18//! # Twelve bytes, not four
19//!
20//! `RIFF` at offset zero does not mean WAV. It means a RIFF container, and AVI
21//! is one too. The form type sits at offset eight and it is the field that
22//! decides. `FORM` is the same story: an EA IFF 85 container whose form type
23//! may be `AIFF`, `AIFC`, `8SVX`, `ILBM` or anything else that family carries.
24//!
25//! A four-byte probe would therefore hand an AVI file to [`WavReader`] and let
26//! it fail somewhere deeper in, reporting a missing `fmt ` chunk for a file
27//! that was never a WAV. This one reads twelve bytes and rejects a RIFF that
28//! is not `WAVE`, or a `FORM` that is neither `AIFF` nor `AIFC`, with
29//! [`DecodeError::UnsupportedContainer`] carrying the form type it actually
30//! found.
31//!
32//! `fLaC` needs no form type, but identification still requires twelve bytes
33//! before it will answer, so that "too short to identify" is one rule rather
34//! than one per format. Nothing is lost by it: the shortest legal FLAC stream
35//! is a signature, a metadata block header and a 34-byte streaminfo body.
36//!
37//! # What the probe does not cover, and will not
38//!
39//! Headerless linear PCM, headerless G.711 and bare FLAC frame streams have no
40//! signature to probe. They stay explicit, with the caller supplying what it
41//! knows, exactly as [`PcmDecoder`], [`G711Decoder`] and the bare frame reader
42//! already require.
43//!
44//! Bare FLAC frames are the one that looks detectable and is not. A frame
45//! begins with a 14-bit sync code and its header ends in a CRC-8, and the
46//! measurement recorded on the recovery reader is that the pair together let
47//! about one position in 32,768 of random data parse as a frame header: some
48//! twenty accepting positions in ten million random runs. Sniffing for that in
49//! bytes of unknown provenance would misfire on input that is not FLAC at all.
50//! Headerless means told, not guessed, and there is no argument that makes a
51//! guess safe here.
52//!
53//! # Nothing here looks at a name
54//!
55//! No entry point in this module takes a path, a file name or an extension,
56//! and none of them is consulted anywhere in the crate. A file called
57//! `input.wav` that holds AIFF bytes decodes as AIFF.
58
59use std::fmt;
60
61use crate::aiff::{AiffFormat, AiffReader, AiffStreamDecoder};
62use crate::audio::{AudioBuffer, AudioSpec};
63use crate::codec::FourCc;
64use crate::error::DecodeError;
65use crate::flac::{FlacReader, FlacStreamDecoder, FlacStreamInfo, Md5Check};
66use crate::source::StreamSource;
67use crate::wav::{WavFormat, WavReader, WavStreamDecoder};
68use crate::{aiff, riff};
69
70/// The four bytes every FLAC stream starts with.
71///
72/// Stated here rather than in the FLAC module because this is where a FLAC
73/// stream is recognised. The FLAC module takes its own signature from this
74/// one, so the bytes are written down once.
75pub(crate) const FLAC_MAGIC: FourCc = FourCc(*b"fLaC");
76
77/// What the leading bytes of an input turned out to be.
78///
79/// One variant per whole-file reader, not one per file format: `AIFF` and
80/// `AIFF-C` are both [`Aiff`](Self::Aiff) because [`AiffReader`] reads both,
81/// and `RIFF` and `RF64` are both [`Wav`](Self::Wav) for the same reason. The
82/// question this answers is which reader the bytes belong to.
83///
84/// This enum is `#[non_exhaustive]`: consumers matching on it must include a
85/// `_ =>` catch-all arm, so the format after next is not source-breaking to
86/// add.
87#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
88#[non_exhaustive]
89pub enum Container {
90    /// A RIFF or RF64 file whose form type is `WAVE`, read by [`WavReader`]
91    /// and [`WavStreamDecoder`].
92    Wav,
93    /// An EA IFF 85 file whose form type is `AIFF` or `AIFC`, read by
94    /// [`AiffReader`] and [`AiffStreamDecoder`].
95    Aiff,
96    /// A FLAC stream, opening with the `fLaC` signature, read by
97    /// [`FlacReader`] and [`FlacStreamDecoder`].
98    Flac,
99}
100
101impl Container {
102    /// How many leading bytes identification reads.
103    ///
104    /// Twelve, because a four-CC at offset zero names a container *family* for
105    /// two of the three formats here and the form type at offset eight is what
106    /// separates a WAV from an AVI. Applied to `fLaC` as well, which needs only
107    /// four, so that an input too short to identify is one rule rather than
108    /// three.
109    pub const PROBE_BYTES: usize = 12;
110}
111
112impl fmt::Display for Container {
113    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
114        let name = match self {
115            Self::Wav => "WAV",
116            Self::Aiff => "AIFF",
117            Self::Flac => "FLAC",
118        };
119        f.write_str(name)
120    }
121}
122
123/// Says what `bytes` are, without decoding any of them.
124///
125/// Reads [`Container::PROBE_BYTES`] bytes and nothing else. Useful on its own,
126/// and it is what [`decode`] and [`AudioStreamDecoder`] are built on, so all
127/// three agree by construction rather than by review.
128///
129/// # Errors
130///
131/// - [`DecodeError::Truncated`] when the input is shorter than
132///   [`Container::PROBE_BYTES`]. A four-byte file that happens to start with
133///   `RIFF` is not a WAV, and guessing from a prefix is how a truncated
134///   download becomes a confusing parse failure much later.
135/// - [`DecodeError::UnsupportedContainer`] carrying the **form type** for a
136///   RIFF or RF64 file that is not `WAVE` and a `FORM` file that is neither
137///   `AIFF` nor `AIFC`, and carrying the **magic** for leading bytes that name
138///   no container this crate reads.
139///
140/// # Example
141///
142/// ```
143/// use decibri_decode::{identify, Container, DecodeError};
144///
145/// // A RIFF container that is not a WAV. Rejected by what is at offset
146/// // eight, naming what was found there.
147/// let mut avi = Vec::new();
148/// avi.extend_from_slice(b"RIFF");
149/// avi.extend_from_slice(&2048u32.to_le_bytes());
150/// avi.extend_from_slice(b"AVI ");
151/// assert!(matches!(
152///     identify(&avi),
153///     Err(DecodeError::UnsupportedContainer { tag }) if tag.as_bytes() == b"AVI "
154/// ));
155///
156/// // A FLAC stream needs no form type, but still needs twelve bytes.
157/// let mut flac = b"fLaC".to_vec();
158/// flac.extend_from_slice(&[0x80, 0x00, 0x00, 0x22, 0x10, 0x00, 0x10, 0x00]);
159/// assert_eq!(identify(&flac)?, Container::Flac);
160/// assert!(matches!(
161///     identify(&flac[..11]),
162///     Err(DecodeError::Truncated { expected: 12, available: 11 })
163/// ));
164/// # Ok::<(), DecodeError>(())
165/// ```
166pub fn identify(bytes: &[u8]) -> Result<Container, DecodeError> {
167    // Both reads are required, so any input under twelve bytes lands here
168    // whatever its first four bytes say.
169    let (Some(magic), Some(form)) = (riff::four_cc_at(bytes, 0), riff::four_cc_at(bytes, 8)) else {
170        return Err(DecodeError::Truncated {
171            expected: Container::PROBE_BYTES as u64,
172            available: bytes.len() as u64,
173        });
174    };
175
176    if magic == FLAC_MAGIC {
177        return Ok(Container::Flac);
178    }
179    if magic == riff::RIFF || magic == riff::RF64 {
180        return if form == riff::WAVE {
181            Ok(Container::Wav)
182        } else {
183            Err(DecodeError::UnsupportedContainer { tag: form })
184        };
185    }
186    if magic == aiff::FORM {
187        return if form == aiff::AIFF || form == aiff::AIFC {
188            Ok(Container::Aiff)
189        } else {
190            Err(DecodeError::UnsupportedContainer { tag: form })
191        };
192    }
193    Err(DecodeError::UnsupportedContainer { tag: magic })
194}
195
196/// Decodes a whole input, whatever of the carried formats it is.
197///
198/// The reader comes from the content by way of [`identify`]. The result is
199/// identical to constructing that reader by hand and calling its own
200/// `decode_to_end`, which is asserted rather than assumed.
201///
202/// The channel count of the returned buffer is never zero, on every carried
203/// container. [`AudioSpec`](crate::AudioSpec) and
204/// [`AudioBuffer::from_samples`](crate::AudioBuffer::from_samples) accept zero
205/// from a caller who states it, and this is a guarantee about what a decode
206/// produces rather than about what the types can hold.
207///
208/// # Errors
209///
210/// Everything [`identify`] returns, plus everything the chosen reader returns,
211/// unaltered.
212///
213/// # Example
214///
215/// ```
216/// use decibri_decode::{decode, AudioSpec, WavCodec, WavWriter};
217///
218/// let file = WavWriter::new(AudioSpec::mono(16_000), WavCodec::PcmI16)
219///     .to_bytes(&[0.0, 0.25, -0.25])?;
220///
221/// // Nothing here names WAV. The bytes do.
222/// let audio = decode(&file)?;
223/// assert_eq!(audio.sample_rate(), 16_000);
224/// assert_eq!(audio.samples(), [0.0, 0.25, -0.25]);
225/// # Ok::<(), decibri_decode::DecodeError>(())
226/// ```
227pub fn decode(bytes: &[u8]) -> Result<AudioBuffer, DecodeError> {
228    match identify(bytes)? {
229        Container::Wav => Ok(WavReader::new(bytes)?.decode_to_end()),
230        Container::Aiff => Ok(AiffReader::new(bytes)?.decode_to_end()),
231        Container::Flac => FlacReader::new(bytes)?.decode_to_end(),
232    }
233}
234
235/// The streaming reader the probe chose, held by value so its buffered-byte
236/// count stays reachable.
237///
238/// The FLAC arm is boxed and the other two are not. `FlacStreamDecoder` holds
239/// the predictor and residual working buffers a frame is reconstructed in and
240/// is some twenty times the size of the other two, so an unboxed enum would
241/// make every WAV stream carry FLAC's footprint. One allocation per FLAC
242/// stream is the cheaper side of that trade by a wide margin.
243#[derive(Debug)]
244enum Inner {
245    Wav(WavStreamDecoder),
246    Aiff(AiffStreamDecoder),
247    Flac(Box<FlacStreamDecoder>),
248}
249
250impl Inner {
251    /// The reader for `container`.
252    fn new(container: Container) -> Self {
253        match container {
254            Container::Wav => Self::Wav(WavStreamDecoder::new()),
255            Container::Aiff => Self::Aiff(AiffStreamDecoder::new()),
256            // `Box::default` rather than `Box::new(FlacStreamDecoder::new())`:
257            // the reader's `Default` is its `new`, and clippy is right that the
258            // longer form allocates a default and then overwrites it.
259            Container::Flac => Self::Flac(Box::default()),
260        }
261    }
262
263    /// The chosen reader as the trait every arm implements.
264    ///
265    /// [`StreamSource`] is object safe, so delegation is one line per method
266    /// here rather than one line per method per format.
267    fn source(&mut self) -> &mut dyn StreamSource {
268        match self {
269            Self::Wav(reader) => reader,
270            Self::Aiff(reader) => reader,
271            Self::Flac(reader) => reader.as_mut(),
272        }
273    }
274
275    /// The chosen reader, for the two methods that only read.
276    fn source_ref(&self) -> &dyn StreamSource {
277        match self {
278            Self::Wav(reader) => reader,
279            Self::Aiff(reader) => reader,
280            Self::Flac(reader) => reader.as_ref(),
281        }
282    }
283}
284
285/// Reads a stream that arrives in pieces, in whatever of the carried formats
286/// its leading bytes turn out to name.
287///
288/// # How it buffers
289///
290/// The first [`Container::PROBE_BYTES`] bytes are held rather than delegated,
291/// because there is no reader to delegate them to until they have all arrived.
292/// On the push that completes them the format is identified, the matching
293/// streaming reader is constructed, and the held bytes go into it **in front
294/// of** everything that follows, so the inner reader sees the stream from its
295/// first byte and not from byte thirteen. Whatever is left of that same push
296/// goes straight on to the inner reader, so a caller that hands over the whole
297/// file at once pays nothing for the indirection.
298///
299/// The buffer is twelve bytes and never grows: it is look-ahead, not a
300/// staging area, and every byte past identification is the inner reader's own
301/// business.
302///
303/// [`spec`](StreamSource::spec) is `None` until the inner reader knows it,
304/// which is strictly later than identification: knowing a stream is a WAV is
305/// not knowing its rate.
306///
307/// # Example
308///
309/// One byte at a time, which is the case that proves the buffering is real:
310/// identification spans twelve separate pushes and the audio still arrives.
311///
312/// ```
313/// use decibri_decode::{
314///     AudioSpec, AudioStreamDecoder, Container, StreamSource, WavCodec, WavWriter,
315/// };
316///
317/// let file = WavWriter::new(AudioSpec::mono(8_000), WavCodec::PcmI16)
318///     .to_bytes(&[0.0, 0.5, -0.5])?;
319///
320/// let mut stream = AudioStreamDecoder::new();
321/// let mut samples = Vec::new();
322/// for byte in &file {
323///     let mut offset = 0;
324///     while offset < 1 {
325///         offset += stream.push(&[*byte][offset..])?;
326///         while stream.pull(&mut samples, usize::MAX)? > 0 {}
327///     }
328/// }
329/// stream.finish(&mut samples)?;
330///
331/// assert_eq!(stream.container(), Some(Container::Wav));
332/// assert_eq!(samples, [0.0, 0.5, -0.5]);
333/// # Ok::<(), decibri_decode::DecodeError>(())
334/// ```
335#[derive(Debug)]
336pub struct AudioStreamDecoder {
337    /// The reader chosen from the leading bytes, once there have been enough
338    /// of them.
339    inner: Option<Inner>,
340    /// The leading bytes, held until there are [`Container::PROBE_BYTES`] of
341    /// them.
342    header: Vec<u8>,
343    /// How much of `header` the inner reader has taken. Everything it has not
344    /// taken is offered again before any later byte is.
345    fed: usize,
346    /// What the probe decided, kept because a caller usually wants to know and
347    /// cannot recover it from the samples.
348    container: Option<Container>,
349    finished: bool,
350}
351
352impl Default for AudioStreamDecoder {
353    fn default() -> Self {
354        Self::new()
355    }
356}
357
358impl AudioStreamDecoder {
359    /// A reader waiting for the first byte of a stream.
360    pub fn new() -> Self {
361        Self {
362            inner: None,
363            header: Vec::with_capacity(Container::PROBE_BYTES),
364            fed: 0,
365            container: None,
366            finished: false,
367        }
368    }
369
370    /// What the leading bytes turned out to be, once enough of them have
371    /// arrived.
372    ///
373    /// `None` before [`Container::PROBE_BYTES`] bytes have been pushed.
374    pub const fn container(&self) -> Option<Container> {
375        self.container
376    }
377
378    /// What the WAV `fmt ` chunk declared, once it has arrived.
379    ///
380    /// This is [`WavStreamDecoder::format`] on the reader the probe chose, so
381    /// a caller reaching the front door gets the same detail as one that
382    /// picked the reader by hand.
383    ///
384    /// `None` in three cases: before the stream has been identified at all,
385    /// for a stream identified as any container other than
386    /// [`Container::Wav`], and for a WAV whose `fmt ` chunk has not yet
387    /// arrived. Identification is not the header: knowing a stream is a WAV
388    /// happens twelve bytes in and the `fmt ` chunk is later.
389    pub const fn wav_format(&self) -> Option<WavFormat> {
390        match &self.inner {
391            Some(Inner::Wav(reader)) => reader.format(),
392            _ => None,
393        }
394    }
395
396    /// What the AIFF `COMM` chunk declared, once it has arrived.
397    ///
398    /// This is [`AiffStreamDecoder::format`] on the reader the probe chose.
399    ///
400    /// `None` before the stream has been identified, for a stream identified
401    /// as any container other than [`Container::Aiff`], and for an AIFF whose
402    /// `COMM` chunk has not yet arrived.
403    pub const fn aiff_format(&self) -> Option<AiffFormat> {
404        match &self.inner {
405            Some(Inner::Aiff(reader)) => reader.format(),
406            _ => None,
407        }
408    }
409
410    /// What the FLAC streaminfo metadata block declared, once it has arrived.
411    ///
412    /// This is [`FlacStreamDecoder::stream_info`] on the reader the probe
413    /// chose.
414    ///
415    /// `None` before the stream has been identified, for a stream identified
416    /// as any container other than [`Container::Flac`], and for a FLAC stream
417    /// whose streaminfo block has not yet arrived. The probe never reaches a
418    /// bare frame stream, so the value here is always a block read from the
419    /// stream rather than one derived from a first frame or supplied by a
420    /// caller.
421    pub fn flac_stream_info(&self) -> Option<FlacStreamInfo> {
422        match &self.inner {
423            Some(Inner::Flac(reader)) => reader.stream_info(),
424            _ => None,
425        }
426    }
427
428    /// What the end of a FLAC stream did about the streaminfo MD5.
429    ///
430    /// This is [`FlacStreamDecoder::md5_check`] on the reader the probe chose.
431    ///
432    /// `None` before the stream has been identified, for a stream identified
433    /// as any container other than [`Container::Flac`], and for a FLAC stream
434    /// on which [`finish`](StreamSource::finish) has not run. `None` is not a
435    /// verdict: the check happens at the end of the stream, and a decode that
436    /// has not finished has nothing to report.
437    pub fn flac_md5_check(&self) -> Option<Md5Check> {
438        match &self.inner {
439            Some(Inner::Flac(reader)) => reader.md5_check(),
440            _ => None,
441        }
442    }
443
444    /// Offers the held leading bytes to the inner reader, front first.
445    ///
446    /// A no-op before identification, and after it a loop rather than a single
447    /// push because [`StreamSource::push`] may take fewer bytes than it is
448    /// offered. In practice it never does here: the inner reader was
449    /// constructed a moment ago and has no decoded samples to apply
450    /// back-pressure with. The loop is written for the contract, not for the
451    /// case.
452    fn feed_header(&mut self) -> Result<(), DecodeError> {
453        while self.fed < self.header.len() {
454            let Some(inner) = self.inner.as_mut() else {
455                return Ok(());
456            };
457            let taken = inner.source().push(&self.header[self.fed..])?;
458            if taken == 0 {
459                break;
460            }
461            self.fed += taken;
462        }
463        Ok(())
464    }
465
466    /// The body of [`push`](StreamSource::push), split out so a failure sets
467    /// the finished flag in one place.
468    fn push_inner(&mut self, bytes: &[u8]) -> Result<usize, DecodeError> {
469        if self.inner.is_none() {
470            let want = Container::PROBE_BYTES - self.header.len();
471            let take = want.min(bytes.len());
472            self.header.extend_from_slice(&bytes[..take]);
473            if self.header.len() < Container::PROBE_BYTES {
474                return Ok(take);
475            }
476            let container = identify(&self.header)?;
477            self.container = Some(container);
478            self.inner = Some(Inner::new(container));
479            self.feed_header()?;
480            if self.fed < self.header.len() {
481                return Ok(take);
482            }
483            // Whatever is left of this push is ordinary stream data now.
484            let Some(inner) = self.inner.as_mut() else {
485                return Ok(take);
486            };
487            return Ok(take + inner.source().push(&bytes[take..])?);
488        }
489
490        self.feed_header()?;
491        if self.fed < self.header.len() {
492            return Ok(0);
493        }
494        let Some(inner) = self.inner.as_mut() else {
495            return Ok(0);
496        };
497        inner.source().push(bytes)
498    }
499}
500
501impl StreamSource for AudioStreamDecoder {
502    fn push(&mut self, bytes: &[u8]) -> Result<usize, DecodeError> {
503        if self.finished {
504            return Ok(0);
505        }
506        let result = self.push_inner(bytes);
507        if result.is_err() {
508            // A stream that has failed structurally is over, for the reason
509            // recorded on the WAV reader: a caller who keeps pushing must not
510            // get a second, different answer from the same stream.
511            self.finished = true;
512        }
513        result
514    }
515
516    fn pull(&mut self, output: &mut Vec<f32>, max_frames: usize) -> Result<usize, DecodeError> {
517        match self.inner.as_mut() {
518            Some(inner) => inner.source().pull(output, max_frames),
519            // Nothing has been identified yet, so nothing can be ready.
520            None => Ok(0),
521        }
522    }
523
524    fn spec(&self) -> Option<AudioSpec> {
525        self.inner
526            .as_ref()
527            .and_then(|inner| inner.source_ref().spec())
528    }
529
530    fn buffered_bytes(&self) -> usize {
531        (self.header.len() - self.fed)
532            + self
533                .inner
534                .as_ref()
535                .map_or(0, |inner| inner.source_ref().buffered_bytes())
536    }
537
538    fn finish(&mut self, output: &mut Vec<f32>) -> Result<usize, DecodeError> {
539        if self.finished {
540            return Ok(0);
541        }
542        self.finished = true;
543        // Anything still held belongs to the inner reader, which has to see it
544        // before it is asked whether the stream ended cleanly.
545        self.feed_header()?;
546        let Some(inner) = self.inner.as_mut() else {
547            // The stream ended before it could be identified. That is the same
548            // shortfall a whole-file caller gets from `identify`, reported the
549            // same way.
550            return Err(DecodeError::Truncated {
551                expected: Container::PROBE_BYTES as u64,
552                available: self.header.len() as u64,
553            });
554        };
555        inner.source().finish(output)
556    }
557
558    fn reset(&mut self) {
559        *self = Self::new();
560    }
561}
562
563#[cfg(test)]
564mod tests {
565    use super::*;
566    use crate::wav::{WavCodec, WavWriter};
567
568    /// A twelve-byte header with `magic` at zero and `form` at eight.
569    fn header(magic: &[u8; 4], form: &[u8; 4]) -> Vec<u8> {
570        let mut bytes = magic.to_vec();
571        bytes.extend_from_slice(&64u32.to_le_bytes());
572        bytes.extend_from_slice(form);
573        bytes
574    }
575
576    #[test]
577    fn the_three_carried_formats_are_identified_by_content() {
578        assert_eq!(identify(&header(b"RIFF", b"WAVE")).unwrap(), Container::Wav);
579        assert_eq!(identify(&header(b"RF64", b"WAVE")).unwrap(), Container::Wav);
580        assert_eq!(
581            identify(&header(b"FORM", b"AIFF")).unwrap(),
582            Container::Aiff
583        );
584        assert_eq!(
585            identify(&header(b"FORM", b"AIFC")).unwrap(),
586            Container::Aiff
587        );
588        assert_eq!(
589            identify(&header(b"fLaC", b"\0\0\0\0")).unwrap(),
590            Container::Flac
591        );
592    }
593
594    #[test]
595    fn a_riff_that_is_not_wave_is_rejected_by_its_form_type() {
596        // The trap a four-byte probe walks into. Every one of these is a real
597        // RIFF or IFF form type that is not audio this crate reads.
598        for form in [b"AVI ", b"ACON", b"RMID", b"CDXA"] {
599            let error = identify(&header(b"RIFF", form)).unwrap_err();
600            let DecodeError::UnsupportedContainer { tag } = error else {
601                panic!("a RIFF of form {form:?} was not rejected as a container: {error}");
602            };
603            assert_eq!(tag.as_bytes(), form, "the error names the form type found");
604        }
605    }
606
607    #[test]
608    fn a_form_that_is_not_aiff_or_aifc_is_rejected_by_its_form_type() {
609        for form in [b"8SVX", b"ILBM", b"ANBM", b"AIFZ"] {
610            let error = identify(&header(b"FORM", form)).unwrap_err();
611            let DecodeError::UnsupportedContainer { tag } = error else {
612                panic!("a FORM of type {form:?} was not rejected as a container: {error}");
613            };
614            assert_eq!(tag.as_bytes(), form);
615        }
616    }
617
618    #[test]
619    fn an_unknown_magic_is_named_by_its_leading_bytes() {
620        let error = identify(&header(b"OggS", b"\0\0\0\0")).unwrap_err();
621        let DecodeError::UnsupportedContainer { tag } = error else {
622            panic!("an Ogg page was not rejected as a container: {error}");
623        };
624        assert_eq!(tag.as_bytes(), b"OggS");
625    }
626
627    #[test]
628    fn every_length_under_the_probe_length_is_truncated_not_a_guess() {
629        let full = header(b"RIFF", b"WAVE");
630        for length in 0..Container::PROBE_BYTES {
631            let error = identify(&full[..length]).unwrap_err();
632            assert!(
633                matches!(
634                    error,
635                    DecodeError::Truncated { expected, available }
636                        if expected == Container::PROBE_BYTES as u64
637                            && available == length as u64
638                ),
639                "{length} bytes gave {error} rather than a truncation"
640            );
641        }
642    }
643
644    #[test]
645    fn a_prefix_that_would_identify_still_needs_the_whole_probe() {
646        // Four bytes of `fLaC` need no form type to be conclusive, and are
647        // still refused: "too short to identify" is one rule, not three.
648        assert!(matches!(
649            identify(b"fLaC"),
650            Err(DecodeError::Truncated { .. })
651        ));
652    }
653
654    #[test]
655    fn the_container_names_itself_for_a_report() {
656        assert_eq!(Container::Wav.to_string(), "WAV");
657        assert_eq!(Container::Aiff.to_string(), "AIFF");
658        assert_eq!(Container::Flac.to_string(), "FLAC");
659    }
660
661    #[test]
662    fn the_whole_file_path_matches_the_reader_it_chose() {
663        let samples = [0.0, 0.25, -0.25, 0.5];
664        let file = WavWriter::new(AudioSpec::new(16_000, 2), WavCodec::PcmI16)
665            .to_bytes(&samples)
666            .expect("a two-channel 16-bit WAV writes");
667        let direct = WavReader::new(&file)
668            .expect("the file opens")
669            .decode_to_end();
670        let probed = decode(&file).expect("the file opens through the probe");
671        assert_eq!(probed, direct);
672    }
673
674    #[test]
675    fn the_streaming_path_reports_what_it_identified_and_nothing_before() {
676        let file = WavWriter::new(AudioSpec::mono(8_000), WavCodec::PcmU8)
677            .to_bytes(&[0.0, 0.5])
678            .expect("an 8-bit WAV writes");
679
680        let mut stream = AudioStreamDecoder::new();
681        assert_eq!(stream.container(), None);
682        assert_eq!(stream.spec(), None);
683
684        // Eleven bytes is one short of identification.
685        assert_eq!(stream.push(&file[..11]).expect("eleven bytes"), 11);
686        assert_eq!(stream.container(), None);
687        assert_eq!(stream.buffered_bytes(), 11);
688
689        assert_eq!(stream.push(&file[11..12]).expect("the twelfth"), 1);
690        assert_eq!(stream.container(), Some(Container::Wav));
691        // Identified, but the rate is the inner reader's to know and it has
692        // not read `fmt ` yet.
693        assert_eq!(stream.spec(), None);
694        assert_eq!(stream.buffered_bytes(), 0);
695    }
696
697    #[test]
698    fn a_stream_that_ends_before_identification_is_truncated() {
699        let mut stream = AudioStreamDecoder::new();
700        assert_eq!(stream.push(b"RIFF\x40\x00").expect("six bytes"), 6);
701        let mut samples = Vec::new();
702        let error = stream.finish(&mut samples).unwrap_err();
703        assert!(
704            matches!(
705                error,
706                DecodeError::Truncated {
707                    expected: 12,
708                    available: 6
709                }
710            ),
711            "a stream cut inside the probe reported {error}"
712        );
713        // Idempotent, exactly as the trait requires.
714        assert_eq!(stream.finish(&mut samples).expect("second finish"), 0);
715    }
716
717    #[test]
718    fn a_failed_stream_stays_failed() {
719        let mut stream = AudioStreamDecoder::new();
720        let mut avi = b"RIFF".to_vec();
721        avi.extend_from_slice(&2048u32.to_le_bytes());
722        avi.extend_from_slice(b"AVI ");
723        assert!(stream.push(&avi).is_err());
724        // A caller who keeps pushing must not get a second answer.
725        assert_eq!(
726            stream.push(&avi).expect("a finished stream takes nothing"),
727            0
728        );
729    }
730
731    #[test]
732    fn reset_returns_the_stream_to_its_just_constructed_state() {
733        let file = WavWriter::new(AudioSpec::mono(8_000), WavCodec::PcmI16)
734            .to_bytes(&[0.0, 0.5])
735            .expect("a 16-bit WAV writes");
736        let mut stream = AudioStreamDecoder::new();
737        stream.push(&file).expect("the whole file at once");
738        assert_eq!(stream.container(), Some(Container::Wav));
739
740        stream.reset();
741        assert_eq!(stream.container(), None);
742        assert_eq!(stream.spec(), None);
743        assert_eq!(stream.buffered_bytes(), 0);
744    }
745}