forge
Explore
Log in

Don't you dare go Hollow

TrueHD: directory from major sync count, 32-byte Atmos major sync (ffmpeg 9.0.2 mlp_parse.c/mlpdec.c)

Browse files at this commit

2c05ed8c47688d464707f92470e190bfb2ab87f3Ahmet Kaan GümüşParent: 76482df
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.rsmodified+1 -1
@@ -779,7 +779,7 @@ impl Track {
779779 // The access unit goes on in the next PES.
780780 break;
781781 }
782- let Ok(head) = AccessUnitHeader::parse(&rest[..len]) else {
782+ let Ok(head) = AccessUnitHeader::parse(&rest[..len], 0) else {
783783 cur += 1;
784784 continue;
785785 };
crates/ec-mpegts/tests/it/truehd.rsmodified+3 -1
@@ -76,10 +76,12 @@ fn truehd_in_ts_decodes_sample_exact_to_ffmpeg() {
7676 assert!(!pkts.is_empty(), "{name}: no TrueHD access units");
7777
7878 // Every packet is one whole access unit: its length word covers it exactly.
79+ let mut substreams = 0;
7980 for p in &pkts {
80- let head = AccessUnitHeader::parse(&p.data)
81+ let head = AccessUnitHeader::parse(&p.data, substreams)
8182 .unwrap_or_else(|e| panic!("{name}: AU at {:#x}: {e}", p.off));
8283 assert_eq!(head.length, p.data.len(), "{name}: AU length");
84+ substreams = head.substreams.len();
8385 }
8486
8587 let mut dec = TrueHdDecoder::new();
crates/ec-truehd/fuzz/fuzz_targets/parse_sync.rsmodified+2 -2
@@ -13,7 +13,7 @@ const MAX_BODY: usize = 8190 - 8;
1313 fuzz_target!(|data: &[u8]| {
1414 // Raw bytes: the length word and, if it happens to match, the major sync.
1515 let _ = frame_length(data);
16- let _ = AccessUnitHeader::parse(data);
16+ let _ = AccessUnitHeader::parse(data, 0);
1717
1818 // Fixup: wrap the input in a valid AU header and TrueHD major sync word, so the
1919 // mutations land on the sync fields and the directory behind them instead of on
@@ -30,5 +30,5 @@ fuzz_target!(|data: &[u8]| {
3030 return;
3131 };
3232 au[..2].copy_from_slice(&(words & 0x0FFF).to_be_bytes());
33- let _ = AccessUnitHeader::parse(&au);
33+ let _ = AccessUnitHeader::parse(&au, 0);
3434 });
crates/ec-truehd/src/sync.rsmodified+69 -53
@@ -20,17 +20,17 @@
2020 //! - `data[4..8]`: `0xF8726FBA` (TrueHD) or `0xF8726FBB` (MLP) names a major
2121 //! sync at this access unit; absent on most access units, present roughly
2222 //! once per video frame.
23-//! - When a major sync is present, it occupies exactly 28 bytes starting at
24-//! `data[4]` (format id + 24 more bytes, ending where the substream
25-//! directory begins): `data[8]` packs two 4-bit sample-rate codes,
26-//! `group1` in the high nibble and `group2` (a secondary/backward-compat
27-//! rate, `0xF` when unused) in the low nibble. A code maps to a rate via
28-//! [`sample_rate`]; codes 0-2 are the 48 kHz family (`48000 * 2^n`), codes
29-//! 8-10 the 44.1 kHz family (`44100 * 2^n`). The rest of the major sync
30-//! (channel-assignment bitfields, flags) is skipped: this build does not
31-//! independently verify their bit positions, so [`ChannelLayout`] is
32-//! derived from the substream *directory* instead (see below), which is
33-//! fully verified against the sample file.
23+//! - When a major sync is present, it occupies 28 bytes starting at `data[4]`
24+//! (format id + 24 more bytes), plus a TrueHD extension block when
25+//! `data[25] & 1` is set: `2 + 2 * (data[26] >> 4)` bytes, then a 2-byte
26+//! checksum (ffmpeg's `mlp_get_major_sync_size`). `data[8]` packs two 4-bit
27+//! sample-rate codes, `group1` in the high nibble and `group2` (a
28+//! secondary/backward-compat rate, `0xF` when unused) in the low nibble. A
29+//! code maps to a rate via [`sample_rate`]; codes 0-2 are the 48 kHz family
30+//! (`48000 * 2^n`), codes 8-10 the 44.1 kHz family (`44100 * 2^n`). The
31+//! 4-bit `num_substreams` is the top nibble of `data[16]`. The rest of the
32+//! major sync (channel-assignment bitfields, flags) is skipped: [`ChannelLayout`]
33+//! is derived from the substream count instead.
3434 //! - The substream directory starts right after the major sync (or right
3535 //! after the 4-byte access-unit header, on an access unit with none), one
3636 //! [`SubstreamInfo`] entry per substream: a 2-byte word whose top 4 bits
@@ -38,11 +38,10 @@
3838 //! word, [`SubstreamInfo::extra`] — follows) and whose low 12 bits are the
3939 //! substream's *end pointer*: the cumulative byte offset, in 16-bit words
4040 //! from the end of the whole directory, where this substream's coded data
41-//! ends. There is no explicit substream-count field; a directory entry is
42-//! the *last* one exactly when `directory_end + end_pointer_bytes` lands
43-//! on the access unit's own total length — which is how
44-//! [`AccessUnitHeader::parse`] finds the count, bounded at 4 entries
45-//! (Dolby's own substream cap).
41+//! ends. The count is not inferred from the end pointers (an access unit may
42+//! carry trailing bytes past the last one): it is the major sync's
43+//! `num_substreams`, carried over from the last major sync on access units
44+//! without one, bounded at 4 entries (Dolby's own substream cap).
4645 //!
4746 //! Substream count maps to [`ChannelLayout`] by Dolby's own published
4847 //! substream convention — substream 0 always carries a 2-ch presentation,
@@ -66,8 +65,7 @@ pub const MAJOR_SYNC_TRUEHD: u32 = 0xF872_6FBA;
6665 /// MLP's major sync word (lossless-only, no TrueHD extensions).
6766 pub const MAJOR_SYNC_MLP: u32 = 0xF872_6FBB;
6867
69-/// Bytes a major sync occupies, format id included, ending where the
70-/// substream directory begins.
68+/// Bytes a plain major sync occupies, format id included.
7169 const MAJOR_SYNC_LEN: usize = 28;
7270
7371 /// Dolby's cap on substream directory entries per access unit: entries 0..=2
@@ -123,6 +121,11 @@ pub struct MajorSyncInfo {
123121 /// L/R, 1 = C, 2 = LFE, 3 = Ls/Rs, 6 = Lrs/Rrs; `0x4F` is standard 7.1);
124122 /// 0 when the major sync is plain MLP, which has no such field.
125123 pub ch8_assignment: u16,
124+ /// Substreams in the access unit's directory (the major sync's
125+ /// `num_substreams`, top nibble of `data[16]`).
126+ pub num_substreams: usize,
127+ /// Bytes the major sync occupies, its extension block and checksum included.
128+ pub len: usize,
126129 }
127130
128131 /// A rate code's `44.1k*2^n` / `48k*2^n` value, or [`Error::Unsupported`] for
@@ -164,11 +167,19 @@ impl MajorSyncInfo {
164167 MajorSyncFormat::TrueHd => (u16::from(data[6] & 0x1F) << 8) | u16::from(data[7]),
165168 MajorSyncFormat::Mlp => 0,
166169 };
170+ let len = match format {
171+ MajorSyncFormat::TrueHd if data[25] & 1 != 0 => {
172+ MAJOR_SYNC_LEN + 2 + 2 * usize::from(data[26] >> 4)
173+ }
174+ _ => MAJOR_SYNC_LEN,
175+ };
167176 Ok(MajorSyncInfo {
168177 format,
169178 sample_rate,
170179 rate_code,
171180 ch8_assignment,
181+ num_substreams: usize::from(data[16] >> 4),
182+ len,
172183 })
173184 }
174185 }
@@ -209,8 +220,10 @@ pub struct AccessUnitHeader {
209220
210221 impl AccessUnitHeader {
211222 /// Parses one access unit's header from `data`, which must hold at least
212- /// [`frame_length`]'s worth of bytes.
213- pub fn parse(data: &[u8]) -> Result<AccessUnitHeader> {
223+ /// [`frame_length`]'s worth of bytes. `stream_substreams` is the substream
224+ /// count the stream's last major sync declared (0 before any); a unit with
225+ /// its own major sync uses that sync's count instead.
226+ pub fn parse(data: &[u8], stream_substreams: usize) -> Result<AccessUnitHeader> {
214227 let length = frame_length(data)?;
215228 if data.len() < length {
216229 return Err(Error::NeedMore);
@@ -226,21 +239,18 @@ impl AccessUnitHeader {
226239 }
227240 _ => None,
228241 };
229- let dir_start = AU_HEADER_LEN
230- + if major_sync.is_some() {
231- MAJOR_SYNC_LEN
232- } else {
233- 0
234- };
235-
236- let mut substreams = Vec::new();
237- let mut pos = dir_start;
238- loop {
239- if substreams.len() == MAX_DIRECTORY_ENTRIES {
240- return Err(Error::corrupt(
241- "TrueHD: substream directory has more than 4 entries",
242- ));
243- }
242+ if major_sync.is_some_and(|s| s.num_substreams == 0) {
243+ return Err(Error::corrupt("TrueHD: major sync declares no substreams"));
244+ }
245+ let count = major_sync.map_or(stream_substreams, |s| s.num_substreams);
246+ if count > MAX_DIRECTORY_ENTRIES {
247+ return Err(Error::corrupt(
248+ "TrueHD: substream directory has more than 4 entries",
249+ ));
250+ }
251+ let mut substreams = Vec::with_capacity(count);
252+ let mut pos = AU_HEADER_LEN + major_sync.map_or(0, |s| s.len);
253+ for _ in 0..count {
244254 let word = au.get(pos..pos + 2).ok_or(Error::NeedMore)?;
245255 let word = u16::from_be_bytes([word[0], word[1]]);
246256 let flags = (word >> 12) as u8;
@@ -258,14 +268,14 @@ impl AccessUnitHeader {
258268 end_offset_words,
259269 extra,
260270 });
261- if pos + usize::from(end_offset_words) * 2 == length {
262- break;
263- }
264- if pos >= length {
265- return Err(Error::corrupt(
266- "TrueHD: substream directory did not sum to the access unit's length",
267- ));
268- }
271+ }
272+ if substreams
273+ .iter()
274+ .any(|s| pos + usize::from(s.end_offset_words) * 2 > length)
275+ {
276+ return Err(Error::corrupt(
277+ "TrueHD: substream data runs past the access unit",
278+ ));
269279 }
270280
271281 Ok(AccessUnitHeader {
@@ -314,6 +324,7 @@ pub struct TrueHdDecoder {
314324 params: CodecParameters,
315325 core: crate::decode::Core,
316326 pending: Option<AudioFrame>,
327+ substream_count: usize,
317328 }
318329
319330 impl Default for TrueHdDecoder {
@@ -331,6 +342,7 @@ impl TrueHdDecoder {
331342 params: CodecParameters::new(CodecId::TrueHd),
332343 core: crate::decode::Core::new(),
333344 pending: None,
345+ substream_count: 0,
334346 }
335347 }
336348
@@ -349,7 +361,8 @@ impl TrueHdDecoder {
349361
350362 /// See [`TrueHdDecoder::push`].
351363 pub fn decode_access_unit(&mut self, data: &[u8]) -> Result<Option<AudioFrame>> {
352- let header = AccessUnitHeader::parse(data)?;
364+ let header = AccessUnitHeader::parse(data, self.substream_count)?;
365+ self.substream_count = header.substreams.len();
353366 self.core.decode(&header, data)
354367 }
355368 }
@@ -379,6 +392,7 @@ impl Decoder for TrueHdDecoder {
379392
380393 fn reset(&mut self) {
381394 self.pending = None;
395+ self.substream_count = 0;
382396 self.core.reset();
383397 }
384398 }
@@ -409,7 +423,9 @@ mod tests {
409423 ];
410424 au.extend_from_slice(&MAJOR_SYNC_TRUEHD.to_be_bytes());
411425 au.push(0x0F); // sample rate: group1 code 0 (48000), group2 0xF (absent)
412- au.extend(std::iter::repeat_n(0u8, 23)); // rest of the major sync, unused here
426+ let mut rest = [0u8; 23]; // rest of the major sync, unused here
427+ rest[11] = 0x20; // num_substreams = 2 (byte 16's top nibble)
428+ au.extend_from_slice(&rest);
413429 au.extend_from_slice(&[0x00, 0x01]); // substream 0: end +1 word (not the last)
414430 au.extend_from_slice(&[0x00, 0x04]); // substream 1: end +4 words (lands on EOF)
415431 au.extend_from_slice(&[0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88]);
@@ -430,7 +446,7 @@ mod tests {
430446
431447 #[test]
432448 fn parses_a_stereo_access_unit_with_no_major_sync() {
433- let au = AccessUnitHeader::parse(&stereo_au()).unwrap();
449+ let au = AccessUnitHeader::parse(&stereo_au(), 1).unwrap();
434450 assert_eq!(au.length, 10);
435451 assert_eq!(au.input_timing, 0x1234);
436452 assert!(au.major_sync.is_none());
@@ -440,7 +456,7 @@ mod tests {
440456
441457 #[test]
442458 fn parses_a_5_1_access_unit_with_a_major_sync() {
443- let au = AccessUnitHeader::parse(&surround51_au()).unwrap();
459+ let au = AccessUnitHeader::parse(&surround51_au(), 0).unwrap();
444460 assert_eq!(au.length, 44);
445461 let sync = au.major_sync.expect("major sync detected");
446462 assert_eq!(sync.format, MajorSyncFormat::TrueHd);
@@ -457,7 +473,7 @@ mod tests {
457473 // major-sync bytes as if they were directory entries and cannot
458474 // land on the access unit's real end, but must not panic.
459475 au[5] = 0x00;
460- assert!(AccessUnitHeader::parse(&au).is_err());
476+ assert!(AccessUnitHeader::parse(&au, 2).is_err());
461477 }
462478
463479 #[test]
@@ -465,7 +481,7 @@ mod tests {
465481 let au = surround51_au();
466482 // The header claims 44 bytes; hand over fewer.
467483 assert!(matches!(
468- AccessUnitHeader::parse(&au[..20]),
484+ AccessUnitHeader::parse(&au[..20], 0),
469485 Err(Error::NeedMore)
470486 ));
471487 }
@@ -480,7 +496,7 @@ mod tests {
480496 au.extend_from_slice(&[0x00, 0x01]);
481497 }
482498 au.resize(20, 0);
483- let err = AccessUnitHeader::parse(&au).unwrap_err();
499+ let err = AccessUnitHeader::parse(&au, 5).unwrap_err();
484500 assert!(matches!(err, Error::Corrupt { .. }), "{err:?}");
485501 }
486502
@@ -497,7 +513,7 @@ mod tests {
497513 au.extend_from_slice(&[0x00, 0x01]); // substream 2: doesn't land on EOF yet
498514 au.extend_from_slice(&[0x00, 0x04]); // substream 3: pos(12) + 4*2 == 20, lands on EOF
499515 au.resize(20, 0);
500- let parsed = AccessUnitHeader::parse(&au).unwrap();
516+ let parsed = AccessUnitHeader::parse(&au, 4).unwrap();
501517 assert_eq!(parsed.substreams.len(), 4);
502518 // Entry 3's coded data is the object-audio span the decoder skips.
503519 assert_eq!(parsed.substream_span(3), (14, 20));
@@ -513,7 +529,7 @@ mod tests {
513529 au.extend_from_slice(&[0x00, 0x01]); // substream 1: doesn't land on EOF yet
514530 au.extend_from_slice(&[0x00, 0x05]); // substream 2: pos(10) + 5*2 == 20, lands on EOF
515531 au.resize(20, 0);
516- let parsed = AccessUnitHeader::parse(&au).unwrap();
532+ let parsed = AccessUnitHeader::parse(&au, 3).unwrap();
517533 assert_eq!(parsed.substreams.len(), 3);
518534 assert_eq!(parsed.channel_layout().unwrap(), ChannelLayout::Surround7_1);
519535 }
@@ -526,7 +542,7 @@ mod tests {
526542
527543 #[test]
528544 fn substream_spans_follow_the_directory() {
529- let au = AccessUnitHeader::parse(&surround51_au()).unwrap();
545+ let au = AccessUnitHeader::parse(&surround51_au(), 0).unwrap();
530546 assert_eq!(au.substream_span(0), (36, 38));
531547 assert_eq!(au.substream_span(1), (38, 44));
532548 }
crates/ec-truehd/tests/it/atmos_synth.rsmodified+2 -2
@@ -93,7 +93,7 @@ fn parity_ok(header: &[u8], directory: &[u8]) -> bool {
9393 /// Rebuilds one access unit of the 7.1 remux with a 4th (object-audio)
9494 /// directory entry whose coded data is `FILLER_WORDS` words of `filler`.
9595 fn with_object_substream(au: &[u8], filler: u8) -> Vec<u8> {
96- let header = AccessUnitHeader::parse(au).expect("the original access unit parses");
96+ let header = AccessUnitHeader::parse(au, 0).expect("the original access unit parses");
9797 assert_eq!(
9898 header.substreams.len(),
9999 3,
@@ -193,7 +193,7 @@ fn synthetic_atmos_decodes_bit_exact_to_the_original_7_1() {
193193 .collect();
194194
195195 for au in &synthetic {
196- let header = AccessUnitHeader::parse(au).expect("synthetic access unit parses");
196+ let header = AccessUnitHeader::parse(au, 0).expect("synthetic access unit parses");
197197 assert_eq!(header.substreams.len(), 4, "a 4-entry directory");
198198 assert_eq!(
199199 header.channel_layout().expect("a layout"),
crates/ec-truehd/tests/it/common.rsmodified+3 -1
@@ -3,11 +3,13 @@ use ec_truehd::sync::AccessUnitHeader;
33 pub fn raw_access_units(data: &[u8]) -> Vec<Vec<u8>> {
44 let mut aus = Vec::new();
55 let mut pos = 0;
6+ let mut substreams = 0;
67 while pos < data.len() {
7- let header = AccessUnitHeader::parse(&data[pos..])
8+ let header = AccessUnitHeader::parse(&data[pos..], substreams)
89 .unwrap_or_else(|e| panic!("access unit {}: {e}", aus.len()));
910 aus.push(data[pos..pos + header.length].to_vec());
1011 pos += header.length;
12+ substreams = header.substreams.len();
1113 }
1214 aus
1315 }