forge
Explore
Log in

Don't you dare go Hollow

Fixture migration M8: ec-testkit for ffmpeg and fixtures in image, ASS, subs, PGS, DVD/DVB and CC tests; skips become failures; real-library tests retargeted to open media

Browse files at this commit

9981db71345ba7cc18f854f5b3433beb504bf301Ahmet Kaan GümüşParent: 155ce74
Cargo.lockmodified+6 -0
@@ -364,6 +364,7 @@ version = "0.1.0"
364 dependencies = [364 dependencies = [
365 "ec-core",365 "ec-core",
366 "ec-subs",366 "ec-subs",
367+ "ec-testkit",
367 ]368 ]
368 369
369 [[package]]370 [[package]]
@@ -417,6 +418,7 @@ dependencies = [
417 "ec-h264-syntax",418 "ec-h264-syntax",
418 "ec-h265-syntax",419 "ec-h265-syntax",
419 "ec-subs",420 "ec-subs",
421+ "ec-testkit",
420 ]422 ]
421 423
422 [[package]]424 [[package]]
@@ -464,6 +466,7 @@ dependencies = [
464 "ec-core",466 "ec-core",
465 "ec-matroska",467 "ec-matroska",
466 "ec-mpegts",468 "ec-mpegts",
469+ "ec-testkit",
467 ]470 ]
468 471
469 [[package]]472 [[package]]
@@ -474,6 +477,7 @@ dependencies = [
474 "ec-matroska",477 "ec-matroska",
475 "ec-mp4",478 "ec-mp4",
476 "ec-mpegts",479 "ec-mpegts",
480+ "ec-testkit",
477 ]481 ]
478 482
479 [[package]]483 [[package]]
@@ -542,6 +546,7 @@ version = "0.1.0"
542 dependencies = [546 dependencies = [
543 "ec-core",547 "ec-core",
544 "ec-inflate",548 "ec-inflate",
549+ "ec-testkit",
545 "image 0.25.10 (registry+https://github.com/rust-lang/crates.io-index)",550 "image 0.25.10 (registry+https://github.com/rust-lang/crates.io-index)",
546 "tracking-allocator",551 "tracking-allocator",
547 ]552 ]
@@ -704,6 +709,7 @@ dependencies = [
704 "ec-ass",709 "ec-ass",
705 "ec-core",710 "ec-core",
706 "ec-pgs",711 "ec-pgs",
712+ "ec-testkit",
707 ]713 ]
708 714
709 [[package]]715 [[package]]
crates/ec-ass/Cargo.tomlmodified+3 -0
@@ -9,3 +9,6 @@ authors.workspace = true
9 [dependencies]9 [dependencies]
10 ec-core.workspace = true10 ec-core.workspace = true
11 ec-subs = { path = "../ec-subs", version = "0.1.0" }11 ec-subs = { path = "../ec-subs", version = "0.1.0" }
12+
13+[dev-dependencies]
14+ec-testkit.workspace = true
crates/ec-ass/fuzz/seed.shmodified+4 -4
@@ -1,20 +1,20 @@
1 #!/usr/bin/env bash1 #!/usr/bin/env bash
2 # seed.sh: fill fuzz/corpus/<target>/ from the repo's ASS fixture.2 # seed.sh: fill fuzz/corpus/<target>/ from the repo's ASS fixture.
3 #3 #
4-# fixtures/subs/real.ass seeds script whole. events and overrides get its Dialogue rows (the lines4+# subs/tos-en.ass seeds script whole. events and overrides get its Dialogue rows (the lines
5 # after the first Dialogue: prefix, which is what each of those targets takes as input). styles gets5 # after the first Dialogue: prefix, which is what each of those targets takes as input). styles gets
6 # the Style rows. Corpus lives under fuzz/corpus, git-ignored.6 # the Style rows. Corpus lives under fuzz/corpus, git-ignored.
7 set -euo pipefail7 set -euo pipefail
8 8
9 FUZZ_DIR=$(cd -- "$(dirname -- "$0")" && pwd)9 FUZZ_DIR=$(cd -- "$(dirname -- "$0")" && pwd)
10 ROOT=$(cd -- "$FUZZ_DIR/../../.." && pwd)10 ROOT=$(cd -- "$FUZZ_DIR/../../.." && pwd)
11-SUBS="$ROOT/fixtures/subs"11+SUBS="${EC_FIXTURES:-$ROOT/fixtures}/subs"
12-[ -d "$SUBS" ] || { echo "seed.sh: $SUBS missing; run scripts/link-fixtures.sh" >&2; exit 2; }12+[ -f "$SUBS/tos-en.ass" ] || { echo "seed.sh: $SUBS/tos-en.ass missing; run scripts/fixtures.sh" >&2; exit 2; }
13 13
14 CORPUS="$FUZZ_DIR/corpus"14 CORPUS="$FUZZ_DIR/corpus"
15 mkdir -p "$CORPUS"/{script,styles,events,overrides}15 mkdir -p "$CORPUS"/{script,styles,events,overrides}
16 16
17-python3 -I - "$SUBS/real.ass" "$CORPUS" <<'PY'17+python3 -I - "$SUBS/tos-en.ass" "$CORPUS" <<'PY'
18 import os, sys18 import os, sys
19 19
20 ass, corpus = sys.argv[1], sys.argv[2]20 ass, corpus = sys.argv[1], sys.argv[2]
crates/ec-ass/tests/ffmpeg_parity.rsmodified+2 -25
@@ -9,11 +9,8 @@
9 //! `reordered_format.ass` is not compared with ffmpeg. Its demuxer produces no packets at all for a9 //! `reordered_format.ass` is not compared with ffmpeg. Its demuxer produces no packets at all for a
10 //! script whose Events `Format:` line puts Start before Layer, so there is nothing to compare. Its10 //! script whose Events `Format:` line puts Start before Layer, so there is nothing to compare. Its
11 //! expectations are written out by hand instead.11 //! expectations are written out by hand instead.
12-//!
13-//! The ffmpeg tests skip loudly when `ffmpeg` or `ffprobe` is not on PATH.
14 12
15 use std::path::{Path, PathBuf};13 use std::path::{Path, PathBuf};
16-use std::process::Command;
17 14
18 use ec_ass::parse;15 use ec_ass::parse;
19 use ec_subs::{Segment, SubtitleCue, TextAlign, plain_text};16 use ec_subs::{Segment, SubtitleCue, TextAlign, plain_text};
@@ -40,23 +37,6 @@ fn fixture(name: &str) -> Vec<u8> {
40 std::fs::read(&path).unwrap_or_else(|e| panic!("reading {}: {e}", path.display()))37 std::fs::read(&path).unwrap_or_else(|e| panic!("reading {}: {e}", path.display()))
41 }38 }
42 39
43-fn tool_present(tool: &str) -> bool {
44- Command::new(tool)
45- .arg("-version")
46- .output()
47- .map(|o| o.status.success())
48- .unwrap_or(false)
49-}
50-
51-/// Both reference tools, or `None` (with a loud note) when either is missing.
52-fn ffmpeg_available() -> bool {
53- if tool_present("ffmpeg") && tool_present("ffprobe") {
54- return true;
55- }
56- eprintln!("SKIP: ffmpeg/ffprobe not on PATH; ASS parity with ffmpeg not checked");
57- false
58-}
59-
60 /// Seconds in ffprobe's decimal form to whole milliseconds.40 /// Seconds in ffprobe's decimal form to whole milliseconds.
61 fn ms(seconds: &str) -> i64 {41 fn ms(seconds: &str) -> i64 {
62 (seconds.trim().parse::<f64>().expect("seconds") * 1000.0).round() as i6442 (seconds.trim().parse::<f64>().expect("seconds") * 1000.0).round() as i64
@@ -64,7 +44,7 @@ fn ms(seconds: &str) -> i64 {
64 44
65 /// `(start_ms, end_ms)` per packet, in the order ffprobe lists them.45 /// `(start_ms, end_ms)` per packet, in the order ffprobe lists them.
66 fn ffprobe_spans(path: &Path) -> Vec<(i64, i64)> {46 fn ffprobe_spans(path: &Path) -> Vec<(i64, i64)> {
67- let out = Command::new("ffprobe")47+ let out = ec_testkit::ffprobe()
68 .args([48 .args([
69 "-v",49 "-v",
70 "error",50 "error",
@@ -101,7 +81,7 @@ fn ffprobe_spans(path: &Path) -> Vec<(i64, i64)> {
101 81
102 /// ffmpeg's SRT rendering of the script's cues, words only.82 /// ffmpeg's SRT rendering of the script's cues, words only.
103 fn ffmpeg_srt(path: &Path) -> String {83 fn ffmpeg_srt(path: &Path) -> String {
104- let out = Command::new("ffmpeg")84+ let out = ec_testkit::ffmpeg()
105 .args(["-v", "error", "-nostdin", "-i"])85 .args(["-v", "error", "-nostdin", "-i"])
106 .arg(path)86 .arg(path)
107 .args(["-map", "0:s:0", "-c:s", "text", "-f", "srt", "-"])87 .args(["-map", "0:s:0", "-c:s", "text", "-f", "srt", "-"])
@@ -169,9 +149,6 @@ fn ours_in_ffmpeg_order(cues: &[SubtitleCue]) -> Vec<(i64, i64, String)> {
169 149
170 #[test]150 #[test]
171 fn cues_match_ffmpeg_timing_order_and_text() {151 fn cues_match_ffmpeg_timing_order_and_text() {
172- if !ffmpeg_available() {
173- return;
174- }
175 for name in FFMPEG_FIXTURES {152 for name in FFMPEG_FIXTURES {
176 let path = data_path(name);153 let path = data_path(name);
177 let track = parse(&fixture(name)).unwrap_or_else(|e| panic!("{name}: {e}"));154 let track = parse(&fixture(name)).unwrap_or_else(|e| panic!("{name}: {e}"));
crates/ec-cc/Cargo.tomlmodified+3 -0
@@ -11,3 +11,6 @@ ec-core.workspace = true
11 ec-subs = { path = "../ec-subs", version = "0.1.0" }11 ec-subs = { path = "../ec-subs", version = "0.1.0" }
12 ec-h264-syntax.workspace = true12 ec-h264-syntax.workspace = true
13 ec-h265-syntax.workspace = true13 ec-h265-syntax.workspace = true
14+
15+[dev-dependencies]
16+ec-testkit.workspace = true
crates/ec-cc/tests/streams.rsmodified+20 -59
@@ -1,35 +1,15 @@
1 //! End-to-end: synthetic captions spliced into ffmpeg-encoded H.264 / HEVC / MPEG-2 streams1 //! End-to-end: synthetic captions spliced into ffmpeg-encoded H.264 / HEVC / MPEG-2 streams
2 //! (with B-frames), extracted in presentation order, decoded, and compared with ffmpeg's own2 //! (with B-frames), extracted in presentation order, decoded, and compared with ffmpeg's own
3-//! caption decoder. Needs ffmpeg + ffprobe; skipped without them unless EC_REQUIRE_FIXTURES=1.3+//! caption decoder.
4 4
5 use ec_cc::extract::{H264Extractor, HevcExtractor, Mpeg2Extractor, NalFormat};5 use ec_cc::extract::{H264Extractor, HevcExtractor, Mpeg2Extractor, NalFormat};
6 use ec_cc::synth::*;6 use ec_cc::synth::*;
7 use ec_cc::{CcTriplet, decode_all};7 use ec_cc::{CcTriplet, decode_all};
8 use ec_subs::plain_text;8 use ec_subs::plain_text;
9 use std::path::PathBuf;9 use std::path::PathBuf;
10-use std::process::Command;
11 10
12 const FRAMES: usize = 90;11 const FRAMES: usize = 90;
13 12
14-fn have(tool: &str) -> bool {
15- Command::new(tool)
16- .arg("-version")
17- .output()
18- .is_ok_and(|o| o.status.success())
19-}
20-
21-fn require() -> bool {
22- if have("ffmpeg") && have("ffprobe") {
23- return true;
24- }
25- assert!(
26- std::env::var("EC_REQUIRE_FIXTURES").is_err(),
27- "ffmpeg/ffprobe required"
28- );
29- eprintln!("skipping: no ffmpeg");
30- false
31-}
32-
33 fn tmp(name: &str) -> PathBuf {13 fn tmp(name: &str) -> PathBuf {
34 let d = std::env::temp_dir().join(format!("ec-cc-{}", std::process::id()));14 let d = std::env::temp_dir().join(format!("ec-cc-{}", std::process::id()));
35 std::fs::create_dir_all(&d).unwrap();15 std::fs::create_dir_all(&d).unwrap();
@@ -63,7 +43,7 @@ fn caption_frames() -> Vec<Vec<CcTriplet>> {
63 /// Encode a testsrc clip into mkv, return (mkv path, decode-order display indices).43 /// Encode a testsrc clip into mkv, return (mkv path, decode-order display indices).
64 fn encode(codec: &[&str], name: &str) -> (PathBuf, Vec<usize>) {44 fn encode(codec: &[&str], name: &str) -> (PathBuf, Vec<usize>) {
65 let mkv = tmp(&format!("{name}.mkv"));45 let mkv = tmp(&format!("{name}.mkv"));
66- let st = Command::new("ffmpeg")46+ let st = ec_testkit::ffmpeg()
67 .args([47 .args([
68 "-v",48 "-v",
69 "error",49 "error",
@@ -79,7 +59,7 @@ fn encode(codec: &[&str], name: &str) -> (PathBuf, Vec<usize>) {
79 .status()59 .status()
80 .unwrap();60 .unwrap();
81 assert!(st.success());61 assert!(st.success());
82- let out = Command::new("ffprobe")62+ let out = ec_testkit::ffprobe()
83 .args([63 .args([
84 "-v",64 "-v",
85 "error",65 "error",
@@ -109,7 +89,7 @@ fn encode(codec: &[&str], name: &str) -> (PathBuf, Vec<usize>) {
109 89
110 fn raw(mkv: &PathBuf, fmt: &str, bsf: Option<&str>, name: &str) -> PathBuf {90 fn raw(mkv: &PathBuf, fmt: &str, bsf: Option<&str>, name: &str) -> PathBuf {
111 let out = tmp(name);91 let out = tmp(name);
112- let mut c = Command::new("ffmpeg");92+ let mut c = ec_testkit::ffmpeg();
113 c.args(["-v", "error", "-y", "-i"])93 c.args(["-v", "error", "-y", "-i"])
114 .arg(mkv)94 .arg(mkv)
115 .args(["-c:v", "copy", "-an"]);95 .args(["-c:v", "copy", "-an"]);
@@ -145,42 +125,38 @@ fn check(timed: &[ec_cc::TimedCc], captions: &[Vec<CcTriplet>]) {
145 );125 );
146 }126 }
147 127
148-fn ffmpeg_cues(path: &PathBuf, demuxer_args: &[&str]) -> Option<Vec<(String, f64)>> {128+fn ffmpeg_cues(path: &PathBuf, demuxer_args: &[&str]) -> Vec<(String, f64)> {
149 let srt = tmp("ff.srt");129 let srt = tmp("ff.srt");
150 let mkv = tmp("remux.mp4");130 let mkv = tmp("remux.mp4");
151- let st = Command::new("ffmpeg")131+ let st = ec_testkit::ffmpeg()
152 .args(["-v", "error", "-y", "-framerate", "30", "-i"])132 .args(["-v", "error", "-y", "-framerate", "30", "-i"])
153 .arg(path)133 .arg(path)
154 .args(["-c", "copy"])134 .args(["-c", "copy"])
155 .arg(&mkv)135 .arg(&mkv)
156 .status()136 .status()
157- .ok()?;137+ .unwrap();
158- if !st.success() {138+ assert!(st.success());
159- return None;
160- }
161 let spec = format!("movie={}[out0+subcc]", mkv.display());139 let spec = format!("movie={}[out0+subcc]", mkv.display());
162- let st = Command::new("ffmpeg")140+ let st = ec_testkit::ffmpeg()
163 .args(["-v", "error", "-y"])141 .args(["-v", "error", "-y"])
164 .args(demuxer_args)142 .args(demuxer_args)
165 .args(["-f", "lavfi", "-i", &spec, "-map", "0:s:0", "-f", "srt"])143 .args(["-f", "lavfi", "-i", &spec, "-map", "0:s:0", "-f", "srt"])
166 .arg(&srt)144 .arg(&srt)
167 .status()145 .status()
168- .ok()?;146+ .unwrap();
169- if !st.success() {147+ assert!(st.success());
170- return None;148+ let text = std::fs::read_to_string(&srt).unwrap();
171- }
172- let text = std::fs::read_to_string(&srt).ok()?;
173 let mut out = Vec::new();149 let mut out = Vec::new();
174 for block in text.split("\n\n") {150 for block in text.split("\n\n") {
175 let mut l = block.lines();151 let mut l = block.lines();
176- l.next()?;152+ l.next().unwrap();
177 let Some(tl) = l.next() else { continue };153 let Some(tl) = l.next() else { continue };
178- let start = tl.split(" --> ").next()?;154+ let start = tl.split(" --> ").next().unwrap();
179- let secs = parse_srt(start)?;155+ let secs = parse_srt(start);
180 let body: Vec<&str> = l.collect();156 let body: Vec<&str> = l.collect();
181 out.push((strip(&body.join("\n")), secs));157 out.push((strip(&body.join("\n")), secs));
182 }158 }
183- Some(out)159+ out
184 }160 }
185 161
186 fn strip(s: &str) -> String {162 fn strip(s: &str) -> String {
@@ -197,17 +173,14 @@ fn strip(s: &str) -> String {
197 o.trim().to_string()173 o.trim().to_string()
198 }174 }
199 175
200-fn parse_srt(s: &str) -> Option<f64> {176+fn parse_srt(s: &str) -> f64 {
201- let (hms, ms) = s.trim().split_once(',')?;177+ let (hms, ms) = s.trim().split_once(',').unwrap();
202 let p: Vec<f64> = hms.split(':').map(|x| x.parse().unwrap()).collect();178 let p: Vec<f64> = hms.split(':').map(|x| x.parse().unwrap()).collect();
203- Some(p[0] * 3600.0 + p[1] * 60.0 + p[2] + ms.parse::<f64>().ok()? / 1000.0)179+ p[0] * 3600.0 + p[1] * 60.0 + p[2] + ms.parse::<f64>().unwrap() / 1000.0
204 }180 }
205 181
206 fn compare_with_ffmpeg(timed: &[ec_cc::TimedCc], path: &PathBuf) {182 fn compare_with_ffmpeg(timed: &[ec_cc::TimedCc], path: &PathBuf) {
207- let Some(theirs) = ffmpeg_cues(path, &[]) else {183+ let theirs = ffmpeg_cues(path, &[]);
208- eprintln!("ffmpeg subcc extraction unavailable; skipped comparison");
209- return;
210- };
211 let ours = decode_all(timed).cea608;184 let ours = decode_all(timed).cea608;
212 assert!(!theirs.is_empty(), "ffmpeg found no captions");185 assert!(!theirs.is_empty(), "ffmpeg found no captions");
213 assert_eq!(186 assert_eq!(
@@ -233,9 +206,6 @@ fn compare_with_ffmpeg(timed: &[ec_cc::TimedCc], path: &PathBuf) {
233 206
234 #[test]207 #[test]
235 fn h264_with_b_frames() {208 fn h264_with_b_frames() {
236- if !require() {
237- return;
238- }
239 let (mkv, idx) = encode(209 let (mkv, idx) = encode(
240 &[210 &[
241 "-c:v",211 "-c:v",
@@ -268,9 +238,6 @@ fn h264_with_b_frames() {
268 238
269 #[test]239 #[test]
270 fn h264_with_container_pts_in_decode_order() {240 fn h264_with_container_pts_in_decode_order() {
271- if !require() {
272- return;
273- }
274 let (mkv, idx) = encode(&["-c:v", "libx264", "-bf", "2", "-g", "30"], "h264pts");241 let (mkv, idx) = encode(&["-c:v", "libx264", "-bf", "2", "-g", "30"], "h264pts");
275 let ann = raw(&mkv, "h264", Some("h264_mp4toannexb"), "b.264");242 let ann = raw(&mkv, "h264", Some("h264_mp4toannexb"), "b.264");
276 let caps = caption_frames();243 let caps = caption_frames();
@@ -287,9 +254,6 @@ fn h264_with_container_pts_in_decode_order() {
287 254
288 #[test]255 #[test]
289 fn hevc_with_b_frames() {256 fn hevc_with_b_frames() {
290- if !require() {
291- return;
292- }
293 let (mkv, idx) = encode(257 let (mkv, idx) = encode(
294 &[258 &[
295 "-c:v",259 "-c:v",
@@ -317,9 +281,6 @@ fn hevc_with_b_frames() {
317 281
318 #[test]282 #[test]
319 fn mpeg2_atsc_and_dvd_user_data() {283 fn mpeg2_atsc_and_dvd_user_data() {
320- if !require() {
321- return;
322- }
323 let (mkv, idx) = encode(&["-c:v", "mpeg2video", "-bf", "2", "-g", "12"], "m2v");284 let (mkv, idx) = encode(&["-c:v", "mpeg2video", "-bf", "2", "-g", "12"], "m2v");
324 let es = std::fs::read(raw(&mkv, "mpeg2video", None, "a.m2v")).unwrap();285 let es = std::fs::read(raw(&mkv, "mpeg2video", None, "a.m2v")).unwrap();
325 let caps = caption_frames();286 let caps = caption_frames();
crates/ec-dvbsub/Cargo.tomlmodified+1 -0
@@ -10,5 +10,6 @@ authors.workspace = true
10 ec-core.workspace = true10 ec-core.workspace = true
11 11
12 [dev-dependencies]12 [dev-dependencies]
13+ec-testkit.workspace = true
13 ec-matroska.workspace = true14 ec-matroska.workspace = true
14 ec-mpegts.workspace = true15 ec-mpegts.workspace = true
crates/ec-dvbsub/tests/ffmpeg_parity.rsmodified+9 -21
@@ -1,13 +1,11 @@
1 //! Our DVB subtitle decode against ffmpeg's (sub2video frames: `[0:s:0]` out as raw RGBA).1 //! Our DVB subtitle decode against ffmpeg's (sub2video frames: `[0:s:0]` out as raw RGBA).
2 //!2 //!
3 //! Fixtures are tiny files made by `scripts/gen-bitmap-sub-fixtures.sh` from a synthetic3 //! Fixtures are tiny files made by `scripts/gen-bitmap-sub-fixtures.sh` from a synthetic
4-//! 720x576 PGS source (four cues). ffmpeg is the oracle; without it the tests skip loudly, and4+//! 720x576 PGS source (four cues). ffmpeg is the oracle.
5-//! with `EC_REQUIRE_FIXTURES=1` a missing ffmpeg fails.
6 5
7 use std::fs::File;6 use std::fs::File;
8 use std::io::BufReader;7 use std::io::BufReader;
9 use std::path::PathBuf;8 use std::path::PathBuf;
10-use std::process::Command;
11 9
12 use ec_core::{Decoder, Demuxer, Error};10 use ec_core::{Decoder, Demuxer, Error};
13 use ec_dvbsub::DvbSubDecoder;11 use ec_dvbsub::DvbSubDecoder;
@@ -21,8 +19,8 @@ struct Oracle {
21 frames: Vec<(f64, Vec<u8>)>,19 frames: Vec<(f64, Vec<u8>)>,
22 }20 }
23 21
24-fn oracle(path: &PathBuf, w: usize, h: usize) -> Option<Oracle> {22+fn oracle(path: &PathBuf, w: usize, h: usize) -> Oracle {
25- let out = Command::new("ffmpeg")23+ let out = ec_testkit::ffmpeg()
26 .args(["-v", "info", "-nostdin", "-canvas_size", &format!("{w}x{h}"), "-i"])24 .args(["-v", "info", "-nostdin", "-canvas_size", &format!("{w}x{h}"), "-i"])
27 .arg(path)25 .arg(path)
28 .args([26 .args([
@@ -38,18 +36,8 @@ fn oracle(path: &PathBuf, w: usize, h: usize) -> Option<Oracle> {
38 "rgba",36 "rgba",
39 "-",37 "-",
40 ])38 ])
41- .output();39+ .output()
42- let out = match out {40+ .expect("ffmpeg runs");
43- Ok(o) => o,
44- Err(_) => {
45- assert!(
46- std::env::var_os("EC_REQUIRE_FIXTURES").is_none(),
47- "EC_REQUIRE_FIXTURES=1 but ffmpeg is not installed"
48- );
49- eprintln!("SKIP: ffmpeg not installed");
50- return None;
51- }
52- };
53 assert!(out.status.success(), "ffmpeg failed: {}", String::from_utf8_lossy(&out.stderr));41 assert!(out.status.success(), "ffmpeg failed: {}", String::from_utf8_lossy(&out.stderr));
54 let text = String::from_utf8_lossy(&out.stderr);42 let text = String::from_utf8_lossy(&out.stderr);
55 let times: Vec<f64> = text43 let times: Vec<f64> = text
@@ -59,13 +47,13 @@ fn oracle(path: &PathBuf, w: usize, h: usize) -> Option<Oracle> {
59 .collect();47 .collect();
60 let fsize = w * h * 4;48 let fsize = w * h * 4;
61 assert_eq!(out.stdout.len(), times.len() * fsize, "frame count mismatch");49 assert_eq!(out.stdout.len(), times.len() * fsize, "frame count mismatch");
62- Some(Oracle {50+ Oracle {
63 frames: times51 frames: times
64 .iter()52 .iter()
65 .enumerate()53 .enumerate()
66 .map(|(i, &t)| (t, out.stdout[i * fsize..(i + 1) * fsize].to_vec()))54 .map(|(i, &t)| (t, out.stdout[i * fsize..(i + 1) * fsize].to_vec()))
67 .collect(),55 .collect(),
68- })56+ }
69 }57 }
70 58
71 fn blank(f: &[u8]) -> bool {59 fn blank(f: &[u8]) -> bool {
@@ -142,7 +130,7 @@ fn compare(ours: &[(Vec<u8>, f64, Option<f64>)], o: &Oracle, what: &str) {
142 #[test]130 #[test]
143 fn mkv_dvbsub_matches_ffmpeg() {131 fn mkv_dvbsub_matches_ffmpeg() {
144 let path = data("dvb.mkv");132 let path = data("dvb.mkv");
145- let Some(o) = oracle(&path, 720, 576) else { return };133+ let o = oracle(&path, 720, 576);
146 let mut d = ec_matroska::MatroskaDemuxer::new(BufReader::new(File::open(&path).unwrap())).unwrap();134 let mut d = ec_matroska::MatroskaDemuxer::new(BufReader::new(File::open(&path).unwrap())).unwrap();
147 assert_eq!(d.streams()[0].params.codec, ec_core::CodecId::DvbSub);135 assert_eq!(d.streams()[0].params.codec, ec_core::CodecId::DvbSub);
148 let ours = run_packets(&mut d, 0);136 let ours = run_packets(&mut d, 0);
@@ -152,7 +140,7 @@ fn mkv_dvbsub_matches_ffmpeg() {
152 #[test]140 #[test]
153 fn ts_private_pes_matches_ffmpeg() {141 fn ts_private_pes_matches_ffmpeg() {
154 let path = data("dvb.ts");142 let path = data("dvb.ts");
155- let Some(o) = oracle(&path, 720, 576) else { return };143+ let o = oracle(&path, 720, 576);
156 let mut d = ec_mpegts::TsDemuxer::new(BufReader::new(File::open(&path).unwrap())).unwrap();144 let mut d = ec_mpegts::TsDemuxer::new(BufReader::new(File::open(&path).unwrap())).unwrap();
157 let sub = d145 let sub = d
158 .streams()146 .streams()
crates/ec-dvdsub/Cargo.tomlmodified+1 -0
@@ -10,6 +10,7 @@ authors.workspace = true
10 ec-core.workspace = true10 ec-core.workspace = true
11 11
12 [dev-dependencies]12 [dev-dependencies]
13+ec-testkit.workspace = true
13 ec-matroska.workspace = true14 ec-matroska.workspace = true
14 ec-mpegts.workspace = true15 ec-mpegts.workspace = true
15 ec-mp4.workspace = true16 ec-mp4.workspace = true
crates/ec-dvdsub/tests/ffmpeg_parity.rsmodified+12 -24
@@ -1,13 +1,11 @@
1 //! Our subpicture decode against ffmpeg's (sub2video frames: `[0:s:0]` out as raw RGBA).1 //! Our subpicture decode against ffmpeg's (sub2video frames: `[0:s:0]` out as raw RGBA).
2 //!2 //!
3 //! Fixtures are tiny files made by `scripts/gen-bitmap-sub-fixtures.sh` from a synthetic3 //! Fixtures are tiny files made by `scripts/gen-bitmap-sub-fixtures.sh` from a synthetic
4-//! 720x576 PGS source (four cues). ffmpeg is the oracle; without it the tests skip loudly, and4+//! 720x576 PGS source (four cues). ffmpeg is the oracle.
5-//! with `EC_REQUIRE_FIXTURES=1` a missing ffmpeg fails.
6 5
7 use std::fs::File;6 use std::fs::File;
8 use std::io::BufReader;7 use std::io::BufReader;
9 use std::path::PathBuf;8 use std::path::PathBuf;
10-use std::process::Command;
11 9
12 use ec_core::{Demuxer, Error, Frame, Decoder};10 use ec_core::{Demuxer, Error, Frame, Decoder};
13 use ec_dvdsub::{DvdSubDecoder, parse_idx, sub_file_units};11 use ec_dvdsub::{DvdSubDecoder, parse_idx, sub_file_units};
@@ -21,8 +19,8 @@ struct Oracle {
21 frames: Vec<(f64, Vec<u8>)>,19 frames: Vec<(f64, Vec<u8>)>,
22 }20 }
23 21
24-fn oracle(path: &PathBuf, w: usize, h: usize) -> Option<Oracle> {22+fn oracle(path: &PathBuf, w: usize, h: usize) -> Oracle {
25- let out = Command::new("ffmpeg")23+ let out = ec_testkit::ffmpeg()
26 .args(["-v", "info", "-nostdin", "-canvas_size", &format!("{w}x{h}"), "-i"])24 .args(["-v", "info", "-nostdin", "-canvas_size", &format!("{w}x{h}"), "-i"])
27 .arg(path)25 .arg(path)
28 .args([26 .args([
@@ -38,18 +36,8 @@ fn oracle(path: &PathBuf, w: usize, h: usize) -> Option<Oracle> {
38 "rgba",36 "rgba",
39 "-",37 "-",
40 ])38 ])
41- .output();39+ .output()
42- let out = match out {40+ .expect("ffmpeg runs");
43- Ok(o) => o,
44- Err(_) => {
45- assert!(
46- std::env::var_os("EC_REQUIRE_FIXTURES").is_none(),
47- "EC_REQUIRE_FIXTURES=1 but ffmpeg is not installed"
48- );
49- eprintln!("SKIP: ffmpeg not installed");
50- return None;
51- }
52- };
53 assert!(out.status.success(), "ffmpeg failed: {}", String::from_utf8_lossy(&out.stderr));41 assert!(out.status.success(), "ffmpeg failed: {}", String::from_utf8_lossy(&out.stderr));
54 let text = String::from_utf8_lossy(&out.stderr);42 let text = String::from_utf8_lossy(&out.stderr);
55 let times: Vec<f64> = text43 let times: Vec<f64> = text
@@ -59,13 +47,13 @@ fn oracle(path: &PathBuf, w: usize, h: usize) -> Option<Oracle> {
59 .collect();47 .collect();
60 let fsize = w * h * 4;48 let fsize = w * h * 4;
61 assert_eq!(out.stdout.len(), times.len() * fsize, "frame count mismatch");49 assert_eq!(out.stdout.len(), times.len() * fsize, "frame count mismatch");
62- Some(Oracle {50+ Oracle {
63 frames: times51 frames: times
64 .iter()52 .iter()
65 .enumerate()53 .enumerate()
66 .map(|(i, &t)| (t, out.stdout[i * fsize..(i + 1) * fsize].to_vec()))54 .map(|(i, &t)| (t, out.stdout[i * fsize..(i + 1) * fsize].to_vec()))
67 .collect(),55 .collect(),
68- })56+ }
69 }57 }
70 58
71 fn blank(f: &[u8]) -> bool {59 fn blank(f: &[u8]) -> bool {
@@ -136,7 +124,7 @@ fn run_packets(
136 #[test]124 #[test]
137 fn mkv_vobsub_matches_ffmpeg() {125 fn mkv_vobsub_matches_ffmpeg() {
138 let path = data("dvd.mkv");126 let path = data("dvd.mkv");
139- let Some(o) = oracle(&path, 720, 576) else { return };127+ let o = oracle(&path, 720, 576);
140 let mut d = ec_matroska::MatroskaDemuxer::new(BufReader::new(File::open(&path).unwrap())).unwrap();128 let mut d = ec_matroska::MatroskaDemuxer::new(BufReader::new(File::open(&path).unwrap())).unwrap();
141 let info = &d.streams()[0];129 let info = &d.streams()[0];
142 let extra = info.params.extradata.as_deref().map(<[u8]>::to_vec);130 let extra = info.params.extradata.as_deref().map(<[u8]>::to_vec);
@@ -148,13 +136,13 @@ fn mkv_vobsub_matches_ffmpeg() {
148 compare(&ours, &o, "mkv");136 compare(&ours, &o, "mkv");
149 }137 }
150 138
151-fn mkv_oracle() -> Option<Oracle> {139+fn mkv_oracle() -> Oracle {
152 oracle(&data("dvd.mkv"), 720, 576)140 oracle(&data("dvd.mkv"), 720, 576)
153 }141 }
154 142
155 #[test]143 #[test]
156 fn vob_private_stream_1_matches_ffmpeg() {144 fn vob_private_stream_1_matches_ffmpeg() {
157- let Some(o) = mkv_oracle() else { return };145+ let o = mkv_oracle();
158 let path = data("dvd.vob");146 let path = data("dvd.vob");
159 let mut d = ec_mpegts::PsDemuxer::new(BufReader::new(File::open(&path).unwrap())).unwrap();147 let mut d = ec_mpegts::PsDemuxer::new(BufReader::new(File::open(&path).unwrap())).unwrap();
160 let sub = d148 let sub = d
@@ -169,7 +157,7 @@ fn vob_private_stream_1_matches_ffmpeg() {
169 157
170 #[test]158 #[test]
171 fn mp4s_esds_matches_ffmpeg() {159 fn mp4s_esds_matches_ffmpeg() {
172- let Some(o) = mkv_oracle() else { return };160+ let o = mkv_oracle();
173 let path = data("dvd.mp4");161 let path = data("dvd.mp4");
174 let mut d = ec_mp4::Mp4Demuxer::new(BufReader::new(File::open(&path).unwrap())).unwrap();162 let mut d = ec_mp4::Mp4Demuxer::new(BufReader::new(File::open(&path).unwrap())).unwrap();
175 let sub = d163 let sub = d
@@ -186,7 +174,7 @@ fn mp4s_esds_matches_ffmpeg() {
186 174
187 #[test]175 #[test]
188 fn idx_sub_pair_matches_ffmpeg() {176 fn idx_sub_pair_matches_ffmpeg() {
189- let Some(o) = mkv_oracle() else { return };177+ let o = mkv_oracle();
190 let idx = parse_idx(&std::fs::read(data("dvd.idx")).unwrap());178 let idx = parse_idx(&std::fs::read(data("dvd.idx")).unwrap());
191 assert_eq!(idx.size, Some((720, 576)));179 assert_eq!(idx.size, Some((720, 576)));
192 assert_eq!(idx.languages, vec![("en".to_string(), 0)]);180 assert_eq!(idx.languages, vec![("en".to_string(), 0)]);
crates/ec-image/Cargo.tomlmodified+1 -0
@@ -11,6 +11,7 @@ ec-core = { workspace = true }
11 ec-inflate = { workspace = true }11 ec-inflate = { workspace = true }
12 12
13 [dev-dependencies]13 [dev-dependencies]
14+ec-testkit.workspace = true
14 # The incumbent, as a differential oracle only: every test decodes the same15 # The incumbent, as a differential oracle only: every test decodes the same
15 # bytes both ways and compares pixels. Running it is the point; nothing is16 # bytes both ways and compares pixels. Running it is the point; nothing is
16 # copied from it.17 # copied from it.
crates/ec-image/src/gif_encode.rsmodified+2 -8
@@ -739,20 +739,14 @@ mod tests {
739 }739 }
740 740
741 #[test]741 #[test]
742- fn ffprobe_reads_the_output_when_it_is_installed() {742+ fn ffprobe_reads_the_output() {
743- let probe = std::process::Command::new("ffprobe")
744- .arg("-version")
745- .output();
746- if probe.is_err() {
747- return;
748- }
749 let px: Vec<u8> = (0..8 * 4)743 let px: Vec<u8> = (0..8 * 4)
750 .flat_map(|i: u8| [i * 8, 128, 255 - i * 8, 255])744 .flat_map(|i: u8| [i * 8, 128, 255 - i * 8, 255])
751 .collect();745 .collect();
752 let gif = encode_frames(8, 4, GifOptions::default(), &[(&px, 5), (&px, 5)]);746 let gif = encode_frames(8, 4, GifOptions::default(), &[(&px, 5), (&px, 5)]);
753 let path = std::env::temp_dir().join(format!("ec-gif-encode-{}.gif", std::process::id()));747 let path = std::env::temp_dir().join(format!("ec-gif-encode-{}.gif", std::process::id()));
754 std::fs::write(&path, &gif).unwrap();748 std::fs::write(&path, &gif).unwrap();
755- let out = std::process::Command::new("ffprobe")749+ let out = ec_testkit::ffprobe()
756 .args(["-v", "error", "-select_streams", "v:0", "-show_entries"])750 .args(["-v", "error", "-select_streams", "v:0", "-show_entries"])
757 .args(["stream=width,height", "-of", "csv=p=0"])751 .args(["stream=width,height", "-of", "csv=p=0"])
758 .arg(&path)752 .arg(&path)
crates/ec-image/tests/fuzz.rsmodified+3 -12
@@ -190,10 +190,7 @@ fn repair_png_crcs(data: &mut [u8]) {
190 fn sweep(name: &str, seed_file: &str) {190 fn sweep(name: &str, seed_file: &str) {
191 // Mutated headers can claim canvases up to the budget, so a sweep is heavy too.191 // Mutated headers can claim canvases up to the budget, so a sweep is heavy too.
192 let _heavy = heavy();192 let _heavy = heavy();
193- let Ok(seed) = std::fs::read(fixtures().join(seed_file)) else {193+ let seed = std::fs::read(fixtures().join(seed_file)).unwrap();
194- eprintln!("skipped: fixtures/stills not generated; run scripts/gen-still-fixtures.sh");
195- return;
196- };
197 let mut rng = Rng(0x2545_f491_4f6c_dd1d ^ name.len() as u64);194 let mut rng = Rng(0x2545_f491_4f6c_dd1d ^ name.len() as u64);
198 let mut decoded = 0usize;195 let mut decoded = 0usize;
199 for round in 0..ROUNDS {196 for round in 0..ROUNDS {
@@ -263,10 +260,7 @@ fn single_seed_sweeps_survive_mutation() {
263 /// disposal state machine, none of which `decode` reaches past frame one.260 /// disposal state machine, none of which `decode` reaches past frame one.
264 #[test]261 #[test]
265 fn a_gif_animation_survives_mutation() {262 fn a_gif_animation_survives_mutation() {
266- let Ok(seed) = std::fs::read(fixtures().join("animated.gif")) else {263+ let seed = std::fs::read(fixtures().join("animated.gif")).unwrap();
267- eprintln!("skipped: fixtures/stills not generated; run scripts/gen-still-fixtures.sh");
268- return;
269- };
270 let _heavy = heavy();264 let _heavy = heavy();
271 let mut rng = Rng(0x2545_f491_4f6c_dd1d ^ 0x9e37);265 let mut rng = Rng(0x2545_f491_4f6c_dd1d ^ 0x9e37);
272 let mut decoded = 0usize;266 let mut decoded = 0usize;
@@ -292,10 +286,7 @@ fn a_gif_animation_survives_mutation() {
292 /// canvas sized by a different chunk, so a mutation can make the two disagree.286 /// canvas sized by a different chunk, so a mutation can make the two disagree.
293 #[test]287 #[test]
294 fn an_animated_webp_survives_mutation() {288 fn an_animated_webp_survives_mutation() {
295- let Ok(seed) = std::fs::read(fixtures().join("anim-alpha.webp")) else {289+ let seed = std::fs::read(fixtures().join("anim-alpha.webp")).unwrap();
296- eprintln!("skipped: fixtures/stills not generated; run scripts/gen-still-fixtures.sh");
297- return;
298- };
299 let _heavy = heavy();290 let _heavy = heavy();
300 let mut rng = Rng(0x2545_f491_4f6c_dd1d ^ 0x5eed);291 let mut rng = Rng(0x2545_f491_4f6c_dd1d ^ 0x5eed);
301 let mut decoded = 0usize;292 let mut decoded = 0usize;
crates/ec-image/tests/it/differential.rsmodified+24 -83
@@ -42,11 +42,6 @@ fn corpus(extension: &str) -> Vec<PathBuf> {
42 found42 found
43 }43 }
44 44
45-fn skip(what: &str) -> bool {
46- eprintln!("skipped: fixtures/stills not generated ({what}); run scripts/gen-still-fixtures.sh");
47- true
48-}
49-
50 /// Largest per-sample difference and Pearson correlation between two buffers.45 /// Largest per-sample difference and Pearson correlation between two buffers.
51 fn compare(ours: &[u8], theirs: &[u8]) -> (u32, f64) {46 fn compare(ours: &[u8], theirs: &[u8]) -> (u32, f64) {
52 assert_eq!(ours.len(), theirs.len(), "sample counts differ");47 assert_eq!(ours.len(), theirs.len(), "sample counts differ");
@@ -93,9 +88,7 @@ fn psnr(a: &[u8], b: &[u8]) -> f64 {
93 #[test]88 #[test]
94 fn png_decodes_pixel_exactly() {89 fn png_decodes_pixel_exactly() {
95 let files = corpus("png");90 let files = corpus("png");
96- if files.is_empty() && skip("png") {91+ assert!(!files.is_empty(), "no png stills");
97- return;
98- }
99 for path in files {92 for path in files {
100 let bytes = std::fs::read(&path).unwrap();93 let bytes = std::fs::read(&path).unwrap();
101 let ours = ec_image::decode(&bytes).unwrap_or_else(|e| panic!("{}: {e}", path.display()));94 let ours = ec_image::decode(&bytes).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
@@ -126,9 +119,7 @@ fn webp_lossless_decodes_pixel_exactly() {
126 .into_iter()119 .into_iter()
127 .filter(|p| name_of(p).contains("lossless"))120 .filter(|p| name_of(p).contains("lossless"))
128 .collect();121 .collect();
129- if files.is_empty() && skip("webp") {122+ assert!(!files.is_empty(), "no webp stills");
130- return;
131- }
132 for path in files {123 for path in files {
133 let bytes = std::fs::read(&path).unwrap();124 let bytes = std::fs::read(&path).unwrap();
134 let ours = ec_image::decode(&bytes).unwrap_or_else(|e| panic!("{}: {e}", path.display()));125 let ours = ec_image::decode(&bytes).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
@@ -151,9 +142,7 @@ fn webp_lossless_decodes_pixel_exactly() {
151 #[test]142 #[test]
152 fn jpeg_matches_the_incumbent_within_rounding() {143 fn jpeg_matches_the_incumbent_within_rounding() {
153 let files = corpus("jpg");144 let files = corpus("jpg");
154- if files.is_empty() && skip("jpg") {145+ assert!(!files.is_empty(), "no jpg stills");
155- return;
156- }
157 let mut worst = 0u32;146 let mut worst = 0u32;
158 for path in files {147 for path in files {
159 let bytes = std::fs::read(&path).unwrap();148 let bytes = std::fs::read(&path).unwrap();
@@ -194,9 +183,7 @@ fn webp_lossy_reconstructs_at_least_as_well_as_the_incumbent() {
194 .into_iter()183 .into_iter()
195 .filter(|p| name_of(p).contains("lossy"))184 .filter(|p| name_of(p).contains("lossy"))
196 .collect();185 .collect();
197- if files.is_empty() && skip("webp") {186+ assert!(!files.is_empty(), "no webp stills");
198- return;
199- }
200 let mut shortfalls: Vec<String> = Vec::new();187 let mut shortfalls: Vec<String> = Vec::new();
201 for path in files {188 for path in files {
202 let name = path.file_name().unwrap().to_string_lossy().to_string();189 let name = path.file_name().unwrap().to_string_lossy().to_string();
@@ -258,18 +245,13 @@ fn header_dimensions_match_the_incumbent() {
258 checked += 1;245 checked += 1;
259 }246 }
260 }247 }
261- if checked == 0 {248+ assert!(checked > 0, "no stills");
262- skip("any");
263- }
264 }249 }
265 250
266 #[test]251 #[test]
267 fn an_animated_webp_is_refused_by_name() {252 fn an_animated_webp_is_refused_by_name() {
268 let path = fixtures().join("animated.webp");253 let path = fixtures().join("animated.webp");
269- let Ok(bytes) = std::fs::read(&path) else {254+ let bytes = std::fs::read(&path).unwrap();
270- skip("animated.webp");
271- return;
272- };
273 let err = ec_image::decode(&bytes).expect_err("an animation is not a still");255 let err = ec_image::decode(&bytes).expect_err("an animation is not a still");
274 let message = format!("{err}");256 let message = format!("{err}");
275 assert!(message.contains("animated"), "{message}");257 assert!(message.contains("animated"), "{message}");
@@ -302,10 +284,7 @@ fn with_exif_orientation(jpeg: &[u8], orientation: u16) -> Vec<u8> {
302 284
303 #[test]285 #[test]
304 fn exif_orientation_is_reported_and_not_applied() {286 fn exif_orientation_is_reported_and_not_applied() {
305- let Ok(plain) = std::fs::read(fixtures().join("baseline-444.jpg")) else {287+ let plain = std::fs::read(fixtures().join("baseline-444.jpg")).unwrap();
306- skip("baseline-444.jpg");
307- return;
308- };
309 let bytes = with_exif_orientation(&plain, 6);288 let bytes = with_exif_orientation(&plain, 6);
310 let ours = ec_image::decode(&bytes).unwrap();289 let ours = ec_image::decode(&bytes).unwrap();
311 let theirs = image::load_from_memory(&bytes).unwrap();290 let theirs = image::load_from_memory(&bytes).unwrap();
@@ -344,10 +323,7 @@ fn every_fixture_decodes() {
344 }323 }
345 }324 }
346 }325 }
347- if count == 0 {326+ assert!(count > 0, "no stills");
348- skip("any");
349- return;
350- }
351 assert!(327 assert!(
352 failures.is_empty(),328 failures.is_empty(),
353 "{} failed:\n{}",329 "{} failed:\n{}",
@@ -359,9 +335,7 @@ fn every_fixture_decodes() {
359 #[test]335 #[test]
360 fn gif_decodes_pixel_exactly() {336 fn gif_decodes_pixel_exactly() {
361 let files = corpus("gif");337 let files = corpus("gif");
362- if files.is_empty() && skip("gif") {338+ assert!(!files.is_empty(), "no gif stills");
363- return;
364- }
365 for path in files {339 for path in files {
366 let bytes = std::fs::read(&path).unwrap();340 let bytes = std::fs::read(&path).unwrap();
367 let ours = ec_image::decode(&bytes).unwrap_or_else(|e| panic!("{}: {e}", path.display()));341 let ours = ec_image::decode(&bytes).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
@@ -392,9 +366,6 @@ fn a_gif_animation_composites_frame_for_frame_like_the_incumbent() {
392 use image::AnimationDecoder;366 use image::AnimationDecoder;
393 367
394 let path = fixtures().join("animated.gif");368 let path = fixtures().join("animated.gif");
395- if !path.exists() && skip("animated.gif") {
396- return;
397- }
398 let bytes = std::fs::read(&path).unwrap();369 let bytes = std::fs::read(&path).unwrap();
399 let ours = ec_image::decode_animation(&bytes).expect("our animation decode");370 let ours = ec_image::decode_animation(&bytes).expect("our animation decode");
400 let theirs: Vec<image::Frame> =371 let theirs: Vec<image::Frame> =
@@ -433,9 +404,6 @@ fn a_gif_animation_composites_frame_for_frame_like_the_incumbent() {
433 #[test]404 #[test]
434 fn a_still_of_any_format_is_one_frame_of_animation() {405 fn a_still_of_any_format_is_one_frame_of_animation() {
435 let path = fixtures().join("rgb8.png");406 let path = fixtures().join("rgb8.png");
436- if !path.exists() && skip("rgb8.png") {
437- return;
438- }
439 let bytes = std::fs::read(&path).unwrap();407 let bytes = std::fs::read(&path).unwrap();
440 let frames = ec_image::decode_animation(&bytes).expect("decode");408 let frames = ec_image::decode_animation(&bytes).expect("decode");
441 assert_eq!(frames.len(), 1);409 assert_eq!(frames.len(), 1);
@@ -455,10 +423,7 @@ fn one_animated_webp(fixture: &str) {
455 use image::AnimationDecoder;423 use image::AnimationDecoder;
456 424
457 let path = fixtures().join(fixture);425 let path = fixtures().join(fixture);
458- let Ok(bytes) = std::fs::read(&path) else {426+ let bytes = std::fs::read(&path).unwrap();
459- skip(fixture);
460- return;
461- };
462 assert!(427 assert!(
463 ec_image::webp::is_animated(&bytes),428 ec_image::webp::is_animated(&bytes),
464 "the fixture is not an animation"429 "the fixture is not an animation"
@@ -516,18 +481,12 @@ fn one_animated_webp(fixture: &str) {
516 #[test]481 #[test]
517 fn webp_disposal_and_blending_match_libwebp() {482 fn webp_disposal_and_blending_match_libwebp() {
518 let path = fixtures().join("anim-alpha.webp");483 let path = fixtures().join("anim-alpha.webp");
519- let Ok(bytes) = std::fs::read(&path) else {484+ let bytes = std::fs::read(&path).unwrap();
520- skip("anim-alpha.webp");
521- return;
522- };
523 let goldens: Vec<PathBuf> = (0..)485 let goldens: Vec<PathBuf> = (0..)
524 .map(|i| fixtures().join(format!("anim-alpha-f{i}.png")))486 .map(|i| fixtures().join(format!("anim-alpha-f{i}.png")))
525 .take_while(|p| p.exists())487 .take_while(|p| p.exists())
526 .collect();488 .collect();
527- if goldens.is_empty() {489+ assert!(!goldens.is_empty(), "libwebp goldens missing");
528- skip("anim-alpha-f0.png (libwebp goldens; Pillow not installed?)");
529- return;
530- }
531 490
532 let ours = ec_image::decode_animation(&bytes).expect("our animation decode");491 let ours = ec_image::decode_animation(&bytes).expect("our animation decode");
533 assert_eq!(ours.len(), goldens.len(), "frame count against libwebp");492 assert_eq!(ours.len(), goldens.len(), "frame count against libwebp");
@@ -555,9 +514,7 @@ fn webp_disposal_and_blending_match_libwebp() {
555 #[test]514 #[test]
556 fn bmp_decodes_pixel_exactly() {515 fn bmp_decodes_pixel_exactly() {
557 let files = corpus("bmp");516 let files = corpus("bmp");
558- if files.is_empty() && skip("bmp") {517+ assert!(!files.is_empty(), "no bmp stills");
559- return;
560- }
561 for path in files {518 for path in files {
562 let name = path.file_name().unwrap().to_string_lossy().to_string();519 let name = path.file_name().unwrap().to_string_lossy().to_string();
563 if name.starts_with("embedded-") || name == "os2v2.bmp" {520 if name.starts_with("embedded-") || name == "os2v2.bmp" {
@@ -587,12 +544,7 @@ fn a_bmp_wrapping_another_format_decodes_to_that_format() {
587 // implementation-defined, so the two decoders round differently.544 // implementation-defined, so the two decoders round differently.
588 for (fixture, bar) in [("embedded-png.bmp", 0u32), ("embedded-jpeg.bmp", 5)] {545 for (fixture, bar) in [("embedded-png.bmp", 0u32), ("embedded-jpeg.bmp", 5)] {
589 let path = fixtures().join(fixture);546 let path = fixtures().join(fixture);
590- let Ok(data) = std::fs::read(&path) else {547+ let data = std::fs::read(&path).unwrap();
591- if skip(fixture) {
592- return;
593- }
594- unreachable!()
595- };
596 // The payload starts where the file header says the pixels do.548 // The payload starts where the file header says the pixels do.
597 let offset = u32::from_le_bytes([data[10], data[11], data[12], data[13]]) as usize;549 let offset = u32::from_le_bytes([data[10], data[11], data[12], data[13]]) as usize;
598 let payload = &data[offset..];550 let payload = &data[offset..];
@@ -622,10 +574,7 @@ fn a_bmp_wrapping_another_format_decodes_to_that_format() {
622 fn an_os2_v2_header_reads_as_the_same_picture() {574 fn an_os2_v2_header_reads_as_the_same_picture() {
623 let short = fixtures().join("os2v2.bmp");575 let short = fixtures().join("os2v2.bmp");
624 let long = fixtures().join("os2v1.bmp");576 let long = fixtures().join("os2v1.bmp");
625- let (Ok(short), Ok(long)) = (std::fs::read(&short), std::fs::read(&long)) else {577+ let (short, long) = (std::fs::read(&short).unwrap(), std::fs::read(&long).unwrap());
626- skip("os2v2.bmp");
627- return;
628- };
629 assert!(578 assert!(
630 image::load_from_memory(&short).is_err(),579 image::load_from_memory(&short).is_err(),
631 "the incumbent now reads a 16-byte header; this test's premise is stale"580 "the incumbent now reads a 16-byte header; this test's premise is stale"
@@ -649,9 +598,7 @@ fn tiff_decodes_pixel_exactly() {
649 let mut files = corpus("tiff");598 let mut files = corpus("tiff");
650 files.extend(corpus("tif"));599 files.extend(corpus("tif"));
651 files.sort();600 files.sort();
652- if files.is_empty() && skip("tiff") {601+ assert!(!files.is_empty(), "no tiff stills");
653- return;
654- }
655 for path in files {602 for path in files {
656 let name = path.file_name().unwrap().to_string_lossy().to_string();603 let name = path.file_name().unwrap().to_string_lossy().to_string();
657 if name == "palette4.tiff" {604 if name == "palette4.tiff" {
@@ -681,13 +628,10 @@ fn tiff_decodes_pixel_exactly() {
681 /// lossless, so the associated file must decode to the straight one exactly.628 /// lossless, so the associated file must decode to the straight one exactly.
682 #[test]629 #[test]
683 fn an_associated_alpha_tiff_reads_unpremultiplied() {630 fn an_associated_alpha_tiff_reads_unpremultiplied() {
684- let (Ok(assoc), Ok(straight)) = (631+ let (assoc, straight) = (
685- std::fs::read(fixtures().join("rgba8-assoc.tiff")),632+ std::fs::read(fixtures().join("rgba8-assoc.tiff")).unwrap(),
686- std::fs::read(fixtures().join("rgba8.tiff")),633+ std::fs::read(fixtures().join("rgba8.tiff")).unwrap(),
687- ) else {634+ );
688- skip("rgba8-assoc.tiff");
689- return;
690- };
691 let ours = ec_image::decode(&assoc).expect("rgba8-assoc.tiff");635 let ours = ec_image::decode(&assoc).expect("rgba8-assoc.tiff");
692 let reference = ec_image::decode(&straight).expect("rgba8.tiff");636 let reference = ec_image::decode(&straight).expect("rgba8.tiff");
693 // Under a zero alpha the colour is gone for good -- premultiplying by zero637 // Under a zero alpha the colour is gone for good -- premultiplying by zero
@@ -721,13 +665,10 @@ fn an_associated_alpha_tiff_reads_unpremultiplied() {
721 /// when the corpus was generated.665 /// when the corpus was generated.
722 #[test]666 #[test]
723 fn a_four_bit_tiff_palette_reads_as_ffmpeg_reads_it() {667 fn a_four_bit_tiff_palette_reads_as_ffmpeg_reads_it() {
724- let (Ok(narrow), Ok(wide)) = (668+ let (narrow, wide) = (
725- std::fs::read(fixtures().join("palette4.tiff")),669+ std::fs::read(fixtures().join("palette4.tiff")).unwrap(),
726- std::fs::read(fixtures().join("palette4-golden.png")),670+ std::fs::read(fixtures().join("palette4-golden.png")).unwrap(),
727- ) else {671+ );
728- skip("palette4.tiff");
729- return;
730- };
731 assert!(672 assert!(
732 image::load_from_memory(&narrow).is_err(),673 image::load_from_memory(&narrow).is_err(),
733 "the incumbent now reads a 4-bit palette; this test's premise is stale"674 "the incumbent now reads a 4-bit palette; this test's premise is stale"
crates/ec-image/tests/it/gaps.rsmodified+1 -4
@@ -366,10 +366,7 @@ fn png_encoder_round_trips_bit_exact_and_matches_image_decode() {
366 fn png_encoder_size_against_image_on_the_still_fixture() {366 fn png_encoder_size_against_image_on_the_still_fixture() {
367 let path =367 let path =
368 std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/stills/source.png");368 std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/stills/source.png");
369- let Ok(bytes) = std::fs::read(&path) else {369+ let bytes = std::fs::read(&path).unwrap();
370- eprintln!("skipped: {} not generated", path.display());
371- return;
372- };
373 let src = image::load_from_memory(&bytes).unwrap().to_rgb8();370 let src = image::load_from_memory(&bytes).unwrap().to_rgb8();
374 let (w, h) = src.dimensions();371 let (w, h) = src.dimensions();
375 let ours = ec_image::png_encode::encode_rgb8(w, h, src.as_raw()).unwrap();372 let ours = ec_image::png_encode::encode_rgb8(w, h, src.as_raw()).unwrap();
crates/ec-image/tests/it/main.rsmodified+0 -1
@@ -4,4 +4,3 @@
4 4
5 mod differential;5 mod differential;
6 mod gaps;6 mod gaps;
7-mod real_library;
crates/ec-image/tests/it/real_library.rsdeleted+0 -257
@@ -1,257 +0,0 @@
1-//! The same differential bars, against real pictures on this machine.
2-//!
3-//! Generated fixtures come out of two encoders with default settings; a real
4-//! library has phone JPEGs with EXIF, screenshots, scans and downloads, and
5-//! those are the files a user actually opens. The sweep is read-only, prints a
6-//! per-file table, and skips silently when the directories hold no pictures.
7-
8-use image::GenericImageView;
9-use std::path::PathBuf;
10-
11-/// Where a real library lives on this machine; absent directories are skipped.
12-fn library() -> Vec<PathBuf> {
13- let home = std::env::var("HOME").unwrap_or_default();
14- ["Videos", "Downloads"]
15- .iter()
16- .map(|d| PathBuf::from(&home).join(d))
17- .filter(|p| p.is_dir())
18- .collect()
19-}
20-
21-/// Every still under `roots`, three directory levels deep, capped.
22-fn stills(roots: &[PathBuf], cap: usize) -> Vec<PathBuf> {
23- fn walk(dir: &PathBuf, depth: usize, out: &mut Vec<PathBuf>) {
24- if depth == 0 {
25- return;
26- }
27- let Ok(entries) = std::fs::read_dir(dir) else {
28- return;
29- };
30- for entry in entries.flatten() {
31- let path = entry.path();
32- if path.is_dir() {
33- walk(&path, depth - 1, out);
34- } else if let Some(extension) = path.extension() {
35- let extension = extension.to_string_lossy().to_lowercase();
36- if ["png", "jpg", "jpeg", "webp"].contains(&extension.as_str()) {
37- out.push(path);
38- }
39- }
40- }
41- }
42- let mut found = Vec::new();
43- for root in roots {
44- walk(root, 3, &mut found);
45- }
46- found.sort();
47- found.truncate(cap);
48- found
49-}
50-
51-#[test]
52-fn real_pictures_decode_like_the_incumbent() {
53- let files = stills(&library(), 20);
54- if files.is_empty() {
55- eprintln!("skipped: no PNG/JPEG/WebP under ~/Videos or ~/Downloads");
56- return;
57- }
58- let mut failures = Vec::new();
59- for path in &files {
60- let name = path.file_name().unwrap().to_string_lossy().to_string();
61- let bytes = std::fs::read(path).unwrap();
62- let started = std::time::Instant::now();
63- let ours = match ec_image::decode(&bytes) {
64- Ok(image) => image,
65- Err(e) => {
66- // The incumbent's verdict decides whether this is our failure
67- // or a file neither crate claims to decode.
68- if image::load_from_memory(&bytes).is_ok() {
69- failures.push(format!(
70- "{name}: we refuse it, the incumbent decodes it ({e})"
71- ));
72- } else {
73- eprintln!("{name:<44} both refuse: {e}");
74- }
75- continue;
76- }
77- };
78- let ours_ms = started.elapsed().as_secs_f64() * 1000.0;
79- let theirs = match image::load_from_memory(&bytes) {
80- Ok(image) => image,
81- Err(e) => {
82- eprintln!("{name:<44} we decode it, the incumbent does not ({e})");
83- continue;
84- }
85- };
86- if (ours.width, ours.height) != theirs.dimensions() {
87- failures.push(format!(
88- "{name}: {}x{} against the incumbent's {:?}",
89- ours.width,
90- ours.height,
91- theirs.dimensions()
92- ));
93- continue;
94- }
95- let a = ours.to_rgb8();
96- let b = theirs.to_rgb8().into_raw();
97- let max = a
98- .iter()
99- .zip(&b)
100- .map(|(&x, &y)| x.abs_diff(y))
101- .max()
102- .unwrap_or(0);
103- let lossless = path
104- .extension()
105- .is_some_and(|e| e.eq_ignore_ascii_case("png"));
106- eprintln!(
107- "{name:<44} {}x{} max delta {max:>3} {ours_ms:>7.1} ms",
108- ours.width, ours.height
109- );
110- let bar = if lossless { 0 } else { 8 };
111- if u32::from(max) > bar {
112- failures.push(format!("{name}: max delta {max}, bar {bar}"));
113- }
114- }
115- assert!(
116- failures.is_empty(),
117- "{} of {} real pictures failed:\n{}",
118- failures.len(),
119- files.len(),
120- failures.join("\n")
121- );
122-}
123-
124-/// Every GIF on this machine, composited frame for frame against the
125-/// incumbent.
126-///
127-/// The still sweep above compares RGB, which a GIF's transparent index makes
128-/// meaningless; an animation is only decoded correctly if the canvas, the
129-/// disposal method and the alpha all agree, so this one compares RGBA over
130-/// every frame of every file.
131-#[test]
132-fn real_gifs_animate_like_the_incumbent() {
133- use image::AnimationDecoder;
134-
135- let files = walk_extension(&library(), "gif", 20);
136- if files.is_empty() {
137- eprintln!("skipped: no GIF under ~/Videos or ~/Downloads");
138- return;
139- }
140- let mut failures = Vec::new();
141- for path in &files {
142- let name = path.file_name().unwrap().to_string_lossy().to_string();
143- let bytes = std::fs::read(path).unwrap();
144- let started = std::time::Instant::now();
145- let ours = match ec_image::decode_animation(&bytes) {
146- Ok(frames) => frames,
147- Err(e) => {
148- if image::load_from_memory(&bytes).is_ok() {
149- failures.push(format!(
150- "{name}: we refuse it, the incumbent decodes it ({e})"
151- ));
152- } else {
153- eprintln!("{name:<44} both refuse: {e}");
154- }
155- continue;
156- }
157- };
158- let ours_ms = started.elapsed().as_secs_f64() * 1000.0;
159- let theirs = image::codecs::gif::GifDecoder::new(std::io::Cursor::new(&bytes))
160- .and_then(|d| d.into_frames().collect::<Result<Vec<_>, _>>());
161- let theirs = match theirs {
162- Ok(frames) => frames,
163- Err(e) => {
164- eprintln!("{name:<44} we decode it, the incumbent does not ({e})");
165- continue;
166- }
167- };
168- if ours.len() != theirs.len() {
169- failures.push(format!(
170- "{name}: {} frames against the incumbent's {}",
171- ours.len(),
172- theirs.len()
173- ));
174- continue;
175- }
176- let mut worst = None;
177- for (i, (ours, theirs)) in ours.iter().zip(&theirs).enumerate() {
178- if (ours.image.width, ours.image.height) != theirs.buffer().dimensions() {
179- worst = Some(format!(
180- "frame {i}: {}x{} against {:?}",
181- ours.image.width,
182- ours.image.height,
183- theirs.buffer().dimensions()
184- ));
185- break;
186- }
187- let a = ours.image.to_rgba8();
188- let b = theirs.buffer().as_raw();
189- let delta = a
190- .iter()
191- .zip(b)
192- .map(|(&x, &y)| x.abs_diff(y))
193- .max()
194- .unwrap_or(0);
195- let (num, den) = theirs.delay().numer_denom_ms();
196- let ours_ms = f64::from(ours.delay_num) * 1000.0 / f64::from(ours.delay_den);
197- let theirs_ms = f64::from(num) / f64::from(den);
198- if delta != 0 {
199- worst = Some(format!("frame {i}: max delta {delta}, bar 0"));
200- break;
201- }
202- if (ours_ms - theirs_ms).abs() >= 0.5 {
203- worst = Some(format!(
204- "frame {i}: {ours_ms} ms against the incumbent's {theirs_ms} ms"
205- ));
206- break;
207- }
208- }
209- eprintln!(
210- "{name:<44} {}x{} {:>3} frames {ours_ms:>7.1} ms {}",
211- ours[0].image.width,
212- ours[0].image.height,
213- ours.len(),
214- worst.as_deref().unwrap_or("exact")
215- );
216- if let Some(worst) = worst {
217- failures.push(format!("{name}: {worst}"));
218- }
219- }
220- assert!(
221- failures.is_empty(),
222- "{} of {} real GIFs failed:\n{}",
223- failures.len(),
224- files.len(),
225- failures.join("\n")
226- );
227-}
228-
229-/// Every file under `roots` with the given extension, three levels deep.
230-fn walk_extension(roots: &[PathBuf], extension: &str, cap: usize) -> Vec<PathBuf> {
231- fn walk(dir: &PathBuf, want: &str, depth: usize, out: &mut Vec<PathBuf>) {
232- if depth == 0 {
233- return;
234- }
235- let Ok(entries) = std::fs::read_dir(dir) else {
236- return;
237- };
238- for entry in entries.flatten() {
239- let path = entry.path();
240- if path.is_dir() {
241- walk(&path, want, depth - 1, out);
242- } else if path
243- .extension()
244- .is_some_and(|e| e.eq_ignore_ascii_case(want))
245- {
246- out.push(path);
247- }
248- }
249- }
250- let mut found = Vec::new();
251- for root in roots {
252- walk(root, extension, 3, &mut found);
253- }
254- found.sort();
255- found.truncate(cap);
256- found
257-}
crates/ec-pgs/fuzz/seed.shmodified+6 -6
@@ -1,19 +1,19 @@
1 #!/usr/bin/env bash1 #!/usr/bin/env bash
2 # seed.sh: fill fuzz/corpus/<target>/ from the repo's PGS fixture.2 # seed.sh: fill fuzz/corpus/<target>/ from the repo's PGS fixture.
3 #3 #
4-# fixtures/subs/pgs-1080p.sup is a real disc's display sets. segments gets the file's first 64 KiB4+# open/fate/sub/pgs_sub.sup is a PGS stream of display sets. segments gets the file's first 64 KiB
5 # as is. compose and rle get the same bytes too; those two read their own input layouts, so the5 # as is. compose and rle get the same bytes too; those two read their own input layouts, so the
6 # seeds are mostly rejects, which still steer the mutator. Corpus lives under fuzz/corpus.6 # seeds are mostly rejects, which still steer the mutator. Corpus lives under fuzz/corpus.
7 set -euo pipefail7 set -euo pipefail
8 8
9 FUZZ_DIR=$(cd -- "$(dirname -- "$0")" && pwd)9 FUZZ_DIR=$(cd -- "$(dirname -- "$0")" && pwd)
10 ROOT=$(cd -- "$FUZZ_DIR/../../.." && pwd)10 ROOT=$(cd -- "$FUZZ_DIR/../../.." && pwd)
11-SUBS="$ROOT/fixtures/subs"11+SUP="${EC_FIXTURES:-$ROOT/fixtures}/open/fate/sub/pgs_sub.sup"
12-[ -f "$SUBS/pgs-1080p.sup" ] || { echo "seed.sh: $SUBS/pgs-1080p.sup missing; run scripts/link-fixtures.sh" >&2; exit 2; }12+[ -f "$SUP" ] || { echo "seed.sh: $SUP missing; run scripts/fixtures.sh" >&2; exit 2; }
13 13
14 CORPUS="$FUZZ_DIR/corpus"14 CORPUS="$FUZZ_DIR/corpus"
15 mkdir -p "$CORPUS"/{segments,rle,compose}15 mkdir -p "$CORPUS"/{segments,rle,compose}
16-head -c 65536 "$SUBS/pgs-1080p.sup" > "$CORPUS/segments/pgs-1080p"16+head -c 65536 "$SUP" > "$CORPUS/segments/pgs_sub"
17-head -c 4096 "$SUBS/pgs-1080p.sup" > "$CORPUS/compose/pgs-1080p"17+head -c 4096 "$SUP" > "$CORPUS/compose/pgs_sub"
18-head -c 4096 "$SUBS/pgs-1080p.sup" > "$CORPUS/rle/pgs-1080p"18+head -c 4096 "$SUP" > "$CORPUS/rle/pgs_sub"
19 echo "ec-pgs seeds written"19 echo "ec-pgs seeds written"
crates/ec-subs/Cargo.tomlmodified+1 -0
@@ -10,5 +10,6 @@ authors.workspace = true
10 ec-core.workspace = true10 ec-core.workspace = true
11 11
12 [dev-dependencies]12 [dev-dependencies]
13+ec-testkit.workspace = true
13 ec-ass = { path = "../ec-ass", version = "0.1.0" }14 ec-ass = { path = "../ec-ass", version = "0.1.0" }
14 ec-pgs = { path = "../ec-pgs", version = "0.1.0" }15 ec-pgs = { path = "../ec-pgs", version = "0.1.0" }
crates/ec-subs/fuzz/seed.shmodified+4 -4
@@ -1,19 +1,19 @@
1 #!/usr/bin/env bash1 #!/usr/bin/env bash
2 # seed.sh: fill fuzz/corpus/<target>/ from the repo's subtitle fixtures.2 # seed.sh: fill fuzz/corpus/<target>/ from the repo's subtitle fixtures.
3 #3 #
4-# fixtures/subs/real.srt seeds srt, markup and ir. A WebVTT twin of it (commas become dots, a4+# subs/TOS-en.srt seeds srt, markup and ir. A WebVTT twin of it (commas become dots, a
5 # WEBVTT header goes on) seeds webvtt, markup and ir. Corpus lives under fuzz/corpus, git-ignored.5 # WEBVTT header goes on) seeds webvtt, markup and ir. Corpus lives under fuzz/corpus, git-ignored.
6 set -euo pipefail6 set -euo pipefail
7 7
8 FUZZ_DIR=$(cd -- "$(dirname -- "$0")" && pwd)8 FUZZ_DIR=$(cd -- "$(dirname -- "$0")" && pwd)
9 ROOT=$(cd -- "$FUZZ_DIR/../../.." && pwd)9 ROOT=$(cd -- "$FUZZ_DIR/../../.." && pwd)
10-SUBS="$ROOT/fixtures/subs"10+SUBS="${EC_FIXTURES:-$ROOT/fixtures}/subs"
11-[ -d "$SUBS" ] || { echo "seed.sh: $SUBS missing; run scripts/link-fixtures.sh" >&2; exit 2; }11+[ -f "$SUBS/TOS-en.srt" ] || { echo "seed.sh: $SUBS/TOS-en.srt missing; run scripts/fixtures.sh" >&2; exit 2; }
12 12
13 CORPUS="$FUZZ_DIR/corpus"13 CORPUS="$FUZZ_DIR/corpus"
14 mkdir -p "$CORPUS"/{srt,webvtt,markup,ir}14 mkdir -p "$CORPUS"/{srt,webvtt,markup,ir}
15 15
16-python3 -I - "$SUBS/real.srt" "$CORPUS" <<'PY'16+python3 -I - "$SUBS/TOS-en.srt" "$CORPUS" <<'PY'
17 import os, sys17 import os, sys
18 18
19 srt, corpus = sys.argv[1], sys.argv[2]19 srt, corpus = sys.argv[1], sys.argv[2]
crates/ec-subs/tests/real_library.rs → crates/ec-subs/tests/open_media.rsrenamed+11 -34
@@ -1,33 +1,15 @@
1-//! The three parsers against streams taken out of the user's own library.1+//! The three parsers against open subtitle media: the Tears of Steel SubRip file, an ASS script
2-//!2+//! generated from it, and a FATE PGS display set.
3-//! Hand-written cases live in the crates' unit tests; what cannot be written by
4-//! hand is a disc's PGS display set or a fansub's thousand-line ASS script.
5-//! `scripts/gen-subtitle-fixtures.sh` extracts them (fixtures are gitignored,
6-//! the script is not), and every test here *skips* when its fixture is absent
7-//! so a fresh clone still runs green.
8-
9-use std::path::PathBuf;
10 3
11 use ec_subs::{SourceFormat, plain_text};4 use ec_subs::{SourceFormat, plain_text};
12 5
13-fn fixture(name: &str) -> Option<Vec<u8>> {6+fn fixture(rel: &str) -> Vec<u8> {
14- let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))7+ std::fs::read(ec_testkit::fixture(rel)).unwrap()
15- .join("../../fixtures/subs")
16- .join(name);
17- match std::fs::read(&path) {
18- Ok(bytes) => Some(bytes),
19- Err(_) => {
20- eprintln!("skipping: no {name} — run scripts/gen-subtitle-fixtures.sh");
21- None
22- }
23- }
24 }8 }
25 9
26 #[test]10 #[test]
27 fn a_real_subrip_track_parses_whole() {11 fn a_real_subrip_track_parses_whole() {
28- let Some(bytes) = fixture("real.srt") else {12+ let bytes = fixture("subs/TOS-en.srt");
29- return;
30- };
31 let track = ec_subs::srt::parse(&bytes).unwrap();13 let track = ec_subs::srt::parse(&bytes).unwrap();
32 assert_eq!(track.source, Some(SourceFormat::Srt));14 assert_eq!(track.source, Some(SourceFormat::Srt));
33 assert!(track.cues.len() > 100, "{} cues", track.cues.len());15 assert!(track.cues.len() > 100, "{} cues", track.cues.len());
@@ -52,9 +34,7 @@ fn a_real_subrip_track_parses_whole() {
52 34
53 #[test]35 #[test]
54 fn a_real_ass_script_parses_whole() {36 fn a_real_ass_script_parses_whole() {
55- let Some(bytes) = fixture("real.ass") else {37+ let bytes = fixture("subs/tos-en.ass");
56- return;
57- };
58 let track = ec_ass::parse(&bytes).unwrap();38 let track = ec_ass::parse(&bytes).unwrap();
59 assert_eq!(track.source, Some(SourceFormat::AssOrSsa));39 assert_eq!(track.source, Some(SourceFormat::AssOrSsa));
60 assert!(!track.styles.is_empty(), "a script declares styles");40 assert!(!track.styles.is_empty(), "a script declares styles");
@@ -90,9 +70,7 @@ fn a_real_ass_script_parses_whole() {
90 70
91 #[test]71 #[test]
92 fn a_real_pgs_stream_decodes_to_plausible_bitmaps() {72 fn a_real_pgs_stream_decodes_to_plausible_bitmaps() {
93- let Some(bytes) = fixture("pgs-1080p.sup") else {73+ let bytes = fixture("open/fate/sub/pgs_sub.sup");
94- return;
95- };
96 let mut decoder = ec_pgs::PgsDecoder::new();74 let mut decoder = ec_pgs::PgsDecoder::new();
97 decoder.push(&bytes).unwrap();75 decoder.push(&bytes).unwrap();
98 let mut frames = 0;76 let mut frames = 0;
@@ -100,10 +78,9 @@ fn a_real_pgs_stream_decodes_to_plausible_bitmaps() {
100 let mut coverage_max = 0.0f64;78 let mut coverage_max = 0.0f64;
101 while let Some(frame) = decoder.take_frame() {79 while let Some(frame) = decoder.take_frame() {
102 frames += 1;80 frames += 1;
103- // A disc composes against its own video frame, and this one is HD.81+ let (w, h) = (frame.width as usize, frame.height as usize);
104- assert_eq!((frame.width, frame.height), (1920, 1080));
105 let stride = frame.planes[0].stride;82 let stride = frame.planes[0].stride;
106- assert_eq!(stride, 1920 * 4);83+ assert_eq!(stride, w * 4);
107 let opaque = frame.planes[0]84 let opaque = frame.planes[0]
108 .data85 .data
109 .as_chunks::<4>()86 .as_chunks::<4>()
@@ -116,7 +93,7 @@ fn a_real_pgs_stream_decodes_to_plausible_bitmaps() {
116 continue;93 continue;
117 }94 }
118 painted += 1;95 painted += 1;
119- let coverage = opaque as f64 / (1920.0 * 1080.0);96+ let coverage = opaque as f64 / (w * h) as f64;
120 coverage_max = coverage_max.max(coverage);97 coverage_max = coverage_max.max(coverage);
121 // Subtitles are lines of text over a film: ink, not a filled canvas.98 // Subtitles are lines of text over a film: ink, not a filled canvas.
122 assert!(99 assert!(
@@ -125,7 +102,7 @@ fn a_real_pgs_stream_decodes_to_plausible_bitmaps() {
125 coverage * 100.0102 coverage * 100.0
126 );103 );
127 // The ink sits in the lower or upper band, never as a single stray row.104 // The ink sits in the lower or upper band, never as a single stray row.
128- let rows = (0..1080)105+ let rows = (0..h)
129 .filter(|y| {106 .filter(|y| {
130 frame.planes[0].data[y * stride..(y + 1) * stride]107 frame.planes[0].data[y * stride..(y + 1) * stride]
131 .as_chunks::<4>()108 .as_chunks::<4>()