Skip to main content

decibri_decode/
decoder.rs

1//! The decoder boundary: bytes in, samples out.
2
3use crate::audio::AudioSpec;
4use crate::error::DecodeError;
5
6/// Turns encoded frames into `f32` samples.
7///
8/// # Why this shape
9///
10/// The trait is a *pull* model, feed bytes and then pull whatever samples are
11/// ready, rather than a chunk-in-chunk-out function. Nothing in the pure-PCM
12/// codecs needs that: they are stateless and a byte slice maps to a sample
13/// slice. MP3 does. Its bit reservoir lets a frame borrow bits from earlier
14/// frames, so a decoder must be able to accept bytes that produce nothing yet
15/// and produce samples from bytes it accepted earlier. Establishing that here
16/// costs almost nothing; establishing it once four codecs are written above a
17/// chunk-in-chunk-out API means rewriting all of them.
18///
19/// The trait is [object safe](https://doc.rust-lang.org/reference/items/traits.html#object-safety),
20/// because the decoder for a given input is chosen at run time from what the
21/// container turned out to declare, and because platform decoders, AudioToolbox
22/// on iOS, MediaCodec on Android, both hardware-accelerated and already licensed
23/// by the platform vendor, must be able to sit behind the same `dyn Decoder`
24/// as the crate's own. That is the single most expensive property here to
25/// retrofit.
26///
27/// Implementations are [`Send`], so an instance can be constructed on one
28/// thread and driven on another.
29///
30/// # Contract
31///
32/// - [`output_spec`](Decoder::output_spec) is fixed for the life of the
33///   instance and known at construction, because a decoder is built by whatever
34///   parsed the header. A stream whose header has not arrived has no decoder
35///   yet; see [`StreamSource::spec`](crate::StreamSource::spec).
36/// - [`feed`](Decoder::feed) may consume less than it is offered and may
37///   produce nothing. [`decode`](Decoder::decode) may produce samples from
38///   bytes fed in earlier calls. Neither is one-in-one-out and neither assumes
39///   the caller holds the whole input.
40/// - Where a byte lands in the feed sequence makes no difference to the output.
41///   Feeding a file in one slice, in 4096-byte slices, or one byte at a time
42///   produces the same samples in the same order.
43/// - After [`flush`](Decoder::flush), the decoder is at end of stream:
44///   `feed` consumes nothing and `decode` produces nothing until
45///   [`reset`](Decoder::reset). This mirrors
46///   `decibri_resampler::Resampler`, except that it is a quiet no-op rather
47///   than an error, because [`DecodeError`] has no variant for driving a
48///   decoder wrongly and is not going to grow one.
49///
50/// # Sample-count guarantee
51///
52/// For an input the container describes as `n` frames, the totals across a
53/// full `feed`/`decode`/`flush` sequence come to exactly `n * channels`
54/// samples. Not approximately, and not "plus whatever the last partial frame
55/// yields". A codec that cannot state its output count for a given input does
56/// not belong behind this trait.
57pub trait Decoder: Send {
58    /// The rate and layout of the samples this decoder produces.
59    ///
60    /// Fixed for the life of the instance. This is the authority for the rate
61    /// of everything [`decode`](Decoder::decode) and [`flush`](Decoder::flush)
62    /// append; pair the two with
63    /// [`AudioBuffer::from_samples`](crate::AudioBuffer::from_samples) at the
64    /// point where the samples travel any further.
65    fn output_spec(&self) -> AudioSpec;
66
67    /// Hands `input` to the decoder and returns how many of its bytes were
68    /// taken.
69    ///
70    /// A short return means the decoder's internal buffer is full: drain it
71    /// with [`decode`](Decoder::decode) and offer the remainder again. A return
72    /// of `input.len()` does not mean any samples are ready, and a return of
73    /// `0` does not mean the input is bad.
74    ///
75    /// A partial frame at the end of `input` is held, not rejected. It is only
76    /// an error if the stream then ends; see [`flush`](Decoder::flush).
77    ///
78    /// # Errors
79    ///
80    /// Returns [`DecodeError::Malformed`] when the accepted bytes cannot be a
81    /// valid continuation of the stream at all. Running out of bytes is not an
82    /// error here.
83    fn feed(&mut self, input: &[u8]) -> Result<usize, DecodeError>;
84
85    /// Appends every sample the decoder can produce from what it has been fed,
86    /// and returns how many it appended.
87    ///
88    /// `output` is appended to, never cleared, and the caller owns it, the
89    /// same convention as `decibri_resampler::Resampler::process`, so a
90    /// decoder's output vector feeds a resampler with no copy in between.
91    ///
92    /// A return of `0` means "starved, feed me more", not "end of stream".
93    /// Callers loop `decode` until it returns `0`, then `feed` again.
94    ///
95    /// # Errors
96    ///
97    /// Returns [`DecodeError::Malformed`] when a buffered frame turns out to be
98    /// invalid once enough of it has arrived to judge.
99    fn decode(&mut self, output: &mut Vec<f32>) -> Result<usize, DecodeError>;
100
101    /// Declares end of input, appends any remaining samples and returns how
102    /// many were appended.
103    ///
104    /// Call it once the last byte has been fed. Codecs with a decode tail emit
105    /// it here; codecs without one append nothing and return `0`. It is
106    /// idempotent.
107    ///
108    /// # Errors
109    ///
110    /// Returns [`DecodeError::Truncated`] when bytes of an incomplete frame are
111    /// still held. That is the one place a partial frame becomes an error:
112    /// while the stream is open it is simply data that has not arrived yet.
113    fn flush(&mut self, output: &mut Vec<f32>) -> Result<usize, DecodeError>;
114
115    /// Returns the decoder to its just-constructed state.
116    ///
117    /// Buffered bytes, undelivered samples and any end-of-stream condition set
118    /// by [`flush`](Decoder::flush) are dropped. The output spec is unchanged.
119    /// Use it to decode a second stream on the same instance, or to resume
120    /// after a seek.
121    fn reset(&mut self);
122}
123
124#[cfg(test)]
125mod tests {
126    use super::*;
127    use crate::audio::AudioBuffer;
128
129    /// A decoder whose "codec" is the identity: four input bytes are one
130    /// output sample, read back as the `f32` they already were.
131    ///
132    /// It exists to prove the trait can actually be implemented and used
133    /// through `dyn Decoder`. A trait that compiles but cannot be implemented
134    /// is the failure this fixture catches. It is `#[cfg(test)]` and never
135    /// ships in the crate proper, because this crate contains no codec.
136    struct PassThrough {
137        spec: AudioSpec,
138        /// Bytes fed but not yet forming a whole sample. Never more than three.
139        pending: Vec<u8>,
140        /// Samples decoded but not yet handed back.
141        ready: Vec<f32>,
142        finished: bool,
143    }
144
145    impl PassThrough {
146        fn new(spec: AudioSpec) -> Self {
147            Self {
148                spec,
149                pending: Vec::new(),
150                ready: Vec::new(),
151                finished: false,
152            }
153        }
154    }
155
156    impl Decoder for PassThrough {
157        fn output_spec(&self) -> AudioSpec {
158            self.spec
159        }
160
161        fn feed(&mut self, input: &[u8]) -> Result<usize, DecodeError> {
162            if self.finished {
163                return Ok(0);
164            }
165            self.pending.extend_from_slice(input);
166            let whole = self.pending.len() / 4 * 4;
167            for chunk in self.pending[..whole].chunks_exact(4) {
168                let bytes: [u8; 4] = chunk.try_into().expect("chunks_exact(4) yields 4 bytes");
169                self.ready.push(f32::from_ne_bytes(bytes));
170            }
171            self.pending.drain(..whole);
172            Ok(input.len())
173        }
174
175        fn decode(&mut self, output: &mut Vec<f32>) -> Result<usize, DecodeError> {
176            if self.finished {
177                return Ok(0);
178            }
179            let produced = self.ready.len();
180            output.append(&mut self.ready);
181            Ok(produced)
182        }
183
184        fn flush(&mut self, output: &mut Vec<f32>) -> Result<usize, DecodeError> {
185            if self.finished {
186                return Ok(0);
187            }
188            self.finished = true;
189            if !self.pending.is_empty() {
190                return Err(DecodeError::Truncated {
191                    expected: 4,
192                    available: self.pending.len() as u64,
193                });
194            }
195            let produced = self.ready.len();
196            output.append(&mut self.ready);
197            Ok(produced)
198        }
199
200        fn reset(&mut self) {
201            self.pending.clear();
202            self.ready.clear();
203            self.finished = false;
204        }
205    }
206
207    fn encode(samples: &[f32]) -> Vec<u8> {
208        samples.iter().flat_map(|s| s.to_ne_bytes()).collect()
209    }
210
211    /// Drives a decoder to completion over `input` split into `chunk` byte
212    /// pieces, the way a caller is expected to.
213    fn drive(
214        decoder: &mut dyn Decoder,
215        input: &[u8],
216        chunk: usize,
217    ) -> Result<AudioBuffer, DecodeError> {
218        let mut samples = Vec::new();
219        for piece in input.chunks(chunk) {
220            let mut offset = 0;
221            while offset < piece.len() {
222                offset += decoder.feed(&piece[offset..])?;
223                while decoder.decode(&mut samples)? > 0 {}
224            }
225        }
226        decoder.flush(&mut samples)?;
227        Ok(AudioBuffer::from_samples(decoder.output_spec(), samples))
228    }
229
230    #[test]
231    fn the_trait_is_object_safe() {
232        // Decoders are selected at run time, so this has to hold.
233        let boxed: Box<dyn Decoder> = Box::new(PassThrough::new(AudioSpec::mono(16_000)));
234        assert_eq!(boxed.output_spec(), AudioSpec::mono(16_000));
235
236        let mut decoders: Vec<Box<dyn Decoder>> =
237            vec![Box::new(PassThrough::new(AudioSpec::new(48_000, 2)))];
238        let by_ref: &mut dyn Decoder = decoders[0].as_mut();
239        assert_eq!(by_ref.output_spec().channels, 2);
240    }
241
242    #[test]
243    fn a_decoder_can_be_moved_between_threads() {
244        fn assert_send<T: Send>() {}
245        assert_send::<PassThrough>();
246        assert_send::<Box<dyn Decoder>>();
247    }
248
249    #[test]
250    fn samples_survive_the_round_trip() {
251        let expected = [0.0_f32, 1.0, -1.0, 0.5, -0.25];
252        let mut decoder = PassThrough::new(AudioSpec::mono(16_000));
253        let decoded = drive(&mut decoder, &encode(&expected), 1024).expect("decode");
254        assert_eq!(decoded.samples(), expected);
255        assert_eq!(decoded.sample_rate(), 16_000);
256        assert_eq!(decoded.frames(), 5);
257    }
258
259    #[test]
260    fn the_chunk_boundary_is_invisible() {
261        let expected: Vec<f32> = (0..64).map(|i| i as f32 / 64.0).collect();
262        let encoded = encode(&expected);
263        // 1, 3 and 7 all split samples mid-way; 4 lands on the boundary.
264        for chunk in [1, 3, 4, 7, 256] {
265            let mut decoder = PassThrough::new(AudioSpec::mono(8_000));
266            let decoded = drive(&mut decoder, &encoded, chunk).expect("decode");
267            assert_eq!(
268                decoded.samples(),
269                expected.as_slice(),
270                "output changed with a {chunk}-byte feed size"
271            );
272        }
273    }
274
275    #[test]
276    fn the_sample_count_is_exact() {
277        let frames = 100;
278        let spec = AudioSpec::new(44_100, 2);
279        let encoded = encode(&vec![0.125_f32; frames * spec.channels as usize]);
280        let mut decoder = PassThrough::new(spec);
281        let decoded = drive(&mut decoder, &encoded, 13).expect("decode");
282        assert_eq!(decoded.samples().len(), frames * spec.channels as usize);
283        assert_eq!(decoded.frames(), frames);
284    }
285
286    #[test]
287    fn a_starved_decoder_reports_zero_rather_than_end_of_stream() {
288        let mut decoder = PassThrough::new(AudioSpec::mono(16_000));
289        let mut out = Vec::new();
290        assert_eq!(decoder.decode(&mut out).expect("decode"), 0);
291
292        // Three bytes is not yet a sample. Still not an error.
293        assert_eq!(decoder.feed(&[1, 2, 3]).expect("feed"), 3);
294        assert_eq!(decoder.decode(&mut out).expect("decode"), 0);
295        assert!(out.is_empty());
296
297        // The fourth byte completes it.
298        assert_eq!(decoder.feed(&[4]).expect("feed"), 1);
299        assert_eq!(decoder.decode(&mut out).expect("decode"), 1);
300    }
301
302    #[test]
303    fn a_partial_frame_at_end_of_stream_is_truncated() {
304        let mut decoder = PassThrough::new(AudioSpec::mono(16_000));
305        decoder.feed(&[0, 0, 0]).expect("feed");
306        let mut out = Vec::new();
307        let error = decoder.flush(&mut out).expect_err("flush must reject");
308        assert!(
309            matches!(
310                error,
311                DecodeError::Truncated {
312                    expected: 4,
313                    available: 3
314                }
315            ),
316            "unexpected error: {error}"
317        );
318    }
319
320    #[test]
321    fn feeding_after_flush_is_quiet_until_reset() {
322        let mut decoder = PassThrough::new(AudioSpec::mono(16_000));
323        let mut out = Vec::new();
324        assert_eq!(decoder.flush(&mut out).expect("flush"), 0);
325        // Idempotent.
326        assert_eq!(decoder.flush(&mut out).expect("second flush"), 0);
327        assert_eq!(decoder.feed(&encode(&[1.0])).expect("feed"), 0);
328        assert_eq!(decoder.decode(&mut out).expect("decode"), 0);
329        assert!(out.is_empty());
330
331        decoder.reset();
332        assert_eq!(decoder.feed(&encode(&[1.0])).expect("feed"), 4);
333        assert_eq!(decoder.decode(&mut out).expect("decode"), 1);
334        assert_eq!(out, [1.0]);
335    }
336
337    #[test]
338    fn reset_drops_a_held_partial_frame() {
339        let mut decoder = PassThrough::new(AudioSpec::mono(16_000));
340        decoder.feed(&[9, 9, 9]).expect("feed");
341        decoder.reset();
342        let mut out = Vec::new();
343        assert_eq!(decoder.flush(&mut out).expect("flush after reset"), 0);
344    }
345}