forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB30d372eTahinli3 months ago42 commits

decoder.rs386 lines, 14.4 KiBHistoryRawDownload
1//! The public decoder: syncframes in, interleaved `f32` audio frames out.
2
3use ec_core::{
4 AudioFrame, AudioParameters, Buf, ChannelLayout, ChannelPosition, CodecId, CodecParameters,
5 Decoder, Error, Frame, MediaParameters, Packet, Result, SampleFormat, Timestamp,
6};
7
8use crate::bsi::{self, Acmod, Bsi};
9use crate::decode::{Core, Syntax};
10use crate::eac3;
11use crate::syncinfo;
12use crate::transform::BLOCK_SAMPLES;
13
14/// Blocks per AC-3 syncframe (A/52 §5.3.3); E-AC-3 states its own count.
15const AC3_BLOCKS: usize = 6;
16
17/// How the decoder should fold the coded channels down, if at all.
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
19pub enum Downmix {
20 /// Hand out every coded channel in the stream's own layout.
21 #[default]
22 Native,
23 /// A/52 §7.8.2 Lo/Ro stereo downmix.
24 Stereo,
25 /// The §7.8.2 mono sum of that stereo downmix.
26 Mono,
27}
28
29/// Decoder knobs. The defaults are what the standard asks a decoder to do.
30#[derive(Debug, Clone, Copy, PartialEq)]
31pub struct Options {
32 /// Fraction of the `dynrng` compression to apply, `0.0` to `1.0`.
33 ///
34 /// §7.7.1: "the AC-3 decoder shall, by default, implement the compression
35 /// characteristic indicated by the `dynrng` values", so this defaults to
36 /// full. Set it to `0.0` for the original dynamic range; the raw words stay
37 /// visible either way through [`crate::FrameInfo`].
38 pub drc_scale: f32,
39 /// Channel folding, off by default.
40 pub downmix: Downmix,
41 /// Substitute pseudo-random noise for zero-bit mantissas (§7.3.4), which
42 /// is what the standard asks a decoder to do and what this defaults to.
43 ///
44 /// The sequence itself is implementation-defined ("any reasonably random
45 /// sequence"), so two conformant decoders differ by exactly this noise;
46 /// turning it off is how a comparison against another decoder isolates
47 /// everything else.
48 pub dither: bool,
49}
50
51impl Default for Options {
52 fn default() -> Options {
53 Options {
54 drc_scale: 1.0,
55 downmix: Downmix::Native,
56 dither: true,
57 }
58 }
59}
60
61/// What a decoded frame's header said, for callers that route on it rather
62/// than on the samples: rate, layout and the metadata AC-3 carries per frame.
63#[derive(Debug, Clone, PartialEq)]
64pub struct FrameInfo {
65 /// AC-3 or E-AC-3.
66 pub syntax: Syntax,
67 /// Sample rate in Hz.
68 pub sample_rate: u32,
69 /// Full-bandwidth channels, LFE excluded.
70 pub nfchans: usize,
71 /// LFE present.
72 pub lfeon: bool,
73 /// Dialogue normalisation in -dB. Surfaced, never applied: the volume
74 /// control that has to combine it with the listener's setting is not in
75 /// this crate (§7.6).
76 pub dialnorm: u8,
77 /// Heavy compression word, when the frame carried one (§7.7.2).
78 pub compr: Option<u8>,
79 /// Centre mix level as a linear gain, when the mode has three fronts.
80 pub center_mix_level: Option<f32>,
81 /// Surround mix level as a linear gain, when the mode has surrounds.
82 pub surround_mix_level: Option<f32>,
83 /// Bit stream mode (Table 5.7).
84 pub bsmod: u8,
85 /// Audio coding mode.
86 pub acmod: Acmod,
87 /// Samples per channel this frame produced.
88 pub samples: usize,
89}
90
91/// An AC-3 / E-AC-3 decoder.
92///
93/// One packet is one syncframe (plus any E-AC-3 substreams that belong to it),
94/// which is how every container this family reads stores the format.
95pub struct Ac3Decoder {
96 core: Core,
97 params: CodecParameters,
98 options: Options,
99 pending: Option<Frame>,
100 info: Option<FrameInfo>,
101 /// Set by [`Decoder::flush`]; the next drained call reports end of stream.
102 flushed: bool,
103}
104
105impl Default for Ac3Decoder {
106 fn default() -> Ac3Decoder {
107 Ac3Decoder::new()
108 }
109}
110
111impl Ac3Decoder {
112 /// A decoder with default [`Options`] and no stream configuration yet;
113 /// everything it needs comes from the first syncframe.
114 pub fn new() -> Ac3Decoder {
115 Ac3Decoder::with_options(Options::default())
116 }
117
118 /// A decoder with explicit options.
119 pub fn with_options(options: Options) -> Ac3Decoder {
120 Ac3Decoder {
121 core: Core::new(),
122 params: CodecParameters::new(CodecId::Ac3),
123 options,
124 pending: None,
125 info: None,
126 flushed: false,
127 }
128 }
129
130 /// The options in force; changes take effect on the next packet.
131 pub fn options_mut(&mut self) -> &mut Options {
132 &mut self.options
133 }
134
135 /// What the last decoded frame's header said.
136 pub fn frame_info(&self) -> Option<&FrameInfo> {
137 self.info.as_ref()
138 }
139
140 /// Decode one syncframe into interleaved `f32` samples.
141 ///
142 /// `data` starts at a sync word. Truncated input is [`Error::NeedMore`], a
143 /// broken bit stream [`Error::Corrupt`], and a construct this build does
144 /// not implement [`Error::Unsupported`] with the reason named — never a
145 /// panic, on any input.
146 pub fn decode_frame(&mut self, data: &[u8]) -> Result<AudioFrame> {
147 let mut samples = Vec::new();
148 let (info, consumed) = self.decode_substream(data, &mut samples)?;
149 let _ = consumed;
150 let layout = self.layout(&info);
151 let interleaved = self.fold(samples, &info);
152 let channels = layout.channel_count();
153 let count = interleaved.len().checked_div(channels).unwrap_or(0);
154 self.info = Some(info.clone());
155 self.params.media = MediaParameters::Audio(AudioParameters {
156 sample_rate: info.sample_rate,
157 layout: layout.clone(),
158 format: Some(SampleFormat::F32),
159 bits_per_sample: None,
160 });
161 self.params.codec = match info.syntax {
162 Syntax::Ac3 => CodecId::Ac3,
163 Syntax::Eac3 => CodecId::EAc3,
164 };
165 let mut bytes = Vec::with_capacity(interleaved.len() * 4);
166 for v in &interleaved {
167 bytes.extend_from_slice(&v.to_le_bytes());
168 }
169 AudioFrame::try_new(
170 SampleFormat::F32,
171 false,
172 layout,
173 info.sample_rate,
174 count,
175 vec![Buf::from_vec(bytes)],
176 )
177 }
178
179 /// Decode one independent substream, appending interleaved samples.
180 /// Returns the frame's header summary and the bytes it consumed.
181 fn decode_substream(&mut self, data: &[u8], out: &mut Vec<f32>) -> Result<(FrameInfo, usize)> {
182 // Six bytes, not five: the sixth is where both syntaxes put bsid.
183 if data.len() < 6 {
184 return Err(Error::NeedMore);
185 }
186 // The syntax is decided by bsid, which sits five bytes in for AC-3 and
187 // two for E-AC-3 — so read it where both agree it can be found: after
188 // the sync word, E-AC-3 puts strmtyp/substreamid/frmsiz first, and
189 // bsid is at a fixed offset from the frame start in both.
190 let bsid = data[5] >> 3;
191 let mut r = ec_core::BitReader::new(data);
192 if bsid <= 10 {
193 let sync = syncinfo::parse_from(&mut r)?;
194 let bsi = bsi::parse_from(&mut r)?;
195 if data.len() < sync.frame_size {
196 return Err(Error::NeedMore);
197 }
198 self.core.drc_scale = self.options.drc_scale;
199 self.core.dither_on = self.options.dither;
200 self.core
201 .start_frame(Syntax::Ac3, sync.fscod as usize, &bsi);
202 for blk in 0..AC3_BLOCKS {
203 self.core.block(&mut r, blk, out)?;
204 }
205 Ok((
206 self.info_from(Syntax::Ac3, sync.sample_rate, &bsi, AC3_BLOCKS),
207 sync.frame_size,
208 ))
209 } else {
210 let hdr = eac3::bsi::parse_from(&mut r)?;
211 if data.len() < hdr.frame_size {
212 return Err(Error::NeedMore);
213 }
214 if hdr.strmtyp == eac3::StreamType::Dependent {
215 return Err(Error::unsupported(
216 "E-AC-3 dependent substream as the first substream of a packet",
217 "a dependent substream carries channel extensions for an \
218 independent one that has to be decoded first",
219 ));
220 }
221 self.core.drc_scale = self.options.drc_scale;
222 self.core.dither_on = self.options.dither;
223 eac3::decode_frame(&mut self.core, &mut r, &hdr, out)?;
224 Ok((
225 self.info_from(Syntax::Eac3, hdr.sample_rate, &hdr.bsi, hdr.nblocks),
226 hdr.frame_size,
227 ))
228 }
229 }
230
231 fn info_from(&self, syntax: Syntax, sample_rate: u32, bsi: &Bsi, nblocks: usize) -> FrameInfo {
232 FrameInfo {
233 syntax,
234 sample_rate,
235 nfchans: bsi.nfchans,
236 lfeon: bsi.lfeon,
237 dialnorm: bsi.dialnorm,
238 compr: bsi.compr,
239 center_mix_level: bsi.cmixlev.map(bsi::center_mix_level),
240 surround_mix_level: bsi.surmixlev.map(bsi::surround_mix_level),
241 bsmod: bsi.bsmod,
242 acmod: bsi.acmod,
243 samples: nblocks * BLOCK_SAMPLES,
244 }
245 }
246
247 /// The channel layout the coded channels are handed out in.
248 fn native_layout(&self, info: &FrameInfo) -> ChannelLayout {
249 use ChannelPosition::*;
250 let mut positions: Vec<ChannelPosition> = match info.acmod {
251 Acmod::DualMono => vec![FrontLeft, FrontRight],
252 Acmod::Mono => vec![FrontCenter],
253 Acmod::Stereo => vec![FrontLeft, FrontRight],
254 Acmod::Surround3_0 => vec![FrontLeft, FrontRight, FrontCenter],
255 Acmod::Surround2_1 => vec![FrontLeft, FrontRight, BackCenter],
256 Acmod::Surround3_1 => vec![FrontLeft, FrontRight, FrontCenter, BackCenter],
257 Acmod::Surround2_2 => vec![FrontLeft, FrontRight, BackLeft, BackRight],
258 Acmod::Surround3_2 => vec![FrontLeft, FrontRight, FrontCenter, BackLeft, BackRight],
259 };
260 if info.lfeon {
261 let fronts = match info.acmod {
262 Acmod::Mono => 1,
263 Acmod::Surround3_0 | Acmod::Surround3_1 | Acmod::Surround3_2 => 3,
264 _ => 2,
265 };
266 positions.insert(fronts.min(positions.len()), Lfe);
267 }
268 match positions.len() {
269 1 => ChannelLayout::Mono,
270 2 => ChannelLayout::Stereo,
271 _ if positions == ChannelLayout::Surround5_1.positions() => ChannelLayout::Surround5_1,
272 _ => ChannelLayout::Custom(positions),
273 }
274 }
275
276 fn layout(&self, info: &FrameInfo) -> ChannelLayout {
277 match self.options.downmix {
278 Downmix::Native => self.native_layout(info),
279 Downmix::Stereo => ChannelLayout::Stereo,
280 Downmix::Mono => ChannelLayout::Mono,
281 }
282 }
283
284 /// Apply the requested downmix, if any (§7.8.2).
285 fn fold(&self, samples: Vec<f32>, info: &FrameInfo) -> Vec<f32> {
286 if self.options.downmix == Downmix::Native {
287 return samples;
288 }
289 let layout = self.native_layout(info);
290 let positions = layout.positions().to_vec();
291 let channels = positions.len();
292 if channels == 0 {
293 return samples;
294 }
295 let clev = info.center_mix_level.unwrap_or(0.707);
296 let slev = info.surround_mix_level.unwrap_or(0.707);
297 // §7.8.2 with the standard's own coefficients, then one scaling so a
298 // full-scale input cannot overflow the downmix — the standard's fixed
299 // -7.65 dB would quieten every stereo listener instead.
300 let (mut left, mut right) = (Vec::new(), Vec::new());
301 for &p in &positions {
302 let (l, r) = match p {
303 ChannelPosition::FrontLeft => (1.0, 0.0),
304 ChannelPosition::FrontRight => (0.0, 1.0),
305 ChannelPosition::FrontCenter => (clev, clev),
306 ChannelPosition::BackLeft | ChannelPosition::SideLeft => (slev, 0.0),
307 ChannelPosition::BackRight | ChannelPosition::SideRight => (0.0, slev),
308 // A single surround channel feeds both sides at 0.7 × slev.
309 ChannelPosition::BackCenter => (0.7 * slev, 0.7 * slev),
310 // The LFE is not part of a §7.8.2 downmix.
311 _ => (0.0, 0.0),
312 };
313 left.push(l);
314 right.push(r);
315 }
316 let peak = left
317 .iter()
318 .sum::<f32>()
319 .max(right.iter().sum::<f32>())
320 .max(1.0);
321 let frames = samples.len() / channels;
322 match self.options.downmix {
323 Downmix::Stereo => {
324 let mut out = vec![0.0; frames * 2];
325 for f in 0..frames {
326 let block = &samples[f * channels..(f + 1) * channels];
327 let (mut lo, mut ro) = (0.0, 0.0);
328 for (ch, &v) in block.iter().enumerate() {
329 lo += v * left[ch];
330 ro += v * right[ch];
331 }
332 out[f * 2] = lo / peak;
333 out[f * 2 + 1] = ro / peak;
334 }
335 out
336 }
337 _ => {
338 let mut out = vec![0.0; frames];
339 for f in 0..frames {
340 let block = &samples[f * channels..(f + 1) * channels];
341 let mut m = 0.0;
342 for (ch, &v) in block.iter().enumerate() {
343 m += v * (left[ch] + right[ch]);
344 }
345 out[f] = m / (2.0 * peak);
346 }
347 out
348 }
349 }
350 }
351}
352
353impl Decoder for Ac3Decoder {
354 fn codec_parameters(&self) -> &CodecParameters {
355 &self.params
356 }
357
358 fn send_packet(&mut self, packet: &Packet) -> Result<()> {
359 let mut frame = self.decode_frame(&packet.data)?;
360 frame.pts = packet.pts.map(|ts| Timestamp::new(ts, packet.time_base));
361 self.pending = Some(Frame::Audio(frame));
362 Ok(())
363 }
364
365 fn receive_frame(&mut self) -> Result<Frame> {
366 match self.pending.take() {
367 Some(frame) => Ok(frame),
368 None if self.flushed => Err(Error::Eof),
369 None => Err(Error::NeedMore),
370 }
371 }
372
373 fn flush(&mut self) -> Result<()> {
374 // Nothing is held back: one packet in, one frame out. The overlap-add
375 // tail belongs to the *next* frame, so there is no delayed frame to
376 // drain — draining it would emit a half block of silence.
377 self.flushed = true;
378 Ok(())
379 }
380
381 fn reset(&mut self) {
382 self.core.reset();
383 self.pending = None;
384 self.flushed = false;
385 }
386}