forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBea55462Tahinli3 months ago753 commits

decode.rs924 lines, 34.7 KiBHistoryRawDownload
1//! The lossless substream decode: restart headers, decoding parameters,
2//! Huffman/LSB residuals, FIR/IIR prediction, rematrixing with the seeded
3//! noise generators, output shift — and the stream's own integrity checks
4//! (restart-header CRC, per-substream parity, the lossless-check byte).
5//!
6//! Written from the public description of the MLP/TrueHD bitstream. Every
7//! numeric constant a from-memory description could get wrong (the three
8//! Huffman codebooks, the noise table, the generators' feedback taps, the
9//! restart-header CRC) was *derived or confirmed* against an external
10//! decoder: the codebooks were read off externally encoded mono streams
11//! whose PCM is known, the 256-entry noise table was solved for by
12//! constraint intersection over the real 7.1 track, and `tests/oracle.rs`
13//! keeps both bit-exact.
14//!
15//! **Per-substream syntax** (one substream's bytes, bit-serial MSB-first):
16//!
17//! ```text
18//! loop {
19//! params_present(1)
20//! restart_present(1) → restart header:
21//! sync(14) = 0x31EA|0x31EB (low bit = noise type), output_timing(16),
22//! min_ch(4), max_ch(4), max_matrix_ch(4), noise_shift(4),
23//! noise_seed(23), reserved(19), data_check_present(1),
24//! lossless_check(8), reserved(16), ch_assign(6) × (max_matrix_ch+1),
25//! crc8(8, poly 0x1D)
26//! decoding params (each group gated by a presence flag):
27//! presence flags(8); block size(9); matrices: count(4), per matrix
28//! out_ch(4) frac_bits(4) lsb_bypass(1) [present(1) coeff(frac+2)] per
29//! input channel (+2 noise channels for noise type 0) [noise_shift(4)
30//! for noise type 1]; output shift(4 signed) per matrix channel;
31//! quant step(4) per channel; per channel: FIR/IIR (order(4), shift(4),
32//! coeff_bits(5), coeff_shift(3), coeffs, [IIR state]), huff_offset(15
33//! signed), codebook(2), huff_lsbs(5)
34//! block: [data check: bit count(16)] per sample: lsb-bypass bits, then
35//! per channel Huffman index (codebook 1..3) + lsb bits; [crc(8)]
36//! end_of_segment(1)
37//! }
38//! align(16) [0xD234D234 end-of-stream] [parity(8) crc8(8, not validated)]
39//! ```
40//!
41//! **Reconstruction**: `residual = ((index << lsb_bits) + lsbs +
42//! sign_offset) << quant_step`; `sample = (predict(FIR over past samples,
43//! IIR over past residual-after-FIR) + residual) & !((1 << quant_step) - 1)`;
44//! then, for the highest substream only, each primitive matrix rewrites one
45//! channel as `(Σ coeff·chan + noise) >> 14` masked to the quant step plus
46//! its bypassed LSB; then `<< output_shift`; then `<< 8` to a left-justified
47//! 24-in-32 sample.
48//!
49//! **Channel order**: TrueHD's 8-channel presentation with assignment `0x4F`
50//! (L R C LFE Ls Rs Lrs Rrs) lands on [`ChannelLayout::Surround7_1`]'s
51//! FL FR FC LFE BL BR SL SR as output index `[0,1,2,3,6,7,4,5]` — TrueHD's
52//! Ls/Rs pair is the *side* pair, Lrs/Rrs the *back* pair. 2- and 6-channel
53//! presentations map 1:1.
54
55use ec_core::bitio::BitReader;
56use ec_core::error::{Error, Result};
57use ec_core::frame::{AudioFrame, ChannelLayout, SampleFormat};
58use ec_core::packet::Buf;
59
60use crate::sync::AccessUnitHeader;
61
62/// Highest matrix/output channel index the 2/6/8-channel presentations use;
63/// anything above is the 16-channel object substream, refused.
64const MAX_MATRIX_CHANNEL: usize = 7;
65/// Sample-buffer width: 8 PCM channels plus the 2 noise channels noise type 0
66/// appends after the last matrix channel.
67const MAX_CHANNELS: usize = MAX_MATRIX_CHANNEL + 3;
68const MAX_MATRICES: usize = 8;
69const MAX_FILTER_ORDER: usize = 8;
70const END_OF_STREAM: u32 = 0xD234_D234;
71
72/// The fixed 256-entry dither table noise type 1 (TrueHD's `0x31EB`) draws
73/// matrix noise from, indexed by the generator's top byte. A constant of the
74/// format; every entry was solved for exactly (constraint intersection over
75/// 72 000 access units of the real 7.1 track against the external decoder's
76/// output) and is kept bit-exact by `tests/oracle.rs`.
77#[rustfmt::skip]
78const NOISE_TABLE: [i8; 256] = [
79 30, 51, 22, 54, 3, 7, -4, 38, 14, 55, 46, 81, 22, 58, -3, 2,
80 52, 31, -7, 51, 15, 44, 74, 30, 85, -17, 10, 33, 18, 80, 28, 62,
81 10, 32, 23, 69, 72, 26, 35, 17, 73, 60, 8, 56, 2, 6, -2, -5,
82 51, 4, 11, 50, 66, 76, 21, 44, 33, 47, 1, 26, 64, 48, 57, 40,
83 38, 16, -10, -28, 92, 22, -18, 29, -10, 5, -13, 49, 19, 24, 70, 34,
84 61, 48, 30, 14, -6, 25, 58, 33, 42, 60, 67, 17, 54, 17, 22, 30,
85 67, 44, -9, 50, -11, 43, 40, 32, 59, 82, 13, 49, -14, 55, 60, 36,
86 48, 49, 31, 47, 15, 12, 4, 65, 1, 23, 29, 39, 45, -2, 84, 69,
87 0, 72, 37, 57, 27, 41, -15, -16, 35, 31, 14, 61, 24, 0, 27, 24,
88 16, 41, 55, 34, 53, 9, 56, 12, 25, 29, 53, 5, 20, -20, -8, 20,
89 13, 28, -3, 78, 38, 16, 11, 62, 46, 29, 21, 24, 46, 65, 43, -23,
90 89, 18, 74, 21, 38, -12, 19, 12, -19, 8, 15, 33, 4, 57, 9, -8,
91 36, 35, 26, 28, 7, 83, 63, 79, 75, 11, 3, 87, 37, 47, 34, 40,
92 39, 19, 20, 42, 27, 34, 39, 77, 13, 42, 59, 64, 45, -1, 32, 37,
93 45, -5, 53, -6, 7, 36, 50, 23, 6, 32, 9, -21, 18, 71, 27, 52,
94 -25, 31, 35, 42, -1, 68, 63, 52, 26, 43, 66, 37, 41, 25, 40, 70,
95];
96
97const PARAM_BLOCKSIZE: u8 = 1 << 7;
98const PARAM_MATRIX: u8 = 1 << 6;
99const PARAM_OUTSHIFT: u8 = 1 << 5;
100const PARAM_QUANTSTEP: u8 = 1 << 4;
101const PARAM_FIR: u8 = 1 << 3;
102const PARAM_IIR: u8 = 1 << 2;
103const PARAM_HUFFOFFSET: u8 = 1 << 1;
104const PARAM_PRESENCE: u8 = 1 << 0;
105
106/// The three residual codebooks as `(code, length)` per index: codebook 1
107/// covers indices 0..18, codebook 2 0..16, codebook 3 0..15. Unused tail
108/// entries have length 0. Shape: a unary run `0…01` of length `7 - i + 2`
109/// below the centre, `010…01` above it, and 1-3 short codes at the centre
110/// (the three books differ only there). Verified code-for-code against an
111/// external encoder's output (`tests/oracle.rs`).
112pub const HUFFMAN_TABLES: [[(u16, u8); 18]; 3] = [
113 [
114 (0x01, 9),
115 (0x01, 8),
116 (0x01, 7),
117 (0x01, 6),
118 (0x01, 5),
119 (0x01, 4),
120 (0x01, 3),
121 (0x04, 3),
122 (0x05, 3),
123 (0x06, 3),
124 (0x07, 3),
125 (0x03, 3),
126 (0x05, 4),
127 (0x09, 5),
128 (0x11, 6),
129 (0x21, 7),
130 (0x41, 8),
131 (0x81, 9),
132 ],
133 [
134 (0x01, 9),
135 (0x01, 8),
136 (0x01, 7),
137 (0x01, 6),
138 (0x01, 5),
139 (0x01, 4),
140 (0x01, 3),
141 (0x02, 2),
142 (0x03, 2),
143 (0x03, 3),
144 (0x05, 4),
145 (0x09, 5),
146 (0x11, 6),
147 (0x21, 7),
148 (0x41, 8),
149 (0x81, 9),
150 (0, 0),
151 (0, 0),
152 ],
153 [
154 (0x01, 9),
155 (0x01, 8),
156 (0x01, 7),
157 (0x01, 6),
158 (0x01, 5),
159 (0x01, 4),
160 (0x01, 3),
161 (0x01, 1),
162 (0x03, 3),
163 (0x05, 4),
164 (0x09, 5),
165 (0x11, 6),
166 (0x21, 7),
167 (0x41, 8),
168 (0x81, 9),
169 (0, 0),
170 (0, 0),
171 (0, 0),
172 ],
173];
174
175/// 512-entry lookup per codebook: `(index, length)`, length 0 = invalid code.
176struct HuffLut([[(u8, u8); 512]; 3]);
177
178impl HuffLut {
179 fn build() -> HuffLut {
180 let mut lut = [[(0u8, 0u8); 512]; 3];
181 for (book, table) in HUFFMAN_TABLES.iter().enumerate() {
182 for (index, &(code, len)) in table.iter().enumerate() {
183 if len == 0 {
184 continue;
185 }
186 let base = usize::from(code) << (9 - len);
187 for k in 0..(1usize << (9 - len)) {
188 lut[book][base + k] = (index as u8, len);
189 }
190 }
191 }
192 HuffLut(lut)
193 }
194
195 fn decode(&self, br: &mut BitReader, book: usize) -> Result<i32> {
196 let avail = br.bits_remaining().min(9) as u32;
197 if avail == 0 {
198 return Err(Error::NeedMore);
199 }
200 let bits = br.peek_bits(avail)? << (9 - avail);
201 let (index, len) = self.0[book][bits as usize];
202 if len == 0 || u64::from(len) > br.bits_remaining() {
203 return Err(Error::corrupt("TrueHD: invalid Huffman code"));
204 }
205 br.skip_bits(u64::from(len))?;
206 Ok(i32::from(index))
207 }
208}
209
210/// Bit-serial CRC-8 (MSB first, no reflection, no final xor).
211fn crc8(poly: u8, init: u8, bytes: &[u8]) -> u8 {
212 let mut crc = init;
213 for &b in bytes {
214 crc ^= b;
215 for _ in 0..8 {
216 crc = if crc & 0x80 != 0 {
217 (crc << 1) ^ poly
218 } else {
219 crc << 1
220 };
221 }
222 }
223 crc
224}
225
226/// The restart header's own CRC-8 (poly 0x1D), over the header from its
227/// first byte (`buf[0]`, whose two leading bits — the params/restart flags —
228/// are masked off) through its last full byte and the trailing partial bits.
229pub(crate) fn restart_checksum(buf: &[u8], bit_size: u64) -> u8 {
230 let bit_size = bit_size as usize + 2;
231 let num_bytes = bit_size / 8;
232 let mut crc = crc8(0x1D, 0, &[buf[0] & 0x3F]);
233 crc = crc8(0x1D, crc, &buf[1..num_bytes - 1]);
234 crc ^= buf[num_bytes - 1];
235 for i in 0..(bit_size & 7) {
236 let top = crc & 0x80 != 0;
237 crc <<= 1;
238 if top {
239 crc ^= 0x1D;
240 }
241 crc ^= (buf[num_bytes] >> (7 - i)) & 1;
242 }
243 crc
244}
245
246/// XOR-fold a 32-bit word to 8 bits.
247fn xor_32_to_8(v: u32) -> u8 {
248 (v ^ (v >> 8) ^ (v >> 16) ^ (v >> 24)) as u8
249}
250
251#[derive(Debug, Clone, Copy, Default)]
252struct Filter {
253 order: usize,
254 shift: u32,
255 coeffs: [i32; MAX_FILTER_ORDER],
256 /// History, most recent first.
257 state: [i32; MAX_FILTER_ORDER],
258}
259
260#[derive(Debug, Clone, Copy, Default)]
261struct ChannelParams {
262 fir: Filter,
263 iir: Filter,
264 huff_offset: i32,
265 sign_huff_offset: i32,
266 codebook: u8,
267 huff_lsbs: u8,
268}
269
270#[derive(Debug, Clone, Copy, Default)]
271struct Matrix {
272 out_ch: usize,
273 lsb_bypass: bool,
274 noise_shift: u32,
275 coeffs: [i32; MAX_CHANNELS],
276}
277
278#[derive(Debug, Clone)]
279struct Substream {
280 restart_seen: bool,
281 noise_type: bool,
282 min_channel: usize,
283 max_channel: usize,
284 max_matrix_channel: usize,
285 noise_shift: u32,
286 noisegen_seed: u32,
287 data_check_present: bool,
288 lossless_check_data: u32,
289 ch_assign: [usize; MAX_CHANNELS],
290 param_presence_flags: u8,
291 blocksize: usize,
292 matrices: Vec<Matrix>,
293 output_shift: [i32; MAX_CHANNELS],
294 quant_step_size: [u32; MAX_CHANNELS],
295 channels: [ChannelParams; MAX_CHANNELS],
296 /// Samples decoded so far in this access unit.
297 blockpos: usize,
298}
299
300impl Substream {
301 fn new() -> Substream {
302 Substream {
303 restart_seen: false,
304 noise_type: false,
305 min_channel: 0,
306 max_channel: 0,
307 max_matrix_channel: 0,
308 noise_shift: 0,
309 noisegen_seed: 0,
310 data_check_present: false,
311 lossless_check_data: 0,
312 ch_assign: [0; MAX_CHANNELS],
313 param_presence_flags: 0xFF,
314 blocksize: 8,
315 matrices: Vec::new(),
316 output_shift: [0; MAX_CHANNELS],
317 quant_step_size: [0; MAX_CHANNELS],
318 channels: [ChannelParams::default(); MAX_CHANNELS],
319 blockpos: 0,
320 }
321 }
322
323 fn recompute_sign_offset(&mut self, ch: usize) {
324 let cp = &mut self.channels[ch];
325 let lsb_bits = i32::from(cp.huff_lsbs) - self.quant_step_size[ch] as i32;
326 let sign_shift = lsb_bits
327 + if cp.codebook > 0 {
328 2 - i32::from(cp.codebook)
329 } else {
330 -1
331 };
332 let mut off = cp.huff_offset;
333 if cp.codebook > 0 {
334 off -= 7 << lsb_bits;
335 }
336 if sign_shift >= 0 {
337 off -= 1 << sign_shift;
338 }
339 cp.sign_huff_offset = off;
340 }
341}
342
343/// Integrity counters the decoder keeps across access units; every one is a
344/// stream-side self-check that stays zero on a clean decode.
345#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
346pub struct CheckStats {
347 /// Restart headers whose CRC-8 did not match.
348 pub restart_crc_failures: u64,
349 /// Restart headers seen (the lossless-check byte is verified at each
350 /// one after the first, against the samples output since the previous).
351 pub restart_headers: u64,
352 /// Lossless-check bytes that did not match the output.
353 pub lossless_check_failures: u64,
354 /// Substream segments whose parity byte did not match.
355 pub parity_failures: u64,
356 /// Substream segments whose bit count did not land on the directory's
357 /// end pointer.
358 pub length_mismatches: u64,
359}
360
361/// Decoder state shared across the substreams of one stream.
362#[derive(Debug, Clone)]
363pub(crate) struct Core {
364 huff: std::sync::Arc<HuffLutBox>,
365 substreams: Vec<Substream>,
366 /// Samples per access unit (40 at 48 kHz) and its next power of two.
367 access_unit_size: usize,
368 access_unit_size_pow2: usize,
369 sample_rate: u32,
370 /// The major sync's 8-channel presentation assignment mask.
371 ch8_assignment: u16,
372 sample_buffer: Vec<[i32; MAX_CHANNELS]>,
373 bypassed_lsbs: Vec<[i32; MAX_MATRICES]>,
374 noise_buffer: Vec<i8>,
375 /// Self-check tallies.
376 pub stats: CheckStats,
377}
378
379struct HuffLutBox(HuffLut);
380
381impl std::fmt::Debug for HuffLutBox {
382 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
383 f.write_str("HuffLut")
384 }
385}
386
387impl Core {
388 pub(crate) fn new() -> Core {
389 Core {
390 huff: std::sync::Arc::new(HuffLutBox(HuffLut::build())),
391 substreams: Vec::new(),
392 access_unit_size: 0,
393 access_unit_size_pow2: 0,
394 sample_rate: 0,
395 ch8_assignment: 0,
396 sample_buffer: Vec::new(),
397 bypassed_lsbs: Vec::new(),
398 noise_buffer: Vec::new(),
399 stats: CheckStats::default(),
400 }
401 }
402
403 pub(crate) fn reset(&mut self) {
404 self.substreams.clear();
405 self.access_unit_size = 0;
406 }
407
408 /// Decodes one access unit whose header already parsed; `None` until the
409 /// first major sync and every substream's first restart header are seen.
410 pub(crate) fn decode(
411 &mut self,
412 header: &AccessUnitHeader,
413 data: &[u8],
414 ) -> Result<Option<AudioFrame>> {
415 if !self.prepare(header)? || !self.decode_substreams(header, data)? {
416 return Ok(None);
417 }
418 self.finish()
419 }
420
421 /// Takes a major sync's stream parameters on board; `Ok(false)` while no
422 /// major sync has been seen yet.
423 fn prepare(&mut self, header: &AccessUnitHeader) -> Result<bool> {
424 if let Some(sync) = &header.major_sync {
425 let shift = sync.rate_code & 7;
426 if shift > 2 {
427 return Err(Error::unsupported(
428 format!("TrueHD sample rate code {}", sync.rate_code),
429 "the format reserves it",
430 ));
431 }
432 self.access_unit_size = 40 << shift;
433 self.access_unit_size_pow2 = 64 << shift;
434 self.sample_rate = sync.sample_rate;
435 if self.substreams.len() != header.substreams.len() {
436 self.substreams = vec![Substream::new(); header.substreams.len()];
437 }
438 self.sample_buffer = vec![[0; MAX_CHANNELS]; self.access_unit_size];
439 self.bypassed_lsbs = vec![[0; MAX_MATRICES]; self.access_unit_size];
440 self.noise_buffer = vec![0; self.access_unit_size_pow2];
441 self.ch8_assignment = sync.ch8_assignment;
442 }
443 Ok(self.access_unit_size != 0 && self.substreams.len() == header.substreams.len())
444 }
445
446 /// Every substream's blocks into `sample_buffer`; `Ok(false)` while some
447 /// substream still awaits its first restart header.
448 fn decode_substreams(&mut self, header: &AccessUnitHeader, data: &[u8]) -> Result<bool> {
449 let mut all_seen = true;
450 for (i, info) in header.substreams.iter().enumerate() {
451 let (start, end) = header.substream_span(i);
452 let seg = data.get(start..end).ok_or(Error::NeedMore)?;
453 let seen = self.decode_substream(i, seg, info.flags & 0x2 != 0)?;
454 all_seen &= seen;
455 }
456 Ok(all_seen)
457 }
458
459 /// Rematrix + output of the top substream for the current access unit.
460 fn finish(&mut self) -> Result<Option<AudioFrame>> {
461 let top = self.substreams.len() - 1;
462 let samples = self.substreams[top].blockpos;
463 let channels = self.substreams[top].max_matrix_channel + 1;
464 let layout = ChannelLayout::from_count(channels);
465 if layout == ChannelLayout::Surround7_1 && self.ch8_assignment != 0x4F {
466 return Err(Error::unsupported(
467 format!(
468 "TrueHD 8-channel presentation with channel assignment {:#x}",
469 self.ch8_assignment
470 ),
471 "only the standard 7.1 (L R C LFE Ls Rs Lrs Rrs) assignment is mapped",
472 ));
473 }
474 self.rematrix(top);
475 let frame = self.output(top, layout, samples)?;
476 Ok(Some(frame))
477 }
478
479 /// One substream's segment; `Ok(false)` when no restart header has been
480 /// seen yet (nothing to decode until one arrives).
481 fn decode_substream(&mut self, idx: usize, seg: &[u8], checkdata: bool) -> Result<bool> {
482 let mut br = BitReader::new(seg);
483 self.substreams[idx].blockpos = 0;
484 loop {
485 if br.read_bit()? {
486 if br.read_bit()? {
487 self.read_restart_header(idx, &mut br, seg)?;
488 }
489 if !self.substreams[idx].restart_seen {
490 return Ok(false);
491 }
492 self.read_decoding_params(idx, &mut br)?;
493 }
494 if !self.substreams[idx].restart_seen {
495 return Ok(false);
496 }
497 self.read_block(idx, &mut br)?;
498 if br.bits_remaining() == 0 {
499 self.stats.length_mismatches += 1;
500 return Ok(true);
501 }
502 if br.read_bit()? {
503 break;
504 }
505 }
506 let pad = (16 - (br.bit_position() % 16)) % 16;
507 br.skip_bits(pad)?;
508 if br.bits_remaining() >= 32 && br.peek_bits(32)? == END_OF_STREAM {
509 br.skip_bits(32)?;
510 }
511 if checkdata {
512 let data_len = (br.bit_position() / 8) as usize;
513 if seg.len() < data_len + 2 {
514 return Err(Error::corrupt("TrueHD: substream check bytes missing"));
515 }
516 let parity = seg[..data_len].iter().fold(0u8, |a, &b| a ^ b) ^ 0xA9;
517 let parity_bits = br.read_bits(8)? as u8;
518 // corner-cut: the second check byte is a CRC-8 whose generator
519 // and span this build could not pin down (no plain CRC-8 over
520 // the segment, with any polynomial/init/reflection, matched
521 // either the real track or an external encoder's output) — it
522 // is skipped, not validated. Parity, the restart-header CRC and
523 // the lossless check cover the same data.
524 br.skip_bits(8)?;
525 if parity != parity_bits {
526 self.stats.parity_failures += 1;
527 }
528 }
529 if br.bits_remaining() != 0 {
530 self.stats.length_mismatches += 1;
531 }
532 Ok(true)
533 }
534
535 fn read_restart_header(&mut self, idx: usize, br: &mut BitReader, seg: &[u8]) -> Result<()> {
536 let start = br.bit_position();
537 // 0x31EA / 0x31EB as a 14-bit field: 13 bits of sync, 1 bit of
538 // noise type.
539 let sync = br.read_bits(13)?;
540 if sync != 0x31EA >> 1 {
541 return Err(Error::corrupt(format!("TrueHD: restart sync {sync:#x}")));
542 }
543 let noise_type = br.read_bit()?;
544 br.skip_bits(16)?; // output timing
545 let min_channel = br.read_bits(4)? as usize;
546 let max_channel = br.read_bits(4)? as usize;
547 let max_matrix_channel = br.read_bits(4)? as usize;
548 if max_matrix_channel > MAX_MATRIX_CHANNEL || max_channel > MAX_MATRIX_CHANNEL {
549 return Err(Error::unsupported(
550 "TrueHD substream with more than 8 matrix channels",
551 "the 16-channel object substream is not implemented",
552 ));
553 }
554 if min_channel > max_channel {
555 return Err(Error::corrupt("TrueHD: min channel above max channel"));
556 }
557 let noise_shift = br.read_bits(4)?;
558 let noisegen_seed = br.read_bits(23)?;
559 br.skip_bits(19)?;
560 let data_check_present = br.read_bit()?;
561 let lossless_check = br.read_bits(8)? as u8;
562 br.skip_bits(16)?;
563 // Per matrix channel, the presentation's output slot it lands on;
564 // stored inverted (output slot → matrix channel) for `output`.
565 let mut ch_assign = [0usize; MAX_CHANNELS];
566 for ch in 0..=max_matrix_channel {
567 let a = br.read_bits(6)? as usize;
568 if a > max_matrix_channel {
569 return Err(Error::corrupt("TrueHD: channel assignment out of range"));
570 }
571 ch_assign[a] = ch;
572 }
573 let expected = restart_checksum(&seg[(start / 8) as usize..], br.bit_position() - start);
574 let crc = br.read_bits(8)? as u8;
575 self.stats.restart_headers += 1;
576 if crc != expected {
577 self.stats.restart_crc_failures += 1;
578 }
579
580 let is_top = idx == self.substreams.len() - 1;
581 let s = &mut self.substreams[idx];
582 if s.restart_seen && is_top && xor_32_to_8(s.lossless_check_data) != lossless_check {
583 self.stats.lossless_check_failures += 1;
584 }
585 let s = &mut self.substreams[idx];
586 *s = Substream {
587 restart_seen: true,
588 noise_type,
589 min_channel,
590 max_channel,
591 max_matrix_channel,
592 noise_shift,
593 noisegen_seed,
594 data_check_present,
595 ch_assign,
596 ..Substream::new()
597 };
598 Ok(())
599 }
600
601 fn read_decoding_params(&mut self, idx: usize, br: &mut BitReader) -> Result<()> {
602 let s = &mut self.substreams[idx];
603 if s.param_presence_flags & PARAM_PRESENCE != 0 && br.read_bit()? {
604 s.param_presence_flags = br.read_bits(8)? as u8;
605 }
606 let flags = s.param_presence_flags;
607 if flags & PARAM_BLOCKSIZE != 0 && br.read_bit()? {
608 s.blocksize = br.read_bits(9)? as usize;
609 if s.blocksize < 8 || s.blocksize > self.access_unit_size {
610 return Err(Error::corrupt(format!(
611 "TrueHD: block size {}",
612 s.blocksize
613 )));
614 }
615 }
616 if flags & PARAM_MATRIX != 0 && br.read_bit()? {
617 let count = br.read_bits(4)? as usize;
618 if count > MAX_MATRICES {
619 return Err(Error::corrupt("TrueHD: too many primitive matrices"));
620 }
621 let max_chan = s.max_matrix_channel + if s.noise_type { 0 } else { 2 };
622 s.matrices.clear();
623 for _ in 0..count {
624 let out_ch = br.read_bits(4)? as usize;
625 let frac_bits = br.read_bits(4)?;
626 let lsb_bypass = br.read_bit()?;
627 if out_ch > s.max_matrix_channel || frac_bits > 14 {
628 return Err(Error::corrupt("TrueHD: matrix parameters out of range"));
629 }
630 let mut coeffs = [0i32; MAX_CHANNELS];
631 for c in coeffs.iter_mut().take(max_chan + 1) {
632 if br.read_bit()? {
633 *c = br.read_signed(frac_bits + 2)? << (14 - frac_bits);
634 }
635 }
636 let noise_shift = if s.noise_type { br.read_bits(4)? } else { 0 };
637 s.matrices.push(Matrix {
638 out_ch,
639 lsb_bypass,
640 noise_shift,
641 coeffs,
642 });
643 }
644 }
645 if flags & PARAM_OUTSHIFT != 0 && br.read_bit()? {
646 for ch in 0..=s.max_matrix_channel {
647 s.output_shift[ch] = br.read_signed(4)?;
648 }
649 }
650 if flags & PARAM_QUANTSTEP != 0 && br.read_bit()? {
651 for ch in 0..=s.max_channel {
652 s.quant_step_size[ch] = br.read_bits(4)?;
653 s.recompute_sign_offset(ch);
654 }
655 }
656 for ch in s.min_channel..=s.max_channel {
657 if br.read_bit()? {
658 if flags & PARAM_FIR != 0 && br.read_bit()? {
659 read_filter(br, &mut s.channels[ch].fir, false)?;
660 }
661 if flags & PARAM_IIR != 0 && br.read_bit()? {
662 read_filter(br, &mut s.channels[ch].iir, true)?;
663 }
664 let cp = &s.channels[ch];
665 if cp.fir.order + cp.iir.order > MAX_FILTER_ORDER {
666 return Err(Error::corrupt("TrueHD: FIR+IIR order above 8"));
667 }
668 if cp.fir.order > 0 && cp.iir.order > 0 && cp.fir.shift != cp.iir.shift {
669 return Err(Error::corrupt("TrueHD: FIR and IIR shifts differ"));
670 }
671 if flags & PARAM_HUFFOFFSET != 0 && br.read_bit()? {
672 s.channels[ch].huff_offset = br.read_signed(15)?;
673 }
674 s.channels[ch].codebook = br.read_bits(2)? as u8;
675 s.channels[ch].huff_lsbs = br.read_bits(5)? as u8;
676 if s.channels[ch].huff_lsbs > 24 {
677 return Err(Error::corrupt("TrueHD: huff_lsbs above 24"));
678 }
679 s.recompute_sign_offset(ch);
680 }
681 }
682 Ok(())
683 }
684
685 fn read_block(&mut self, idx: usize, br: &mut BitReader) -> Result<()> {
686 let s = &mut self.substreams[idx];
687 let expected_end = if s.data_check_present {
688 Some(br.bit_position() + u64::from(br.read_bits(16)?))
689 } else {
690 None
691 };
692 if s.blockpos + s.blocksize > self.access_unit_size {
693 return Err(Error::corrupt("TrueHD: blocks exceed the access unit"));
694 }
695 for i in s.blockpos..s.blockpos + s.blocksize {
696 for (m, mat) in s.matrices.iter().enumerate() {
697 if mat.lsb_bypass {
698 self.bypassed_lsbs[i][m] = br.read_bit()? as i32;
699 }
700 }
701 for ch in s.min_channel..=s.max_channel {
702 let cp = &s.channels[ch];
703 let qss = s.quant_step_size[ch];
704 let lsb_bits = i32::from(cp.huff_lsbs) - qss as i32;
705 let mut result = 0i32;
706 if cp.codebook > 0 {
707 result = self.huff.0.decode(br, usize::from(cp.codebook) - 1)?;
708 }
709 if lsb_bits > 0 {
710 result = (result << lsb_bits) + br.read_bits(lsb_bits as u32)? as i32;
711 } else if lsb_bits < 0 {
712 return Err(Error::corrupt("TrueHD: quant step above huff_lsbs"));
713 }
714 result = result.wrapping_add(cp.sign_huff_offset).wrapping_shl(qss);
715 self.sample_buffer[i][ch] = result;
716 }
717 }
718 for ch in s.min_channel..=s.max_channel {
719 filter_channel(
720 &mut s.channels[ch],
721 s.quant_step_size[ch],
722 &mut self.sample_buffer[s.blockpos..s.blockpos + s.blocksize],
723 ch,
724 );
725 }
726 s.blockpos += s.blocksize;
727 if let Some(end) = expected_end {
728 if br.bit_position() != end {
729 self.stats.length_mismatches += 1;
730 }
731 br.skip_bits(8)?;
732 }
733 Ok(())
734 }
735
736 fn rematrix(&mut self, idx: usize) {
737 let s = &mut self.substreams[idx];
738 let mut maxchan = s.max_matrix_channel;
739 if !s.noise_type {
740 // Two noise channels after the last matrix channel, from the
741 // 23-bit generator seeded by the restart header and carried on.
742 let mut seed = s.noisegen_seed;
743 for row in self.sample_buffer.iter_mut().take(s.blockpos) {
744 let shr7 = (seed >> 7) as u16;
745 row[maxchan + 1] = i32::from((seed >> 15) as u8 as i8) << s.noise_shift;
746 row[maxchan + 2] = i32::from(shr7 as u8 as i8) << s.noise_shift;
747 seed = (seed << 16) ^ (u32::from(shr7) << 5) ^ (u32::from(shr7) << 7);
748 }
749 s.noisegen_seed = seed;
750 maxchan += 2;
751 } else {
752 let mut seed = s.noisegen_seed;
753 for slot in self.noise_buffer.iter_mut() {
754 let shr15 = (seed >> 15) as u8;
755 *slot = NOISE_TABLE[usize::from(shr15)];
756 seed = (seed << 8) ^ u32::from(shr15) ^ (u32::from(shr15) << 5);
757 }
758 s.noisegen_seed = seed;
759 }
760 let pow2_mask = self.access_unit_size_pow2 - 1;
761 let count = s.matrices.len();
762 for (m, mat) in s.matrices.iter().enumerate() {
763 let mask = !((1i32 << s.quant_step_size[mat.out_ch]) - 1);
764 let mut index = count - m;
765 let index2 = 2 * index + 1;
766 for (i, row) in self.sample_buffer.iter_mut().take(s.blockpos).enumerate() {
767 let mut accum: i64 = 0;
768 for (sample, coeff) in row.iter().zip(&mat.coeffs).take(maxchan + 1) {
769 accum += i64::from(*sample) * i64::from(*coeff);
770 }
771 if mat.noise_shift != 0 {
772 index &= pow2_mask;
773 accum += i64::from(self.noise_buffer[index]) << (mat.noise_shift + 7);
774 index += index2;
775 }
776 row[mat.out_ch] = ((accum >> 14) as i32 & mask) + self.bypassed_lsbs[i][m];
777 }
778 }
779 }
780
781 fn output(&mut self, idx: usize, layout: ChannelLayout, samples: usize) -> Result<AudioFrame> {
782 let s = &mut self.substreams[idx];
783 let channels = layout.channel_count();
784 // TrueHD's Ls/Rs (output 4,5) are our side pair, Lrs/Rrs (6,7) our
785 // back pair.
786 const PERM_7_1: [usize; 8] = [0, 1, 2, 3, 6, 7, 4, 5];
787 let mut bytes = Vec::with_capacity(samples * channels * 4);
788 for row in self.sample_buffer.iter().take(samples) {
789 for (out_ch, &perm) in PERM_7_1.iter().enumerate().take(channels) {
790 let thd_ch = if channels == 8 { perm } else { out_ch };
791 let mat_ch = s.ch_assign[thd_ch];
792 let sample = row[mat_ch].wrapping_shl(s.output_shift[mat_ch] as u32);
793 s.lossless_check_data ^= ((sample as u32) & 0xFF_FFFF) << mat_ch;
794 bytes.extend_from_slice(&(sample << 8).to_ne_bytes());
795 }
796 }
797 AudioFrame::try_new(
798 SampleFormat::S32,
799 false,
800 layout,
801 self.sample_rate,
802 samples,
803 vec![Buf::from_vec(bytes)],
804 )
805 }
806}
807
808/// New coefficients for `f`; its history carries over unless the stream
809/// sends an explicit (IIR-only) state.
810fn read_filter(br: &mut BitReader, f: &mut Filter, iir: bool) -> Result<()> {
811 f.order = br.read_bits(4)? as usize;
812 if f.order > MAX_FILTER_ORDER || (!iir && f.order > 8) || (iir && f.order > 4) {
813 return Err(Error::corrupt("TrueHD: filter order out of range"));
814 }
815 if f.order > 0 {
816 f.shift = br.read_bits(4)?;
817 let coeff_bits = br.read_bits(5)?;
818 let coeff_shift = br.read_bits(3)?;
819 if !(1..=16).contains(&coeff_bits) || coeff_bits + coeff_shift > 16 {
820 return Err(Error::corrupt(
821 "TrueHD: filter coefficient precision out of range",
822 ));
823 }
824 for c in f.coeffs.iter_mut().take(f.order) {
825 *c = br.read_signed(coeff_bits)? << coeff_shift;
826 }
827 if br.read_bit()? {
828 if !iir {
829 return Err(Error::corrupt("TrueHD: FIR filter with explicit state"));
830 }
831 let state_bits = br.read_bits(4)?;
832 let state_shift = br.read_bits(4)?;
833 for st in f.state.iter_mut().take(f.order) {
834 *st = if state_bits > 0 {
835 br.read_signed(state_bits)? << state_shift
836 } else {
837 0
838 };
839 }
840 }
841 }
842 Ok(())
843}
844
845/// Residual → sample through the channel's FIR (over past samples) and IIR
846/// (over past residual-after-prediction) filters, in place on column `ch`.
847fn filter_channel(cp: &mut ChannelParams, qss: u32, rows: &mut [[i32; MAX_CHANNELS]], ch: usize) {
848 let mask = !((1i32 << qss) - 1);
849 let shift = if cp.fir.order > 0 {
850 cp.fir.shift
851 } else {
852 cp.iir.shift
853 };
854 for row in rows {
855 let mut accum: i64 = 0;
856 for j in 0..cp.fir.order {
857 accum += i64::from(cp.fir.state[j]) * i64::from(cp.fir.coeffs[j]);
858 }
859 for j in 0..cp.iir.order {
860 accum += i64::from(cp.iir.state[j]) * i64::from(cp.iir.coeffs[j]);
861 }
862 let accum = (accum >> shift) as i32;
863 let result = accum.wrapping_add(row[ch]) & mask;
864 cp.fir.state.copy_within(0..MAX_FILTER_ORDER - 1, 1);
865 cp.fir.state[0] = result;
866 cp.iir.state.copy_within(0..MAX_FILTER_ORDER - 1, 1);
867 cp.iir.state[0] = result.wrapping_sub(accum);
868 row[ch] = result;
869 }
870}
871
872#[cfg(test)]
873mod tests {
874 use super::*;
875
876 /// Every code in the public tables decodes back to its own index when
877 /// written bit-exactly, with and without trailing garbage.
878 #[test]
879 fn every_codebook_entry_decodes_to_its_index() {
880 use ec_core::bitio::BitWriter;
881 let lut = HuffLut::build();
882 for (book, table) in HUFFMAN_TABLES.iter().enumerate() {
883 for (index, &(code, len)) in table.iter().enumerate() {
884 if len == 0 {
885 continue;
886 }
887 let mut w = BitWriter::new();
888 w.write_bits(u32::from(code), u32::from(len));
889 w.write_bits(0x5A5, 11);
890 let bytes = w.into_bytes();
891 let mut br = BitReader::new(&bytes);
892 assert_eq!(
893 lut.decode(&mut br, book).unwrap(),
894 index as i32,
895 "book {book} index {index}"
896 );
897 assert_eq!(br.bit_position(), u64::from(len));
898 // Bare code at the very end of the buffer must decode too.
899 let mut w = BitWriter::new();
900 w.write_bits(u32::from(code), u32::from(len));
901 let bytes = w.into_bytes();
902 let mut br = BitReader::new(&bytes);
903 assert_eq!(lut.decode(&mut br, book).unwrap(), index as i32);
904 }
905 }
906 // An all-zero 9-bit word is not a code in any book.
907 for book in 0..3 {
908 assert!(lut.decode(&mut BitReader::new(&[0, 0]), book).is_err());
909 }
910 }
911
912 #[test]
913 fn codebooks_are_prefix_free() {
914 for table in &HUFFMAN_TABLES {
915 let used: Vec<_> = table.iter().filter(|e| e.1 > 0).collect();
916 for (i, a) in used.iter().enumerate() {
917 for b in &used[i + 1..] {
918 let l = a.1.min(b.1);
919 assert_ne!(a.0 >> (a.1 - l), b.0 >> (b.1 - l), "{a:?} vs {b:?}");
920 }
921 }
922 }
923 }
924}