Skip to main content

decibri_decode/
pcm.rs

1//! The decoder for headerless linear PCM.
2
3use crate::audio::AudioSpec;
4use crate::decoder::Decoder;
5use crate::error::DecodeError;
6use crate::sample::{SampleFormat, MAX_BYTES_PER_SAMPLE};
7
8/// How many decoded samples accumulate before [`feed`](Decoder::feed) stops
9/// taking bytes.
10///
11/// 65,536 `f32` is 256 KiB. A caller feeding ordinary 4 KiB blocks and draining
12/// between them never reaches it; a caller handing over a whole file in one call
13/// gets back-pressure and a bounded decoder rather than a buffer the size of the
14/// file. This is the short-return path the [`Decoder`] contract describes, and
15/// the reason it is implemented rather than assumed is that this is the first
16/// real implementation of that contract. A clause nothing exercises is a clause
17/// nobody has checked.
18const READY_LIMIT: usize = 65_536;
19
20/// Decodes a headerless linear PCM stream: bytes in one of the
21/// [`SampleFormat`]s, samples out at a [`AudioSpec`] the caller states.
22///
23/// Headerless PCM is what a microphone produces and what several streaming
24/// transports carry, so nothing declares its rate, layout or sample format:
25/// they arrive out of band and are given at construction. Both are then fixed
26/// for the life of the instance, as [`Decoder::output_spec`] requires.
27///
28/// # Partial samples and partial frames
29///
30/// A `feed` that ends part-way through a sample holds the leftover bytes until
31/// the rest arrive. Three bytes of a four-byte `f32` are not an error while the
32/// stream is open, and the boundary a caller happens to split its buffers on is
33/// not something a decoder gets to have an opinion about: feeding a stream in
34/// one slice, in 4096-byte slices or one byte at a time produces the same
35/// samples in the same order.
36///
37/// [`flush`](Decoder::flush) is where an incomplete item becomes
38/// [`DecodeError::Truncated`], and it counts *frames*, not samples. A stereo
39/// stream that ends after an odd number of samples ended mid-frame, and
40/// reporting that as a clean end would hand the caller a buffer whose length is
41/// not a whole number of frames.
42///
43/// # Example
44///
45/// ```
46/// use decibri_decode::{AudioSpec, Decoder, PcmDecoder, SampleFormat};
47///
48/// let mut decoder = PcmDecoder::new(SampleFormat::I16Le, AudioSpec::mono(16_000));
49/// let mut samples = Vec::new();
50///
51/// // 0x8000 is -1.0; 0x4000 is 0.5. The second sample arrives split in two.
52/// decoder.feed(&[0x00, 0x80, 0x00])?;
53/// decoder.decode(&mut samples)?;
54/// assert_eq!(samples, [-1.0]);
55///
56/// decoder.feed(&[0x40])?;
57/// decoder.decode(&mut samples)?;
58/// decoder.flush(&mut samples)?;
59/// assert_eq!(samples, [-1.0, 0.5]);
60/// # Ok::<(), decibri_decode::DecodeError>(())
61/// ```
62#[derive(Debug)]
63pub struct PcmDecoder {
64    /// The format of the bytes fed in.
65    format: SampleFormat,
66    /// The rate and layout of the samples produced.
67    spec: AudioSpec,
68    /// Bytes of a sample that has not fully arrived. Never more than one
69    /// sample's worth, which is why this is an array and not a `Vec`.
70    pending: [u8; MAX_BYTES_PER_SAMPLE],
71    /// How many of `pending` are live.
72    pending_len: usize,
73    /// Samples decoded but not yet handed to a caller.
74    ready: Vec<f32>,
75    /// Samples produced since construction or the last `reset`, which is what
76    /// says whether the stream is on a frame boundary.
77    produced: u64,
78    /// Set by `flush`: end of stream until `reset`.
79    finished: bool,
80}
81
82impl PcmDecoder {
83    /// A decoder for `format` bytes producing samples at `spec`.
84    ///
85    /// Nothing is validated because nothing can be: a headerless stream carries
86    /// no claim to check the arguments against. `spec` is the assertion.
87    pub const fn new(format: SampleFormat, spec: AudioSpec) -> Self {
88        Self {
89            format,
90            spec,
91            pending: [0; MAX_BYTES_PER_SAMPLE],
92            pending_len: 0,
93            ready: Vec::new(),
94            produced: 0,
95            finished: false,
96        }
97    }
98
99    /// The format this decoder reads.
100    pub const fn format(&self) -> SampleFormat {
101        self.format
102    }
103
104    /// How many bytes are held awaiting the rest of their frame.
105    ///
106    /// `0` means the stream is on a frame boundary and could be cut here
107    /// without loss, the same meaning the figure carries on
108    /// [`StreamSource::buffered_bytes`](crate::StreamSource::buffered_bytes),
109    /// and the same figure [`flush`](Decoder::flush) reports as `available`
110    /// when it rejects a truncated stream. It counts the bytes of an incomplete
111    /// sample *and* any whole samples sitting past the last frame boundary.
112    pub fn buffered_bytes(&self) -> usize {
113        let channels = u64::from(self.spec.channels).max(1);
114        let inside_frame = (self.produced % channels) as usize;
115        inside_frame * self.format.bytes_per_sample() + self.pending_len
116    }
117
118    /// How many bytes one whole frame occupies.
119    ///
120    /// A spec with no channels has no frame at all, so one sample stands in for
121    /// one: it keeps the truncation report meaningful instead of dividing by
122    /// zero, and matches [`AudioSpec::frames`] answering `0` rather than
123    /// panicking.
124    fn frame_bytes(&self) -> usize {
125        usize::from(self.spec.channels).max(1) * self.format.bytes_per_sample()
126    }
127
128    /// Decodes whole samples out of `bytes` into `ready`, keeping the running
129    /// count that `buffered_bytes` reads.
130    fn push_samples(&mut self, bytes: &[u8]) {
131        self.produced += self.format.decode(bytes, &mut self.ready) as u64;
132    }
133}
134
135impl Decoder for PcmDecoder {
136    fn output_spec(&self) -> AudioSpec {
137        self.spec
138    }
139
140    fn feed(&mut self, input: &[u8]) -> Result<usize, DecodeError> {
141        if self.finished {
142            return Ok(0);
143        }
144        // Room is counted in samples, so a format's width decides how many
145        // bytes that is. At zero, the caller has to drain before feeding again.
146        let mut room = READY_LIMIT.saturating_sub(self.ready.len());
147        if room == 0 {
148            return Ok(0);
149        }
150
151        let width = self.format.bytes_per_sample();
152        let mut taken = 0;
153
154        // A sample left half-arrived by an earlier feed is completed from the
155        // head of this one, before anything else is looked at.
156        if self.pending_len > 0 {
157            let take = (width - self.pending_len).min(input.len());
158            self.pending[self.pending_len..self.pending_len + take].copy_from_slice(&input[..take]);
159            self.pending_len += take;
160            taken = take;
161            if self.pending_len < width {
162                // Still short. Hold it; the rest is not late, it is unsent.
163                return Ok(taken);
164            }
165            let completed = self.pending;
166            self.push_samples(&completed[..width]);
167            self.pending_len = 0;
168            room -= 1;
169        }
170
171        let rest = &input[taken..];
172        let whole = (rest.len() / width).min(room) * width;
173        self.push_samples(&rest[..whole]);
174        taken += whole;
175
176        // Whatever is left is either a partial sample, which is held, or bytes
177        // that did not fit in `room`, which are left for the caller to offer
178        // again once they have drained.
179        let tail = &input[taken..];
180        if tail.len() < width {
181            self.pending[..tail.len()].copy_from_slice(tail);
182            self.pending_len = tail.len();
183            taken += tail.len();
184        }
185        Ok(taken)
186    }
187
188    fn decode(&mut self, output: &mut Vec<f32>) -> Result<usize, DecodeError> {
189        if self.finished {
190            return Ok(0);
191        }
192        let produced = self.ready.len();
193        output.append(&mut self.ready);
194        Ok(produced)
195    }
196
197    fn flush(&mut self, output: &mut Vec<f32>) -> Result<usize, DecodeError> {
198        if self.finished {
199            return Ok(0);
200        }
201        self.finished = true;
202        let held = self.buffered_bytes();
203        if held > 0 {
204            // The one place a partial frame is an error. A caller following the
205            // documented loop has already drained everything whole through
206            // `decode`, so nothing complete is lost with the rejection.
207            return Err(DecodeError::Truncated {
208                expected: self.frame_bytes() as u64,
209                available: held as u64,
210            });
211        }
212        let produced = self.ready.len();
213        output.append(&mut self.ready);
214        Ok(produced)
215    }
216
217    fn reset(&mut self) {
218        self.pending_len = 0;
219        self.ready.clear();
220        self.produced = 0;
221        self.finished = false;
222    }
223}
224
225#[cfg(test)]
226mod tests {
227    use super::*;
228    use crate::audio::AudioBuffer;
229    use crate::sample::{I24_MAX, I24_MIN};
230
231    const ALL: [SampleFormat; 12] = [
232        SampleFormat::U8,
233        SampleFormat::I8,
234        SampleFormat::I16Le,
235        SampleFormat::I16Be,
236        SampleFormat::I24Le,
237        SampleFormat::I24Be,
238        SampleFormat::I32Le,
239        SampleFormat::I32Be,
240        SampleFormat::F32Le,
241        SampleFormat::F32Be,
242        SampleFormat::F64Le,
243        SampleFormat::F64Be,
244    ];
245
246    /// Drives a decoder to completion over `input` split into `chunk`-byte
247    /// pieces, the way the trait documents a caller should.
248    fn drive(
249        decoder: &mut dyn Decoder,
250        input: &[u8],
251        chunk: usize,
252    ) -> Result<AudioBuffer, DecodeError> {
253        let mut samples = Vec::new();
254        for piece in input.chunks(chunk) {
255            let mut offset = 0;
256            while offset < piece.len() {
257                offset += decoder.feed(&piece[offset..])?;
258                while decoder.decode(&mut samples)? > 0 {}
259            }
260        }
261        decoder.flush(&mut samples)?;
262        Ok(AudioBuffer::from_samples(decoder.output_spec(), samples))
263    }
264
265    fn encode(format: SampleFormat, samples: &[f32]) -> Vec<u8> {
266        let mut bytes = Vec::new();
267        format.encode(samples, &mut bytes);
268        bytes
269    }
270
271    #[test]
272    fn a_headerless_stream_decodes_at_the_spec_it_was_given() {
273        let mut decoder = PcmDecoder::new(SampleFormat::I16Le, AudioSpec::mono(8_000));
274        assert_eq!(decoder.format(), SampleFormat::I16Le);
275        assert_eq!(decoder.output_spec(), AudioSpec::mono(8_000));
276
277        // Hand-written: 0x0000, 0x4000, 0x8000, 0xC000 little-endian.
278        let bytes = [0x00, 0x00, 0x00, 0x40, 0x00, 0x80, 0x00, 0xc0];
279        let decoded = drive(&mut decoder, &bytes, 64).expect("decode");
280        assert_eq!(decoded.samples(), [0.0, 0.5, -1.0, -0.5]);
281        assert_eq!(decoded.sample_rate(), 8_000);
282        assert_eq!(decoded.frames(), 4);
283    }
284
285    /// The property the whole partial-sample machinery exists for: where a byte
286    /// lands in the feed sequence makes no difference to the output. One byte
287    /// at a time splits every format mid-sample; the primes split the wide ones
288    /// at every possible offset.
289    #[test]
290    fn the_feed_boundary_is_invisible_for_every_format() {
291        let samples: Vec<f32> = (0..64).map(|i| (i as f32 / 32.0) - 1.0).collect();
292        for format in ALL {
293            let bytes = encode(format, &samples);
294            let reference = {
295                let mut decoder = PcmDecoder::new(format, AudioSpec::mono(16_000));
296                drive(&mut decoder, &bytes, bytes.len()).expect("whole-input decode")
297            };
298            for chunk in [1, 2, 3, 5, 7, 8, 13, 64] {
299                let mut decoder = PcmDecoder::new(format, AudioSpec::mono(16_000));
300                let decoded = drive(&mut decoder, &bytes, chunk).expect("chunked decode");
301                assert_eq!(
302                    decoded.samples(),
303                    reference.samples(),
304                    "{format:?} changed with a {chunk}-byte feed size"
305                );
306            }
307        }
308    }
309
310    /// A partial sample is held rather than rejected, across as many feeds as
311    /// it takes. Eight bytes of `f64` delivered one at a time produce nothing
312    /// until the eighth.
313    #[test]
314    fn a_partial_sample_is_held_until_the_rest_arrives() {
315        let mut decoder = PcmDecoder::new(SampleFormat::F64Be, AudioSpec::mono(48_000));
316        let bytes = [0x3f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; // 1.0
317        let mut out = Vec::new();
318
319        for (index, byte) in bytes.iter().enumerate() {
320            assert_eq!(decoder.feed(&[*byte]).expect("feed"), 1);
321            let produced = decoder.decode(&mut out).expect("decode");
322            if index < 7 {
323                assert_eq!(produced, 0, "byte {index} completed a sample too early");
324                assert_eq!(decoder.buffered_bytes(), index + 1);
325            } else {
326                assert_eq!(produced, 1, "the last byte must complete the sample");
327                assert_eq!(decoder.buffered_bytes(), 0);
328            }
329        }
330        assert_eq!(out, [1.0]);
331        assert_eq!(decoder.flush(&mut out).expect("flush"), 0);
332    }
333
334    /// A sample split across a feed boundary is reassembled from both halves,
335    /// not dropped and not decoded twice.
336    #[test]
337    fn a_sample_split_across_two_feeds_is_reassembled() {
338        let mut decoder = PcmDecoder::new(SampleFormat::I24Le, AudioSpec::mono(44_100));
339        let mut out = Vec::new();
340        // 0x7FFFFF, the largest positive 24-bit value, split 2 + 1.
341        assert_eq!(decoder.feed(&[0xff, 0xff]).expect("feed"), 2);
342        assert_eq!(decoder.decode(&mut out).expect("decode"), 0);
343        assert_eq!(decoder.buffered_bytes(), 2);
344        assert_eq!(decoder.feed(&[0x7f]).expect("feed"), 1);
345        assert_eq!(decoder.decode(&mut out).expect("decode"), 1);
346        assert_eq!(out, [8_388_607.0 / 8_388_608.0]);
347    }
348
349    /// A feed that spans the end of one pending sample and the start of the
350    /// next partial one leaves exactly the right tail behind.
351    #[test]
352    fn a_feed_completing_one_sample_and_starting_another_holds_only_the_tail() {
353        let mut decoder = PcmDecoder::new(SampleFormat::I32Le, AudioSpec::mono(16_000));
354        let mut out = Vec::new();
355        assert_eq!(decoder.feed(&[0x00, 0x00]).expect("feed"), 2);
356        // Completes the first sample (four bytes) and leaves three of the next.
357        assert_eq!(
358            decoder.feed(&[0x00, 0x40, 0x11, 0x22, 0x33]).expect("feed"),
359            5
360        );
361        assert_eq!(decoder.decode(&mut out).expect("decode"), 1);
362        assert_eq!(out, [0.5]);
363        assert_eq!(decoder.buffered_bytes(), 3);
364    }
365
366    /// End of stream with part of a sample held is the one place a partial item
367    /// is an error, and the error names the frame it was short of.
368    #[test]
369    fn a_partial_sample_at_end_of_stream_is_truncated() {
370        let mut decoder = PcmDecoder::new(SampleFormat::I32Be, AudioSpec::mono(16_000));
371        decoder.feed(&[0x11, 0x22, 0x33]).expect("feed");
372        let mut out = Vec::new();
373        let error = decoder.flush(&mut out).expect_err("flush must reject");
374        assert!(
375            matches!(
376                error,
377                DecodeError::Truncated {
378                    expected: 4,
379                    available: 3
380                }
381            ),
382            "unexpected error: {error}"
383        );
384        // Idempotent: the second flush is a quiet no-op, not a second error.
385        assert_eq!(decoder.flush(&mut out).expect("second flush"), 0);
386    }
387
388    /// A stereo stream that ends after an odd number of samples ended
389    /// mid-frame. Reporting that as a clean end would hand back a buffer whose
390    /// length is not a whole number of frames.
391    #[test]
392    fn a_partial_frame_at_end_of_stream_is_truncated() {
393        let mut decoder = PcmDecoder::new(SampleFormat::I16Le, AudioSpec::new(44_100, 2));
394        let mut out = Vec::new();
395        // One whole sample: half a stereo frame.
396        decoder.feed(&[0x00, 0x40]).expect("feed");
397        assert_eq!(decoder.decode(&mut out).expect("decode"), 1);
398        assert_eq!(
399            decoder.buffered_bytes(),
400            2,
401            "one sample into a 4-byte frame"
402        );
403
404        let error = decoder.flush(&mut out).expect_err("flush must reject");
405        assert!(
406            matches!(
407                error,
408                DecodeError::Truncated {
409                    expected: 4,
410                    available: 2
411                }
412            ),
413            "unexpected error: {error}"
414        );
415
416        // And the same stream one sample longer ends cleanly.
417        let mut decoder = PcmDecoder::new(SampleFormat::I16Le, AudioSpec::new(44_100, 2));
418        let decoded = drive(&mut decoder, &[0x00, 0x40, 0x00, 0xc0], 3).expect("decode");
419        assert_eq!(decoded.frames(), 1);
420        assert_eq!(decoded.samples(), [0.5, -0.5]);
421    }
422
423    /// Three of a stereo frame's four bytes: a partial sample and a partial
424    /// frame at once, reported against the frame.
425    #[test]
426    fn a_partial_sample_inside_a_partial_frame_reports_the_frame() {
427        let mut decoder = PcmDecoder::new(SampleFormat::I16Be, AudioSpec::new(48_000, 2));
428        decoder.feed(&[0x01, 0x02, 0x03]).expect("feed");
429        let mut out = Vec::new();
430        while decoder.decode(&mut out).expect("decode") > 0 {}
431        assert_eq!(decoder.buffered_bytes(), 3);
432        let error = decoder.flush(&mut out).expect_err("flush must reject");
433        assert!(
434            matches!(
435                error,
436                DecodeError::Truncated {
437                    expected: 4,
438                    available: 3
439                }
440            ),
441            "unexpected error: {error}"
442        );
443    }
444
445    /// The sample-count guarantee, stated for this decoder: `n` frames in,
446    /// exactly `n * channels` samples out, whatever the feed size.
447    #[test]
448    fn the_sample_count_is_exact_for_every_format_and_layout() {
449        for format in ALL {
450            for channels in [1_u16, 2, 6] {
451                let frames = 50;
452                let spec = AudioSpec::new(48_000, channels);
453                let count = frames * usize::from(channels);
454                let bytes = encode(format, &vec![0.125; count]);
455                let mut decoder = PcmDecoder::new(format, spec);
456                let decoded = drive(&mut decoder, &bytes, 13).expect("decode");
457                assert_eq!(
458                    decoded.samples().len(),
459                    count,
460                    "{format:?} at {channels} channels produced the wrong count"
461                );
462                assert_eq!(decoded.frames(), frames);
463            }
464        }
465    }
466
467    /// A starved decoder says `0`, which means "feed me", not "end of stream".
468    #[test]
469    fn a_starved_decoder_reports_zero_rather_than_end_of_stream() {
470        let mut decoder = PcmDecoder::new(SampleFormat::I16Le, AudioSpec::mono(16_000));
471        let mut out = Vec::new();
472        assert_eq!(decoder.decode(&mut out).expect("decode"), 0);
473        assert_eq!(decoder.feed(&[0x01]).expect("feed"), 1);
474        assert_eq!(decoder.decode(&mut out).expect("decode"), 0);
475        assert!(out.is_empty());
476        assert_eq!(decoder.feed(&[0x02]).expect("feed"), 1);
477        assert_eq!(decoder.decode(&mut out).expect("decode"), 1);
478    }
479
480    #[test]
481    fn feeding_after_flush_is_quiet_until_reset() {
482        let mut decoder = PcmDecoder::new(SampleFormat::U8, AudioSpec::mono(8_000));
483        let mut out = Vec::new();
484        assert_eq!(decoder.flush(&mut out).expect("flush"), 0);
485        assert_eq!(decoder.feed(&[0x80]).expect("feed"), 0);
486        assert_eq!(decoder.decode(&mut out).expect("decode"), 0);
487        assert!(out.is_empty());
488
489        decoder.reset();
490        assert_eq!(decoder.feed(&[0xff]).expect("feed"), 1);
491        assert_eq!(decoder.decode(&mut out).expect("decode"), 1);
492        assert_eq!(out, [127.0 / 128.0]);
493    }
494
495    /// `reset` drops a held partial sample and the frame position with it, so
496    /// the next stream starts on a boundary rather than inheriting one.
497    #[test]
498    fn reset_drops_a_held_partial_frame() {
499        let mut decoder = PcmDecoder::new(SampleFormat::I16Le, AudioSpec::new(16_000, 2));
500        decoder.feed(&[0x01, 0x02, 0x03]).expect("feed");
501        assert_eq!(decoder.buffered_bytes(), 3);
502        decoder.reset();
503        assert_eq!(decoder.buffered_bytes(), 0);
504        let mut out = Vec::new();
505        assert_eq!(decoder.flush(&mut out).expect("flush after reset"), 0);
506    }
507
508    /// Back-pressure: a caller that hands over more than the decoder will hold
509    /// gets a short return and has to drain. Nothing is lost and the loop still
510    /// terminates, the property that makes the short return usable rather than
511    /// merely permitted.
512    #[test]
513    fn a_full_decoder_applies_back_pressure_instead_of_growing() {
514        let spec = AudioSpec::mono(16_000);
515        let mut decoder = PcmDecoder::new(SampleFormat::U8, spec);
516        // Three times what the decoder will hold, so the short return is
517        // unavoidable rather than incidental.
518        let bytes: Vec<u8> = (0..READY_LIMIT * 3).map(|i| (i % 256) as u8).collect();
519
520        let first = decoder.feed(&bytes).expect("feed");
521        assert!(first < bytes.len(), "a full decoder must return short");
522        assert_eq!(first, READY_LIMIT);
523        assert_eq!(decoder.feed(&bytes[first..]).expect("feed"), 0);
524
525        let decoded = drive(&mut decoder, &bytes, bytes.len()).expect("decode");
526        // The first feed's samples are still in there, ahead of the rest.
527        assert_eq!(decoded.samples().len(), bytes.len() + first);
528    }
529
530    /// Every format decodes what it encoded through the full decoder, at the
531    /// values where each format's edges live.
532    #[test]
533    fn every_format_survives_the_decoder_round_trip() {
534        let edges = [0.0_f32, 0.5, -0.5, 1.0, -1.0, 1.0 / 128.0, -0.75];
535        for format in ALL {
536            let bytes = encode(format, &edges);
537            let mut decoder = PcmDecoder::new(format, AudioSpec::mono(16_000));
538            let decoded = drive(&mut decoder, &bytes, 5).expect("decode");
539            assert_eq!(decoded.samples().len(), edges.len());
540            for (original, recovered) in edges.iter().zip(decoded.samples()) {
541                // 1/128 is the 8-bit step; every wider format is exact here.
542                assert!(
543                    (original - recovered).abs() <= 1.0 / 128.0,
544                    "{format:?}: {original} came back as {recovered}"
545                );
546            }
547        }
548    }
549
550    /// The extreme raw values of each integer format, fed as bytes rather than
551    /// produced by this crate's encoder.
552    #[test]
553    fn the_integer_extremes_decode_to_the_expected_floats() {
554        let cases: [(SampleFormat, &[u8], f32); 6] = [
555            (SampleFormat::U8, &[0x00], -1.0),
556            (SampleFormat::I16Be, &[0x80, 0x00], -1.0),
557            (SampleFormat::I16Be, &[0x7f, 0xff], 32767.0 / 32768.0),
558            (SampleFormat::I24Be, &[0x80, 0x00, 0x00], -1.0),
559            (SampleFormat::I32Be, &[0x80, 0x00, 0x00, 0x00], -1.0),
560            (SampleFormat::I32Be, &[0x7f, 0xff, 0xff, 0xff], 1.0),
561        ];
562        for (format, bytes, expected) in cases {
563            let mut decoder = PcmDecoder::new(format, AudioSpec::mono(8_000));
564            let decoded = drive(&mut decoder, bytes, 1).expect("decode");
565            assert_eq!(decoded.samples(), [expected], "{format:?} on {bytes:02x?}");
566        }
567        // And the packed 24-bit bounds agree with the constants.
568        assert_eq!(I24_MIN, -8_388_608);
569        assert_eq!(I24_MAX, 8_388_607);
570    }
571
572    #[test]
573    fn the_decoder_is_object_safe_and_sendable() {
574        fn assert_send<T: Send>() {}
575        assert_send::<PcmDecoder>();
576
577        let boxed: Box<dyn Decoder> = Box::new(PcmDecoder::new(
578            SampleFormat::F32Le,
579            AudioSpec::new(44_100, 2),
580        ));
581        assert_eq!(boxed.output_spec().channels, 2);
582    }
583
584    /// A spec with no channels is degenerate but must not divide by zero.
585    #[test]
586    fn a_zero_channel_spec_does_not_divide_by_zero() {
587        let mut decoder = PcmDecoder::new(SampleFormat::I16Le, AudioSpec::new(16_000, 0));
588        let mut out = Vec::new();
589        decoder.feed(&[0x00, 0x40]).expect("feed");
590        assert_eq!(decoder.decode(&mut out).expect("decode"), 1);
591        assert_eq!(decoder.buffered_bytes(), 0);
592        assert_eq!(decoder.flush(&mut out).expect("flush"), 0);
593    }
594
595    // -- Gate 10: cross-platform determinism ------------------------------
596
597    /// FNV-1a over the little-endian bit patterns of the samples, so the
598    /// witness is the bytes themselves and not a float comparison.
599    fn fnv1a(samples: &[f32]) -> u64 {
600        let mut hash = 0xcbf2_9ce4_8422_2325_u64;
601        for sample in samples {
602            for byte in sample.to_bits().to_le_bytes() {
603                hash ^= u64::from(byte);
604                hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
605            }
606        }
607        hash
608    }
609
610    /// A fixed signal, built from integer arithmetic and an exact division by a
611    /// power of two so it is the same on every target.
612    ///
613    /// The last two values are past full scale, so the witness covers the
614    /// clamping path as well as the ordinary one.
615    fn witness_signal() -> Vec<f32> {
616        let mut state = 0x2545_F491_4F6C_DD1D_u64;
617        let mut signal: Vec<f32> = (0..254)
618            .map(|_| {
619                state = state
620                    .wrapping_mul(6_364_136_223_846_793_005)
621                    .wrapping_add(1_442_695_040_888_963_407);
622                crate::sample::i32_to_f32((state >> 32) as u32 as i32)
623            })
624            .collect();
625        signal.push(1.5);
626        signal.push(-3.0);
627        signal
628    }
629
630    /// One number that changes if any bit of any decoded sample changes, for a
631    /// fixed signal put through every format.
632    ///
633    /// The claim on this crate is bit-exact, cross-platform, byte-identical
634    /// output. Running this on two toolchains and getting the same constant is
635    /// the evidence for it; a tolerance-based test would pass on both while the
636    /// outputs differed. The constant is pinned rather than recomputed at run
637    /// time so that a change shows up as a diff in this file.
638    ///
639    /// The signal is encoded and decoded rather than fed as arbitrary bytes,
640    /// which keeps it a statement about real audio. That used to be load-bearing
641    /// as well: arbitrary bytes reach `f64` as a NaN roughly once in a thousand
642    /// samples, and the bit pattern a NaN keeps through the `f64` to `f32`
643    /// narrowing is not something IEEE 754 pins down. It is no longer a
644    /// constraint: that narrowing now normalises NaN to silence, so the witness
645    /// would hold over arbitrary bytes too.
646    #[test]
647    fn decoded_output_is_bit_identical_to_a_pinned_witness() {
648        let signal = witness_signal();
649        let mut samples = Vec::new();
650        for format in ALL {
651            let bytes = encode(format, &signal);
652            let mut decoder = PcmDecoder::new(format, AudioSpec::mono(16_000));
653            // 7 is coprime with every sample width here, so each format is
654            // driven across its partial-sample path as well as its whole one.
655            let decoded = drive(&mut decoder, &bytes, 7).expect("decode");
656            samples.extend_from_slice(decoded.samples());
657        }
658        assert_eq!(samples.len(), ALL.len() * signal.len());
659        // Re-pinned when `I8` joined `ALL`: the witness now covers twelve
660        // formats rather than eleven, so its input, and therefore its value,
661        // changed. The eleven original formats are unchanged, which the WAV
662        // conformance witness attests independently: it hashes the same
663        // decode paths and did not move.
664        assert_eq!(
665            fnv1a(&samples),
666            0x57ac_66d6_2a28_b665,
667            "decoded output changed"
668        );
669    }
670}