forge
Explore
Log in

Don't you dare go Hollow

U12: ec-truehd drop duplicate atmos_synth/library/refused_au_recovery tests and the bench example; oracle and fixture_exact kept

Browse files at this commit

68c61cbf5913c4de55a496a5ab70efbc529b2541Ahmet Kaan GümüşParent: 72cc7d1
crates/ec-truehd/examples/bench.rsdeleted+0 -64
@@ -1,64 +0,0 @@
1-//! bench: TrueHD decode throughput for lanes/bench.md ("lane benchaudio").
2-//!
3-//! usage: bench dec <in.thd> <out.s32le> [reps]
4-//!
5-//! Splits a raw TrueHD elementary stream (as ffmpeg's `truehd` muxer writes it) into access
6-//! units with `frame_length`, decodes each with `TrueHdDecoder`, `reps` times (default 5), and
7-//! keeps the best wall time. The decoded interleaved S32 samples of the last run are written to
8-//! `out.s32le`. The lossless self-checks (`check_stats`) are printed; any failure count other
9-//! than zero means the decode is not trustworthy.
10-use std::hint::black_box;
11-use std::time::Instant;
12-
13-use ec_truehd::{TrueHdDecoder, frame_length};
14-
15-/// Decode the whole stream once: (S32 bytes, channels, rate, access units, lossless failures).
16-fn decode_once(data: &[u8]) -> (Vec<u8>, usize, u32, usize, u64) {
17- let mut decoder = TrueHdDecoder::new();
18- let mut out = Vec::new();
19- let (mut channels, mut rate, mut units) = (0usize, 0u32, 0usize);
20- let mut at = 0usize;
21- while at < data.len() {
22- let len = match frame_length(&data[at..]) {
23- Ok(len) if len > 0 => len.min(data.len() - at),
24- _ => break,
25- };
26- if let Some(frame) = decoder
27- .decode_access_unit(&data[at..at + len])
28- .expect("truehd access unit")
29- {
30- channels = frame.layout.channel_count();
31- rate = frame.rate;
32- out.extend_from_slice(&frame.data[0]);
33- }
34- units += 1;
35- at += len;
36- }
37- let stats = decoder.check_stats();
38- let failures = stats.lossless_check_failures + stats.parity_failures + stats.restart_crc_failures;
39- (out, channels, rate, units, failures)
40-}
41-
42-fn main() {
43- let args: Vec<String> = std::env::args().collect();
44- if args.len() < 4 || args[1] != "dec" {
45- eprintln!("usage: bench dec <in.thd> <out.s32le> [reps]");
46- std::process::exit(2);
47- }
48- let reps: usize = args.get(4).map_or(5, |s| s.parse().expect("reps"));
49- let data = std::fs::read(&args[2]).expect("read input");
50- let (pcm, channels, rate, units, failures) = decode_once(&data);
51- let mut best = f64::MAX;
52- for _ in 0..reps {
53- let t = Instant::now();
54- black_box(decode_once(black_box(&data)).0.len());
55- best = best.min(t.elapsed().as_secs_f64());
56- }
57- std::fs::write(&args[3], &pcm).expect("write output");
58- let samples = pcm.len() / 4;
59- println!(
60- "access_units={units} channels={channels} rate={rate} samples={} check_failures={failures} best_decode_s={best:.4} reps={reps} audio_s={:.3}",
61- samples / channels.max(1),
62- samples as f64 / channels.max(1) as f64 / f64::from(rate.max(1))
63- );
64-}
crates/ec-truehd/tests/it/atmos_synth.rsdeleted+0 -227
@@ -1,227 +0,0 @@
1-use std::path::Path;
2-
3-use ec_core::frame::ChannelLayout;
4-use ec_truehd::TrueHdDecoder;
5-use ec_truehd::sync::AccessUnitHeader;
6-
7-use crate::common::raw_access_units;
8-
9-const MIN_ACCESS_UNITS: usize = 100;
10-const FILLER_WORDS: u16 = 4;
11-const MAX_AU_WORDS: usize = 0x0FFF;
12-
13-fn sample_access_units() -> Vec<Vec<u8>> {
14- let data =
15- std::fs::read(ec_testkit::fixture("open/fate/truehd/atmos.thd")).expect("read atmos.thd");
16- let aus = raw_access_units(&data);
17- assert!(
18- aus.len() >= MIN_ACCESS_UNITS,
19- "atmos.thd has only {} access units",
20- aus.len()
21- );
22- aus
23-}
24-
25-fn header_of(au: &[u8], substreams: usize) -> AccessUnitHeader {
26- AccessUnitHeader::parse(au, substreams).expect("access unit parses")
27-}
28-
29-fn crc16_table() -> [u32; 256] {
30- let mut table = [0u32; 256];
31- for (i, entry) in table.iter_mut().enumerate() {
32- let mut c = (i as i32) << 24;
33- for _ in 0..8 {
34- let overflow = c >> 31;
35- c = (c << 1) ^ ((0x002D_i32 << 16) & overflow);
36- }
37- *entry = (c as u32).swap_bytes();
38- }
39- table
40-}
41-
42-fn major_sync_checksum(sync: &[u8]) -> u16 {
43- let n = sync.len() - 4;
44- let table = crc16_table();
45- let mut crc: u32 = 0;
46- for &b in &sync[..n] {
47- crc = table[usize::from((crc as u8) ^ b)] ^ (crc >> 8);
48- }
49- (crc as u16) ^ u16::from_le_bytes([sync[n], sync[n + 1]])
50-}
51-
52-fn checksum_is_valid(sync: &[u8]) -> bool {
53- let n = sync.len() - 2;
54- major_sync_checksum(sync) == u16::from_le_bytes([sync[n], sync[n + 1]])
55-}
56-
57-fn set_substream_count(sync: &mut [u8], count: u8) {
58- sync[16] = (sync[16] & 0x0F) | (count << 4);
59- let checksum = major_sync_checksum(sync);
60- let n = sync.len() - 2;
61- sync[n..].copy_from_slice(&checksum.to_le_bytes());
62-}
63-
64-fn parity_ok(header: &[u8], directory: &[u8]) -> bool {
65- let p = header.iter().chain(directory).fold(0u8, |a, &b| a ^ b);
66- ((p >> 4) ^ p) & 0xF == 0xF
67-}
68-
69-fn assemble(timing: [u8; 2], sync: Option<&[u8]>, dir: &[u8], coded: &[u8]) -> Vec<u8> {
70- let mut body = Vec::new();
71- body.extend_from_slice(sync.unwrap_or(&[]));
72- body.extend_from_slice(dir);
73- body.extend_from_slice(coded);
74- let words = (4 + body.len()) / 2;
75- assert!(words <= MAX_AU_WORDS, "synthetic access unit too long");
76- let nibble = (0u8..16)
77- .find(|&cn| {
78- let head = [
79- (cn << 4) | ((words >> 8) as u8 & 0x0F),
80- (words & 0xFF) as u8,
81- timing[0],
82- timing[1],
83- ];
84- parity_ok(&head, dir)
85- })
86- .expect("one of the 16 nibble values satisfies the fold");
87- let word = (u16::from(nibble) << 12) | words as u16;
88- let mut out = Vec::with_capacity(4 + body.len());
89- out.extend_from_slice(&word.to_be_bytes());
90- out.extend_from_slice(&timing);
91- out.extend_from_slice(&body);
92- out
93-}
94-
95-fn sync_of(au: &[u8], header: &AccessUnitHeader) -> Option<Vec<u8>> {
96- header.major_sync.map(|s| au[4..4 + s.len].to_vec())
97-}
98-
99-fn directory_start(header: &AccessUnitHeader) -> usize {
100- 4 + header.major_sync.map_or(0, |s| s.len)
101-}
102-
103-fn convert(aus: &[Vec<u8>], f: impl Fn(&[u8], usize) -> Vec<u8>) -> Vec<Vec<u8>> {
104- let mut count = 0;
105- aus.iter()
106- .map(|au| {
107- let out = f(au.as_slice(), count);
108- count = header_of(au.as_slice(), count).substreams.len();
109- out
110- })
111- .collect()
112-}
113-
114-fn strip_object_substream(au: &[u8], substreams: usize) -> Vec<u8> {
115- let header = header_of(au, substreams);
116- assert_eq!(header.substreams.len(), 4, "the sample has 4 substreams");
117- let entry_len = if header.substreams[3].extra.is_some() {
118- 4
119- } else {
120- 2
121- };
122- let dir = &au[directory_start(&header)..header.data_start - entry_len];
123- let mut sync = sync_of(au, &header);
124- if let Some(s) = sync.as_mut() {
125- assert!(checksum_is_valid(s), "the sample's major sync checksum");
126- set_substream_count(s, 3);
127- }
128- let (_, end) = header.substream_span(2);
129- assemble(
130- [au[2], au[3]],
131- sync.as_deref(),
132- dir,
133- &au[header.data_start..end],
134- )
135-}
136-
137-fn with_object_substream(au: &[u8], substreams: usize, filler: u8) -> Vec<u8> {
138- let header = header_of(au, substreams);
139- assert_eq!(header.substreams.len(), 3, "the input is a 7.1 access unit");
140- let last = header.substreams[2];
141- let nonrestart = last.flags & 0x4;
142- let entry = (u16::from(nonrestart) << 12) | (last.end_offset_words + FILLER_WORDS);
143- let mut dir = au[directory_start(&header)..header.data_start].to_vec();
144- dir.extend_from_slice(&entry.to_be_bytes());
145- let mut sync = sync_of(au, &header);
146- if let Some(s) = sync.as_mut() {
147- set_substream_count(s, 4);
148- }
149- let (_, end) = header.substream_span(2);
150- let mut coded = au[header.data_start..end].to_vec();
151- coded.extend(std::iter::repeat_n(filler, usize::from(FILLER_WORDS) * 2));
152- assemble([au[2], au[3]], sync.as_deref(), &dir, &coded)
153-}
154-
155-fn with_object_payload(au: &[u8], substreams: usize, fill: u8) -> Vec<u8> {
156- let header = header_of(au, substreams);
157- assert_eq!(header.substreams.len(), 4, "the sample has 4 substreams");
158- let (start, end) = header.substream_span(3);
159- assert!(start < end, "the object substream has coded data");
160- let mut out = au.to_vec();
161- out[start..end].fill(fill);
162- out
163-}
164-
165-type Decoded = Vec<(ChannelLayout, Vec<Vec<u8>>)>;
166-
167-fn decode_all(aus: &[Vec<u8>]) -> (Decoded, ec_truehd::CheckStats) {
168- let mut decoder = TrueHdDecoder::new();
169- let mut frames = Vec::new();
170- for au in aus {
171- if let Some(frame) = decoder.push(au).expect("access unit decodes") {
172- let planes = frame.data.iter().map(|b| b.as_ref().to_vec()).collect();
173- frames.push((frame.layout, planes));
174- }
175- }
176- (frames, decoder.check_stats())
177-}
178-
179-#[test]
180-fn synthetic_atmos_decodes_bit_exact_to_the_original_7_1() {
181- let originals = sample_access_units();
182- let sevens = convert(&originals, strip_object_substream);
183- let atmos = convert(&sevens, |au, n| with_object_substream(au, n, 0xA5));
184-
185- if let Some(out) = std::env::var_os("EC_ATMOS_SYNTH_OUT") {
186- let raw: Vec<u8> = atmos.iter().flatten().copied().collect();
187- std::fs::write(&out, raw).expect("write the synthetic TrueHD stream");
188- eprintln!("wrote synthetic stream to {}", Path::new(&out).display());
189- }
190-
191- let (ours, _) = decode_all(&originals);
192- let (seven, _) = decode_all(&sevens);
193- let (synth, stats) = decode_all(&atmos);
194- assert!(!ours.is_empty(), "the original stream decodes to frames");
195- assert_eq!(seven.len(), ours.len(), "7.1 rebuild: same number of frames");
196- assert!(seven == ours, "the 3-substream 7.1 stream differs from the original");
197- assert_eq!(synth.len(), ours.len(), "synthetic: same number of frames");
198- for (i, ((la, pa), (lb, pb))) in ours.iter().zip(&synth).enumerate() {
199- assert_eq!(*la, ChannelLayout::Surround7_1, "frame {i} is 7.1");
200- assert_eq!(*lb, ChannelLayout::Surround7_1, "frame {i} is 7.1");
201- assert_eq!(pa, pb, "frame {i} differs from the original");
202- }
203- assert_eq!(stats.parity_failures, 0, "substream parity");
204- assert_eq!(stats.restart_crc_failures, 0, "restart header CRC");
205- assert_eq!(stats.lossless_check_failures, 0, "lossless check");
206- assert_eq!(stats.length_mismatches, 0, "substream lengths");
207-}
208-
209-#[test]
210-fn object_substream_contents_do_not_change_the_pcm_output() {
211- let originals = sample_access_units();
212- let zeros = convert(&originals, |au, n| with_object_payload(au, n, 0x00));
213- let ones = convert(&originals, |au, n| with_object_payload(au, n, 0xFF));
214- assert_ne!(zeros, originals, "the object payload was replaced");
215- let (a, sa) = decode_all(&originals);
216- let (b, sb) = decode_all(&zeros);
217- let (c, sc) = decode_all(&ones);
218- for s in [sa, sb, sc] {
219- assert_eq!(s.parity_failures, 0, "substream parity");
220- assert_eq!(s.restart_crc_failures, 0, "restart header CRC");
221- assert_eq!(s.lossless_check_failures, 0, "lossless check");
222- assert_eq!(s.length_mismatches, 0, "substream lengths");
223- }
224- assert!(!a.is_empty());
225- assert!(a == b, "object payload of zeros changes the PCM");
226- assert!(a == c, "object payload of ones changes the PCM");
227-}
crates/ec-truehd/tests/it/library.rsdeleted+0 -29
@@ -1,29 +0,0 @@
1-use crate::common::raw_access_units;
2-
3-#[test]
4-fn walks_every_truehd_access_unit_of_atmos() {
5- let path = ec_testkit::fixture("open/fate/truehd/atmos.thd");
6- let data = std::fs::read(&path).expect("read atmos.thd");
7- let aus = raw_access_units(&data);
8- assert!(!aus.is_empty(), "found no TrueHD access units at all");
9- let out = ec_testkit::ffprobe()
10- .args([
11- "-v",
12- "error",
13- "-select_streams",
14- "a:0",
15- "-count_packets",
16- "-show_entries",
17- "stream=nb_read_packets",
18- "-of",
19- "csv=p=0",
20- ])
21- .arg(&path)
22- .output()
23- .expect("run ffprobe");
24- let expected: usize = String::from_utf8_lossy(&out.stdout)
25- .trim()
26- .parse()
27- .expect("ffprobe packet count");
28- assert_eq!(aus.len(), expected, "AU count vs ffprobe's packet count");
29-}
crates/ec-truehd/tests/it/main.rsmodified+0 -3
@@ -1,10 +1,7 @@
1 //! One integration-test binary for ec-truehd; each module is one former `tests/*.rs` file.1 //! One integration-test binary for ec-truehd; each module is one former `tests/*.rs` file.
2 #![forbid(unsafe_code)]2 #![forbid(unsafe_code)]
3 3
4-mod atmos_synth;
5 mod common;4 mod common;
6 mod fixture_exact;5 mod fixture_exact;
7 mod fuzz_regressions;6 mod fuzz_regressions;
8-mod library;
9 mod oracle;7 mod oracle;
10-mod refused_au_recovery;
crates/ec-truehd/tests/it/refused_au_recovery.rsdeleted+0 -136
@@ -1,136 +0,0 @@
1-//! A refused access unit must not poison the access units after it.
2-//!
3-//! The oracle is the same stream with the corrupt access unit removed. A refused unit is
4-//! defined to leave no trace: every later unit must decode exactly as it would have if the
5-//! refused unit had never been sent. This is checked for every single-byte corruption of one
6-//! access unit in the middle of each committed fixture that the decoder refuses.
7-//!
8-//! Each fixture is read from `crates/ec-truehd/fixtures/` (made with ffmpeg's encoder, see
9-//! `fixture_exact.rs`). Nothing here needs ffmpeg at run time.
10-
11-use std::fs::File;
12-use std::io::BufReader;
13-use std::path::{Path, PathBuf};
14-
15-use ec_core::{CodecId, Demuxer};
16-use ec_matroska::MatroskaDemuxer;
17-use ec_truehd::TrueHdDecoder;
18-
19-/// One access unit's outcome: `Ok(frame bytes)` (or `None` when no frame yet) or a refusal.
20-type Outcome = Result<Option<Vec<u8>>, String>;
21-
22-const FIXTURES: [&str; 4] = [
23- "truehd-s16-2ch.mkv",
24- "truehd-s16-51.mkv",
25- "truehd-s24-2ch.mkv",
26- "truehd-s24-51.mkv",
27-];
28-
29-fn fixture(name: &str) -> PathBuf {
30- Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures").join(name)
31-}
32-
33-/// Every access unit of the file's TrueHD track, in stream order.
34-fn access_units(path: &Path) -> Vec<Vec<u8>> {
35- let mut demux = MatroskaDemuxer::new(BufReader::new(File::open(path).unwrap())).unwrap();
36- let stream = demux
37- .streams()
38- .iter()
39- .find(|s| s.params.codec == CodecId::TrueHd)
40- .expect("a TrueHD track")
41- .index;
42- let mut aus = Vec::new();
43- loop {
44- let packet = match demux.next_packet() {
45- Ok(p) => p,
46- Err(e) if e.is_eof() => break,
47- Err(e) => panic!("{}: demux: {e}", path.display()),
48- };
49- if packet.stream == stream {
50- aus.push(packet.data.to_vec());
51- }
52- }
53- aus
54-}
55-
56-/// Decodes `aus` in order through one decoder, recording each unit's outcome.
57-fn run(aus: &[Vec<u8>]) -> Vec<Outcome> {
58- let mut dec = TrueHdDecoder::new();
59- aus.iter()
60- .map(|au| match dec.decode_access_unit(au) {
61- Ok(frame) => Ok(frame.map(|f| f.data[0].to_vec())),
62- Err(e) => Err(e.to_string()),
63- })
64- .collect()
65-}
66-
67-#[test]
68-fn refused_access_unit_does_not_poison_later_units() {
69- let mut total_refusals = 0;
70- let mut total_checked = 0;
71- let mut failures = Vec::new();
72-
73- for name in FIXTURES {
74- let clean = access_units(&fixture(name));
75- assert!(clean.len() > 40, "{name}: too few access units ({})", clean.len());
76-
77- let clean_run = run(&clean);
78- assert!(
79- clean_run.iter().all(Result::is_ok),
80- "{name}: the clean stream must decode without refusals"
81- );
82- let frames = clean_run.iter().filter(|o| matches!(o, Ok(Some(_)))).count();
83- assert!(frames > 20, "{name}: only {frames} frames decoded");
84-
85- // One unit in the middle of the stream, after the first major sync and several restarts.
86- let k = clean.len() / 3;
87- let without_k: Vec<Vec<u8>> = clean
88- .iter()
89- .enumerate()
90- .filter(|(i, _)| *i != k)
91- .map(|(_, au)| au.clone())
92- .collect();
93- let oracle = run(&without_k);
94-
95- for pos in 0..clean[k].len() {
96- let mut corrupt = clean[k].clone();
97- corrupt[pos] ^= 0xFF;
98-
99- // Only units the decoder refuses matter here. Check that cheaply on the prefix.
100- let mut prefix: Vec<Vec<u8>> = clean[..k].to_vec();
101- prefix.push(corrupt.clone());
102- let Err(err) = run(&prefix).pop().expect("prefix is non-empty") else {
103- continue;
104- };
105- total_refusals += 1;
106-
107- let mut stream = clean.clone();
108- stream[k] = corrupt;
109- let got = run(&stream);
110- assert!(got[k].is_err(), "{name} byte {pos}: the corrupt unit must be refused");
111-
112- for j in k + 1..clean.len() {
113- total_checked += 1;
114- if got[j] != oracle[j - 1] {
115- failures.push(format!(
116- "{name}: byte {pos} of unit {k} refused ({err}); unit {j} differs from the \
117- stream without unit {k}: got {:?}, want {:?}",
118- got[j].as_ref().map(|o| o.as_ref().map(Vec::len)),
119- oracle[j - 1].as_ref().map(|o| o.as_ref().map(Vec::len)),
120- ));
121- break;
122- }
123- }
124- }
125- }
126-
127- assert!(total_refusals >= 10, "only {total_refusals} refused corruptions found");
128- assert!(
129- failures.is_empty(),
130- "{} of {} refused corruptions poisoned later units; first: {}",
131- failures.len(),
132- total_refusals,
133- failures[0]
134- );
135- eprintln!("refused corruptions: {total_refusals}, later units compared: {total_checked}");
136-}