diff --git a/crates/ec-truehd/tests/it/atmos_synth.rs b/crates/ec-truehd/tests/it/atmos_synth.rs index 07128ce5..bd7f09ae 100644 --- a/crates/ec-truehd/tests/it/atmos_synth.rs +++ b/crates/ec-truehd/tests/it/atmos_synth.rs @@ -1,33 +1,5 @@ -//! 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). -//! +//! Atmos backward compatibility on the open FATE sample (4 substreams, the 4th +//! being object audio, and a 32-byte extended major sync). use std::path::Path; @@ -37,27 +9,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 +42,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, 0).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 +181,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, 0).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 +211,14 @@ 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, _) = decode_all(&originals); + let (b, _) = decode_all(&zeros); + let (c, _) = decode_all(&ones); 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/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