forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBdd00c7cTahinli3 months ago169 commits

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