forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBb07f07aTahinli3 months ago1061 commits

lib.rs266 lines, 9.7 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;
38pub mod sbr_qmf;
39mod sbr_qmf_window;
40mod sbr_tables;
41pub mod tables;
42
43pub use config::{
44 AOT_AAC_LC, AOT_PS, AOT_SBR, AdtsHeader, AudioSpecificConfig, ProgramConfig,
45 audio_specific_config_bytes, channels_for_config, config_for_channels, is_adts, parse_adts,
46 parse_audio_specific_config, parse_program_config, sample_rate_for_index, sf_index_for_rate,
47 write_adts_header, write_audio_specific_config,
48};
49pub use decode::{FRAME_LEN, ToolSideInfoRow, WindowSequence, tool_sideinfo_log};
50pub use ec_core::{Error, Result};
51pub use encode::{AacEncoder, AacEncoderConfig, EncodedPacket, WindowShape};
52/// Diagnostic only (round-20): per-(access-unit, channel) side-info rows
53/// logged during decode when `EC_AAC_SBR_SIDEINFO_DEBUG` is set.
54pub use sbr_chain::{SbrSideInfoRow, hold_call_count, sbr_sideinfo_log};
55/// Diagnostic only (round-17 Task 1 conviction check): reads back the
56/// per-absolute-QMF-band transmitted signal/noise energy sums
57/// `EC_AAC_SBR_NOISE_FRACTION_DEBUG` accumulates during decode.
58pub use sbr_env::noise_fraction_table;
59pub use tables::SAMPLE_RATES;
60
61use decode::BlockDecoder;
62use ec_core::BitReader;
63
64/// What this decoder does with a High Efficiency stream.
65#[derive(Clone, Copy, Debug, PartialEq, Eq)]
66pub enum SbrSupport {
67 /// The stream is plain AAC-LC: nothing is missing.
68 NotSignalled,
69 /// SBR is signalled and **is** reconstructed: the decoded audio spans
70 /// the full extension bandwidth at the extension sample rate.
71 V1,
72 /// SBR is signalled but not reconstructed (Parametric Stereo streams:
73 /// PS itself is still unimplemented). The AAC-LC core decodes, at the
74 /// core rate, half the signalled bandwidth.
75 CoreOnly,
76}
77
78/// One decoded frame: interleaved `f32` in film channel order.
79#[derive(Clone, Debug, Default)]
80pub struct DecodedAudio {
81 pub sample_rate: u32,
82 pub channels: u16,
83 /// Interleaved samples, `frames() * channels` of them.
84 pub samples: Vec<f32>,
85 pub pts: Option<i64>,
86}
87
88impl DecodedAudio {
89 /// Sample frames in this block.
90 pub fn frames(&self) -> usize {
91 if self.channels == 0 {
92 0
93 } else {
94 self.samples.len() / usize::from(self.channels)
95 }
96 }
97}
98
99/// Bitstream element order to the film order `FL, FR, FC, LFE, BL, BR, SL, SR`
100/// that every downmix in this family folds (ISO/IEC 14496-3 tbl 1.19: the
101/// elements arrive centre first, LFE last).
102fn film_order(channels: usize) -> &'static [usize] {
103 match channels {
104 3 => &[1, 2, 0],
105 4 => &[1, 2, 0, 3],
106 5 => &[1, 2, 0, 3, 4],
107 6 => &[1, 2, 0, 5, 3, 4],
108 8 => &[1, 2, 0, 7, 5, 6, 3, 4],
109 _ => &[0, 1, 2, 3, 4, 5, 6, 7],
110 }
111}
112
113/// An AAC-LC decoder.
114pub struct AacDecoder {
115 block: BlockDecoder,
116 config: Option<AudioSpecificConfig>,
117 sample_rate: u32,
118 channels: u16,
119}
120
121impl AacDecoder {
122 /// A decoder with no configuration yet: it will take its parameters from
123 /// the first ADTS header it sees.
124 pub fn new() -> AacDecoder {
125 AacDecoder {
126 block: BlockDecoder::new(3),
127 config: None,
128 sample_rate: 0,
129 channels: 0,
130 }
131 }
132
133 /// A decoder configured from a parsed AudioSpecificConfig.
134 pub fn with_config(cfg: AudioSpecificConfig) -> AacDecoder {
135 let mut d = AacDecoder::new();
136 d.block.set_sf_index(cfg.sf_index);
137 d.sample_rate = cfg.sample_rate;
138 d.channels = cfg.channels;
139 // PS is not reconstructed; SBR is. Both still need the core
140 // decoded first, but only a plain-SBR (non-PS) stream gets the
141 // extension-rate QMF chain wired in.
142 if cfg.sbr_present && !cfg.ps_present {
143 let rate = cfg.extension_sample_rate.unwrap_or(cfg.sample_rate * 2);
144 d.block.set_sbr_rate(Some(rate));
145 }
146 d.config = Some(cfg);
147 d
148 }
149
150 /// A decoder configured from raw AudioSpecificConfig bytes -- an mp4
151 /// `esds` payload or a Matroska `CodecPrivate`.
152 pub fn with_config_bytes(data: &[u8]) -> Result<AacDecoder> {
153 Ok(AacDecoder::with_config(parse_audio_specific_config(data)?))
154 }
155
156 /// Successful access units that used perceptual noise substitution.
157 pub fn pns_aus(&self) -> usize {
158 self.block.pns_aus()
159 }
160
161 /// The configuration this decoder was built with, if any.
162 pub fn config(&self) -> Option<&AudioSpecificConfig> {
163 self.config.as_ref()
164 }
165
166 /// Whether the stream asked for SBR, and what became of it.
167 pub fn sbr_support(&self) -> SbrSupport {
168 match &self.config {
169 Some(c) if c.ps_present => SbrSupport::CoreOnly,
170 Some(c) if c.sbr_present => SbrSupport::V1,
171 _ => SbrSupport::NotSignalled,
172 }
173 }
174
175 /// The rate the samples this decoder hands back are actually at: the
176 /// extension rate for a reconstructed (V1) HE-AAC stream, the core
177 /// rate for plain AAC-LC or an unreconstructed (PS) stream -- claiming
178 /// bandwidth that was not actually rebuilt would be a lie.
179 pub fn output_sample_rate(&self) -> Option<u32> {
180 self.config.as_ref().map(|c| match self.sbr_support() {
181 SbrSupport::V1 => c.extension_sample_rate.unwrap_or(c.sample_rate * 2),
182 _ => c.sample_rate,
183 })
184 }
185
186 /// Decodes one packet: a raw `raw_data_block`, or one or more ADTS frames.
187 pub fn decode(&mut self, packet: &[u8], pts: Option<i64>) -> Result<DecodedAudio> {
188 let mut planes: Vec<Vec<f32>> = Vec::new();
189 if is_adts(packet) {
190 let mut at = 0usize;
191 while at + 7 <= packet.len() {
192 let header = parse_adts(&packet[at..])?;
193 let end = (at + header.frame_length).min(packet.len());
194 let body = &packet[at + header.header_len..end];
195 if self.config.is_none() {
196 self.sample_rate = header.sample_rate;
197 self.channels = header.channels;
198 self.block.set_sf_index(header.sf_index);
199 }
200 let mut r = BitReader::new(body);
201 for _ in 0..header.raw_blocks {
202 let block = self.block.raw_data_block(&mut r)?;
203 merge(&mut planes, block);
204 if r.bits_remaining() < 8 {
205 break;
206 }
207 }
208 if header.frame_length == 0 {
209 break;
210 }
211 at += header.frame_length;
212 }
213 } else {
214 let mut r = BitReader::new(packet);
215 planes = self.block.raw_data_block(&mut r)?;
216 }
217 let channels = planes.len();
218 if channels == 0 {
219 return Ok(DecodedAudio {
220 sample_rate: self.output_sample_rate().unwrap_or(self.sample_rate),
221 channels: self.channels,
222 samples: Vec::new(),
223 pts,
224 });
225 }
226 if self.channels == 0 {
227 self.channels = channels as u16;
228 }
229 let order = film_order(channels);
230 let frames = planes[0].len();
231 let mut samples = vec![0.0f32; frames * channels];
232 for (out_ch, &src) in order.iter().take(channels).enumerate() {
233 let plane = &planes[src.min(channels - 1)];
234 for (i, &v) in plane.iter().enumerate() {
235 samples[i * channels + out_ch] = v;
236 }
237 }
238 Ok(DecodedAudio {
239 sample_rate: self.output_sample_rate().unwrap_or(self.sample_rate),
240 channels: channels as u16,
241 samples,
242 pts,
243 })
244 }
245}
246
247/// Appends a block's planes to the packet's, growing the plane count if a later
248/// `raw_data_block` carries more channels than an earlier one.
249fn merge(planes: &mut Vec<Vec<f32>>, block: Vec<Vec<f32>>) {
250 if planes.is_empty() {
251 *planes = block;
252 return;
253 }
254 for (i, plane) in block.into_iter().enumerate() {
255 match planes.get_mut(i) {
256 Some(dst) => dst.extend_from_slice(&plane),
257 None => planes.push(plane),
258 }
259 }
260}
261
262impl Default for AacDecoder {
263 fn default() -> AacDecoder {
264 AacDecoder::new()
265 }
266}