forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBe83e29aTahinli2 months ago2365 commits

decode.rs943 lines, 35.9 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;
69pub(crate) const 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 // A restart header resets every decoding *parameter* (order,
587 // codebook, huff_lsbs, ...) to its spec default, but — per ffmpeg's
588 // `read_restart_header` (mlpdec.c), which `memset`s
589 // `output_shift`/`quant_step_size`/per-channel param fields but
590 // never touches `filter_params[FIR/IIR].state` — the FIR/IIR
591 // predictor's *history* (the actual past decoded samples) is a
592 // rolling buffer `filter_channel` maintains every block regardless
593 // of the channel's current order, and survives every restart
594 // header in an access-unit stream. Zeroing it here (this crate's
595 // previous behaviour) was self-consistent with our own encoder's
596 // matching per-AU-fresh-history assumption but diverges from a
597 // real MLP/TrueHD stream from AU 2 onward whenever a channel uses
598 // a nonzero-order filter.
599 let old_states: [(Filter, Filter); MAX_CHANNELS] =
600 std::array::from_fn(|ch| (s.channels[ch].fir, s.channels[ch].iir));
601 *s = Substream {
602 restart_seen: true,
603 noise_type,
604 min_channel,
605 max_channel,
606 max_matrix_channel,
607 noise_shift,
608 noisegen_seed,
609 data_check_present,
610 ch_assign,
611 ..Substream::new()
612 };
613 for (ch, (old_fir, old_iir)) in old_states.into_iter().enumerate() {
614 s.channels[ch].fir.state = old_fir.state;
615 s.channels[ch].iir.state = old_iir.state;
616 }
617 Ok(())
618 }
619
620 fn read_decoding_params(&mut self, idx: usize, br: &mut BitReader) -> Result<()> {
621 let s = &mut self.substreams[idx];
622 if s.param_presence_flags & PARAM_PRESENCE != 0 && br.read_bit()? {
623 s.param_presence_flags = br.read_bits(8)? as u8;
624 }
625 let flags = s.param_presence_flags;
626 if flags & PARAM_BLOCKSIZE != 0 && br.read_bit()? {
627 s.blocksize = br.read_bits(9)? as usize;
628 if s.blocksize < 8 || s.blocksize > self.access_unit_size {
629 return Err(Error::corrupt(format!(
630 "TrueHD: block size {}",
631 s.blocksize
632 )));
633 }
634 }
635 if flags & PARAM_MATRIX != 0 && br.read_bit()? {
636 let count = br.read_bits(4)? as usize;
637 if count > MAX_MATRICES {
638 return Err(Error::corrupt("TrueHD: too many primitive matrices"));
639 }
640 let max_chan = s.max_matrix_channel + if s.noise_type { 0 } else { 2 };
641 s.matrices.clear();
642 for _ in 0..count {
643 let out_ch = br.read_bits(4)? as usize;
644 let frac_bits = br.read_bits(4)?;
645 let lsb_bypass = br.read_bit()?;
646 if out_ch > s.max_matrix_channel || frac_bits > 14 {
647 return Err(Error::corrupt("TrueHD: matrix parameters out of range"));
648 }
649 let mut coeffs = [0i32; MAX_CHANNELS];
650 for c in coeffs.iter_mut().take(max_chan + 1) {
651 if br.read_bit()? {
652 *c = br.read_signed(frac_bits + 2)? << (14 - frac_bits);
653 }
654 }
655 let noise_shift = if s.noise_type { br.read_bits(4)? } else { 0 };
656 s.matrices.push(Matrix {
657 out_ch,
658 lsb_bypass,
659 noise_shift,
660 coeffs,
661 });
662 }
663 }
664 if flags & PARAM_OUTSHIFT != 0 && br.read_bit()? {
665 for ch in 0..=s.max_matrix_channel {
666 s.output_shift[ch] = br.read_signed(4)?;
667 }
668 }
669 if flags & PARAM_QUANTSTEP != 0 && br.read_bit()? {
670 for ch in 0..=s.max_channel {
671 s.quant_step_size[ch] = br.read_bits(4)?;
672 s.recompute_sign_offset(ch);
673 }
674 }
675 for ch in s.min_channel..=s.max_channel {
676 if br.read_bit()? {
677 if flags & PARAM_FIR != 0 && br.read_bit()? {
678 read_filter(br, &mut s.channels[ch].fir, false)?;
679 }
680 if flags & PARAM_IIR != 0 && br.read_bit()? {
681 read_filter(br, &mut s.channels[ch].iir, true)?;
682 }
683 let cp = &s.channels[ch];
684 if cp.fir.order + cp.iir.order > MAX_FILTER_ORDER {
685 return Err(Error::corrupt("TrueHD: FIR+IIR order above 8"));
686 }
687 if cp.fir.order > 0 && cp.iir.order > 0 && cp.fir.shift != cp.iir.shift {
688 return Err(Error::corrupt("TrueHD: FIR and IIR shifts differ"));
689 }
690 if flags & PARAM_HUFFOFFSET != 0 && br.read_bit()? {
691 s.channels[ch].huff_offset = br.read_signed(15)?;
692 }
693 s.channels[ch].codebook = br.read_bits(2)? as u8;
694 s.channels[ch].huff_lsbs = br.read_bits(5)? as u8;
695 if s.channels[ch].huff_lsbs > 24 {
696 return Err(Error::corrupt("TrueHD: huff_lsbs above 24"));
697 }
698 s.recompute_sign_offset(ch);
699 }
700 }
701 Ok(())
702 }
703
704 fn read_block(&mut self, idx: usize, br: &mut BitReader) -> Result<()> {
705 let s = &mut self.substreams[idx];
706 let expected_end = if s.data_check_present {
707 Some(br.bit_position() + u64::from(br.read_bits(16)?))
708 } else {
709 None
710 };
711 if s.blockpos + s.blocksize > self.access_unit_size {
712 return Err(Error::corrupt("TrueHD: blocks exceed the access unit"));
713 }
714 for i in s.blockpos..s.blockpos + s.blocksize {
715 for (m, mat) in s.matrices.iter().enumerate() {
716 if mat.lsb_bypass {
717 self.bypassed_lsbs[i][m] = br.read_bit()? as i32;
718 }
719 }
720 for ch in s.min_channel..=s.max_channel {
721 let cp = &s.channels[ch];
722 let qss = s.quant_step_size[ch];
723 let lsb_bits = i32::from(cp.huff_lsbs) - qss as i32;
724 let mut result = 0i32;
725 if cp.codebook > 0 {
726 result = self.huff.0.decode(br, usize::from(cp.codebook) - 1)?;
727 }
728 if lsb_bits > 0 {
729 result = (result << lsb_bits) + br.read_bits(lsb_bits as u32)? as i32;
730 } else if lsb_bits < 0 {
731 return Err(Error::corrupt("TrueHD: quant step above huff_lsbs"));
732 }
733 result = result.wrapping_add(cp.sign_huff_offset).wrapping_shl(qss);
734 self.sample_buffer[i][ch] = result;
735 }
736 }
737 for ch in s.min_channel..=s.max_channel {
738 filter_channel(
739 &mut s.channels[ch],
740 s.quant_step_size[ch],
741 &mut self.sample_buffer[s.blockpos..s.blockpos + s.blocksize],
742 ch,
743 );
744 }
745 s.blockpos += s.blocksize;
746 if let Some(end) = expected_end {
747 if br.bit_position() != end {
748 self.stats.length_mismatches += 1;
749 }
750 br.skip_bits(8)?;
751 }
752 Ok(())
753 }
754
755 fn rematrix(&mut self, idx: usize) {
756 let s = &mut self.substreams[idx];
757 let mut maxchan = s.max_matrix_channel;
758 if !s.noise_type {
759 // Two noise channels after the last matrix channel, from the
760 // 23-bit generator seeded by the restart header and carried on.
761 let mut seed = s.noisegen_seed;
762 for row in self.sample_buffer.iter_mut().take(s.blockpos) {
763 let shr7 = (seed >> 7) as u16;
764 row[maxchan + 1] = i32::from((seed >> 15) as u8 as i8) << s.noise_shift;
765 row[maxchan + 2] = i32::from(shr7 as u8 as i8) << s.noise_shift;
766 seed = (seed << 16) ^ (u32::from(shr7) << 5) ^ (u32::from(shr7) << 7);
767 }
768 s.noisegen_seed = seed;
769 maxchan += 2;
770 } else {
771 let mut seed = s.noisegen_seed;
772 for slot in self.noise_buffer.iter_mut() {
773 let shr15 = (seed >> 15) as u8;
774 *slot = NOISE_TABLE[usize::from(shr15)];
775 seed = (seed << 8) ^ u32::from(shr15) ^ (u32::from(shr15) << 5);
776 }
777 s.noisegen_seed = seed;
778 }
779 let pow2_mask = self.access_unit_size_pow2 - 1;
780 let count = s.matrices.len();
781 for (m, mat) in s.matrices.iter().enumerate() {
782 let mask = !((1i32 << s.quant_step_size[mat.out_ch]) - 1);
783 let mut index = count - m;
784 let index2 = 2 * index + 1;
785 for (i, row) in self.sample_buffer.iter_mut().take(s.blockpos).enumerate() {
786 let mut accum: i64 = 0;
787 for (sample, coeff) in row.iter().zip(&mat.coeffs).take(maxchan + 1) {
788 accum += i64::from(*sample) * i64::from(*coeff);
789 }
790 if mat.noise_shift != 0 {
791 index &= pow2_mask;
792 accum += i64::from(self.noise_buffer[index]) << (mat.noise_shift + 7);
793 index += index2;
794 }
795 row[mat.out_ch] = ((accum >> 14) as i32 & mask) + self.bypassed_lsbs[i][m];
796 }
797 }
798 }
799
800 fn output(&mut self, idx: usize, layout: ChannelLayout, samples: usize) -> Result<AudioFrame> {
801 let s = &mut self.substreams[idx];
802 let channels = layout.channel_count();
803 // TrueHD's Ls/Rs (output 4,5) are our side pair, Lrs/Rrs (6,7) our
804 // back pair.
805 const PERM_7_1: [usize; 8] = [0, 1, 2, 3, 6, 7, 4, 5];
806 let mut bytes = Vec::with_capacity(samples * channels * 4);
807 for row in self.sample_buffer.iter().take(samples) {
808 for (out_ch, &perm) in PERM_7_1.iter().enumerate().take(channels) {
809 let thd_ch = if channels == 8 { perm } else { out_ch };
810 let mat_ch = s.ch_assign[thd_ch];
811 let sample = row[mat_ch].wrapping_shl(s.output_shift[mat_ch] as u32);
812 s.lossless_check_data ^= ((sample as u32) & 0xFF_FFFF) << mat_ch;
813 bytes.extend_from_slice(&(sample << 8).to_ne_bytes());
814 }
815 }
816 AudioFrame::try_new(
817 SampleFormat::S32,
818 false,
819 layout,
820 self.sample_rate,
821 samples,
822 vec![Buf::from_vec(bytes)],
823 )
824 }
825}
826
827/// New coefficients for `f`; its history carries over unless the stream
828/// sends an explicit (IIR-only) state.
829fn read_filter(br: &mut BitReader, f: &mut Filter, iir: bool) -> Result<()> {
830 f.order = br.read_bits(4)? as usize;
831 if f.order > MAX_FILTER_ORDER || (!iir && f.order > 8) || (iir && f.order > 4) {
832 return Err(Error::corrupt("TrueHD: filter order out of range"));
833 }
834 if f.order > 0 {
835 f.shift = br.read_bits(4)?;
836 let coeff_bits = br.read_bits(5)?;
837 let coeff_shift = br.read_bits(3)?;
838 if !(1..=16).contains(&coeff_bits) || coeff_bits + coeff_shift > 16 {
839 return Err(Error::corrupt(
840 "TrueHD: filter coefficient precision out of range",
841 ));
842 }
843 for c in f.coeffs.iter_mut().take(f.order) {
844 *c = br.read_signed(coeff_bits)? << coeff_shift;
845 }
846 if br.read_bit()? {
847 if !iir {
848 return Err(Error::corrupt("TrueHD: FIR filter with explicit state"));
849 }
850 let state_bits = br.read_bits(4)?;
851 let state_shift = br.read_bits(4)?;
852 for st in f.state.iter_mut().take(f.order) {
853 *st = if state_bits > 0 {
854 br.read_signed(state_bits)? << state_shift
855 } else {
856 0
857 };
858 }
859 }
860 }
861 Ok(())
862}
863
864/// Residual → sample through the channel's FIR (over past samples) and IIR
865/// (over past residual-after-prediction) filters, in place on column `ch`.
866fn filter_channel(cp: &mut ChannelParams, qss: u32, rows: &mut [[i32; MAX_CHANNELS]], ch: usize) {
867 let mask = !((1i32 << qss) - 1);
868 let shift = if cp.fir.order > 0 {
869 cp.fir.shift
870 } else {
871 cp.iir.shift
872 };
873 for row in rows {
874 let mut accum: i64 = 0;
875 for j in 0..cp.fir.order {
876 accum += i64::from(cp.fir.state[j]) * i64::from(cp.fir.coeffs[j]);
877 }
878 for j in 0..cp.iir.order {
879 accum += i64::from(cp.iir.state[j]) * i64::from(cp.iir.coeffs[j]);
880 }
881 let accum = (accum >> shift) as i32;
882 let result = accum.wrapping_add(row[ch]) & mask;
883 cp.fir.state.copy_within(0..MAX_FILTER_ORDER - 1, 1);
884 cp.fir.state[0] = result;
885 cp.iir.state.copy_within(0..MAX_FILTER_ORDER - 1, 1);
886 cp.iir.state[0] = result.wrapping_sub(accum);
887 row[ch] = result;
888 }
889}
890
891#[cfg(test)]
892mod tests {
893 use super::*;
894
895 /// Every code in the public tables decodes back to its own index when
896 /// written bit-exactly, with and without trailing garbage.
897 #[test]
898 fn every_codebook_entry_decodes_to_its_index() {
899 use ec_core::bitio::BitWriter;
900 let lut = HuffLut::build();
901 for (book, table) in HUFFMAN_TABLES.iter().enumerate() {
902 for (index, &(code, len)) in table.iter().enumerate() {
903 if len == 0 {
904 continue;
905 }
906 let mut w = BitWriter::new();
907 w.write_bits(u32::from(code), u32::from(len));
908 w.write_bits(0x5A5, 11);
909 let bytes = w.into_bytes();
910 let mut br = BitReader::new(&bytes);
911 assert_eq!(
912 lut.decode(&mut br, book).unwrap(),
913 index as i32,
914 "book {book} index {index}"
915 );
916 assert_eq!(br.bit_position(), u64::from(len));
917 // Bare code at the very end of the buffer must decode too.
918 let mut w = BitWriter::new();
919 w.write_bits(u32::from(code), u32::from(len));
920 let bytes = w.into_bytes();
921 let mut br = BitReader::new(&bytes);
922 assert_eq!(lut.decode(&mut br, book).unwrap(), index as i32);
923 }
924 }
925 // An all-zero 9-bit word is not a code in any book.
926 for book in 0..3 {
927 assert!(lut.decode(&mut BitReader::new(&[0, 0]), book).is_err());
928 }
929 }
930
931 #[test]
932 fn codebooks_are_prefix_free() {
933 for table in &HUFFMAN_TABLES {
934 let used: Vec<_> = table.iter().filter(|e| e.1 > 0).collect();
935 for (i, a) in used.iter().enumerate() {
936 for b in &used[i + 1..] {
937 let l = a.1.min(b.1);
938 assert_ne!(a.0 >> (a.1 - l), b.0 >> (b.1 - l), "{a:?} vs {b:?}");
939 }
940 }
941 }
942 }
943}