forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBe63caffTahinli3 months ago103 commits

lib.rs230 lines, 8.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's SBR and Parametric Stereo are
20//! **not** implemented; a stream that signals them decodes to its AAC-LC core,
21//! at the core sample rate, and says so through [`AacDecoder::sbr_support`] and
22//! [`AacDecoder::output_sample_rate`] rather than silently claiming the
23//! extension rate. See `sbr_is_reported_not_silently_upsampled` in the tests.
24
25#![forbid(unsafe_code)]
26
27mod config;
28mod decode;
29mod encode;
30mod huffman;
31pub mod tables;
32
33pub use config::{
34 AOT_AAC_LC, AOT_PS, AOT_SBR, AdtsHeader, AudioSpecificConfig, ProgramConfig,
35 audio_specific_config_bytes, channels_for_config, config_for_channels, is_adts, parse_adts,
36 parse_audio_specific_config, parse_program_config, sample_rate_for_index, sf_index_for_rate,
37 write_adts_header, write_audio_specific_config,
38};
39pub use decode::{FRAME_LEN, WindowSequence};
40pub use ec_core::{Error, Result};
41pub use encode::{AacEncoder, AacEncoderConfig, EncodedPacket, WindowShape};
42pub use tables::SAMPLE_RATES;
43
44use decode::BlockDecoder;
45use ec_core::BitReader;
46
47/// What this decoder does with a High Efficiency stream.
48#[derive(Clone, Copy, Debug, PartialEq, Eq)]
49pub enum SbrSupport {
50 /// The stream is plain AAC-LC: nothing is missing.
51 NotSignalled,
52 /// SBR (and possibly PS) is signalled and is **not** reconstructed. The
53 /// AAC-LC core decodes, at the core rate, half the signalled bandwidth.
54 CoreOnly,
55}
56
57/// One decoded frame: interleaved `f32` in film channel order.
58#[derive(Clone, Debug, Default)]
59pub struct DecodedAudio {
60 pub sample_rate: u32,
61 pub channels: u16,
62 /// Interleaved samples, `frames() * channels` of them.
63 pub samples: Vec<f32>,
64 pub pts: Option<i64>,
65}
66
67impl DecodedAudio {
68 /// Sample frames in this block.
69 pub fn frames(&self) -> usize {
70 if self.channels == 0 {
71 0
72 } else {
73 self.samples.len() / usize::from(self.channels)
74 }
75 }
76}
77
78/// Bitstream element order to the film order `FL, FR, FC, LFE, BL, BR, SL, SR`
79/// that every downmix in this family folds (ISO/IEC 14496-3 tbl 1.19: the
80/// elements arrive centre first, LFE last).
81fn film_order(channels: usize) -> &'static [usize] {
82 match channels {
83 3 => &[1, 2, 0],
84 4 => &[1, 2, 0, 3],
85 5 => &[1, 2, 0, 3, 4],
86 6 => &[1, 2, 0, 5, 3, 4],
87 8 => &[1, 2, 0, 7, 5, 6, 3, 4],
88 _ => &[0, 1, 2, 3, 4, 5, 6, 7],
89 }
90}
91
92/// An AAC-LC decoder.
93pub struct AacDecoder {
94 block: BlockDecoder,
95 config: Option<AudioSpecificConfig>,
96 sample_rate: u32,
97 channels: u16,
98}
99
100impl AacDecoder {
101 /// A decoder with no configuration yet: it will take its parameters from
102 /// the first ADTS header it sees.
103 pub fn new() -> AacDecoder {
104 AacDecoder {
105 block: BlockDecoder::new(3),
106 config: None,
107 sample_rate: 0,
108 channels: 0,
109 }
110 }
111
112 /// A decoder configured from a parsed AudioSpecificConfig.
113 pub fn with_config(cfg: AudioSpecificConfig) -> AacDecoder {
114 let mut d = AacDecoder::new();
115 d.block.set_sf_index(cfg.sf_index);
116 d.sample_rate = cfg.sample_rate;
117 d.channels = cfg.channels;
118 d.config = Some(cfg);
119 d
120 }
121
122 /// A decoder configured from raw AudioSpecificConfig bytes -- an mp4
123 /// `esds` payload or a Matroska `CodecPrivate`.
124 pub fn with_config_bytes(data: &[u8]) -> Result<AacDecoder> {
125 Ok(AacDecoder::with_config(parse_audio_specific_config(data)?))
126 }
127
128 /// The configuration this decoder was built with, if any.
129 pub fn config(&self) -> Option<&AudioSpecificConfig> {
130 self.config.as_ref()
131 }
132
133 /// Whether the stream asked for SBR, and what became of it.
134 pub fn sbr_support(&self) -> SbrSupport {
135 match &self.config {
136 Some(c) if c.sbr_present || c.ps_present => SbrSupport::CoreOnly,
137 _ => SbrSupport::NotSignalled,
138 }
139 }
140
141 /// The rate the samples this decoder hands back are actually at.
142 ///
143 /// For an HE-AAC stream this is the **core** rate, not the doubled rate the
144 /// configuration advertises: the SBR extension is not reconstructed, so
145 /// claiming its rate would be claiming bandwidth that is not there.
146 pub fn output_sample_rate(&self) -> Option<u32> {
147 self.config.as_ref().map(|c| c.sample_rate)
148 }
149
150 /// Decodes one packet: a raw `raw_data_block`, or one or more ADTS frames.
151 pub fn decode(&mut self, packet: &[u8], pts: Option<i64>) -> Result<DecodedAudio> {
152 let mut planes: Vec<Vec<f32>> = Vec::new();
153 if is_adts(packet) {
154 let mut at = 0usize;
155 while at + 7 <= packet.len() {
156 let header = parse_adts(&packet[at..])?;
157 let end = (at + header.frame_length).min(packet.len());
158 let body = &packet[at + header.header_len..end];
159 if self.config.is_none() {
160 self.sample_rate = header.sample_rate;
161 self.channels = header.channels;
162 self.block.set_sf_index(header.sf_index);
163 }
164 let mut r = BitReader::new(body);
165 for _ in 0..header.raw_blocks {
166 let block = self.block.raw_data_block(&mut r)?;
167 merge(&mut planes, block);
168 if r.bits_remaining() < 8 {
169 break;
170 }
171 }
172 if header.frame_length == 0 {
173 break;
174 }
175 at += header.frame_length;
176 }
177 } else {
178 let mut r = BitReader::new(packet);
179 planes = self.block.raw_data_block(&mut r)?;
180 }
181 let channels = planes.len();
182 if channels == 0 {
183 return Ok(DecodedAudio {
184 sample_rate: self.sample_rate,
185 channels: self.channels,
186 samples: Vec::new(),
187 pts,
188 });
189 }
190 if self.channels == 0 {
191 self.channels = channels as u16;
192 }
193 let order = film_order(channels);
194 let frames = planes[0].len();
195 let mut samples = vec![0.0f32; frames * channels];
196 for (out_ch, &src) in order.iter().take(channels).enumerate() {
197 let plane = &planes[src.min(channels - 1)];
198 for (i, &v) in plane.iter().enumerate() {
199 samples[i * channels + out_ch] = v;
200 }
201 }
202 Ok(DecodedAudio {
203 sample_rate: self.sample_rate,
204 channels: channels as u16,
205 samples,
206 pts,
207 })
208 }
209}
210
211/// Appends a block's planes to the packet's, growing the plane count if a later
212/// `raw_data_block` carries more channels than an earlier one.
213fn merge(planes: &mut Vec<Vec<f32>>, block: Vec<Vec<f32>>) {
214 if planes.is_empty() {
215 *planes = block;
216 return;
217 }
218 for (i, plane) in block.into_iter().enumerate() {
219 match planes.get_mut(i) {
220 Some(dst) => dst.extend_from_slice(&plane),
221 None => planes.push(plane),
222 }
223 }
224}
225
226impl Default for AacDecoder {
227 fn default() -> AacDecoder {
228 AacDecoder::new()
229 }
230}