forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust381.2 MiBe18142dTahinli5 hours ago4543 commits

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