forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB4331d17Tahinli3 months ago558 commits

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