forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBe12d32fTahinli6 days ago3982 commits

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