Skip to main content

decibri_decode/
lib.rs

1#![forbid(unsafe_code)]
2#![warn(missing_docs)]
3//! Encoded audio bytes in, `f32` samples out, with the sample rate and channel
4//! count travelling with them and a stated and tested sample-count guarantee.
5//!
6//! That sentence is the crate. Codecs fill the contract in; they are not the
7//! contract. The trait boundaries, the error type and the buffer types are
8//! settled before any codec exists, because changing them afterwards is a
9//! breaking change and changing them now is free.
10//!
11//! # The contract
12//!
13//! - **In:** encoded bytes, held whole in memory and handed to a reader, or
14//!   arriving in pieces via [`StreamSource`].
15//! - **Out:** `f32` samples that always travel with the [`AudioSpec`] that
16//!   describes them, so no downstream stage ever infers or assumes a rate. That
17//!   is the whole reason [`AudioBuffer`] exists rather than a bare `Vec<f32>`:
18//!   decibri has been bitten repeatedly by rate and layout travelling
19//!   separately from the samples they describe, most expensively on the AEC
20//!   reference path, where a wrong-rate reference is accepted silently and
21//!   cancels nothing.
22//! - **Guarantee:** the number of samples produced for a given input is stated
23//!   and tested, not incidental. Decoding a source of `n` frames yields exactly
24//!   `n * channels` samples, and there is no rate conversion here for that
25//!   count to be conditional on. A caller who goes on to resample gets the
26//!   count [`decibri_resampler`] states for that rate pair and input length,
27//!   which is that crate's guarantee rather than this one's. A codec that
28//!   cannot state its output count does not go behind [`Decoder`].
29//! - **Failure:** every rejection is a [`DecodeError`] that names the specific
30//!   thing it rejected. "Unsupported" on its own tells a caller nothing they
31//!   can act on.
32//!
33//! # Choosing a reader
34//!
35//! [`decode`] takes bytes in any carried container and gives back an
36//! [`AudioBuffer`], [`AudioStreamDecoder`] does the same for a stream that
37//! arrives in pieces, and [`identify`] answers what an input is without
38//! decoding it. All three read the same twelve leading bytes, so a caller
39//! never writes a magic-byte check and there is one statement of what a WAV
40//! looks like rather than one per call site.
41//!
42//! Twelve, not four, because `RIFF` names a container *family*: the form type
43//! at offset eight is what separates a WAV from an AVI, and `FORM` from an
44//! `8SVX`. A container whose form type is not one this crate reads is
45//! [`DecodeError::UnsupportedContainer`] naming the form type found, never a
46//! reader handed a file that was never its.
47//!
48//! Headerless linear PCM, headerless G.711 and bare FLAC frame streams have no
49//! signature and are outside this. They stay explicit, because the alternative
50//! is guessing: a FLAC frame's 14-bit sync code and 8-bit header CRC together
51//! let about one position in 32,768 of random data parse as a frame header, so
52//! sniffing for one in bytes of unknown provenance would misfire on input that
53//! is not FLAC at all.
54//!
55//! # Determinism
56//!
57//! For every format this crate carries (PCM, G.711, WAV, AIFF and FLAC),
58//! decoding is **bit-exact and cross-platform byte-identical**. The same input
59//! produces the same bytes on every target: no floating-point reassociation, no
60//! platform-specific fast paths, no reliance on FMA contraction.
61//!
62//! If MP3 is ever added, its decode is compliant within the ISO/IEC 11172-4
63//! accuracy bound and is explicitly **not** claimed as byte-identical. MPEG
64//! never specified bit-exact decoding, and two conforming decoders legitimately
65//! differ. That exception will be stated on the MP3 decoder itself and does not
66//! weaken the guarantee above for any other format.
67//!
68//! This is written now, while it is a true statement about an empty crate,
69//! rather than retrofitted once somebody has assumed otherwise.
70//!
71//! **Determinism is not losslessness.** Determinism holds for everything here.
72//! Losslessness, a value surviving the round trip through `f32` with its
73//! bits intact, holds for every format at or below 24 significant bits, all of
74//! them except `i32` and `f64`. An `f32` significand is 24 bits, so 31-bit and
75//! 53-bit values land on the nearest representable `f32` instead of on
76//! themselves. That is inherent to an `f32` internal representation and is the
77//! right trade for a crate feeding decibri's `f32` chain, but it is stated here
78//! rather than left to be discovered. The error is bounded by half an ulp at the
79//! value's magnitude; nothing wraps and no sign flips.
80//!
81//! # Rate conversion
82//!
83//! There is none here, and there never will be. Rate conversion is
84//! [`decibri_resampler`], the crate's only dependency, called and never
85//! reimplemented. Its failures arrive as [`DecodeError::Resample`]. Additional
86//! *instances* of a resampler are expected and fine; a second *implementation*
87//! is a correctness hazard, because resampler choice was measured during the
88//! echo-cancellation work as moving AECMOS by up to 1.03, larger than the
89//! effect being measured.
90//!
91//! # Sample conversion
92//!
93//! [`SampleFormat`] carries every linear PCM format the crate reads: `u8`
94//! and `i8` (WAV's 8-bit is unsigned and AIFF's is signed, and those are the
95//! two specifications' rules rather than a choice here), and 16-, 24- and
96//! 32-bit integer and 32- and 64-bit float in both byte orders. It converts
97//! each to and from `f32`. The numerical conventions are not
98//! this crate's to choose: the scale factor, the rounding and clamping rule and
99//! the downmix formula were all read out of decibri so that the same input
100//! decoded through either crate gives the same samples. They are recorded, with
101//! the file and line each came from, on the [`sample`] module.
102//!
103//! There is no dither, no feature flag for one and no plan for one. It needs a
104//! random source, which would either break the byte-identical claim above or
105//! make a generator seed part of the public contract.
106//!
107//! # G.711
108//!
109//! [`G711Law`] carries both ITU-T companding laws, mu-law and A-law, in both
110//! directions, and [`G711Decoder`] decodes a headerless stream in either. The
111//! tables are derived from the recommendation's own segment geometry rather than
112//! transcribed from a third-party implementation, because the crate is published
113//! under Apache-2.0 and reference data with an unestablished licence is a real
114//! constraint.
115//!
116//! G.711 is a *sample format, not a rate*. It is overwhelmingly carried at
117//! 8 kHz in telephony and nothing in the recommendation says so, so the rate
118//! comes from the [`AudioSpec`] the caller states and nothing here defaults to
119//! 8000.
120//!
121//! Decoding is a code to `i16` through the table, then `i16` to `f32` through
122//! [`sample`]; encoding is the reverse. There is no direct code-to-`f32` path,
123//! so the crate has one scaling rule rather than two.
124//!
125//! # WAV
126//!
127//! [`WavReader`] reads a RIFF/WAVE or RF64 file held whole in memory and
128//! [`WavStreamDecoder`] reads one that arrives in pieces; [`WavWriter`] writes
129//! every encoding either of them reads. [`WavCodec`] is the set of encodings a
130//! WAV file can carry and this crate can decode: four widths of linear PCM, two
131//! of IEEE float, and both G.711 laws.
132//!
133//! Dispatch is on the **`(wFormatTag, wBitsPerSample)` pair**, never on the tag
134//! alone. Tag 1 covers four widths, and a reader that picked one would decode
135//! the others at the wrong stride and produce noise rather than an error. It is
136//! never, at any point, on a file name. `WAVE_FORMAT_EXTENSIBLE` resolves
137//! through its SubFormat GUID.
138//!
139//! Malformed input is a typed [`DecodeError`] rather than a panic, and no
140//! allocation anywhere is proportional to a size the file declared: a `data`
141//! chunk announcing four gigabytes inside a two-kilobyte file is rejected
142//! before a byte is reserved for it. All chunk arithmetic is 64-bit and
143//! checked, which is what makes that true on a 32-bit target as well.
144//!
145//! # AIFF and AIFF-C
146//!
147//! [`AiffReader`] reads an AIFF or AIFF-C file held whole in memory,
148//! [`AiffStreamDecoder`] reads one that arrives in pieces, and [`AiffWriter`]
149//! writes every encoding either of them reads: plain `AIFF` where big-endian
150//! PCM makes that form legal, `AIFC` with its `FVER` chunk and compression
151//! field where the encoding requires it. [`AiffCodec`] is the set of encodings
152//! this crate carries in the container: linear PCM at four widths (big-endian
153//! under `NONE`/`twos`, little-endian under `sowt`, and **signed** at 8 bits
154//! where WAV is unsigned), unsigned 8-bit under AIFF-C's `raw `, IEEE float
155//! under `fl32`/`fl64`, and both G.711 laws under `alaw`/`ulaw`. Every other
156//! compression type is [`DecodeError::UnsupportedCodec`].
157//!
158//! Dispatch is on the **form type and the compression four-CC** (paired with
159//! `sampleSize` for the linear widths), never on a file name. The 80-bit
160//! extended-precision sample rate is parsed by hand, and `COMM`'s
161//! `numSampleFrames` is required to agree exactly with the `SSND` chunk's
162//! length. Disagreement is a typed error, never a silent preference for
163//! either source.
164//!
165//! # FLAC
166//!
167//! `FlacReader` reads a FLAC stream held whole in memory and
168//! `FlacStreamDecoder` reads one that arrives in pieces; `FlacStreamInfo` is
169//! what the streaminfo metadata block declared. Both readers are always
170//! built: this crate has no Cargo features, so a FLAC stream decodes in every
171//! build of it.
172//!
173//! Decoding is written from RFC 9639 and covers the whole format this crate
174//! claims: every bit depth from 4 to 32, every channel count from 1 to 8, the
175//! three stereo decorrelations, constant, verbatim, fixed and linear
176//! predictor subframes, both Rice parameter widths and the escaped
177//! partitions, fixed and variable block size streams, and the uncommon block
178//! sizes and sample rates that live outside the streamable subset.
179//!
180//! **The integrity check is a runtime feature, not a test.** Every FLAC file
181//! carries an MD5 of its own unencoded audio, so unlike every other format
182//! here the decoder can check its own output on *every file it ever sees*. It
183//! does: a whole-file decode hashes as it goes, a streaming decode hashes
184//! incrementally, and both verify at the end. A mismatch is a typed error
185//! rather than audio. An all-zero checksum means "not known", which the
186//! format permits and which is not a failure. The frame header CRC-8 and the
187//! whole-frame CRC-16 are verified as well, before any sample from that frame
188//! is delivered.
189//!
190//! **Properties may not change mid-stream.** A FLAC frame header restates the
191//! sample rate, channel count and bit depth, and the format allows them to
192//! differ between frames. This crate rejects that with a typed error, because
193//! [`AudioBuffer`] carries one [`AudioSpec`] for the samples it holds and
194//! there is no honest way to describe a buffer whose rate changed half way
195//! through.
196//!
197//! [`FlacWriter`] writes native FLAC streams at compression levels 0
198//! through 8, computing residuals through the same integer prediction
199//! functions the decoder reconstructs with, so the two cannot disagree about
200//! the arithmetic. The Ogg and Matroska mappings are not here.
201//!
202//! ## Bare frames, out-of-band streaminfo, and recovery
203//!
204//! A FLAC frame is self-describing, so a run of frames with no `fLaC`
205//! signature and no metadata in front of it is still decodable.
206//! `FlacFrameReader` reads one held whole in memory and
207//! `FlacStreamDecoder::frames` reads one that arrives in pieces, the third
208//! headerless decoder in the crate, beside [`PcmDecoder`] and
209//! [`G711Decoder`]. The two frame header codes that mean "take this field
210//! from streaminfo", sample rate `0b0000` and bit depth `0b000`, have nothing
211//! to be taken from on that path and are a typed error naming which field was
212//! unresolved, never a default.
213//!
214//! Both readers accept a streaminfo block from **out of band**, which is what
215//! Ogg and Matroska do: the block travels in the container's codec-private
216//! header and the packets carry bare frames. The block's 34-byte body parses
217//! through `FlacStreamInfo::from_block`, and supplying the result resolves
218//! those two codes and restores the MD5 check to a path that otherwise has
219//! none.
220//! Whether that check actually ran is reported, as `Md5Check`, because a
221//! caller cannot tell from the samples and a decode that quietly verified
222//! nothing is how a guarantee gets claimed that was never provided.
223//!
224//! `FlacRecovery` finds frame boundaries in a byte run that may begin
225//! mid-frame, hold garbage or be damaged. It is a separate type rather than a
226//! flag, because everywhere else here a damaged frame is an error rather than
227//! quietly shortened audio: recovery has to be asked for, and every decode
228//! through it reports the byte ranges that produced nothing and the sample
229//! positions lost. A sync point is accepted only when the frame at it passes
230//! its CRC-16 *and* another frame header parses where that frame ends. The
231//! 14-bit sync code and 8-bit header CRC together let about one position in
232//! 32,768 of random data look like a frame, so a single validating header is
233//! not evidence.
234//!
235//! **Recovery is whole-buffer only.** `FlacRecovery` takes a slice, and there
236//! is no streaming form of it: a live stream that meets corruption part-way
237//! through is a typed error from `FlacStreamDecoder`, not a resync. Accepting
238//! a sync point requires the bytes *after* the candidate frame, so a
239//! streaming resync would have to buffer forward without a bound or accept
240//! weaker evidence than the standard above. Recovering a damaged live stream
241//! means collecting its bytes and handing them to `FlacRecovery`.
242//!
243//! # Layout
244//!
245//! - [`decode`], [`AudioStreamDecoder`] and [`identify`] are the front door:
246//!   the reader comes from the content, not from the caller.
247//! - [`Decoder`] is the boundary: frames in, samples out. It is object safe, so
248//!   platform decoders (AudioToolbox, MediaCodec) can sit behind it alongside
249//!   the crate's own.
250//! - [`PcmDecoder`] is the implementation of it for headerless PCM, and
251//!   [`G711Decoder`] for headerless G.711.
252//! - [`StreamSource`] is how bytes arrive when they arrive in pieces.
253//! - [`WavReader`], [`WavStreamDecoder`] and [`WavWriter`] are the RIFF/WAVE
254//!   and RF64 container.
255//! - [`AiffReader`], [`AiffStreamDecoder`] and [`AiffWriter`] are the AIFF
256//!   and AIFF-C container.
257//! - `FlacReader`, `FlacStreamDecoder` and [`FlacWriter`] are FLAC;
258//!   `FlacFrameReader` is a bare frame stream and `FlacRecovery` is a
259//!   damaged one.
260//! - [`AudioSpec`] and [`AudioBuffer`] keep rate and layout attached to
261//!   samples.
262//! - [`SampleFormat`] and the functions beside it convert samples;
263//!   [`downmix_to_mono`], [`interleave`] and [`deinterleave`] rearrange them.
264//! - [`G711Law`] is the mu-law and A-law table, in both directions.
265//! - [`CodecId`] and [`FourCc`] let [`DecodeError`] name what it saw, and
266//!   [`Container`] is what [`identify`] answers with.
267//!
268//! # Status
269//!
270//! Linear PCM, G.711, the RIFF/WAVE and RF64 container, the AIFF and AIFF-C
271//! container, and FLAC. [`PcmDecoder`] decodes headerless streams in any
272//! [`SampleFormat`] and [`G711Decoder`] decodes headerless mu-law and A-law;
273//! [`WavReader`] and [`WavStreamDecoder`] read WAV whole or in pieces and
274//! [`WavWriter`] writes it; [`AiffReader`], [`AiffStreamDecoder`] and
275//! [`AiffWriter`] do the same three things for AIFF; `FlacReader` and
276//! `FlacStreamDecoder` read FLAC whole or in pieces, [`FlacWriter`] writes
277//! it at compression levels 0 through 8, `FlacFrameReader` reads a bare
278//! frame stream and `FlacRecovery` recovers what a damaged byte run holds.
279//! The Ogg and Matroska mappings of FLAC are not here; the codec they would
280//! build on is. [`decode`] and [`AudioStreamDecoder`] pick between the three
281//! containers by content. [`WavStreamDecoder`], [`AiffStreamDecoder`],
282//! `FlacStreamDecoder` and [`AudioStreamDecoder`] are the [`StreamSource`]s.
283
284mod aiff;
285mod audio;
286mod codec;
287mod decoder;
288mod error;
289mod flac;
290mod g711;
291mod md5;
292mod payload;
293mod pcm;
294mod probe;
295mod riff;
296pub mod sample;
297mod source;
298mod wav;
299
300pub use aiff::{AiffCodec, AiffForm, AiffFormat, AiffReader, AiffStreamDecoder, AiffWriter};
301pub use audio::{AudioBuffer, AudioSpec};
302pub use codec::{CodecId, FourCc};
303pub use decoder::Decoder;
304pub use error::DecodeError;
305pub use flac::{
306    FlacFrameReader, FlacFrameReport, FlacReader, FlacRecovery, FlacRecoveryReport, FlacSkip,
307    FlacSkipReason, FlacStreamDecoder, FlacStreamInfo, FlacWriter, Md5Check,
308};
309pub use g711::{G711Decoder, G711Law};
310pub use pcm::PcmDecoder;
311pub use probe::{decode, identify, AudioStreamDecoder, Container};
312pub use sample::{
313    deinterleave, downmix_to_mono, f32_to_i16, f32_to_i24, f32_to_i32, f32_to_i8, f32_to_u8,
314    i16_to_f32, i24_to_f32, i32_to_f32, i8_to_f32, interleave, u8_to_f32, SampleFormat, I24_MAX,
315    I24_MIN, MAX_BYTES_PER_SAMPLE,
316};
317pub use source::StreamSource;
318pub use wav::{
319    RiffFlavour, WavCodec, WavFormat, WavHeaderStyle, WavReader, WavStreamDecoder, WavWriter,
320};
321
322/// The resampler this crate defers all rate conversion to.
323///
324/// Re-exported so a consumer can name [`ResamplerError`](decibri_resampler::ResamplerError)
325/// when matching [`DecodeError::Resample`] without taking its own dependency,
326/// and, more to the point, without taking a *different version* of it.
327pub use decibri_resampler;
328
329/// The README's Rust blocks, compiled and run as doctests so the examples on
330/// the crate's front page cannot rot.
331///
332/// `cfg(doctest)` is set only while rustdoc collects doctests, so this item
333/// exists to `cargo test` and to nothing else: it is not part of the public
334/// API, does not appear in the built documentation, and the crate-level
335/// documentation above stays the curated text rather than the README.
336///
337#[cfg(doctest)]
338#[doc = include_str!("../README.md")]
339pub struct ReadmeDoctests;