forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBb7434a2Tahinli1 month ago3896 commits

decoder.rs578 lines, 23.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::dependent;
11use crate::eac3;
12use crate::syncinfo;
13use crate::transform::BLOCK_SAMPLES;
14
15/// Blocks per AC-3 syncframe (A/52 §5.3.3); E-AC-3 states its own count.
16const AC3_BLOCKS: usize = 6;
17
18/// How the decoder should fold the coded channels down, if at all.
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
20pub enum Downmix {
21 /// Hand out every coded channel in the stream's own layout.
22 #[default]
23 Native,
24 /// A/52 §7.8.2 Lo/Ro stereo downmix.
25 Stereo,
26 /// The §7.8.2 mono sum of that stereo downmix.
27 Mono,
28}
29
30/// Decoder knobs. The defaults are what the standard asks a decoder to do.
31#[derive(Debug, Clone, Copy, PartialEq)]
32pub struct Options {
33 /// Fraction of the `dynrng` compression to apply, `0.0` to `1.0`.
34 ///
35 /// §7.7.1: "the AC-3 decoder shall, by default, implement the compression
36 /// characteristic indicated by the `dynrng` values", so this defaults to
37 /// full. Set it to `0.0` for the original dynamic range; the raw words stay
38 /// visible either way through [`crate::FrameInfo`].
39 pub drc_scale: f32,
40 /// Channel folding, off by default.
41 pub downmix: Downmix,
42 /// Generate the pseudo-random noise the format asks for: dither in place
43 /// of zero-bit mantissas (§7.3.4) and the blend that fills the spectral
44 /// extension band (§E3.6.4.2.4). On by default, because both are what the
45 /// standard asks a decoder to do.
46 ///
47 /// Neither sequence is specified — §7.3.4 says "any reasonably random
48 /// sequence" and §E3.6.4.2.4 just names a zero-mean unit-variance source —
49 /// so two conformant decoders differ by exactly this noise and nothing
50 /// else. Turning it off is how a comparison against another decoder
51 /// isolates everything that *is* specified.
52 pub dither: bool,
53}
54
55impl Default for Options {
56 fn default() -> Options {
57 Options {
58 drc_scale: 1.0,
59 downmix: Downmix::Native,
60 dither: true,
61 }
62 }
63}
64
65/// What a decoded frame's header said, for callers that route on it rather
66/// than on the samples: rate, layout and the metadata AC-3 carries per frame.
67#[derive(Debug, Clone, PartialEq)]
68pub struct FrameInfo {
69 /// AC-3 or E-AC-3.
70 pub syntax: Syntax,
71 /// Sample rate in Hz.
72 pub sample_rate: u32,
73 /// Full-bandwidth channels of the independent substream, LFE excluded.
74 /// Dependent substreams add to the frame's layout, not to this count.
75 pub nfchans: usize,
76 /// LFE present.
77 pub lfeon: bool,
78 /// Dialogue normalisation in -dB. Surfaced, never applied: the volume
79 /// control that has to combine it with the listener's setting is not in
80 /// this crate (§7.6).
81 pub dialnorm: u8,
82 /// Heavy compression word, when the frame carried one (§7.7.2).
83 pub compr: Option<u8>,
84 /// Centre mix level as a linear gain, when the mode has three fronts.
85 pub center_mix_level: Option<f32>,
86 /// Surround mix level as a linear gain, when the mode has surrounds.
87 pub surround_mix_level: Option<f32>,
88 /// Bit stream mode (Table 5.7).
89 pub bsmod: u8,
90 /// Audio coding mode.
91 pub acmod: Acmod,
92 /// Samples per channel this frame produced.
93 pub samples: usize,
94}
95
96/// An AC-3 / E-AC-3 decoder.
97///
98/// One packet is one syncframe (plus any E-AC-3 substreams that belong to it),
99/// which is how the containers this family reads usually store the format. A
100/// packet holding several syncframes is walked by [`Ac3Decoder::decode_packet`].
101pub struct Ac3Decoder {
102 core: Core,
103 /// One decoder state per dependent substream of the packet, in packet
104 /// order: each carries its own blocks' history from frame to frame.
105 dependents: Vec<Core>,
106 params: CodecParameters,
107 options: Options,
108 pending: Option<Frame>,
109 info: Option<FrameInfo>,
110 /// Set by [`Decoder::flush`]; the next drained call reports end of stream.
111 flushed: bool,
112}
113
114impl Default for Ac3Decoder {
115 fn default() -> Ac3Decoder {
116 Ac3Decoder::new()
117 }
118}
119
120impl Ac3Decoder {
121 /// A decoder with default [`Options`] and no stream configuration yet;
122 /// everything it needs comes from the first syncframe.
123 pub fn new() -> Ac3Decoder {
124 Ac3Decoder::with_options(Options::default())
125 }
126
127 /// A decoder with explicit options.
128 pub fn with_options(options: Options) -> Ac3Decoder {
129 Ac3Decoder {
130 core: Core::new(),
131 dependents: Vec::new(),
132 params: CodecParameters::new(CodecId::Ac3),
133 options,
134 pending: None,
135 info: None,
136 flushed: false,
137 }
138 }
139
140 /// The options in force; changes take effect on the next packet.
141 pub fn options_mut(&mut self) -> &mut Options {
142 &mut self.options
143 }
144
145 /// What the last decoded frame's header said.
146 pub fn frame_info(&self) -> Option<&FrameInfo> {
147 self.info.as_ref()
148 }
149
150 /// Decode one syncframe into interleaved `f32` samples.
151 ///
152 /// `data` starts at a sync word. Truncated input is [`Error::NeedMore`], a
153 /// broken bit stream [`Error::Corrupt`], and a construct this build does
154 /// not implement [`Error::Unsupported`] with the reason named — never a
155 /// panic, on any input.
156 ///
157 /// The independent substream's channels come first, then the channels of
158 /// each E-AC-3 dependent substream that follows it, in packet order. A
159 /// dependent substream whose channel map names a speaker this build has no
160 /// position for is refused by name (see [`dependent`]). After the
161 /// frame, `data` may hold only padding that is not itself a syncframe:
162 /// container slack is ignored. A second syncframe after this one is
163 /// [`Error::Unsupported`] naming what it is: this call takes one syncframe,
164 /// and [`Ac3Decoder::decode_packet`] takes a packet of several.
165 pub fn decode_frame(&mut self, data: &[u8]) -> Result<AudioFrame> {
166 let syncframe = self.decode_syncframe(data)?;
167 reject_tail(&data[syncframe.consumed..])?;
168 self.audio_frame(syncframe.info, syncframe.layout, syncframe.interleaved)
169 }
170
171 /// Decode a packet holding one or more syncframes into one audio frame.
172 ///
173 /// Each syncframe (with its E-AC-3 dependent substreams) is decoded in
174 /// packet order against the same decoder state, so the output is the
175 /// frames' samples back to back, exactly as decoding them one packet at a
176 /// time would give. Bytes after the last syncframe that do not begin a
177 /// header are padding and ignored. A following syncframe must share the
178 /// first one's channel layout, and an E-AC-3 independent substream of
179 /// another program (substream id 1 and up) is refused by name: it would be
180 /// stream this decoder does not produce.
181 pub fn decode_packet(&mut self, data: &[u8]) -> Result<AudioFrame> {
182 let mut first = self.decode_syncframe(data)?;
183 let mut pos = first.consumed;
184 while begins_syncframe(&data[pos..]) {
185 let tail = &data[pos..];
186 if tail[5] >> 3 > 10 {
187 let hdr = eac3::parse_from(&mut ec_core::BitReader::new(tail))?;
188 if hdr.substreamid != 0 {
189 return Err(Error::unsupported(
190 "E-AC-3 independent substream of another program in the packet",
191 "programs 2 and up are not decoded; the packet's first \
192 program is the one this decoder produces",
193 ));
194 }
195 }
196 let next = self.decode_syncframe(tail).map_err(|e| match e {
197 Error::NeedMore => Error::corrupt("syncframe in the packet tail is truncated"),
198 other => other,
199 })?;
200 if next.layout != first.layout {
201 return Err(Error::unsupported(
202 "syncframes with different channel layouts in one packet",
203 "a packet's frames are concatenated into one frame of one layout",
204 ));
205 }
206 first.interleaved.extend(next.interleaved);
207 first.info = next.info;
208 pos += next.consumed;
209 }
210 self.audio_frame(first.info, first.layout, first.interleaved)
211 }
212
213 /// Decode the syncframe that starts `data`: its independent substream and
214 /// the dependent substreams after it, as interleaved samples in the layout
215 /// the options ask for. Bytes after it are the caller's to judge.
216 fn decode_syncframe(&mut self, data: &[u8]) -> Result<Syncframe> {
217 let mut samples = Vec::new();
218 let (info, consumed) = self.decode_substream(data, &mut samples)?;
219 let (dependents, consumed) = self.decode_dependents(data, consumed, info.samples)?;
220 let mut frame = dependent::split(&samples, &self.core_positions(&info));
221 for d in dependents {
222 frame = dependent::merge(frame, d);
223 }
224 let positions: Vec<ChannelPosition> = frame.iter().map(|c| c.position).collect();
225 let layout = self.layout(&positions);
226 let interleaved = self.fold(dependent::interleave(&frame), &info, &positions);
227 Ok(Syncframe {
228 info,
229 layout,
230 interleaved,
231 consumed,
232 })
233 }
234
235 /// The audio frame for decoded interleaved samples, and the decoder's
236 /// stream parameters updated to match.
237 fn audio_frame(
238 &mut self,
239 info: FrameInfo,
240 layout: ChannelLayout,
241 interleaved: Vec<f32>,
242 ) -> Result<AudioFrame> {
243 let channels = layout.channel_count();
244 let count = interleaved.len().checked_div(channels).unwrap_or(0);
245 self.params.media = MediaParameters::Audio(AudioParameters {
246 sample_rate: info.sample_rate,
247 layout: layout.clone(),
248 format: Some(SampleFormat::F32),
249 bits_per_sample: None,
250 });
251 self.params.codec = match info.syntax {
252 Syntax::Ac3 => CodecId::Ac3,
253 Syntax::Eac3 => CodecId::EAc3,
254 };
255 let mut bytes = Vec::with_capacity(interleaved.len() * 4);
256 for v in &interleaved {
257 bytes.extend_from_slice(&v.to_le_bytes());
258 }
259 self.info = Some(info.clone());
260 AudioFrame::try_new(
261 SampleFormat::F32,
262 false,
263 layout,
264 info.sample_rate,
265 count,
266 vec![Buf::from_vec(bytes)],
267 )
268 }
269
270 /// Decode one independent substream, appending interleaved samples.
271 /// Returns the frame's header summary and the bytes it consumed.
272 fn decode_substream(&mut self, data: &[u8], out: &mut Vec<f32>) -> Result<(FrameInfo, usize)> {
273 // Six bytes, not five: the sixth is where both syntaxes put bsid.
274 if data.len() < 6 {
275 return Err(Error::NeedMore);
276 }
277 // The syntax is decided by bsid, which sits five bytes in for AC-3 and
278 // two for E-AC-3 — so read it where both agree it can be found: after
279 // the sync word, E-AC-3 puts strmtyp/substreamid/frmsiz first, and
280 // bsid is at a fixed offset from the frame start in both.
281 let bsid = data[5] >> 3;
282 let mut r = ec_core::BitReader::new(data);
283 if bsid <= 10 {
284 let sync = syncinfo::parse_from(&mut r)?;
285 let bsi = bsi::parse_from(&mut r)?;
286 if data.len() < sync.frame_size {
287 return Err(Error::NeedMore);
288 }
289 self.core.drc_scale = self.options.drc_scale;
290 self.core.dither_on = self.options.dither;
291 self.core
292 .start_frame(Syntax::Ac3, sync.fscod as usize, &bsi);
293 for blk in 0..AC3_BLOCKS {
294 self.core.block(&mut r, blk, out)?;
295 }
296 Ok((
297 self.info_from(Syntax::Ac3, sync.sample_rate, &bsi, AC3_BLOCKS),
298 sync.frame_size,
299 ))
300 } else {
301 let hdr = eac3::bsi::parse_from(&mut r)?;
302 if data.len() < hdr.frame_size {
303 return Err(Error::NeedMore);
304 }
305 if hdr.strmtyp == eac3::StreamType::Dependent {
306 return Err(Error::unsupported(
307 "E-AC-3 dependent substream as the first substream of a packet",
308 "a dependent substream carries channel extensions for an \
309 independent one that has to be decoded first",
310 ));
311 }
312 self.core.drc_scale = self.options.drc_scale;
313 self.core.dither_on = self.options.dither;
314 eac3::decode_frame(&mut self.core, &mut r, &hdr, out)?;
315 Ok((
316 self.info_from(Syntax::Eac3, hdr.sample_rate, &hdr.bsi, hdr.nblocks),
317 hdr.frame_size,
318 ))
319 }
320 }
321
322 /// Decode the dependent substreams that follow the independent one
323 /// (Annex E, E.3.8), starting at `pos`. Returns what each one adds and the
324 /// offset after the last of them.
325 fn decode_dependents(
326 &mut self,
327 data: &[u8],
328 mut pos: usize,
329 frames: usize,
330 ) -> Result<(Vec<Vec<dependent::Channel>>, usize)> {
331 let mut found = Vec::new();
332 let mut slot = 0;
333 while let Some(hdr) = dependent::peek(&data[pos..]) {
334 let body = data
335 .get(pos..pos + hdr.frame_size)
336 .ok_or_else(|| Error::corrupt("E-AC-3 dependent substream: truncated"))?;
337 if hdr.nblocks * BLOCK_SAMPLES != frames {
338 return Err(Error::corrupt(format!(
339 "E-AC-3 dependent substream: {} blocks, the independent substream has {}",
340 hdr.nblocks,
341 frames / BLOCK_SAMPLES
342 )));
343 }
344 let channels = hdr.nfchans + usize::from(hdr.bsi.lfeon);
345 let positions = dependent::positions(hdr.chanmap, channels)?;
346 if self.dependents.len() <= slot {
347 self.dependents.push(Core::new());
348 }
349 let (drc_scale, dither) = (self.options.drc_scale, self.options.dither);
350 let core = &mut self.dependents[slot];
351 core.drc_scale = drc_scale;
352 core.dither_on = dither;
353 let mut r = ec_core::BitReader::new(body);
354 let own = eac3::parse_from(&mut r)?;
355 let mut samples = Vec::new();
356 eac3::decode_frame(core, &mut r, &own, &mut samples)?;
357 found.push(dependent::split(&samples, &positions));
358 slot += 1;
359 pos += hdr.frame_size;
360 }
361 Ok((found, pos))
362 }
363
364 fn info_from(&self, syntax: Syntax, sample_rate: u32, bsi: &Bsi, nblocks: usize) -> FrameInfo {
365 FrameInfo {
366 syntax,
367 sample_rate,
368 nfchans: bsi.nfchans,
369 lfeon: bsi.lfeon,
370 dialnorm: bsi.dialnorm,
371 compr: bsi.compr,
372 center_mix_level: bsi.cmixlev.map(bsi::center_mix_level),
373 surround_mix_level: bsi.surmixlev.map(bsi::surround_mix_level),
374 bsmod: bsi.bsmod,
375 acmod: bsi.acmod,
376 samples: nblocks * BLOCK_SAMPLES,
377 }
378 }
379
380 /// The positions the independent substream's channels fill, in the order
381 /// its samples come out.
382 fn core_positions(&self, info: &FrameInfo) -> Vec<ChannelPosition> {
383 use ChannelPosition::*;
384 let mut positions: Vec<ChannelPosition> = match info.acmod {
385 Acmod::DualMono => vec![FrontLeft, FrontRight],
386 Acmod::Mono => vec![FrontCenter],
387 Acmod::Stereo => vec![FrontLeft, FrontRight],
388 Acmod::Surround3_0 => vec![FrontLeft, FrontRight, FrontCenter],
389 Acmod::Surround2_1 => vec![FrontLeft, FrontRight, BackCenter],
390 Acmod::Surround3_1 => vec![FrontLeft, FrontRight, FrontCenter, BackCenter],
391 Acmod::Surround2_2 => vec![FrontLeft, FrontRight, BackLeft, BackRight],
392 // ffmpeg places AC-3's Ls/Rs at the side positions ("5.1(side)").
393 Acmod::Surround3_2 => vec![FrontLeft, FrontRight, FrontCenter, SideLeft, SideRight],
394 };
395 if info.lfeon {
396 let fronts = match info.acmod {
397 Acmod::Mono => 1,
398 Acmod::Surround3_0 | Acmod::Surround3_1 | Acmod::Surround3_2 => 3,
399 _ => 2,
400 };
401 positions.insert(fronts.min(positions.len()), Lfe);
402 }
403 positions
404 }
405
406 /// The layout of a frame whose channels sit at `positions` (canonical order).
407 fn layout(&self, positions: &[ChannelPosition]) -> ChannelLayout {
408 match self.options.downmix {
409 Downmix::Native => layout_of(positions),
410 Downmix::Stereo => ChannelLayout::Stereo,
411 Downmix::Mono => ChannelLayout::Mono,
412 }
413 }
414
415 /// Apply the requested downmix, if any (§7.8.2).
416 fn fold(&self, samples: Vec<f32>, info: &FrameInfo, positions: &[ChannelPosition]) -> Vec<f32> {
417 if self.options.downmix == Downmix::Native {
418 return samples;
419 }
420 let channels = positions.len();
421 if channels == 0 {
422 return samples;
423 }
424 let clev = info.center_mix_level.unwrap_or(0.707);
425 let slev = info.surround_mix_level.unwrap_or(0.707);
426 // §7.8.2 with the standard's own coefficients, then one scaling so a
427 // full-scale input cannot overflow the downmix — the standard's fixed
428 // -7.65 dB would quieten every stereo listener instead.
429 let (mut left, mut right) = (Vec::new(), Vec::new());
430 for &p in positions {
431 let (l, r) = match p {
432 ChannelPosition::FrontLeft => (1.0, 0.0),
433 ChannelPosition::FrontRight => (0.0, 1.0),
434 ChannelPosition::FrontCenter => (clev, clev),
435 // Lc/Rc from a dependent substream sit at the -3 dB point that
436 // the standard's centre coefficient stands for.
437 ChannelPosition::FrontLeftOfCenter => (0.707, 0.0),
438 ChannelPosition::FrontRightOfCenter => (0.0, 0.707),
439 ChannelPosition::BackLeft | ChannelPosition::SideLeft => (slev, 0.0),
440 ChannelPosition::BackRight | ChannelPosition::SideRight => (0.0, slev),
441 // A single surround channel feeds both sides at 0.7 × slev.
442 ChannelPosition::BackCenter => (0.7 * slev, 0.7 * slev),
443 // The LFE is not part of a §7.8.2 downmix.
444 _ => (0.0, 0.0),
445 };
446 left.push(l);
447 right.push(r);
448 }
449 let peak = left
450 .iter()
451 .sum::<f32>()
452 .max(right.iter().sum::<f32>())
453 .max(1.0);
454 let frames = samples.len() / channels;
455 match self.options.downmix {
456 Downmix::Stereo => {
457 let mut out = vec![0.0; frames * 2];
458 for f in 0..frames {
459 let block = &samples[f * channels..(f + 1) * channels];
460 let (mut lo, mut ro) = (0.0, 0.0);
461 for (ch, &v) in block.iter().enumerate() {
462 lo += v * left[ch];
463 ro += v * right[ch];
464 }
465 out[f * 2] = lo / peak;
466 out[f * 2 + 1] = ro / peak;
467 }
468 out
469 }
470 _ => {
471 let mut out = vec![0.0; frames];
472 for f in 0..frames {
473 let block = &samples[f * channels..(f + 1) * channels];
474 let mut m = 0.0;
475 for (ch, &v) in block.iter().enumerate() {
476 m += v * (left[ch] + right[ch]);
477 }
478 out[f] = m / (2.0 * peak);
479 }
480 out
481 }
482 }
483 }
484}
485
486impl Decoder for Ac3Decoder {
487 fn codec_parameters(&self) -> &CodecParameters {
488 &self.params
489 }
490
491 fn send_packet(&mut self, packet: &Packet) -> Result<()> {
492 let mut frame = self.decode_packet(&packet.data)?;
493 frame.pts = packet.pts.map(|ts| Timestamp::new(ts, packet.time_base));
494 self.pending = Some(Frame::Audio(frame));
495 Ok(())
496 }
497
498 fn receive_frame(&mut self) -> Result<Frame> {
499 match self.pending.take() {
500 Some(frame) => Ok(frame),
501 None if self.flushed => Err(Error::Eof),
502 None => Err(Error::NeedMore),
503 }
504 }
505
506 fn flush(&mut self) -> Result<()> {
507 // Nothing is held back: one packet in, one frame out. The overlap-add
508 // tail belongs to the *next* frame, so there is no delayed frame to
509 // drain — draining it would emit a half block of silence.
510 self.flushed = true;
511 Ok(())
512 }
513
514 fn reset(&mut self) {
515 self.core.reset();
516 for d in &mut self.dependents {
517 d.reset();
518 }
519 self.pending = None;
520 self.flushed = false;
521 }
522}
523
524/// The layout of canonically ordered `positions`: the named layouts where they
525/// match, a custom one otherwise.
526fn layout_of(positions: &[ChannelPosition]) -> ChannelLayout {
527 match positions {
528 [ChannelPosition::FrontCenter] => ChannelLayout::Mono,
529 [ChannelPosition::FrontLeft, ChannelPosition::FrontRight] => ChannelLayout::Stereo,
530 _ if positions == ChannelLayout::Surround5_1.positions() => ChannelLayout::Surround5_1,
531 _ if positions == ChannelLayout::Surround7_1.positions() => ChannelLayout::Surround7_1,
532 _ => ChannelLayout::Custom(positions.to_vec()),
533 }
534}
535
536/// One syncframe as decoded: its interleaved samples in the requested layout,
537/// the header summary, and the bytes its independent and dependent substreams
538/// took.
539struct Syncframe {
540 info: FrameInfo,
541 layout: ChannelLayout,
542 interleaved: Vec<f32>,
543 consumed: usize,
544}
545
546/// Whether `tail` begins a syncframe header: the sync word, then a header that
547/// parses as AC-3 or E-AC-3 (the syntax picked by bsid). A `0x0B77`
548/// coincidence that does not parse as a header is junk, which is the spec's
549/// own allowance, so it does not count.
550fn begins_syncframe(tail: &[u8]) -> bool {
551 // Both syntaxes announce a frame with 0x0B77, and no header is shorter
552 // than six bytes.
553 if tail.len() < 6 || u16::from_be_bytes([tail[0], tail[1]]) != syncinfo::SYNCWORD {
554 return false;
555 }
556 if tail[5] >> 3 > 10 {
557 eac3::parse_from(&mut ec_core::BitReader::new(tail)).is_ok()
558 } else {
559 syncinfo::parse(tail).is_ok()
560 }
561}
562
563/// What the bytes after a frame and its dependent substreams may say. Nothing,
564/// or padding that is not itself a syncframe — the slack a container's block
565/// may carry around a frame. A tail that *begins* a syncframe is a second
566/// independent substream or a second frame: [`Ac3Decoder::decode_frame`] takes
567/// one syncframe, so that is a named refusal, and [`Ac3Decoder::decode_packet`]
568/// is the call that walks them.
569fn reject_tail(tail: &[u8]) -> Result<()> {
570 if begins_syncframe(tail) {
571 return Err(Error::unsupported(
572 "a second syncframe in the tail of the packet",
573 "decode_frame takes one syncframe; decode_packet (and send_packet) \
574 walks a packet holding several",
575 ));
576 }
577 Ok(())
578}