forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

real_library.rs417 lines, 14.1 KiBHistoryRawDownload
1//! The personal media library, Ogg half: every `ogg` row of
2//! `fixtures/real-library-manifest.tsv` whose audio is Vorbis or Opus is read
3//! by [`OggDemuxer`] end to end and compared with ffmpeg/ffprobe.
4//!
5//! Per file the oracle checks:
6//! - packet count and every packet's size (ffprobe, audio stream 0);
7//! - the concatenated packet payloads (ffmpeg `-c copy -f data`), byte for byte;
8//! - the header block: Opus's `OpusHead` against ffprobe's `extradata_size`
9//! exactly; Vorbis's three Xiph-laced packets by their lacing and magic (see
10//! below for why the size is not compared);
11//! - timing: where a packet carries a pts, it equals ffprobe's pts after the
12//! Opus pre-skip shift; where a page ends on a packet, the granule position
13//! equals that packet's ffprobe end (pts + duration) after the same shift.
14//!
15//! Timing rule, as ffmpeg's Ogg demuxer applies it (measured on these files):
16//! - Vorbis: granule = the sample position at the packet's end, at the stream
17//! rate; ffmpeg's pts = granule - duration. No shift. The first packet is the
18//! one exception: ffmpeg starts it at minus its own length, while ec-ogg, by
19//! its documented convention, starts the stream at zero and states no
20//! duration for a Vorbis packet. Its pts is therefore not compared; its
21//! granule still is.
22//! - Opus: granule counts 48 kHz samples *including* the pre-skip; ffmpeg's pts
23//! = granule - pre_skip - duration, so the end is `granule - pre_skip`. Our
24//! packet pts start at zero, so ours = ffmpeg's pts + pre_skip.
25//!
26//! Header block: ffmpeg's stated Vorbis extradata size differs from ours on
27//! some files (ours keeps the comment header verbatim, which the remux path
28//! relies on for bit-identical output). ffprobe does not expose the extradata
29//! bytes, so the Vorbis block is checked structurally and the size difference
30//! is reported, not failed.
31//!
32//! Scope: demux only. The decoded PCM is not compared here.
33//!
34//! Each file either matches, is refused by name (no logical stream with a
35//! known mapping), or fails. A refusal is reported, not counted as a failure.
36//!
37//! LOCAL ONLY and ignored: the manifest is generated from the user's own media
38//! by `scripts/scan-real-library.sh` and is gitignored, so no other host has it.
39//! cargo test -p ec-ogg --test real_library -- --ignored --nocapture
40
41use std::path::{Path, PathBuf};
42use std::process::{Command, Stdio};
43
44use ec_core::Demuxer;
45use ec_ogg::{Mapping, OggDemuxer, granule_of};
46
47/// One manifest row: the columns the sweep reads.
48struct Entry {
49 path: PathBuf,
50 acodecs: String,
51}
52
53/// One packet as ffprobe reports it.
54struct Probed {
55 pts: Option<i64>,
56 duration: Option<i64>,
57 size: usize,
58}
59
60/// The verdict for one file, with the text the table prints.
61enum Verdict {
62 Match(String),
63 Refused(String),
64 Failed(String),
65}
66
67fn have(tool: &str) -> bool {
68 Command::new(tool)
69 .arg("-version")
70 .stdout(Stdio::null())
71 .stderr(Stdio::null())
72 .status()
73 .is_ok_and(|s| s.success())
74}
75
76/// The manifest's Ogg rows with Vorbis or Opus audio, or `None` when the
77/// manifest itself is absent.
78fn manifest_ogg_entries() -> Option<Vec<Entry>> {
79 let manifest =
80 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/real-library-manifest.tsv");
81 let text = std::fs::read_to_string(&manifest).ok()?;
82 let mut out = Vec::new();
83 for line in text.lines().skip(1) {
84 let f: Vec<&str> = line.split('\t').collect();
85 if f.len() < 8 || f[1] != "ogg" || !Path::new(f[0]).is_file() {
86 continue;
87 }
88 // The first audio stream decides the mapping this file is checked as.
89 let first = f[7].split(',').next().unwrap_or_default();
90 if first != "vorbis" && first != "opus" {
91 continue;
92 }
93 out.push(Entry {
94 path: PathBuf::from(f[0]),
95 acodecs: f[7].to_string(),
96 });
97 }
98 Some(out)
99}
100
101/// Parses an ffprobe csv cell: `N/A` and blanks are absent.
102fn cell(s: &str) -> Option<i64> {
103 let s = s.trim();
104 if s.is_empty() || s == "N/A" {
105 None
106 } else {
107 s.parse().ok()
108 }
109}
110
111/// Audio stream 0's packets: header packets are not among them, as with ours.
112fn ffprobe_packets(path: &Path) -> Result<Vec<Probed>, String> {
113 let out = Command::new("ffprobe")
114 .args([
115 "-v",
116 "error",
117 "-select_streams",
118 "a:0",
119 "-show_entries",
120 "packet=pts,duration,size",
121 "-of",
122 "csv=p=0",
123 ])
124 .arg(path)
125 .output()
126 .map_err(|e| format!("ffprobe: {e}"))?;
127 if !out.status.success() {
128 return Err("ffprobe failed on the packets".into());
129 }
130 let mut packets = Vec::new();
131 for line in String::from_utf8_lossy(&out.stdout).lines() {
132 let f: Vec<&str> = line.split(',').collect();
133 if f.len() < 3 {
134 return Err(format!("unexpected ffprobe packet row: {line}"));
135 }
136 let size = cell(f[2]).ok_or_else(|| format!("no packet size in: {line}"))?;
137 packets.push(Probed {
138 pts: cell(f[0]),
139 duration: cell(f[1]),
140 size: size as usize,
141 });
142 }
143 Ok(packets)
144}
145
146/// ffprobe's stated extradata size for audio stream 0.
147fn ffprobe_extradata_size(path: &Path) -> Result<usize, String> {
148 let out = Command::new("ffprobe")
149 .args([
150 "-v",
151 "error",
152 "-select_streams",
153 "a:0",
154 "-show_entries",
155 "stream=extradata_size",
156 "-of",
157 "csv=p=0",
158 ])
159 .arg(path)
160 .output()
161 .map_err(|e| format!("ffprobe: {e}"))?;
162 let text = String::from_utf8_lossy(&out.stdout);
163 let first = text.lines().next().unwrap_or_default().trim_matches(',');
164 cell(first)
165 .map(|n| n as usize)
166 .ok_or_else(|| format!("no extradata_size: {text:?}"))
167}
168
169/// ffmpeg's concatenated audio packet payloads, copied and not decoded.
170fn ffmpeg_payload(path: &Path) -> Result<Vec<u8>, String> {
171 let out = Command::new("ffmpeg")
172 .args(["-v", "error", "-i"])
173 .arg(path)
174 .args(["-map", "0:a:0", "-c", "copy", "-f", "data", "-"])
175 .output()
176 .map_err(|e| format!("ffmpeg: {e}"))?;
177 if !out.status.success() {
178 return Err(format!(
179 "ffmpeg failed to copy the packets: {}",
180 String::from_utf8_lossy(&out.stderr).trim()
181 ));
182 }
183 Ok(out.stdout)
184}
185
186/// Reads one file with ec-ogg and compares it with the oracle.
187fn check_file(path: &Path) -> Verdict {
188 let file = match std::fs::File::open(path) {
189 Ok(f) => f,
190 Err(e) => return Verdict::Failed(format!("open: {e}")),
191 };
192 let mut demuxer = match OggDemuxer::open(file) {
193 Ok(d) => d,
194 Err(e) => {
195 let text = e.to_string();
196 if text.contains("no logical stream with a known mapping") {
197 return Verdict::Refused(text);
198 }
199 return Verdict::Failed(format!("open: {text}"));
200 }
201 };
202 let Some(mapping) = demuxer.mapping(0) else {
203 return Verdict::Refused("no audio stream with a known mapping".into());
204 };
205 let pre_skip = match mapping {
206 Mapping::Opus { pre_skip, .. } => i64::from(pre_skip),
207 _ => 0,
208 };
209 let streams = demuxer.streams().to_vec();
210 let block: &[u8] = streams[0].params.extradata.as_ref().map_or(&[], |b| &b[..]);
211 let vorbis = matches!(mapping, Mapping::Vorbis { .. });
212
213 let mut ours = Vec::new();
214 loop {
215 match demuxer.next_packet() {
216 Ok(p) if p.stream == 0 => ours.push(p),
217 Ok(_) => {}
218 Err(e) if e.is_eof() => break,
219 Err(e) => return Verdict::Failed(format!("demux: {e}")),
220 }
221 }
222 if demuxer.damaged_pages() != 0 {
223 return Verdict::Failed(format!("{} damaged pages", demuxer.damaged_pages()));
224 }
225
226 let probed = match ffprobe_packets(path) {
227 Ok(p) => p,
228 Err(e) => return Verdict::Failed(e),
229 };
230 let payload = match ffmpeg_payload(path) {
231 Ok(p) => p,
232 Err(e) => return Verdict::Failed(e),
233 };
234 let header_len = match ffprobe_extradata_size(path) {
235 Ok(n) => n,
236 Err(e) => return Verdict::Failed(e),
237 };
238
239 let mut problems: Vec<String> = Vec::new();
240 if ours.len() != probed.len() {
241 problems.push(format!(
242 "packet count {} (ffprobe {})",
243 ours.len(),
244 probed.len()
245 ));
246 }
247 let size_bad = ours
248 .iter()
249 .zip(&probed)
250 .filter(|(p, q)| p.data.len() != q.size)
251 .count();
252 if size_bad > 0 {
253 problems.push(format!("{size_bad} packet sizes differ"));
254 }
255 let ours_payload: Vec<u8> = ours.iter().flat_map(|p| p.data.iter().copied()).collect();
256 if ours_payload != payload {
257 let at = ours_payload
258 .iter()
259 .zip(&payload)
260 .position(|(a, b)| a != b)
261 .unwrap_or(ours_payload.len().min(payload.len()));
262 problems.push(format!(
263 "payload differs: {} bytes vs ffmpeg {}, first difference at byte {at}",
264 ours_payload.len(),
265 payload.len()
266 ));
267 }
268 if vorbis {
269 if let Some(p) = vorbis_header_problem(block) {
270 problems.push(p);
271 }
272 } else if block.len() != header_len {
273 problems.push(format!(
274 "header block {} bytes (ffprobe extradata {header_len})",
275 block.len()
276 ));
277 }
278
279 // Timing, checked on the pairs both sides state.
280 let mut pts_checked = 0usize;
281 let mut pts_bad = 0usize;
282 let mut granule_checked = 0usize;
283 let mut granule_bad = 0usize;
284 let mut first_timing: Option<String> = None;
285 for (i, (p, q)) in ours.iter().zip(&probed).enumerate() {
286 // The Vorbis first packet's start is the convention exception (see the
287 // module doc): not compared.
288 if let Some(pts) = p.pts.filter(|_| i > 0 || !vorbis) {
289 pts_checked += 1;
290 if q.pts.map(|f| f + pre_skip) != Some(pts) {
291 pts_bad += 1;
292 first_timing.get_or_insert(format!(
293 "packet {i}: pts {pts}, ffmpeg pts {:?} (+{pre_skip})",
294 q.pts
295 ));
296 }
297 }
298 if let Some(g) = granule_of(p) {
299 granule_checked += 1;
300 let end = q.pts.zip(q.duration).map(|(a, b)| a + b);
301 if end != Some(g - pre_skip) {
302 granule_bad += 1;
303 first_timing.get_or_insert(format!(
304 "packet {i}: granule {g}, ffmpeg end {end:?} (-{pre_skip})"
305 ));
306 }
307 }
308 }
309 if pts_bad > 0 {
310 problems.push(format!("{pts_bad} of {pts_checked} pts differ"));
311 }
312 if granule_bad > 0 {
313 problems.push(format!(
314 "{granule_bad} of {granule_checked} granule ends differ"
315 ));
316 }
317 if let Some(t) = first_timing {
318 problems.push(format!("first timing difference: {t}"));
319 }
320
321 let summary = format!(
322 "{} packets, {} bytes, {} pts and {} granules checked",
323 ours.len(),
324 payload.len(),
325 pts_checked,
326 granule_checked
327 );
328 if problems.is_empty() {
329 Verdict::Match(summary)
330 } else {
331 Verdict::Failed(format!("{summary}; {}", problems.join("; ")))
332 }
333}
334
335/// Our Vorbis header block: three Xiph-laced packets, identification,
336/// comment and setup, each carrying its own magic. `None` when it is sound.
337fn vorbis_header_problem(block: &[u8]) -> Option<String> {
338 let Ok(parts) = ec_ogg::xiph_unlace(block) else {
339 return Some("header block is not Xiph-laced".into());
340 };
341 if parts.len() != 3 {
342 return Some(format!("{} header packets, want 3", parts.len()));
343 }
344 for (part, kind) in parts.iter().zip([1u8, 3, 5]) {
345 if part.len() < 7 || part[0] != kind || &part[1..7] != b"vorbis" {
346 return Some(format!("header packet of kind {kind} lacks its magic"));
347 }
348 }
349 if parts[0].len() != 30 {
350 return Some(format!(
351 "identification header is {} bytes, want 30",
352 parts[0].len()
353 ));
354 }
355 None
356}
357
358fn short_name(path: &Path) -> String {
359 path.file_name()
360 .map(|n| n.to_string_lossy().chars().take(38).collect())
361 .unwrap_or_default()
362}
363
364#[test]
365#[ignore = "sweeps the PERSONAL media library (fixtures/real-library-manifest.tsv, ogg rows) through ffmpeg; local only: run with --ignored."]
366fn real_library_ogg_streams_match_ffmpeg() {
367 if !have("ffmpeg") || !have("ffprobe") {
368 eprintln!("skipped: ffmpeg and ffprobe are required to sweep the library");
369 return;
370 }
371 let Some(entries) = manifest_ogg_entries() else {
372 eprintln!(
373 "skipped: no fixtures/real-library-manifest.tsv; generate it with \
374 scripts/scan-real-library.sh on the machine that holds the media"
375 );
376 return;
377 };
378 if entries.is_empty() {
379 eprintln!("skipped: the manifest lists no ogg rows with vorbis or opus audio");
380 return;
381 }
382
383 let mut table = String::new();
384 let mut checked = 0usize;
385 let mut refused = 0usize;
386 let mut failures = Vec::new();
387 for entry in &entries {
388 let name = short_name(&entry.path);
389 let codec = entry.acodecs.split(',').next().unwrap_or_default();
390 let verdict = check_file(&entry.path);
391 let line = match verdict {
392 Verdict::Match(s) => {
393 checked += 1;
394 format!("{name:<38} {codec:<7} match: {s}\n")
395 }
396 Verdict::Refused(e) => {
397 refused += 1;
398 format!("{name:<38} {codec:<7} refused: {e}\n")
399 }
400 Verdict::Failed(e) => {
401 failures.push(format!("{name}: {e}"));
402 format!("{name:<38} {codec:<7} FAILED {e}\n")
403 }
404 };
405 table.push_str(&line);
406 }
407 eprintln!("{table}");
408 eprintln!(
409 "real library ogg: {checked} match, {refused} refused by name, {} failed",
410 failures.len()
411 );
412 assert!(failures.is_empty(), "{failures:#?}");
413 assert!(
414 checked + refused >= 1 && checked >= 1,
415 "no real Ogg file was checked end to end"
416 );
417}