From 2c05ed8c47688d464707f92470e190bfb2ab87f3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 2 Dec 2026 10:07:18 +0300 Subject: [PATCH] TrueHD: directory from major sync count, 32-byte Atmos major sync (ffmpeg 9.0.2 mlp_parse.c/mlpdec.c) Root cause, sync.rs AccessUnitHeader::parse: (1) the major sync was fixed at 28 bytes, but ffmpeg mlp_get_major_sync_size adds 2+2*(buf[26]>>4) bytes when buf[25]&1 (TrueHD); atmos.thd AU0 has extension bit set, so the directory started at 32 instead of 36. (2) the entry count was inferred from end pointers landing on the AU length; ffmpeg reads num_substreams (major sync buf[16]>>4, mlp_parse.c:160) and ignores trailing bytes, and atmos.thd AU25/63/102 carry 32 words past the last end pointer, so the walk ran past 4 entries. Fix: length from the extension block; count from num_substreams, carried over from the last major sync on units without one (TrueHdDecoder::substream_count); entries past the data are corrupt. Atmos fixture: AU0 4 entries, ends 546w lands on 1136 bytes; num_substreams=4 with substream_info 0x80 (16-ch). --- crates/ec-mpegts/src/track.rs | 2 +- crates/ec-mpegts/tests/it/truehd.rs | 4 +- .../ec-truehd/fuzz/fuzz_targets/parse_sync.rs | 4 +- crates/ec-truehd/src/sync.rs | 122 ++++++++++-------- crates/ec-truehd/tests/it/atmos_synth.rs | 4 +- crates/ec-truehd/tests/it/common.rs | 4 +- 6 files changed, 80 insertions(+), 60 deletions(-) diff --git a/crates/ec-mpegts/src/track.rs b/crates/ec-mpegts/src/track.rs index 0dcc875d..2e74a7c8 100644 --- a/crates/ec-mpegts/src/track.rs +++ b/crates/ec-mpegts/src/track.rs @@ -779,7 +779,7 @@ impl Track { // The access unit goes on in the next PES. break; } - let Ok(head) = AccessUnitHeader::parse(&rest[..len]) else { + let Ok(head) = AccessUnitHeader::parse(&rest[..len], 0) else { cur += 1; continue; }; diff --git a/crates/ec-mpegts/tests/it/truehd.rs b/crates/ec-mpegts/tests/it/truehd.rs index 7dce65b1..f0d26281 100644 --- a/crates/ec-mpegts/tests/it/truehd.rs +++ b/crates/ec-mpegts/tests/it/truehd.rs @@ -76,10 +76,12 @@ fn truehd_in_ts_decodes_sample_exact_to_ffmpeg() { assert!(!pkts.is_empty(), "{name}: no TrueHD access units"); // Every packet is one whole access unit: its length word covers it exactly. + let mut substreams = 0; for p in &pkts { - let head = AccessUnitHeader::parse(&p.data) + let head = AccessUnitHeader::parse(&p.data, substreams) .unwrap_or_else(|e| panic!("{name}: AU at {:#x}: {e}", p.off)); assert_eq!(head.length, p.data.len(), "{name}: AU length"); + substreams = head.substreams.len(); } let mut dec = TrueHdDecoder::new(); diff --git a/crates/ec-truehd/fuzz/fuzz_targets/parse_sync.rs b/crates/ec-truehd/fuzz/fuzz_targets/parse_sync.rs index aafc03b8..7facb0d0 100644 --- a/crates/ec-truehd/fuzz/fuzz_targets/parse_sync.rs +++ b/crates/ec-truehd/fuzz/fuzz_targets/parse_sync.rs @@ -13,7 +13,7 @@ const MAX_BODY: usize = 8190 - 8; fuzz_target!(|data: &[u8]| { // Raw bytes: the length word and, if it happens to match, the major sync. let _ = frame_length(data); - let _ = AccessUnitHeader::parse(data); + let _ = AccessUnitHeader::parse(data, 0); // Fixup: wrap the input in a valid AU header and TrueHD major sync word, so the // mutations land on the sync fields and the directory behind them instead of on @@ -30,5 +30,5 @@ fuzz_target!(|data: &[u8]| { return; }; au[..2].copy_from_slice(&(words & 0x0FFF).to_be_bytes()); - let _ = AccessUnitHeader::parse(&au); + let _ = AccessUnitHeader::parse(&au, 0); }); diff --git a/crates/ec-truehd/src/sync.rs b/crates/ec-truehd/src/sync.rs index 2cb69876..5ea77428 100644 --- a/crates/ec-truehd/src/sync.rs +++ b/crates/ec-truehd/src/sync.rs @@ -20,17 +20,17 @@ //! - `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. +//! - When a major sync is present, it occupies 28 bytes starting at `data[4]` +//! (format id + 24 more bytes), plus a TrueHD extension block when +//! `data[25] & 1` is set: `2 + 2 * (data[26] >> 4)` bytes, then a 2-byte +//! checksum (ffmpeg's `mlp_get_major_sync_size`). `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 +//! 4-bit `num_substreams` is the top nibble of `data[16]`. The rest of the +//! major sync (channel-assignment bitfields, flags) is skipped: [`ChannelLayout`] +//! is derived from the substream count instead. //! - 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 @@ -38,11 +38,10 @@ //! 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). +//! ends. The count is not inferred from the end pointers (an access unit may +//! carry trailing bytes past the last one): it is the major sync's +//! `num_substreams`, carried over from the last major sync on access units +//! without one, 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, @@ -66,8 +65,7 @@ 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. +/// Bytes a plain major sync occupies, format id included. const MAJOR_SYNC_LEN: usize = 28; /// Dolby's cap on substream directory entries per access unit: entries 0..=2 @@ -123,6 +121,11 @@ pub struct MajorSyncInfo { /// 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, + /// Substreams in the access unit's directory (the major sync's + /// `num_substreams`, top nibble of `data[16]`). + pub num_substreams: usize, + /// Bytes the major sync occupies, its extension block and checksum included. + pub len: usize, } /// A rate code's `44.1k*2^n` / `48k*2^n` value, or [`Error::Unsupported`] for @@ -164,11 +167,19 @@ impl MajorSyncInfo { MajorSyncFormat::TrueHd => (u16::from(data[6] & 0x1F) << 8) | u16::from(data[7]), MajorSyncFormat::Mlp => 0, }; + let len = match format { + MajorSyncFormat::TrueHd if data[25] & 1 != 0 => { + MAJOR_SYNC_LEN + 2 + 2 * usize::from(data[26] >> 4) + } + _ => MAJOR_SYNC_LEN, + }; Ok(MajorSyncInfo { format, sample_rate, rate_code, ch8_assignment, + num_substreams: usize::from(data[16] >> 4), + len, }) } } @@ -209,8 +220,10 @@ pub struct AccessUnitHeader { 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 { + /// [`frame_length`]'s worth of bytes. `stream_substreams` is the substream + /// count the stream's last major sync declared (0 before any); a unit with + /// its own major sync uses that sync's count instead. + pub fn parse(data: &[u8], stream_substreams: usize) -> Result { let length = frame_length(data)?; if data.len() < length { return Err(Error::NeedMore); @@ -226,21 +239,18 @@ impl AccessUnitHeader { } _ => 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 { - if substreams.len() == MAX_DIRECTORY_ENTRIES { - return Err(Error::corrupt( - "TrueHD: substream directory has more than 4 entries", - )); - } + if major_sync.is_some_and(|s| s.num_substreams == 0) { + return Err(Error::corrupt("TrueHD: major sync declares no substreams")); + } + let count = major_sync.map_or(stream_substreams, |s| s.num_substreams); + if count > MAX_DIRECTORY_ENTRIES { + return Err(Error::corrupt( + "TrueHD: substream directory has more than 4 entries", + )); + } + let mut substreams = Vec::with_capacity(count); + let mut pos = AU_HEADER_LEN + major_sync.map_or(0, |s| s.len); + for _ in 0..count { 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; @@ -258,14 +268,14 @@ impl AccessUnitHeader { end_offset_words, extra, }); - 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", - )); - } + } + if substreams + .iter() + .any(|s| pos + usize::from(s.end_offset_words) * 2 > length) + { + return Err(Error::corrupt( + "TrueHD: substream data runs past the access unit", + )); } Ok(AccessUnitHeader { @@ -314,6 +324,7 @@ pub struct TrueHdDecoder { params: CodecParameters, core: crate::decode::Core, pending: Option, + substream_count: usize, } impl Default for TrueHdDecoder { @@ -331,6 +342,7 @@ impl TrueHdDecoder { params: CodecParameters::new(CodecId::TrueHd), core: crate::decode::Core::new(), pending: None, + substream_count: 0, } } @@ -349,7 +361,8 @@ impl TrueHdDecoder { /// See [`TrueHdDecoder::push`]. pub fn decode_access_unit(&mut self, data: &[u8]) -> Result> { - let header = AccessUnitHeader::parse(data)?; + let header = AccessUnitHeader::parse(data, self.substream_count)?; + self.substream_count = header.substreams.len(); self.core.decode(&header, data) } } @@ -379,6 +392,7 @@ impl Decoder for TrueHdDecoder { fn reset(&mut self) { self.pending = None; + self.substream_count = 0; self.core.reset(); } } @@ -409,7 +423,9 @@ mod tests { ]; 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 + let mut rest = [0u8; 23]; // rest of the major sync, unused here + rest[11] = 0x20; // num_substreams = 2 (byte 16's top nibble) + au.extend_from_slice(&rest); 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]); @@ -430,7 +446,7 @@ mod tests { #[test] fn parses_a_stereo_access_unit_with_no_major_sync() { - let au = AccessUnitHeader::parse(&stereo_au()).unwrap(); + let au = AccessUnitHeader::parse(&stereo_au(), 1).unwrap(); assert_eq!(au.length, 10); assert_eq!(au.input_timing, 0x1234); assert!(au.major_sync.is_none()); @@ -440,7 +456,7 @@ mod tests { #[test] fn parses_a_5_1_access_unit_with_a_major_sync() { - let au = AccessUnitHeader::parse(&surround51_au()).unwrap(); + let au = AccessUnitHeader::parse(&surround51_au(), 0).unwrap(); assert_eq!(au.length, 44); let sync = au.major_sync.expect("major sync detected"); assert_eq!(sync.format, MajorSyncFormat::TrueHd); @@ -457,7 +473,7 @@ mod tests { // 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()); + assert!(AccessUnitHeader::parse(&au, 2).is_err()); } #[test] @@ -465,7 +481,7 @@ mod tests { let au = surround51_au(); // The header claims 44 bytes; hand over fewer. assert!(matches!( - AccessUnitHeader::parse(&au[..20]), + AccessUnitHeader::parse(&au[..20], 0), Err(Error::NeedMore) )); } @@ -480,7 +496,7 @@ mod tests { au.extend_from_slice(&[0x00, 0x01]); } au.resize(20, 0); - let err = AccessUnitHeader::parse(&au).unwrap_err(); + let err = AccessUnitHeader::parse(&au, 5).unwrap_err(); assert!(matches!(err, Error::Corrupt { .. }), "{err:?}"); } @@ -497,7 +513,7 @@ mod tests { 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 parsed = AccessUnitHeader::parse(&au).unwrap(); + let parsed = AccessUnitHeader::parse(&au, 4).unwrap(); assert_eq!(parsed.substreams.len(), 4); // Entry 3's coded data is the object-audio span the decoder skips. assert_eq!(parsed.substream_span(3), (14, 20)); @@ -513,7 +529,7 @@ mod tests { 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(); + let parsed = AccessUnitHeader::parse(&au, 3).unwrap(); assert_eq!(parsed.substreams.len(), 3); assert_eq!(parsed.channel_layout().unwrap(), ChannelLayout::Surround7_1); } @@ -526,7 +542,7 @@ mod tests { #[test] fn substream_spans_follow_the_directory() { - let au = AccessUnitHeader::parse(&surround51_au()).unwrap(); + let au = AccessUnitHeader::parse(&surround51_au(), 0).unwrap(); assert_eq!(au.substream_span(0), (36, 38)); assert_eq!(au.substream_span(1), (38, 44)); } diff --git a/crates/ec-truehd/tests/it/atmos_synth.rs b/crates/ec-truehd/tests/it/atmos_synth.rs index 260ad502..07128ce5 100644 --- a/crates/ec-truehd/tests/it/atmos_synth.rs +++ b/crates/ec-truehd/tests/it/atmos_synth.rs @@ -93,7 +93,7 @@ fn parity_ok(header: &[u8], directory: &[u8]) -> bool { /// Rebuilds one access unit of the 7.1 remux with a 4th (object-audio) /// directory entry whose coded data is `FILLER_WORDS` words of `filler`. fn with_object_substream(au: &[u8], filler: u8) -> Vec { - let header = AccessUnitHeader::parse(au).expect("the original access unit parses"); + let header = AccessUnitHeader::parse(au, 0).expect("the original access unit parses"); assert_eq!( header.substreams.len(), 3, @@ -193,7 +193,7 @@ fn synthetic_atmos_decodes_bit_exact_to_the_original_7_1() { .collect(); for au in &synthetic { - let header = AccessUnitHeader::parse(au).expect("synthetic access unit parses"); + let header = AccessUnitHeader::parse(au, 0).expect("synthetic access unit parses"); assert_eq!(header.substreams.len(), 4, "a 4-entry directory"); assert_eq!( header.channel_layout().expect("a layout"), diff --git a/crates/ec-truehd/tests/it/common.rs b/crates/ec-truehd/tests/it/common.rs index c85ad9d5..61f5fea5 100644 --- a/crates/ec-truehd/tests/it/common.rs +++ b/crates/ec-truehd/tests/it/common.rs @@ -3,11 +3,13 @@ use ec_truehd::sync::AccessUnitHeader; pub fn raw_access_units(data: &[u8]) -> Vec> { let mut aus = Vec::new(); let mut pos = 0; + let mut substreams = 0; while pos < data.len() { - let header = AccessUnitHeader::parse(&data[pos..]) + let header = AccessUnitHeader::parse(&data[pos..], substreams) .unwrap_or_else(|e| panic!("access unit {}: {e}", aus.len())); aus.push(data[pos..pos + header.length].to_vec()); pos += header.length; + substreams = header.substreams.len(); } aus }