forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB2cccf17Tahinli3 months ago136 commits

lib.rs257 lines, 9.3 KiBHistoryRawDownload
1//! AAC-LC: decoder (mono through 7.1) and encoder, in safe Rust.
2//!
3//! # Where the tables come from
4//!
5//! The Huffman codebooks, the scalefactor codebook and the scalefactor-band
6//! offsets in [`tables`] were **derived**, not transcribed: `scripts/derive-aac-tables.py`
7//! synthesises access units whose spectral payload is a chosen bit string, has a
8//! reference decoder decode them, and reads the quantised spectrum back through
9//! the inverse MDCT. Walking the binary tree of probes enumerates each codebook
10//! in about `2M` frames for `M` codewords. Every table came out with a Kraft
11//! sum of exactly 1 and the entry count ISO/IEC 14496-3 prescribes, which is
12//! what makes the derivation self-checking rather than a transcription to be
13//! trusted.
14//!
15//! # What is here and what is not
16//!
17//! AAC-LC (audio object type 2) is complete: all four window sequences, both
18//! window shapes, TNS, pulse data, M/S and intensity stereo, PNS, and SCE, CPE,
19//! LFE, DSE, PCE and FIL elements. HE-AAC v1 (SBR) is reconstructed: the core
20//! decodes, its low bands feed the SBR QMF/HF/envelope chain, and the output
21//! is at the extension rate. Parametric Stereo is **not** implemented; a
22//! stream that signals it decodes to its AAC-LC core, at the core sample
23//! rate, and says so through [`AacDecoder::sbr_support`] and
24//! [`AacDecoder::output_sample_rate`] rather than silently claiming the
25//! extension rate. See `sbr_is_reported_not_silently_upsampled` in the tests.
26
27#![forbid(unsafe_code)]
28
29mod config;
30mod decode;
31mod encode;
32mod huffman;
33mod sbr_bands;
34mod sbr_chain;
35mod sbr_env;
36mod sbr_hf;
37mod sbr_payload;
38mod sbr_qmf;
39mod sbr_tables;
40pub mod tables;
41
42pub use config::{
43 AOT_AAC_LC, AOT_PS, AOT_SBR, AdtsHeader, AudioSpecificConfig, ProgramConfig,
44 audio_specific_config_bytes, channels_for_config, config_for_channels, is_adts, parse_adts,
45 parse_audio_specific_config, parse_program_config, sample_rate_for_index, sf_index_for_rate,
46 write_adts_header, write_audio_specific_config,
47};
48pub use decode::{FRAME_LEN, WindowSequence};
49pub use ec_core::{Error, Result};
50pub use encode::{AacEncoder, AacEncoderConfig, EncodedPacket, WindowShape};
51/// Diagnostic only (round-17 Task 1 conviction check): reads back the
52/// per-absolute-QMF-band transmitted signal/noise energy sums
53/// `EC_AAC_SBR_NOISE_FRACTION_DEBUG` accumulates during decode.
54pub use sbr_env::noise_fraction_table;
55pub use tables::SAMPLE_RATES;
56
57use decode::BlockDecoder;
58use ec_core::BitReader;
59
60/// What this decoder does with a High Efficiency stream.
61#[derive(Clone, Copy, Debug, PartialEq, Eq)]
62pub enum SbrSupport {
63 /// The stream is plain AAC-LC: nothing is missing.
64 NotSignalled,
65 /// SBR is signalled and **is** reconstructed: the decoded audio spans
66 /// the full extension bandwidth at the extension sample rate.
67 V1,
68 /// SBR is signalled but not reconstructed (Parametric Stereo streams:
69 /// PS itself is still unimplemented). The AAC-LC core decodes, at the
70 /// core rate, half the signalled bandwidth.
71 CoreOnly,
72}
73
74/// One decoded frame: interleaved `f32` in film channel order.
75#[derive(Clone, Debug, Default)]
76pub struct DecodedAudio {
77 pub sample_rate: u32,
78 pub channels: u16,
79 /// Interleaved samples, `frames() * channels` of them.
80 pub samples: Vec<f32>,
81 pub pts: Option<i64>,
82}
83
84impl DecodedAudio {
85 /// Sample frames in this block.
86 pub fn frames(&self) -> usize {
87 if self.channels == 0 {
88 0
89 } else {
90 self.samples.len() / usize::from(self.channels)
91 }
92 }
93}
94
95/// Bitstream element order to the film order `FL, FR, FC, LFE, BL, BR, SL, SR`
96/// that every downmix in this family folds (ISO/IEC 14496-3 tbl 1.19: the
97/// elements arrive centre first, LFE last).
98fn film_order(channels: usize) -> &'static [usize] {
99 match channels {
100 3 => &[1, 2, 0],
101 4 => &[1, 2, 0, 3],
102 5 => &[1, 2, 0, 3, 4],
103 6 => &[1, 2, 0, 5, 3, 4],
104 8 => &[1, 2, 0, 7, 5, 6, 3, 4],
105 _ => &[0, 1, 2, 3, 4, 5, 6, 7],
106 }
107}
108
109/// An AAC-LC decoder.
110pub struct AacDecoder {
111 block: BlockDecoder,
112 config: Option<AudioSpecificConfig>,
113 sample_rate: u32,
114 channels: u16,
115}
116
117impl AacDecoder {
118 /// A decoder with no configuration yet: it will take its parameters from
119 /// the first ADTS header it sees.
120 pub fn new() -> AacDecoder {
121 AacDecoder {
122 block: BlockDecoder::new(3),
123 config: None,
124 sample_rate: 0,
125 channels: 0,
126 }
127 }
128
129 /// A decoder configured from a parsed AudioSpecificConfig.
130 pub fn with_config(cfg: AudioSpecificConfig) -> AacDecoder {
131 let mut d = AacDecoder::new();
132 d.block.set_sf_index(cfg.sf_index);
133 d.sample_rate = cfg.sample_rate;
134 d.channels = cfg.channels;
135 // PS is not reconstructed; SBR is. Both still need the core
136 // decoded first, but only a plain-SBR (non-PS) stream gets the
137 // extension-rate QMF chain wired in.
138 if cfg.sbr_present && !cfg.ps_present {
139 let rate = cfg.extension_sample_rate.unwrap_or(cfg.sample_rate * 2);
140 d.block.set_sbr_rate(Some(rate));
141 }
142 d.config = Some(cfg);
143 d
144 }
145
146 /// A decoder configured from raw AudioSpecificConfig bytes -- an mp4
147 /// `esds` payload or a Matroska `CodecPrivate`.
148 pub fn with_config_bytes(data: &[u8]) -> Result<AacDecoder> {
149 Ok(AacDecoder::with_config(parse_audio_specific_config(data)?))
150 }
151
152 /// The configuration this decoder was built with, if any.
153 pub fn config(&self) -> Option<&AudioSpecificConfig> {
154 self.config.as_ref()
155 }
156
157 /// Whether the stream asked for SBR, and what became of it.
158 pub fn sbr_support(&self) -> SbrSupport {
159 match &self.config {
160 Some(c) if c.ps_present => SbrSupport::CoreOnly,
161 Some(c) if c.sbr_present => SbrSupport::V1,
162 _ => SbrSupport::NotSignalled,
163 }
164 }
165
166 /// The rate the samples this decoder hands back are actually at: the
167 /// extension rate for a reconstructed (V1) HE-AAC stream, the core
168 /// rate for plain AAC-LC or an unreconstructed (PS) stream -- claiming
169 /// bandwidth that was not actually rebuilt would be a lie.
170 pub fn output_sample_rate(&self) -> Option<u32> {
171 self.config.as_ref().map(|c| match self.sbr_support() {
172 SbrSupport::V1 => c.extension_sample_rate.unwrap_or(c.sample_rate * 2),
173 _ => c.sample_rate,
174 })
175 }
176
177 /// Decodes one packet: a raw `raw_data_block`, or one or more ADTS frames.
178 pub fn decode(&mut self, packet: &[u8], pts: Option<i64>) -> Result<DecodedAudio> {
179 let mut planes: Vec<Vec<f32>> = Vec::new();
180 if is_adts(packet) {
181 let mut at = 0usize;
182 while at + 7 <= packet.len() {
183 let header = parse_adts(&packet[at..])?;
184 let end = (at + header.frame_length).min(packet.len());
185 let body = &packet[at + header.header_len..end];
186 if self.config.is_none() {
187 self.sample_rate = header.sample_rate;
188 self.channels = header.channels;
189 self.block.set_sf_index(header.sf_index);
190 }
191 let mut r = BitReader::new(body);
192 for _ in 0..header.raw_blocks {
193 let block = self.block.raw_data_block(&mut r)?;
194 merge(&mut planes, block);
195 if r.bits_remaining() < 8 {
196 break;
197 }
198 }
199 if header.frame_length == 0 {
200 break;
201 }
202 at += header.frame_length;
203 }
204 } else {
205 let mut r = BitReader::new(packet);
206 planes = self.block.raw_data_block(&mut r)?;
207 }
208 let channels = planes.len();
209 if channels == 0 {
210 return Ok(DecodedAudio {
211 sample_rate: self.output_sample_rate().unwrap_or(self.sample_rate),
212 channels: self.channels,
213 samples: Vec::new(),
214 pts,
215 });
216 }
217 if self.channels == 0 {
218 self.channels = channels as u16;
219 }
220 let order = film_order(channels);
221 let frames = planes[0].len();
222 let mut samples = vec![0.0f32; frames * channels];
223 for (out_ch, &src) in order.iter().take(channels).enumerate() {
224 let plane = &planes[src.min(channels - 1)];
225 for (i, &v) in plane.iter().enumerate() {
226 samples[i * channels + out_ch] = v;
227 }
228 }
229 Ok(DecodedAudio {
230 sample_rate: self.output_sample_rate().unwrap_or(self.sample_rate),
231 channels: channels as u16,
232 samples,
233 pts,
234 })
235 }
236}
237
238/// Appends a block's planes to the packet's, growing the plane count if a later
239/// `raw_data_block` carries more channels than an earlier one.
240fn merge(planes: &mut Vec<Vec<f32>>, block: Vec<Vec<f32>>) {
241 if planes.is_empty() {
242 *planes = block;
243 return;
244 }
245 for (i, plane) in block.into_iter().enumerate() {
246 match planes.get_mut(i) {
247 Some(dst) => dst.extend_from_slice(&plane),
248 None => planes.push(plane),
249 }
250 }
251}
252
253impl Default for AacDecoder {
254 fn default() -> AacDecoder {
255 AacDecoder::new()
256 }
257}