forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB86fb0f3Tahinli7 days ago3927 commits

lib.rs340 lines, 13.0 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. HE-AAC v2 adds Parametric Stereo (ISO/IEC
22//! 14496-3 subpart 8), reconstructed as FFmpeg does: a PS stream decodes to
23//! two channels at the extension rate. A PS element whose PS header has not
24//! been decoded yet outputs its mono SBR signal on both channels. Malformed
25//! PS data disables PS for that frame, with the same fallback.
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;
38pub mod sbr_qmf;
39mod sbr_qmf_window;
40mod ps_data;
41mod ps_dsp;
42mod ps_huff;
43mod sbr_tables;
44pub mod tables;
45#[doc(hidden)]
46pub mod knobs;
47
48pub use config::{
49 AOT_AAC_LC, AOT_PS, AOT_SBR, AdtsHeader, AudioSpecificConfig, ProgramConfig,
50 audio_specific_config_bytes, channels_for_config, config_for_channels, is_adts, parse_adts,
51 parse_audio_specific_config, parse_program_config, sample_rate_for_index, sf_index_for_rate,
52 write_adts_header, write_audio_specific_config,
53};
54pub use decode::{FRAME_LEN, ToolSideInfoRow, WindowSequence, tool_sideinfo_log};
55pub use ec_core::{Error, Result};
56pub use encode::{AacEncoder, AacEncoderConfig, EncodedPacket, WindowShape};
57/// Diagnostic only (round-20): per-(access-unit, channel) side-info rows
58/// logged during decode when `EC_AAC_SBR_SIDEINFO_DEBUG` is set.
59pub use sbr_chain::{SbrSideInfoRow, hold_call_count, sbr_sideinfo_log};
60/// Diagnostic only (round-17 Task 1 conviction check): reads back the
61/// per-absolute-QMF-band transmitted signal/noise energy sums
62/// `EC_AAC_SBR_NOISE_FRACTION_DEBUG` accumulates during decode.
63pub use sbr_env::noise_fraction_table;
64pub use tables::SAMPLE_RATES;
65
66use decode::BlockDecoder;
67use ec_core::BitReader;
68
69/// What this decoder does with a High Efficiency stream.
70#[derive(Clone, Copy, Debug, PartialEq, Eq)]
71pub enum SbrSupport {
72 /// The stream is plain AAC-LC: nothing is missing.
73 NotSignalled,
74 /// SBR is signalled and **is** reconstructed: the decoded audio spans
75 /// the full extension bandwidth at the extension sample rate.
76 V1,
77 /// SBR is signalled but not reconstructed. Not produced by this decoder
78 /// any more: Parametric Stereo streams report [`SbrSupport::V1`].
79 CoreOnly,
80}
81
82/// One decoded frame: interleaved `f32` in film channel order.
83#[derive(Clone, Debug, Default)]
84pub struct DecodedAudio {
85 pub sample_rate: u32,
86 pub channels: u16,
87 /// Interleaved samples, `frames() * channels` of them.
88 pub samples: Vec<f32>,
89 pub pts: Option<i64>,
90}
91
92impl DecodedAudio {
93 /// Sample frames in this block.
94 pub fn frames(&self) -> usize {
95 if self.channels == 0 {
96 0
97 } else {
98 self.samples.len() / usize::from(self.channels)
99 }
100 }
101}
102
103/// Bitstream element order to the film order `FL, FR, FC, LFE, BL, BR, SL, SR`
104/// that every downmix in this family folds (ISO/IEC 14496-3 tbl 1.19: the
105/// elements arrive centre first, LFE last).
106fn film_order(channels: usize) -> &'static [usize] {
107 match channels {
108 3 => &[1, 2, 0],
109 4 => &[1, 2, 0, 3],
110 5 => &[1, 2, 0, 3, 4],
111 6 => &[1, 2, 0, 5, 3, 4],
112 8 => &[1, 2, 0, 7, 5, 6, 3, 4],
113 _ => &[0, 1, 2, 3, 4, 5, 6, 7],
114 }
115}
116
117/// An AAC-LC decoder.
118pub struct AacDecoder {
119 block: BlockDecoder,
120 config: Option<AudioSpecificConfig>,
121 sample_rate: u32,
122 channels: u16,
123}
124
125impl AacDecoder {
126 /// A decoder with no configuration yet: it will take its parameters from
127 /// the first ADTS header it sees.
128 pub fn new() -> AacDecoder {
129 AacDecoder {
130 block: BlockDecoder::new(3),
131 config: None,
132 sample_rate: 0,
133 channels: 0,
134 }
135 }
136
137 /// A decoder configured from a parsed AudioSpecificConfig.
138 pub fn with_config(cfg: AudioSpecificConfig) -> AacDecoder {
139 let mut d = AacDecoder::new();
140 d.block.set_sf_index(cfg.sf_index);
141 d.block.set_pce(cfg.pce.clone());
142 d.sample_rate = cfg.sample_rate;
143 d.channels = cfg.channels;
144 // SBR (and Parametric Stereo, for HE-AACv2) is reconstructed: the
145 // core is decoded first, then the extension-rate chain runs on it.
146 if cfg.sbr_present {
147 let rate = cfg.extension_sample_rate.unwrap_or(cfg.sample_rate * 2);
148 d.block.set_sbr_rate(Some(rate));
149 d.block.set_sbr_ps(cfg.ps_present);
150 } else if !cfg.ps_present {
151 // Plain AAC-LC config: an SBR payload may still follow (implicit signalling).
152 d.block.set_implicit_core(cfg.sample_rate);
153 }
154 if cfg.ps_present {
155 // PS output is stereo whatever the core's channel count.
156 d.channels = 2;
157 }
158 d.config = Some(cfg);
159 d
160 }
161
162 /// Core-only decoding: SBR and PS are never applied. An explicit SBR or PS
163 /// config is dropped, and implicit SBR is never armed, so every SBR extension
164 /// payload is skipped and the output stays at the core rate.
165 pub fn core_only(mut self) -> AacDecoder {
166 self.block.set_sbr_rate(None);
167 self.block.disable_implicit_sbr();
168 if let Some(c) = self.config.as_mut() {
169 c.sbr_present = false;
170 c.ps_present = false;
171 c.extension_sample_rate = None;
172 }
173 self
174 }
175
176 /// A decoder configured from raw AudioSpecificConfig bytes -- an mp4
177 /// `esds` payload or a Matroska `CodecPrivate`.
178 pub fn with_config_bytes(data: &[u8]) -> Result<AacDecoder> {
179 Ok(AacDecoder::with_config(parse_audio_specific_config(data)?))
180 }
181
182 /// Successful access units that used perceptual noise substitution.
183 pub fn pns_aus(&self) -> usize {
184 self.block.pns_aus()
185 }
186
187 /// The configuration this decoder was built with, if any.
188 pub fn config(&self) -> Option<&AudioSpecificConfig> {
189 self.config.as_ref()
190 }
191
192 /// Whether the stream asked for SBR, and what became of it. A plain AAC-LC
193 /// stream whose frames carry an SBR payload (implicit signalling) reports
194 /// [`SbrSupport::V1`] once the first such payload has been decoded; see
195 /// [`AacDecoder::sbr_implicit`].
196 pub fn sbr_support(&self) -> SbrSupport {
197 if self.block.implicit_sbr() {
198 return SbrSupport::V1;
199 }
200 match &self.config {
201 Some(c) if c.ps_present || c.sbr_present => SbrSupport::V1,
202 _ => SbrSupport::NotSignalled,
203 }
204 }
205
206 /// Whether SBR was switched on by an implicit payload: a stream that
207 /// signals plain AAC-LC (config or ADTS header) but carries an SBR
208 /// extension payload, decoded at twice the core rate as ffmpeg and the
209 /// ISO reference do. Only ever true once the first such payload has been
210 /// decoded, and only for a core rate of at most 24 kHz. Explicit SBR
211 /// signalling is reported by [`AacDecoder::sbr_support`] alone.
212 pub fn sbr_implicit(&self) -> bool {
213 self.block.implicit_sbr()
214 }
215
216 /// Whether Parametric Stereo was switched on by an implicit payload: a
217 /// stream that signals plain AAC-LC but whose SBR extension carries a PS
218 /// extension (the HE-AACv2 form with no explicit signalling). Only true once
219 /// such a PS extension has been decoded, so a caller reads it after the
220 /// first frames. Implies [`AacDecoder::sbr_implicit`].
221 pub fn ps_implicit(&self) -> bool {
222 self.block.implicit_ps()
223 }
224
225 /// The rate the samples this decoder hands back are actually at: the
226 /// extension rate for a reconstructed (V1) HE-AAC or HE-AACv2 stream,
227 /// the core rate for plain AAC-LC -- claiming bandwidth that was not
228 /// actually rebuilt would be a lie.
229 ///
230 /// For a decoder built from an ADTS header (no config), this is `None`
231 /// until the first frame has been decoded. After that it is the core
232 /// rate, or twice it once implicit SBR has switched on, so a caller
233 /// should read it again after each packet.
234 pub fn output_sample_rate(&self) -> Option<u32> {
235 let (core, ext) = match &self.config {
236 Some(c) => (c.sample_rate, c.extension_sample_rate),
237 None if self.sample_rate != 0 => (self.sample_rate, None),
238 None => return None,
239 };
240 Some(match self.sbr_support() {
241 SbrSupport::V1 => ext.unwrap_or(core * 2),
242 _ => core,
243 })
244 }
245
246 /// Decodes one packet: a raw `raw_data_block`, or one or more ADTS frames.
247 pub fn decode(&mut self, packet: &[u8], pts: Option<i64>) -> Result<DecodedAudio> {
248 let mut planes: Vec<Vec<f32>> = Vec::new();
249 if is_adts(packet) {
250 let mut at = 0usize;
251 while at + 7 <= packet.len() {
252 let header = parse_adts(&packet[at..])?;
253 let end = (at + header.frame_length).min(packet.len());
254 // A truncated frame can end before its header does; clamp so the slice cannot invert.
255 let body = &packet[(at + header.header_len).min(end)..end];
256 if self.config.is_none() {
257 self.sample_rate = header.sample_rate;
258 self.channels = header.channels;
259 self.block.set_sf_index(header.sf_index);
260 self.block.set_implicit_core(header.sample_rate);
261 }
262 let mut r = BitReader::new(body);
263 for _ in 0..header.raw_blocks {
264 let block = self.block.raw_data_block(&mut r)?;
265 merge(&mut planes, block);
266 if r.bits_remaining() < 8 {
267 break;
268 }
269 }
270 if header.frame_length == 0 {
271 break;
272 }
273 at += header.frame_length;
274 }
275 } else {
276 let mut r = BitReader::new(packet);
277 planes = self.block.raw_data_block(&mut r)?;
278 }
279 // ffmpeg decodes an HE-AAC mono stream with no PS payload (SBR reconstructed, one
280 // plane) as two identical channels ("Treating HE-AAC mono as stereo"). Match it.
281 if planes.len() == 1 && self.sbr_support() == SbrSupport::V1 {
282 let dup = planes[0].clone();
283 planes.push(dup);
284 }
285 let channels = planes.len();
286 if channels == 0 {
287 return Ok(DecodedAudio {
288 sample_rate: self.output_sample_rate().unwrap_or(self.sample_rate),
289 channels: self.channels,
290 samples: Vec::new(),
291 pts,
292 });
293 }
294 if self.channels == 0 {
295 self.channels = channels as u16;
296 }
297 // A PCE names each plane's speaker, which orders the output; otherwise the
298 // channel configuration's bitstream order does.
299 let order = self
300 .block
301 .plane_order(channels)
302 .unwrap_or_else(|| film_order(channels).to_vec());
303 let frames = planes[0].len();
304 let mut samples = vec![0.0f32; frames * channels];
305 for (out_ch, &src) in order.iter().take(channels).enumerate() {
306 let plane = &planes[src.min(channels - 1)];
307 // Planes can differ in length after `merge`; only the first `frames` samples fit.
308 for (i, &v) in plane.iter().take(frames).enumerate() {
309 samples[i * channels + out_ch] = v;
310 }
311 }
312 Ok(DecodedAudio {
313 sample_rate: self.output_sample_rate().unwrap_or(self.sample_rate),
314 channels: channels as u16,
315 samples,
316 pts,
317 })
318 }
319}
320
321/// Appends a block's planes to the packet's, growing the plane count if a later
322/// `raw_data_block` carries more channels than an earlier one.
323fn merge(planes: &mut Vec<Vec<f32>>, block: Vec<Vec<f32>>) {
324 if planes.is_empty() {
325 *planes = block;
326 return;
327 }
328 for (i, plane) in block.into_iter().enumerate() {
329 match planes.get_mut(i) {
330 Some(dst) => dst.extend_from_slice(&plane),
331 None => planes.push(plane),
332 }
333 }
334}
335
336impl Default for AacDecoder {
337 fn default() -> AacDecoder {
338 AacDecoder::new()
339 }
340}