forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBc0d4024Tahinli3 months ago866 commits

lib.rs233 lines, 6.7 KiBHistoryRawDownload
1//! The `rusty_aac` 0.5 surface, served by `ec-aac`.
2//!
3//! Only what edith consumes is here, at the incumbent's signatures:
4//! `AacDecoder::with_config_bytes` (audio.rs:1731), `AacEncoder::new` with
5//! `AacEncoderConfig` (mux.rs:2116, export.rs:1756) and `sf_index_for_rate`
6//! (export.rs:1678). The encoder's tool flags are kept as fields so a caller
7//! written against the incumbent still compiles; each one names what it maps to.
8
9#![forbid(unsafe_code)]
10
11pub use ec_aac::{
12 AdtsHeader, AudioSpecificConfig, SAMPLE_RATES, audio_specific_config_bytes, is_adts,
13 parse_adts, parse_audio_specific_config, sample_rate_for_index, sf_index_for_rate,
14 write_adts_header, write_audio_specific_config,
15};
16
17/// The incumbent's error type: one variant per refusal reason, `Eof` included
18/// so `while let Ok(p) = next_packet()` still terminates.
19#[derive(Debug)]
20pub enum Error {
21 Eof,
22 NeedMore,
23 Invalid(String),
24 Unsupported(String),
25}
26
27impl std::fmt::Display for Error {
28 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
29 match self {
30 Error::Eof => write!(f, "end of stream"),
31 Error::NeedMore => write!(f, "need more data"),
32 Error::Invalid(m) => write!(f, "invalid: {m}"),
33 Error::Unsupported(m) => write!(f, "unsupported: {m}"),
34 }
35 }
36}
37
38impl std::error::Error for Error {}
39
40impl Error {
41 pub fn invalid(msg: impl Into<String>) -> Error {
42 Error::Invalid(msg.into())
43 }
44
45 pub fn unsupported(msg: impl Into<String>) -> Error {
46 Error::Unsupported(msg.into())
47 }
48}
49
50impl From<ec_aac::Error> for Error {
51 fn from(e: ec_aac::Error) -> Error {
52 match e {
53 ec_aac::Error::Eof => Error::Eof,
54 ec_aac::Error::NeedMore => Error::NeedMore,
55 ec_aac::Error::Unsupported { .. } => Error::Unsupported(e.to_string()),
56 other => Error::Invalid(other.to_string()),
57 }
58 }
59}
60
61pub type Result<T> = std::result::Result<T, Error>;
62
63/// One decoded frame, interleaved, in film channel order.
64#[derive(Clone, Debug, Default)]
65pub struct DecodedAudio {
66 pub sample_rate: u32,
67 pub channels: u16,
68 pub samples: Vec<f32>,
69 pub pts: Option<i64>,
70}
71
72impl DecodedAudio {
73 pub fn frames(&self) -> usize {
74 if self.channels == 0 {
75 0
76 } else {
77 self.samples.len() / usize::from(self.channels)
78 }
79 }
80}
81
82/// What the decoder does with a High Efficiency stream.
83pub use ec_aac::SbrSupport;
84
85/// An AAC-LC decoder.
86pub struct AacDecoder(ec_aac::AacDecoder);
87
88impl AacDecoder {
89 pub fn new() -> AacDecoder {
90 AacDecoder(ec_aac::AacDecoder::new())
91 }
92
93 pub fn with_config(cfg: AudioSpecificConfig) -> AacDecoder {
94 AacDecoder(ec_aac::AacDecoder::with_config(cfg))
95 }
96
97 pub fn with_config_bytes(data: &[u8]) -> Result<AacDecoder> {
98 Ok(AacDecoder(ec_aac::AacDecoder::with_config_bytes(data)?))
99 }
100
101 pub fn sbr_support(&self) -> SbrSupport {
102 self.0.sbr_support()
103 }
104
105 pub fn output_sample_rate(&self) -> Option<u32> {
106 self.0.output_sample_rate()
107 }
108
109 pub fn decode(&mut self, packet: &[u8], pts: Option<i64>) -> Result<DecodedAudio> {
110 let d = self.0.decode(packet, pts)?;
111 Ok(DecodedAudio {
112 sample_rate: d.sample_rate,
113 channels: d.channels,
114 samples: d.samples,
115 pts: d.pts,
116 })
117 }
118}
119
120impl Default for AacDecoder {
121 fn default() -> AacDecoder {
122 AacDecoder::new()
123 }
124}
125
126/// Window-shape policy.
127#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
128pub enum WindowShape {
129 #[default]
130 Sine,
131 Kbd,
132 /// Per-frame dispatch on content tonality; served here as [`WindowShape::Sine`].
133 Auto,
134}
135
136/// Encoder options, at the incumbent's field set.
137#[derive(Debug, Clone, Copy)]
138pub struct AacEncoderConfig {
139 /// Target bitrate in bits per second.
140 pub bitrate_bps: u32,
141 /// Window-shape policy.
142 pub window_shape: WindowShape,
143 /// The `Auto` gate's threshold; unused here, `Auto` codes as sine.
144 pub shape_tonality_pct: f32,
145 /// Run the psychoacoustic model on short blocks: always on here.
146 pub short_block_psy: bool,
147 /// Make the signal-to-mask ratio a function of band tonality: always on here.
148 pub tonality_smr: bool,
149 /// Emit TNS on long blocks; not emitted by this encoder (decoding it is
150 /// complete either way).
151 pub tns: bool,
152 /// Level-invariant transient detector: always on here.
153 pub relative_transients: bool,
154 /// Perceptual noise substitution; not emitted by this encoder.
155 pub pns: bool,
156 /// Intensity stereo; not emitted by this encoder.
157 pub intensity: bool,
158 /// Split a pair's bit budget by perceptual demand: always on here, the rate
159 /// loop is joint over the whole frame.
160 pub stereo_bit_split: bool,
161}
162
163impl Default for AacEncoderConfig {
164 fn default() -> AacEncoderConfig {
165 AacEncoderConfig {
166 bitrate_bps: 128_000,
167 window_shape: WindowShape::Sine,
168 shape_tonality_pct: 0.5,
169 short_block_psy: true,
170 tonality_smr: true,
171 tns: false,
172 relative_transients: true,
173 pns: false,
174 intensity: false,
175 stereo_bit_split: true,
176 }
177 }
178}
179
180/// One encoded raw access unit (a `raw_data_block`, no ADTS framing).
181#[derive(Debug, Clone)]
182pub struct EncodedPacket {
183 pub data: Vec<u8>,
184 pub pts: i64,
185 pub duration: u32,
186}
187
188/// An AAC-LC encoder.
189pub struct AacEncoder(ec_aac::AacEncoder);
190
191impl AacEncoder {
192 pub fn new(config: AacEncoderConfig) -> AacEncoder {
193 AacEncoder(ec_aac::AacEncoder::new(ec_aac::AacEncoderConfig {
194 bitrate_bps: config.bitrate_bps.max(1),
195 window_shape: match config.window_shape {
196 WindowShape::Kbd => ec_aac::WindowShape::Kbd,
197 _ => ec_aac::WindowShape::Sine,
198 },
199 adts: false,
200 mid_side: true,
201 window_switching: true,
202 }))
203 }
204
205 pub fn sample_rate(&self) -> u32 {
206 self.0.sample_rate()
207 }
208
209 pub fn channels(&self) -> u16 {
210 self.0.channels()
211 }
212
213 pub fn push_pcm(&mut self, interleaved: &[f32], channels: u16, sample_rate: u32) -> Result<()> {
214 Ok(self.0.push_pcm(interleaved, channels, sample_rate)?)
215 }
216
217 pub fn push_pcm_planar(&mut self, planes: &[&[f32]], sample_rate: u32) -> Result<()> {
218 Ok(self.0.push_pcm_planar(planes, sample_rate)?)
219 }
220
221 pub fn finish(&mut self) {
222 self.0.finish();
223 }
224
225 pub fn next_packet(&mut self) -> Result<EncodedPacket> {
226 let p = self.0.next_packet()?;
227 Ok(EncodedPacket {
228 data: p.data,
229 pts: p.pts,
230 duration: p.duration,
231 })
232 }
233}