forge
Explore
Log in

Don't you dare go Hollow

Lossless substream decode — 2/6/8-ch presentations bit-exact, 16-ch object substream refused

Browse files at this commit

2f6b7e8a1c1500ebcf50ceb2dc5ae4ccec58e336Ahmet Kaan GümüşParent: f77ac31
  • feat
    • lossless substream decode — 2/6/8-ch presentations bit-exact, 16-ch object substream refused
Show full message
feat(truehd): lossless substream decode — 2/6/8-ch presentations bit-exact, 16-ch object substream refused

Decodes: restart headers (14-bit sync, CRC-8 poly 0x1D verified), decoding
parameters (presence flags, block size, primitive matrices, output shift,
quant step, FIR≤8/IIR≤4 with carried history, Huffman offset/codebook/LSBs),
residuals through the three codebooks (read off an external encoder's mono
output, then oracle-checked), per-substream parity and the lossless-check
byte, rematrixing with both noise generators (23-bit LFSR 2-channel noise for
0x31EA; 256-entry dither table for 0x31EB, every entry solved by constraint
intersection against the external decoder on the real 7.1 track), output
shift, interleaved S32 left-justified 24-bit. TrueHD 7.1 (assignment 0x4F)
lands on FL FR FC LFE BL BR SL SR via [0,1,2,3,6,7,4,5]. MLP major sync's
rate-code offset fixed (data[9], not data[8]).

Refused by name (Error::Unsupported): the 4th / 16-channel object substream,
any substream with more than 8 matrix channels, 8-ch presentations whose
channel assignment is not the standard 7.1 mask, reserved rate codes.
Not validated: the per-substream CRC-8 check byte (generator/span unknown;
parsed and skipped, see corner-cut in decode.rs).

Oracle (tests/oracle.rs, skipped without ffmpeg / the remux): first 60 s of
the real 7.1 remux 23 040 000 / 23 040 000 samples exact, 0 lossless-check,
0 parity, 0 restart-CRC, 0 length failures over 72 000 access units;
externally encoded MLP and TrueHD mono/stereo/5.1 streams all bit-exact.
crates/ec-truehd/src/decode.rsadded+839 -0
@@ -0,0 +1,839 @@
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+
55+use ec_core::bitio::BitReader;
56+use ec_core::error::{Error, Result};
57+use ec_core::frame::{AudioFrame, ChannelLayout, SampleFormat};
58+use ec_core::packet::Buf;
59+
60+use 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.
64+const 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.
67+const MAX_CHANNELS: usize = MAX_MATRIX_CHANNEL + 3;
68+const MAX_MATRICES: usize = 8;
69+const MAX_FILTER_ORDER: usize = 8;
70+const 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]
78+const 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+
97+const PARAM_BLOCKSIZE: u8 = 1 << 7;
98+const PARAM_MATRIX: u8 = 1 << 6;
99+const PARAM_OUTSHIFT: u8 = 1 << 5;
100+const PARAM_QUANTSTEP: u8 = 1 << 4;
101+const PARAM_FIR: u8 = 1 << 3;
102+const PARAM_IIR: u8 = 1 << 2;
103+const PARAM_HUFFOFFSET: u8 = 1 << 1;
104+const 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`).
112+pub 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.
128+struct HuffLut([[(u8, u8); 512]; 3]);
129+
130+impl 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).
163+fn 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.
177+fn 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.
195+fn 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)]
200+struct 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)]
209+struct 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)]
219+struct Matrix {
220+ out_ch: usize,
221+ lsb_bypass: bool,
222+ noise_shift: u32,
223+ coeffs: [i32; MAX_CHANNELS],
224+}
225+
226+#[derive(Debug, Clone)]
227+struct 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+
248+impl 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)]
289+pub 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)]
306+pub(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+
322+struct HuffLutBox(HuffLut);
323+
324+impl 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+
330+impl 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.
738+fn 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`.
769+fn 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)]
791+mod 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+
crates/ec-truehd/src/lib.rsmodified+9 -4
@@ -3,15 +3,18 @@
33 //! Written from Dolby's public TrueHD/MLP documentation of the bitstream's
44 //! *shape* — major sync, per-substream access-unit directory, FIR/IIR filter
55 //! parameters, the Huffman/LSB entropy coder and matrixing — not from any
6-//! third party's source. The syntax layer ([`sync`]) is parsed and verified
7-//! against a real 7.1 Blu-ray remux; the substream *decode* itself
8-//! ([`TrueHdDecoder::decode_access_unit`]) is not implemented yet.
6+//! third party's source. The syntax layer ([`sync`]) and the lossless
7+//! substream decode ([`decode`], reached through
8+//! [`TrueHdDecoder::decode_access_unit`]) are both verified bit-exact
9+//! against an external decoder on a real 7.1 Blu-ray remux (first 60 s,
10+//! 23 040 000 of 23 040 000 samples) and on externally encoded MLP/TrueHD
11+//! mono, stereo and 5.1 streams.
912 //!
1013 //! Scope, stated once so a caller knows what to expect:
1114 //!
1215 //! - **In scope**: major sync detection and parsing (format id, sample rate,
1316 //! channel presentations), the access-unit header's per-substream
14-//! directory (end pointers, checksum/parity), and — once implemented — the
17+//! directory (end pointers, checksum/parity), and the
1518 //! three PCM-presentation substreams a real Blu-ray track carries: 2-ch,
1619 //! 6-ch (5.1) and 8-ch (7.1), each built from restart headers, FIR/IIR
1720 //! predictor filters, Huffman/LSB residual entropy and the channel
@@ -33,7 +36,9 @@
3336 #![forbid(unsafe_code)]
3437 #![warn(missing_docs)]
3538
39+pub mod decode;
3640 pub mod sync;
3741
3842 pub use ec_core::Error;
43+pub use decode::CheckStats;
3944 pub use sync::{AccessUnitHeader, MajorSyncInfo, MajorSyncFormat, SubstreamInfo, TrueHdDecoder, frame_length};
crates/ec-truehd/src/sync.rsmodified+80 -25
@@ -105,6 +105,13 @@ pub struct MajorSyncInfo {
105105 pub format: MajorSyncFormat,
106106 /// The primary sample rate, decoded from `data[8]`'s high nibble.
107107 pub sample_rate: u32,
108+ /// The raw 4-bit rate code (`& 7` is the `2^n` multiplier, which also
109+ /// sizes the access unit: `40 << n` samples).
110+ pub rate_code: u8,
111+ /// The 8-channel presentation's 13-bit channel-assignment mask (bit 0 =
112+ /// L/R, 1 = C, 2 = LFE, 3 = Ls/Rs, 6 = Lrs/Rrs; `0x4F` is standard 7.1);
113+ /// 0 when the major sync is plain MLP, which has no such field.
114+ pub ch8_assignment: u16,
108115 }
109116
110117 /// A rate code's `44.1k*2^n` / `48k*2^n` value, or [`Error::Unsupported`] for
@@ -134,10 +141,23 @@ impl MajorSyncInfo {
134141 MAJOR_SYNC_MLP => MajorSyncFormat::Mlp,
135142 _ => return Err(Error::corrupt("TrueHD: no major sync word")),
136143 };
137- let sample_rate = sample_rate(data[4] >> 4)?;
144+ // TrueHD: format_info starts with the rate code; MLP puts its two
145+ // 4-bit word-length codes first and the rate codes one byte later.
146+ let rate_code = match format {
147+ MajorSyncFormat::TrueHd => data[4] >> 4,
148+ MajorSyncFormat::Mlp => data[5] >> 4,
149+ };
150+ let sample_rate = sample_rate(rate_code)?;
151+ // format_info's last 13 bits: data[6] low 5 bits + data[7].
152+ let ch8_assignment = match format {
153+ MajorSyncFormat::TrueHd => (u16::from(data[6] & 0x1F) << 8) | u16::from(data[7]),
154+ MajorSyncFormat::Mlp => 0,
155+ };
138156 Ok(MajorSyncInfo {
139157 format,
140158 sample_rate,
159+ rate_code,
160+ ch8_assignment,
141161 })
142162 }
143163 }
@@ -168,6 +188,9 @@ pub struct AccessUnitHeader {
168188 pub input_timing: u16,
169189 /// Present on roughly one access unit per video frame.
170190 pub major_sync: Option<MajorSyncInfo>,
191+ /// Byte offset where the substream directory ends and substream 0's
192+ /// coded data begins.
193+ pub data_start: usize,
171194 /// One entry per substream, in stream order (`substreams.len()` is the
172195 /// substream count).
173196 pub substreams: Vec<SubstreamInfo>,
@@ -234,10 +257,22 @@ impl AccessUnitHeader {
234257 length,
235258 input_timing,
236259 major_sync,
260+ data_start: pos,
237261 substreams,
238262 })
239263 }
240264
265+ /// Byte span `(start, end)` of substream `i`'s coded data within the
266+ /// access unit, from the directory's cumulative end pointers.
267+ pub fn substream_span(&self, i: usize) -> (usize, usize) {
268+ let start = if i == 0 {
269+ self.data_start
270+ } else {
271+ self.data_start + usize::from(self.substreams[i - 1].end_offset_words) * 2
272+ };
273+ (start, self.data_start + usize::from(self.substreams[i].end_offset_words) * 2)
274+ }
275+
241276 /// The channel layout Dolby's substream convention implies: substream 0
242277 /// is always a 2-ch presentation, substream 1 (when present) a discrete
243278 /// 5.1, substream 2 (when present) a discrete 7.1. [`parse`](Self::parse)
@@ -252,14 +287,20 @@ impl AccessUnitHeader {
252287 }
253288 }
254289
255-/// A TrueHD/MLP decoder for one stream.
256-///
257-/// Access-unit framing and major-sync/substream-directory parsing are fully
258-/// implemented; substream decoding is not — see the crate-level docs for the
259-/// scope this covers once it is.
290+/// A TrueHD/MLP decoder for one stream: access units in, one interleaved
291+/// S32 (24-bit left-justified) [`AudioFrame`] of the highest presentation
292+/// out per access unit. See the crate-level docs for scope.
260293 #[derive(Debug)]
261294 pub struct TrueHdDecoder {
262295 params: CodecParameters,
296+ core: crate::decode::Core,
297+ pending: Option<AudioFrame>,
298+}
299+
300+impl Default for TrueHdDecoder {
301+ fn default() -> Self {
302+ Self::new()
303+ }
263304 }
264305
265306 impl TrueHdDecoder {
@@ -269,25 +310,28 @@ impl TrueHdDecoder {
269310 pub fn new() -> TrueHdDecoder {
270311 TrueHdDecoder {
271312 params: CodecParameters::new(CodecId::TrueHd),
313+ core: crate::decode::Core::new(),
314+ pending: None,
272315 }
273316 }
274317
275- /// One access unit in; parses its header and — TODO(H2): decode the
276- /// substreams (restart headers, FIR/IIR predictor filters, Huffman/LSB
277- /// residual entropy, channel matrixing, the lossless check) into PCM.
278- /// Until then this always answers [`Error::Unsupported`] once the header
279- /// itself parses cleanly, and any framing error before that.
318+ /// The stream-side self-check tallies so far (restart CRC, parity,
319+ /// lossless check); all stay zero on a clean decode.
320+ pub fn check_stats(&self) -> crate::decode::CheckStats {
321+ self.core.stats
322+ }
323+
324+ /// One access unit in; one frame of the highest presentation out —
325+ /// `None` until the first major sync and every substream's first
326+ /// restart header have been seen.
280327 pub fn push(&mut self, data: &[u8]) -> Result<Option<AudioFrame>> {
281328 self.decode_access_unit(data)
282329 }
283330
284331 /// See [`TrueHdDecoder::push`].
285332 pub fn decode_access_unit(&mut self, data: &[u8]) -> Result<Option<AudioFrame>> {
286- AccessUnitHeader::parse(data)?;
287- Err(Error::unsupported(
288- "TrueHD substream decode",
289- "substream decode pending",
290- ))
333+ let header = AccessUnitHeader::parse(data)?;
334+ self.core.decode(&header, data)
291335 }
292336 }
293337
@@ -297,22 +341,27 @@ impl Decoder for TrueHdDecoder {
297341 }
298342
299343 fn send_packet(&mut self, packet: &Packet) -> Result<()> {
300- self.decode_access_unit(&packet.data)?;
344+ if let Some(mut frame) = self.decode_access_unit(&packet.data)? {
345+ frame.pts = packet
346+ .pts
347+ .map(|ticks| ec_core::timebase::Timestamp::new(ticks, packet.time_base));
348+ self.pending = Some(frame);
349+ }
301350 Ok(())
302351 }
303352
304353 fn receive_frame(&mut self) -> Result<Frame> {
305- // decode_access_unit never returns Ok, so send_packet never
306- // completes and this is unreachable in practice; NeedMore is the
307- // honest answer for "nothing queued" regardless.
308- Err(Error::NeedMore)
354+ self.pending.take().map(Frame::Audio).ok_or(Error::NeedMore)
309355 }
310356
311357 fn flush(&mut self) -> Result<()> {
312358 Ok(())
313359 }
314360
315- fn reset(&mut self) {}
361+ fn reset(&mut self) {
362+ self.pending = None;
363+ self.core.reset();
364+ }
316365 }
317366
318367 #[cfg(test)]
@@ -417,9 +466,15 @@ mod tests {
417466 }
418467
419468 #[test]
420- fn decoder_names_substream_decode_as_pending() {
469+ fn decoder_yields_nothing_before_a_major_sync() {
421470 let mut decoder = TrueHdDecoder::new();
422- let err = decoder.decode_access_unit(&stereo_au()).unwrap_err();
423- assert!(matches!(err, Error::Unsupported { .. }));
471+ assert_eq!(decoder.decode_access_unit(&stereo_au()).unwrap(), None);
472+ }
473+
474+ #[test]
475+ fn substream_spans_follow_the_directory() {
476+ let au = AccessUnitHeader::parse(&surround51_au()).unwrap();
477+ assert_eq!(au.substream_span(0), (36, 38));
478+ assert_eq!(au.substream_span(1), (38, 44));
424479 }
425480 }
crates/ec-truehd/tests/oracle.rsadded+178 -0
@@ -0,0 +1,178 @@
1+//! Bit-exactness against an external decoder: the first 60 s of a real 7.1
2+//! Blu-ray TrueHD remux (3 substreams, noise type 1 matrices), and
3+//! externally encoded MLP/TrueHD streams (mono, stereo, 5.1 pink noise —
4+//! every codebook, matrices with the 2-channel noise generator, two
5+//! substreams). Both need `ffmpeg` on PATH and skip loudly without it; the
6+//! remux is a live discovery over `~/Downloads`.
7+
8+use std::fs::File;
9+use std::io::BufReader;
10+use std::path::{Path, PathBuf};
11+use std::process::Command;
12+
13+use ec_core::{CodecId, Demuxer};
14+use ec_matroska::MatroskaDemuxer;
15+use ec_truehd::{frame_length, TrueHdDecoder};
16+
17+fn find_file() -> Option<PathBuf> {
18+ fn walk(dir: &Path, out: &mut Vec<PathBuf>) {
19+ let Ok(entries) = std::fs::read_dir(dir) else { return };
20+ for e in entries.flatten() {
21+ let p = e.path();
22+ if p.is_dir() {
23+ walk(&p, out);
24+ } else {
25+ out.push(p);
26+ }
27+ }
28+ }
29+ let home = std::env::var("HOME").ok()?;
30+ let mut all = Vec::new();
31+ walk(&PathBuf::from(home).join("Downloads"), &mut all);
32+ all.into_iter().find(|p| {
33+ p.file_name()
34+ .and_then(|n| n.to_str())
35+ .is_some_and(|n| n.contains("ReelR") && n.ends_with(".mkv"))
36+ })
37+}
38+
39+fn have_ffmpeg() -> bool {
40+ Command::new("ffmpeg").arg("-version").output().map(|o| o.status.success()).unwrap_or(false)
41+}
42+
43+fn ffmpeg(args: &[&str]) -> Vec<u8> {
44+ let out = Command::new("ffmpeg").args(["-v", "error", "-nostdin"]).args(args).output().expect("run ffmpeg");
45+ assert!(out.status.success(), "ffmpeg {args:?}: {}", String::from_utf8_lossy(&out.stderr));
46+ out.stdout
47+}
48+
49+fn s32le(bytes: &[u8]) -> Vec<i32> {
50+ bytes.chunks_exact(4).map(|c| i32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect()
51+}
52+
53+/// Compares `ours` with `reference` sample-for-sample; returns (exact,
54+/// total, first mismatch index).
55+fn compare(ours: &[i32], reference: &[i32]) -> (usize, usize, Option<usize>) {
56+ let n = ours.len().min(reference.len());
57+ let mut exact = 0;
58+ let mut first = None;
59+ for i in 0..n {
60+ if ours[i] == reference[i] {
61+ exact += 1;
62+ } else if first.is_none() {
63+ first = Some(i);
64+ }
65+ }
66+ (exact, n, first)
67+}
68+
69+#[test]
70+fn first_60_seconds_of_a_real_7_1_remux_are_bit_exact() {
71+ let Some(path) = find_file() else {
72+ eprintln!("skip: no 'ReelR ... TrueHD ...mkv' under ~/Downloads");
73+ return;
74+ };
75+ if !have_ffmpeg() {
76+ eprintln!("skip: ffmpeg not on PATH");
77+ return;
78+ }
79+ const SECONDS: usize = 60;
80+ let mut demux = MatroskaDemuxer::new(BufReader::new(File::open(&path).unwrap())).unwrap();
81+ let track = demux.streams().iter().find(|s| s.params.codec == CodecId::TrueHd).expect("a TrueHD track");
82+ let stream_index = track.index;
83+
84+ let reference = s32le(&ffmpeg(&[
85+ "-i", path.to_str().unwrap(), "-map", &format!("0:{stream_index}"), "-t", &SECONDS.to_string(),
86+ "-f", "s32le", "-",
87+ ]));
88+ let channels = 8;
89+ let wanted = SECONDS * 48_000 * channels;
90+
91+ let mut decoder = TrueHdDecoder::new();
92+ let mut ours: Vec<i32> = Vec::with_capacity(wanted);
93+ let mut aus = 0;
94+ while ours.len() < wanted {
95+ let packet = match demux.next_packet() {
96+ Ok(p) => p,
97+ Err(e) if e.is_eof() => break,
98+ Err(e) => panic!("demux: {e}"),
99+ };
100+ if packet.stream != stream_index {
101+ continue;
102+ }
103+ let frame = decoder.decode_access_unit(&packet.data).unwrap_or_else(|e| panic!("AU {aus}: {e}"));
104+ aus += 1;
105+ if let Some(f) = frame {
106+ assert_eq!(f.channels(), channels);
107+ ours.extend(s32le(&f.data[0]));
108+ }
109+ }
110+ let (exact, total, first) = compare(&ours, &reference);
111+ let stats = decoder.check_stats();
112+ for ch in 0..channels {
113+ let n = total / channels;
114+ let e = (0..n).filter(|&i| ours[i * channels + ch] == reference[i * channels + ch]).count();
115+ eprintln!("channel {ch}: {e}/{n} exact");
116+ }
117+ eprintln!(
118+ "{aus} access units, {total} samples compared ({} s), {exact} exact ({:.4}%), first mismatch {first:?}, {stats:?}",
119+ total / channels / 48_000,
120+ 100.0 * exact as f64 / total as f64
121+ );
122+ assert!(total >= (SECONDS - 1) * 48_000 * channels, "only {total} samples");
123+ assert_eq!(stats.lossless_check_failures, 0, "{stats:?}");
124+ assert_eq!(stats.parity_failures, 0, "{stats:?}");
125+ assert_eq!(stats.restart_crc_failures, 0, "{stats:?}");
126+ assert_eq!(stats.length_mismatches, 0, "{stats:?}");
127+ assert!(exact as f64 >= 0.9999 * total as f64, "{exact}/{total} exact, first mismatch {first:?}");
128+}
129+
130+/// An externally encoded MLP stream (raw access units) decoded by us must
131+/// match the external decoder's own output exactly; noise drives every
132+/// codebook and a wide range of LSB widths.
133+#[test]
134+fn externally_encoded_mlp_round_trips_bit_exact() {
135+ if !have_ffmpeg() {
136+ eprintln!("skip: ffmpeg not on PATH");
137+ return;
138+ }
139+ let dir = std::env::temp_dir().join(format!("ec-truehd-oracle-{}", std::process::id()));
140+ std::fs::create_dir_all(&dir).unwrap();
141+ let mut failures = Vec::new();
142+ for (codec, layout, channels) in [
143+ ("mlp", "mono", 1usize), ("mlp", "stereo", 2), ("mlp", "5.1", 6),
144+ ("truehd", "mono", 1), ("truehd", "stereo", 2), ("truehd", "5.1", 6),
145+ ] {
146+ let name = format!("{codec}-{layout}");
147+ let mlp = dir.join(format!("{name}.{}", if codec == "mlp" { "mlp" } else { "thd" }));
148+ let src = format!(
149+ "anoisesrc=color=pink:amplitude=0.3:seed=7:sample_rate=48000:duration=3,aformat=sample_fmts=s32:channel_layouts={layout}"
150+ );
151+ ffmpeg(&["-y", "-f", "lavfi", "-i", &src, "-c:a", codec, "-strict", "-2", mlp.to_str().unwrap()]);
152+ let reference = s32le(&ffmpeg(&["-i", mlp.to_str().unwrap(), "-f", "s32le", "-"]));
153+ let data = std::fs::read(&mlp).unwrap();
154+
155+ let mut decoder = TrueHdDecoder::new();
156+ let mut ours = Vec::new();
157+ let mut pos = 0;
158+ while pos < data.len() {
159+ let len = frame_length(&data[pos..]).unwrap();
160+ if let Some(f) = decoder.decode_access_unit(&data[pos..pos + len]).unwrap() {
161+ assert_eq!(f.channels(), channels);
162+ ours.extend(s32le(&f.data[0]));
163+ }
164+ pos += len;
165+ }
166+ let (exact, total, first) = compare(&ours, &reference);
167+ let stats = decoder.check_stats();
168+ eprintln!("{name}: {exact}/{total} exact (ours {}, reference {}), first mismatch {first:?}, {stats:?}", ours.len(), reference.len());
169+ if stats.lossless_check_failures + stats.parity_failures + stats.restart_crc_failures != 0
170+ || exact != total
171+ || total < 2 * 48_000 * channels
172+ {
173+ failures.push(format!("{name}: {exact}/{total}, first mismatch {first:?}, {stats:?}"));
174+ }
175+ }
176+ let _ = std::fs::remove_dir_all(&dir);
177+ assert!(failures.is_empty(), "{failures:#?}");
178+}