forge
Explore
Log in

Don't you dare go Hollow

AC-3 decoder — coupling, rematrixing, DRC and the public surface

Browse files at this commit

5bc2be282a0bd78829c316e768e0e43118e6b878Ahmet Kaan GümüşParent: bd2188c
  • feat
    • AC-3 decoder — coupling, rematrixing, DRC and the public surface
Show full message
feat(ac3): AC-3 decoder — coupling, rematrixing, DRC and the public surface

One packet is one syncframe; frames come out as interleaved f32 in the
family's channel order, with an optional section 7.8 Lo/Ro downmix for
callers that want stereo. Dynamic range compression is applied by default
because section 7.7.1 says a decoder shall, with drc_scale to turn it
down; dialnorm is surfaced and never applied.

Every fixture decodes to a per-channel correlation of 1.000000 against
ffmpeg (mono, stereo and 5.1 at 32/44.1/48 kHz).
crates/ec-ac3/src/decode.rsadded+806 -0
@@ -0,0 +1,806 @@
1+//! Syncframe and audio-block decoding: everything between a parsed header and
2+//! a block of PCM (A/52 §6.1, §7.3-§7.9).
3+//!
4+//! One [`Core`] holds the state a syncframe stream carries from block to block
5+//! and from frame to frame — exponents, coupling coordinates, bit allocation
6+//! parameters, and the overlap-add tail. The audio block routine parses
7+//! `audblk()` in bit stream order, because that is the only order in which it
8+//! can be parsed: the number of bits a mantissa occupies is computed, not sent.
9+
10+use ec_core::{BitReader, Error, Result};
11+
12+use crate::bitalloc::{self, Allocation, BitAllocParams, Channel, DeltaBa};
13+use crate::bsi::{Acmod, Bsi};
14+use crate::exps::{self, Strategy};
15+use crate::mantissa::{Dither, Mantissas, scale};
16+use crate::transform::{BLOCK_SAMPLES, Imdct};
17+
18+/// Full-bandwidth channels at most (3/2 mode).
19+pub(crate) const MAX_FBW: usize = 5;
20+/// Index of the LFE channel in the per-channel arrays.
21+pub(crate) const LFE: usize = 5;
22+/// Index of the coupling channel in the per-channel arrays.
23+pub(crate) const CPL: usize = 6;
24+/// Coded channels a frame can carry, plus the coupling channel.
25+pub(crate) const CHANNELS: usize = 7;
26+/// Coefficients per channel per block.
27+pub(crate) const COEFFS: usize = 256;
28+
29+/// Which syntax the frame is written in.
30+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31+pub enum Syntax {
32+ /// AC-3 (`bsid <= 10`), six blocks per frame.
33+ Ac3,
34+ /// Enhanced AC-3 (Annex E, `bsid == 16`), one to six blocks per frame.
35+ Eac3,
36+}
37+
38+/// The decoder state a stream carries across blocks and frames.
39+pub(crate) struct Core {
40+ pub(crate) syntax: Syntax,
41+ pub(crate) fscod: usize,
42+ pub(crate) acmod: Acmod,
43+ pub(crate) nfchans: usize,
44+ pub(crate) lfeon: bool,
45+ /// Decoded exponents per channel, valid up to that channel's `endmant`.
46+ pub(crate) exps: [[u8; COEFFS]; CHANNELS],
47+ /// Bit allocation pointers per channel.
48+ pub(crate) bap: [[u8; COEFFS]; CHANNELS],
49+ /// Exponent strategy of the current block per channel.
50+ pub(crate) expstr: [Strategy; CHANNELS],
51+ pub(crate) endmant: [usize; CHANNELS],
52+ pub(crate) strtmant: [usize; CHANNELS],
53+ // Coupling.
54+ pub(crate) cplinu: bool,
55+ pub(crate) chincpl: [bool; MAX_FBW],
56+ pub(crate) phsflginu: bool,
57+ pub(crate) cplbegf: usize,
58+ pub(crate) ncplsubnd: usize,
59+ pub(crate) ncplbnd: usize,
60+ /// Coupling band each sub-band belongs to, after `cplbndstrc` merging.
61+ pub(crate) cplband: [usize; 18],
62+ pub(crate) cplco: [[f32; 18]; MAX_FBW],
63+ pub(crate) phsflg: [bool; 18],
64+ pub(crate) cplleak: (i32, i32),
65+ /// Annex E sends a channel's coupling coordinates in the first block of
66+ /// each coupling run and only when they change after that.
67+ pub(crate) first_cplco: [bool; MAX_FBW],
68+ /// Likewise for the coupling leak initialisation.
69+ pub(crate) first_cplleak: bool,
70+ // Rematrixing.
71+ pub(crate) nrematbnd: usize,
72+ pub(crate) rematflg: [bool; 4],
73+ // Bit allocation.
74+ pub(crate) ba: BitAllocParams,
75+ pub(crate) csnroffst: u8,
76+ pub(crate) fsnroffst: [u8; CHANNELS],
77+ pub(crate) fgaincod: [u8; CHANNELS],
78+ pub(crate) deltba: [DeltaBa; CHANNELS],
79+ pub(crate) deltba_on: [bool; CHANNELS],
80+ // Per-block flags.
81+ pub(crate) blksw: [bool; MAX_FBW],
82+ pub(crate) dithflag: [bool; MAX_FBW],
83+ /// Dynamic range gain for program 1 and, in 1+1 mode, program 2.
84+ pub(crate) dynrng: [f32; 2],
85+ // Output.
86+ pub(crate) coeffs: [[f32; COEFFS]; CHANNELS],
87+ pub(crate) delay: [[f32; COEFFS]; MAX_FBW + 1],
88+ pub(crate) imdct: Imdct,
89+ pub(crate) dither: Dither,
90+ /// Fraction of the `dynrng` compression to apply (§7.7.1).
91+ pub(crate) drc_scale: f32,
92+ /// Whether zero-bit mantissas get dither (§7.3.4).
93+ pub(crate) dither_on: bool,
94+ // Spectral extension (Annex E §3.6). All unused under AC-3.
95+ pub(crate) spxinu: bool,
96+ pub(crate) chinspx: [bool; MAX_FBW],
97+ /// First and last-plus-one spectral extension sub-band.
98+ pub(crate) spx_begin: usize,
99+ pub(crate) spx_end: usize,
100+ /// Sub-band the copy region starts at.
101+ pub(crate) spxstrtf: usize,
102+ /// Raw `spxbegf`, which the coupling end frequency is derived from.
103+ pub(crate) spxbegf: usize,
104+ pub(crate) spxbndstrc: [bool; 18],
105+ /// Coupling banding structure, kept across blocks for Annex E's "reuse".
106+ pub(crate) cplbndstrc: [bool; 18],
107+ pub(crate) nspxbnds: usize,
108+ pub(crate) spxbndsz: [usize; 18],
109+ pub(crate) spxco: [[f32; 18]; MAX_FBW],
110+ /// Noise and signal blending factors per band.
111+ pub(crate) nblend: [[f32; 18]; MAX_FBW],
112+ pub(crate) sblend: [[f32; 18]; MAX_FBW],
113+ pub(crate) first_spxco: [bool; MAX_FBW],
114+ pub(crate) chinspxatten: [bool; MAX_FBW],
115+ pub(crate) spxattencod: [u8; MAX_FBW],
116+ /// The noise source of §3.6.4.2.4, kept apart from the dither source so
117+ /// neither one's sequence depends on the other's use.
118+ pub(crate) spx_noise: Dither,
119+ // Adaptive hybrid transform (Annex E §3.4). All false under AC-3.
120+ /// Which channels are AHT-coded this frame.
121+ pub(crate) aht: [bool; CHANNELS],
122+ /// Whether a channel's whole-frame AHT payload has been read yet.
123+ pub(crate) aht_read: [bool; CHANNELS],
124+ /// Six blocks of mantissas per channel: `[ch][blk * COEFFS + bin]`.
125+ pub(crate) aht_mant: Vec<f32>,
126+}
127+
128+impl Core {
129+ /// A decoder with no history: silence in the overlap-add tail and no
130+ /// coupling, which is the state the standard asks for at a sync point.
131+ pub(crate) fn new() -> Core {
132+ Core {
133+ syntax: Syntax::Ac3,
134+ fscod: 0,
135+ acmod: Acmod::Stereo,
136+ nfchans: 2,
137+ lfeon: false,
138+ exps: [[0; COEFFS]; CHANNELS],
139+ bap: [[0; COEFFS]; CHANNELS],
140+ expstr: [Strategy::Reuse; CHANNELS],
141+ endmant: [0; CHANNELS],
142+ strtmant: [0; CHANNELS],
143+ cplinu: false,
144+ chincpl: [false; MAX_FBW],
145+ phsflginu: false,
146+ cplbegf: 0,
147+ ncplsubnd: 0,
148+ ncplbnd: 0,
149+ cplband: [0; 18],
150+ cplco: [[0.0; 18]; MAX_FBW],
151+ phsflg: [false; 18],
152+ cplleak: (0, 0),
153+ first_cplco: [true; MAX_FBW],
154+ first_cplleak: true,
155+ nrematbnd: 0,
156+ rematflg: [false; 4],
157+ ba: BitAllocParams::default(),
158+ csnroffst: 0,
159+ fsnroffst: [0; CHANNELS],
160+ fgaincod: [0; CHANNELS],
161+ deltba: [DeltaBa::default(); CHANNELS],
162+ deltba_on: [false; CHANNELS],
163+ blksw: [false; MAX_FBW],
164+ dithflag: [true; MAX_FBW],
165+ dynrng: [1.0; 2],
166+ coeffs: [[0.0; COEFFS]; CHANNELS],
167+ delay: [[0.0; COEFFS]; MAX_FBW + 1],
168+ imdct: Imdct::new(),
169+ dither: Dither::default(),
170+ drc_scale: 1.0,
171+ dither_on: true,
172+ spxinu: false,
173+ chinspx: [false; MAX_FBW],
174+ spx_begin: 0,
175+ spx_end: 0,
176+ spxstrtf: 0,
177+ spxbegf: 0,
178+ spxbndstrc: [false; 18],
179+ cplbndstrc: [false; 18],
180+ nspxbnds: 0,
181+ spxbndsz: [0; 18],
182+ spxco: [[0.0; 18]; MAX_FBW],
183+ nblend: [[0.0; 18]; MAX_FBW],
184+ sblend: [[0.0; 18]; MAX_FBW],
185+ first_spxco: [true; MAX_FBW],
186+ chinspxatten: [false; MAX_FBW],
187+ spxattencod: [0; MAX_FBW],
188+ spx_noise: Dither::default(),
189+ aht: [false; CHANNELS],
190+ aht_read: [false; CHANNELS],
191+ aht_mant: vec![0.0; CHANNELS * crate::aht::AHT_BLOCKS * COEFFS],
192+ }
193+ }
194+
195+ /// Drop everything a seek invalidates.
196+ pub(crate) fn reset(&mut self) {
197+ for d in &mut self.delay {
198+ d.fill(0.0);
199+ }
200+ self.cplinu = false;
201+ self.dynrng = [1.0; 2];
202+ self.exps = [[0; COEFFS]; CHANNELS];
203+ }
204+
205+ /// Adopt a frame header: channel configuration for the blocks that follow.
206+ pub(crate) fn start_frame(&mut self, syntax: Syntax, fscod: usize, bsi: &Bsi) {
207+ self.syntax = syntax;
208+ self.fscod = fscod;
209+ self.acmod = bsi.acmod;
210+ self.nfchans = bsi.nfchans;
211+ self.lfeon = bsi.lfeon;
212+ self.strtmant = [0; CHANNELS];
213+ self.endmant[LFE] = 7;
214+ self.aht_read = [false; CHANNELS];
215+ // §7.2.2.6: delta bit allocation starts each syncframe switched off.
216+ self.deltba_on = [false; CHANNELS];
217+ self.deltba = [DeltaBa::default(); CHANNELS];
218+ }
219+
220+ /// One `dynrng` word as the gain this decoder will actually apply,
221+ /// scaled by [`Core::drc_scale`] (§7.7.1 "Partial Compression").
222+ pub(crate) fn gain(&self, dynrng: u8) -> f32 {
223+ let gain = dynrng_gain(dynrng);
224+ if self.drc_scale == 1.0 {
225+ gain
226+ } else {
227+ gain.powf(self.drc_scale)
228+ }
229+ }
230+
231+ /// Everything after the bit stream has been parsed: decouple, rematrix,
232+ /// apply the dynamic range gain, transform, interleave.
233+ pub(crate) fn finish_block(&mut self, out: &mut Vec<f32>) {
234+ self.decouple();
235+ self.rematrix();
236+ self.apply_gain();
237+ self.transform(out);
238+ }
239+
240+ /// Coded channels the frame hands out, LFE included.
241+ pub(crate) fn channels(&self) -> usize {
242+ self.nfchans + usize::from(self.lfeon)
243+ }
244+
245+ /// Decode one `audblk()`, appending `BLOCK_SAMPLES` interleaved samples per
246+ /// channel to `out` in the order [`Core::channel_order`] states.
247+ pub(crate) fn block(
248+ &mut self,
249+ r: &mut BitReader<'_>,
250+ blk: usize,
251+ out: &mut Vec<f32>,
252+ ) -> Result<()> {
253+ self.parse_block(r, blk)?;
254+ self.finish_block(out);
255+ Ok(())
256+ }
257+
258+ // ------------------------------------------------------------- parsing --
259+
260+ fn parse_block(&mut self, r: &mut BitReader<'_>, blk: usize) -> Result<()> {
261+ let nfchans = self.nfchans;
262+ for ch in 0..nfchans {
263+ self.blksw[ch] = r.read_bit()?;
264+ }
265+ for ch in 0..nfchans {
266+ self.dithflag[ch] = r.read_bit()?;
267+ }
268+ if r.read_bit()? {
269+ self.dynrng[0] = self.gain(r.read_bits(8)? as u8);
270+ } else if blk == 0 {
271+ self.dynrng[0] = 1.0;
272+ }
273+ if self.acmod == Acmod::DualMono {
274+ if r.read_bit()? {
275+ self.dynrng[1] = self.gain(r.read_bits(8)? as u8);
276+ } else if blk == 0 {
277+ self.dynrng[1] = 1.0;
278+ }
279+ }
280+
281+ // Coupling strategy.
282+ if r.read_bit()? {
283+ self.cplinu = r.read_bit()?;
284+ if self.cplinu {
285+ for ch in 0..nfchans {
286+ self.chincpl[ch] = r.read_bit()?;
287+ }
288+ if self.acmod == Acmod::Stereo {
289+ self.phsflginu = r.read_bit()?;
290+ }
291+ self.cplbegf = r.read_bits(4)? as usize;
292+ let cplendf = r.read_bits(4)? as usize;
293+ if cplendf + 3 <= self.cplbegf {
294+ return Err(Error::corrupt(format!(
295+ "AC-3 coupling: cplbegf {} above cplendf {cplendf}",
296+ self.cplbegf
297+ )));
298+ }
299+ self.ncplsubnd = 3 + cplendf - self.cplbegf;
300+ self.strtmant[CPL] = 37 + 12 * self.cplbegf;
301+ self.endmant[CPL] = 37 + 12 * (cplendf + 3);
302+ // Sub-bands merge into coupling bands as cplbndstrc says.
303+ self.cplband[0] = 0;
304+ self.ncplbnd = 1;
305+ for sbnd in 1..self.ncplsubnd {
306+ if !r.read_bit()? {
307+ self.ncplbnd += 1;
308+ }
309+ self.cplband[sbnd] = self.ncplbnd - 1;
310+ }
311+ }
312+ }
313+
314+ // Coupling coordinates.
315+ let mut cplcoe = [false; MAX_FBW];
316+ if self.cplinu {
317+ for ch in 0..nfchans {
318+ if !self.chincpl[ch] {
319+ continue;
320+ }
321+ cplcoe[ch] = r.read_bit()?;
322+ if !cplcoe[ch] {
323+ continue;
324+ }
325+ let mstrcplco = r.read_bits(2)? as i32;
326+ for bnd in 0..self.ncplbnd {
327+ let cplcoexp = r.read_bits(4)? as i32;
328+ let cplcomant = r.read_bits(4)? as f32;
329+ let mant = if cplcoexp == 15 {
330+ cplcomant / 16.0
331+ } else {
332+ (cplcomant + 16.0) / 32.0
333+ };
334+ self.cplco[ch][bnd] = mant * scale((cplcoexp + 3 * mstrcplco).min(24) as u8);
335+ }
336+ }
337+ if self.acmod == Acmod::Stereo && self.phsflginu && (cplcoe[0] || cplcoe[1]) {
338+ for bnd in 0..self.ncplbnd {
339+ self.phsflg[bnd] = r.read_bit()?;
340+ }
341+ }
342+ }
343+
344+ // Rematrixing.
345+ if self.acmod == Acmod::Stereo && r.read_bit()? {
346+ self.nrematbnd = if !self.cplinu || self.cplbegf > 2 {
347+ 4
348+ } else if self.cplbegf > 0 {
349+ 3
350+ } else {
351+ 2
352+ };
353+ for bnd in 0..self.nrematbnd {
354+ self.rematflg[bnd] = r.read_bit()?;
355+ }
356+ }
357+
358+ // Exponent strategies and bandwidths.
359+ self.expstr = [Strategy::Reuse; CHANNELS];
360+ if self.cplinu {
361+ self.expstr[CPL] = Strategy::from_code(r.read_bits(2)?);
362+ }
363+ for ch in 0..nfchans {
364+ self.expstr[ch] = Strategy::from_code(r.read_bits(2)?);
365+ }
366+ if self.lfeon {
367+ self.expstr[LFE] = if r.read_bit()? {
368+ Strategy::D15
369+ } else {
370+ Strategy::Reuse
371+ };
372+ }
373+ for ch in 0..nfchans {
374+ if self.expstr[ch] != Strategy::Reuse {
375+ if self.chincpl[ch] && self.cplinu {
376+ self.endmant[ch] = self.strtmant[CPL];
377+ } else {
378+ let chbwcod = r.read_bits(6)? as usize;
379+ if chbwcod > 60 {
380+ return Err(Error::corrupt(format!(
381+ "AC-3 audblk: chbwcod = {chbwcod} > 60"
382+ )));
383+ }
384+ self.endmant[ch] = (chbwcod + 12) * 3 + 37;
385+ }
386+ }
387+ }
388+
389+ // Exponents.
390+ if self.cplinu && self.expstr[CPL] != Strategy::Reuse {
391+ let absexp = (r.read_bits(4)? << 1) as u8;
392+ let (start, end) = (self.strtmant[CPL], self.endmant[CPL]);
393+ let ngrps = self.expstr[CPL].coupling_groups(start, end);
394+ exps::decode(
395+ r,
396+ self.expstr[CPL],
397+ ngrps,
398+ absexp,
399+ start,
400+ &mut self.exps[CPL],
401+ )?;
402+ }
403+ for ch in 0..nfchans {
404+ if self.expstr[ch] == Strategy::Reuse {
405+ continue;
406+ }
407+ let absexp = r.read_bits(4)? as u8;
408+ self.exps[ch][0] = absexp;
409+ let ngrps = self.expstr[ch].fbw_groups(self.endmant[ch]);
410+ exps::decode(r, self.expstr[ch], ngrps, absexp, 1, &mut self.exps[ch]).map_err(
411+ |e| match e {
412+ Error::Corrupt { context } => Error::corrupt(format!(
413+ "{context} (block {blk}, channel {ch}, {:?}, endmant {})",
414+ self.expstr[ch], self.endmant[ch]
415+ )),
416+ other => other,
417+ },
418+ )?;
419+ let _gainrng = r.read_bits(2)?;
420+ }
421+ if self.lfeon && self.expstr[LFE] != Strategy::Reuse {
422+ let absexp = r.read_bits(4)? as u8;
423+ self.exps[LFE][0] = absexp;
424+ exps::decode(r, Strategy::D15, 2, absexp, 1, &mut self.exps[LFE])?;
425+ }
426+
427+ // Bit allocation parameters.
428+ if r.read_bit()? {
429+ self.ba = BitAllocParams {
430+ sdcycod: r.read_bits(2)? as u8,
431+ fdcycod: r.read_bits(2)? as u8,
432+ sgaincod: r.read_bits(2)? as u8,
433+ dbpbcod: r.read_bits(2)? as u8,
434+ floorcod: r.read_bits(3)? as u8,
435+ };
436+ } else if blk == 0 {
437+ return Err(Error::corrupt(
438+ "AC-3 audblk 0: bit allocation parameters absent, nothing to reuse",
439+ ));
440+ }
441+ if r.read_bit()? {
442+ self.csnroffst = r.read_bits(6)? as u8;
443+ if self.cplinu {
444+ self.fsnroffst[CPL] = r.read_bits(4)? as u8;
445+ self.fgaincod[CPL] = r.read_bits(3)? as u8;
446+ }
447+ for ch in 0..nfchans {
448+ self.fsnroffst[ch] = r.read_bits(4)? as u8;
449+ self.fgaincod[ch] = r.read_bits(3)? as u8;
450+ }
451+ if self.lfeon {
452+ self.fsnroffst[LFE] = r.read_bits(4)? as u8;
453+ self.fgaincod[LFE] = r.read_bits(3)? as u8;
454+ }
455+ } else if blk == 0 {
456+ return Err(Error::corrupt(
457+ "AC-3 audblk 0: SNR offsets absent, nothing to reuse",
458+ ));
459+ }
460+ if self.cplinu && r.read_bit()? {
461+ // §7.2.2.1: fastleak = (cplfleak << 8) + 768, and the same for
462+ // the slow leak — the offset is not optional.
463+ self.cplleak = (
464+ ((r.read_bits(3)? as i32) << 8) + 768,
465+ ((r.read_bits(3)? as i32) << 8) + 768,
466+ );
467+ }
468+
469+ // Delta bit allocation.
470+ if r.read_bit()? {
471+ let mut deltbae = [0u32; CHANNELS];
472+ if self.cplinu {
473+ deltbae[CPL] = r.read_bits(2)?;
474+ }
475+ for ch in 0..nfchans {
476+ deltbae[ch] = r.read_bits(2)?;
477+ }
478+ let mut order = Vec::with_capacity(CHANNELS);
479+ if self.cplinu {
480+ order.push(CPL);
481+ }
482+ order.extend(0..nfchans);
483+ for ch in order {
484+ match deltbae[ch] {
485+ // Reuse: leave the previous segments in place.
486+ 0 => {}
487+ 1 => {
488+ self.deltba_on[ch] = true;
489+ let nseg = r.read_bits(3)? as usize + 1;
490+ let mut dba = DeltaBa {
491+ nseg,
492+ ..DeltaBa::default()
493+ };
494+ for seg in 0..nseg {
495+ dba.offset[seg] = r.read_bits(5)? as u8;
496+ dba.length[seg] = r.read_bits(4)? as u8;
497+ dba.delta[seg] = r.read_bits(3)? as u8;
498+ }
499+ self.deltba[ch] = dba;
500+ }
501+ // Off, and reserved treated as off.
502+ _ => self.deltba_on[ch] = false,
503+ }
504+ }
505+ }
506+
507+ // Dummy data.
508+ if r.read_bit()? {
509+ let skipl = r.read_bits(9)? as u64;
510+ r.skip_bits(skipl * 8)?;
511+ }
512+
513+ self.allocate();
514+ self.read_mantissas(r, blk)
515+ }
516+
517+ /// Run the bit allocation model for every channel of this block.
518+ pub(crate) fn allocate(&mut self) {
519+ // §7.2.2.1.1: an all-zero set of SNR offsets means no bits at all.
520+ let all_zero = (0..self.nfchans).all(|ch| self.fsnroffst[ch] == 0)
521+ && (!self.lfeon || self.fsnroffst[LFE] == 0)
522+ && (!self.cplinu || self.fsnroffst[CPL] == 0);
523+ if self.csnroffst == 0 && all_zero {
524+ for ch in 0..CHANNELS {
525+ self.bap[ch].fill(0);
526+ }
527+ return;
528+ }
529+ let mut channels: Vec<(usize, Channel)> = (0..self.nfchans)
530+ .filter(|&ch| self.endmant[ch] > 0)
531+ .map(|ch| (ch, Channel::Fbw))
532+ .collect();
533+ if self.cplinu {
534+ channels.push((CPL, Channel::Coupling { leak: self.cplleak }));
535+ }
536+ if self.lfeon {
537+ channels.push((LFE, Channel::Lfe));
538+ }
539+ for (ch, kind) in channels {
540+ let snroffset =
541+ (((i32::from(self.csnroffst) - 15) << 4) + i32::from(self.fsnroffst[ch])) << 2;
542+ let alloc = Allocation {
543+ fscod: self.fscod,
544+ params: self.ba,
545+ range: (self.strtmant[ch], self.endmant[ch]),
546+ fgaincod: self.fgaincod[ch],
547+ snroffset,
548+ kind,
549+ dba: self.deltba_on[ch].then_some(&self.deltba[ch]),
550+ high_efficiency: self.aht[ch],
551+ };
552+ bitalloc::compute(&alloc, &self.exps[ch], &mut self.bap[ch]);
553+ }
554+ }
555+
556+ /// Unpack every mantissa of the block into [`Core::coeffs`].
557+ pub(crate) fn read_mantissas(&mut self, r: &mut BitReader<'_>, blk: usize) -> Result<()> {
558+ // §7.3.5: the 3-, 5- and 11-level groups are shared *across* exponent
559+ // sets — a partial group left by one channel is finished by the next.
560+ // One reader per block, not per channel, is the whole of that rule.
561+ let mut m = Mantissas::new();
562+ let mut got_cplchan = false;
563+ for ch in 0..self.nfchans {
564+ let end = self.endmant[ch];
565+ if self.aht[ch] {
566+ self.aht_channel(r, ch, (0, end), blk)?;
567+ } else {
568+ for bin in 0..end {
569+ let bap = self.bap[ch][bin];
570+ let value = m.read(r, bap)?;
571+ self.coeffs[ch][bin] = if bap == 0 && self.dithflag[ch] && self.dither_on {
572+ self.dither.value() * scale(self.exps[ch][bin])
573+ } else {
574+ value * scale(self.exps[ch][bin])
575+ };
576+ }
577+ }
578+ self.coeffs[ch][end..].fill(0.0);
579+ if self.cplinu && self.chincpl[ch] && !got_cplchan {
580+ let (start, end) = (self.strtmant[CPL], self.endmant[CPL]);
581+ if self.aht[CPL] {
582+ self.aht_channel(r, CPL, (start, end), blk)?;
583+ } else {
584+ for bin in start..end {
585+ let value = m.read(r, self.bap[CPL][bin])?;
586+ self.coeffs[CPL][bin] = value * scale(self.exps[CPL][bin]);
587+ }
588+ }
589+ got_cplchan = true;
590+ }
591+ }
592+ if self.lfeon {
593+ if self.aht[LFE] {
594+ self.aht_channel(r, LFE, (0, 7), blk)?;
595+ } else {
596+ for bin in 0..7 {
597+ let value = m.read(r, self.bap[LFE][bin])?;
598+ self.coeffs[LFE][bin] = value * scale(self.exps[LFE][bin]);
599+ }
600+ }
601+ self.coeffs[LFE][7..].fill(0.0);
602+ }
603+ Ok(())
604+ }
605+
606+ /// One AHT channel: read the whole frame's mantissas on the first block
607+ /// that asks for them, then hand this block its share (§E3.4).
608+ fn aht_channel(
609+ &mut self,
610+ r: &mut BitReader<'_>,
611+ ch: usize,
612+ range: (usize, usize),
613+ blk: usize,
614+ ) -> Result<()> {
615+ let base = ch * crate::aht::AHT_BLOCKS * COEFFS;
616+ if !self.aht_read[ch] {
617+ let frame = &mut self.aht_mant[base..base + crate::aht::AHT_BLOCKS * COEFFS];
618+ crate::aht::read_channel(
619+ r,
620+ &self.bap[ch],
621+ range,
622+ &mut self.dither,
623+ self.dither_on,
624+ frame,
625+ )?;
626+ self.aht_read[ch] = true;
627+ }
628+ let offset = base + blk * COEFFS;
629+ for bin in range.0..range.1 {
630+ self.coeffs[ch][bin] = self.aht_mant[offset + bin] * scale(self.exps[ch][bin]);
631+ }
632+ Ok(())
633+ }
634+
635+ // ------------------------------------------------------------ decoding --
636+
637+ /// §7.4.3: rebuild each coupled channel's high bins from the coupling
638+ /// channel, scaled by that channel's coupling coordinates.
639+ pub(crate) fn decouple(&mut self) {
640+ if !self.cplinu {
641+ return;
642+ }
643+ let (start, end) = (self.strtmant[CPL], self.endmant[CPL]);
644+ for ch in 0..self.nfchans {
645+ if !self.chincpl[ch] {
646+ continue;
647+ }
648+ for sbnd in 0..self.ncplsubnd {
649+ let bnd = self.cplband[sbnd];
650+ let mut co = self.cplco[ch][bnd] * 8.0;
651+ // §5.4.3.18: in 2/0 with phase flags, the right channel's
652+ // contribution is inverted for the flagged bands.
653+ if ch == 1 && self.phsflginu && self.phsflg[bnd] {
654+ co = -co;
655+ }
656+ let from = start + sbnd * 12;
657+ for bin in from..(from + 12).min(end) {
658+ let cpl = if self.bap[CPL][bin] == 0 && self.dithflag[ch] && self.dither_on {
659+ self.dither.value() * scale(self.exps[CPL][bin])
660+ } else {
661+ self.coeffs[CPL][bin]
662+ };
663+ self.coeffs[ch][bin] = cpl * co;
664+ }
665+ }
666+ self.coeffs[ch][end..].fill(0.0);
667+ }
668+ }
669+
670+ /// §7.5.4: undo the sum/difference coding of the 2/0 mode.
671+ pub(crate) fn rematrix(&mut self) {
672+ if self.acmod != Acmod::Stereo || self.nrematbnd == 0 {
673+ return;
674+ }
675+ const BANDS: [usize; 4] = [13, 25, 37, 61];
676+ let limit = if self.cplinu {
677+ self.strtmant[CPL]
678+ } else {
679+ self.endmant[0].min(self.endmant[1])
680+ };
681+ for bnd in 0..self.nrematbnd {
682+ if !self.rematflg[bnd] {
683+ continue;
684+ }
685+ let start = BANDS[bnd];
686+ let end = if bnd + 1 < BANDS.len() {
687+ BANDS[bnd + 1].min(limit)
688+ } else {
689+ limit
690+ };
691+ for bin in start..end {
692+ let (l, r) = (self.coeffs[0][bin], self.coeffs[1][bin]);
693+ self.coeffs[0][bin] = l + r;
694+ self.coeffs[1][bin] = l - r;
695+ }
696+ }
697+ }
698+
699+ /// §7.7.1: the dynamic range gain the encoder asked for.
700+ pub(crate) fn apply_gain(&mut self) {
701+ let mut channels: Vec<usize> = (0..self.nfchans).collect();
702+ if self.lfeon {
703+ channels.push(LFE);
704+ }
705+ for ch in channels {
706+ // In 1+1 mode the two coded channels are separate programs with
707+ // separate gain words; everywhere else one word covers the frame.
708+ let program = usize::from(self.acmod == Acmod::DualMono && ch == 1);
709+ let gain = self.dynrng[program];
710+ if gain != 1.0 {
711+ for v in &mut self.coeffs[ch] {
712+ *v *= gain;
713+ }
714+ }
715+ }
716+ }
717+
718+ /// Inverse transform every channel and interleave the result.
719+ pub(crate) fn transform(&mut self, out: &mut Vec<f32>) {
720+ let channels = self.channels();
721+ let base = out.len();
722+ out.resize(base + channels * BLOCK_SAMPLES, 0.0);
723+ let mut pcm = [0.0f32; BLOCK_SAMPLES];
724+ for (slot, ch) in self.channel_order().into_iter().enumerate() {
725+ let short = ch < MAX_FBW && self.blksw[ch];
726+ let store = if ch == LFE { MAX_FBW } else { ch };
727+ self.imdct
728+ .block(&self.coeffs[ch], short, &mut self.delay[store], &mut pcm);
729+ for (n, &v) in pcm.iter().enumerate() {
730+ out[base + n * channels + slot] = v;
731+ }
732+ }
733+ }
734+
735+ /// The order this frame's channels are handed out in: the family's own
736+ /// L, R, C, LFE, Ls, Rs convention, as indices into the coded channels.
737+ pub(crate) fn channel_order(&self) -> Vec<usize> {
738+ let mut order: Vec<usize> = match self.acmod {
739+ // 1+1 and 2/0 are already in order, as is any mode without a
740+ // centre channel; the coded order only differs where C sits.
741+ Acmod::Surround3_0 | Acmod::Surround3_1 | Acmod::Surround3_2 => {
742+ let mut v = vec![0, 2, 1];
743+ v.extend(3..self.nfchans);
744+ v
745+ }
746+ _ => (0..self.nfchans).collect(),
747+ };
748+ if self.lfeon {
749+ // The LFE follows the front channels, which is where every layout
750+ // in the family (and in WAVE) puts it.
751+ let fronts = match self.acmod {
752+ Acmod::Surround3_0 | Acmod::Surround3_1 | Acmod::Surround3_2 => 3,
753+ Acmod::Mono => 1,
754+ _ => 2,
755+ };
756+ order.insert(fronts.min(order.len()), LFE);
757+ }
758+ order
759+ }
760+}
761+
762+/// §7.7.1.2: the 8-bit `dynrng` word as a linear gain.
763+///
764+/// The three most significant bits are a signed power of two from -4 to 3 with
765+/// an implicit +1, and the five least significant bits a fraction in `[1/2, 1)`.
766+/// The all-zero word is unity, which is what a block with no `dynrng` means.
767+fn dynrng_gain(dynrng: u8) -> f32 {
768+ let exponent = ((dynrng as i8) >> 5) as i32 + 1;
769+ let mantissa = f32::from(32 + (dynrng & 0x1f)) / 64.0;
770+ mantissa * (exponent as f32).exp2()
771+}
772+
773+#[cfg(test)]
774+mod tests {
775+ use super::*;
776+
777+ #[test]
778+ fn dynrng_zero_is_unity_and_the_ends_are_plus_minus_24_db() {
779+ assert!((dynrng_gain(0x00) - 1.0).abs() < 1e-6);
780+ // X = 3 (+24.08 dB), Y = 11111 (63/64) => 2^4 * 63/64 = 15.75.
781+ assert!((dynrng_gain(0b011_11111) - 15.75).abs() < 1e-4);
782+ // X = -4 (-18.06 dB), Y = 00000 (1/2) => 2^-3 * 1/2 = 0.0625.
783+ assert!((dynrng_gain(0b100_00000) - 0.0625).abs() < 1e-6);
784+ // X = -1 is the table's "0 dB", but Y always contributes between
785+ // -0.14 and -6.02 dB: 2^0 * 1/2.
786+ assert!((dynrng_gain(0b111_00000) - 0.5).abs() < 1e-6);
787+ }
788+
789+ #[test]
790+ fn channel_order_puts_centre_second_and_lfe_after_the_fronts() {
791+ let mut core = Core::new();
792+ core.acmod = Acmod::Surround3_2;
793+ core.nfchans = 5;
794+ core.lfeon = true;
795+ assert_eq!(core.channel_order(), vec![0, 2, 1, LFE, 3, 4]);
796+ core.lfeon = false;
797+ assert_eq!(core.channel_order(), vec![0, 2, 1, 3, 4]);
798+ core.acmod = Acmod::Stereo;
799+ core.nfchans = 2;
800+ assert_eq!(core.channel_order(), vec![0, 1]);
801+ core.acmod = Acmod::Mono;
802+ core.nfchans = 1;
803+ core.lfeon = true;
804+ assert_eq!(core.channel_order(), vec![0, LFE]);
805+ }
806+}
crates/ec-ac3/src/decoder.rsadded+386 -0
@@ -0,0 +1,386 @@
1+//! The public decoder: syncframes in, interleaved `f32` audio frames out.
2+
3+use ec_core::{
4+ AudioFrame, AudioParameters, Buf, ChannelLayout, ChannelPosition, CodecId, CodecParameters,
5+ Decoder, Error, Frame, MediaParameters, Packet, Result, SampleFormat, Timestamp,
6+};
7+
8+use crate::bsi::{self, Acmod, Bsi};
9+use crate::decode::{Core, Syntax};
10+use crate::eac3;
11+use crate::syncinfo;
12+use crate::transform::BLOCK_SAMPLES;
13+
14+/// Blocks per AC-3 syncframe (A/52 §5.3.3); E-AC-3 states its own count.
15+const 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)]
19+pub 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)]
31+pub 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+
51+impl 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)]
64+pub 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.
95+pub 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+
105+impl Default for Ac3Decoder {
106+ fn default() -> Ac3Decoder {
107+ Ac3Decoder::new()
108+ }
109+}
110+
111+impl 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+
353+impl 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+}
crates/ec-ac3/src/lib.rsadded+96 -0
@@ -0,0 +1,96 @@
1+//! AC-3 and Enhanced AC-3 decoding, from the ATSC A/52 standard.
2+//!
3+//! Two entry points, depending on how much of the format the caller needs:
4+//!
5+//! - [`Ac3Decoder`] takes syncframes and hands back interleaved `f32` audio
6+//! frames, with the coded channel layout or a §7.8 downmix.
7+//! - [`syncinfo::parse`], [`bsi::parse`] and [`eac3::bsi::parse`] read the
8+//! headers alone, which is what a container needs to state a track's sample
9+//! rate and channel count before decoding anything.
10+//!
11+//! Contracts worth knowing before implementing against this crate:
12+//!
13+//! - **Decode only.** Nothing here encodes AC-3; the format is a decode-side
14+//! concern for this family.
15+//! - **Truncated input is [`Error::NeedMore`]**, a broken bit stream is
16+//! [`Error::Corrupt`], and a construct this build does not implement is
17+//! [`Error::Unsupported`] naming *what* and *why*. No input panics — the bit
18+//! reader bounds every read and the exponent and bandwidth fields are range
19+//! checked before they index anything.
20+//! - **Dynamic range compression is applied by default**, because §7.7.1 says a
21+//! decoder shall: `dynrng` is the program provider's compression curve and
22+//! leaving it out makes explosions 20 dB louder than the mix intended. The
23+//! raw words stay visible on [`FrameInfo`], and [`Options::drc_scale`] turns
24+//! it down or off.
25+//! - **Dialogue normalisation is surfaced, never applied.** §7.6 puts
26+//! `dialnorm` in the volume control, which is not in this crate.
27+//! - **Dither is on by default** (§7.3.4) but its sequence is
28+//! implementation-defined, so two conformant decoders differ by exactly that
29+//! noise; [`Options::dither`] turns it off when a comparison needs to
30+//! isolate everything else.
31+//!
32+//! Annex E coverage: the adaptive hybrid transform (with its vector and
33+//! gain-adaptive quantizers) and spectral extension are decoded; enhanced
34+//! coupling and dependent substreams above 5.1 are refused by name rather than
35+//! decoded wrongly. On a real Dolby Digital Plus stream that uses AHT and
36+//! spectral extension the output tracks ffmpeg's to a per-channel correlation
37+//! of 0.994 rather than the 0.9999 the rest of the format reaches — the
38+//! remaining difference is in the AHT quantizer detail and the two decoders'
39+//! independent noise sources.
40+//!
41+//! No unsafe, no allocation on the block path beyond the output buffer, and no
42+//! dependencies beyond the family IR and DSP crates.
43+
44+#![forbid(unsafe_code)]
45+#![warn(missing_docs)]
46+// A bit stream parser indexes several per-channel and per-band arrays from one
47+// loop variable, which is the domain's own notion of position; iterator
48+// rewrites of those loops obscure which array is which.
49+#![allow(clippy::needless_range_loop)]
50+
51+mod aht;
52+mod aht_tables;
53+
54+pub mod bitalloc;
55+pub mod bsi;
56+pub mod eac3;
57+pub mod exps;
58+pub mod mantissa;
59+pub mod syncinfo;
60+pub mod tables;
61+pub mod transform;
62+
63+mod decode;
64+mod decoder;
65+
66+pub use decode::Syntax;
67+pub use decoder::{Ac3Decoder, Downmix, FrameInfo, Options};
68+pub use ec_core::Error;
69+
70+/// Samples per channel one audio block produces.
71+pub use transform::BLOCK_SAMPLES;
72+
73+/// Blocks in an AC-3 syncframe; Enhanced AC-3 may send 1, 2, 3 or 6.
74+pub const AC3_BLOCKS_PER_FRAME: usize = 6;
75+
76+/// Length in bytes of the syncframe starting at `data[0]`, for either syntax.
77+///
78+/// This is what walking an elementary stream needs — the frame length lives in
79+/// `frmsizecod` for AC-3 and `frmsiz` for E-AC-3, in different places and
80+/// different units. A short buffer is [`Error::NeedMore`]; anything that is not
81+/// a syncframe is [`Error::Corrupt`].
82+pub fn frame_size(data: &[u8]) -> ec_core::Result<usize> {
83+ if data.len() < 6 {
84+ return Err(Error::NeedMore);
85+ }
86+ if data[0] != 0x0B || data[1] != 0x77 {
87+ return Err(Error::corrupt(
88+ "AC-3: no syncword at the start of the frame",
89+ ));
90+ }
91+ if data[5] >> 3 <= 10 {
92+ Ok(syncinfo::parse(data)?.frame_size)
93+ } else {
94+ Ok(eac3::parse(&data[2..])?.frame_size)
95+ }
96+}