forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust381.4 MiB6c331afTahinli11 hours ago4261 commits

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