forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

core.rs1393 lines, 50.4 KiBHistoryRawDownload
1//! The core decoder: primary audio coding header and subframes (ETSI TS 102
2//! 114 section 5), subband ADPCM, high frequency VQ, joint intensity, LFE,
3//! the XCH extension and the 32-band synthesis bank.
4//!
5//! The arithmetic is the integer formulation (24-bit subband samples,
6//! Q23 filter coefficients, 64-bit accumulators) so a decode is exact and
7//! reproducible: the same bits always give the same 24-bit samples.
8
9use crate::bits::Bits;
10use crate::dct::{imdct_half_32, imdct_half_64};
11use crate::header::{FrameHeader, BIT_RATES, CHANNELS};
12use crate::huff::{books, Books};
13use crate::math::{clip23, mul, mul23, norm};
14use crate::tables_data::*;
15use ec_core::{Error, Result};
16
17pub(crate) const CH: usize = 7;
18const SUBBANDS: usize = 32;
19const ADPCM: usize = 4;
20const STRIDE: usize = ADPCM + 128;
21const LFE_HISTORY: usize = 8;
22const ABITS_MAX: i32 = 26;
23const SSF_SAMPLES: usize = 8;
24
25/// Speaker slots, in the order of the standard's speaker mask.
26pub(crate) const SPK_C: usize = 0;
27pub(crate) const SPK_L: usize = 1;
28pub(crate) const SPK_R: usize = 2;
29pub(crate) const SPK_LS: usize = 3;
30pub(crate) const SPK_RS: usize = 4;
31pub(crate) const SPK_LFE: usize = 5;
32pub(crate) const SPK_CS: usize = 6;
33
34const MASK_C: u32 = 1 << SPK_C;
35const MASK_L: u32 = 1 << SPK_L;
36const MASK_R: u32 = 1 << SPK_R;
37const MASK_LS: u32 = 1 << SPK_LS;
38const MASK_RS: u32 = 1 << SPK_RS;
39pub(crate) const MASK_LFE: u32 = 1 << SPK_LFE;
40pub(crate) const MASK_CS: u32 = 1 << SPK_CS;
41
42/// Primary channel to speaker, by `AMODE`.
43const PRM_CH_TO_SPKR: [[i8; 5]; 10] = [
44 [0, -1, -1, -1, -1],
45 [1, 2, -1, -1, -1],
46 [1, 2, -1, -1, -1],
47 [1, 2, -1, -1, -1],
48 [1, 2, -1, -1, -1],
49 [0, 1, 2, -1, -1],
50 [1, 2, 6, -1, -1],
51 [0, 1, 2, 6, -1],
52 [1, 2, 3, 4, -1],
53 [0, 1, 2, 3, 4],
54];
55
56const AMODE_MASK: [u32; 10] = [
57 MASK_C,
58 MASK_L | MASK_R,
59 MASK_L | MASK_R,
60 MASK_L | MASK_R,
61 MASK_L | MASK_R,
62 MASK_L | MASK_R | MASK_C,
63 MASK_L | MASK_R | MASK_CS,
64 MASK_L | MASK_R | MASK_C | MASK_CS,
65 MASK_L | MASK_R | MASK_LS | MASK_RS,
66 MASK_L | MASK_R | MASK_C | MASK_LS | MASK_RS,
67];
68
69const BLOCK_CODE_NBITS: [u32; 7] = [7, 10, 12, 13, 15, 17, 19];
70const QUANT_INDEX_SEL_NBITS: [u32; 10] = [1, 2, 2, 2, 2, 3, 3, 3, 3, 3];
71const QUANT_INDEX_GROUP_SIZE: [u8; 10] = [1, 3, 3, 3, 3, 7, 7, 7, 7, 7];
72
73#[derive(Clone, Copy, PartialEq, Eq)]
74enum Header {
75 Core,
76 Xch,
77}
78
79/// Synthesis filter history of one channel.
80struct Dsp {
81 hist1: Vec<i32>,
82 hist2: [i32; 64],
83 offset: usize,
84}
85
86impl Dsp {
87 fn new() -> Dsp {
88 Dsp {
89 hist1: vec![0; 1024],
90 hist2: [0; 64],
91 offset: 0,
92 }
93 }
94 fn clear(&mut self) {
95 self.hist1.iter_mut().for_each(|x| *x = 0);
96 self.hist2 = [0; 64];
97 self.offset = 0;
98 }
99}
100
101/// What the extension search and parse found, for the frame info.
102#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
103pub struct Extensions {
104 /// XCH (6.1 centre surround) was present and decoded.
105 pub xch: bool,
106 /// X96 (96 kHz) was present and decoded.
107 pub x96: bool,
108 /// An XXCH extension was signalled and ignored.
109 pub xxch_ignored: bool,
110}
111
112/// One decoded core frame: planar 24-bit samples per speaker slot.
113pub(crate) struct Decoded {
114 pub nsamples: usize,
115 pub sample_rate: u32,
116 pub ch_mask: u32,
117 pub out: Vec<Vec<i32>>,
118 pub ext: Extensions,
119}
120
121pub(crate) struct Core {
122 books: &'static Books,
123 // Bit stream header
124 crc_present: bool,
125 npcmblocks: usize,
126 frame_size: usize,
127 audio_mode: usize,
128 sample_rate: u32,
129 bit_rate: u32,
130 drc_present: bool,
131 ts_present: bool,
132 aux_present: bool,
133 ext_audio_type: u8,
134 ext_audio_present: bool,
135 sync_ssf: bool,
136 lfe_present: usize,
137 predictor_history: bool,
138 filter_perfect: bool,
139 es_format: bool,
140 sumdiff_front: bool,
141 sumdiff_surround: bool,
142 // Primary audio coding header
143 nsubframes: usize,
144 nchannels: usize,
145 ch_mask: u32,
146 nsubbands: [usize; CH],
147 subband_vq_start: [usize; CH],
148 joint_intensity_index: [usize; CH],
149 transition_mode_sel: [usize; CH],
150 scale_factor_sel: [usize; CH],
151 bit_allocation_sel: [usize; CH],
152 quant_index_sel: [[u8; 10]; CH],
153 scale_factor_adj: [[i32; 10]; CH],
154 // Side information
155 nsubsubframes: [usize; 16],
156 prediction_mode: [[bool; 64]; CH],
157 prediction_vq_index: [[u16; 64]; CH],
158 bit_allocation: [[i32; 64]; CH],
159 transition_mode: [[[u8; SUBBANDS]; CH]; 16],
160 scale_factors: [[[i32; 2]; SUBBANDS]; CH],
161 joint_scale_sel: [usize; CH],
162 joint_scale_factors: [[i32; 64]; CH],
163 // Sample buffers: [ch][band][ADPCM history + 128 samples]
164 sb: Vec<i32>,
165 lfe_samples: Vec<i32>,
166 // X96 extension
167 x96_sb: Vec<i32>,
168 x96_rand: u32,
169 x96_rev_no: u32,
170 x96_crc_present: bool,
171 x96_nchannels: usize,
172 x96_high_res: bool,
173 x96_subband_start: usize,
174 // Synthesis state
175 dsp: Vec<Dsp>,
176 filter_mode: u8,
177 lfe_x96_hist: i32,
178 ext: Extensions,
179}
180
181#[inline]
182fn sbi(ch: usize, band: usize) -> usize {
183 (ch * SUBBANDS + band) * STRIDE
184}
185
186#[inline]
187fn xbi(ch: usize, band: usize) -> usize {
188 (ch * 64 + band) * STRIDE
189}
190
191impl Core {
192 pub fn new() -> Core {
193 Core {
194 books: books(),
195 crc_present: false,
196 npcmblocks: 0,
197 frame_size: 0,
198 audio_mode: 0,
199 sample_rate: 0,
200 bit_rate: 0,
201 drc_present: false,
202 ts_present: false,
203 aux_present: false,
204 ext_audio_type: 0,
205 ext_audio_present: false,
206 sync_ssf: false,
207 lfe_present: 0,
208 predictor_history: false,
209 filter_perfect: false,
210 es_format: false,
211 sumdiff_front: false,
212 sumdiff_surround: false,
213 nsubframes: 0,
214 nchannels: 0,
215 ch_mask: 0,
216 nsubbands: [0; CH],
217 subband_vq_start: [0; CH],
218 joint_intensity_index: [0; CH],
219 transition_mode_sel: [0; CH],
220 scale_factor_sel: [0; CH],
221 bit_allocation_sel: [0; CH],
222 quant_index_sel: [[0; 10]; CH],
223 scale_factor_adj: [[0; 10]; CH],
224 nsubsubframes: [0; 16],
225 prediction_mode: [[false; 64]; CH],
226 prediction_vq_index: [[0; 64]; CH],
227 bit_allocation: [[0; 64]; CH],
228 transition_mode: [[[0; SUBBANDS]; CH]; 16],
229 scale_factors: [[[0; 2]; SUBBANDS]; CH],
230 joint_scale_sel: [0; CH],
231 joint_scale_factors: [[0; 64]; CH],
232 sb: vec![0; CH * SUBBANDS * STRIDE],
233 lfe_samples: vec![0; LFE_HISTORY + 64],
234 x96_sb: vec![0; CH * 64 * STRIDE],
235 x96_rand: 1,
236 x96_rev_no: 0,
237 x96_crc_present: false,
238 x96_nchannels: 0,
239 x96_high_res: false,
240 x96_subband_start: 0,
241 dsp: (0..CH).map(|_| Dsp::new()).collect(),
242 filter_mode: 0,
243 lfe_x96_hist: 0,
244 ext: Extensions::default(),
245 }
246 }
247
248 /// Drop every carried-over history (ADPCM, LFE, synthesis).
249 pub fn reset(&mut self) {
250 self.sb.iter_mut().for_each(|x| *x = 0);
251 self.x96_sb.iter_mut().for_each(|x| *x = 0);
252 self.lfe_samples.iter_mut().for_each(|x| *x = 0);
253 for d in &mut self.dsp {
254 d.clear();
255 }
256 }
257
258 fn erase_adpcm_history(&mut self) {
259 for ch in 0..CH {
260 for band in 0..SUBBANDS {
261 let b = sbi(ch, band);
262 self.sb[b..b + ADPCM].iter_mut().for_each(|x| *x = 0);
263 }
264 }
265 }
266
267 fn load_header(&mut self, h: &FrameHeader) {
268 self.crc_present = h.crc_present;
269 self.npcmblocks = h.npcmblocks as usize;
270 self.frame_size = h.frame_size;
271 self.audio_mode = h.amode as usize;
272 self.sample_rate = h.sample_rate;
273 self.bit_rate = BIT_RATES[h.bit_rate_code as usize];
274 self.drc_present = h.drc_present;
275 self.ts_present = h.ts_present;
276 self.aux_present = h.aux_present;
277 self.ext_audio_type = h.ext_audio_type;
278 self.ext_audio_present = h.ext_audio_present;
279 self.sync_ssf = h.sync_ssf;
280 self.lfe_present = h.lfe as usize;
281 self.predictor_history = h.predictor_history;
282 self.filter_perfect = h.filter_perfect;
283 self.es_format = h.es_format;
284 self.sumdiff_front = h.sumdiff_front;
285 self.sumdiff_surround = h.sumdiff_surround;
286 }
287
288 /// Decode one canonical frame. `canon` starts at the sync word and holds
289 /// at least the header; `hdr` is its parsed header.
290 pub fn decode(&mut self, canon: &[u8], hdr: &FrameHeader, exss_x96: Option<&[u8]>) -> Result<Decoded> {
291 self.load_header(hdr);
292 self.ext = Extensions::default();
293 let mut r = Bits::new(canon);
294 // Skip the header, which the caller parsed: re-read to find its end.
295 skip_frame_header(&mut r, hdr);
296 if !self.predictor_history {
297 self.erase_adpcm_history();
298 }
299 self.parse_frame_data(&mut r, Header::Core, 0)?;
300
301 // Optional information: time stamp, auxiliary data, extension search.
302 if self.ts_present {
303 r.skip(32);
304 }
305 let last_pos = r.pos() / 32;
306 let mut xch_pos = 0usize;
307 let mut x96_pos = 0usize;
308 if self.ext_audio_present {
309 let fs = self.frame_size.min(canon.len());
310 let mut sync_pos = (fs / 4).min(canon.len() / 4) as isize - 1;
311 let rd = |i: isize| -> u32 {
312 let o = i as usize * 4;
313 canon
314 .get(o..o + 4)
315 .map_or(0, |b| u32::from_be_bytes([b[0], b[1], b[2], b[3]]))
316 };
317 let mut w2 = 0u32;
318 match self.ext_audio_type {
319 0 => {
320 while sync_pos >= last_pos as isize {
321 let w1 = rd(sync_pos);
322 if w1 == 0x5A5A_5A5A {
323 let size = (w2 >> 22) as usize + 1;
324 let dist = self.frame_size as isize - sync_pos * 4;
325 if size >= 96
326 && (size as isize == dist || size as isize - 1 == dist)
327 && (w2 >> 15 & 0x7f) == 0x08
328 {
329 xch_pos = sync_pos as usize * 32 + 49;
330 break;
331 }
332 }
333 sync_pos -= 1;
334 w2 = w1;
335 }
336 }
337 2 => {
338 while sync_pos >= last_pos as isize {
339 let w1 = rd(sync_pos);
340 if w1 == 0x1D95_F262 {
341 let size = (w2 >> 20) as usize + 1;
342 let dist = self.frame_size as isize - sync_pos * 4;
343 if size >= 96 && size as isize == dist {
344 x96_pos = sync_pos as usize * 32 + 44;
345 break;
346 }
347 }
348 sync_pos -= 1;
349 w2 = w1;
350 }
351 }
352 6 => self.ext.xxch_ignored = true,
353 _ => {}
354 }
355 }
356
357 if xch_pos != 0 {
358 let mut rx = Bits::new(canon);
359 if rx.seek(xch_pos) && self.parse_xch_frame(&mut rx).is_ok() {
360 self.ext.xch = true;
361 } else {
362 self.nchannels = CHANNELS[self.audio_mode] as usize;
363 self.ch_mask = AMODE_MASK[self.audio_mode];
364 if self.lfe_present != 0 {
365 self.ch_mask |= MASK_LFE;
366 }
367 }
368 }
369 if let Some(x) = exss_x96 {
370 if self.parse_x96_frame_exss(x).is_ok() {
371 self.ext.x96 = true;
372 }
373 } else if x96_pos != 0 {
374 let mut rx = Bits::new(canon);
375 if rx.seek(x96_pos) && self.parse_x96_frame(&mut rx).is_ok() {
376 self.ext.x96 = true;
377 }
378 }
379 self.filter()
380 }
381
382 // 5.3.2 - Primary audio coding header
383 fn parse_coding_header(&mut self, r: &mut Bits<'_>, header: Header, xch_base: usize) -> Result<()> {
384 if r.left() < 0 {
385 return Err(Error::corrupt("DTS: truncated frame"));
386 }
387 match header {
388 Header::Core => {
389 self.nsubframes = r.get(4) as usize + 1;
390 self.nchannels = r.get(3) as usize + 1;
391 if self.nchannels != CHANNELS[self.audio_mode] as usize {
392 return Err(Error::corrupt(
393 "DTS: primary channel count disagrees with AMODE",
394 ));
395 }
396 self.ch_mask = AMODE_MASK[self.audio_mode];
397 if self.lfe_present != 0 {
398 self.ch_mask |= MASK_LFE;
399 }
400 }
401 Header::Xch => {
402 self.nchannels = CHANNELS[self.audio_mode] as usize + 1;
403 self.ch_mask |= MASK_CS;
404 }
405 }
406 let n = self.nchannels;
407 for ch in xch_base..n {
408 let v = r.get(5) as usize + 2;
409 if v > SUBBANDS {
410 return Err(Error::corrupt("DTS: invalid subband activity count"));
411 }
412 self.nsubbands[ch] = v;
413 }
414 for ch in xch_base..n {
415 self.subband_vq_start[ch] = r.get(5) as usize + 1;
416 }
417 for ch in xch_base..n {
418 let v = r.get(3) as usize;
419 if v > n {
420 return Err(Error::corrupt("DTS: invalid joint intensity coding index"));
421 }
422 self.joint_intensity_index[ch] = v;
423 }
424 for ch in xch_base..n {
425 self.transition_mode_sel[ch] = r.get(2) as usize;
426 }
427 for ch in xch_base..n {
428 let v = r.get(3) as usize;
429 if v == 7 {
430 return Err(Error::corrupt("DTS: invalid scale factor code book"));
431 }
432 self.scale_factor_sel[ch] = v;
433 }
434 for ch in xch_base..n {
435 let v = r.get(3) as usize;
436 if v == 7 {
437 return Err(Error::corrupt("DTS: invalid bit allocation quantizer select"));
438 }
439 self.bit_allocation_sel[ch] = v;
440 }
441 for k in 0..10 {
442 for ch in xch_base..n {
443 self.quant_index_sel[ch][k] = r.get(QUANT_INDEX_SEL_NBITS[k]) as u8;
444 }
445 }
446 for k in 0..10 {
447 for ch in xch_base..n {
448 if self.quant_index_sel[ch][k] < QUANT_INDEX_GROUP_SIZE[k] {
449 self.scale_factor_adj[ch][k] = SCALE_FACTOR_ADJ[r.get(2) as usize] as i32;
450 }
451 }
452 }
453 if self.crc_present {
454 r.skip(16);
455 }
456 Ok(())
457 }
458
459 fn parse_scale(&self, r: &mut Bits<'_>, scale_index: &mut i32, sel: usize) -> Result<i32> {
460 let (table, size): (&[u32], usize) = if sel > 5 {
461 (&SCALE_FACTOR_QUANT7, 128)
462 } else {
463 (&SCALE_FACTOR_QUANT6, 64)
464 };
465 if sel < 5 {
466 *scale_index += self.books.scale_factor[sel].read(r);
467 } else {
468 *scale_index = r.get(sel as u32 + 1) as i32;
469 }
470 if (*scale_index as u32) as usize >= size {
471 return Err(Error::corrupt("DTS: invalid scale factor index"));
472 }
473 Ok(table[*scale_index as usize] as i32)
474 }
475
476 fn parse_joint_scale(&self, r: &mut Bits<'_>, sel: usize) -> Result<i32> {
477 let mut idx = if sel < 5 {
478 self.books.scale_factor[sel].read(r)
479 } else {
480 r.get(sel as u32 + 1) as i32
481 };
482 idx += 64;
483 if idx < 0 || idx as usize >= JOINT_SCALE_FACTORS.len() {
484 return Err(Error::corrupt("DTS: invalid joint scale factor index"));
485 }
486 Ok(JOINT_SCALE_FACTORS[idx as usize] as i32)
487 }
488
489 // 5.4.1 - Primary audio coding side information
490 fn parse_subframe_header(&mut self, r: &mut Bits<'_>, sf: usize, header: Header, xch_base: usize) -> Result<()> {
491 if r.left() < 0 {
492 return Err(Error::corrupt("DTS: truncated frame"));
493 }
494 if header == Header::Core {
495 self.nsubsubframes[sf] = r.get(2) as usize + 1;
496 r.skip(3);
497 }
498 let n = self.nchannels;
499 for ch in xch_base..n {
500 for band in 0..self.nsubbands[ch] {
501 self.prediction_mode[ch][band] = r.get1() != 0;
502 }
503 }
504 for ch in xch_base..n {
505 for band in 0..self.nsubbands[ch] {
506 if self.prediction_mode[ch][band] {
507 self.prediction_vq_index[ch][band] = r.get(12) as u16;
508 }
509 }
510 }
511 for ch in xch_base..n {
512 let sel = self.bit_allocation_sel[ch];
513 for band in 0..self.subband_vq_start[ch] {
514 let abits = if sel < 5 {
515 self.books.bit_allocation[sel].read(r)
516 } else {
517 r.get(sel as u32 - 1) as i32
518 };
519 if abits > ABITS_MAX {
520 return Err(Error::corrupt("DTS: invalid bit allocation index"));
521 }
522 self.bit_allocation[ch][band] = abits;
523 }
524 }
525 for ch in xch_base..n {
526 self.transition_mode[sf][ch] = [0; SUBBANDS];
527 if self.nsubsubframes[sf] > 1 {
528 let sel = self.transition_mode_sel[ch];
529 for band in 0..self.subband_vq_start[ch] {
530 if self.bit_allocation[ch][band] != 0 {
531 self.transition_mode[sf][ch][band] =
532 self.books.transition_mode[sel].read(r) as u8;
533 }
534 }
535 }
536 }
537 for ch in xch_base..n {
538 let sel = self.scale_factor_sel[ch];
539 let mut scale_index = 0i32;
540 for band in 0..self.subband_vq_start[ch] {
541 if self.bit_allocation[ch][band] != 0 {
542 self.scale_factors[ch][band][0] = self.parse_scale(r, &mut scale_index, sel)?;
543 if self.transition_mode[sf][ch][band] != 0 {
544 self.scale_factors[ch][band][1] = self.parse_scale(r, &mut scale_index, sel)?;
545 }
546 } else {
547 self.scale_factors[ch][band][0] = 0;
548 }
549 }
550 for band in self.subband_vq_start[ch]..self.nsubbands[ch] {
551 self.scale_factors[ch][band][0] = self.parse_scale(r, &mut scale_index, sel)?;
552 }
553 }
554 for ch in xch_base..n {
555 if self.joint_intensity_index[ch] != 0 {
556 let v = r.get(3) as usize;
557 if v == 7 {
558 return Err(Error::corrupt("DTS: invalid joint scale factor code book"));
559 }
560 self.joint_scale_sel[ch] = v;
561 }
562 }
563 for ch in xch_base..n {
564 if self.joint_intensity_index[ch] != 0 {
565 let src_ch = self.joint_intensity_index[ch] - 1;
566 let sel = self.joint_scale_sel[ch];
567 for band in self.nsubbands[ch]..self.nsubbands[src_ch] {
568 self.joint_scale_factors[ch][band] = self.parse_joint_scale(r, sel)?;
569 }
570 }
571 }
572 if self.drc_present && header == Header::Core {
573 r.skip(8);
574 }
575 if self.crc_present {
576 r.skip(16);
577 }
578 Ok(())
579 }
580
581 fn extract_audio(&self, r: &mut Bits<'_>, audio: &mut [i32; 16], abits: usize, ch: usize) -> Result<bool> {
582 if abits == 0 {
583 audio[..SSF_SAMPLES].iter_mut().for_each(|x| *x = 0);
584 return Ok(false);
585 }
586 if abits <= 10 {
587 let sel = self.quant_index_sel[ch][abits - 1];
588 if sel < QUANT_INDEX_GROUP_SIZE[abits - 1] {
589 let book = &self.books.quant_index[abits - 1][sel as usize];
590 for a in audio[..SSF_SAMPLES].iter_mut() {
591 *a = book.read(r);
592 }
593 return Ok(true);
594 }
595 if abits <= 7 {
596 let nb = BLOCK_CODE_NBITS[abits - 1];
597 let mut code1 = r.get(nb) as i64;
598 let mut code2 = r.get(nb) as i64;
599 let levels = QUANT_LEVELS[abits] as i64;
600 let offset = (levels - 1) / 2;
601 for n in 0..SSF_SAMPLES / 2 {
602 let div = code1 / levels;
603 audio[n] = (code1 - div * levels - offset) as i32;
604 code1 = div;
605 }
606 for n in SSF_SAMPLES / 2..SSF_SAMPLES {
607 let div = code2 / levels;
608 audio[n] = (code2 - div * levels - offset) as i32;
609 code2 = div;
610 }
611 if code1 | code2 != 0 {
612 return Err(Error::corrupt("DTS: failed to decode block code"));
613 }
614 return Ok(false);
615 }
616 }
617 for a in audio[..SSF_SAMPLES].iter_mut() {
618 *a = r.get_signed(abits as u32 - 3);
619 }
620 Ok(false)
621 }
622
623 // 5.5 - Primary audio data arrays
624 fn parse_subframe_audio(
625 &mut self,
626 r: &mut Bits<'_>,
627 sf: usize,
628 header: Header,
629 xch_base: usize,
630 sub_pos: &mut usize,
631 lfe_pos: &mut usize,
632 ) -> Result<()> {
633 let nsamples = self.nsubsubframes[sf] * SSF_SAMPLES;
634 if *sub_pos + nsamples > self.npcmblocks {
635 return Err(Error::corrupt("DTS: subband sample buffer overflow"));
636 }
637 if r.left() < 0 {
638 return Err(Error::corrupt("DTS: truncated frame"));
639 }
640 let n = self.nchannels;
641 let mut audio = [0i32; 16];
642
643 // VQ encoded subbands
644 for ch in xch_base..n {
645 let mut vq_index = [0usize; SUBBANDS];
646 for band in self.subband_vq_start[ch]..self.nsubbands[ch] {
647 vq_index[band] = r.get(10) as usize;
648 }
649 for band in self.subband_vq_start[ch]..self.nsubbands[ch] {
650 let coeff = &HIGH_FREQ_VQ[vq_index[band] * 32..vq_index[band] * 32 + 32];
651 let scale = self.scale_factors[ch][band][0];
652 let base = sbi(ch, band) + ADPCM + *sub_pos;
653 for j in 0..nsamples {
654 self.sb[base + j] =
655 clip23(((coeff[j] as i32).wrapping_mul(scale).wrapping_add(1 << 3)) >> 4);
656 }
657 }
658 }
659
660 // Low frequency effect data
661 if self.lfe_present != 0 && header == Header::Core {
662 let nlfe = 2 * self.lfe_present * self.nsubsubframes[sf];
663 for a in audio[..nlfe].iter_mut() {
664 *a = r.get_signed(8);
665 }
666 let index = r.get(8) as usize;
667 if index >= SCALE_FACTOR_QUANT7.len() {
668 return Err(Error::corrupt("DTS: invalid LFE scale factor index"));
669 }
670 let scale = SCALE_FACTOR_QUANT7[index] as i32;
671 let scale = mul23(4697620, scale);
672 for k in 0..nlfe {
673 let ofs = *lfe_pos + k;
674 if ofs >= self.lfe_samples.len() {
675 return Err(Error::corrupt("DTS: LFE sample overflow"));
676 }
677 self.lfe_samples[ofs] = clip23(audio[k].wrapping_mul(scale) >> 4);
678 }
679 *lfe_pos += nlfe;
680 }
681
682 // Audio data
683 let mut ofs = *sub_pos;
684 for ssf in 0..self.nsubsubframes[sf] {
685 for ch in xch_base..n {
686 if r.left() < 0 {
687 return Err(Error::corrupt("DTS: truncated frame"));
688 }
689 for band in 0..self.subband_vq_start[ch] {
690 let abits = self.bit_allocation[ch][band] as usize;
691 let huff = self.extract_audio(r, &mut audio, abits, ch)?;
692 let step_size = if self.bit_rate == 3 {
693 LOSSLESS_QUANT[abits]
694 } else {
695 LOSSY_QUANT[abits]
696 } as i32;
697 let trans_ssf = self.transition_mode[sf][ch][band] as usize;
698 let mut scale = if trans_ssf == 0 || ssf < trans_ssf {
699 self.scale_factors[ch][band][0]
700 } else {
701 self.scale_factors[ch][band][1]
702 };
703 if huff {
704 let adj = self.scale_factor_adj[ch][abits - 1] as i64;
705 scale = clip23(((adj * scale as i64) >> 22) as i32);
706 }
707 let base = sbi(ch, band) + ADPCM + ofs;
708 dequantize(&mut self.sb[base..base + SSF_SAMPLES], &audio[..SSF_SAMPLES], step_size, scale, false);
709 }
710 }
711 // DSYNC
712 if (ssf == self.nsubsubframes[sf] - 1 || self.sync_ssf) && r.get(16) != 0xffff {
713 return Err(Error::corrupt("DTS: DSYNC check failed"));
714 }
715 ofs += SSF_SAMPLES;
716 }
717
718 // Inverse ADPCM
719 for ch in xch_base..n {
720 for band in 0..self.nsubbands[ch] {
721 if self.prediction_mode[ch][band] {
722 let id = self.prediction_vq_index[ch][band] as usize;
723 let base = sbi(ch, band) + ADPCM + *sub_pos;
724 for j in 0..nsamples {
725 let x = predict(id, &self.sb[base + j - ADPCM..base + j]);
726 self.sb[base + j] = clip23(self.sb[base + j].wrapping_add(x));
727 }
728 }
729 }
730 }
731
732 // Joint subband coding
733 for ch in xch_base..n {
734 if self.joint_intensity_index[ch] != 0 {
735 let src_ch = self.joint_intensity_index[ch] - 1;
736 for band in self.nsubbands[ch]..self.nsubbands[src_ch] {
737 let scale = self.joint_scale_factors[ch][band];
738 let sbase = sbi(src_ch, band) + ADPCM + *sub_pos;
739 let dbase = sbi(ch, band) + ADPCM + *sub_pos;
740 for j in 0..nsamples {
741 self.sb[dbase + j] = clip23(mul(self.sb[sbase + j], scale, 17));
742 }
743 }
744 }
745 }
746
747 *sub_pos = ofs;
748 Ok(())
749 }
750
751 fn parse_frame_data(&mut self, r: &mut Bits<'_>, header: Header, xch_base: usize) -> Result<()> {
752 self.parse_coding_header(r, header, xch_base)?;
753 let mut sub_pos = 0usize;
754 let mut lfe_pos = LFE_HISTORY;
755 for sf in 0..self.nsubframes {
756 self.parse_subframe_header(r, sf, header, xch_base)?;
757 self.parse_subframe_audio(r, sf, header, xch_base, &mut sub_pos, &mut lfe_pos)?;
758 }
759 if r.over {
760 return Err(Error::corrupt("DTS: truncated frame"));
761 }
762 for ch in xch_base..self.nchannels {
763 let mut nsubbands = self.nsubbands[ch];
764 if self.joint_intensity_index[ch] != 0 {
765 nsubbands = nsubbands.max(self.nsubbands[self.joint_intensity_index[ch] - 1]);
766 }
767 let np = self.npcmblocks;
768 for band in 0..nsubbands {
769 let b = sbi(ch, band);
770 for k in 0..ADPCM {
771 self.sb[b + k] = self.sb[b + np + k];
772 }
773 }
774 for band in nsubbands..SUBBANDS {
775 let b = sbi(ch, band);
776 self.sb[b..b + ADPCM + np].iter_mut().for_each(|x| *x = 0);
777 }
778 }
779 Ok(())
780 }
781
782 fn erase_x96_adpcm_history(&mut self) {
783 for ch in 0..CH {
784 for band in 0..64 {
785 let b = xbi(ch, band);
786 self.x96_sb[b..b + ADPCM].iter_mut().for_each(|x| *x = 0);
787 }
788 }
789 }
790
791 fn rand_x96(&mut self) -> i32 {
792 self.x96_rand = self.x96_rand.wrapping_mul(1103515245).wrapping_add(12345);
793 (self.x96_rand & 0x7fff_ffff) as i32 - 0x4000_0000
794 }
795
796 fn parse_x96_coding_header(&mut self, r: &mut Bits<'_>, exss: bool, xch_base: usize) -> Result<()> {
797 let header_pos = r.pos();
798 let mut header_size = 0usize;
799 if r.left() < 0 {
800 return Err(Error::corrupt("DTS: truncated X96 frame"));
801 }
802 if exss {
803 header_size = r.get(7) as usize + 1;
804 }
805 self.x96_high_res = r.get1() != 0;
806 if self.x96_rev_no < 8 {
807 self.x96_subband_start = r.get(5) as usize;
808 if self.x96_subband_start > 27 {
809 return Err(Error::corrupt("DTS: invalid X96 subband start index"));
810 }
811 } else {
812 self.x96_subband_start = SUBBANDS;
813 }
814 let n = self.x96_nchannels;
815 for ch in xch_base..n {
816 let v = r.get(6) as usize + 1;
817 if v < SUBBANDS {
818 return Err(Error::corrupt("DTS: invalid X96 subband activity count"));
819 }
820 self.nsubbands[ch] = v;
821 }
822 for ch in xch_base..n {
823 let mut v = r.get(3) as usize;
824 if v != 0 && xch_base != 0 {
825 v += xch_base - 1;
826 }
827 if v > n {
828 return Err(Error::corrupt("DTS: invalid X96 joint intensity coding index"));
829 }
830 self.joint_intensity_index[ch] = v;
831 }
832 for ch in xch_base..n {
833 let v = r.get(3) as usize;
834 if v >= 6 {
835 return Err(Error::corrupt("DTS: invalid X96 scale factor code book"));
836 }
837 self.scale_factor_sel[ch] = v;
838 }
839 for ch in xch_base..n {
840 self.bit_allocation_sel[ch] = r.get(3) as usize;
841 }
842 let nbooks = 6 + 4 * usize::from(self.x96_high_res);
843 for k in 0..nbooks {
844 for ch in xch_base..n {
845 self.quant_index_sel[ch][k] = r.get(QUANT_INDEX_SEL_NBITS[k]) as u8;
846 }
847 }
848 if exss {
849 if !r.seek(header_pos + header_size * 8) {
850 return Err(Error::corrupt("DTS: read past the end of an X96 channel set header"));
851 }
852 } else if self.crc_present {
853 r.skip(16);
854 }
855 Ok(())
856 }
857
858 fn parse_x96_subframe_header(&mut self, r: &mut Bits<'_>, xch_base: usize) -> Result<()> {
859 if r.left() < 0 {
860 return Err(Error::corrupt("DTS: truncated X96 frame"));
861 }
862 let n = self.x96_nchannels;
863 let start = self.x96_subband_start;
864 for ch in xch_base..n {
865 for band in start..self.nsubbands[ch] {
866 self.prediction_mode[ch][band] = r.get1() != 0;
867 }
868 }
869 for ch in xch_base..n {
870 for band in start..self.nsubbands[ch] {
871 if self.prediction_mode[ch][band] {
872 self.prediction_vq_index[ch][band] = r.get(12) as u16;
873 }
874 }
875 }
876 let hr = usize::from(self.x96_high_res);
877 for ch in xch_base..n {
878 let sel = self.bit_allocation_sel[ch];
879 let mut abits = 0i32;
880 for band in start..self.nsubbands[ch] {
881 if sel < 7 {
882 abits += self.books.quant_index[5 + 2 * hr][sel].read(r);
883 } else {
884 abits = r.get(3 + hr as u32) as i32;
885 }
886 if abits < 0 || abits > 7 + 8 * hr as i32 {
887 return Err(Error::corrupt("DTS: invalid X96 bit allocation index"));
888 }
889 self.bit_allocation[ch][band] = abits;
890 }
891 }
892 for ch in xch_base..n {
893 let sel = self.scale_factor_sel[ch];
894 let mut scale_index = 0i32;
895 for band in start..self.nsubbands[ch] {
896 self.scale_factors[ch][band >> 1][band & 1] = self.parse_scale(r, &mut scale_index, sel)?;
897 }
898 }
899 for ch in xch_base..n {
900 if self.joint_intensity_index[ch] != 0 {
901 let v = r.get(3) as usize;
902 if v == 7 {
903 return Err(Error::corrupt("DTS: invalid X96 joint scale factor code book"));
904 }
905 self.joint_scale_sel[ch] = v;
906 }
907 }
908 for ch in xch_base..n {
909 if self.joint_intensity_index[ch] != 0 {
910 let src_ch = self.joint_intensity_index[ch] - 1;
911 let sel = self.joint_scale_sel[ch];
912 for band in self.nsubbands[ch]..self.nsubbands[src_ch] {
913 self.joint_scale_factors[ch][band] = self.parse_joint_scale(r, sel)?;
914 }
915 }
916 }
917 if self.crc_present {
918 r.skip(16);
919 }
920 Ok(())
921 }
922
923 fn parse_x96_subframe_audio(&mut self, r: &mut Bits<'_>, sf: usize, xch_base: usize, sub_pos: &mut usize) -> Result<()> {
924 let nsamples = self.nsubsubframes[sf] * SSF_SAMPLES;
925 if *sub_pos + nsamples > self.npcmblocks {
926 return Err(Error::corrupt("DTS: X96 subband sample buffer overflow"));
927 }
928 if r.left() < 0 {
929 return Err(Error::corrupt("DTS: truncated X96 frame"));
930 }
931 let n = self.x96_nchannels;
932 let start = self.x96_subband_start;
933 let mut audio = [0i32; 16];
934
935 // VQ encoded or unallocated subbands
936 for ch in xch_base..n {
937 for band in start..self.nsubbands[ch] {
938 let scale = self.scale_factors[ch][band >> 1][band & 1];
939 let base = xbi(ch, band) + ADPCM + *sub_pos;
940 match self.bit_allocation[ch][band] {
941 0 => {
942 if scale <= 1 {
943 self.x96_sb[base..base + nsamples].iter_mut().for_each(|x| *x = 0);
944 } else {
945 for k in 0..nsamples {
946 let rnd = self.rand_x96();
947 self.x96_sb[base + k] = mul(rnd, scale, 31);
948 }
949 }
950 }
951 1 => {
952 let mut at = base;
953 for ssf in 0..self.nsubsubframes[sf].div_ceil(2) {
954 let idx = r.get(10) as usize;
955 let vq = &HIGH_FREQ_VQ[idx * 32..idx * 32 + 32];
956 for k in 0..(nsamples - ssf * 16).min(16) {
957 self.x96_sb[at] =
958 clip23(((vq[k] as i32).wrapping_mul(scale).wrapping_add(1 << 3)) >> 4);
959 at += 1;
960 }
961 }
962 }
963 _ => {}
964 }
965 }
966 }
967
968 // Audio data
969 let mut ofs = *sub_pos;
970 for ssf in 0..self.nsubsubframes[sf] {
971 for ch in xch_base..n {
972 if r.left() < 0 {
973 return Err(Error::corrupt("DTS: truncated X96 frame"));
974 }
975 for band in start..self.nsubbands[ch] {
976 let abits = self.bit_allocation[ch][band] - 1;
977 if abits < 1 {
978 continue;
979 }
980 let abits = abits as usize;
981 self.extract_audio(r, &mut audio, abits, ch)?;
982 let step_size = if self.bit_rate == 3 {
983 LOSSLESS_QUANT[abits]
984 } else {
985 LOSSY_QUANT[abits]
986 } as i32;
987 let scale = self.scale_factors[ch][band >> 1][band & 1];
988 let base = xbi(ch, band) + ADPCM + ofs;
989 dequantize(&mut self.x96_sb[base..base + SSF_SAMPLES], &audio[..SSF_SAMPLES], step_size, scale, false);
990 }
991 }
992 if (ssf == self.nsubsubframes[sf] - 1 || self.sync_ssf) && r.get(16) != 0xffff {
993 return Err(Error::corrupt("DTS: X96-DSYNC check failed"));
994 }
995 ofs += SSF_SAMPLES;
996 }
997
998 // Inverse ADPCM
999 for ch in xch_base..n {
1000 for band in start..self.nsubbands[ch] {
1001 if self.prediction_mode[ch][band] {
1002 let id = self.prediction_vq_index[ch][band] as usize;
1003 let base = xbi(ch, band) + ADPCM + *sub_pos;
1004 for j in 0..nsamples {
1005 let x = predict(id, &self.x96_sb[base + j - ADPCM..base + j]);
1006 self.x96_sb[base + j] = clip23(self.x96_sb[base + j].wrapping_add(x));
1007 }
1008 }
1009 }
1010 }
1011
1012 // Joint subband coding
1013 for ch in xch_base..n {
1014 if self.joint_intensity_index[ch] != 0 {
1015 let src_ch = self.joint_intensity_index[ch] - 1;
1016 for band in self.nsubbands[ch]..self.nsubbands[src_ch] {
1017 let scale = self.joint_scale_factors[ch][band];
1018 let sbase = xbi(src_ch, band) + ADPCM + *sub_pos;
1019 let dbase = xbi(ch, band) + ADPCM + *sub_pos;
1020 for j in 0..nsamples {
1021 self.x96_sb[dbase + j] = clip23(mul(self.x96_sb[sbase + j], scale, 17));
1022 }
1023 }
1024 }
1025 }
1026
1027 *sub_pos = ofs;
1028 Ok(())
1029 }
1030
1031 fn parse_x96_frame_data(&mut self, r: &mut Bits<'_>, exss: bool, xch_base: usize) -> Result<()> {
1032 self.parse_x96_coding_header(r, exss, xch_base)?;
1033 let mut sub_pos = 0usize;
1034 for sf in 0..self.nsubframes {
1035 self.parse_x96_subframe_header(r, xch_base)?;
1036 self.parse_x96_subframe_audio(r, sf, xch_base, &mut sub_pos)?;
1037 }
1038 if r.over {
1039 return Err(Error::corrupt("DTS: truncated X96 frame"));
1040 }
1041 let np = self.npcmblocks;
1042 for ch in xch_base..self.x96_nchannels {
1043 let mut nsubbands = self.nsubbands[ch];
1044 if self.joint_intensity_index[ch] != 0 {
1045 nsubbands = nsubbands.max(self.nsubbands[self.joint_intensity_index[ch] - 1]);
1046 }
1047 for band in 0..64 {
1048 let b = xbi(ch, band);
1049 if band >= self.x96_subband_start && band < nsubbands {
1050 for k in 0..ADPCM {
1051 self.x96_sb[b + k] = self.x96_sb[b + np + k];
1052 }
1053 } else {
1054 self.x96_sb[b..b + ADPCM + np].iter_mut().for_each(|x| *x = 0);
1055 }
1056 }
1057 }
1058 Ok(())
1059 }
1060
1061 fn parse_x96_frame(&mut self, r: &mut Bits<'_>) -> Result<()> {
1062 self.x96_rev_no = r.get(4);
1063 if self.x96_rev_no < 1 || self.x96_rev_no > 8 {
1064 return Err(Error::corrupt("DTS: invalid X96 revision"));
1065 }
1066 self.x96_crc_present = false;
1067 self.x96_nchannels = self.nchannels;
1068 if !self.predictor_history {
1069 self.erase_x96_adpcm_history();
1070 }
1071 self.parse_x96_frame_data(r, false, 0)
1072 }
1073
1074 fn parse_x96_frame_exss(&mut self, data: &[u8]) -> Result<()> {
1075 let mut r = Bits::new(data);
1076 let header_pos = r.pos();
1077 if r.get(32) != 0x1D95_F262 {
1078 return Err(Error::corrupt("DTS: invalid X96 sync word"));
1079 }
1080 let header_size = r.get(6) as usize + 1;
1081 self.x96_rev_no = r.get(4);
1082 if self.x96_rev_no < 1 || self.x96_rev_no > 8 {
1083 return Err(Error::corrupt("DTS: invalid X96 revision"));
1084 }
1085 self.x96_crc_present = r.get1() != 0;
1086 let nchsets = r.get(2) as usize + 1;
1087 let mut frame_size = [0usize; 4];
1088 let mut nch = [0usize; 4];
1089 for fs in frame_size.iter_mut().take(nchsets) {
1090 *fs = r.get(12) as usize + 1;
1091 }
1092 for c in nch.iter_mut().take(nchsets) {
1093 *c = r.get(3) as usize + 1;
1094 }
1095 if !r.seek(header_pos + header_size * 8) {
1096 return Err(Error::corrupt("DTS: read past the end of the X96 frame header"));
1097 }
1098 if !self.predictor_history {
1099 self.erase_x96_adpcm_history();
1100 }
1101 self.x96_nchannels = 0;
1102 let mut base_ch = 0usize;
1103 for i in 0..nchsets {
1104 let pos = r.pos();
1105 if base_ch + nch[i] <= self.nchannels {
1106 self.x96_nchannels = base_ch + nch[i];
1107 self.parse_x96_frame_data(&mut r, true, base_ch)?;
1108 }
1109 base_ch += nch[i];
1110 if !r.seek(pos + frame_size[i] * 8) {
1111 return Err(Error::corrupt("DTS: read past the end of an X96 channel set"));
1112 }
1113 }
1114 Ok(())
1115 }
1116
1117 fn parse_xch_frame(&mut self, r: &mut Bits<'_>) -> Result<()> {
1118 if self.ch_mask & MASK_CS != 0 {
1119 return Err(Error::corrupt("DTS: XCH with Cs speaker already present"));
1120 }
1121 let base = self.nchannels;
1122 self.parse_frame_data(r, Header::Xch, base)
1123 }
1124
1125 /// Map a primary channel to its speaker slot, -1 when unmapped.
1126 fn map_prm_ch_to_spkr(&self, ch: usize) -> i32 {
1127 let pos = CHANNELS[self.audio_mode] as usize;
1128 if ch < pos {
1129 return PRM_CH_TO_SPKR[self.audio_mode][ch] as i32;
1130 }
1131 if self.ext.xch && ch == pos {
1132 return SPK_CS as i32;
1133 }
1134 -1
1135 }
1136
1137 fn filter(&mut self) -> Result<Decoded> {
1138 let np = self.npcmblocks;
1139 let x96 = self.ext.x96;
1140 let x96_nch = if x96 { self.x96_nchannels } else { 0 };
1141 let nsamples = (np * 32) << usize::from(x96);
1142 let mut out: Vec<Vec<i32>> = (0..CH).map(|_| Vec::new()).collect();
1143 for spk in 0..CH {
1144 if self.ch_mask & (1 << spk) != 0 {
1145 out[spk] = vec![0; nsamples];
1146 }
1147 }
1148 let mode = u8::from(x96);
1149 if self.filter_mode != mode {
1150 for d in &mut self.dsp {
1151 d.clear();
1152 }
1153 self.lfe_x96_hist = 0;
1154 self.filter_mode = mode;
1155 }
1156 let window: &[i32; 512] = if self.filter_perfect {
1157 &FIR_32_PERFECT
1158 } else {
1159 &FIR_32_NONPERFECT
1160 };
1161 for ch in 0..self.nchannels {
1162 let spkr = self.map_prm_ch_to_spkr(ch);
1163 if spkr < 0 {
1164 return Err(Error::corrupt("DTS: channel without a speaker"));
1165 }
1166 let dsp = &mut self.dsp[ch];
1167 let o = &mut out[spkr as usize];
1168 if x96 {
1169 let mut input = [0i32; 64];
1170 for j in 0..np {
1171 for i in 0..32 {
1172 let lo = self.sb[sbi(ch, i) + ADPCM + j];
1173 input[i] = if ch < x96_nch {
1174 lo.wrapping_add(self.x96_sb[xbi(ch, i) + ADPCM + j])
1175 } else {
1176 lo
1177 };
1178 }
1179 for i in 32..64 {
1180 input[i] = if ch < x96_nch {
1181 self.x96_sb[xbi(ch, i) + ADPCM + j]
1182 } else {
1183 0
1184 };
1185 }
1186 synth_filter_64(dsp, &FIR_64, &mut o[j * 64..j * 64 + 64], &input);
1187 }
1188 } else {
1189 let mut input = [0i32; 32];
1190 for j in 0..np {
1191 for i in 0..SUBBANDS {
1192 input[i] = self.sb[sbi(ch, i) + ADPCM + j];
1193 }
1194 synth_filter_32(dsp, window, &mut o[j * 32..j * 32 + 32], &input);
1195 }
1196 }
1197 }
1198
1199 // LFE
1200 if self.lfe_present != 0 {
1201 let dec128 = self.lfe_present == 1;
1202 let nlfe = np >> (usize::from(dec128) + 1);
1203 let mut base = vec![0i32; np * 32];
1204 if dec128 {
1205 // The fixed-point reference has no 128x decimation filter;
1206 // interpolate in floating point and round to the same grid.
1207 for i in 0..nlfe {
1208 for j in 0..64 {
1209 let (mut a, mut b) = (0f64, 0f64);
1210 for k in 0..4 {
1211 let s = self.lfe_samples[LFE_HISTORY + i - k] as f64;
1212 a += LFE_FIR_128[j * 4 + k] as f64 * s;
1213 b += LFE_FIR_128[255 - j * 4 - k] as f64 * s;
1214 }
1215 base[128 * i + j] = clip23(a.round() as i32);
1216 base[128 * i + 64 + j] = clip23(b.round() as i32);
1217 }
1218 }
1219 } else {
1220 for i in 0..nlfe {
1221 for j in 0..32 {
1222 let (mut a, mut b) = (0i64, 0i64);
1223 for k in 0..8 {
1224 let s = self.lfe_samples[LFE_HISTORY + i - k] as i64;
1225 a += LFE_FIR_64[j * 8 + k] as i64 * s;
1226 b += LFE_FIR_64[255 - j * 8 - k] as i64 * s;
1227 }
1228 base[64 * i + j] = clip23(norm(a, 23));
1229 base[64 * i + 32 + j] = clip23(norm(b, 23));
1230 }
1231 }
1232 }
1233 let o = &mut out[SPK_LFE];
1234 if x96 {
1235 // Smooth the 96 kHz oversampled LFE to attenuate the image
1236 // between 47.6 and 48 kHz.
1237 let mut prev = self.lfe_x96_hist;
1238 for (i, &src) in base.iter().enumerate() {
1239 let a = 2097471i64 * src as i64 + 6291137i64 * prev as i64;
1240 let b = 6291137i64 * src as i64 + 2097471i64 * prev as i64;
1241 prev = src;
1242 o[2 * i] = clip23(norm(a, 23));
1243 o[2 * i + 1] = clip23(norm(b, 23));
1244 }
1245 self.lfe_x96_hist = prev;
1246 } else {
1247 o.copy_from_slice(&base);
1248 }
1249 for n in (0..LFE_HISTORY).rev() {
1250 self.lfe_samples[n] = self.lfe_samples[nlfe + n];
1251 }
1252 }
1253
1254 // Undo the embedded XCH downmix of ES mastered material.
1255 if self.es_format && self.ext.xch && self.audio_mode >= 8 {
1256 let cs = out[SPK_CS].clone();
1257 for i in 0..nsamples {
1258 let c = mul23(cs[i], 5931520);
1259 out[SPK_LS][i] = out[SPK_LS][i].wrapping_sub(c);
1260 out[SPK_RS][i] = out[SPK_RS][i].wrapping_sub(c);
1261 }
1262 }
1263
1264 if !self.ext.xch {
1265 if (self.sumdiff_front && self.audio_mode > 0) || self.audio_mode == 3 {
1266 butterflies(&mut out, SPK_L, SPK_R);
1267 }
1268 if self.sumdiff_surround && self.audio_mode >= 8 {
1269 butterflies(&mut out, SPK_LS, SPK_RS);
1270 }
1271 }
1272
1273 Ok(Decoded {
1274 nsamples,
1275 sample_rate: self.sample_rate << u32::from(x96),
1276 ch_mask: self.ch_mask,
1277 out,
1278 ext: self.ext,
1279 })
1280 }
1281}
1282
1283fn butterflies(out: &mut [Vec<i32>], a: usize, b: usize) {
1284 let (x, y) = if a < b {
1285 let (lo, hi) = out.split_at_mut(b);
1286 (&mut lo[a], &mut hi[0])
1287 } else {
1288 let (lo, hi) = out.split_at_mut(a);
1289 (&mut hi[0], &mut lo[b])
1290 };
1291 for (p, q) in x.iter_mut().zip(y.iter_mut()) {
1292 let t = p.wrapping_sub(*q);
1293 *p = p.wrapping_add(*q);
1294 *q = t;
1295 }
1296}
1297
1298/// Skip over the core frame header the caller already parsed.
1299fn skip_frame_header(r: &mut Bits<'_>, h: &FrameHeader) {
1300 // 32 sync, 1 normal, 5 deficit, 1 crc, 7 nblks, 14 fsize, 6 amode,
1301 // 4 sfreq, 5 rate, 1 reserved, 1 drc, 1 ts, 1 aux, 1 hdcd, 3 ext type,
1302 // 1 ext present, 1 sync, 2 lfe, 1 predictor history = 88 bits.
1303 r.skip(88);
1304 if h.crc_present {
1305 r.skip(16);
1306 }
1307 // 1 filter, 4 rev, 2 copy hist, 3 pcmr, 1+1 sumdiff, 4 dialnorm = 16.
1308 r.skip(16);
1309}
1310
1311/// ff-compatible dequantization: scale to the 22-bit fraction of the 24-bit
1312/// grid, limiting the combined step and scale factor to 24 significant bits.
1313fn dequantize(output: &mut [i32], input: &[i32], step_size: i32, scale: i32, residual: bool) {
1314 let mut step_scale = step_size as i64 * scale as i64;
1315 let mut shift = 0u32;
1316 if step_scale > (1 << 23) {
1317 shift = (63 - (step_scale >> 23).leading_zeros()) + 1;
1318 step_scale >>= shift;
1319 }
1320 for (o, &i) in output.iter_mut().zip(input) {
1321 let bits = (22 - shift as i32).max(0) as u32;
1322 let v = clip23(norm(i as i64 * step_scale, bits));
1323 if residual {
1324 *o = o.wrapping_add(v);
1325 } else {
1326 *o = v;
1327 }
1328 }
1329}
1330
1331/// Four-tap ADPCM prediction from the four samples before `hist.len()`.
1332fn predict(pred_vq_index: usize, hist: &[i32]) -> i32 {
1333 let coeff = &ADPCM_VB[pred_vq_index * 4..pred_vq_index * 4 + 4];
1334 let mut pred: i64 = 0;
1335 for i in 0..ADPCM {
1336 pred += hist[ADPCM - 1 - i] as i64 * coeff[i] as i64;
1337 }
1338 clip23(norm(pred, 13))
1339}
1340
1341/// One subband sample per band in, 32 PCM samples out.
1342fn synth_filter_32(dsp: &mut Dsp, window: &[i32; 512], out: &mut [i32], input: &[i32; 32]) {
1343 let off = dsp.offset;
1344 imdct_half_32(&mut dsp.hist1[off..off + 32], input);
1345 let sb = &dsp.hist1;
1346 for i in 0..16 {
1347 let mut a: i64 = (dsp.hist2[i] as i64) << 21;
1348 let mut b: i64 = (dsp.hist2[i + 16] as i64) << 21;
1349 let mut c: i64 = 0;
1350 let mut d: i64 = 0;
1351 let mut j = 0;
1352 while j < 512 {
1353 let at = |k: usize| sb[(off + k + j) & 511] as i64;
1354 a += window[i + j] as i64 * at(i);
1355 b += window[i + j + 16] as i64 * at(15 - i);
1356 c += window[i + j + 32] as i64 * at(16 + i);
1357 d += window[i + j + 48] as i64 * at(31 - i);
1358 j += 64;
1359 }
1360 out[i] = clip23(norm(a, 21));
1361 out[i + 16] = clip23(norm(b, 21));
1362 dsp.hist2[i] = norm(c, 21);
1363 dsp.hist2[i + 16] = norm(d, 21);
1364 }
1365 dsp.offset = (off.wrapping_sub(32)) & 511;
1366}
1367
1368/// One subband sample per band in, 64 PCM samples out (X96 bank).
1369fn synth_filter_64(dsp: &mut Dsp, window: &[i32; 1024], out: &mut [i32], input: &[i32; 64]) {
1370 let off = dsp.offset;
1371 imdct_half_64(&mut dsp.hist1[off..off + 64], input);
1372 let sb = &dsp.hist1;
1373 for i in 0..32 {
1374 let mut a: i64 = (dsp.hist2[i] as i64) << 20;
1375 let mut b: i64 = (dsp.hist2[i + 32] as i64) << 20;
1376 let mut c: i64 = 0;
1377 let mut d: i64 = 0;
1378 let mut j = 0;
1379 while j < 1024 {
1380 let at = |k: usize| sb[(off + k + j) & 1023] as i64;
1381 a += window[i + j] as i64 * at(i);
1382 b += window[i + j + 32] as i64 * at(31 - i);
1383 c += window[i + j + 64] as i64 * at(32 + i);
1384 d += window[i + j + 96] as i64 * at(63 - i);
1385 j += 128;
1386 }
1387 out[i] = clip23(norm(a, 20));
1388 out[i + 32] = clip23(norm(b, 20));
1389 dsp.hist2[i] = norm(c, 20);
1390 dsp.hist2[i + 32] = norm(d, 20);
1391 }
1392 dsp.offset = off.wrapping_sub(64) & 1023;
1393}