forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

fixture_exact.rs217 lines, 7.7 KiBHistoryRawDownload
1//! Sample-for-sample equality with ffmpeg's TrueHD decoder on the committed
2//! fixtures in `crates/ec-truehd/fixtures/`.
3//!
4//! The committed fixtures are made with ffmpeg's own TrueHD encoder
5//! (`-c:a truehd -strict -2`): 2.0 and 5.1 at 16-bit (s16p input) and 24-bit
6//! (s32p input), 48 kHz. The file name carries the channel count: `2ch` or `51`.
7//!
8//! The 8-channel (7.1) case is not committed: ffmpeg's encoder refuses 7.1, and
9//! the only real 7.1 TrueHD source is a copyrighted remux. It is tested by
10//! [`remux_71_is_bit_exact_against_ffmpeg`], which reads the remux from its
11//! local path (env `EC_TRUEHD_71_REMUX`, or the `truehd_71_remux` key of
12//! `real_library.toml`) and skips loudly when it is absent.
13//!
14//! Each file is decoded here and by ffmpeg (`-f s32le`), and every sample must
15//! be equal. Lossless decoding has no tolerance. ffmpeg is test tooling and is
16//! driven through `std::process`; without it the test skips loudly.
17
18use std::fs::File;
19use std::io::BufReader;
20use std::path::{Path, PathBuf};
21use std::process::Command;
22
23use ec_core::{CodecId, Demuxer};
24use ec_matroska::MatroskaDemuxer;
25use ec_truehd::TrueHdDecoder;
26use crate::common::have_ffmpeg;
27
28fn fixtures() -> PathBuf {
29 Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures")
30}
31
32fn s32le(bytes: &[u8]) -> Vec<i32> {
33 bytes
34 .as_chunks::<4>()
35 .0
36 .iter()
37 .map(|c| i32::from_le_bytes(*c))
38 .collect()
39}
40
41/// Channel count from the file name: `2ch` or `51`.
42fn expected_channels(name: &str) -> usize {
43 if name.contains("2ch") {
44 2
45 } else if name.contains("51") {
46 6
47 } else {
48 panic!("fixture {name}: no channel count in the name")
49 }
50}
51
52/// Decodes every access unit of the file's TrueHD track: (stream index,
53/// interleaved S32 samples, channels, sample rate).
54fn decode_ours(path: &Path) -> (u32, Vec<i32>, usize, u32) {
55 let mut demux = MatroskaDemuxer::new(BufReader::new(File::open(path).unwrap())).unwrap();
56 let stream = demux
57 .streams()
58 .iter()
59 .find(|s| s.params.codec == CodecId::TrueHd)
60 .expect("a TrueHD track")
61 .index;
62 let mut decoder = TrueHdDecoder::new();
63 let mut samples = Vec::new();
64 let mut channels = 0;
65 let mut rate = 0;
66 loop {
67 let packet = match demux.next_packet() {
68 Ok(p) => p,
69 Err(e) if e.is_eof() => break,
70 Err(e) => panic!("{}: demux: {e}", path.display()),
71 };
72 if packet.stream != stream {
73 continue;
74 }
75 let frame = decoder
76 .decode_access_unit(&packet.data)
77 .unwrap_or_else(|e| panic!("{}: {e}", path.display()));
78 if let Some(f) = frame {
79 channels = f.channels();
80 rate = f.rate;
81 samples.extend(s32le(&f.data[0]));
82 }
83 }
84 let stats = decoder.check_stats();
85 assert_eq!(stats.lossless_check_failures, 0, "{}: {stats:?}", path.display());
86 assert_eq!(stats.parity_failures, 0, "{}: {stats:?}", path.display());
87 assert_eq!(stats.restart_crc_failures, 0, "{}: {stats:?}", path.display());
88 assert_eq!(stats.length_mismatches, 0, "{}: {stats:?}", path.display());
89 (stream, samples, channels, rate)
90}
91
92/// ffmpeg's decode of track `stream` as interleaved S32 little-endian.
93fn decode_ffmpeg(path: &Path, stream: u32) -> Vec<i32> {
94 let out = Command::new("ffmpeg")
95 .args(["-v", "error", "-nostdin", "-i"])
96 .arg(path)
97 .args(["-map", &format!("0:{stream}"), "-f", "s32le", "-"])
98 .output()
99 .expect("run ffmpeg");
100 assert!(
101 out.status.success(),
102 "ffmpeg {}: {}",
103 path.display(),
104 String::from_utf8_lossy(&out.stderr)
105 );
106 s32le(&out.stdout)
107}
108
109#[test]
110fn fixtures_are_bit_exact_against_ffmpeg() {
111 let dir = fixtures();
112 if !have_ffmpeg() {
113 eprintln!("skip: ffmpeg not on PATH");
114 return;
115 }
116 let mut paths: Vec<PathBuf> = std::fs::read_dir(&dir)
117 .expect("fixtures dir")
118 .flatten()
119 .map(|e| e.path())
120 .filter(|p| p.extension().is_some_and(|x| x == "mkv"))
121 .collect();
122 paths.sort();
123 assert!(!paths.is_empty(), "no TrueHD fixtures in {}", dir.display());
124
125 for path in &paths {
126 let name = path.file_name().unwrap().to_string_lossy().into_owned();
127 let want_channels = expected_channels(&name);
128 let (stream, ours, channels, rate) = decode_ours(path);
129 let reference = decode_ffmpeg(path, stream);
130
131 assert_eq!(channels, want_channels, "{name}: channels");
132 assert_eq!(rate, 48_000, "{name}: rate");
133 assert!(!ours.is_empty(), "{name}: no samples decoded");
134 assert_eq!(
135 ours.len(),
136 reference.len(),
137 "{name}: sample count vs ffmpeg"
138 );
139 let mismatch = ours.iter().zip(&reference).position(|(a, b)| a != b);
140 assert_eq!(
141 mismatch, None,
142 "{name}: first mismatch at sample {mismatch:?} (channel {:?})",
143 mismatch.map(|i| i % channels)
144 );
145 eprintln!(
146 "{name}: {channels} ch, {} frames, {} samples, bit-exact",
147 ours.len() / channels,
148 ours.len()
149 );
150 }
151}
152
153/// The local 7.1 remux: env `EC_TRUEHD_71_REMUX`, else the `truehd_71_remux`
154/// key of `real_library.toml` (env `EC_REAL_LIBRARY`, default under
155/// `~/Documents/Code/Rust/edith`).
156fn remux_path() -> Option<PathBuf> {
157 if let Ok(p) = std::env::var("EC_TRUEHD_71_REMUX") {
158 return Some(PathBuf::from(p));
159 }
160 let toml = std::env::var("EC_REAL_LIBRARY").map(PathBuf::from).unwrap_or_else(|_| {
161 let home = std::env::var("HOME").unwrap_or_default();
162 PathBuf::from(home).join("Documents/Code/Rust/edith/real_library.toml")
163 });
164 let text = std::fs::read_to_string(toml).ok()?;
165 text.lines().find_map(|line| {
166 let (key, value) = line.trim().split_once('=')?;
167 if key.trim() != "truehd_71_remux" {
168 return None;
169 }
170 Some(PathBuf::from(value.trim().strip_prefix('"')?.strip_suffix('"')?))
171 })
172}
173
174/// The first 2 s of a real 7.1 TrueHD remux, decoded from the start of the
175/// file and compared sample-for-sample with ffmpeg's decode of the same span.
176#[test]
177fn remux_71_is_bit_exact_against_ffmpeg() {
178 let Some(path) = remux_path() else {
179 eprintln!("skip: no 7.1 remux (set EC_TRUEHD_71_REMUX or truehd_71_remux in real_library.toml)");
180 return;
181 };
182 if !path.exists() {
183 eprintln!("skip: 7.1 remux {} not on disk", path.display());
184 return;
185 }
186 if !have_ffmpeg() {
187 eprintln!("skip: ffmpeg not on PATH");
188 return;
189 }
190 const SECONDS: usize = 2;
191 let (stream, ours, channels, rate) = decode_ours(&path);
192 assert_eq!(channels, 8, "remux channels");
193 assert_eq!(rate, 48_000, "remux rate");
194 let want = SECONDS * 48_000 * channels;
195 assert!(ours.len() >= want, "only {} samples decoded", ours.len());
196 let ours = &ours[..want];
197
198 let out = Command::new("ffmpeg")
199 .args(["-v", "error", "-nostdin", "-i"])
200 .arg(&path)
201 .args(["-map", &format!("0:{stream}"), "-t", &SECONDS.to_string(), "-f", "s32le", "-"])
202 .output()
203 .expect("run ffmpeg");
204 assert!(out.status.success(), "ffmpeg: {}", String::from_utf8_lossy(&out.stderr));
205 let reference = s32le(&out.stdout);
206 assert!(reference.len() >= want, "ffmpeg gave {} samples", reference.len());
207 let reference = &reference[..want];
208
209 let mismatch = ours.iter().zip(reference).position(|(a, b)| a != b);
210 assert_eq!(
211 mismatch,
212 None,
213 "first mismatch at sample {mismatch:?} (channel {:?})",
214 mismatch.map(|i| i % channels)
215 );
216 eprintln!("7.1 remux: {channels} ch, {SECONDS} s, {want} samples, bit-exact");
217}