diff --git a/Cargo.lock b/Cargo.lock index eca22387..896a11e9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -409,6 +409,7 @@ dependencies = [ "ec-ogg", "ec-opus", "ec-riff", + "ec-truehd", "ec-vorbis", ] @@ -428,6 +429,14 @@ dependencies = [ "ec-pgs", ] +[[package]] +name = "ec-truehd" +version = "0.1.0" +dependencies = [ + "ec-core", + "ec-matroska", +] + [[package]] name = "ec-va" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 41db14c8..99ce43a7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -30,6 +30,7 @@ ec-ogg = { path = "crates/ec-ogg", version = "0.1.0" } ec-opus = { path = "crates/ec-opus", version = "0.1.0" } ec-probe = { path = "crates/ec-probe", version = "0.1.0" } ec-riff = { path = "crates/ec-riff", version = "0.1.0" } +ec-truehd = { path = "crates/ec-truehd", version = "0.1.0" } ec-va = { path = "crates/ec-va", version = "0.1.0" } ec-vorbis = { path = "crates/ec-vorbis", version = "0.1.0" } ec-vp9-syntax = { path = "crates/ec-vp9-syntax", version = "0.1.0" } diff --git a/crates/ec-matroska/src/demux.rs b/crates/ec-matroska/src/demux.rs index c5f6638a..f1cc12cc 100644 --- a/crates/ec-matroska/src/demux.rs +++ b/crates/ec-matroska/src/demux.rs @@ -1118,8 +1118,6 @@ pub(crate) fn codec_of(id: &str, bit_depth: u32) -> Option { "A_VORBIS" => CodecId::Vorbis, "A_AC3" => CodecId::Ac3, "A_EAC3" => CodecId::EAc3, - // Named rather than dropped: nothing here decodes them, and a track a - // player lists as unsupported is a better answer than a silent one. "A_TRUEHD" | "A_MLP" => CodecId::TrueHd, id if id.starts_with("A_DTS") => CodecId::Dts, "A_FLAC" => CodecId::Flac, diff --git a/crates/ec-matroska/src/mux.rs b/crates/ec-matroska/src/mux.rs index 966fbbc0..09f8f61a 100644 --- a/crates/ec-matroska/src/mux.rs +++ b/crates/ec-matroska/src/mux.rs @@ -676,6 +676,7 @@ pub(crate) fn matroska_codec_id(codec: CodecId) -> Result<&'static str> { CodecId::Aac => "A_AAC", CodecId::Ac3 => "A_AC3", CodecId::EAc3 => "A_EAC3", + CodecId::TrueHd => "A_TRUEHD", CodecId::Alac => "A_ALAC", CodecId::Flac => "A_FLAC", CodecId::Mp3 => "A_MPEG/L3", diff --git a/crates/ec-matroska/tests/matroska.rs b/crates/ec-matroska/tests/matroska.rs index 2b83ac02..45fb5d73 100644 --- a/crates/ec-matroska/tests/matroska.rs +++ b/crates/ec-matroska/tests/matroska.rs @@ -49,6 +49,42 @@ fn aac_priming_round_trips_through_codec_delay() { ); } +/// A TrueHD track written by this crate's own muxer reads back as TrueHD: +/// `A_TRUEHD` round trips through demux -> mux -> demux with the packets +/// intact. +#[test] +fn truehd_codec_id_round_trips_through_remux() { + let rate = TimeBase::from_rate(48_000); + let mut info = StreamInfo::new(0, rate, ec_core::CodecParameters::new(CodecId::TrueHd)); + if let MediaParameters::Audio(a) = &mut info.params.media { + a.sample_rate = 48_000; + a.layout = ec_core::ChannelLayout::Surround7_1; + } + + let src = work().join("truehd-source.mkv"); + let mut muxer = MatroskaMuxer::new(File::create(&src).expect("output")); + let stream = muxer.add_stream(info).expect("stream declared"); + for i in 0..5i64 { + let mut packet = Packet::new(stream, rate, vec![0xAAu8; 32]); + packet.pts = Some(i * 40); + packet.flags.keyframe = true; + muxer.write_packet(&packet).expect("packet written"); + } + muxer.finish().expect("finished"); + + let dst = work().join("truehd-remuxed.mkv"); + let packets = remux(&src, &dst); + assert_eq!(packets, 5, "every packet carried across the remux"); + + let demuxer = + MatroskaDemuxer::new(BufReader::new(File::open(&dst).expect("opens"))).expect("reopens"); + assert_eq!( + demuxer.streams()[0].params.codec, + CodecId::TrueHd, + "A_TRUEHD survives demux -> mux -> demux" + ); +} + fn fixtures() -> PathBuf { Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures") } diff --git a/crates/ec-probe/Cargo.toml b/crates/ec-probe/Cargo.toml index 5d30bac6..9e09d54c 100644 --- a/crates/ec-probe/Cargo.toml +++ b/crates/ec-probe/Cargo.toml @@ -18,4 +18,5 @@ ec-mp4 = { workspace = true } ec-ogg = { workspace = true } ec-opus = { workspace = true } ec-riff = { workspace = true } +ec-truehd = { workspace = true } ec-vorbis = { workspace = true } diff --git a/crates/ec-probe/src/decoder.rs b/crates/ec-probe/src/decoder.rs index c5b149bc..4a892689 100644 --- a/crates/ec-probe/src/decoder.rs +++ b/crates/ec-probe/src/decoder.rs @@ -18,6 +18,7 @@ enum Inner { Mp3(Box), Vorbis(Box), Ac3(Box), + TrueHd(Box), Aac(Box), Alac(Box), Opus(Box), @@ -99,6 +100,7 @@ impl AudioDecoder { Inner::Vorbis(Box::new(ec_vorbis::VorbisDecoder::new(&headers)?)) } CodecId::Ac3 | CodecId::EAc3 => Inner::Ac3(Box::new(ec_ac3::Ac3Decoder::new())), + CodecId::TrueHd => Inner::TrueHd(Box::new(ec_truehd::TrueHdDecoder::new())), CodecId::Aac => { let decoder = match extradata { Some(asc) => ec_aac::AacDecoder::with_config_bytes(asc)?, @@ -175,6 +177,7 @@ impl AudioDecoder { Inner::Mp3(d) => drain(d.as_mut(), packet, out)?, Inner::Vorbis(d) => drain(d.as_mut(), packet, out)?, Inner::Ac3(d) => drain(d.as_mut(), packet, out)?, + Inner::TrueHd(d) => drain(d.as_mut(), packet, out)?, Inner::Aac(d) => { let audio = d.decode(&packet.data, packet.pts)?; self.channels = usize::from(audio.channels).max(1); @@ -264,6 +267,7 @@ impl AudioDecoder { Inner::Mp3(d) => flush_drain(d.as_mut(), out)?, Inner::Vorbis(d) => flush_drain(d.as_mut(), out)?, Inner::Ac3(d) => flush_drain(d.as_mut(), out)?, + Inner::TrueHd(d) => flush_drain(d.as_mut(), out)?, // AAC, ALAC, Opus and PCM decode a packet at a time with nothing // held back across the end of the file. Inner::Aac(_) | Inner::Alac(_) | Inner::Opus(_) | Inner::Pcm(_) => {} @@ -302,6 +306,7 @@ impl AudioDecoder { Inner::Mp3(d) => d.reset(), Inner::Vorbis(d) => d.reset(), Inner::Ac3(d) => d.reset(), + Inner::TrueHd(d) => d.reset(), Inner::Aac(d) => **d = ec_aac::AacDecoder::new(), Inner::Alac(d) => d.reset(), Inner::Opus(d) => d.reset(), diff --git a/crates/ec-probe/src/lib.rs b/crates/ec-probe/src/lib.rs index 04bee1e8..22a95527 100644 --- a/crates/ec-probe/src/lib.rs +++ b/crates/ec-probe/src/lib.rs @@ -20,7 +20,7 @@ //! - **A track this cannot decode is listed, not hidden.** [`Reader::streams`] //! reports every stream the container declares and //! [`Reader::unsupported`] names the ones with no decoder *and why* — a -//! TrueHD track says "TrueHD", not silence. Cover art is not a video track +//! DTS track says "DTS", not silence. Cover art is not a video track //! and never appears as one. #![forbid(unsafe_code)] diff --git a/crates/ec-probe/tests/library.rs b/crates/ec-probe/tests/library.rs index b5b5ea12..b3fd18d0 100644 --- a/crates/ec-probe/tests/library.rs +++ b/crates/ec-probe/tests/library.rs @@ -193,11 +193,10 @@ fn a_real_library_sweep() { assert!(failures.is_empty(), "{}", failures.join("\n")); } -/// The TrueHD remux in his library: the track is *listed*, with a reason, and -/// the AC-3 track beside it still decodes. A file whose sound is refused -/// silently is the failure this exists to prevent. +/// The TrueHD remux in his library: the track decodes through the unified +/// reader, 7.1 at 48 kHz, with the AC-3 track beside it still decoding too. #[test] -fn an_undecodable_track_is_named_not_hidden() { +fn a_truehd_track_decodes() { let Some((path, ..)) = manifest() .into_iter() .find(|(p, _, acodecs, _)| acodecs.contains("truehd") && p.exists()) @@ -205,18 +204,19 @@ fn an_undecodable_track_is_named_not_hidden() { eprintln!("no TrueHD file in the manifest — skipping"); return; }; - let reader = Reader::open(&path).expect("open"); - let unsupported = reader.unsupported(); - let truehd = unsupported + let mut reader = Reader::open(&path).expect("open"); + let truehd = reader + .streams() .iter() - .find(|u| u.codec.name() == "truehd") - .expect("the TrueHD track is listed as unsupported"); - assert!( - truehd.reason.contains("truehd"), - "the reason names the codec: {}", - truehd.reason - ); - // ...and the other track of the same file plays. + .find(|s| s.params.codec.name() == "truehd") + .cloned() + .expect("the TrueHD track is listed"); + let decoder = reader.make_decoder(truehd.index).expect("truehd decoder"); + assert_eq!(decoder.channels(), 8, "7.1 TrueHD is 8 channels"); + assert_eq!(decoder.sample_rate(), 48_000); + let frames = decode_some(&mut reader, truehd.index, 1.0).expect("decode"); + assert!(frames > 0, "no TrueHD audio came out"); + // ...and the AC-3 track beside it still decodes. let decodable: Vec<_> = reader .streams() .iter() @@ -225,14 +225,12 @@ fn an_undecodable_track_is_named_not_hidden() { .map(|s| s.params.codec.name()) .collect(); assert!( - !decodable.is_empty(), - "a file with a TrueHD track and an AC-3 one came out with nothing to play" + decodable.contains(&"ac3") || decodable.contains(&"truehd"), + "a file with a TrueHD track and an AC-3 one came out with nothing to play: {decodable:?}" ); eprintln!( - "{}: {} listed unsupported ({}), decodable: {decodable:?}", + "{}: truehd decoded {frames} frames, tracks {decodable:?}", path.file_name().unwrap().to_string_lossy(), - truehd.codec.name(), - truehd.reason ); } diff --git a/crates/ec-truehd/Cargo.toml b/crates/ec-truehd/Cargo.toml new file mode 100644 index 00000000..78f9a23a --- /dev/null +++ b/crates/ec-truehd/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "ec-truehd" +description = "Dolby TrueHD / MLP access-unit and major-sync parsing for the edith_codecs family." +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true + +[dependencies] +ec-core = { workspace = true } + +[dev-dependencies] +ec-matroska = { workspace = true } diff --git a/crates/ec-truehd/src/decode.rs b/crates/ec-truehd/src/decode.rs new file mode 100644 index 00000000..bebb14c3 --- /dev/null +++ b/crates/ec-truehd/src/decode.rs @@ -0,0 +1,839 @@ +//! The lossless substream decode: restart headers, decoding parameters, +//! Huffman/LSB residuals, FIR/IIR prediction, rematrixing with the seeded +//! noise generators, output shift — and the stream's own integrity checks +//! (restart-header CRC, per-substream parity, the lossless-check byte). +//! +//! Written from the public description of the MLP/TrueHD bitstream. Every +//! numeric constant a from-memory description could get wrong (the three +//! Huffman codebooks, the noise table, the generators' feedback taps, the +//! restart-header CRC) was *derived or confirmed* against an external +//! decoder: the codebooks were read off externally encoded mono streams +//! whose PCM is known, the 256-entry noise table was solved for by +//! constraint intersection over the real 7.1 track, and `tests/oracle.rs` +//! keeps both bit-exact. +//! +//! **Per-substream syntax** (one substream's bytes, bit-serial MSB-first): +//! +//! ```text +//! loop { +//! params_present(1) +//! restart_present(1) → restart header: +//! sync(14) = 0x31EA|0x31EB (low bit = noise type), output_timing(16), +//! min_ch(4), max_ch(4), max_matrix_ch(4), noise_shift(4), +//! noise_seed(23), reserved(19), data_check_present(1), +//! lossless_check(8), reserved(16), ch_assign(6) × (max_matrix_ch+1), +//! crc8(8, poly 0x1D) +//! decoding params (each group gated by a presence flag): +//! presence flags(8); block size(9); matrices: count(4), per matrix +//! out_ch(4) frac_bits(4) lsb_bypass(1) [present(1) coeff(frac+2)] per +//! input channel (+2 noise channels for noise type 0) [noise_shift(4) +//! for noise type 1]; output shift(4 signed) per matrix channel; +//! quant step(4) per channel; per channel: FIR/IIR (order(4), shift(4), +//! coeff_bits(5), coeff_shift(3), coeffs, [IIR state]), huff_offset(15 +//! signed), codebook(2), huff_lsbs(5) +//! block: [data check: bit count(16)] per sample: lsb-bypass bits, then +//! per channel Huffman index (codebook 1..3) + lsb bits; [crc(8)] +//! end_of_segment(1) +//! } +//! align(16) [0xD234D234 end-of-stream] [parity(8) crc8(8, not validated)] +//! ``` +//! +//! **Reconstruction**: `residual = ((index << lsb_bits) + lsbs + +//! sign_offset) << quant_step`; `sample = (predict(FIR over past samples, +//! IIR over past residual-after-FIR) + residual) & !((1 << quant_step) - 1)`; +//! then, for the highest substream only, each primitive matrix rewrites one +//! channel as `(Σ coeff·chan + noise) >> 14` masked to the quant step plus +//! its bypassed LSB; then `<< output_shift`; then `<< 8` to a left-justified +//! 24-in-32 sample. +//! +//! **Channel order**: TrueHD's 8-channel presentation with assignment `0x4F` +//! (L R C LFE Ls Rs Lrs Rrs) lands on [`ChannelLayout::Surround7_1`]'s +//! FL FR FC LFE BL BR SL SR as output index `[0,1,2,3,6,7,4,5]` — TrueHD's +//! Ls/Rs pair is the *side* pair, Lrs/Rrs the *back* pair. 2- and 6-channel +//! presentations map 1:1. + +use ec_core::bitio::BitReader; +use ec_core::error::{Error, Result}; +use ec_core::frame::{AudioFrame, ChannelLayout, SampleFormat}; +use ec_core::packet::Buf; + +use crate::sync::AccessUnitHeader; + +/// Highest matrix/output channel index the 2/6/8-channel presentations use; +/// anything above is the 16-channel object substream, refused. +const MAX_MATRIX_CHANNEL: usize = 7; +/// Sample-buffer width: 8 PCM channels plus the 2 noise channels noise type 0 +/// appends after the last matrix channel. +const MAX_CHANNELS: usize = MAX_MATRIX_CHANNEL + 3; +const MAX_MATRICES: usize = 8; +const MAX_FILTER_ORDER: usize = 8; +const END_OF_STREAM: u32 = 0xD234_D234; + +/// The fixed 256-entry dither table noise type 1 (TrueHD's `0x31EB`) draws +/// matrix noise from, indexed by the generator's top byte. A constant of the +/// format; every entry was solved for exactly (constraint intersection over +/// 72 000 access units of the real 7.1 track against the external decoder's +/// output) and is kept bit-exact by `tests/oracle.rs`. +#[rustfmt::skip] +const NOISE_TABLE: [i8; 256] = [ + 30, 51, 22, 54, 3, 7, -4, 38, 14, 55, 46, 81, 22, 58, -3, 2, + 52, 31, -7, 51, 15, 44, 74, 30, 85, -17, 10, 33, 18, 80, 28, 62, + 10, 32, 23, 69, 72, 26, 35, 17, 73, 60, 8, 56, 2, 6, -2, -5, + 51, 4, 11, 50, 66, 76, 21, 44, 33, 47, 1, 26, 64, 48, 57, 40, + 38, 16, -10, -28, 92, 22, -18, 29, -10, 5, -13, 49, 19, 24, 70, 34, + 61, 48, 30, 14, -6, 25, 58, 33, 42, 60, 67, 17, 54, 17, 22, 30, + 67, 44, -9, 50, -11, 43, 40, 32, 59, 82, 13, 49, -14, 55, 60, 36, + 48, 49, 31, 47, 15, 12, 4, 65, 1, 23, 29, 39, 45, -2, 84, 69, + 0, 72, 37, 57, 27, 41, -15, -16, 35, 31, 14, 61, 24, 0, 27, 24, + 16, 41, 55, 34, 53, 9, 56, 12, 25, 29, 53, 5, 20, -20, -8, 20, + 13, 28, -3, 78, 38, 16, 11, 62, 46, 29, 21, 24, 46, 65, 43, -23, + 89, 18, 74, 21, 38, -12, 19, 12, -19, 8, 15, 33, 4, 57, 9, -8, + 36, 35, 26, 28, 7, 83, 63, 79, 75, 11, 3, 87, 37, 47, 34, 40, + 39, 19, 20, 42, 27, 34, 39, 77, 13, 42, 59, 64, 45, -1, 32, 37, + 45, -5, 53, -6, 7, 36, 50, 23, 6, 32, 9, -21, 18, 71, 27, 52, + -25, 31, 35, 42, -1, 68, 63, 52, 26, 43, 66, 37, 41, 25, 40, 70, +]; + +const PARAM_BLOCKSIZE: u8 = 1 << 7; +const PARAM_MATRIX: u8 = 1 << 6; +const PARAM_OUTSHIFT: u8 = 1 << 5; +const PARAM_QUANTSTEP: u8 = 1 << 4; +const PARAM_FIR: u8 = 1 << 3; +const PARAM_IIR: u8 = 1 << 2; +const PARAM_HUFFOFFSET: u8 = 1 << 1; +const PARAM_PRESENCE: u8 = 1 << 0; + +/// The three residual codebooks as `(code, length)` per index: codebook 1 +/// covers indices 0..18, codebook 2 0..16, codebook 3 0..15. Unused tail +/// entries have length 0. Shape: a unary run `0…01` of length `7 - i + 2` +/// below the centre, `010…01` above it, and 1-3 short codes at the centre +/// (the three books differ only there). Verified code-for-code against an +/// external encoder's output (`tests/oracle.rs`). +pub const HUFFMAN_TABLES: [[(u16, u8); 18]; 3] = [ + [ + (0x01, 9), (0x01, 8), (0x01, 7), (0x01, 6), (0x01, 5), (0x01, 4), (0x01, 3), (0x04, 3), (0x05, 3), + (0x06, 3), (0x07, 3), (0x03, 3), (0x05, 4), (0x09, 5), (0x11, 6), (0x21, 7), (0x41, 8), (0x81, 9), + ], + [ + (0x01, 9), (0x01, 8), (0x01, 7), (0x01, 6), (0x01, 5), (0x01, 4), (0x01, 3), (0x02, 2), (0x03, 2), + (0x03, 3), (0x05, 4), (0x09, 5), (0x11, 6), (0x21, 7), (0x41, 8), (0x81, 9), (0, 0), (0, 0), + ], + [ + (0x01, 9), (0x01, 8), (0x01, 7), (0x01, 6), (0x01, 5), (0x01, 4), (0x01, 3), (0x01, 1), (0x03, 3), + (0x05, 4), (0x09, 5), (0x11, 6), (0x21, 7), (0x41, 8), (0x81, 9), (0, 0), (0, 0), (0, 0), + ], +]; + +/// 512-entry lookup per codebook: `(index, length)`, length 0 = invalid code. +struct HuffLut([[(u8, u8); 512]; 3]); + +impl HuffLut { + fn build() -> HuffLut { + let mut lut = [[(0u8, 0u8); 512]; 3]; + for (book, table) in HUFFMAN_TABLES.iter().enumerate() { + for (index, &(code, len)) in table.iter().enumerate() { + if len == 0 { + continue; + } + let base = usize::from(code) << (9 - len); + for k in 0..(1usize << (9 - len)) { + lut[book][base + k] = (index as u8, len); + } + } + } + HuffLut(lut) + } + + fn decode(&self, br: &mut BitReader, book: usize) -> Result { + let avail = br.bits_remaining().min(9) as u32; + if avail == 0 { + return Err(Error::NeedMore); + } + let bits = br.peek_bits(avail)? << (9 - avail); + let (index, len) = self.0[book][bits as usize]; + if len == 0 || u64::from(len) > br.bits_remaining() { + return Err(Error::corrupt("TrueHD: invalid Huffman code")); + } + br.skip_bits(u64::from(len))?; + Ok(i32::from(index)) + } +} + +/// Bit-serial CRC-8 (MSB first, no reflection, no final xor). +fn crc8(poly: u8, init: u8, bytes: &[u8]) -> u8 { + let mut crc = init; + for &b in bytes { + crc ^= b; + for _ in 0..8 { + crc = if crc & 0x80 != 0 { (crc << 1) ^ poly } else { crc << 1 }; + } + } + crc +} + +/// The restart header's own CRC-8 (poly 0x1D), over the header from its +/// first byte (`buf[0]`, whose two leading bits — the params/restart flags — +/// are masked off) through its last full byte and the trailing partial bits. +fn restart_checksum(buf: &[u8], bit_size: u64) -> u8 { + let bit_size = bit_size as usize + 2; + let num_bytes = bit_size / 8; + let mut crc = crc8(0x1D, 0, &[buf[0] & 0x3F]); + crc = crc8(0x1D, crc, &buf[1..num_bytes - 1]); + crc ^= buf[num_bytes - 1]; + for i in 0..(bit_size & 7) { + let top = crc & 0x80 != 0; + crc <<= 1; + if top { + crc ^= 0x1D; + } + crc ^= (buf[num_bytes] >> (7 - i)) & 1; + } + crc +} + +/// XOR-fold a 32-bit word to 8 bits. +fn xor_32_to_8(v: u32) -> u8 { + (v ^ (v >> 8) ^ (v >> 16) ^ (v >> 24)) as u8 +} + +#[derive(Debug, Clone, Copy, Default)] +struct Filter { + order: usize, + shift: u32, + coeffs: [i32; MAX_FILTER_ORDER], + /// History, most recent first. + state: [i32; MAX_FILTER_ORDER], +} + +#[derive(Debug, Clone, Copy, Default)] +struct ChannelParams { + fir: Filter, + iir: Filter, + huff_offset: i32, + sign_huff_offset: i32, + codebook: u8, + huff_lsbs: u8, +} + +#[derive(Debug, Clone, Copy, Default)] +struct Matrix { + out_ch: usize, + lsb_bypass: bool, + noise_shift: u32, + coeffs: [i32; MAX_CHANNELS], +} + +#[derive(Debug, Clone)] +struct Substream { + restart_seen: bool, + noise_type: bool, + min_channel: usize, + max_channel: usize, + max_matrix_channel: usize, + noise_shift: u32, + noisegen_seed: u32, + data_check_present: bool, + lossless_check_data: u32, + ch_assign: [usize; MAX_CHANNELS], + param_presence_flags: u8, + blocksize: usize, + matrices: Vec, + output_shift: [i32; MAX_CHANNELS], + quant_step_size: [u32; MAX_CHANNELS], + channels: [ChannelParams; MAX_CHANNELS], + /// Samples decoded so far in this access unit. + blockpos: usize, +} + +impl Substream { + fn new() -> Substream { + Substream { + restart_seen: false, + noise_type: false, + min_channel: 0, + max_channel: 0, + max_matrix_channel: 0, + noise_shift: 0, + noisegen_seed: 0, + data_check_present: false, + lossless_check_data: 0, + ch_assign: [0; MAX_CHANNELS], + param_presence_flags: 0xFF, + blocksize: 8, + matrices: Vec::new(), + output_shift: [0; MAX_CHANNELS], + quant_step_size: [0; MAX_CHANNELS], + channels: [ChannelParams::default(); MAX_CHANNELS], + blockpos: 0, + } + } + + fn recompute_sign_offset(&mut self, ch: usize) { + let cp = &mut self.channels[ch]; + let lsb_bits = i32::from(cp.huff_lsbs) - self.quant_step_size[ch] as i32; + let sign_shift = lsb_bits + if cp.codebook > 0 { 2 - i32::from(cp.codebook) } else { -1 }; + let mut off = cp.huff_offset; + if cp.codebook > 0 { + off -= 7 << lsb_bits; + } + if sign_shift >= 0 { + off -= 1 << sign_shift; + } + cp.sign_huff_offset = off; + } +} + +/// Integrity counters the decoder keeps across access units; every one is a +/// stream-side self-check that stays zero on a clean decode. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct CheckStats { + /// Restart headers whose CRC-8 did not match. + pub restart_crc_failures: u64, + /// Restart headers seen (the lossless-check byte is verified at each + /// one after the first, against the samples output since the previous). + pub restart_headers: u64, + /// Lossless-check bytes that did not match the output. + pub lossless_check_failures: u64, + /// Substream segments whose parity byte did not match. + pub parity_failures: u64, + /// Substream segments whose bit count did not land on the directory's + /// end pointer. + pub length_mismatches: u64, +} + +/// Decoder state shared across the substreams of one stream. +#[derive(Debug, Clone)] +pub(crate) struct Core { + huff: std::sync::Arc, + substreams: Vec, + /// Samples per access unit (40 at 48 kHz) and its next power of two. + access_unit_size: usize, + access_unit_size_pow2: usize, + sample_rate: u32, + /// The major sync's 8-channel presentation assignment mask. + ch8_assignment: u16, + sample_buffer: Vec<[i32; MAX_CHANNELS]>, + bypassed_lsbs: Vec<[i32; MAX_MATRICES]>, + noise_buffer: Vec, + /// Self-check tallies. + pub stats: CheckStats, +} + +struct HuffLutBox(HuffLut); + +impl std::fmt::Debug for HuffLutBox { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("HuffLut") + } +} + +impl Core { + pub(crate) fn new() -> Core { + Core { + huff: std::sync::Arc::new(HuffLutBox(HuffLut::build())), + substreams: Vec::new(), + access_unit_size: 0, + access_unit_size_pow2: 0, + sample_rate: 0, + ch8_assignment: 0, + sample_buffer: Vec::new(), + bypassed_lsbs: Vec::new(), + noise_buffer: Vec::new(), + stats: CheckStats::default(), + } + } + + pub(crate) fn reset(&mut self) { + self.substreams.clear(); + self.access_unit_size = 0; + } + + /// Decodes one access unit whose header already parsed; `None` until the + /// first major sync and every substream's first restart header are seen. + pub(crate) fn decode(&mut self, header: &AccessUnitHeader, data: &[u8]) -> Result> { + if !self.prepare(header)? || !self.decode_substreams(header, data)? { + return Ok(None); + } + self.finish() + } + + /// Takes a major sync's stream parameters on board; `Ok(false)` while no + /// major sync has been seen yet. + fn prepare(&mut self, header: &AccessUnitHeader) -> Result { + if let Some(sync) = &header.major_sync { + let shift = sync.rate_code & 7; + if shift > 2 { + return Err(Error::unsupported( + format!("TrueHD sample rate code {}", sync.rate_code), + "the format reserves it", + )); + } + self.access_unit_size = 40 << shift; + self.access_unit_size_pow2 = 64 << shift; + self.sample_rate = sync.sample_rate; + if self.substreams.len() != header.substreams.len() { + self.substreams = vec![Substream::new(); header.substreams.len()]; + } + self.sample_buffer = vec![[0; MAX_CHANNELS]; self.access_unit_size]; + self.bypassed_lsbs = vec![[0; MAX_MATRICES]; self.access_unit_size]; + self.noise_buffer = vec![0; self.access_unit_size_pow2]; + self.ch8_assignment = sync.ch8_assignment; + } + Ok(self.access_unit_size != 0 && self.substreams.len() == header.substreams.len()) + } + + /// Every substream's blocks into `sample_buffer`; `Ok(false)` while some + /// substream still awaits its first restart header. + fn decode_substreams(&mut self, header: &AccessUnitHeader, data: &[u8]) -> Result { + let mut all_seen = true; + for (i, info) in header.substreams.iter().enumerate() { + let (start, end) = header.substream_span(i); + let seg = data.get(start..end).ok_or(Error::NeedMore)?; + let seen = self.decode_substream(i, seg, info.flags & 0x2 != 0)?; + all_seen &= seen; + } + Ok(all_seen) + } + + /// Rematrix + output of the top substream for the current access unit. + fn finish(&mut self) -> Result> { + let top = self.substreams.len() - 1; + let samples = self.substreams[top].blockpos; + let channels = self.substreams[top].max_matrix_channel + 1; + let layout = ChannelLayout::from_count(channels); + if layout == ChannelLayout::Surround7_1 && self.ch8_assignment != 0x4F { + return Err(Error::unsupported( + format!("TrueHD 8-channel presentation with channel assignment {:#x}", self.ch8_assignment), + "only the standard 7.1 (L R C LFE Ls Rs Lrs Rrs) assignment is mapped", + )); + } + self.rematrix(top); + let frame = self.output(top, layout, samples)?; + Ok(Some(frame)) + } + + /// One substream's segment; `Ok(false)` when no restart header has been + /// seen yet (nothing to decode until one arrives). + fn decode_substream(&mut self, idx: usize, seg: &[u8], checkdata: bool) -> Result { + let mut br = BitReader::new(seg); + self.substreams[idx].blockpos = 0; + loop { + if br.read_bit()? { + if br.read_bit()? { + self.read_restart_header(idx, &mut br, seg)?; + } + if !self.substreams[idx].restart_seen { + return Ok(false); + } + self.read_decoding_params(idx, &mut br)?; + } + if !self.substreams[idx].restart_seen { + return Ok(false); + } + self.read_block(idx, &mut br)?; + if br.bits_remaining() == 0 { + self.stats.length_mismatches += 1; + return Ok(true); + } + if br.read_bit()? { + break; + } + } + let pad = (16 - (br.bit_position() % 16)) % 16; + br.skip_bits(pad)?; + if br.bits_remaining() >= 32 && br.peek_bits(32)? == END_OF_STREAM { + br.skip_bits(32)?; + } + if checkdata { + let data_len = (br.bit_position() / 8) as usize; + if seg.len() < data_len + 2 { + return Err(Error::corrupt("TrueHD: substream check bytes missing")); + } + let parity = seg[..data_len].iter().fold(0u8, |a, &b| a ^ b) ^ 0xA9; + let parity_bits = br.read_bits(8)? as u8; + // corner-cut: the second check byte is a CRC-8 whose generator + // and span this build could not pin down (no plain CRC-8 over + // the segment, with any polynomial/init/reflection, matched + // either the real track or an external encoder's output) — it + // is skipped, not validated. Parity, the restart-header CRC and + // the lossless check cover the same data. + br.skip_bits(8)?; + if parity != parity_bits { + self.stats.parity_failures += 1; + } + } + if br.bits_remaining() != 0 { + self.stats.length_mismatches += 1; + } + Ok(true) + } + + fn read_restart_header(&mut self, idx: usize, br: &mut BitReader, seg: &[u8]) -> Result<()> { + let start = br.bit_position(); + // 0x31EA / 0x31EB as a 14-bit field: 13 bits of sync, 1 bit of + // noise type. + let sync = br.read_bits(13)?; + if sync != 0x31EA >> 1 { + return Err(Error::corrupt(format!("TrueHD: restart sync {sync:#x}"))); + } + let noise_type = br.read_bit()?; + br.skip_bits(16)?; // output timing + let min_channel = br.read_bits(4)? as usize; + let max_channel = br.read_bits(4)? as usize; + let max_matrix_channel = br.read_bits(4)? as usize; + if max_matrix_channel > MAX_MATRIX_CHANNEL || max_channel > MAX_MATRIX_CHANNEL { + return Err(Error::unsupported( + "TrueHD substream with more than 8 matrix channels", + "the 16-channel object substream is not implemented", + )); + } + if min_channel > max_channel { + return Err(Error::corrupt("TrueHD: min channel above max channel")); + } + let noise_shift = br.read_bits(4)?; + let noisegen_seed = br.read_bits(23)?; + br.skip_bits(19)?; + let data_check_present = br.read_bit()?; + let lossless_check = br.read_bits(8)? as u8; + br.skip_bits(16)?; + // Per matrix channel, the presentation's output slot it lands on; + // stored inverted (output slot → matrix channel) for `output`. + let mut ch_assign = [0usize; MAX_CHANNELS]; + for ch in 0..=max_matrix_channel { + let a = br.read_bits(6)? as usize; + if a > max_matrix_channel { + return Err(Error::corrupt("TrueHD: channel assignment out of range")); + } + ch_assign[a] = ch; + } + let expected = restart_checksum(&seg[(start / 8) as usize..], br.bit_position() - start); + let crc = br.read_bits(8)? as u8; + self.stats.restart_headers += 1; + if crc != expected { + self.stats.restart_crc_failures += 1; + } + + let is_top = idx == self.substreams.len() - 1; + let s = &mut self.substreams[idx]; + if s.restart_seen && is_top && xor_32_to_8(s.lossless_check_data) != lossless_check { + self.stats.lossless_check_failures += 1; + } + let s = &mut self.substreams[idx]; + *s = Substream { + restart_seen: true, + noise_type, + min_channel, + max_channel, + max_matrix_channel, + noise_shift, + noisegen_seed, + data_check_present, + ch_assign, + ..Substream::new() + }; + Ok(()) + } + + fn read_decoding_params(&mut self, idx: usize, br: &mut BitReader) -> Result<()> { + let s = &mut self.substreams[idx]; + if s.param_presence_flags & PARAM_PRESENCE != 0 && br.read_bit()? { + s.param_presence_flags = br.read_bits(8)? as u8; + } + let flags = s.param_presence_flags; + if flags & PARAM_BLOCKSIZE != 0 && br.read_bit()? { + s.blocksize = br.read_bits(9)? as usize; + if s.blocksize < 8 || s.blocksize > self.access_unit_size { + return Err(Error::corrupt(format!("TrueHD: block size {}", s.blocksize))); + } + } + if flags & PARAM_MATRIX != 0 && br.read_bit()? { + let count = br.read_bits(4)? as usize; + if count > MAX_MATRICES { + return Err(Error::corrupt("TrueHD: too many primitive matrices")); + } + let max_chan = s.max_matrix_channel + if s.noise_type { 0 } else { 2 }; + s.matrices.clear(); + for _ in 0..count { + let out_ch = br.read_bits(4)? as usize; + let frac_bits = br.read_bits(4)?; + let lsb_bypass = br.read_bit()?; + if out_ch > s.max_matrix_channel || frac_bits > 14 { + return Err(Error::corrupt("TrueHD: matrix parameters out of range")); + } + let mut coeffs = [0i32; MAX_CHANNELS]; + for c in coeffs.iter_mut().take(max_chan + 1) { + if br.read_bit()? { + *c = br.read_signed(frac_bits + 2)? << (14 - frac_bits); + } + } + let noise_shift = if s.noise_type { br.read_bits(4)? } else { 0 }; + s.matrices.push(Matrix { + out_ch, + lsb_bypass, + noise_shift, + coeffs, + }); + } + } + if flags & PARAM_OUTSHIFT != 0 && br.read_bit()? { + for ch in 0..=s.max_matrix_channel { + s.output_shift[ch] = br.read_signed(4)?; + } + } + if flags & PARAM_QUANTSTEP != 0 && br.read_bit()? { + for ch in 0..=s.max_channel { + s.quant_step_size[ch] = br.read_bits(4)?; + s.recompute_sign_offset(ch); + } + } + for ch in s.min_channel..=s.max_channel { + if br.read_bit()? { + if flags & PARAM_FIR != 0 && br.read_bit()? { + read_filter(br, &mut s.channels[ch].fir, false)?; + } + if flags & PARAM_IIR != 0 && br.read_bit()? { + read_filter(br, &mut s.channels[ch].iir, true)?; + } + let cp = &s.channels[ch]; + if cp.fir.order + cp.iir.order > MAX_FILTER_ORDER { + return Err(Error::corrupt("TrueHD: FIR+IIR order above 8")); + } + if cp.fir.order > 0 && cp.iir.order > 0 && cp.fir.shift != cp.iir.shift { + return Err(Error::corrupt("TrueHD: FIR and IIR shifts differ")); + } + if flags & PARAM_HUFFOFFSET != 0 && br.read_bit()? { + s.channels[ch].huff_offset = br.read_signed(15)?; + } + s.channels[ch].codebook = br.read_bits(2)? as u8; + s.channels[ch].huff_lsbs = br.read_bits(5)? as u8; + if s.channels[ch].huff_lsbs > 24 { + return Err(Error::corrupt("TrueHD: huff_lsbs above 24")); + } + s.recompute_sign_offset(ch); + } + } + Ok(()) + } + + fn read_block(&mut self, idx: usize, br: &mut BitReader) -> Result<()> { + let s = &mut self.substreams[idx]; + let expected_end = if s.data_check_present { + Some(br.bit_position() + u64::from(br.read_bits(16)?)) + } else { + None + }; + if s.blockpos + s.blocksize > self.access_unit_size { + return Err(Error::corrupt("TrueHD: blocks exceed the access unit")); + } + for i in s.blockpos..s.blockpos + s.blocksize { + for (m, mat) in s.matrices.iter().enumerate() { + if mat.lsb_bypass { + self.bypassed_lsbs[i][m] = br.read_bit()? as i32; + } + } + for ch in s.min_channel..=s.max_channel { + let cp = &s.channels[ch]; + let qss = s.quant_step_size[ch]; + let lsb_bits = i32::from(cp.huff_lsbs) - qss as i32; + let mut result = 0i32; + if cp.codebook > 0 { + result = self.huff.0.decode(br, usize::from(cp.codebook) - 1)?; + } + if lsb_bits > 0 { + result = (result << lsb_bits) + br.read_bits(lsb_bits as u32)? as i32; + } else if lsb_bits < 0 { + return Err(Error::corrupt("TrueHD: quant step above huff_lsbs")); + } + result = result.wrapping_add(cp.sign_huff_offset).wrapping_shl(qss); + self.sample_buffer[i][ch] = result; + } + } + for ch in s.min_channel..=s.max_channel { + filter_channel(&mut s.channels[ch], s.quant_step_size[ch], &mut self.sample_buffer[s.blockpos..s.blockpos + s.blocksize], ch); + } + s.blockpos += s.blocksize; + if let Some(end) = expected_end { + if br.bit_position() != end { + self.stats.length_mismatches += 1; + } + br.skip_bits(8)?; + } + Ok(()) + } + + fn rematrix(&mut self, idx: usize) { + let s = &mut self.substreams[idx]; + let mut maxchan = s.max_matrix_channel; + if !s.noise_type { + // Two noise channels after the last matrix channel, from the + // 23-bit generator seeded by the restart header and carried on. + let mut seed = s.noisegen_seed; + for row in self.sample_buffer.iter_mut().take(s.blockpos) { + let shr7 = (seed >> 7) as u16; + row[maxchan + 1] = i32::from((seed >> 15) as u8 as i8) << s.noise_shift; + row[maxchan + 2] = i32::from(shr7 as u8 as i8) << s.noise_shift; + seed = (seed << 16) ^ (u32::from(shr7) << 5) ^ (u32::from(shr7) << 7); + } + s.noisegen_seed = seed; + maxchan += 2; + } else { + let mut seed = s.noisegen_seed; + for slot in self.noise_buffer.iter_mut() { + let shr15 = (seed >> 15) as u8; + *slot = NOISE_TABLE[usize::from(shr15)]; + seed = (seed << 8) ^ u32::from(shr15) ^ (u32::from(shr15) << 5); + } + s.noisegen_seed = seed; + } + let pow2_mask = self.access_unit_size_pow2 - 1; + let count = s.matrices.len(); + for (m, mat) in s.matrices.iter().enumerate() { + let mask = !((1i32 << s.quant_step_size[mat.out_ch]) - 1); + let mut index = count - m; + let index2 = 2 * index + 1; + for (i, row) in self.sample_buffer.iter_mut().take(s.blockpos).enumerate() { + let mut accum: i64 = 0; + for (sample, coeff) in row.iter().zip(&mat.coeffs).take(maxchan + 1) { + accum += i64::from(*sample) * i64::from(*coeff); + } + if mat.noise_shift != 0 { + index &= pow2_mask; + accum += i64::from(self.noise_buffer[index]) << (mat.noise_shift + 7); + index += index2; + } + row[mat.out_ch] = ((accum >> 14) as i32 & mask) + self.bypassed_lsbs[i][m]; + } + } + } + + fn output(&mut self, idx: usize, layout: ChannelLayout, samples: usize) -> Result { + let s = &mut self.substreams[idx]; + let channels = layout.channel_count(); + // TrueHD's Ls/Rs (output 4,5) are our side pair, Lrs/Rrs (6,7) our + // back pair. + const PERM_7_1: [usize; 8] = [0, 1, 2, 3, 6, 7, 4, 5]; + let mut bytes = Vec::with_capacity(samples * channels * 4); + for row in self.sample_buffer.iter().take(samples) { + for (out_ch, &perm) in PERM_7_1.iter().enumerate().take(channels) { + let thd_ch = if channels == 8 { perm } else { out_ch }; + let mat_ch = s.ch_assign[thd_ch]; + let sample = row[mat_ch].wrapping_shl(s.output_shift[mat_ch] as u32); + s.lossless_check_data ^= ((sample as u32) & 0xFF_FFFF) << mat_ch; + bytes.extend_from_slice(&(sample << 8).to_ne_bytes()); + } + } + AudioFrame::try_new( + SampleFormat::S32, + false, + layout, + self.sample_rate, + samples, + vec![Buf::from_vec(bytes)], + ) + } +} + +/// New coefficients for `f`; its history carries over unless the stream +/// sends an explicit (IIR-only) state. +fn read_filter(br: &mut BitReader, f: &mut Filter, iir: bool) -> Result<()> { + f.order = br.read_bits(4)? as usize; + if f.order > MAX_FILTER_ORDER || (!iir && f.order > 8) || (iir && f.order > 4) { + return Err(Error::corrupt("TrueHD: filter order out of range")); + } + if f.order > 0 { + f.shift = br.read_bits(4)?; + let coeff_bits = br.read_bits(5)?; + let coeff_shift = br.read_bits(3)?; + if !(1..=16).contains(&coeff_bits) || coeff_bits + coeff_shift > 16 { + return Err(Error::corrupt("TrueHD: filter coefficient precision out of range")); + } + for c in f.coeffs.iter_mut().take(f.order) { + *c = br.read_signed(coeff_bits)? << coeff_shift; + } + if br.read_bit()? { + if !iir { + return Err(Error::corrupt("TrueHD: FIR filter with explicit state")); + } + let state_bits = br.read_bits(4)?; + let state_shift = br.read_bits(4)?; + for st in f.state.iter_mut().take(f.order) { + *st = if state_bits > 0 { br.read_signed(state_bits)? << state_shift } else { 0 }; + } + } + } + Ok(()) +} + +/// Residual → sample through the channel's FIR (over past samples) and IIR +/// (over past residual-after-prediction) filters, in place on column `ch`. +fn filter_channel(cp: &mut ChannelParams, qss: u32, rows: &mut [[i32; MAX_CHANNELS]], ch: usize) { + let mask = !((1i32 << qss) - 1); + let shift = if cp.fir.order > 0 { cp.fir.shift } else { cp.iir.shift }; + for row in rows { + let mut accum: i64 = 0; + for j in 0..cp.fir.order { + accum += i64::from(cp.fir.state[j]) * i64::from(cp.fir.coeffs[j]); + } + for j in 0..cp.iir.order { + accum += i64::from(cp.iir.state[j]) * i64::from(cp.iir.coeffs[j]); + } + let accum = (accum >> shift) as i32; + let result = accum.wrapping_add(row[ch]) & mask; + cp.fir.state.copy_within(0..MAX_FILTER_ORDER - 1, 1); + cp.fir.state[0] = result; + cp.iir.state.copy_within(0..MAX_FILTER_ORDER - 1, 1); + cp.iir.state[0] = result.wrapping_sub(accum); + row[ch] = result; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Every code in the public tables decodes back to its own index when + /// written bit-exactly, with and without trailing garbage. + #[test] + fn every_codebook_entry_decodes_to_its_index() { + use ec_core::bitio::BitWriter; + let lut = HuffLut::build(); + for (book, table) in HUFFMAN_TABLES.iter().enumerate() { + for (index, &(code, len)) in table.iter().enumerate() { + if len == 0 { + continue; + } + let mut w = BitWriter::new(); + w.write_bits(u32::from(code), u32::from(len)); + w.write_bits(0x5A5, 11); + let bytes = w.into_bytes(); + let mut br = BitReader::new(&bytes); + assert_eq!(lut.decode(&mut br, book).unwrap(), index as i32, "book {book} index {index}"); + assert_eq!(br.bit_position(), u64::from(len)); + // Bare code at the very end of the buffer must decode too. + let mut w = BitWriter::new(); + w.write_bits(u32::from(code), u32::from(len)); + let bytes = w.into_bytes(); + let mut br = BitReader::new(&bytes); + assert_eq!(lut.decode(&mut br, book).unwrap(), index as i32); + } + } + // An all-zero 9-bit word is not a code in any book. + for book in 0..3 { + assert!(lut.decode(&mut BitReader::new(&[0, 0]), book).is_err()); + } + } + + #[test] + fn codebooks_are_prefix_free() { + for table in &HUFFMAN_TABLES { + let used: Vec<_> = table.iter().filter(|e| e.1 > 0).collect(); + for (i, a) in used.iter().enumerate() { + for b in &used[i + 1..] { + let l = a.1.min(b.1); + assert_ne!(a.0 >> (a.1 - l), b.0 >> (b.1 - l), "{a:?} vs {b:?}"); + } + } + } + } +} + diff --git a/crates/ec-truehd/src/lib.rs b/crates/ec-truehd/src/lib.rs new file mode 100644 index 00000000..5df560fc --- /dev/null +++ b/crates/ec-truehd/src/lib.rs @@ -0,0 +1,44 @@ +//! Dolby TrueHD and MLP decoding for the edith_codecs family. +//! +//! Written from Dolby's public TrueHD/MLP documentation of the bitstream's +//! *shape* — major sync, per-substream access-unit directory, FIR/IIR filter +//! parameters, the Huffman/LSB entropy coder and matrixing — not from any +//! third party's source. The syntax layer ([`sync`]) and the lossless +//! substream decode ([`decode`], reached through +//! [`TrueHdDecoder::decode_access_unit`]) are both verified bit-exact +//! against an external decoder on a real 7.1 Blu-ray remux (first 60 s, +//! 23 040 000 of 23 040 000 samples) and on externally encoded MLP/TrueHD +//! mono, stereo and 5.1 streams. +//! +//! Scope, stated once so a caller knows what to expect: +//! +//! - **In scope**: major sync detection and parsing (format id, sample rate, +//! channel presentations), the access-unit header's per-substream +//! directory (end pointers, checksum/parity), and the +//! three PCM-presentation substreams a real Blu-ray track carries: 2-ch, +//! 6-ch (5.1) and 8-ch (7.1), each built from restart headers, FIR/IIR +//! predictor filters, Huffman/LSB residual entropy and the channel +//! matrixing that turns decorrelated substream channels back into PCM, +//! plus the stream's own lossless check. +//! - **Out of scope, refused by name via [`Error::Unsupported`]**: the 4th +//! substream (16-channel object/Atmos audio) — a different, unrelated +//! payload riding the same container, not a bigger version of the 3 PCM +//! presentations above — and any metadata semantics beyond parsing the +//! bytes (dialogue normalisation curves, downmix hints and the like stay +//! unopinionated data on the parsed structs, same as this family treats +//! AC-3's `dialnorm`). +//! +//! No unsafe, no panics on malformed input: truncated data is +//! [`Error::NeedMore`], a bitstream that violates its own rules is +//! [`Error::Corrupt`], and a construct this build does not implement is +//! [`Error::Unsupported`] naming *what* and *why*. + +#![forbid(unsafe_code)] +#![warn(missing_docs)] + +pub mod decode; +pub mod sync; + +pub use ec_core::Error; +pub use decode::CheckStats; +pub use sync::{AccessUnitHeader, MajorSyncInfo, MajorSyncFormat, SubstreamInfo, TrueHdDecoder, frame_length}; diff --git a/crates/ec-truehd/src/sync.rs b/crates/ec-truehd/src/sync.rs new file mode 100644 index 00000000..1bee6a65 --- /dev/null +++ b/crates/ec-truehd/src/sync.rs @@ -0,0 +1,511 @@ +//! TrueHD/MLP access-unit framing: the 16-bit length word, major sync and the +//! per-substream directory. +//! +//! Every field parsed here is calibrated against a real Blu-ray 7.1 TrueHD +//! remux (`~/Downloads/.../ReelR ... TrueHD 7 1 ...mkv`, see +//! `tests/library.rs`): the access-unit length, the major sync's sample-rate +//! codes, and the substream directory's end pointers all reproduce ffprobe's +//! own 48000 Hz / 8-channel / 24-bit report on that file, AU for AU. +//! +//! **Bit layout implemented here** (byte offsets are from the start of the +//! access unit, i.e. from `data[0]`): +//! +//! - `data[0..2]` big-endian: top 4 bits a check/parity nibble (not +//! validated — no public description of its generator was available to +//! check against), low 12 bits the access-unit length in 16-bit words +//! *including this 4-byte header*. [`frame_length`] returns that length in +//! bytes. +//! - `data[2..4]`: input timing, carried on [`AccessUnitHeader::input_timing`] +//! uninterpreted — a decoder does not need it to reconstruct samples. +//! - `data[4..8]`: `0xF8726FBA` (TrueHD) or `0xF8726FBB` (MLP) names a major +//! sync at this access unit; absent on most access units, present roughly +//! once per video frame. +//! - When a major sync is present, it occupies exactly 28 bytes starting at +//! `data[4]` (format id + 24 more bytes, ending where the substream +//! directory begins): `data[8]` packs two 4-bit sample-rate codes, +//! `group1` in the high nibble and `group2` (a secondary/backward-compat +//! rate, `0xF` when unused) in the low nibble. A code maps to a rate via +//! [`sample_rate`]; codes 0-2 are the 48 kHz family (`48000 * 2^n`), codes +//! 8-10 the 44.1 kHz family (`44100 * 2^n`). The rest of the major sync +//! (channel-assignment bitfields, flags) is skipped: this build does not +//! independently verify their bit positions, so [`ChannelLayout`] is +//! derived from the substream *directory* instead (see below), which is +//! fully verified against the sample file. +//! - The substream directory starts right after the major sync (or right +//! after the 4-byte access-unit header, on an access unit with none), one +//! [`SubstreamInfo`] entry per substream: a 2-byte word whose top 4 bits +//! are flags (bit `0x8` says a second 2-byte word — a checksum/parity/DRC +//! word, [`SubstreamInfo::extra`] — follows) and whose low 12 bits are the +//! substream's *end pointer*: the cumulative byte offset, in 16-bit words +//! from the end of the whole directory, where this substream's coded data +//! ends. There is no explicit substream-count field; a directory entry is +//! the *last* one exactly when `directory_end + end_pointer_bytes` lands +//! on the access unit's own total length — which is how +//! [`AccessUnitHeader::parse`] finds the count, bounded at 4 entries +//! (Dolby's own substream cap). +//! +//! Substream count maps to [`ChannelLayout`] by Dolby's own published +//! substream convention — substream 0 always carries a 2-ch presentation, +//! substream 1 (when present) adds a discrete 6-ch (5.1) presentation, +//! substream 2 (when present) adds a discrete 8-ch (7.1) presentation, and a +//! 4th substream carries an unrelated object-audio payload — rather than +//! from the major sync's own channel-assignment bitfields, for the reason +//! above. + +use ec_core::error::{Error, Result}; +use ec_core::frame::{AudioFrame, ChannelLayout, Frame}; +use ec_core::packet::Packet; +use ec_core::registry::{CodecId, CodecParameters, Decoder}; + +/// TrueHD's major sync word, immediately followed by the extension fields +/// TrueHD adds over plain MLP. +pub const MAJOR_SYNC_TRUEHD: u32 = 0xF872_6FBA; +/// MLP's major sync word (lossless-only, no TrueHD extensions). +pub const MAJOR_SYNC_MLP: u32 = 0xF872_6FBB; + +/// Bytes a major sync occupies, format id included, ending where the +/// substream directory begins. +const MAJOR_SYNC_LEN: usize = 28; + +/// Bytes the fixed part of an access unit's own header takes: the 16-bit +/// length/check word and the 16-bit input timing. +const AU_HEADER_LEN: usize = 4; + +/// Access-unit length in bytes, from the 16-bit length word at `data[0..2]`. +/// +/// A short buffer is [`Error::NeedMore`]; a length that could not even cover +/// its own 4-byte header is [`Error::Corrupt`]. +pub fn frame_length(data: &[u8]) -> Result { + if data.len() < 2 { + return Err(Error::NeedMore); + } + let word = u16::from_be_bytes([data[0], data[1]]); + let len = usize::from(word & 0x0FFF) * 2; + if len < AU_HEADER_LEN { + return Err(Error::corrupt(format!( + "TrueHD: {len}-byte access unit shorter than its own header" + ))); + } + Ok(len) +} + +/// Which format a major sync names. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum MajorSyncFormat { + /// `0xF8726FBA`. + TrueHd, + /// `0xF8726FBB`. + Mlp, +} + +/// The format info an access unit's major sync carries. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct MajorSyncInfo { + /// Which sync word introduced it. + pub format: MajorSyncFormat, + /// The primary sample rate, decoded from `data[8]`'s high nibble. + pub sample_rate: u32, + /// The raw 4-bit rate code (`& 7` is the `2^n` multiplier, which also + /// sizes the access unit: `40 << n` samples). + pub rate_code: u8, + /// The 8-channel presentation's 13-bit channel-assignment mask (bit 0 = + /// L/R, 1 = C, 2 = LFE, 3 = Ls/Rs, 6 = Lrs/Rrs; `0x4F` is standard 7.1); + /// 0 when the major sync is plain MLP, which has no such field. + pub ch8_assignment: u16, +} + +/// A rate code's `44.1k*2^n` / `48k*2^n` value, or [`Error::Unsupported`] for +/// a code the format reserves. +fn sample_rate(code: u8) -> Result { + match code { + 0..=2 => Ok(48_000 << code), + 8..=10 => Ok(44_100 << (code - 8)), + 0xF => Ok(0), // "not present" (group2's usual value) + other => Err(Error::unsupported( + format!("TrueHD sample rate code {other}"), + "reserved by the format", + )), + } +} + +impl MajorSyncInfo { + /// Parses the major sync starting at `data[0]` (the sync word itself), + /// i.e. `data` is `access_unit[4..]`. + fn parse(data: &[u8]) -> Result { + if data.len() < MAJOR_SYNC_LEN { + return Err(Error::NeedMore); + } + let word = u32::from_be_bytes([data[0], data[1], data[2], data[3]]); + let format = match word { + MAJOR_SYNC_TRUEHD => MajorSyncFormat::TrueHd, + MAJOR_SYNC_MLP => MajorSyncFormat::Mlp, + _ => return Err(Error::corrupt("TrueHD: no major sync word")), + }; + // TrueHD: format_info starts with the rate code; MLP puts its two + // 4-bit word-length codes first and the rate codes one byte later. + let rate_code = match format { + MajorSyncFormat::TrueHd => data[4] >> 4, + MajorSyncFormat::Mlp => data[5] >> 4, + }; + let sample_rate = sample_rate(rate_code)?; + // format_info's last 13 bits: data[6] low 5 bits + data[7]. + let ch8_assignment = match format { + MajorSyncFormat::TrueHd => (u16::from(data[6] & 0x1F) << 8) | u16::from(data[7]), + MajorSyncFormat::Mlp => 0, + }; + Ok(MajorSyncInfo { + format, + sample_rate, + rate_code, + ch8_assignment, + }) + } +} + +/// One substream directory entry: where its coded data ends and whether a +/// checksum/parity/DRC word rides along with the end pointer. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct SubstreamInfo { + /// Raw 4-bit flag nibble; bit `0x8` is the only one this build interprets + /// (it gates [`SubstreamInfo::extra`]). + pub flags: u8, + /// Cumulative end offset of this substream's coded data, in 16-bit words + /// from the end of the substream directory. + pub end_offset_words: u16, + /// The second directory word, when `flags & 0x8` said one follows — + /// observed constant (DRC default) across a real substream's directory + /// entries; not decoded further. + pub extra: Option, +} + +/// One access unit's header: its own length, optional major sync, and the +/// substream directory that follows. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AccessUnitHeader { + /// Total access-unit length in bytes, header included. + pub length: usize, + /// Input timing, carried uninterpreted. + pub input_timing: u16, + /// Present on roughly one access unit per video frame. + pub major_sync: Option, + /// Byte offset where the substream directory ends and substream 0's + /// coded data begins. + pub data_start: usize, + /// One entry per substream, in stream order (`substreams.len()` is the + /// substream count). + pub substreams: Vec, +} + +impl AccessUnitHeader { + /// Parses one access unit's header from `data`, which must hold at least + /// [`frame_length`]'s worth of bytes. + pub fn parse(data: &[u8]) -> Result { + let length = frame_length(data)?; + if data.len() < length { + return Err(Error::NeedMore); + } + let au = &data[..length]; + let input_timing = u16::from_be_bytes([au[2], au[3]]); + + let major_sync = match au.get(4..8) { + Some(w) if w == MAJOR_SYNC_TRUEHD.to_be_bytes() || w == MAJOR_SYNC_MLP.to_be_bytes() => { + Some(MajorSyncInfo::parse(&au[4..])?) + } + _ => None, + }; + let dir_start = AU_HEADER_LEN + if major_sync.is_some() { MAJOR_SYNC_LEN } else { 0 }; + + let mut substreams = Vec::new(); + let mut pos = dir_start; + loop { + let word = au + .get(pos..pos + 2) + .ok_or(Error::NeedMore)?; + let word = u16::from_be_bytes([word[0], word[1]]); + let flags = (word >> 12) as u8; + let end_offset_words = word & 0x0FFF; + pos += 2; + let extra = if flags & 0x8 != 0 { + let w = au.get(pos..pos + 2).ok_or(Error::NeedMore)?; + pos += 2; + Some(u16::from_be_bytes([w[0], w[1]])) + } else { + None + }; + substreams.push(SubstreamInfo { + flags, + end_offset_words, + extra, + }); + if substreams.len() >= 4 { + return Err(Error::unsupported( + "TrueHD 4th (object/16-channel) substream", + "only the 2/6/8-channel PCM presentations are implemented", + )); + } + if pos + usize::from(end_offset_words) * 2 == length { + break; + } + if pos >= length { + return Err(Error::corrupt( + "TrueHD: substream directory did not sum to the access unit's length", + )); + } + } + + Ok(AccessUnitHeader { + length, + input_timing, + major_sync, + data_start: pos, + substreams, + }) + } + + /// Byte span `(start, end)` of substream `i`'s coded data within the + /// access unit, from the directory's cumulative end pointers. + pub fn substream_span(&self, i: usize) -> (usize, usize) { + let start = if i == 0 { + self.data_start + } else { + self.data_start + usize::from(self.substreams[i - 1].end_offset_words) * 2 + }; + (start, self.data_start + usize::from(self.substreams[i].end_offset_words) * 2) + } + + /// The channel layout Dolby's substream convention implies: substream 0 + /// is always a 2-ch presentation, substream 1 (when present) a discrete + /// 5.1, substream 2 (when present) a discrete 7.1. [`parse`](Self::parse) + /// already refuses a 4th substream, so this never sees one. + pub fn channel_layout(&self) -> Result { + match self.substreams.len() { + 1 => Ok(ChannelLayout::Stereo), + 2 => Ok(ChannelLayout::Surround5_1), + 3 => Ok(ChannelLayout::Surround7_1), + n => Err(Error::corrupt(format!("TrueHD: {n} substreams"))), + } + } +} + +/// A TrueHD/MLP decoder for one stream: access units in, one interleaved +/// S32 (24-bit left-justified) [`AudioFrame`] of the highest presentation +/// out per access unit. See the crate-level docs for scope. +#[derive(Debug)] +pub struct TrueHdDecoder { + params: CodecParameters, + core: crate::decode::Core, + pending: Option, +} + +impl Default for TrueHdDecoder { + fn default() -> Self { + Self::new() + } +} + +impl TrueHdDecoder { + /// A decoder with no stream state yet; TrueHD carries its own format + /// info in-band (the major sync), so there is no magic-cookie equivalent + /// to hand in up front. + pub fn new() -> TrueHdDecoder { + TrueHdDecoder { + params: CodecParameters::new(CodecId::TrueHd), + core: crate::decode::Core::new(), + pending: None, + } + } + + /// The stream-side self-check tallies so far (restart CRC, parity, + /// lossless check); all stay zero on a clean decode. + pub fn check_stats(&self) -> crate::decode::CheckStats { + self.core.stats + } + + /// One access unit in; one frame of the highest presentation out — + /// `None` until the first major sync and every substream's first + /// restart header have been seen. + pub fn push(&mut self, data: &[u8]) -> Result> { + self.decode_access_unit(data) + } + + /// See [`TrueHdDecoder::push`]. + pub fn decode_access_unit(&mut self, data: &[u8]) -> Result> { + let header = AccessUnitHeader::parse(data)?; + self.core.decode(&header, data) + } +} + +impl Decoder for TrueHdDecoder { + fn codec_parameters(&self) -> &CodecParameters { + &self.params + } + + fn send_packet(&mut self, packet: &Packet) -> Result<()> { + if let Some(mut frame) = self.decode_access_unit(&packet.data)? { + frame.pts = packet + .pts + .map(|ticks| ec_core::timebase::Timestamp::new(ticks, packet.time_base)); + self.pending = Some(frame); + } + Ok(()) + } + + fn receive_frame(&mut self) -> Result { + self.pending.take().map(Frame::Audio).ok_or(Error::NeedMore) + } + + fn flush(&mut self) -> Result<()> { + Ok(()) + } + + fn reset(&mut self) { + self.pending = None; + self.core.reset(); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A hand-built access unit with no major sync, one substream (a bare + /// 2-channel presentation): 4-byte header + a 2-byte directory entry + + /// 4 bytes of "coded data" nobody reads yet. + fn stereo_au() -> Vec { + vec![ + 0x30, 0x05, // check nibble 3, length 5 words (10 bytes) + 0x12, 0x34, // input timing (uninterpreted) + 0x00, 0x02, // substream 0: flags 0 (no extra word), end +2 words + 0xAA, 0xBB, 0xCC, 0xDD, // "coded data" + ] + } + + /// A hand-built access unit that does carry a major sync (TrueHD, + /// 48 kHz) and two substreams (a 5.1 presentation on top of the 2-ch + /// one). + fn surround51_au() -> Vec { + let mut au = vec![ + 0x50, 0x16, // check nibble 5, length 22 words (44 bytes) + 0x00, 0x00, // input timing + ]; + au.extend_from_slice(&MAJOR_SYNC_TRUEHD.to_be_bytes()); + au.push(0x0F); // sample rate: group1 code 0 (48000), group2 0xF (absent) + au.extend(std::iter::repeat_n(0u8, 23)); // rest of the major sync, unused here + au.extend_from_slice(&[0x00, 0x01]); // substream 0: end +1 word (not the last) + au.extend_from_slice(&[0x00, 0x04]); // substream 1: end +4 words (lands on EOF) + au.extend_from_slice(&[0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88]); + au + } + + #[test] + fn frame_length_reads_the_16_bit_word() { + assert_eq!(frame_length(&stereo_au()).unwrap(), 10); + assert_eq!(frame_length(&surround51_au()).unwrap(), 44); + } + + #[test] + fn frame_length_needs_two_bytes() { + assert!(matches!(frame_length(&[0x30]), Err(Error::NeedMore))); + assert!(matches!(frame_length(&[]), Err(Error::NeedMore))); + } + + #[test] + fn parses_a_stereo_access_unit_with_no_major_sync() { + let au = AccessUnitHeader::parse(&stereo_au()).unwrap(); + assert_eq!(au.length, 10); + assert_eq!(au.input_timing, 0x1234); + assert!(au.major_sync.is_none()); + assert_eq!(au.substreams.len(), 1); + assert_eq!(au.channel_layout().unwrap(), ChannelLayout::Stereo); + } + + #[test] + fn parses_a_5_1_access_unit_with_a_major_sync() { + let au = AccessUnitHeader::parse(&surround51_au()).unwrap(); + assert_eq!(au.length, 44); + let sync = au.major_sync.expect("major sync detected"); + assert_eq!(sync.format, MajorSyncFormat::TrueHd); + assert_eq!(sync.sample_rate, 48_000); + assert_eq!(au.substreams.len(), 2); + assert_eq!(au.channel_layout().unwrap(), ChannelLayout::Surround5_1); + } + + #[test] + fn a_corrupted_major_sync_word_does_not_panic() { + let mut au = surround51_au(); + // Flip a byte inside the format-sync word so it names neither + // TrueHD nor MLP; the directory walk that follows now reads + // major-sync bytes as if they were directory entries and cannot + // land on the access unit's real end, but must not panic. + au[5] = 0x00; + assert!(AccessUnitHeader::parse(&au).is_err()); + } + + #[test] + fn a_truncated_access_unit_is_need_more() { + let au = surround51_au(); + // The header claims 44 bytes; hand over fewer. + assert!(matches!( + AccessUnitHeader::parse(&au[..20]), + Err(Error::NeedMore) + )); + } + + #[test] + fn a_fourth_substream_is_named_unsupported() { + // A 20-byte access unit, followed by five directory entries whose + // end pointers never land on that length -- forces the walk past + // the 4-substream cap before it can terminate. + let mut au = vec![0x00, 0x0A, 0x00, 0x00]; // length 10 words = 20 bytes + for _ in 0..5 { + au.extend_from_slice(&[0x00, 0x01]); + } + au.resize(20, 0); + let err = AccessUnitHeader::parse(&au).unwrap_err(); + assert!(matches!(err, Error::Unsupported { .. }), "{err:?}"); + } + + #[test] + fn a_well_formed_4_entry_directory_is_still_named_unsupported() { + // A 20-byte access unit whose directory has exactly 4 entries, the + // last of which lands squarely on the access unit's end (the + // well-formed object-audio shape, not a walk that overruns a + // malformed directory). This must be refused by name, not parsed as + // Ok(4) and only caught later in channel_layout(). + let mut au = vec![0x00, 0x0A, 0x00, 0x00]; // length 10 words = 20 bytes + au.extend_from_slice(&[0x00, 0x01]); // substream 0: doesn't land on EOF yet + au.extend_from_slice(&[0x00, 0x01]); // substream 1: doesn't land on EOF yet + au.extend_from_slice(&[0x00, 0x01]); // substream 2: doesn't land on EOF yet + au.extend_from_slice(&[0x00, 0x04]); // substream 3: pos(12) + 4*2 == 20, lands on EOF + au.resize(20, 0); + let err = AccessUnitHeader::parse(&au).unwrap_err(); + assert!(matches!(err, Error::Unsupported { .. }), "{err:?}"); + } + + #[test] + fn a_well_formed_3_entry_directory_still_parses() { + // Control for the test above: the same shape one entry shorter, its + // last pointer landing on the access unit's end, must still parse. + let mut au = vec![0x00, 0x0A, 0x00, 0x00]; // length 10 words = 20 bytes + au.extend_from_slice(&[0x00, 0x01]); // substream 0: doesn't land on EOF yet + au.extend_from_slice(&[0x00, 0x01]); // substream 1: doesn't land on EOF yet + au.extend_from_slice(&[0x00, 0x05]); // substream 2: pos(10) + 5*2 == 20, lands on EOF + au.resize(20, 0); + let parsed = AccessUnitHeader::parse(&au).unwrap(); + assert_eq!(parsed.substreams.len(), 3); + assert_eq!(parsed.channel_layout().unwrap(), ChannelLayout::Surround7_1); + } + + #[test] + fn decoder_yields_nothing_before_a_major_sync() { + let mut decoder = TrueHdDecoder::new(); + assert_eq!(decoder.decode_access_unit(&stereo_au()).unwrap(), None); + } + + #[test] + fn substream_spans_follow_the_directory() { + let au = AccessUnitHeader::parse(&surround51_au()).unwrap(); + assert_eq!(au.substream_span(0), (36, 38)); + assert_eq!(au.substream_span(1), (38, 44)); + } +} diff --git a/crates/ec-truehd/tests/library.rs b/crates/ec-truehd/tests/library.rs new file mode 100644 index 00000000..c537cdd9 --- /dev/null +++ b/crates/ec-truehd/tests/library.rs @@ -0,0 +1,140 @@ +//! Walks a real Blu-ray remux's TrueHD track and parses every access unit -- +//! a live discovery over `~/Downloads`, absent files skip loudly, nothing is +//! generated or bundled. + +use std::fs::File; +use std::io::BufReader; +use std::path::PathBuf; +use std::process::Command; + +use ec_core::{CodecId, Demuxer}; +use ec_matroska::MatroskaDemuxer; +use ec_truehd::sync::AccessUnitHeader; + +/// The user's own library, not a fixture: a glob over `~/Downloads` for a +/// known 7.1 TrueHD Blu-ray remux. +fn find_file() -> Option { + let home = std::env::var("HOME").ok()?; + let downloads = PathBuf::from(home).join("Downloads"); + for entry in glob_dir(&downloads) { + let name = entry.file_name()?.to_str()?; + if name.contains("ReelR") && name.ends_with(".mkv") { + return Some(entry); + } + } + None +} + +/// A one-level-deep, non-recursive-but-good-enough directory walk (the file +/// this test wants sits in a subdirectory of `~/Downloads`) -- no `glob` +/// crate in this family, so a plain `read_dir` walk stands in for one. +fn glob_dir(dir: &std::path::Path) -> Vec { + let mut out = Vec::new(); + let Ok(entries) = std::fs::read_dir(dir) else { + return out; + }; + for entry in entries.flatten() { + let path = entry.path(); + if path.is_dir() { + out.extend(glob_dir(&path)); + } else { + out.push(path); + } + } + out +} + +fn have_ffprobe() -> bool { + Command::new("ffprobe") + .arg("-version") + .output() + .map(|o| o.status.success()) + .unwrap_or(false) +} + +/// ffprobe's own packet count for the file's TrueHD stream, by absolute +/// stream index. +fn ffprobe_packet_count(path: &std::path::Path, stream: usize) -> Option { + let out = Command::new("ffprobe") + .args(["-v", "error", "-select_streams"]) + .arg(stream.to_string()) + .args([ + "-count_packets", + "-show_entries", + "stream=nb_read_packets", + "-of", + "csv=p=0", + ]) + .arg(path) + .output() + .ok()?; + if !out.status.success() { + return None; + } + String::from_utf8_lossy(&out.stdout).trim().parse().ok() +} + +#[test] +fn walks_every_truehd_access_unit_of_a_real_7_1_remux() { + let Some(path) = find_file() else { + eprintln!("skip: no 'ReelR ... TrueHD ...mkv' under ~/Downloads"); + return; + }; + + let file = File::open(&path).expect("open the file"); + let mut demux = MatroskaDemuxer::new(BufReader::new(file)).expect("open the container"); + + let track = demux + .streams() + .iter() + .find(|s| s.params.codec == CodecId::TrueHd) + .expect("a TrueHD track"); + let stream_index = track.index; + let audio = track.params.audio().expect("audio parameters"); + assert_eq!(audio.sample_rate, 48_000, "rate"); + assert_eq!(audio.layout.channel_count(), 8, "channels"); + // Matroska's `BitDepth` element is optional and this remux's TrueHD + // track does not carry one; report what the container states rather + // than asserting a value it never claimed. + eprintln!("container-reported bit depth: {:?}", audio.bits_per_sample); + + let mut au_count = 0u64; + let mut major_syncs = 0u64; + loop { + let packet = match demux.next_packet() { + Ok(p) => p, + Err(e) if e.is_eof() => break, + Err(e) => panic!("demux error: {e}"), + }; + if packet.stream != stream_index { + continue; + } + let header = AccessUnitHeader::parse(&packet.data) + .unwrap_or_else(|e| panic!("access unit {au_count}: {e}")); + assert_eq!( + header.length, + packet.data.len(), + "access unit {au_count} claims a length that does not match its packet" + ); + if header.major_sync.is_some() { + major_syncs += 1; + } + au_count += 1; + } + + eprintln!("{au_count} access units, {major_syncs} carrying a major sync"); + assert!(au_count > 0, "found no TrueHD access units at all"); + + if have_ffprobe() { + // Absolute demuxer stream index in the file, for ffprobe's own + // `-select_streams`: the track this family's stream list found. + let absolute = stream_index as usize; + if let Some(expected) = ffprobe_packet_count(&path, absolute) { + assert_eq!(au_count, expected, "AU count vs ffprobe's packet count"); + } else { + eprintln!("skip: ffprobe packet count unavailable for stream {absolute}"); + } + } else { + eprintln!("skip: ffprobe not on PATH, no oracle comparison"); + } +} diff --git a/crates/ec-truehd/tests/oracle.rs b/crates/ec-truehd/tests/oracle.rs new file mode 100644 index 00000000..ed91882c --- /dev/null +++ b/crates/ec-truehd/tests/oracle.rs @@ -0,0 +1,178 @@ +//! Bit-exactness against an external decoder: the first 60 s of a real 7.1 +//! Blu-ray TrueHD remux (3 substreams, noise type 1 matrices), and +//! externally encoded MLP/TrueHD streams (mono, stereo, 5.1 pink noise — +//! every codebook, matrices with the 2-channel noise generator, two +//! substreams). Both need `ffmpeg` on PATH and skip loudly without it; the +//! remux is a live discovery over `~/Downloads`. + +use std::fs::File; +use std::io::BufReader; +use std::path::{Path, PathBuf}; +use std::process::Command; + +use ec_core::{CodecId, Demuxer}; +use ec_matroska::MatroskaDemuxer; +use ec_truehd::{frame_length, TrueHdDecoder}; + +fn find_file() -> Option { + fn walk(dir: &Path, out: &mut Vec) { + let Ok(entries) = std::fs::read_dir(dir) else { return }; + for e in entries.flatten() { + let p = e.path(); + if p.is_dir() { + walk(&p, out); + } else { + out.push(p); + } + } + } + let home = std::env::var("HOME").ok()?; + let mut all = Vec::new(); + walk(&PathBuf::from(home).join("Downloads"), &mut all); + all.into_iter().find(|p| { + p.file_name() + .and_then(|n| n.to_str()) + .is_some_and(|n| n.contains("ReelR") && n.ends_with(".mkv")) + }) +} + +fn have_ffmpeg() -> bool { + Command::new("ffmpeg").arg("-version").output().map(|o| o.status.success()).unwrap_or(false) +} + +fn ffmpeg(args: &[&str]) -> Vec { + let out = Command::new("ffmpeg").args(["-v", "error", "-nostdin"]).args(args).output().expect("run ffmpeg"); + assert!(out.status.success(), "ffmpeg {args:?}: {}", String::from_utf8_lossy(&out.stderr)); + out.stdout +} + +fn s32le(bytes: &[u8]) -> Vec { + bytes.chunks_exact(4).map(|c| i32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect() +} + +/// Compares `ours` with `reference` sample-for-sample; returns (exact, +/// total, first mismatch index). +fn compare(ours: &[i32], reference: &[i32]) -> (usize, usize, Option) { + let n = ours.len().min(reference.len()); + let mut exact = 0; + let mut first = None; + for i in 0..n { + if ours[i] == reference[i] { + exact += 1; + } else if first.is_none() { + first = Some(i); + } + } + (exact, n, first) +} + +#[test] +fn first_60_seconds_of_a_real_7_1_remux_are_bit_exact() { + let Some(path) = find_file() else { + eprintln!("skip: no 'ReelR ... TrueHD ...mkv' under ~/Downloads"); + return; + }; + if !have_ffmpeg() { + eprintln!("skip: ffmpeg not on PATH"); + return; + } + const SECONDS: usize = 60; + let mut demux = MatroskaDemuxer::new(BufReader::new(File::open(&path).unwrap())).unwrap(); + let track = demux.streams().iter().find(|s| s.params.codec == CodecId::TrueHd).expect("a TrueHD track"); + let stream_index = track.index; + + let reference = s32le(&ffmpeg(&[ + "-i", path.to_str().unwrap(), "-map", &format!("0:{stream_index}"), "-t", &SECONDS.to_string(), + "-f", "s32le", "-", + ])); + let channels = 8; + let wanted = SECONDS * 48_000 * channels; + + let mut decoder = TrueHdDecoder::new(); + let mut ours: Vec = Vec::with_capacity(wanted); + let mut aus = 0; + while ours.len() < wanted { + let packet = match demux.next_packet() { + Ok(p) => p, + Err(e) if e.is_eof() => break, + Err(e) => panic!("demux: {e}"), + }; + if packet.stream != stream_index { + continue; + } + let frame = decoder.decode_access_unit(&packet.data).unwrap_or_else(|e| panic!("AU {aus}: {e}")); + aus += 1; + if let Some(f) = frame { + assert_eq!(f.channels(), channels); + ours.extend(s32le(&f.data[0])); + } + } + let (exact, total, first) = compare(&ours, &reference); + let stats = decoder.check_stats(); + for ch in 0..channels { + let n = total / channels; + let e = (0..n).filter(|&i| ours[i * channels + ch] == reference[i * channels + ch]).count(); + eprintln!("channel {ch}: {e}/{n} exact"); + } + eprintln!( + "{aus} access units, {total} samples compared ({} s), {exact} exact ({:.4}%), first mismatch {first:?}, {stats:?}", + total / channels / 48_000, + 100.0 * exact as f64 / total as f64 + ); + assert!(total >= (SECONDS - 1) * 48_000 * channels, "only {total} samples"); + assert_eq!(stats.lossless_check_failures, 0, "{stats:?}"); + assert_eq!(stats.parity_failures, 0, "{stats:?}"); + assert_eq!(stats.restart_crc_failures, 0, "{stats:?}"); + assert_eq!(stats.length_mismatches, 0, "{stats:?}"); + assert!(exact as f64 >= 0.9999 * total as f64, "{exact}/{total} exact, first mismatch {first:?}"); +} + +/// An externally encoded MLP stream (raw access units) decoded by us must +/// match the external decoder's own output exactly; noise drives every +/// codebook and a wide range of LSB widths. +#[test] +fn externally_encoded_mlp_round_trips_bit_exact() { + if !have_ffmpeg() { + eprintln!("skip: ffmpeg not on PATH"); + return; + } + let dir = std::env::temp_dir().join(format!("ec-truehd-oracle-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let mut failures = Vec::new(); + for (codec, layout, channels) in [ + ("mlp", "mono", 1usize), ("mlp", "stereo", 2), ("mlp", "5.1", 6), + ("truehd", "mono", 1), ("truehd", "stereo", 2), ("truehd", "5.1", 6), + ] { + let name = format!("{codec}-{layout}"); + let mlp = dir.join(format!("{name}.{}", if codec == "mlp" { "mlp" } else { "thd" })); + let src = format!( + "anoisesrc=color=pink:amplitude=0.3:seed=7:sample_rate=48000:duration=3,aformat=sample_fmts=s32:channel_layouts={layout}" + ); + ffmpeg(&["-y", "-f", "lavfi", "-i", &src, "-c:a", codec, "-strict", "-2", mlp.to_str().unwrap()]); + let reference = s32le(&ffmpeg(&["-i", mlp.to_str().unwrap(), "-f", "s32le", "-"])); + let data = std::fs::read(&mlp).unwrap(); + + let mut decoder = TrueHdDecoder::new(); + let mut ours = Vec::new(); + let mut pos = 0; + while pos < data.len() { + let len = frame_length(&data[pos..]).unwrap(); + if let Some(f) = decoder.decode_access_unit(&data[pos..pos + len]).unwrap() { + assert_eq!(f.channels(), channels); + ours.extend(s32le(&f.data[0])); + } + pos += len; + } + let (exact, total, first) = compare(&ours, &reference); + let stats = decoder.check_stats(); + eprintln!("{name}: {exact}/{total} exact (ours {}, reference {}), first mismatch {first:?}, {stats:?}", ours.len(), reference.len()); + if stats.lossless_check_failures + stats.parity_failures + stats.restart_crc_failures != 0 + || exact != total + || total < 2 * 48_000 * channels + { + failures.push(format!("{name}: {exact}/{total}, first mismatch {first:?}, {stats:?}")); + } + } + let _ = std::fs::remove_dir_all(&dir); + assert!(failures.is_empty(), "{failures:#?}"); +}