forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-truehd-enc'

Browse files at this commit

ab252be0673a8ba4457ceb18132010bdf382775fAhmet Kaan GümüşParent: ca633b0c3703cb
crates/ec-truehd/src/decode.rsmodified+103 -18
@@ -111,16 +111,64 @@ const PARAM_PRESENCE: u8 = 1 << 0;
111 /// external encoder's output (`tests/oracle.rs`).111 /// external encoder's output (`tests/oracle.rs`).
112 pub const HUFFMAN_TABLES: [[(u16, u8); 18]; 3] = [112 pub const HUFFMAN_TABLES: [[(u16, u8); 18]; 3] = [
113 [113 [
114- (0x01, 9), (0x01, 8), (0x01, 7), (0x01, 6), (0x01, 5), (0x01, 4), (0x01, 3), (0x04, 3), (0x05, 3),114+ (0x01, 9),
115- (0x06, 3), (0x07, 3), (0x03, 3), (0x05, 4), (0x09, 5), (0x11, 6), (0x21, 7), (0x41, 8), (0x81, 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),
116 ],132 ],
117 [133 [
118- (0x01, 9), (0x01, 8), (0x01, 7), (0x01, 6), (0x01, 5), (0x01, 4), (0x01, 3), (0x02, 2), (0x03, 2),134+ (0x01, 9),
119- (0x03, 3), (0x05, 4), (0x09, 5), (0x11, 6), (0x21, 7), (0x41, 8), (0x81, 9), (0, 0), (0, 0),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),
120 ],152 ],
121 [153 [
122- (0x01, 9), (0x01, 8), (0x01, 7), (0x01, 6), (0x01, 5), (0x01, 4), (0x01, 3), (0x01, 1), (0x03, 3),154+ (0x01, 9),
123- (0x05, 4), (0x09, 5), (0x11, 6), (0x21, 7), (0x41, 8), (0x81, 9), (0, 0), (0, 0), (0, 0),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),
124 ],172 ],
125 ];173 ];
126 174
@@ -165,7 +213,11 @@ fn crc8(poly: u8, init: u8, bytes: &[u8]) -> u8 {
165 for &b in bytes {213 for &b in bytes {
166 crc ^= b;214 crc ^= b;
167 for _ in 0..8 {215 for _ in 0..8 {
168- crc = if crc & 0x80 != 0 { (crc << 1) ^ poly } else { crc << 1 };216+ crc = if crc & 0x80 != 0 {
217+ (crc << 1) ^ poly
218+ } else {
219+ crc << 1
220+ };
169 }221 }
170 }222 }
171 crc223 crc
@@ -174,7 +226,7 @@ fn crc8(poly: u8, init: u8, bytes: &[u8]) -> u8 {
174 /// The restart header's own CRC-8 (poly 0x1D), over the header from its226 /// 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 —227 /// 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.228 /// are masked off) through its last full byte and the trailing partial bits.
177-fn restart_checksum(buf: &[u8], bit_size: u64) -> u8 {229+pub(crate) fn restart_checksum(buf: &[u8], bit_size: u64) -> u8 {
178 let bit_size = bit_size as usize + 2;230 let bit_size = bit_size as usize + 2;
179 let num_bytes = bit_size / 8;231 let num_bytes = bit_size / 8;
180 let mut crc = crc8(0x1D, 0, &[buf[0] & 0x3F]);232 let mut crc = crc8(0x1D, 0, &[buf[0] & 0x3F]);
@@ -271,7 +323,12 @@ impl Substream {
271 fn recompute_sign_offset(&mut self, ch: usize) {323 fn recompute_sign_offset(&mut self, ch: usize) {
272 let cp = &mut self.channels[ch];324 let cp = &mut self.channels[ch];
273 let lsb_bits = i32::from(cp.huff_lsbs) - self.quant_step_size[ch] as i32;325 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 };326+ let sign_shift = lsb_bits
327+ + if cp.codebook > 0 {
328+ 2 - i32::from(cp.codebook)
329+ } else {
330+ -1
331+ };
275 let mut off = cp.huff_offset;332 let mut off = cp.huff_offset;
276 if cp.codebook > 0 {333 if cp.codebook > 0 {
277 off -= 7 << lsb_bits;334 off -= 7 << lsb_bits;
@@ -350,7 +407,11 @@ impl Core {
350 407
351 /// Decodes one access unit whose header already parsed; `None` until the408 /// Decodes one access unit whose header already parsed; `None` until the
352 /// first major sync and every substream's first restart header are seen.409 /// 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>> {410+ pub(crate) fn decode(
411+ &mut self,
412+ header: &AccessUnitHeader,
413+ data: &[u8],
414+ ) -> Result<Option<AudioFrame>> {
354 if !self.prepare(header)? || !self.decode_substreams(header, data)? {415 if !self.prepare(header)? || !self.decode_substreams(header, data)? {
355 return Ok(None);416 return Ok(None);
356 }417 }
@@ -403,7 +464,10 @@ impl Core {
403 let layout = ChannelLayout::from_count(channels);464 let layout = ChannelLayout::from_count(channels);
404 if layout == ChannelLayout::Surround7_1 && self.ch8_assignment != 0x4F {465 if layout == ChannelLayout::Surround7_1 && self.ch8_assignment != 0x4F {
405 return Err(Error::unsupported(466 return Err(Error::unsupported(
406- format!("TrueHD 8-channel presentation with channel assignment {:#x}", self.ch8_assignment),467+ format!(
468+ "TrueHD 8-channel presentation with channel assignment {:#x}",
469+ self.ch8_assignment
470+ ),
407 "only the standard 7.1 (L R C LFE Ls Rs Lrs Rrs) assignment is mapped",471 "only the standard 7.1 (L R C LFE Ls Rs Lrs Rrs) assignment is mapped",
408 ));472 ));
409 }473 }
@@ -543,7 +607,10 @@ impl Core {
543 if flags & PARAM_BLOCKSIZE != 0 && br.read_bit()? {607 if flags & PARAM_BLOCKSIZE != 0 && br.read_bit()? {
544 s.blocksize = br.read_bits(9)? as usize;608 s.blocksize = br.read_bits(9)? as usize;
545 if s.blocksize < 8 || s.blocksize > self.access_unit_size {609 if s.blocksize < 8 || s.blocksize > self.access_unit_size {
546- return Err(Error::corrupt(format!("TrueHD: block size {}", s.blocksize)));610+ return Err(Error::corrupt(format!(
611+ "TrueHD: block size {}",
612+ s.blocksize
613+ )));
547 }614 }
548 }615 }
549 if flags & PARAM_MATRIX != 0 && br.read_bit()? {616 if flags & PARAM_MATRIX != 0 && br.read_bit()? {
@@ -649,7 +716,12 @@ impl Core {
649 }716 }
650 }717 }
651 for ch in s.min_channel..=s.max_channel {718 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);719+ filter_channel(
720+ &mut s.channels[ch],
721+ s.quant_step_size[ch],
722+ &mut self.sample_buffer[s.blockpos..s.blockpos + s.blocksize],
723+ ch,
724+ );
653 }725 }
654 s.blockpos += s.blocksize;726 s.blockpos += s.blocksize;
655 if let Some(end) = expected_end {727 if let Some(end) = expected_end {
@@ -745,7 +817,9 @@ fn read_filter(br: &mut BitReader, f: &mut Filter, iir: bool) -> Result<()> {
745 let coeff_bits = br.read_bits(5)?;817 let coeff_bits = br.read_bits(5)?;
746 let coeff_shift = br.read_bits(3)?;818 let coeff_shift = br.read_bits(3)?;
747 if !(1..=16).contains(&coeff_bits) || coeff_bits + coeff_shift > 16 {819 if !(1..=16).contains(&coeff_bits) || coeff_bits + coeff_shift > 16 {
748- return Err(Error::corrupt("TrueHD: filter coefficient precision out of range"));820+ return Err(Error::corrupt(
821+ "TrueHD: filter coefficient precision out of range",
822+ ));
749 }823 }
750 for c in f.coeffs.iter_mut().take(f.order) {824 for c in f.coeffs.iter_mut().take(f.order) {
751 *c = br.read_signed(coeff_bits)? << coeff_shift;825 *c = br.read_signed(coeff_bits)? << coeff_shift;
@@ -757,7 +831,11 @@ fn read_filter(br: &mut BitReader, f: &mut Filter, iir: bool) -> Result<()> {
757 let state_bits = br.read_bits(4)?;831 let state_bits = br.read_bits(4)?;
758 let state_shift = br.read_bits(4)?;832 let state_shift = br.read_bits(4)?;
759 for st in f.state.iter_mut().take(f.order) {833 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 };834+ *st = if state_bits > 0 {
835+ br.read_signed(state_bits)? << state_shift
836+ } else {
837+ 0
838+ };
761 }839 }
762 }840 }
763 }841 }
@@ -768,7 +846,11 @@ fn read_filter(br: &mut BitReader, f: &mut Filter, iir: bool) -> Result<()> {
768 /// (over past residual-after-prediction) filters, in place on column `ch`.846 /// (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) {847 fn filter_channel(cp: &mut ChannelParams, qss: u32, rows: &mut [[i32; MAX_CHANNELS]], ch: usize) {
770 let mask = !((1i32 << qss) - 1);848 let mask = !((1i32 << qss) - 1);
771- let shift = if cp.fir.order > 0 { cp.fir.shift } else { cp.iir.shift };849+ let shift = if cp.fir.order > 0 {
850+ cp.fir.shift
851+ } else {
852+ cp.iir.shift
853+ };
772 for row in rows {854 for row in rows {
773 let mut accum: i64 = 0;855 let mut accum: i64 = 0;
774 for j in 0..cp.fir.order {856 for j in 0..cp.fir.order {
@@ -807,7 +889,11 @@ mod tests {
807 w.write_bits(0x5A5, 11);889 w.write_bits(0x5A5, 11);
808 let bytes = w.into_bytes();890 let bytes = w.into_bytes();
809 let mut br = BitReader::new(&bytes);891 let mut br = BitReader::new(&bytes);
810- assert_eq!(lut.decode(&mut br, book).unwrap(), index as i32, "book {book} index {index}");892+ assert_eq!(
893+ lut.decode(&mut br, book).unwrap(),
894+ index as i32,
895+ "book {book} index {index}"
896+ );
811 assert_eq!(br.bit_position(), u64::from(len));897 assert_eq!(br.bit_position(), u64::from(len));
812 // Bare code at the very end of the buffer must decode too.898 // Bare code at the very end of the buffer must decode too.
813 let mut w = BitWriter::new();899 let mut w = BitWriter::new();
@@ -836,4 +922,3 @@ mod tests {
836 }922 }
837 }923 }
838 }924 }
839-
crates/ec-truehd/src/encode.rsadded+419 -0
@@ -0,0 +1,419 @@
1+//! A stereo, lossless TrueHD encoder.
2+//!
3+//! **Scope (r1)**: 44.1/48 kHz family stereo only, one substream, one
4+//! restart header per access unit (so no cross-AU predictor/parameter
5+//! state), no matrixing (0 primitive matrices — the stereo pair is written
6+//! as two independent, uncorrelated channels) and no FIR/IIR prediction
7+//! (filter order 0 on both channels): every sample is written raw, as a
8+//! 24-bit offset-binary residual (`codebook = 0`, `huff_lsbs = 24`,
9+//! `quant_step = 0`), which [`crate::decode::Core::read_block`] reconstructs
10+//! back to the exact sample with no predictor and no quantization. This
11+//! trades compression for the shortest bitstream that is still conformant:
12+//! every field this build's own decoder does not need to see change is left
13+//! at the restart header's own reset default (`Substream::new()`), so the
14+//! encoder only ever sets `params_present`/`restart_present`, block size,
15+//! and the per-channel codebook/`huff_lsbs` pair.
16+//!
17+//! **Restart header self-check**: the lossless-check byte a restart header
18+//! after the first carries is verified by the decoder against the samples
19+//! output by the *previous* restart interval ([`decode::Core::output`]'s
20+//! `lossless_check_data` fold); since every access unit here is its own
21+//! restart interval, this encoder folds each AU's own samples the same way
22+//! and carries that byte into the next AU's restart header.
23+
24+use std::collections::VecDeque;
25+
26+use ec_core::bitio::BitWriter;
27+use ec_core::error::{Error, Result};
28+use ec_core::frame::{ChannelLayout, Frame, SampleFormat};
29+use ec_core::packet::Packet;
30+use ec_core::registry::{AudioParameters, CodecId, CodecParameters, Encoder, MediaParameters};
31+
32+use crate::decode::restart_checksum;
33+use crate::sync::MAJOR_SYNC_TRUEHD;
34+
35+/// `0x31EA >> 1`: the restart header's 13-bit sync field, common to both
36+/// noise types (the 14th bit picks the type).
37+const RESTART_SYNC13: u32 = 0x31EA >> 1;
38+/// Offset-binary bias for a 24-bit residual with no predictor and no
39+/// quantization: `sample + 2^23`, matching
40+/// [`crate::decode::Substream::recompute_sign_offset`] at `codebook = 0`,
41+/// `huff_lsbs = 24`, `quant_step = 0`.
42+const SAMPLE_BIAS_24: i64 = 1 << 23;
43+
44+/// XOR-fold a 32-bit word to 8 bits (same fold [`decode::Core::output`]
45+/// uses for the lossless-check byte).
46+fn xor_32_to_8(v: u32) -> u8 {
47+ (v ^ (v >> 8) ^ (v >> 16) ^ (v >> 24)) as u8
48+}
49+
50+/// The major sync's own CRC-16 (poly `0x002D`, MSB-first table form,
51+/// matching ffmpeg's `av_crc_init(..., le=0, bits=16, poly=0x2D, ...)`):
52+/// this crate's own decoder does not validate it (see `sync.rs`'s module
53+/// docs — no public description of its generator was available to check
54+/// against), but a foreign decoder (ffmpeg's `mlp_parse.c`) does, so a
55+/// bitstream meant to round-trip through one needs a correct value.
56+fn mlp_crc16_table() -> [u32; 256] {
57+ let mut table = [0u32; 256];
58+ for (i, entry) in table.iter_mut().enumerate() {
59+ let mut c = (i as i32) << 24;
60+ for _ in 0..8 {
61+ let overflow = c >> 31;
62+ c = (c << 1) ^ ((0x002D_i32 << 16) & overflow);
63+ }
64+ *entry = (c as u32).swap_bytes();
65+ }
66+ table
67+}
68+
69+/// The major sync's checksum field (bytes 26..28, little-endian): a CRC-16
70+/// over `major_sync[0..24]`, XORed with the little-endian word at
71+/// `major_sync[24..26]`.
72+fn major_sync_checksum(major_sync: &[u8; 28]) -> u16 {
73+ let table = mlp_crc16_table();
74+ let mut crc: u32 = 0;
75+ for &b in &major_sync[..24] {
76+ crc = table[usize::from((crc as u8) ^ b)] ^ (crc >> 8);
77+ }
78+ (crc as u16) ^ u16::from_le_bytes([major_sync[24], major_sync[25]])
79+}
80+
81+/// A stereo TrueHD encoder. See the module docs for scope.
82+#[derive(Debug)]
83+pub struct TrueHdEncoder {
84+ params: CodecParameters,
85+ sample_rate: u32,
86+ rate_code: u8,
87+ /// Samples per channel a full access unit carries (`40 << (rate_code &
88+ /// 7)`); the last, partial access unit may carry fewer.
89+ access_unit_size: usize,
90+ /// Interleaved stereo samples awaiting an access unit, true PCM range
91+ /// (matches [`crate::decode::TrueHdDecoder`]'s own S32 left-justified
92+ /// output once shifted right by 8).
93+ pending: Vec<i32>,
94+ packets: VecDeque<Vec<u8>>,
95+ /// Lossless-check byte for the *next* access unit's restart header,
96+ /// folded from the access unit just written; `0` (unchecked by the
97+ /// decoder) before the first one.
98+ next_check: u8,
99+ eof: bool,
100+}
101+
102+impl TrueHdEncoder {
103+ /// An encoder for one 44.1/48 kHz-family stereo stream.
104+ pub fn new(sample_rate: u32) -> Result<TrueHdEncoder> {
105+ let (rate_code, access_unit_size) = match sample_rate {
106+ 48_000 => (0u8, 40usize),
107+ 96_000 => (1u8, 80usize),
108+ 192_000 => (2u8, 160usize),
109+ 44_100 => (8u8, 40usize),
110+ 88_200 => (9u8, 80usize),
111+ 176_400 => (10u8, 160usize),
112+ other => {
113+ return Err(Error::unsupported(
114+ format!("TrueHD encoding at {other} Hz"),
115+ "only the 44.1/48 kHz families are implemented",
116+ ));
117+ }
118+ };
119+ let mut params = CodecParameters::new(CodecId::TrueHd);
120+ params.media = MediaParameters::Audio(AudioParameters {
121+ sample_rate,
122+ layout: ChannelLayout::Stereo,
123+ format: Some(SampleFormat::S32),
124+ bits_per_sample: None,
125+ });
126+ Ok(TrueHdEncoder {
127+ params,
128+ sample_rate,
129+ rate_code,
130+ access_unit_size,
131+ pending: Vec::new(),
132+ packets: VecDeque::new(),
133+ next_check: 0,
134+ eof: false,
135+ })
136+ }
137+
138+ /// Encodes one access unit from `samples` (interleaved stereo, `<=
139+ /// access_unit_size` per channel — a shorter slice writes a shorter,
140+ /// still fully self-contained, access unit).
141+ fn encode_access_unit(&mut self, samples: &[i32]) -> Vec<u8> {
142+ let n = samples.len() / 2;
143+ debug_assert!(n <= self.access_unit_size);
144+
145+ let mut seg = BitWriter::new();
146+ seg.write_bit(true); // params_present
147+ seg.write_bit(true); // restart_present
148+
149+ seg.write_bits(RESTART_SYNC13, 13);
150+ seg.write_bit(true); // noise_type (0x31EB); unused, no matrices read it
151+ seg.write_bits(0, 16); // output_timing, uninterpreted by the decoder
152+ seg.write_bits(0, 4); // min_channel
153+ seg.write_bits(1, 4); // max_channel
154+ seg.write_bits(1, 4); // max_matrix_channel
155+ seg.write_bits(0, 4); // noise_shift
156+ seg.write_bits(0, 23); // noisegen_seed
157+ seg.write_bits(0, 19); // reserved
158+ seg.write_bit(false); // data_check_present
159+ seg.write_bits(u32::from(self.next_check), 8); // lossless_check
160+ seg.write_bits(0, 16); // reserved
161+ seg.write_bits(0, 6); // ch_assign: matrix channel 0 -> output slot 0
162+ seg.write_bits(1, 6); // ch_assign: matrix channel 1 -> output slot 1
163+ let bit_size = seg.bit_len() - 2; // restart_checksum's own convention
164+ let crc = restart_checksum(seg.as_bytes(), bit_size);
165+ seg.write_bits(u32::from(crc), 8);
166+
167+ seg.write_bit(false); // presence-flags gate: keep the restart's 0xFF default
168+ seg.write_bit(true); // blocksize gate
169+ seg.write_bits(n as u32, 9);
170+ seg.write_bit(false); // matrix gate: keep 0 matrices
171+ seg.write_bit(false); // output-shift gate: keep shift 0
172+ seg.write_bit(false); // quant-step gate: keep step 0
173+ for _ch in 0..2 {
174+ seg.write_bit(true); // per-channel gate
175+ seg.write_bit(false); // FIR gate: keep order 0
176+ seg.write_bit(false); // IIR gate: keep order 0
177+ seg.write_bit(false); // huff_offset gate: keep 0
178+ seg.write_bits(0, 2); // codebook 0: raw, no Huffman code
179+ seg.write_bits(24, 5); // huff_lsbs: full 24-bit raw residual
180+ }
181+
182+ for &sample in samples {
183+ let raw = ((i64::from(sample) + SAMPLE_BIAS_24) as u32) & 0x00FF_FFFF;
184+ seg.write_bits(raw, 24);
185+ }
186+
187+ seg.write_bit(true); // end_of_segment
188+ seg.align_to_byte();
189+ if seg.bit_len() % 16 != 0 {
190+ seg.write_bits(0, 8);
191+ }
192+ let seg_bytes = seg.into_bytes();
193+
194+ // Fold this AU's own samples the way `decode::Core::output` does,
195+ // for the *next* AU's restart header.
196+ let mut fold = 0u32;
197+ for (i, &sample) in samples.iter().enumerate() {
198+ fold ^= ((sample as u32) & 0x00FF_FFFF) << (i % 2);
199+ }
200+ self.next_check = xor_32_to_8(fold);
201+
202+ // A foreign decoder (ffmpeg's mlp_parse.c) reads more of the major
203+ // sync than this crate's own decoder does: the two 13/5-bit
204+ // "channel arrangement" fields (`ch_arr`/`ch_arr2`, both set to a
205+ // stereo-only chanmap of 1 so `mlpdec.c` reports AV_CH_LAYOUT_STEREO
206+ // and `group1_bits == 24` so it decodes at S32) and `num_substreams`
207+ // (4 bits, at byte 16's top nibble) — 1, matching our own single-
208+ // substream directory.
209+ let mut major_sync = [0u8; 28];
210+ major_sync[0..4].copy_from_slice(&MAJOR_SYNC_TRUEHD.to_be_bytes());
211+ major_sync[4] = self.rate_code << 4; // low nibble ignored by both decoders
212+ major_sync[5] = 0x00;
213+ major_sync[6] = 0x80; // ch_arr low bit (=1) + ch_arr2 top 5 bits (0)
214+ major_sync[7] = 0x01; // ch_arr2 low 8 bits (=1)
215+ major_sync[16] = 0x10; // num_substreams = 1
216+ let checksum = major_sync_checksum(&major_sync);
217+ major_sync[26..28].copy_from_slice(&checksum.to_le_bytes());
218+ let dir_word = (seg_bytes.len() as u16 / 2) & 0x0FFF; // 1 substream, no extra word
219+
220+ let total_len = 4 + major_sync.len() + 2 + seg_bytes.len();
221+ let len_words = (total_len as u16 / 2) & 0x0FFF;
222+ let dir_bytes = dir_word.to_be_bytes();
223+ // Not "unused" after all: a foreign decoder (ffmpeg's mlpdec.c,
224+ // `ff_mlp_calculate_parity`) folds the AU header's 4 bytes against
225+ // the substream directory's bytes and rejects the AU unless the
226+ // result's two nibbles are bitwise complements. This crate's own
227+ // decoder never checks it (`sync.rs`'s docs), so the nibble is free
228+ // to pick; find the one value (of 16) that satisfies the fold.
229+ let check_nibble = (0u8..16)
230+ .find(|&cn| {
231+ let b0 = (cn << 4) | ((len_words >> 8) as u8 & 0x0F);
232+ let b1 = (len_words & 0xFF) as u8;
233+ let p = b0 ^ b1 ^ dir_bytes[0] ^ dir_bytes[1];
234+ ((p >> 4) ^ p) & 0xF == 0xF
235+ })
236+ .expect("one of the 16 check-nibble values always satisfies the fold");
237+ let length_word = (u16::from(check_nibble) << 12) | len_words;
238+
239+ let mut au = Vec::with_capacity(total_len);
240+ au.extend_from_slice(&length_word.to_be_bytes());
241+ au.extend_from_slice(&0u16.to_be_bytes()); // input_timing
242+ au.extend_from_slice(&major_sync);
243+ au.extend_from_slice(&dir_bytes);
244+ au.extend_from_slice(&seg_bytes);
245+ au
246+ }
247+
248+ fn drain_full_units(&mut self) {
249+ let per_au = self.access_unit_size * 2;
250+ while self.pending.len() >= per_au {
251+ let samples: Vec<i32> = self.pending.drain(..per_au).collect();
252+ let bytes = self.encode_access_unit(&samples);
253+ self.packets.push_back(bytes);
254+ }
255+ }
256+}
257+
258+impl Encoder for TrueHdEncoder {
259+ fn codec_parameters(&self) -> &CodecParameters {
260+ &self.params
261+ }
262+
263+ fn send_frame(&mut self, frame: &Frame) -> Result<()> {
264+ let Frame::Audio(audio) = frame else {
265+ return Err(Error::corrupt("video frame pushed into a TrueHD encoder"));
266+ };
267+ if audio.format != SampleFormat::S32 {
268+ return Err(Error::unsupported(
269+ format!("{:?} input", audio.format),
270+ "this encoder takes S32 (24-bit left-justified) samples",
271+ ));
272+ }
273+ if audio.layout.channel_count() != 2 {
274+ return Err(Error::unsupported(
275+ format!("{} channel input", audio.layout.channel_count()),
276+ "this encoder writes stereo only",
277+ ));
278+ }
279+ if audio.rate != self.sample_rate {
280+ return Err(Error::unsupported(
281+ format!("{} Hz input", audio.rate),
282+ "this encoder was set up for a different sample rate",
283+ ));
284+ }
285+ if audio.planar {
286+ for i in 0..audio.samples {
287+ for plane in audio.data.iter().take(2) {
288+ let at = i * 4;
289+ let w = [plane[at], plane[at + 1], plane[at + 2], plane[at + 3]];
290+ self.pending.push(i32::from_ne_bytes(w) >> 8);
291+ }
292+ }
293+ } else {
294+ for word in audio.data[0].chunks_exact(4).take(audio.samples * 2) {
295+ self.pending
296+ .push(i32::from_ne_bytes([word[0], word[1], word[2], word[3]]) >> 8);
297+ }
298+ }
299+ self.drain_full_units();
300+ Ok(())
301+ }
302+
303+ fn receive_packet(&mut self) -> Result<Packet> {
304+ match self.packets.pop_front() {
305+ Some(data) => Ok(Packet::new(
306+ 0,
307+ ec_core::timebase::TimeBase::new(1, i64::from(self.sample_rate)),
308+ data,
309+ )),
310+ None if self.eof => Err(Error::Eof),
311+ None => Err(Error::NeedMore),
312+ }
313+ }
314+
315+ fn flush(&mut self) -> Result<()> {
316+ if !self.pending.is_empty() {
317+ let mut samples = std::mem::take(&mut self.pending);
318+ // corner-cut: TrueHD's own block-size field is invalid under 8
319+ // samples/channel (crate::decode::read_decoding_params rejects
320+ // it); a final partial access unit shorter than that is padded
321+ // by repeating its last real sample pair. Ceiling: a caller
322+ // wanting the exact original count trims the decoder's output
323+ // to it (the container's duration, same as any codec's short
324+ // final frame) — upgrade path is a real short-block encoding,
325+ // not needed at r1 scope.
326+ if samples.len() / 2 < 8 {
327+ let last = [
328+ *samples.get(samples.len().wrapping_sub(2)).unwrap_or(&0),
329+ *samples.last().unwrap_or(&0),
330+ ];
331+ while samples.len() / 2 < 8 {
332+ samples.extend_from_slice(&last);
333+ }
334+ }
335+ let bytes = self.encode_access_unit(&samples);
336+ self.packets.push_back(bytes);
337+ }
338+ self.eof = true;
339+ Ok(())
340+ }
341+}
342+
343+#[cfg(test)]
344+mod tests {
345+ use super::*;
346+ use crate::sync::TrueHdDecoder;
347+ use ec_core::frame::{AudioFrame, Frame as EcFrame};
348+ use ec_core::packet::Buf;
349+
350+ /// A deterministic tone+noise fixture, interleaved stereo S32
351+ /// left-justified, `n` samples per channel.
352+ fn tone_fixture(n: usize) -> Vec<i32> {
353+ let mut v = Vec::with_capacity(n * 2);
354+ let mut lcg: u32 = 0x12345;
355+ for i in 0..n {
356+ let l = ((i as f64 * 0.07).sin() * 4_000_000.0) as i32;
357+ lcg = lcg.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
358+ let r = l.wrapping_add((lcg >> 8) as i32 % 5000 - 2500);
359+ v.push(l.clamp(-8_388_608, 8_388_607));
360+ v.push(r.clamp(-8_388_608, 8_388_607));
361+ }
362+ v
363+ }
364+
365+ fn s32_frame(interleaved: &[i32], sample_rate: u32) -> ec_core::frame::AudioFrame {
366+ let mut bytes = Vec::with_capacity(interleaved.len() * 4);
367+ for &s in interleaved {
368+ bytes.extend_from_slice(&(s << 8).to_ne_bytes());
369+ }
370+ AudioFrame::try_new(
371+ SampleFormat::S32,
372+ false,
373+ ChannelLayout::Stereo,
374+ sample_rate,
375+ interleaved.len() / 2,
376+ vec![Buf::from_vec(bytes)],
377+ )
378+ .unwrap()
379+ }
380+
381+ /// Round-trip gate 1: encode a multi-access-unit stereo fixture (a
382+ /// partial final access unit included), decode every access unit back
383+ /// through this crate's own decoder, and check every sample exactly.
384+ #[test]
385+ fn encoder_round_trips_through_our_own_decoder() {
386+ for n in [173usize, 40, 40 * 5 + 7, 1] {
387+ let samples = tone_fixture(n);
388+ let mut enc = TrueHdEncoder::new(48_000).unwrap();
389+ enc.send_frame(&EcFrame::Audio(s32_frame(&samples, 48_000)))
390+ .unwrap();
391+ enc.flush().unwrap();
392+
393+ let mut dec = TrueHdDecoder::new();
394+ let mut decoded = Vec::new();
395+ loop {
396+ match enc.receive_packet() {
397+ Ok(pkt) => {
398+ if let Some(frame) = dec.decode_access_unit(&pkt.data).unwrap() {
399+ for word in frame.data[0].chunks_exact(4) {
400+ decoded.push(
401+ i32::from_ne_bytes([word[0], word[1], word[2], word[3]]) >> 8,
402+ );
403+ }
404+ }
405+ }
406+ Err(Error::Eof) => break,
407+ Err(e) => panic!("n={n}: {e:?}"),
408+ }
409+ }
410+ decoded.truncate(samples.len());
411+ assert_eq!(decoded, samples, "n={n}: sample mismatch");
412+ let stats = dec.check_stats();
413+ assert_eq!(stats.restart_crc_failures, 0, "n={n}: restart CRC");
414+ assert_eq!(stats.lossless_check_failures, 0, "n={n}: lossless check");
415+ assert_eq!(stats.parity_failures, 0, "n={n}: parity");
416+ assert_eq!(stats.length_mismatches, 0, "n={n}: length mismatch");
417+ }
418+ }
419+}
crates/ec-truehd/src/lib.rsmodified+6 -2
@@ -37,8 +37,12 @@
37 #![warn(missing_docs)]37 #![warn(missing_docs)]
38 38
39 pub mod decode;39 pub mod decode;
40+pub mod encode;
40 pub mod sync;41 pub mod sync;
41 42
42-pub use ec_core::Error;
43 pub use decode::CheckStats;43 pub use decode::CheckStats;
44-pub use sync::{AccessUnitHeader, MajorSyncInfo, MajorSyncFormat, SubstreamInfo, TrueHdDecoder, frame_length};44+pub use ec_core::Error;
45+pub use encode::TrueHdEncoder;
46+pub use sync::{
47+ AccessUnitHeader, MajorSyncFormat, MajorSyncInfo, SubstreamInfo, TrueHdDecoder, frame_length,
48+};
crates/ec-truehd/src/sync.rsmodified+14 -6
@@ -208,19 +208,24 @@ impl AccessUnitHeader {
208 let input_timing = u16::from_be_bytes([au[2], au[3]]);208 let input_timing = u16::from_be_bytes([au[2], au[3]]);
209 209
210 let major_sync = match au.get(4..8) {210 let major_sync = match au.get(4..8) {
211- Some(w) if w == MAJOR_SYNC_TRUEHD.to_be_bytes() || w == MAJOR_SYNC_MLP.to_be_bytes() => {211+ Some(w)
212+ if w == MAJOR_SYNC_TRUEHD.to_be_bytes() || w == MAJOR_SYNC_MLP.to_be_bytes() =>
213+ {
212 Some(MajorSyncInfo::parse(&au[4..])?)214 Some(MajorSyncInfo::parse(&au[4..])?)
213 }215 }
214 _ => None,216 _ => None,
215 };217 };
216- let dir_start = AU_HEADER_LEN + if major_sync.is_some() { MAJOR_SYNC_LEN } else { 0 };218+ let dir_start = AU_HEADER_LEN
219+ + if major_sync.is_some() {
220+ MAJOR_SYNC_LEN
221+ } else {
222+ 0
223+ };
217 224
218 let mut substreams = Vec::new();225 let mut substreams = Vec::new();
219 let mut pos = dir_start;226 let mut pos = dir_start;
220 loop {227 loop {
221- let word = au228+ let word = au.get(pos..pos + 2).ok_or(Error::NeedMore)?;
222- .get(pos..pos + 2)
223- .ok_or(Error::NeedMore)?;
224 let word = u16::from_be_bytes([word[0], word[1]]);229 let word = u16::from_be_bytes([word[0], word[1]]);
225 let flags = (word >> 12) as u8;230 let flags = (word >> 12) as u8;
226 let end_offset_words = word & 0x0FFF;231 let end_offset_words = word & 0x0FFF;
@@ -270,7 +275,10 @@ impl AccessUnitHeader {
270 } else {275 } else {
271 self.data_start + usize::from(self.substreams[i - 1].end_offset_words) * 2276 self.data_start + usize::from(self.substreams[i - 1].end_offset_words) * 2
272 };277 };
273- (start, self.data_start + usize::from(self.substreams[i].end_offset_words) * 2)278+ (
279+ start,
280+ self.data_start + usize::from(self.substreams[i].end_offset_words) * 2,
281+ )
274 }282 }
275 283
276 /// The channel layout Dolby's substream convention implies: substream 0284 /// The channel layout Dolby's substream convention implies: substream 0
crates/ec-truehd/tests/oracle.rsmodified+153 -19
@@ -12,11 +12,13 @@ use std::process::Command;
12 12
13 use ec_core::{CodecId, Demuxer};13 use ec_core::{CodecId, Demuxer};
14 use ec_matroska::MatroskaDemuxer;14 use ec_matroska::MatroskaDemuxer;
15-use ec_truehd::{frame_length, TrueHdDecoder};15+use ec_truehd::{TrueHdDecoder, TrueHdEncoder, frame_length};
16 16
17 fn find_file() -> Option<PathBuf> {17 fn find_file() -> Option<PathBuf> {
18 fn walk(dir: &Path, out: &mut Vec<PathBuf>) {18 fn walk(dir: &Path, out: &mut Vec<PathBuf>) {
19- let Ok(entries) = std::fs::read_dir(dir) else { return };19+ let Ok(entries) = std::fs::read_dir(dir) else {
20+ return;
21+ };
20 for e in entries.flatten() {22 for e in entries.flatten() {
21 let p = e.path();23 let p = e.path();
22 if p.is_dir() {24 if p.is_dir() {
@@ -37,17 +39,32 @@ fn find_file() -> Option<PathBuf> {
37 }39 }
38 40
39 fn have_ffmpeg() -> bool {41 fn have_ffmpeg() -> bool {
40- Command::new("ffmpeg").arg("-version").output().map(|o| o.status.success()).unwrap_or(false)42+ Command::new("ffmpeg")
43+ .arg("-version")
44+ .output()
45+ .map(|o| o.status.success())
46+ .unwrap_or(false)
41 }47 }
42 48
43 fn ffmpeg(args: &[&str]) -> Vec<u8> {49 fn ffmpeg(args: &[&str]) -> Vec<u8> {
44- let out = Command::new("ffmpeg").args(["-v", "error", "-nostdin"]).args(args).output().expect("run ffmpeg");50+ let out = Command::new("ffmpeg")
45- assert!(out.status.success(), "ffmpeg {args:?}: {}", String::from_utf8_lossy(&out.stderr));51+ .args(["-v", "error", "-nostdin"])
52+ .args(args)
53+ .output()
54+ .expect("run ffmpeg");
55+ assert!(
56+ out.status.success(),
57+ "ffmpeg {args:?}: {}",
58+ String::from_utf8_lossy(&out.stderr)
59+ );
46 out.stdout60 out.stdout
47 }61 }
48 62
49 fn s32le(bytes: &[u8]) -> Vec<i32> {63 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()64+ bytes
65+ .chunks_exact(4)
66+ .map(|c| i32::from_le_bytes([c[0], c[1], c[2], c[3]]))
67+ .collect()
51 }68 }
52 69
53 /// Compares `ours` with `reference` sample-for-sample; returns (exact,70 /// Compares `ours` with `reference` sample-for-sample; returns (exact,
@@ -78,12 +95,23 @@ fn first_60_seconds_of_a_real_7_1_remux_are_bit_exact() {
78 }95 }
79 const SECONDS: usize = 60;96 const SECONDS: usize = 60;
80 let mut demux = MatroskaDemuxer::new(BufReader::new(File::open(&path).unwrap())).unwrap();97 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");98+ let track = demux
99+ .streams()
100+ .iter()
101+ .find(|s| s.params.codec == CodecId::TrueHd)
102+ .expect("a TrueHD track");
82 let stream_index = track.index;103 let stream_index = track.index;
83 104
84 let reference = s32le(&ffmpeg(&[105 let reference = s32le(&ffmpeg(&[
85- "-i", path.to_str().unwrap(), "-map", &format!("0:{stream_index}"), "-t", &SECONDS.to_string(),106+ "-i",
86- "-f", "s32le", "-",107+ path.to_str().unwrap(),
108+ "-map",
109+ &format!("0:{stream_index}"),
110+ "-t",
111+ &SECONDS.to_string(),
112+ "-f",
113+ "s32le",
114+ "-",
87 ]));115 ]));
88 let channels = 8;116 let channels = 8;
89 let wanted = SECONDS * 48_000 * channels;117 let wanted = SECONDS * 48_000 * channels;
@@ -100,7 +128,9 @@ fn first_60_seconds_of_a_real_7_1_remux_are_bit_exact() {
100 if packet.stream != stream_index {128 if packet.stream != stream_index {
101 continue;129 continue;
102 }130 }
103- let frame = decoder.decode_access_unit(&packet.data).unwrap_or_else(|e| panic!("AU {aus}: {e}"));131+ let frame = decoder
132+ .decode_access_unit(&packet.data)
133+ .unwrap_or_else(|e| panic!("AU {aus}: {e}"));
104 aus += 1;134 aus += 1;
105 if let Some(f) = frame {135 if let Some(f) = frame {
106 assert_eq!(f.channels(), channels);136 assert_eq!(f.channels(), channels);
@@ -111,7 +141,9 @@ fn first_60_seconds_of_a_real_7_1_remux_are_bit_exact() {
111 let stats = decoder.check_stats();141 let stats = decoder.check_stats();
112 for ch in 0..channels {142 for ch in 0..channels {
113 let n = total / channels;143 let n = total / channels;
114- let e = (0..n).filter(|&i| ours[i * channels + ch] == reference[i * channels + ch]).count();144+ let e = (0..n)
145+ .filter(|&i| ours[i * channels + ch] == reference[i * channels + ch])
146+ .count();
115 eprintln!("channel {ch}: {e}/{n} exact");147 eprintln!("channel {ch}: {e}/{n} exact");
116 }148 }
117 eprintln!(149 eprintln!(
@@ -119,12 +151,18 @@ fn first_60_seconds_of_a_real_7_1_remux_are_bit_exact() {
119 total / channels / 48_000,151 total / channels / 48_000,
120 100.0 * exact as f64 / total as f64152 100.0 * exact as f64 / total as f64
121 );153 );
122- assert!(total >= (SECONDS - 1) * 48_000 * channels, "only {total} samples");154+ assert!(
155+ total >= (SECONDS - 1) * 48_000 * channels,
156+ "only {total} samples"
157+ );
123 assert_eq!(stats.lossless_check_failures, 0, "{stats:?}");158 assert_eq!(stats.lossless_check_failures, 0, "{stats:?}");
124 assert_eq!(stats.parity_failures, 0, "{stats:?}");159 assert_eq!(stats.parity_failures, 0, "{stats:?}");
125 assert_eq!(stats.restart_crc_failures, 0, "{stats:?}");160 assert_eq!(stats.restart_crc_failures, 0, "{stats:?}");
126 assert_eq!(stats.length_mismatches, 0, "{stats:?}");161 assert_eq!(stats.length_mismatches, 0, "{stats:?}");
127- assert!(exact as f64 >= 0.9999 * total as f64, "{exact}/{total} exact, first mismatch {first:?}");162+ assert!(
163+ exact as f64 >= 0.9999 * total as f64,
164+ "{exact}/{total} exact, first mismatch {first:?}"
165+ );
128 }166 }
129 167
130 /// An externally encoded MLP stream (raw access units) decoded by us must168 /// An externally encoded MLP stream (raw access units) decoded by us must
@@ -140,15 +178,33 @@ fn externally_encoded_mlp_round_trips_bit_exact() {
140 std::fs::create_dir_all(&dir).unwrap();178 std::fs::create_dir_all(&dir).unwrap();
141 let mut failures = Vec::new();179 let mut failures = Vec::new();
142 for (codec, layout, channels) in [180 for (codec, layout, channels) in [
143- ("mlp", "mono", 1usize), ("mlp", "stereo", 2), ("mlp", "5.1", 6),181+ ("mlp", "mono", 1usize),
144- ("truehd", "mono", 1), ("truehd", "stereo", 2), ("truehd", "5.1", 6),182+ ("mlp", "stereo", 2),
183+ ("mlp", "5.1", 6),
184+ ("truehd", "mono", 1),
185+ ("truehd", "stereo", 2),
186+ ("truehd", "5.1", 6),
145 ] {187 ] {
146 let name = format!("{codec}-{layout}");188 let name = format!("{codec}-{layout}");
147- let mlp = dir.join(format!("{name}.{}", if codec == "mlp" { "mlp" } else { "thd" }));189+ let mlp = dir.join(format!(
190+ "{name}.{}",
191+ if codec == "mlp" { "mlp" } else { "thd" }
192+ ));
148 let src = format!(193 let src = format!(
149 "anoisesrc=color=pink:amplitude=0.3:seed=7:sample_rate=48000:duration=3,aformat=sample_fmts=s32:channel_layouts={layout}"194 "anoisesrc=color=pink:amplitude=0.3:seed=7:sample_rate=48000:duration=3,aformat=sample_fmts=s32:channel_layouts={layout}"
150 );195 );
151- ffmpeg(&["-y", "-f", "lavfi", "-i", &src, "-c:a", codec, "-strict", "-2", mlp.to_str().unwrap()]);196+ ffmpeg(&[
197+ "-y",
198+ "-f",
199+ "lavfi",
200+ "-i",
201+ &src,
202+ "-c:a",
203+ codec,
204+ "-strict",
205+ "-2",
206+ mlp.to_str().unwrap(),
207+ ]);
152 let reference = s32le(&ffmpeg(&["-i", mlp.to_str().unwrap(), "-f", "s32le", "-"]));208 let reference = s32le(&ffmpeg(&["-i", mlp.to_str().unwrap(), "-f", "s32le", "-"]));
153 let data = std::fs::read(&mlp).unwrap();209 let data = std::fs::read(&mlp).unwrap();
154 210
@@ -165,14 +221,92 @@ fn externally_encoded_mlp_round_trips_bit_exact() {
165 }221 }
166 let (exact, total, first) = compare(&ours, &reference);222 let (exact, total, first) = compare(&ours, &reference);
167 let stats = decoder.check_stats();223 let stats = decoder.check_stats();
168- eprintln!("{name}: {exact}/{total} exact (ours {}, reference {}), first mismatch {first:?}, {stats:?}", ours.len(), reference.len());224+ eprintln!(
225+ "{name}: {exact}/{total} exact (ours {}, reference {}), first mismatch {first:?}, {stats:?}",
226+ ours.len(),
227+ reference.len()
228+ );
169 if stats.lossless_check_failures + stats.parity_failures + stats.restart_crc_failures != 0229 if stats.lossless_check_failures + stats.parity_failures + stats.restart_crc_failures != 0
170 || exact != total230 || exact != total
171 || total < 2 * 48_000 * channels231 || total < 2 * 48_000 * channels
172 {232 {
173- failures.push(format!("{name}: {exact}/{total}, first mismatch {first:?}, {stats:?}"));233+ failures.push(format!(
234+ "{name}: {exact}/{total}, first mismatch {first:?}, {stats:?}"
235+ ));
174 }236 }
175 }237 }
176 let _ = std::fs::remove_dir_all(&dir);238 let _ = std::fs::remove_dir_all(&dir);
177 assert!(failures.is_empty(), "{failures:#?}");239 assert!(failures.is_empty(), "{failures:#?}");
178 }240 }
241+
242+/// GATE 2: a foreign decoder (ffmpeg's own `truehd`/MLP decoder, not this
243+/// crate's) decodes bytes from [`TrueHdEncoder`] sample-exact against the
244+/// PCM that went in — the decisive oracle per the shared-oracle-blindness
245+/// class (see the project ledger): our own decoder alone, as an encoder
246+/// gate, would only prove the two halves of this crate agree with each
247+/// other.
248+#[test]
249+fn ffmpeg_decodes_our_encoder_bit_exact() {
250+ if !have_ffmpeg() {
251+ eprintln!("ffmpeg not found, skipping");
252+ return;
253+ }
254+ use ec_core::frame::{AudioFrame, ChannelLayout, Frame, SampleFormat};
255+ use ec_core::packet::Buf;
256+ use ec_core::registry::Encoder;
257+
258+ let n = 48_000usize;
259+ let mut samples = Vec::with_capacity(n * 2);
260+ let mut lcg: u32 = 0xC0FF_EE00;
261+ for i in 0..n {
262+ let l = ((i as f64 * 440.0 * std::f64::consts::TAU / 48_000.0).sin() * 3_000_000.0) as i32;
263+ lcg = lcg.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
264+ let r = l.wrapping_add((lcg >> 8) as i32 % 20_000 - 10_000);
265+ samples.push(l.clamp(-8_388_608, 8_388_607));
266+ samples.push(r.clamp(-8_388_608, 8_388_607));
267+ }
268+ let mut bytes = Vec::with_capacity(samples.len() * 4);
269+ for &s in &samples {
270+ bytes.extend_from_slice(&(s << 8).to_le_bytes());
271+ }
272+ let reference = s32le(&bytes);
273+ let frame = AudioFrame::try_new(
274+ SampleFormat::S32,
275+ false,
276+ ChannelLayout::Stereo,
277+ 48_000,
278+ n,
279+ vec![Buf::from_vec(bytes)],
280+ )
281+ .unwrap();
282+
283+ let mut enc = TrueHdEncoder::new(48_000).unwrap();
284+ enc.send_frame(&Frame::Audio(frame)).unwrap();
285+ enc.flush().unwrap();
286+ let mut thd = Vec::new();
287+ while let Ok(pkt) = enc.receive_packet() {
288+ thd.extend_from_slice(&pkt.data);
289+ }
290+
291+ let dir = std::env::temp_dir().join(format!("ec-truehd-enc-oracle-{}", std::process::id()));
292+ std::fs::create_dir_all(&dir).unwrap();
293+ let path = dir.join("ours.thd");
294+ std::fs::write(&path, &thd).unwrap();
295+ let out = ffmpeg(&[
296+ "-f",
297+ "truehd",
298+ "-i",
299+ path.to_str().unwrap(),
300+ "-f",
301+ "s32le",
302+ "-",
303+ ]);
304+ let _ = std::fs::remove_dir_all(&dir);
305+
306+ let decoded = s32le(&out);
307+ let (exact, total, first) = compare(&decoded, &reference);
308+ assert_eq!(
309+ exact, total,
310+ "ffmpeg vs our own PCM: first mismatch {first:?} of {total}"
311+ );
312+}