forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB35bdf35Tahinli2 months ago3757 commits

lib.rs105 lines, 4.5 KiBHistoryRawDownload
1//! AC-3 and Enhanced AC-3 decoding, from the ATSC A/52 standard.
2//!
3//! Two entry points, depending on how much of the format the caller needs:
4//!
5//! - [`Ac3Decoder`] takes syncframes and hands back interleaved `f32` audio
6//! frames, with the coded channel layout or a §7.8 downmix.
7//! - [`syncinfo::parse`], [`bsi::parse`] and [`eac3::bsi::parse`] read the
8//! headers alone, which is what a container needs to state a track's sample
9//! rate and channel count before decoding anything.
10//!
11//! Contracts worth knowing before implementing against this crate:
12//!
13//! - **Encoding has no psychoacoustic model yet.** [`Ac3Encoder`] writes
14//! spec-valid syncframes — real MDCT, per-block/channel transient-driven
15//! block switching, an exponent planner (D15/D25/D45/reuse) and a
16//! binary-searched SNR-offset rate loop that fills a frame to roughly
17//! 93-99.6% of its budget depending on content and bit rate — but the bit
18//! allocation curve itself is the standard's masking model rather than a
19//! perceptual search; see [`encode`] for exactly what is and is not
20//! adaptive yet.
21//! - **Truncated input is [`Error::NeedMore`]**, a broken bit stream is
22//! [`Error::Corrupt`], and a construct this build does not implement is
23//! [`Error::Unsupported`] naming *what* and *why*. No input panics — the bit
24//! reader bounds every read and the exponent and bandwidth fields are range
25//! checked before they index anything.
26//! - **Dynamic range compression is applied by default**, because §7.7.1 says a
27//! decoder shall: `dynrng` is the program provider's compression curve and
28//! leaving it out makes explosions 20 dB louder than the mix intended. The
29//! raw words stay visible on [`FrameInfo`], and [`Options::drc_scale`] turns
30//! it down or off.
31//! - **Dialogue normalisation is surfaced, never applied.** §7.6 puts
32//! `dialnorm` in the volume control, which is not in this crate.
33//! - **The noise this format asks for is on by default**: dither for zero-bit
34//! mantissas (§7.3.4) and the spectral extension blend (§E3.6.4.2.4). Neither
35//! sequence is specified, so two conformant decoders differ by exactly that
36//! noise; [`Options::dither`] turns both off when a comparison needs to
37//! isolate everything else.
38//!
39//! Annex E coverage: the adaptive hybrid transform (with its vector and
40//! gain-adaptive quantizers) and spectral extension are decoded; enhanced
41//! coupling and dependent substreams above 5.1 are refused by name rather than
42//! decoded wrongly. On a real Dolby Digital Plus stream that uses both, the
43//! coded bins land within 0.01% of the oracle's energy and the whole channel within
44//! 0.999 correlation once the two decoders' independent noise is taken out of
45//! the comparison ([`Options::dither`]).
46//!
47//! No unsafe, no allocation on the block path beyond the output buffer, and no
48//! dependencies beyond the family IR and DSP crates.
49
50#![forbid(unsafe_code)]
51#![warn(missing_docs)]
52// A bit stream parser indexes several per-channel and per-band arrays from one
53// loop variable, which is the domain's own notion of position; iterator
54// rewrites of those loops obscure which array is which.
55#![allow(clippy::needless_range_loop)]
56
57mod aht;
58mod aht_tables;
59
60pub mod bitalloc;
61pub mod bsi;
62pub mod eac3;
63pub mod exps;
64pub mod mantissa;
65mod stack_budget;
66pub mod syncinfo;
67pub mod tables;
68pub mod transform;
69
70mod decode;
71mod decoder;
72pub mod encode;
73
74pub use decode::Syntax;
75pub use decoder::{Ac3Decoder, Downmix, FrameInfo, Options};
76pub use ec_core::Error;
77pub use encode::{Ac3Encoder, EncodeStats, EncoderConfig};
78
79/// Samples per channel one audio block produces.
80pub use transform::BLOCK_SAMPLES;
81
82/// Blocks in an AC-3 syncframe; Enhanced AC-3 may send 1, 2, 3 or 6.
83pub const AC3_BLOCKS_PER_FRAME: usize = 6;
84
85/// Length in bytes of the syncframe starting at `data[0]`, for either syntax.
86///
87/// This is what walking an elementary stream needs — the frame length lives in
88/// `frmsizecod` for AC-3 and `frmsiz` for E-AC-3, in different places and
89/// different units. A short buffer is [`Error::NeedMore`]; anything that is not
90/// a syncframe is [`Error::Corrupt`].
91pub fn frame_size(data: &[u8]) -> ec_core::Result<usize> {
92 if data.len() < 6 {
93 return Err(Error::NeedMore);
94 }
95 if data[0] != 0x0B || data[1] != 0x77 {
96 return Err(Error::corrupt(
97 "AC-3: no syncword at the start of the frame",
98 ));
99 }
100 if data[5] >> 3 <= 10 {
101 Ok(syncinfo::parse(data)?.frame_size)
102 } else {
103 Ok(eac3::parse(&data[2..])?.frame_size)
104 }
105}