forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB06be466Tahinli2 months ago3574 commits

decoder.rs441 lines, 17.2 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 /// Generate the pseudo-random noise the format asks for: dither in place
42 /// of zero-bit mantissas (§7.3.4) and the blend that fills the spectral
43 /// extension band (§E3.6.4.2.4). On by default, because both are what the
44 /// standard asks a decoder to do.
45 ///
46 /// Neither sequence is specified — §7.3.4 says "any reasonably random
47 /// sequence" and §E3.6.4.2.4 just names a zero-mean unit-variance source —
48 /// so two conformant decoders differ by exactly this noise and nothing
49 /// else. Turning it off is how a comparison against another decoder
50 /// isolates everything that *is* specified.
51 pub dither: bool,
52}
53
54impl Default for Options {
55 fn default() -> Options {
56 Options {
57 drc_scale: 1.0,
58 downmix: Downmix::Native,
59 dither: true,
60 }
61 }
62}
63
64/// What a decoded frame's header said, for callers that route on it rather
65/// than on the samples: rate, layout and the metadata AC-3 carries per frame.
66#[derive(Debug, Clone, PartialEq)]
67pub struct FrameInfo {
68 /// AC-3 or E-AC-3.
69 pub syntax: Syntax,
70 /// Sample rate in Hz.
71 pub sample_rate: u32,
72 /// Full-bandwidth channels, LFE excluded.
73 pub nfchans: usize,
74 /// LFE present.
75 pub lfeon: bool,
76 /// Dialogue normalisation in -dB. Surfaced, never applied: the volume
77 /// control that has to combine it with the listener's setting is not in
78 /// this crate (§7.6).
79 pub dialnorm: u8,
80 /// Heavy compression word, when the frame carried one (§7.7.2).
81 pub compr: Option<u8>,
82 /// Centre mix level as a linear gain, when the mode has three fronts.
83 pub center_mix_level: Option<f32>,
84 /// Surround mix level as a linear gain, when the mode has surrounds.
85 pub surround_mix_level: Option<f32>,
86 /// Bit stream mode (Table 5.7).
87 pub bsmod: u8,
88 /// Audio coding mode.
89 pub acmod: Acmod,
90 /// Samples per channel this frame produced.
91 pub samples: usize,
92}
93
94/// An AC-3 / E-AC-3 decoder.
95///
96/// One packet is one syncframe (plus any E-AC-3 substreams that belong to it),
97/// which is how every container this family reads stores the format.
98pub struct Ac3Decoder {
99 core: Core,
100 params: CodecParameters,
101 options: Options,
102 pending: Option<Frame>,
103 info: Option<FrameInfo>,
104 /// Set by [`Decoder::flush`]; the next drained call reports end of stream.
105 flushed: bool,
106}
107
108impl Default for Ac3Decoder {
109 fn default() -> Ac3Decoder {
110 Ac3Decoder::new()
111 }
112}
113
114impl Ac3Decoder {
115 /// A decoder with default [`Options`] and no stream configuration yet;
116 /// everything it needs comes from the first syncframe.
117 pub fn new() -> Ac3Decoder {
118 Ac3Decoder::with_options(Options::default())
119 }
120
121 /// A decoder with explicit options.
122 pub fn with_options(options: Options) -> Ac3Decoder {
123 Ac3Decoder {
124 core: Core::new(),
125 params: CodecParameters::new(CodecId::Ac3),
126 options,
127 pending: None,
128 info: None,
129 flushed: false,
130 }
131 }
132
133 /// The options in force; changes take effect on the next packet.
134 pub fn options_mut(&mut self) -> &mut Options {
135 &mut self.options
136 }
137
138 /// What the last decoded frame's header said.
139 pub fn frame_info(&self) -> Option<&FrameInfo> {
140 self.info.as_ref()
141 }
142
143 /// Decode one syncframe into interleaved `f32` samples.
144 ///
145 /// `data` starts at a sync word. Truncated input is [`Error::NeedMore`], a
146 /// broken bit stream [`Error::Corrupt`], and a construct this build does
147 /// not implement [`Error::Unsupported`] with the reason named — never a
148 /// panic, on any input.
149 ///
150 /// After the frame, `data` may hold only padding that is not itself a
151 /// syncframe: container slack is ignored. A tail that *begins* another
152 /// syncframe is stream this decoder would otherwise drop in silence — a
153 /// dependent substream whose channels extend the frame, or a second frame
154 /// altogether — and that is [`Error::Unsupported`] naming what it is;
155 /// containers hand frames over one at a time.
156 pub fn decode_frame(&mut self, data: &[u8]) -> Result<AudioFrame> {
157 let mut samples = Vec::new();
158 let (info, consumed) = self.decode_substream(data, &mut samples)?;
159 reject_tail(&data[consumed..])?;
160 let layout = self.layout(&info);
161 let interleaved = self.fold(samples, &info);
162 let channels = layout.channel_count();
163 let count = interleaved.len().checked_div(channels).unwrap_or(0);
164 self.info = Some(info.clone());
165 self.params.media = MediaParameters::Audio(AudioParameters {
166 sample_rate: info.sample_rate,
167 layout: layout.clone(),
168 format: Some(SampleFormat::F32),
169 bits_per_sample: None,
170 });
171 self.params.codec = match info.syntax {
172 Syntax::Ac3 => CodecId::Ac3,
173 Syntax::Eac3 => CodecId::EAc3,
174 };
175 let mut bytes = Vec::with_capacity(interleaved.len() * 4);
176 for v in &interleaved {
177 bytes.extend_from_slice(&v.to_le_bytes());
178 }
179 AudioFrame::try_new(
180 SampleFormat::F32,
181 false,
182 layout,
183 info.sample_rate,
184 count,
185 vec![Buf::from_vec(bytes)],
186 )
187 }
188
189 /// Decode one independent substream, appending interleaved samples.
190 /// Returns the frame's header summary and the bytes it consumed.
191 fn decode_substream(&mut self, data: &[u8], out: &mut Vec<f32>) -> Result<(FrameInfo, usize)> {
192 // Six bytes, not five: the sixth is where both syntaxes put bsid.
193 if data.len() < 6 {
194 return Err(Error::NeedMore);
195 }
196 // The syntax is decided by bsid, which sits five bytes in for AC-3 and
197 // two for E-AC-3 — so read it where both agree it can be found: after
198 // the sync word, E-AC-3 puts strmtyp/substreamid/frmsiz first, and
199 // bsid is at a fixed offset from the frame start in both.
200 let bsid = data[5] >> 3;
201 let mut r = ec_core::BitReader::new(data);
202 if bsid <= 10 {
203 let sync = syncinfo::parse_from(&mut r)?;
204 let bsi = bsi::parse_from(&mut r)?;
205 if data.len() < sync.frame_size {
206 return Err(Error::NeedMore);
207 }
208 self.core.drc_scale = self.options.drc_scale;
209 self.core.dither_on = self.options.dither;
210 self.core
211 .start_frame(Syntax::Ac3, sync.fscod as usize, &bsi);
212 for blk in 0..AC3_BLOCKS {
213 self.core.block(&mut r, blk, out)?;
214 }
215 Ok((
216 self.info_from(Syntax::Ac3, sync.sample_rate, &bsi, AC3_BLOCKS),
217 sync.frame_size,
218 ))
219 } else {
220 let hdr = eac3::bsi::parse_from(&mut r)?;
221 if data.len() < hdr.frame_size {
222 return Err(Error::NeedMore);
223 }
224 if hdr.strmtyp == eac3::StreamType::Dependent {
225 return Err(Error::unsupported(
226 "E-AC-3 dependent substream as the first substream of a packet",
227 "a dependent substream carries channel extensions for an \
228 independent one that has to be decoded first",
229 ));
230 }
231 self.core.drc_scale = self.options.drc_scale;
232 self.core.dither_on = self.options.dither;
233 eac3::decode_frame(&mut self.core, &mut r, &hdr, out)?;
234 Ok((
235 self.info_from(Syntax::Eac3, hdr.sample_rate, &hdr.bsi, hdr.nblocks),
236 hdr.frame_size,
237 ))
238 }
239 }
240
241 fn info_from(&self, syntax: Syntax, sample_rate: u32, bsi: &Bsi, nblocks: usize) -> FrameInfo {
242 FrameInfo {
243 syntax,
244 sample_rate,
245 nfchans: bsi.nfchans,
246 lfeon: bsi.lfeon,
247 dialnorm: bsi.dialnorm,
248 compr: bsi.compr,
249 center_mix_level: bsi.cmixlev.map(bsi::center_mix_level),
250 surround_mix_level: bsi.surmixlev.map(bsi::surround_mix_level),
251 bsmod: bsi.bsmod,
252 acmod: bsi.acmod,
253 samples: nblocks * BLOCK_SAMPLES,
254 }
255 }
256
257 /// The channel layout the coded channels are handed out in.
258 fn native_layout(&self, info: &FrameInfo) -> ChannelLayout {
259 use ChannelPosition::*;
260 let mut positions: Vec<ChannelPosition> = match info.acmod {
261 Acmod::DualMono => vec![FrontLeft, FrontRight],
262 Acmod::Mono => vec![FrontCenter],
263 Acmod::Stereo => vec![FrontLeft, FrontRight],
264 Acmod::Surround3_0 => vec![FrontLeft, FrontRight, FrontCenter],
265 Acmod::Surround2_1 => vec![FrontLeft, FrontRight, BackCenter],
266 Acmod::Surround3_1 => vec![FrontLeft, FrontRight, FrontCenter, BackCenter],
267 Acmod::Surround2_2 => vec![FrontLeft, FrontRight, BackLeft, BackRight],
268 Acmod::Surround3_2 => vec![FrontLeft, FrontRight, FrontCenter, BackLeft, BackRight],
269 };
270 if info.lfeon {
271 let fronts = match info.acmod {
272 Acmod::Mono => 1,
273 Acmod::Surround3_0 | Acmod::Surround3_1 | Acmod::Surround3_2 => 3,
274 _ => 2,
275 };
276 positions.insert(fronts.min(positions.len()), Lfe);
277 }
278 match positions.len() {
279 1 => ChannelLayout::Mono,
280 2 => ChannelLayout::Stereo,
281 _ if positions == ChannelLayout::Surround5_1.positions() => ChannelLayout::Surround5_1,
282 _ => ChannelLayout::Custom(positions),
283 }
284 }
285
286 fn layout(&self, info: &FrameInfo) -> ChannelLayout {
287 match self.options.downmix {
288 Downmix::Native => self.native_layout(info),
289 Downmix::Stereo => ChannelLayout::Stereo,
290 Downmix::Mono => ChannelLayout::Mono,
291 }
292 }
293
294 /// Apply the requested downmix, if any (§7.8.2).
295 fn fold(&self, samples: Vec<f32>, info: &FrameInfo) -> Vec<f32> {
296 if self.options.downmix == Downmix::Native {
297 return samples;
298 }
299 let layout = self.native_layout(info);
300 let positions = layout.positions().to_vec();
301 let channels = positions.len();
302 if channels == 0 {
303 return samples;
304 }
305 let clev = info.center_mix_level.unwrap_or(0.707);
306 let slev = info.surround_mix_level.unwrap_or(0.707);
307 // §7.8.2 with the standard's own coefficients, then one scaling so a
308 // full-scale input cannot overflow the downmix — the standard's fixed
309 // -7.65 dB would quieten every stereo listener instead.
310 let (mut left, mut right) = (Vec::new(), Vec::new());
311 for &p in &positions {
312 let (l, r) = match p {
313 ChannelPosition::FrontLeft => (1.0, 0.0),
314 ChannelPosition::FrontRight => (0.0, 1.0),
315 ChannelPosition::FrontCenter => (clev, clev),
316 ChannelPosition::BackLeft | ChannelPosition::SideLeft => (slev, 0.0),
317 ChannelPosition::BackRight | ChannelPosition::SideRight => (0.0, slev),
318 // A single surround channel feeds both sides at 0.7 × slev.
319 ChannelPosition::BackCenter => (0.7 * slev, 0.7 * slev),
320 // The LFE is not part of a §7.8.2 downmix.
321 _ => (0.0, 0.0),
322 };
323 left.push(l);
324 right.push(r);
325 }
326 let peak = left
327 .iter()
328 .sum::<f32>()
329 .max(right.iter().sum::<f32>())
330 .max(1.0);
331 let frames = samples.len() / channels;
332 match self.options.downmix {
333 Downmix::Stereo => {
334 let mut out = vec![0.0; frames * 2];
335 for f in 0..frames {
336 let block = &samples[f * channels..(f + 1) * channels];
337 let (mut lo, mut ro) = (0.0, 0.0);
338 for (ch, &v) in block.iter().enumerate() {
339 lo += v * left[ch];
340 ro += v * right[ch];
341 }
342 out[f * 2] = lo / peak;
343 out[f * 2 + 1] = ro / peak;
344 }
345 out
346 }
347 _ => {
348 let mut out = vec![0.0; frames];
349 for f in 0..frames {
350 let block = &samples[f * channels..(f + 1) * channels];
351 let mut m = 0.0;
352 for (ch, &v) in block.iter().enumerate() {
353 m += v * (left[ch] + right[ch]);
354 }
355 out[f] = m / (2.0 * peak);
356 }
357 out
358 }
359 }
360 }
361}
362
363impl Decoder for Ac3Decoder {
364 fn codec_parameters(&self) -> &CodecParameters {
365 &self.params
366 }
367
368 fn send_packet(&mut self, packet: &Packet) -> Result<()> {
369 let mut frame = self.decode_frame(&packet.data)?;
370 frame.pts = packet.pts.map(|ts| Timestamp::new(ts, packet.time_base));
371 self.pending = Some(Frame::Audio(frame));
372 Ok(())
373 }
374
375 fn receive_frame(&mut self) -> Result<Frame> {
376 match self.pending.take() {
377 Some(frame) => Ok(frame),
378 None if self.flushed => Err(Error::Eof),
379 None => Err(Error::NeedMore),
380 }
381 }
382
383 fn flush(&mut self) -> Result<()> {
384 // Nothing is held back: one packet in, one frame out. The overlap-add
385 // tail belongs to the *next* frame, so there is no delayed frame to
386 // drain — draining it would emit a half block of silence.
387 self.flushed = true;
388 Ok(())
389 }
390
391 fn reset(&mut self) {
392 self.core.reset();
393 self.pending = None;
394 self.flushed = false;
395 }
396}
397
398/// What the bytes after a decoded frame may say. Nothing, or padding that is
399/// not itself a syncframe — the slack a container's block may carry around a
400/// frame. A tail that *begins* a syncframe is stream the caller handed over in
401/// one packet that this decoder decodes only the first of: a dependent
402/// substream whose channels extend the frame, or a second frame altogether.
403/// Dropping either loses audio in silence, so both are named refusals; a
404/// `0x0B77` coincidence that does not parse as a header is junk, and junk is
405/// the spec's own allowance.
406fn reject_tail(tail: &[u8]) -> Result<()> {
407 // Both syntaxes announce a frame with 0x0B77, and no header is shorter
408 // than six bytes.
409 if tail.len() < 6 || u16::from_be_bytes([tail[0], tail[1]]) != syncinfo::SYNCWORD {
410 return Ok(());
411 }
412 let named = if tail[5] >> 3 > 10 {
413 match eac3::parse_from(&mut ec_core::BitReader::new(tail)) {
414 // The 7.1-as-5.1-plus-dependents shape: the first substream is
415 // exactly what decoded, the tail is the extension channels this
416 // build does not assemble.
417 Ok(hdr) if hdr.strmtyp == eac3::StreamType::Dependent => Some((
418 "E-AC-3 dependent substream in the tail of the packet",
419 "a dependent substream carries channel extensions for an \
420 independent one that has to be decoded first",
421 )),
422 Ok(_) => Some((
423 "a second syncframe in the tail of the packet",
424 "one packet is one syncframe and the substreams that belong \
425 to it; hand frames to the decoder one at a time",
426 )),
427 // A syncword coincidence that is no header is padding, not stream.
428 Err(_) => None,
429 }
430 } else {
431 syncinfo::parse(tail).is_ok().then_some((
432 "a second syncframe in the tail of the packet",
433 "one packet is one syncframe and the substreams that belong \
434 to it; hand frames to the decoder one at a time",
435 ))
436 };
437 match named {
438 Some((what, why)) => Err(Error::unsupported(what, why)),
439 None => Ok(()),
440 }
441}