Skip to main content

decode_whole_file/
decode_whole_file.rs

1//! The whole-file integration path: encoded bytes of any supported container
2//! in, mono `f32` at a target rate the caller declares, out.
3//!
4//! This is the shape a consumer holding a complete file uses. The stages after
5//! the decode are deliberately visible rather than wrapped in a convenience
6//! function, because each one is a decision the consumer owns: whether to
7//! downmix, and what rate to resample to. This crate makes neither of those
8//! decisions, has no rate policy and no default sample rate, and nothing in it
9//! branches on a file name. Choosing the container reader is *not* one of
10//! those decisions, which is why it is one call.
11//!
12//! Run against a real WAV, AIFF or FLAC file:
13//!
14//! ```text
15//! cargo run --example decode_whole_file -- path/to/audio.wav
16//! ```
17//!
18//! or with no argument to run against a WAV built in memory.
19
20use decibri_decode::decibri_resampler::{PolyphaseResampler, Resampler};
21use decibri_decode::{
22    decode, downmix_to_mono, identify, AiffReader, AudioBuffer, AudioSpec, Container, DecodeError,
23    FlacReader, WavCodec, WavReader, WavWriter,
24};
25
26/// The target rate the caller declares. Nothing in this crate supplies one.
27const TARGET_RATE: u32 = 16_000;
28
29/// Decodes a complete file of any supported format to mono `f32` at
30/// `target_rate`.
31///
32/// The container comes out of the content, never out of a file name or an
33/// extension, and the crate does that part: [`decode`] reads the leading twelve
34/// bytes, picks the reader and rejects anything it does not carry with a typed
35/// error that names what it found.
36fn decode_to_mono_at(bytes: &[u8], target_rate: u32) -> Result<AudioBuffer, DecodeError> {
37    // 1. Container to interleaved samples, at the file's own rate and layout.
38    //    The rate travels with the samples from here on; nothing downstream
39    //    infers it.
40    let decoded = decode(bytes)?;
41
42    // 2. Interleaved to mono. The channel count comes from the buffer itself,
43    //    and the downmix is the arithmetic mean of the channels, the same
44    //    formula decibri uses, read from its source rather than chosen.
45    let mut mono = Vec::new();
46    downmix_to_mono(decoded.samples(), decoded.channels(), &mut mono);
47
48    // 3. The file's rate to the declared target rate, through the one
49    //    resampler this crate defers all rate conversion to. When the rates
50    //    already match, the resampler is an identity passthrough and the
51    //    samples come back bit-identical with nothing appended at the flush.
52    let mut resampler = PolyphaseResampler::new(decoded.sample_rate(), target_rate)?;
53    let mut samples = Vec::new();
54    resampler.process(&mono, &mut samples)?;
55    resampler.flush(&mut samples);
56
57    Ok(AudioBuffer::from_samples(
58        AudioSpec::mono(target_rate),
59        samples,
60    ))
61}
62
63/// What a probe of the input establishes before any sample is decoded: the
64/// file's own rate and channel count, and how many frames it holds.
65///
66/// [`identify`] gives the container and nothing else, which is what makes the
67/// reader-specific part of this short. The rate and the count are the
68/// container's own to state, so they come from the reader that understands it;
69/// FLAC is the one that may honestly not know its length, and says `None`
70/// rather than nought.
71fn probe(bytes: &[u8]) -> Result<(AudioSpec, Option<u64>), DecodeError> {
72    match identify(bytes)? {
73        Container::Aiff => {
74            let reader = AiffReader::new(bytes)?;
75            Ok((reader.spec(), Some(reader.frames())))
76        }
77        Container::Flac => {
78            let reader = FlacReader::new(bytes)?;
79            Ok((reader.spec(), reader.frames()))
80        }
81        // `Container` is non-exhaustive, so this arm is required. It covers
82        // WAV, and anything a later version of the crate adds, which the WAV
83        // reader refuses by naming the bytes it saw.
84        _ => {
85            let reader = WavReader::new(bytes)?;
86            Ok((reader.spec(), Some(reader.frames())))
87        }
88    }
89}
90
91/// A two-channel 16-bit PCM WAV at 44.1 kHz, built in memory.
92///
93/// The signal is integer arithmetic scaled by powers of two, not a
94/// transcendental, so every sample is exactly representable and the file is
95/// byte-identical on every platform.
96fn demo_wav() -> Result<Vec<u8>, DecodeError> {
97    const FRAMES: usize = 4_410;
98    let mut samples = Vec::with_capacity(FRAMES * 2);
99    for frame in 0..FRAMES {
100        let value = ((frame * 37) % 2_000) as f32 / 2_048.0 - 0.488_281_25;
101        samples.push(value); // left
102        samples.push(-value * 0.5); // right
103    }
104    WavWriter::new(AudioSpec::new(44_100, 2), WavCodec::PcmI16).to_bytes(&samples)
105}
106
107fn main() -> Result<(), Box<dyn std::error::Error>> {
108    let bytes = match std::env::args_os().nth(1) {
109        Some(path) => std::fs::read(path)?,
110        None => demo_wav()?,
111    };
112
113    let (spec, frames) = probe(&bytes)?;
114    let counted = match frames {
115        Some(frames) => frames.to_string(),
116        None => "an unstated number of".to_string(),
117    };
118    println!(
119        "input: {} channel(s) at {} Hz, {counted} frames",
120        spec.channels, spec.sample_rate
121    );
122
123    let audio = decode_to_mono_at(&bytes, TARGET_RATE)?;
124    println!(
125        "output: {} samples of mono f32 at {} Hz",
126        audio.samples().len(),
127        audio.sample_rate()
128    );
129
130    // The crate's count guarantee, checked on the identity path: with the
131    // target equal to the file's own rate the resampler is a passthrough, so
132    // the output holds exactly the frame count the container declared. The
133    // resampled count above is the resampler's statement, not this crate's,
134    // which is why this check runs at the identity rate. A container that did
135    // not state a count has nothing to check against and says so.
136    if let Some(frames) = frames {
137        let identity = decode_to_mono_at(&bytes, spec.sample_rate)?;
138        assert_eq!(
139            identity.samples().len() as u64,
140            frames,
141            "identity-rate decode must hold exactly the container's frame count"
142        );
143        println!("identity-rate decode holds exactly {frames} frames");
144    }
145
146    Ok(())
147}