forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB8a26b91Tahinli3 months ago348 commits

decode.rs806 lines, 29.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 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
128impl 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.
767fn 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)]
774mod 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}