diff --git a/crates/ec-mpegts/src/track.rs b/crates/ec-mpegts/src/track.rs index 0dcc875d..fc6f59e9 100644 --- a/crates/ec-mpegts/src/track.rs +++ b/crates/ec-mpegts/src/track.rs @@ -90,6 +90,7 @@ pub(crate) struct TrueHdFacts { pub rate: u32, pub layout: ChannelLayout, pub samples: u32, + pub substreams: usize, } /// How the program-stream front end hands pictures over (see `psvideo`). @@ -779,10 +780,15 @@ impl Track { // The access unit goes on in the next PES. break; } - let Ok(head) = AccessUnitHeader::parse(&rest[..len]) else { + let streams = self.cfg.truehd.as_ref().map_or(0, |t| t.substreams); + let Ok(head) = AccessUnitHeader::parse(&rest[..len], streams) else { cur += 1; continue; }; + if head.substreams.is_empty() { + cur += 1; + continue; + } if let Some(m) = head.major_sync && let Ok(layout) = head.channel_layout() { @@ -791,6 +797,7 @@ impl Track { layout, // A major sync's rate code sizes the access units: 40 << n samples. samples: 40 << (m.rate_code & 7), + substreams: head.substreams.len(), }); } if cur >= new_start && !anchored && p.pts.is_some() { 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..3630a809 100644 --- a/crates/ec-truehd/src/sync.rs +++ b/crates/ec-truehd/src/sync.rs @@ -20,17 +20,6 @@ //! - `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 @@ -38,11 +27,7 @@ //! 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. //! //! Substream count maps to [`ChannelLayout`] by Dolby's own published //! substream convention — substream 0 always carries a 2-ch presentation, @@ -66,8 +51,6 @@ 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; /// Dolby's cap on substream directory entries per access unit: entries 0..=2 @@ -123,6 +106,10 @@ 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, + #[allow(missing_docs)] + pub num_substreams: usize, + #[allow(missing_docs)] + pub len: usize, } /// A rate code's `44.1k*2^n` / `48k*2^n` value, or [`Error::Unsupported`] for @@ -164,11 +151,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, }) } } @@ -210,7 +205,7 @@ 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 { + pub fn parse(data: &[u8], stream_substreams: usize) -> Result { let length = frame_length(data)?; if data.len() < length { return Err(Error::NeedMore); @@ -226,21 +221,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 +250,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 +306,7 @@ pub struct TrueHdDecoder { params: CodecParameters, core: crate::decode::Core, pending: Option, + substream_count: usize, } impl Default for TrueHdDecoder { @@ -331,6 +324,7 @@ impl TrueHdDecoder { params: CodecParameters::new(CodecId::TrueHd), core: crate::decode::Core::new(), pending: None, + substream_count: 0, } } @@ -349,7 +343,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 +374,7 @@ impl Decoder for TrueHdDecoder { fn reset(&mut self) { self.pending = None; + self.substream_count = 0; self.core.reset(); } } @@ -409,7 +405,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[11] = 0x20; + 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 +428,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 +438,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 +455,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 +463,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 +478,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 +495,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 +511,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 +524,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..527c4357 100644 --- a/crates/ec-truehd/tests/it/atmos_synth.rs +++ b/crates/ec-truehd/tests/it/atmos_synth.rs @@ -1,34 +1,3 @@ -//! Atmos backward compatibility, tested on a synthetic 4-substream stream. -//! -//! [`with_object_substream`] rebuilds it with a 4th directory entry: the -//! object-audio substream, here a run of [`FILLER_WORDS`] stand-in words -//! appended after substream 2's coded data. The rebuilt access unit is: -//! -//! - header: length word (new word count, parity nibble recomputed) and the -//! original input timing; -//! - major sync, when the original has one: `num_substreams` (top nibble of -//! byte 16) set to 4, and the major sync's own CRC-16 (bytes 26..28) -//! recomputed; -//! - directory: the original three entries unchanged (their cumulative end -//! pointers are relative to the directory end, so the coded data they name -//! does not move relative to it), then a fourth entry whose end pointer is -//! the old last pointer plus the filler length; -//! - substream data: the original substreams 0..2 bytes verbatim, then the -//! filler. -//! -//! Decoding the synthetic stream must therefore equal decoding the original -//! bit-exactly: the 8-channel (7.1) presentation is the one decoded and -//! output, substream 3 is skipped via its end pointer, and the parity and -//! checksum of substreams 0..2 are still checked. Object audio itself is out -//! of scope and never decoded, so the filler's contents must not matter; a -//! second test checks that. -//! -//! Optional cross-check: with `EC_ATMOS_SYNTH_OUT=` set, the synthetic -//! access units are also written there as a raw TrueHD elementary stream, so -//! `ffmpeg -f truehd -i -f s32le` can be compared against this -//! decoder's output (ffmpeg decodes the same 8-channel presentation). -//! - use std::path::Path; use ec_core::frame::ChannelLayout; @@ -37,27 +6,26 @@ use ec_truehd::sync::AccessUnitHeader; use crate::common::raw_access_units; -/// major sync among them. -const AUS: usize = 1200; -/// Length of the object-audio stand-in, in 16-bit words. +const MIN_ACCESS_UNITS: usize = 100; const FILLER_WORDS: u16 = 4; -/// The 12-bit access-unit length word's maximum, in 16-bit words. const MAX_AU_WORDS: usize = 0x0FFF; -const MAJOR_SYNC_LEN: usize = 28; -fn truehd_access_units() -> Vec> { +fn sample_access_units() -> Vec> { let data = std::fs::read(ec_testkit::fixture("open/fate/truehd/atmos.thd")).expect("read atmos.thd"); let aus = raw_access_units(&data); assert!( - aus.len() >= AUS, - "atmos.thd has fewer than {AUS} access units" + aus.len() >= MIN_ACCESS_UNITS, + "atmos.thd has only {} access units", + aus.len() ); - aus.into_iter().take(AUS).collect() + aus +} + +fn header_of(au: &[u8], substreams: usize) -> AccessUnitHeader { + AccessUnitHeader::parse(au, substreams).expect("access unit parses") } -/// The major sync's CRC-16 (poly `0x002D`, MSB-first table form), the same -/// one the crate's encoder writes and ffmpeg checks. fn crc16_table() -> [u32; 256] { let mut table = [0u32; 256]; for (i, entry) in table.iter_mut().enumerate() { @@ -71,107 +39,131 @@ fn crc16_table() -> [u32; 256] { table } -/// The major sync's checksum field value: CRC-16 over bytes `0..24`, XORed -/// with the little-endian word at `24..26`, stored little-endian at `26..28`. fn major_sync_checksum(sync: &[u8]) -> u16 { + let n = sync.len() - 4; let table = crc16_table(); let mut crc: u32 = 0; - for &b in &sync[..24] { + for &b in &sync[..n] { crc = table[usize::from((crc as u8) ^ b)] ^ (crc >> 8); } - (crc as u16) ^ u16::from_le_bytes([sync[24], sync[25]]) + (crc as u16) ^ u16::from_le_bytes([sync[n], sync[n + 1]]) +} + +fn checksum_is_valid(sync: &[u8]) -> bool { + let n = sync.len() - 2; + major_sync_checksum(sync) == u16::from_le_bytes([sync[n], sync[n + 1]]) +} + +fn set_substream_count(sync: &mut [u8], count: u8) { + sync[16] = (sync[16] & 0x0F) | (count << 4); + let checksum = major_sync_checksum(sync); + let n = sync.len() - 2; + sync[n..].copy_from_slice(&checksum.to_le_bytes()); } -/// The access-unit header's parity fold: the 4 header bytes and every -/// directory byte, XORed together, must leave a nibble pair that is bitwise -/// complementary (`((p >> 4) ^ p) & 0xF == 0xF`). fn parity_ok(header: &[u8], directory: &[u8]) -> bool { let p = header.iter().chain(directory).fold(0u8, |a, &b| a ^ b); ((p >> 4) ^ p) & 0xF == 0xF } -/// 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"); - assert_eq!( - header.substreams.len(), - 3, - "the remux is a 3-substream 7.1 stream" - ); - let sync_len = if header.major_sync.is_some() { - MAJOR_SYNC_LEN - } else { - 0 - }; - let dir_start = 4 + sync_len; - let old_dir = &au[dir_start..header.data_start]; - let old_last_end = header.substreams[2].end_offset_words; - let new_last_end = old_last_end + FILLER_WORDS; - - // The original directory bytes are reused verbatim. The new entry is a - // plain 2-byte word: no extra word, no check data, and the non-restart bit - // (0x4) copied from substream 2. That bit is set exactly on access units - // without a major sync, and ffmpeg rejects an entry that disagrees with - // the access unit's major sync. Its end pointer is cumulative. - let nonrestart = header.substreams[2].flags & 0x4; - let mut dir = old_dir.to_vec(); - let entry = (u16::from(nonrestart) << 12) | new_last_end; - dir.extend_from_slice(&entry.to_be_bytes()); - - let coded = &au[header.data_start..header.length]; - let filler_bytes = usize::from(FILLER_WORDS) * 2; - +fn assemble(timing: [u8; 2], sync: Option<&[u8]>, dir: &[u8], coded: &[u8]) -> Vec { let mut body = Vec::new(); - if header.major_sync.is_some() { - let mut sync = au[4..4 + MAJOR_SYNC_LEN].to_vec(); - assert_eq!( - u16::from_le_bytes([sync[26], sync[27]]), - major_sync_checksum(&sync), - "the remux's major sync checksum matches the formula" - ); - sync[16] = (sync[16] & 0x0F) | (4 << 4); // num_substreams = 4 - let checksum = major_sync_checksum(&sync); - sync[26..28].copy_from_slice(&checksum.to_le_bytes()); - body.extend_from_slice(&sync); - } - body.extend_from_slice(&dir); + body.extend_from_slice(sync.unwrap_or(&[])); + body.extend_from_slice(dir); body.extend_from_slice(coded); - body.extend(std::iter::repeat_n(filler, filler_bytes)); - - let total = 4 + body.len(); - let words = total / 2; + let words = (4 + body.len()) / 2; assert!(words <= MAX_AU_WORDS, "synthetic access unit too long"); - let timing = [au[2], au[3]]; - // The parity nibble is the one value that makes the fold complementary. let nibble = (0u8..16) .find(|&cn| { - let len_hi = (words >> 8) as u8 & 0x0F; - let len_lo = (words & 0xFF) as u8; - let head = [(cn << 4) | len_hi, len_lo, timing[0], timing[1]]; - parity_ok(&head, &dir) + let head = [ + (cn << 4) | ((words >> 8) as u8 & 0x0F), + (words & 0xFF) as u8, + timing[0], + timing[1], + ]; + parity_ok(&head, dir) }) .expect("one of the 16 nibble values satisfies the fold"); let word = (u16::from(nibble) << 12) | words as u16; - - // Sanity: the same fold rule holds for the original access unit. - assert!( - parity_ok(&au[..4], old_dir), - "the remux's own parity fold holds" - ); - - let mut out = Vec::with_capacity(total); + let mut out = Vec::with_capacity(4 + body.len()); out.extend_from_slice(&word.to_be_bytes()); out.extend_from_slice(&timing); out.extend_from_slice(&body); out } -/// One decoded frame: its layout and its planes. +fn sync_of(au: &[u8], header: &AccessUnitHeader) -> Option> { + header.major_sync.map(|s| au[4..4 + s.len].to_vec()) +} + +fn directory_start(header: &AccessUnitHeader) -> usize { + 4 + header.major_sync.map_or(0, |s| s.len) +} + +fn convert(aus: &[Vec], f: impl Fn(&[u8], usize) -> Vec) -> Vec> { + let mut count = 0; + aus.iter() + .map(|au| { + let out = f(au.as_slice(), count); + count = header_of(au.as_slice(), count).substreams.len(); + out + }) + .collect() +} + +fn strip_object_substream(au: &[u8], substreams: usize) -> Vec { + let header = header_of(au, substreams); + assert_eq!(header.substreams.len(), 4, "the sample has 4 substreams"); + let entry_len = if header.substreams[3].extra.is_some() { + 4 + } else { + 2 + }; + let dir = &au[directory_start(&header)..header.data_start - entry_len]; + let mut sync = sync_of(au, &header); + if let Some(s) = sync.as_mut() { + assert!(checksum_is_valid(s), "the sample's major sync checksum"); + set_substream_count(s, 3); + } + let (_, end) = header.substream_span(2); + assemble( + [au[2], au[3]], + sync.as_deref(), + dir, + &au[header.data_start..end], + ) +} + +fn with_object_substream(au: &[u8], substreams: usize, filler: u8) -> Vec { + let header = header_of(au, substreams); + assert_eq!(header.substreams.len(), 3, "the input is a 7.1 access unit"); + let last = header.substreams[2]; + let nonrestart = last.flags & 0x4; + let entry = (u16::from(nonrestart) << 12) | (last.end_offset_words + FILLER_WORDS); + let mut dir = au[directory_start(&header)..header.data_start].to_vec(); + dir.extend_from_slice(&entry.to_be_bytes()); + let mut sync = sync_of(au, &header); + if let Some(s) = sync.as_mut() { + set_substream_count(s, 4); + } + let (_, end) = header.substream_span(2); + let mut coded = au[header.data_start..end].to_vec(); + coded.extend(std::iter::repeat_n(filler, usize::from(FILLER_WORDS) * 2)); + assemble([au[2], au[3]], sync.as_deref(), &dir, &coded) +} + +fn with_object_payload(au: &[u8], substreams: usize, fill: u8) -> Vec { + let header = header_of(au, substreams); + assert_eq!(header.substreams.len(), 4, "the sample has 4 substreams"); + let (start, end) = header.substream_span(3); + assert!(start < end, "the object substream has coded data"); + let mut out = au.to_vec(); + out[start..end].fill(fill); + out +} + type Decoded = Vec<(ChannelLayout, Vec>)>; -/// Decodes `aus` with a fresh decoder and returns every output frame's planes -/// plus the decoder's self-check tallies. fn decode_all(aus: &[Vec]) -> (Decoded, ec_truehd::CheckStats) { let mut decoder = TrueHdDecoder::new(); let mut frames = Vec::new(); @@ -186,43 +178,28 @@ fn decode_all(aus: &[Vec]) -> (Decoded, ec_truehd::CheckStats) { #[test] fn synthetic_atmos_decodes_bit_exact_to_the_original_7_1() { - let originals = truehd_access_units(); - let synthetic: Vec> = originals - .iter() - .map(|au| with_object_substream(au, 0xA5)) - .collect(); - - for au in &synthetic { - let header = AccessUnitHeader::parse(au).expect("synthetic access unit parses"); - assert_eq!(header.substreams.len(), 4, "a 4-entry directory"); - assert_eq!( - header.channel_layout().expect("a layout"), - ChannelLayout::Surround7_1, - "the 8-ch presentation is the top PCM one" - ); - } + let originals = sample_access_units(); + let sevens = convert(&originals, strip_object_substream); + let atmos = convert(&sevens, |au, n| with_object_substream(au, n, 0xA5)); if let Some(out) = std::env::var_os("EC_ATMOS_SYNTH_OUT") { - let raw: Vec = synthetic.iter().flatten().copied().collect(); + let raw: Vec = atmos.iter().flatten().copied().collect(); std::fs::write(&out, raw).expect("write the synthetic TrueHD stream"); eprintln!("wrote synthetic stream to {}", Path::new(&out).display()); } let (ours, _) = decode_all(&originals); - let (synth, stats) = decode_all(&synthetic); + let (seven, _) = decode_all(&sevens); + let (synth, stats) = decode_all(&atmos); assert!(!ours.is_empty(), "the original stream decodes to frames"); - assert_eq!(synth.len(), ours.len(), "same number of frames"); + assert_eq!(seven.len(), ours.len(), "7.1 rebuild: same number of frames"); + assert!(seven == ours, "the 3-substream 7.1 stream differs from the original"); + assert_eq!(synth.len(), ours.len(), "synthetic: same number of frames"); for (i, ((la, pa), (lb, pb))) in ours.iter().zip(&synth).enumerate() { assert_eq!(*la, ChannelLayout::Surround7_1, "frame {i} is 7.1"); assert_eq!(*lb, ChannelLayout::Surround7_1, "frame {i} is 7.1"); assert_eq!(pa, pb, "frame {i} differs from the original"); } - eprintln!( - "{} frames, 8-channel, bit-exact vs the original", - ours.len() - ); - - // The PCM substreams' own checks still run on the synthetic stream. assert_eq!(stats.parity_failures, 0, "substream parity"); assert_eq!(stats.restart_crc_failures, 0, "restart header CRC"); assert_eq!(stats.lossless_check_failures, 0, "lossless check"); @@ -231,21 +208,20 @@ fn synthetic_atmos_decodes_bit_exact_to_the_original_7_1() { #[test] fn object_substream_contents_do_not_change_the_pcm_output() { - let originals = truehd_access_units(); - // Filler bytes are never read, so any value must decode identically. - let zeros: Vec> = originals - .iter() - .map(|au| with_object_substream(au, 0x00)) - .collect(); - let ones: Vec> = originals - .iter() - .map(|au| with_object_substream(au, 0xFF)) - .collect(); - let (a, _) = decode_all(&zeros); - let (b, _) = decode_all(&ones); + let originals = sample_access_units(); + let zeros = convert(&originals, |au, n| with_object_payload(au, n, 0x00)); + let ones = convert(&originals, |au, n| with_object_payload(au, n, 0xFF)); + assert_ne!(zeros, originals, "the object payload was replaced"); + let (a, sa) = decode_all(&originals); + let (b, sb) = decode_all(&zeros); + let (c, sc) = decode_all(&ones); + for s in [sa, sb, sc] { + assert_eq!(s.parity_failures, 0, "substream parity"); + assert_eq!(s.restart_crc_failures, 0, "restart header CRC"); + assert_eq!(s.lossless_check_failures, 0, "lossless check"); + assert_eq!(s.length_mismatches, 0, "substream lengths"); + } assert!(!a.is_empty()); - assert_eq!( - a, b, - "the object substream's bytes are skipped, not decoded" - ); + assert!(a == b, "object payload of zeros changes the PCM"); + assert!(a == c, "object payload of ones changes the PCM"); } 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 } diff --git a/crates/ec-truehd/tests/it/oracle.rs b/crates/ec-truehd/tests/it/oracle.rs index 30af64c0..9cbfb74c 100644 --- a/crates/ec-truehd/tests/it/oracle.rs +++ b/crates/ec-truehd/tests/it/oracle.rs @@ -42,29 +42,22 @@ fn compare(ours: &[i32], reference: &[i32]) -> (usize, usize, Option) { } #[test] -fn first_60_seconds_of_atmos_are_bit_exact() { - const SECONDS: usize = 60; +fn atmos_sample_is_bit_exact_on_every_channel() { let path = ec_testkit::fixture("open/fate/truehd/atmos.thd"); let reference = s32le(&ffmpeg(&[ "-i", path.to_str().unwrap(), - "-t", - &SECONDS.to_string(), "-f", "s32le", "-", ])); let channels = 8; - let wanted = SECONDS * 48_000 * channels; let data = std::fs::read(&path).expect("read atmos.thd"); let mut decoder = TrueHdDecoder::new(); - let mut ours: Vec = Vec::with_capacity(wanted); + let mut ours: Vec = Vec::with_capacity(reference.len()); let mut aus = 0; for au in raw_access_units(&data) { - if ours.len() >= wanted { - break; - } let frame = decoder .decode_access_unit(&au) .unwrap_or_else(|e| panic!("AU {aus}: {e}")); @@ -76,30 +69,18 @@ fn first_60_seconds_of_atmos_are_bit_exact() { } 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!(aus >= 100, "only {aus} access units"); + assert_eq!(ours.len(), reference.len(), "sample count vs ffmpeg"); 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:?}" - ); + assert_eq!(exact, total, "first mismatch {first:?}"); } /// An externally encoded MLP stream (raw access units) decoded by us must