Skip to main content

decode_stream/
decode_stream.rs

1//! The streaming integration path: bytes in as they arrive, mono `f32` at a
2//! target rate declared up front, out as soon as it is ready.
3//!
4//! The target rate is stated before the first byte of the file exists, which
5//! is the real shape of a live consumer: it knows what rate its pipeline runs
6//! at, and it does not know what rate the file will turn out to be. The file's
7//! own rate becomes known part-way through, when the header has arrived,
8//! and that is the moment the resampler is constructed. Nothing here defaults
9//! a rate, and nothing waits for the whole file.
10//!
11//! The example ends by decoding the same bytes through the whole-file path and
12//! asserting the two outputs are bit-identical. That agreement is guaranteed,
13//! not incidental: piece boundaries are invisible to the streaming decoder,
14//! and chunk boundaries are invisible to the resampler, so the two paths are
15//! the same arithmetic in a different delivery order.
16//!
17//! Neither path names a container. `AudioStreamDecoder` holds the leading
18//! twelve bytes until it can tell what they are, then delegates to the reader
19//! for that format; `decode` does the same for the whole file. The demo below
20//! happens to build a WAV, and nothing in the pipeline knows that.
21
22use decibri_decode::decibri_resampler::{PolyphaseResampler, Resampler};
23use decibri_decode::{
24    decode, downmix_to_mono, AudioBuffer, AudioSpec, AudioStreamDecoder, DecodeError, StreamSource,
25    WavCodec, WavWriter,
26};
27
28/// The target rate the caller declares up front. Nothing in this crate
29/// supplies one.
30const TARGET_RATE: u32 = 16_000;
31
32/// Everything the streaming path holds between arriving pieces.
33struct StreamPipeline {
34    target_rate: u32,
35    decoder: AudioStreamDecoder,
36    /// Built the moment the header arrives and the file's own rate is known.
37    /// `None` until then: a stream cannot be resampled from a rate it has
38    /// not been told.
39    resampler: Option<PolyphaseResampler>,
40    /// Interleaved frames pulled from the decoder, reused between pieces.
41    batch: Vec<f32>,
42    /// The downmix of one batch, reused between pieces.
43    mono: Vec<f32>,
44    /// The mono output at `target_rate`, growing as pieces arrive.
45    samples: Vec<f32>,
46}
47
48impl StreamPipeline {
49    fn new(target_rate: u32) -> Self {
50        Self {
51            target_rate,
52            decoder: AudioStreamDecoder::new(),
53            resampler: None,
54            batch: Vec::new(),
55            mono: Vec::new(),
56            samples: Vec::new(),
57        }
58    }
59
60    /// Hands one arriving piece to the pipeline, in whatever size it turned
61    /// up. A short return from the decoder is back-pressure, answered by
62    /// draining and offering the remainder again.
63    fn push(&mut self, mut piece: &[u8]) -> Result<(), DecodeError> {
64        while !piece.is_empty() {
65            let taken = self.decoder.push(piece)?;
66            piece = &piece[taken..];
67            self.drain()?;
68        }
69        Ok(())
70    }
71
72    /// Pulls every frame the decoder has ready and sends it through downmix
73    /// and resample. Before the header has arrived there is no spec and
74    /// nothing to pull, and this is a quiet no-op.
75    fn drain(&mut self) -> Result<(), DecodeError> {
76        let Some(spec) = self.decoder.spec() else {
77            return Ok(());
78        };
79        loop {
80            self.batch.clear();
81            if self.decoder.pull(&mut self.batch, usize::MAX)? == 0 {
82                break;
83            }
84            self.convert(spec)?;
85        }
86        Ok(())
87    }
88
89    /// Downmixes the current batch and resamples it onto the output. `pull`
90    /// and `finish` deliver whole frames only, so the downmix never sees a
91    /// partial frame.
92    fn convert(&mut self, spec: AudioSpec) -> Result<(), DecodeError> {
93        self.mono.clear();
94        downmix_to_mono(&self.batch, spec.channels, &mut self.mono);
95        if self.resampler.is_none() {
96            self.resampler = Some(PolyphaseResampler::new(spec.sample_rate, self.target_rate)?);
97        }
98        let resampler = self
99            .resampler
100            .as_mut()
101            .expect("constructed on the line above");
102        resampler.process(&self.mono, &mut self.samples)?;
103        Ok(())
104    }
105
106    /// Declares end of stream, drains the decoder's tail and the resampler's
107    /// tail, and returns the output bound to the spec that describes it.
108    fn finish(mut self) -> Result<AudioBuffer, DecodeError> {
109        self.batch.clear();
110        self.decoder.finish(&mut self.batch)?;
111        if let Some(spec) = self.decoder.spec() {
112            if !self.batch.is_empty() {
113                self.convert(spec)?;
114            }
115        }
116        if let Some(resampler) = self.resampler.as_mut() {
117            resampler.flush(&mut self.samples);
118        }
119        Ok(AudioBuffer::from_samples(
120            AudioSpec::mono(self.target_rate),
121            self.samples,
122        ))
123    }
124}
125
126/// A two-channel 32-bit float WAV at 48 kHz, built in memory.
127///
128/// The signal is integer arithmetic scaled by powers of two, not a
129/// transcendental, so every sample is exactly representable and the file is
130/// byte-identical on every platform.
131fn demo_wav() -> Result<Vec<u8>, DecodeError> {
132    const FRAMES: usize = 4_800;
133    let mut samples = Vec::with_capacity(FRAMES * 2);
134    for frame in 0..FRAMES {
135        let value = ((frame * 41) % 1_024) as f32 / 1_024.0 - 0.5;
136        samples.push(value); // left
137        samples.push(value * 0.25); // right
138    }
139    WavWriter::new(AudioSpec::new(48_000, 2), WavCodec::Float32).to_bytes(&samples)
140}
141
142fn main() -> Result<(), Box<dyn std::error::Error>> {
143    let file = demo_wav()?;
144
145    // The target rate is declared here, before the first byte is pushed.
146    let mut pipeline = StreamPipeline::new(TARGET_RATE);
147
148    // 509 is deliberately awkward: prime, so it splits the RIFF header, the
149    // fmt chunk and every frame across piece boundaries somewhere in the file.
150    for piece in file.chunks(509) {
151        pipeline.push(piece)?;
152    }
153    let streamed = pipeline.finish()?;
154    println!(
155        "streamed: {} samples of mono f32 at {} Hz",
156        streamed.samples().len(),
157        streamed.sample_rate()
158    );
159
160    // The same bytes through the whole-file path, for the agreement check.
161    let decoded = decode(&file)?;
162    let mut mono = Vec::new();
163    downmix_to_mono(decoded.samples(), decoded.channels(), &mut mono);
164    let mut resampler = PolyphaseResampler::new(decoded.sample_rate(), TARGET_RATE)?;
165    let mut whole = Vec::new();
166    resampler.process(&mono, &mut whole)?;
167    resampler.flush(&mut whole);
168
169    assert_eq!(
170        streamed.samples().len(),
171        whole.len(),
172        "the two paths must produce the same sample count"
173    );
174    assert!(
175        streamed
176            .samples()
177            .iter()
178            .zip(&whole)
179            .all(|(a, b)| a.to_bits() == b.to_bits()),
180        "the two paths must agree bit-for-bit"
181    );
182    println!("streamed output is bit-identical to the whole-file path");
183
184    Ok(())
185}