forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

decode.rs1064 lines, 41.4 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, PCM_SUBSTREAMS};
61
62/// Highest matrix/output channel index the 2/6/8-channel presentations use;
63/// a PCM substream asking for more is refused (none of them has more than 8).
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) -> Result<()> {
324 let cp = &mut self.channels[ch];
325 let lsb_bits = i32::from(cp.huff_lsbs) - self.quant_step_size[ch] as i32;
326 // A quant step above huff_lsbs is refused in read_block before this offset is used. It
327 // is called before huff_lsbs is re-read, so this must not shift by a negative amount.
328 if lsb_bits < 0 {
329 cp.sign_huff_offset = 0;
330 return Ok(());
331 }
332 // huff_lsbs is checked against 24 after it is read, but this call can run first, on the
333 // value a refused access unit left behind. Above 24, `7 << lsb_bits` overflows i32.
334 if lsb_bits > 24 {
335 return Err(Error::corrupt("TrueHD: huff_lsbs above 24"));
336 }
337 let sign_shift = lsb_bits
338 + if cp.codebook > 0 {
339 2 - i32::from(cp.codebook)
340 } else {
341 -1
342 };
343 let mut off = cp.huff_offset;
344 if cp.codebook > 0 {
345 off -= 7 << lsb_bits;
346 }
347 if sign_shift >= 0 {
348 off -= 1 << sign_shift;
349 }
350 cp.sign_huff_offset = off;
351 Ok(())
352 }
353}
354
355/// Integrity counters the decoder keeps across access units; every one is a
356/// stream-side self-check that stays zero on a clean decode.
357#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
358pub struct CheckStats {
359 /// Restart headers whose CRC-8 did not match.
360 pub restart_crc_failures: u64,
361 /// Restart headers seen (the lossless-check byte is verified at each
362 /// one after the first, against the samples output since the previous).
363 pub restart_headers: u64,
364 /// Lossless-check bytes that did not match the output.
365 pub lossless_check_failures: u64,
366 /// Substream segments whose parity byte did not match.
367 pub parity_failures: u64,
368 /// Substream segments whose bit count did not land on the directory's
369 /// end pointer.
370 pub length_mismatches: u64,
371}
372
373/// How many of an access unit's directory entries are PCM presentations this
374/// decoder reconstructs: all of them up to [`PCM_SUBSTREAMS`]; any entry past
375/// that (Atmos object audio) is skipped via its end pointer, never decoded.
376fn decoded_substreams(header: &AccessUnitHeader) -> usize {
377 header.substreams.len().min(PCM_SUBSTREAMS)
378}
379
380/// Decoder state shared across the substreams of one stream.
381#[derive(Debug, Clone)]
382pub(crate) struct Core {
383 huff: std::sync::Arc<HuffLutBox>,
384 substreams: Vec<Substream>,
385 /// Samples per access unit (40 at 48 kHz) and its next power of two.
386 access_unit_size: usize,
387 access_unit_size_pow2: usize,
388 sample_rate: u32,
389 /// The major sync's 8-channel presentation assignment mask.
390 ch8_assignment: u16,
391 sample_buffer: Vec<[i32; MAX_CHANNELS]>,
392 bypassed_lsbs: Vec<[i32; MAX_MATRICES]>,
393 noise_buffer: Vec<i8>,
394 /// Self-check tallies.
395 pub stats: CheckStats,
396}
397
398/// [`Core`] state saved before an access unit, restored if the unit is refused.
399#[derive(Debug, Clone)]
400struct Snapshot {
401 substreams: Vec<Substream>,
402 access_unit_size: usize,
403 access_unit_size_pow2: usize,
404 sample_rate: u32,
405 ch8_assignment: u16,
406}
407
408struct HuffLutBox(HuffLut);
409
410impl std::fmt::Debug for HuffLutBox {
411 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
412 f.write_str("HuffLut")
413 }
414}
415
416impl Core {
417 pub(crate) fn new() -> Core {
418 Core {
419 huff: std::sync::Arc::new(HuffLutBox(HuffLut::build())),
420 substreams: Vec::new(),
421 access_unit_size: 0,
422 access_unit_size_pow2: 0,
423 sample_rate: 0,
424 ch8_assignment: 0,
425 sample_buffer: Vec::new(),
426 bypassed_lsbs: Vec::new(),
427 noise_buffer: Vec::new(),
428 stats: CheckStats::default(),
429 }
430 }
431
432 pub(crate) fn reset(&mut self) {
433 self.substreams.clear();
434 self.access_unit_size = 0;
435 }
436
437 /// Decodes one access unit whose header already parsed; `None` until the
438 /// first major sync and every substream's first restart header are seen.
439 ///
440 /// A refused unit leaves no trace: the stream state is restored to what it was before the
441 /// unit, so later units decode as if the refused one had never been sent. Without this, a
442 /// unit refused part-way through a parameter block leaves a stale `huff_lsbs`, codebook or
443 /// filter history behind, and every following unit is refused or decoded wrongly.
444 pub(crate) fn decode(
445 &mut self,
446 header: &AccessUnitHeader,
447 data: &[u8],
448 ) -> Result<Option<AudioFrame>> {
449 let saved = self.snapshot();
450 let result = self.decode_unit(header, data);
451 if result.is_err() {
452 self.restore(saved);
453 }
454 result
455 }
456
457 fn decode_unit(&mut self, header: &AccessUnitHeader, data: &[u8]) -> Result<Option<AudioFrame>> {
458 if !self.prepare(header)? || !self.decode_substreams(header, data)? {
459 return Ok(None);
460 }
461 self.finish()
462 }
463
464 /// The state a refused access unit may have changed: the substreams (parameters, filter
465 /// history, noise generator, check data) and the stream format from the major sync.
466 fn snapshot(&self) -> Snapshot {
467 Snapshot {
468 substreams: self.substreams.clone(),
469 access_unit_size: self.access_unit_size,
470 access_unit_size_pow2: self.access_unit_size_pow2,
471 sample_rate: self.sample_rate,
472 ch8_assignment: self.ch8_assignment,
473 }
474 }
475
476 fn restore(&mut self, saved: Snapshot) {
477 self.substreams = saved.substreams;
478 self.access_unit_size = saved.access_unit_size;
479 self.access_unit_size_pow2 = saved.access_unit_size_pow2;
480 self.sample_rate = saved.sample_rate;
481 self.ch8_assignment = saved.ch8_assignment;
482 // The scratch buffers follow the restored unit size; their contents are rebuilt per unit.
483 if self.sample_buffer.len() != self.access_unit_size {
484 self.sample_buffer = vec![[0; MAX_CHANNELS]; self.access_unit_size];
485 self.bypassed_lsbs = vec![[0; MAX_MATRICES]; self.access_unit_size];
486 self.noise_buffer = vec![0; self.access_unit_size_pow2];
487 }
488 }
489
490 /// Takes a major sync's stream parameters on board; `Ok(false)` while no
491 /// major sync has been seen yet.
492 fn prepare(&mut self, header: &AccessUnitHeader) -> Result<bool> {
493 let pcm = decoded_substreams(header);
494 if let Some(sync) = &header.major_sync {
495 let shift = sync.rate_code & 7;
496 if shift > 2 {
497 return Err(Error::unsupported(
498 format!("TrueHD sample rate code {}", sync.rate_code),
499 "the format reserves it",
500 ));
501 }
502 self.access_unit_size = 40 << shift;
503 self.access_unit_size_pow2 = 64 << shift;
504 self.sample_rate = sync.sample_rate;
505 if self.substreams.len() != pcm {
506 self.substreams = vec![Substream::new(); pcm];
507 }
508 self.sample_buffer = vec![[0; MAX_CHANNELS]; self.access_unit_size];
509 self.bypassed_lsbs = vec![[0; MAX_MATRICES]; self.access_unit_size];
510 self.noise_buffer = vec![0; self.access_unit_size_pow2];
511 self.ch8_assignment = sync.ch8_assignment;
512 }
513 Ok(self.access_unit_size != 0 && self.substreams.len() == pcm)
514 }
515
516 /// Every PCM substream's blocks into `sample_buffer`; `Ok(false)` while
517 /// some substream still awaits its first restart header. Substreams past
518 /// the PCM presentations (an Atmos object substream) are not decoded.
519 fn decode_substreams(&mut self, header: &AccessUnitHeader, data: &[u8]) -> Result<bool> {
520 let mut all_seen = true;
521 for (i, info) in header.substreams.iter().enumerate().take(PCM_SUBSTREAMS) {
522 let (start, end) = header.substream_span(i);
523 let seg = data.get(start..end).ok_or(Error::NeedMore)?;
524 let seen = self.decode_substream(i, seg, info.flags & 0x2 != 0)?;
525 all_seen &= seen;
526 }
527 Ok(all_seen)
528 }
529
530 /// Rematrix + output of the top substream for the current access unit.
531 fn finish(&mut self) -> Result<Option<AudioFrame>> {
532 let top = self.substreams.len() - 1;
533 let samples = self.substreams[top].blockpos;
534 let channels = self.substreams[top].max_matrix_channel + 1;
535 let layout = ChannelLayout::from_count(channels);
536 if layout == ChannelLayout::Surround7_1 && self.ch8_assignment != 0x4F {
537 return Err(Error::unsupported(
538 format!(
539 "TrueHD 8-channel presentation with channel assignment {:#x}",
540 self.ch8_assignment
541 ),
542 "only the standard 7.1 (L R C LFE Ls Rs Lrs Rrs) assignment is mapped",
543 ));
544 }
545 self.rematrix(top);
546 let frame = self.output(top, layout, samples)?;
547 Ok(Some(frame))
548 }
549
550 /// One substream's segment; `Ok(false)` when no restart header has been
551 /// seen yet (nothing to decode until one arrives).
552 fn decode_substream(&mut self, idx: usize, seg: &[u8], checkdata: bool) -> Result<bool> {
553 let mut br = BitReader::new(seg);
554 self.substreams[idx].blockpos = 0;
555 loop {
556 if br.read_bit()? {
557 if br.read_bit()? {
558 self.read_restart_header(idx, &mut br, seg)?;
559 }
560 if !self.substreams[idx].restart_seen {
561 return Ok(false);
562 }
563 self.read_decoding_params(idx, &mut br)?;
564 }
565 if !self.substreams[idx].restart_seen {
566 return Ok(false);
567 }
568 self.read_block(idx, &mut br)?;
569 if br.bits_remaining() == 0 {
570 self.stats.length_mismatches += 1;
571 return Ok(true);
572 }
573 if br.read_bit()? {
574 break;
575 }
576 }
577 let pad = (16 - (br.bit_position() % 16)) % 16;
578 br.skip_bits(pad)?;
579 if br.bits_remaining() >= 32 && br.peek_bits(32)? == END_OF_STREAM {
580 br.skip_bits(32)?;
581 }
582 if checkdata {
583 let data_len = (br.bit_position() / 8) as usize;
584 if seg.len() < data_len + 2 {
585 return Err(Error::corrupt("TrueHD: substream check bytes missing"));
586 }
587 let parity = seg[..data_len].iter().fold(0u8, |a, &b| a ^ b) ^ 0xA9;
588 let parity_bits = br.read_bits(8)? as u8;
589 // corner-cut: the second check byte is a CRC-8 whose generator
590 // and span this build could not pin down (no plain CRC-8 over
591 // the segment, with any polynomial/init/reflection, matched
592 // either the real track or an external encoder's output) — it
593 // is skipped, not validated. Parity, the restart-header CRC and
594 // the lossless check cover the same data.
595 br.skip_bits(8)?;
596 if parity != parity_bits {
597 self.stats.parity_failures += 1;
598 }
599 }
600 if br.bits_remaining() != 0 {
601 self.stats.length_mismatches += 1;
602 }
603 Ok(true)
604 }
605
606 fn read_restart_header(&mut self, idx: usize, br: &mut BitReader, seg: &[u8]) -> Result<()> {
607 let start = br.bit_position();
608 // 0x31EA / 0x31EB as a 14-bit field: 13 bits of sync, 1 bit of
609 // noise type.
610 let sync = br.read_bits(13)?;
611 if sync != 0x31EA >> 1 {
612 return Err(Error::corrupt(format!("TrueHD: restart sync {sync:#x}")));
613 }
614 let noise_type = br.read_bit()?;
615 br.skip_bits(16)?; // output timing
616 let min_channel = br.read_bits(4)? as usize;
617 let max_channel = br.read_bits(4)? as usize;
618 let max_matrix_channel = br.read_bits(4)? as usize;
619 if max_matrix_channel > MAX_MATRIX_CHANNEL || max_channel > MAX_MATRIX_CHANNEL {
620 return Err(Error::unsupported(
621 "TrueHD substream with more than 8 matrix channels",
622 "no PCM presentation carries more than 8 channels",
623 ));
624 }
625 if min_channel > max_channel {
626 return Err(Error::corrupt("TrueHD: min channel above max channel"));
627 }
628 let noise_shift = br.read_bits(4)?;
629 let noisegen_seed = br.read_bits(23)?;
630 br.skip_bits(19)?;
631 let data_check_present = br.read_bit()?;
632 let lossless_check = br.read_bits(8)? as u8;
633 br.skip_bits(16)?;
634 // Per matrix channel, the presentation's output slot it lands on;
635 // stored inverted (output slot → matrix channel) for `output`.
636 let mut ch_assign = [0usize; MAX_CHANNELS];
637 for ch in 0..=max_matrix_channel {
638 let a = br.read_bits(6)? as usize;
639 if a > max_matrix_channel {
640 return Err(Error::corrupt("TrueHD: channel assignment out of range"));
641 }
642 ch_assign[a] = ch;
643 }
644 let expected = restart_checksum(&seg[(start / 8) as usize..], br.bit_position() - start);
645 let crc = br.read_bits(8)? as u8;
646 self.stats.restart_headers += 1;
647 if crc != expected {
648 self.stats.restart_crc_failures += 1;
649 }
650
651 let is_top = idx == self.substreams.len() - 1;
652 let s = &mut self.substreams[idx];
653 if s.restart_seen && is_top && xor_32_to_8(s.lossless_check_data) != lossless_check {
654 self.stats.lossless_check_failures += 1;
655 }
656 let s = &mut self.substreams[idx];
657 // A restart header resets every decoding *parameter* (order,
658 // codebook, huff_lsbs, ...) to its spec default, but — per ffmpeg's
659 // `read_restart_header` (mlpdec.c), which `memset`s
660 // `output_shift`/`quant_step_size`/per-channel param fields but
661 // never touches `filter_params[FIR/IIR].state` — the FIR/IIR
662 // predictor's *history* (the actual past decoded samples) is a
663 // rolling buffer `filter_channel` maintains every block regardless
664 // of the channel's current order, and survives every restart
665 // header in an access-unit stream. Zeroing it here (this crate's
666 // previous behaviour) was self-consistent with our own encoder's
667 // matching per-AU-fresh-history assumption but diverges from a
668 // real MLP/TrueHD stream from AU 2 onward whenever a channel uses
669 // a nonzero-order filter.
670 let old_states: [(Filter, Filter); MAX_CHANNELS] =
671 std::array::from_fn(|ch| (s.channels[ch].fir, s.channels[ch].iir));
672 *s = Substream {
673 restart_seen: true,
674 noise_type,
675 min_channel,
676 max_channel,
677 max_matrix_channel,
678 noise_shift,
679 noisegen_seed,
680 data_check_present,
681 ch_assign,
682 ..Substream::new()
683 };
684 for (ch, (old_fir, old_iir)) in old_states.into_iter().enumerate() {
685 s.channels[ch].fir.state = old_fir.state;
686 s.channels[ch].iir.state = old_iir.state;
687 }
688 Ok(())
689 }
690
691 fn read_decoding_params(&mut self, idx: usize, br: &mut BitReader) -> Result<()> {
692 let s = &mut self.substreams[idx];
693 if s.param_presence_flags & PARAM_PRESENCE != 0 && br.read_bit()? {
694 s.param_presence_flags = br.read_bits(8)? as u8;
695 }
696 let flags = s.param_presence_flags;
697 if flags & PARAM_BLOCKSIZE != 0 && br.read_bit()? {
698 s.blocksize = br.read_bits(9)? as usize;
699 if s.blocksize < 8 || s.blocksize > self.access_unit_size {
700 return Err(Error::corrupt(format!(
701 "TrueHD: block size {}",
702 s.blocksize
703 )));
704 }
705 }
706 if flags & PARAM_MATRIX != 0 && br.read_bit()? {
707 let count = br.read_bits(4)? as usize;
708 if count > MAX_MATRICES {
709 return Err(Error::corrupt("TrueHD: too many primitive matrices"));
710 }
711 let max_chan = s.max_matrix_channel + if s.noise_type { 0 } else { 2 };
712 s.matrices.clear();
713 for _ in 0..count {
714 let out_ch = br.read_bits(4)? as usize;
715 let frac_bits = br.read_bits(4)?;
716 let lsb_bypass = br.read_bit()?;
717 if out_ch > s.max_matrix_channel || frac_bits > 14 {
718 return Err(Error::corrupt("TrueHD: matrix parameters out of range"));
719 }
720 let mut coeffs = [0i32; MAX_CHANNELS];
721 for c in coeffs.iter_mut().take(max_chan + 1) {
722 if br.read_bit()? {
723 *c = br.read_signed(frac_bits + 2)? << (14 - frac_bits);
724 }
725 }
726 let noise_shift = if s.noise_type { br.read_bits(4)? } else { 0 };
727 s.matrices.push(Matrix {
728 out_ch,
729 lsb_bypass,
730 noise_shift,
731 coeffs,
732 });
733 }
734 }
735 if flags & PARAM_OUTSHIFT != 0 && br.read_bit()? {
736 for ch in 0..=s.max_matrix_channel {
737 s.output_shift[ch] = br.read_signed(4)?;
738 }
739 }
740 if flags & PARAM_QUANTSTEP != 0 && br.read_bit()? {
741 for ch in 0..=s.max_channel {
742 s.quant_step_size[ch] = br.read_bits(4)?;
743 s.recompute_sign_offset(ch)?;
744 }
745 }
746 for ch in s.min_channel..=s.max_channel {
747 if br.read_bit()? {
748 if flags & PARAM_FIR != 0 && br.read_bit()? {
749 read_filter(br, &mut s.channels[ch].fir, false)?;
750 }
751 if flags & PARAM_IIR != 0 && br.read_bit()? {
752 read_filter(br, &mut s.channels[ch].iir, true)?;
753 }
754 let cp = &s.channels[ch];
755 if cp.fir.order + cp.iir.order > MAX_FILTER_ORDER {
756 return Err(Error::corrupt("TrueHD: FIR+IIR order above 8"));
757 }
758 if cp.fir.order > 0 && cp.iir.order > 0 && cp.fir.shift != cp.iir.shift {
759 return Err(Error::corrupt("TrueHD: FIR and IIR shifts differ"));
760 }
761 if flags & PARAM_HUFFOFFSET != 0 && br.read_bit()? {
762 s.channels[ch].huff_offset = br.read_signed(15)?;
763 }
764 let codebook = br.read_bits(2)? as u8;
765 let huff_lsbs = br.read_bits(5)? as u8;
766 // Validated before either field is stored.
767 if huff_lsbs > 24 {
768 return Err(Error::corrupt("TrueHD: huff_lsbs above 24"));
769 }
770 s.channels[ch].codebook = codebook;
771 s.channels[ch].huff_lsbs = huff_lsbs;
772 s.recompute_sign_offset(ch)?;
773 }
774 }
775 Ok(())
776 }
777
778 fn read_block(&mut self, idx: usize, br: &mut BitReader) -> Result<()> {
779 let s = &mut self.substreams[idx];
780 let expected_end = if s.data_check_present {
781 Some(br.bit_position() + u64::from(br.read_bits(16)?))
782 } else {
783 None
784 };
785 if s.blockpos + s.blocksize > self.access_unit_size {
786 return Err(Error::corrupt("TrueHD: blocks exceed the access unit"));
787 }
788 for i in s.blockpos..s.blockpos + s.blocksize {
789 for (m, mat) in s.matrices.iter().enumerate() {
790 if mat.lsb_bypass {
791 self.bypassed_lsbs[i][m] = br.read_bit()? as i32;
792 }
793 }
794 for ch in s.min_channel..=s.max_channel {
795 let cp = &s.channels[ch];
796 let qss = s.quant_step_size[ch];
797 let lsb_bits = i32::from(cp.huff_lsbs) - qss as i32;
798 let mut result = 0i32;
799 if cp.codebook > 0 {
800 result = self.huff.0.decode(br, usize::from(cp.codebook) - 1)?;
801 }
802 if lsb_bits > 0 {
803 result = (result << lsb_bits) + br.read_bits(lsb_bits as u32)? as i32;
804 } else if lsb_bits < 0 {
805 return Err(Error::corrupt("TrueHD: quant step above huff_lsbs"));
806 }
807 result = result.wrapping_add(cp.sign_huff_offset).wrapping_shl(qss);
808 self.sample_buffer[i][ch] = result;
809 }
810 }
811 for ch in s.min_channel..=s.max_channel {
812 filter_channel(
813 &mut s.channels[ch],
814 s.quant_step_size[ch],
815 &mut self.sample_buffer[s.blockpos..s.blockpos + s.blocksize],
816 ch,
817 );
818 }
819 s.blockpos += s.blocksize;
820 if let Some(end) = expected_end {
821 if br.bit_position() != end {
822 self.stats.length_mismatches += 1;
823 }
824 br.skip_bits(8)?;
825 }
826 Ok(())
827 }
828
829 fn rematrix(&mut self, idx: usize) {
830 let s = &mut self.substreams[idx];
831 let mut maxchan = s.max_matrix_channel;
832 if !s.noise_type {
833 // Two noise channels after the last matrix channel, from the
834 // 23-bit generator seeded by the restart header and carried on.
835 let mut seed = s.noisegen_seed;
836 for row in self.sample_buffer.iter_mut().take(s.blockpos) {
837 let shr7 = (seed >> 7) as u16;
838 row[maxchan + 1] = i32::from((seed >> 15) as u8 as i8) << s.noise_shift;
839 row[maxchan + 2] = i32::from(shr7 as u8 as i8) << s.noise_shift;
840 seed = (seed << 16) ^ (u32::from(shr7) << 5) ^ (u32::from(shr7) << 7);
841 }
842 s.noisegen_seed = seed;
843 maxchan += 2;
844 } else {
845 let mut seed = s.noisegen_seed;
846 for slot in self.noise_buffer.iter_mut() {
847 let shr15 = (seed >> 15) as u8;
848 *slot = NOISE_TABLE[usize::from(shr15)];
849 seed = (seed << 8) ^ u32::from(shr15) ^ (u32::from(shr15) << 5);
850 }
851 s.noisegen_seed = seed;
852 }
853 let pow2_mask = self.access_unit_size_pow2 - 1;
854 let count = s.matrices.len();
855 for (m, mat) in s.matrices.iter().enumerate() {
856 let mask = !((1i32 << s.quant_step_size[mat.out_ch]) - 1);
857 let mut index = count - m;
858 let index2 = 2 * index + 1;
859 for (i, row) in self.sample_buffer.iter_mut().take(s.blockpos).enumerate() {
860 let mut accum: i64 = 0;
861 for (sample, coeff) in row.iter().zip(&mat.coeffs).take(maxchan + 1) {
862 accum += i64::from(*sample) * i64::from(*coeff);
863 }
864 if mat.noise_shift != 0 {
865 index &= pow2_mask;
866 accum += i64::from(self.noise_buffer[index]) << (mat.noise_shift + 7);
867 index += index2;
868 }
869 row[mat.out_ch] = ((accum >> 14) as i32 & mask) + self.bypassed_lsbs[i][m];
870 }
871 }
872 }
873
874 fn output(&mut self, idx: usize, layout: ChannelLayout, samples: usize) -> Result<AudioFrame> {
875 let s = &mut self.substreams[idx];
876 let channels = layout.channel_count();
877 // TrueHD's Ls/Rs (output 4,5) are our side pair, Lrs/Rrs (6,7) our
878 // back pair.
879 const PERM_7_1: [usize; 8] = [0, 1, 2, 3, 6, 7, 4, 5];
880 let mut bytes = Vec::with_capacity(samples * channels * 4);
881 for row in self.sample_buffer.iter().take(samples) {
882 for (out_ch, &perm) in PERM_7_1.iter().enumerate().take(channels) {
883 let thd_ch = if channels == 8 { perm } else { out_ch };
884 let mat_ch = s.ch_assign[thd_ch];
885 let sample = row[mat_ch].wrapping_shl(s.output_shift[mat_ch] as u32);
886 s.lossless_check_data ^= ((sample as u32) & 0xFF_FFFF) << mat_ch;
887 bytes.extend_from_slice(&(sample << 8).to_ne_bytes());
888 }
889 }
890 AudioFrame::try_new(
891 SampleFormat::S32,
892 false,
893 layout,
894 self.sample_rate,
895 samples,
896 vec![Buf::from_vec(bytes)],
897 )
898 }
899}
900
901/// New coefficients for `f`; its history carries over unless the stream
902/// sends an explicit (IIR-only) state.
903fn read_filter(br: &mut BitReader, f: &mut Filter, iir: bool) -> Result<()> {
904 // Validate before storing: the decode loop keeps going after an error, so an out-of-range
905 // order left in `f` would index past the state arrays on a later access unit.
906 let order = br.read_bits(4)? as usize;
907 if order > MAX_FILTER_ORDER || (!iir && order > 8) || (iir && order > 4) {
908 return Err(Error::corrupt("TrueHD: filter order out of range"));
909 }
910 f.order = order;
911 if f.order > 0 {
912 f.shift = br.read_bits(4)?;
913 let coeff_bits = br.read_bits(5)?;
914 let coeff_shift = br.read_bits(3)?;
915 if !(1..=16).contains(&coeff_bits) || coeff_bits + coeff_shift > 16 {
916 return Err(Error::corrupt(
917 "TrueHD: filter coefficient precision out of range",
918 ));
919 }
920 for c in f.coeffs.iter_mut().take(f.order) {
921 *c = br.read_signed(coeff_bits)? << coeff_shift;
922 }
923 if br.read_bit()? {
924 if !iir {
925 return Err(Error::corrupt("TrueHD: FIR filter with explicit state"));
926 }
927 let state_bits = br.read_bits(4)?;
928 let state_shift = br.read_bits(4)?;
929 for st in f.state.iter_mut().take(f.order) {
930 *st = if state_bits > 0 {
931 br.read_signed(state_bits)? << state_shift
932 } else {
933 0
934 };
935 }
936 }
937 }
938 Ok(())
939}
940
941/// Residual → sample through the channel's FIR (over past samples) and IIR
942/// (over past residual-after-prediction) filters, in place on column `ch`.
943fn filter_channel(cp: &mut ChannelParams, qss: u32, rows: &mut [[i32; MAX_CHANNELS]], ch: usize) {
944 let mask = !((1i32 << qss) - 1);
945 let shift = if cp.fir.order > 0 {
946 cp.fir.shift
947 } else {
948 cp.iir.shift
949 };
950 for row in rows {
951 let mut accum: i64 = 0;
952 for j in 0..cp.fir.order {
953 accum += i64::from(cp.fir.state[j]) * i64::from(cp.fir.coeffs[j]);
954 }
955 for j in 0..cp.iir.order {
956 accum += i64::from(cp.iir.state[j]) * i64::from(cp.iir.coeffs[j]);
957 }
958 let accum = (accum >> shift) as i32;
959 let result = accum.wrapping_add(row[ch]) & mask;
960 cp.fir.state.copy_within(0..MAX_FILTER_ORDER - 1, 1);
961 cp.fir.state[0] = result;
962 cp.iir.state.copy_within(0..MAX_FILTER_ORDER - 1, 1);
963 cp.iir.state[0] = result.wrapping_sub(accum);
964 row[ch] = result;
965 }
966}
967
968#[cfg(test)]
969mod tests {
970 use super::*;
971
972 /// An out-of-range filter order is refused and not stored: the decode loop
973 /// continues after an error, and a stored order above the state array's
974 /// length would index out of bounds on a later access unit (fuzz finding).
975 #[test]
976 fn out_of_range_filter_order_is_refused_and_not_stored() {
977 // 4-bit order field = 9 (above the FIR limit of 8), then padding.
978 let data = [0x90u8, 0, 0, 0];
979 let mut br = BitReader::new(&data);
980 let mut f = Filter::default();
981 assert!(matches!(read_filter(&mut br, &mut f, false), Err(Error::Corrupt { .. })));
982 assert_eq!(f.order, 0);
983
984 // 4-bit order field = 5: refused for IIR (limit 4), and not stored.
985 let data = [0x50u8, 0, 0, 0];
986 let mut br = BitReader::new(&data);
987 let mut f = Filter::default();
988 assert!(read_filter(&mut br, &mut f, true).is_err());
989 assert_eq!(f.order, 0);
990 }
991
992 /// A quant step above huff_lsbs (set before huff_lsbs is re-read) leaves the sign offset
993 /// at zero instead of shifting by a negative amount (fuzz finding; debug builds panic).
994 #[test]
995 fn quant_step_above_huff_lsbs_does_not_shift_negatively() {
996 let mut s = Substream::new();
997 s.channels[0].huff_lsbs = 2;
998 s.channels[0].huff_offset = 100;
999 s.quant_step_size[0] = 5;
1000 s.recompute_sign_offset(0).unwrap();
1001 assert_eq!(s.channels[0].sign_huff_offset, 0);
1002 }
1003
1004 /// A stale huff_lsbs above 24 (left by a refused access unit) is corrupt, not an i32
1005 /// overflow in `7 << lsb_bits` (fuzz finding crash-3c28...; debug and fuzz builds panic).
1006 #[test]
1007 fn stale_huff_lsbs_above_24_is_corrupt_not_an_overflow() {
1008 let mut s = Substream::new();
1009 s.channels[0].huff_lsbs = 31;
1010 s.channels[0].codebook = 1;
1011 s.channels[0].huff_offset = 100;
1012 let err = s.recompute_sign_offset(0).expect_err("lsb_bits above 24 is corrupt");
1013 assert!(err.to_string().contains("huff_lsbs"), "wrong refusal: {err}");
1014 }
1015
1016 /// Every code in the public tables decodes back to its own index when
1017 /// written bit-exactly, with and without trailing garbage.
1018 #[test]
1019 fn every_codebook_entry_decodes_to_its_index() {
1020 use ec_core::bitio::BitWriter;
1021 let lut = HuffLut::build();
1022 for (book, table) in HUFFMAN_TABLES.iter().enumerate() {
1023 for (index, &(code, len)) in table.iter().enumerate() {
1024 if len == 0 {
1025 continue;
1026 }
1027 let mut w = BitWriter::new();
1028 w.write_bits(u32::from(code), u32::from(len));
1029 w.write_bits(0x5A5, 11);
1030 let bytes = w.into_bytes();
1031 let mut br = BitReader::new(&bytes);
1032 assert_eq!(
1033 lut.decode(&mut br, book).unwrap(),
1034 index as i32,
1035 "book {book} index {index}"
1036 );
1037 assert_eq!(br.bit_position(), u64::from(len));
1038 // Bare code at the very end of the buffer must decode too.
1039 let mut w = BitWriter::new();
1040 w.write_bits(u32::from(code), u32::from(len));
1041 let bytes = w.into_bytes();
1042 let mut br = BitReader::new(&bytes);
1043 assert_eq!(lut.decode(&mut br, book).unwrap(), index as i32);
1044 }
1045 }
1046 // An all-zero 9-bit word is not a code in any book.
1047 for book in 0..3 {
1048 assert!(lut.decode(&mut BitReader::new(&[0, 0]), book).is_err());
1049 }
1050 }
1051
1052 #[test]
1053 fn codebooks_are_prefix_free() {
1054 for table in &HUFFMAN_TABLES {
1055 let used: Vec<_> = table.iter().filter(|e| e.1 > 0).collect();
1056 for (i, a) in used.iter().enumerate() {
1057 for b in &used[i + 1..] {
1058 let l = a.1.min(b.1);
1059 assert_ne!(a.0 >> (a.1 - l), b.0 >> (b.1 - l), "{a:?} vs {b:?}");
1060 }
1061 }
1062 }
1063 }
1064}