forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust382.4 MiBe18142dTahinli10 hours ago4543 commits

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