forge
Explore
Log in

Don't you dare go Hollow

Merge simplify/w0-m8 (ec-image stills: committed tests/data/stills, no skips)

Browse files at this commit

83b74a41d377a281db573c90f20acbd787c11937Ahmet Kaan GümüşParent: 74f088c035372f
Cargo.lockmodified+6 -0
@@ -368,6 +368,7 @@ version = "0.1.0"
368368 dependencies = [
369369 "ec-core",
370370 "ec-subs",
371+ "ec-testkit",
371372 ]
372373
373374 [[package]]
@@ -423,6 +424,7 @@ dependencies = [
423424 "ec-h264-syntax",
424425 "ec-h265-syntax",
425426 "ec-subs",
427+ "ec-testkit",
426428 ]
427429
428430 [[package]]
@@ -473,6 +475,7 @@ dependencies = [
473475 "ec-core",
474476 "ec-matroska",
475477 "ec-mpegts",
478+ "ec-testkit",
476479 ]
477480
478481 [[package]]
@@ -483,6 +486,7 @@ dependencies = [
483486 "ec-matroska",
484487 "ec-mp4",
485488 "ec-mpegts",
489+ "ec-testkit",
486490 ]
487491
488492 [[package]]
@@ -555,6 +559,7 @@ version = "0.1.0"
555559 dependencies = [
556560 "ec-core",
557561 "ec-inflate",
562+ "ec-testkit",
558563 "image 0.25.10 (registry+https://github.com/rust-lang/crates.io-index)",
559564 "tracking-allocator",
560565 ]
@@ -730,6 +735,7 @@ dependencies = [
730735 "ec-ass",
731736 "ec-core",
732737 "ec-pgs",
738+ "ec-testkit",
733739 ]
734740
735741 [[package]]
crates/ec-ass/Cargo.tomlmodified+3 -0
@@ -9,3 +9,6 @@ authors.workspace = true
99 [dependencies]
1010 ec-core.workspace = true
1111 ec-subs = { path = "../ec-subs", version = "0.1.0" }
12+
13+[dev-dependencies]
14+ec-testkit.workspace = true
crates/ec-ass/fuzz/seed.shmodified+3 -8
@@ -1,20 +1,15 @@
11 #!/usr/bin/env bash
2-# seed.sh: fill fuzz/corpus/<target>/ from the repo's ASS fixture.
3-#
4-# fixtures/subs/real.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 gets
6-# the Style rows. Corpus lives under fuzz/corpus, git-ignored.
72 set -euo pipefail
83
94 FUZZ_DIR=$(cd -- "$(dirname -- "$0")" && pwd)
105 ROOT=$(cd -- "$FUZZ_DIR/../../.." && pwd)
11-SUBS="$ROOT/fixtures/subs"
12-[ -d "$SUBS" ] || { echo "seed.sh: $SUBS missing; run scripts/link-fixtures.sh" >&2; exit 2; }
6+SUBS="${EC_FIXTURES:-$ROOT/fixtures}/subs"
7+[ -f "$SUBS/tos-en.ass" ] || { echo "seed.sh: $SUBS/tos-en.ass missing; run scripts/fixtures.sh" >&2; exit 2; }
138
149 CORPUS="$FUZZ_DIR/corpus"
1510 mkdir -p "$CORPUS"/{script,styles,events,overrides}
1611
17-python3 -I - "$SUBS/real.ass" "$CORPUS" <<'PY'
12+python3 -I - "$SUBS/tos-en.ass" "$CORPUS" <<'PY'
1813 import os, sys
1914
2015 ass, corpus = sys.argv[1], sys.argv[2]
crates/ec-ass/tests/ffmpeg_parity.rsmodified+2 -25
@@ -9,11 +9,8 @@
99 //! `reordered_format.ass` is not compared with ffmpeg. Its demuxer produces no packets at all for a
1010 //! script whose Events `Format:` line puts Start before Layer, so there is nothing to compare. Its
1111 //! expectations are written out by hand instead.
12-//!
13-//! The ffmpeg tests skip loudly when `ffmpeg` or `ffprobe` is not on PATH.
1412
1513 use std::path::{Path, PathBuf};
16-use std::process::Command;
1714
1815 use ec_ass::parse;
1916 use ec_subs::{Segment, SubtitleCue, TextAlign, plain_text};
@@ -40,23 +37,6 @@ fn fixture(name: &str) -> Vec<u8> {
4037 std::fs::read(&path).unwrap_or_else(|e| panic!("reading {}: {e}", path.display()))
4138 }
4239
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-
6040 /// Seconds in ffprobe's decimal form to whole milliseconds.
6141 fn ms(seconds: &str) -> i64 {
6242 (seconds.trim().parse::<f64>().expect("seconds") * 1000.0).round() as i64
@@ -64,7 +44,7 @@ fn ms(seconds: &str) -> i64 {
6444
6545 /// `(start_ms, end_ms)` per packet, in the order ffprobe lists them.
6646 fn ffprobe_spans(path: &Path) -> Vec<(i64, i64)> {
67- let out = Command::new("ffprobe")
47+ let out = ec_testkit::ffprobe()
6848 .args([
6949 "-v",
7050 "error",
@@ -101,7 +81,7 @@ fn ffprobe_spans(path: &Path) -> Vec<(i64, i64)> {
10181
10282 /// ffmpeg's SRT rendering of the script's cues, words only.
10383 fn ffmpeg_srt(path: &Path) -> String {
104- let out = Command::new("ffmpeg")
84+ let out = ec_testkit::ffmpeg()
10585 .args(["-v", "error", "-nostdin", "-i"])
10686 .arg(path)
10787 .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)> {
169149
170150 #[test]
171151 fn cues_match_ffmpeg_timing_order_and_text() {
172- if !ffmpeg_available() {
173- return;
174- }
175152 for name in FFMPEG_FIXTURES {
176153 let path = data_path(name);
177154 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
1111 ec-subs = { path = "../ec-subs", version = "0.1.0" }
1212 ec-h264-syntax.workspace = true
1313 ec-h265-syntax.workspace = true
14+
15+[dev-dependencies]
16+ec-testkit.workspace = true
crates/ec-cc/tests/streams.rsmodified+19 -62
@@ -1,35 +1,11 @@
1-//! 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 own
3-//! caption decoder. Needs ffmpeg + ffprobe; skipped without them unless EC_REQUIRE_FIXTURES=1.
4-
51 use ec_cc::extract::{H264Extractor, HevcExtractor, Mpeg2Extractor, NalFormat};
62 use ec_cc::synth::*;
73 use ec_cc::{CcTriplet, decode_all};
84 use ec_subs::plain_text;
95 use std::path::PathBuf;
10-use std::process::Command;
116
127 const FRAMES: usize = 90;
138
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-
339 fn tmp(name: &str) -> PathBuf {
3410 let d = std::env::temp_dir().join(format!("ec-cc-{}", std::process::id()));
3511 std::fs::create_dir_all(&d).unwrap();
@@ -63,7 +39,7 @@ fn caption_frames() -> Vec<Vec<CcTriplet>> {
6339 /// Encode a testsrc clip into mkv, return (mkv path, decode-order display indices).
6440 fn encode(codec: &[&str], name: &str) -> (PathBuf, Vec<usize>) {
6541 let mkv = tmp(&format!("{name}.mkv"));
66- let st = Command::new("ffmpeg")
42+ let st = ec_testkit::ffmpeg()
6743 .args([
6844 "-v",
6945 "error",
@@ -79,7 +55,7 @@ fn encode(codec: &[&str], name: &str) -> (PathBuf, Vec<usize>) {
7955 .status()
8056 .unwrap();
8157 assert!(st.success());
82- let out = Command::new("ffprobe")
58+ let out = ec_testkit::ffprobe()
8359 .args([
8460 "-v",
8561 "error",
@@ -109,7 +85,7 @@ fn encode(codec: &[&str], name: &str) -> (PathBuf, Vec<usize>) {
10985
11086 fn raw(mkv: &PathBuf, fmt: &str, bsf: Option<&str>, name: &str) -> PathBuf {
11187 let out = tmp(name);
112- let mut c = Command::new("ffmpeg");
88+ let mut c = ec_testkit::ffmpeg();
11389 c.args(["-v", "error", "-y", "-i"])
11490 .arg(mkv)
11591 .args(["-c:v", "copy", "-an"]);
@@ -145,42 +121,38 @@ fn check(timed: &[ec_cc::TimedCc], captions: &[Vec<CcTriplet>]) {
145121 );
146122 }
147123
148-fn ffmpeg_cues(path: &PathBuf, demuxer_args: &[&str]) -> Option<Vec<(String, f64)>> {
124+fn ffmpeg_cues(path: &PathBuf, demuxer_args: &[&str]) -> Vec<(String, f64)> {
149125 let srt = tmp("ff.srt");
150126 let mkv = tmp("remux.mp4");
151- let st = Command::new("ffmpeg")
127+ let st = ec_testkit::ffmpeg()
152128 .args(["-v", "error", "-y", "-framerate", "30", "-i"])
153129 .arg(path)
154130 .args(["-c", "copy"])
155131 .arg(&mkv)
156132 .status()
157- .ok()?;
158- if !st.success() {
159- return None;
160- }
133+ .unwrap();
134+ assert!(st.success());
161135 let spec = format!("movie={}[out0+subcc]", mkv.display());
162- let st = Command::new("ffmpeg")
136+ let st = ec_testkit::ffmpeg()
163137 .args(["-v", "error", "-y"])
164138 .args(demuxer_args)
165139 .args(["-f", "lavfi", "-i", &spec, "-map", "0:s:0", "-f", "srt"])
166140 .arg(&srt)
167141 .status()
168- .ok()?;
169- if !st.success() {
170- return None;
171- }
172- let text = std::fs::read_to_string(&srt).ok()?;
142+ .unwrap();
143+ assert!(st.success());
144+ let text = std::fs::read_to_string(&srt).unwrap();
173145 let mut out = Vec::new();
174146 for block in text.split("\n\n") {
175147 let mut l = block.lines();
176- l.next()?;
148+ l.next().unwrap();
177149 let Some(tl) = l.next() else { continue };
178- let start = tl.split(" --> ").next()?;
179- let secs = parse_srt(start)?;
150+ let start = tl.split(" --> ").next().unwrap();
151+ let secs = parse_srt(start);
180152 let body: Vec<&str> = l.collect();
181153 out.push((strip(&body.join("\n")), secs));
182154 }
183- Some(out)
155+ out
184156 }
185157
186158 fn strip(s: &str) -> String {
@@ -197,17 +169,14 @@ fn strip(s: &str) -> String {
197169 o.trim().to_string()
198170 }
199171
200-fn parse_srt(s: &str) -> Option<f64> {
201- let (hms, ms) = s.trim().split_once(',')?;
172+fn parse_srt(s: &str) -> f64 {
173+ let (hms, ms) = s.trim().split_once(',').unwrap();
202174 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)
175+ p[0] * 3600.0 + p[1] * 60.0 + p[2] + ms.parse::<f64>().unwrap() / 1000.0
204176 }
205177
206178 fn compare_with_ffmpeg(timed: &[ec_cc::TimedCc], path: &PathBuf) {
207- let Some(theirs) = ffmpeg_cues(path, &[]) else {
208- eprintln!("ffmpeg subcc extraction unavailable; skipped comparison");
209- return;
210- };
179+ let theirs = ffmpeg_cues(path, &[]);
211180 let ours = decode_all(timed).cea608;
212181 assert!(!theirs.is_empty(), "ffmpeg found no captions");
213182 assert_eq!(
@@ -233,9 +202,6 @@ fn compare_with_ffmpeg(timed: &[ec_cc::TimedCc], path: &PathBuf) {
233202
234203 #[test]
235204 fn h264_with_b_frames() {
236- if !require() {
237- return;
238- }
239205 let (mkv, idx) = encode(
240206 &[
241207 "-c:v",
@@ -268,9 +234,6 @@ fn h264_with_b_frames() {
268234
269235 #[test]
270236 fn h264_with_container_pts_in_decode_order() {
271- if !require() {
272- return;
273- }
274237 let (mkv, idx) = encode(&["-c:v", "libx264", "-bf", "2", "-g", "30"], "h264pts");
275238 let ann = raw(&mkv, "h264", Some("h264_mp4toannexb"), "b.264");
276239 let caps = caption_frames();
@@ -287,9 +250,6 @@ fn h264_with_container_pts_in_decode_order() {
287250
288251 #[test]
289252 fn hevc_with_b_frames() {
290- if !require() {
291- return;
292- }
293253 let (mkv, idx) = encode(
294254 &[
295255 "-c:v",
@@ -317,9 +277,6 @@ fn hevc_with_b_frames() {
317277
318278 #[test]
319279 fn mpeg2_atsc_and_dvd_user_data() {
320- if !require() {
321- return;
322- }
323280 let (mkv, idx) = encode(&["-c:v", "mpeg2video", "-bf", "2", "-g", "12"], "m2v");
324281 let es = std::fs::read(raw(&mkv, "mpeg2video", None, "a.m2v")).unwrap();
325282 let caps = caption_frames();
crates/ec-dvbsub/Cargo.tomlmodified+1 -0
@@ -10,5 +10,6 @@ authors.workspace = true
1010 ec-core.workspace = true
1111
1212 [dev-dependencies]
13+ec-testkit.workspace = true
1314 ec-matroska.workspace = true
1415 ec-mpegts.workspace = true
crates/ec-dvbsub/tests/ffmpeg_parity.rsmodified+8 -25
@@ -1,13 +1,6 @@
1-//! Our DVB subtitle decode against ffmpeg's (sub2video frames: `[0:s:0]` out as raw RGBA).
2-//!
3-//! 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, and
5-//! with `EC_REQUIRE_FIXTURES=1` a missing ffmpeg fails.
6-
71 use std::fs::File;
82 use std::io::BufReader;
93 use std::path::PathBuf;
10-use std::process::Command;
114
125 use ec_core::{Decoder, Demuxer, Error};
136 use ec_dvbsub::DvbSubDecoder;
@@ -21,8 +14,8 @@ struct Oracle {
2114 frames: Vec<(f64, Vec<u8>)>,
2215 }
2316
24-fn oracle(path: &PathBuf, w: usize, h: usize) -> Option<Oracle> {
25- let out = Command::new("ffmpeg")
17+fn oracle(path: &PathBuf, w: usize, h: usize) -> Oracle {
18+ let out = ec_testkit::ffmpeg()
2619 .args(["-v", "info", "-nostdin", "-canvas_size", &format!("{w}x{h}"), "-i"])
2720 .arg(path)
2821 .args([
@@ -38,18 +31,8 @@ fn oracle(path: &PathBuf, w: usize, h: usize) -> Option<Oracle> {
3831 "rgba",
3932 "-",
4033 ])
41- .output();
42- let out = match out {
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- };
34+ .output()
35+ .expect("ffmpeg runs");
5336 assert!(out.status.success(), "ffmpeg failed: {}", String::from_utf8_lossy(&out.stderr));
5437 let text = String::from_utf8_lossy(&out.stderr);
5538 let times: Vec<f64> = text
@@ -59,13 +42,13 @@ fn oracle(path: &PathBuf, w: usize, h: usize) -> Option<Oracle> {
5942 .collect();
6043 let fsize = w * h * 4;
6144 assert_eq!(out.stdout.len(), times.len() * fsize, "frame count mismatch");
62- Some(Oracle {
45+ Oracle {
6346 frames: times
6447 .iter()
6548 .enumerate()
6649 .map(|(i, &t)| (t, out.stdout[i * fsize..(i + 1) * fsize].to_vec()))
6750 .collect(),
68- })
51+ }
6952 }
7053
7154 fn blank(f: &[u8]) -> bool {
@@ -142,7 +125,7 @@ fn compare(ours: &[(Vec<u8>, f64, Option<f64>)], o: &Oracle, what: &str) {
142125 #[test]
143126 fn mkv_dvbsub_matches_ffmpeg() {
144127 let path = data("dvb.mkv");
145- let Some(o) = oracle(&path, 720, 576) else { return };
128+ let o = oracle(&path, 720, 576);
146129 let mut d = ec_matroska::MatroskaDemuxer::new(BufReader::new(File::open(&path).unwrap())).unwrap();
147130 assert_eq!(d.streams()[0].params.codec, ec_core::CodecId::DvbSub);
148131 let ours = run_packets(&mut d, 0);
@@ -152,7 +135,7 @@ fn mkv_dvbsub_matches_ffmpeg() {
152135 #[test]
153136 fn ts_private_pes_matches_ffmpeg() {
154137 let path = data("dvb.ts");
155- let Some(o) = oracle(&path, 720, 576) else { return };
138+ let o = oracle(&path, 720, 576);
156139 let mut d = ec_mpegts::TsDemuxer::new(BufReader::new(File::open(&path).unwrap())).unwrap();
157140 let sub = d
158141 .streams()
crates/ec-dvdsub/Cargo.tomlmodified+1 -0
@@ -10,6 +10,7 @@ authors.workspace = true
1010 ec-core.workspace = true
1111
1212 [dev-dependencies]
13+ec-testkit.workspace = true
1314 ec-matroska.workspace = true
1415 ec-mpegts.workspace = true
1516 ec-mp4.workspace = true
crates/ec-dvdsub/tests/ffmpeg_parity.rsmodified+11 -28
@@ -1,13 +1,6 @@
1-//! Our subpicture decode against ffmpeg's (sub2video frames: `[0:s:0]` out as raw RGBA).
2-//!
3-//! 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, and
5-//! with `EC_REQUIRE_FIXTURES=1` a missing ffmpeg fails.
6-
71 use std::fs::File;
82 use std::io::BufReader;
93 use std::path::PathBuf;
10-use std::process::Command;
114
125 use ec_core::{Demuxer, Error, Frame, Decoder};
136 use ec_dvdsub::{DvdSubDecoder, parse_idx, sub_file_units};
@@ -21,8 +14,8 @@ struct Oracle {
2114 frames: Vec<(f64, Vec<u8>)>,
2215 }
2316
24-fn oracle(path: &PathBuf, w: usize, h: usize) -> Option<Oracle> {
25- let out = Command::new("ffmpeg")
17+fn oracle(path: &PathBuf, w: usize, h: usize) -> Oracle {
18+ let out = ec_testkit::ffmpeg()
2619 .args(["-v", "info", "-nostdin", "-canvas_size", &format!("{w}x{h}"), "-i"])
2720 .arg(path)
2821 .args([
@@ -38,18 +31,8 @@ fn oracle(path: &PathBuf, w: usize, h: usize) -> Option<Oracle> {
3831 "rgba",
3932 "-",
4033 ])
41- .output();
42- let out = match out {
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- };
34+ .output()
35+ .expect("ffmpeg runs");
5336 assert!(out.status.success(), "ffmpeg failed: {}", String::from_utf8_lossy(&out.stderr));
5437 let text = String::from_utf8_lossy(&out.stderr);
5538 let times: Vec<f64> = text
@@ -59,13 +42,13 @@ fn oracle(path: &PathBuf, w: usize, h: usize) -> Option<Oracle> {
5942 .collect();
6043 let fsize = w * h * 4;
6144 assert_eq!(out.stdout.len(), times.len() * fsize, "frame count mismatch");
62- Some(Oracle {
45+ Oracle {
6346 frames: times
6447 .iter()
6548 .enumerate()
6649 .map(|(i, &t)| (t, out.stdout[i * fsize..(i + 1) * fsize].to_vec()))
6750 .collect(),
68- })
51+ }
6952 }
7053
7154 fn blank(f: &[u8]) -> bool {
@@ -136,7 +119,7 @@ fn run_packets(
136119 #[test]
137120 fn mkv_vobsub_matches_ffmpeg() {
138121 let path = data("dvd.mkv");
139- let Some(o) = oracle(&path, 720, 576) else { return };
122+ let o = oracle(&path, 720, 576);
140123 let mut d = ec_matroska::MatroskaDemuxer::new(BufReader::new(File::open(&path).unwrap())).unwrap();
141124 let info = &d.streams()[0];
142125 let extra = info.params.extradata.as_deref().map(<[u8]>::to_vec);
@@ -148,13 +131,13 @@ fn mkv_vobsub_matches_ffmpeg() {
148131 compare(&ours, &o, "mkv");
149132 }
150133
151-fn mkv_oracle() -> Option<Oracle> {
134+fn mkv_oracle() -> Oracle {
152135 oracle(&data("dvd.mkv"), 720, 576)
153136 }
154137
155138 #[test]
156139 fn vob_private_stream_1_matches_ffmpeg() {
157- let Some(o) = mkv_oracle() else { return };
140+ let o = mkv_oracle();
158141 let path = data("dvd.vob");
159142 let mut d = ec_mpegts::PsDemuxer::new(BufReader::new(File::open(&path).unwrap())).unwrap();
160143 let sub = d
@@ -169,7 +152,7 @@ fn vob_private_stream_1_matches_ffmpeg() {
169152
170153 #[test]
171154 fn mp4s_esds_matches_ffmpeg() {
172- let Some(o) = mkv_oracle() else { return };
155+ let o = mkv_oracle();
173156 let path = data("dvd.mp4");
174157 let mut d = ec_mp4::Mp4Demuxer::new(BufReader::new(File::open(&path).unwrap())).unwrap();
175158 let sub = d
@@ -186,7 +169,7 @@ fn mp4s_esds_matches_ffmpeg() {
186169
187170 #[test]
188171 fn idx_sub_pair_matches_ffmpeg() {
189- let Some(o) = mkv_oracle() else { return };
172+ let o = mkv_oracle();
190173 let idx = parse_idx(&std::fs::read(data("dvd.idx")).unwrap());
191174 assert_eq!(idx.size, Some((720, 576)));
192175 assert_eq!(idx.languages, vec![("en".to_string(), 0)]);
crates/ec-image/Cargo.tomlmodified+1 -0
@@ -11,6 +11,7 @@ ec-core = { workspace = true }
1111 ec-inflate = { workspace = true }
1212
1313 [dev-dependencies]
14+ec-testkit.workspace = true
1415 # The incumbent, as a differential oracle only: every test decodes the same
1516 # bytes both ways and compares pixels. Running it is the point; nothing is
1617 # copied from it.
crates/ec-image/src/gif_encode.rsmodified+2 -8
@@ -739,20 +739,14 @@ mod tests {
739739 }
740740
741741 #[test]
742- fn ffprobe_reads_the_output_when_it_is_installed() {
743- let probe = std::process::Command::new("ffprobe")
744- .arg("-version")
745- .output();
746- if probe.is_err() {
747- return;
748- }
742+ fn ffprobe_reads_the_output() {
749743 let px: Vec<u8> = (0..8 * 4)
750744 .flat_map(|i: u8| [i * 8, 128, 255 - i * 8, 255])
751745 .collect();
752746 let gif = encode_frames(8, 4, GifOptions::default(), &[(&px, 5), (&px, 5)]);
753747 let path = std::env::temp_dir().join(format!("ec-gif-encode-{}.gif", std::process::id()));
754748 std::fs::write(&path, &gif).unwrap();
755- let out = std::process::Command::new("ffprobe")
749+ let out = ec_testkit::ffprobe()
756750 .args(["-v", "error", "-select_streams", "v:0", "-show_entries"])
757751 .args(["stream=width,height", "-of", "csv=p=0"])
758752 .arg(&path)
crates/ec-image/tests/fuzz.rsmodified+3 -12
@@ -190,10 +190,7 @@ fn repair_png_crcs(data: &mut [u8]) {
190190 fn sweep(name: &str, seed_file: &str) {
191191 // Mutated headers can claim canvases up to the budget, so a sweep is heavy too.
192192 let _heavy = heavy();
193- let Ok(seed) = std::fs::read(fixtures().join(seed_file)) else {
194- eprintln!("skipped: tests/data/stills missing");
195- return;
196- };
193+ let seed = std::fs::read(fixtures().join(seed_file)).unwrap();
197194 let mut rng = Rng(0x2545_f491_4f6c_dd1d ^ name.len() as u64);
198195 let mut decoded = 0usize;
199196 for round in 0..ROUNDS {
@@ -263,10 +260,7 @@ fn single_seed_sweeps_survive_mutation() {
263260 /// disposal state machine, none of which `decode` reaches past frame one.
264261 #[test]
265262 fn a_gif_animation_survives_mutation() {
266- let Ok(seed) = std::fs::read(fixtures().join("animated.gif")) else {
267- eprintln!("skipped: tests/data/stills missing");
268- return;
269- };
263+ let seed = std::fs::read(fixtures().join("animated.gif")).unwrap();
270264 let _heavy = heavy();
271265 let mut rng = Rng(0x2545_f491_4f6c_dd1d ^ 0x9e37);
272266 let mut decoded = 0usize;
@@ -292,10 +286,7 @@ fn a_gif_animation_survives_mutation() {
292286 /// canvas sized by a different chunk, so a mutation can make the two disagree.
293287 #[test]
294288 fn an_animated_webp_survives_mutation() {
295- let Ok(seed) = std::fs::read(fixtures().join("anim-alpha.webp")) else {
296- eprintln!("skipped: tests/data/stills missing");
297- return;
298- };
289+ let seed = std::fs::read(fixtures().join("anim-alpha.webp")).unwrap();
299290 let _heavy = heavy();
300291 let mut rng = Rng(0x2545_f491_4f6c_dd1d ^ 0x5eed);
301292 let mut decoded = 0usize;
crates/ec-image/tests/it/differential.rsmodified+24 -83
@@ -42,11 +42,6 @@ fn corpus(extension: &str) -> Vec<PathBuf> {
4242 found
4343 }
4444
45-fn skip(what: &str) -> bool {
46- eprintln!("skipped: tests/data/stills missing ({what})");
47- true
48-}
49-
5045 /// Largest per-sample difference and Pearson correlation between two buffers.
5146 fn compare(ours: &[u8], theirs: &[u8]) -> (u32, f64) {
5247 assert_eq!(ours.len(), theirs.len(), "sample counts differ");
@@ -93,9 +88,7 @@ fn psnr(a: &[u8], b: &[u8]) -> f64 {
9388 #[test]
9489 fn png_decodes_pixel_exactly() {
9590 let files = corpus("png");
96- if files.is_empty() && skip("png") {
97- return;
98- }
91+ assert!(!files.is_empty(), "no png stills");
9992 for path in files {
10093 let bytes = std::fs::read(&path).unwrap();
10194 let ours = ec_image::decode(&bytes).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
@@ -126,9 +119,7 @@ fn webp_lossless_decodes_pixel_exactly() {
126119 .into_iter()
127120 .filter(|p| name_of(p).contains("lossless"))
128121 .collect();
129- if files.is_empty() && skip("webp") {
130- return;
131- }
122+ assert!(!files.is_empty(), "no webp stills");
132123 for path in files {
133124 let bytes = std::fs::read(&path).unwrap();
134125 let ours = ec_image::decode(&bytes).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
@@ -151,9 +142,7 @@ fn webp_lossless_decodes_pixel_exactly() {
151142 #[test]
152143 fn jpeg_matches_the_incumbent_within_rounding() {
153144 let files = corpus("jpg");
154- if files.is_empty() && skip("jpg") {
155- return;
156- }
145+ assert!(!files.is_empty(), "no jpg stills");
157146 let mut worst = 0u32;
158147 for path in files {
159148 let bytes = std::fs::read(&path).unwrap();
@@ -194,9 +183,7 @@ fn webp_lossy_reconstructs_at_least_as_well_as_the_incumbent() {
194183 .into_iter()
195184 .filter(|p| name_of(p).contains("lossy"))
196185 .collect();
197- if files.is_empty() && skip("webp") {
198- return;
199- }
186+ assert!(!files.is_empty(), "no webp stills");
200187 let mut shortfalls: Vec<String> = Vec::new();
201188 for path in files {
202189 let name = path.file_name().unwrap().to_string_lossy().to_string();
@@ -258,18 +245,13 @@ fn header_dimensions_match_the_incumbent() {
258245 checked += 1;
259246 }
260247 }
261- if checked == 0 {
262- skip("any");
263- }
248+ assert!(checked > 0, "no stills");
264249 }
265250
266251 #[test]
267252 fn an_animated_webp_is_refused_by_name() {
268253 let path = fixtures().join("animated.webp");
269- let Ok(bytes) = std::fs::read(&path) else {
270- skip("animated.webp");
271- return;
272- };
254+ let bytes = std::fs::read(&path).unwrap();
273255 let err = ec_image::decode(&bytes).expect_err("an animation is not a still");
274256 let message = format!("{err}");
275257 assert!(message.contains("animated"), "{message}");
@@ -302,10 +284,7 @@ fn with_exif_orientation(jpeg: &[u8], orientation: u16) -> Vec<u8> {
302284
303285 #[test]
304286 fn exif_orientation_is_reported_and_not_applied() {
305- let Ok(plain) = std::fs::read(fixtures().join("baseline-444.jpg")) else {
306- skip("baseline-444.jpg");
307- return;
308- };
287+ let plain = std::fs::read(fixtures().join("baseline-444.jpg")).unwrap();
309288 let bytes = with_exif_orientation(&plain, 6);
310289 let ours = ec_image::decode(&bytes).unwrap();
311290 let theirs = image::load_from_memory(&bytes).unwrap();
@@ -344,10 +323,7 @@ fn every_fixture_decodes() {
344323 }
345324 }
346325 }
347- if count == 0 {
348- skip("any");
349- return;
350- }
326+ assert!(count > 0, "no stills");
351327 assert!(
352328 failures.is_empty(),
353329 "{} failed:\n{}",
@@ -359,9 +335,7 @@ fn every_fixture_decodes() {
359335 #[test]
360336 fn gif_decodes_pixel_exactly() {
361337 let files = corpus("gif");
362- if files.is_empty() && skip("gif") {
363- return;
364- }
338+ assert!(!files.is_empty(), "no gif stills");
365339 for path in files {
366340 let bytes = std::fs::read(&path).unwrap();
367341 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() {
392366 use image::AnimationDecoder;
393367
394368 let path = fixtures().join("animated.gif");
395- if !path.exists() && skip("animated.gif") {
396- return;
397- }
398369 let bytes = std::fs::read(&path).unwrap();
399370 let ours = ec_image::decode_animation(&bytes).expect("our animation decode");
400371 let theirs: Vec<image::Frame> =
@@ -433,9 +404,6 @@ fn a_gif_animation_composites_frame_for_frame_like_the_incumbent() {
433404 #[test]
434405 fn a_still_of_any_format_is_one_frame_of_animation() {
435406 let path = fixtures().join("rgb8.png");
436- if !path.exists() && skip("rgb8.png") {
437- return;
438- }
439407 let bytes = std::fs::read(&path).unwrap();
440408 let frames = ec_image::decode_animation(&bytes).expect("decode");
441409 assert_eq!(frames.len(), 1);
@@ -455,10 +423,7 @@ fn one_animated_webp(fixture: &str) {
455423 use image::AnimationDecoder;
456424
457425 let path = fixtures().join(fixture);
458- let Ok(bytes) = std::fs::read(&path) else {
459- skip(fixture);
460- return;
461- };
426+ let bytes = std::fs::read(&path).unwrap();
462427 assert!(
463428 ec_image::webp::is_animated(&bytes),
464429 "the fixture is not an animation"
@@ -516,18 +481,12 @@ fn one_animated_webp(fixture: &str) {
516481 #[test]
517482 fn webp_disposal_and_blending_match_libwebp() {
518483 let path = fixtures().join("anim-alpha.webp");
519- let Ok(bytes) = std::fs::read(&path) else {
520- skip("anim-alpha.webp");
521- return;
522- };
484+ let bytes = std::fs::read(&path).unwrap();
523485 let goldens: Vec<PathBuf> = (0..)
524486 .map(|i| fixtures().join(format!("anim-alpha-f{i}.png")))
525487 .take_while(|p| p.exists())
526488 .collect();
527- if goldens.is_empty() {
528- skip("anim-alpha-f0.png (libwebp goldens; Pillow not installed?)");
529- return;
530- }
489+ assert!(!goldens.is_empty(), "libwebp goldens missing");
531490
532491 let ours = ec_image::decode_animation(&bytes).expect("our animation decode");
533492 assert_eq!(ours.len(), goldens.len(), "frame count against libwebp");
@@ -555,9 +514,7 @@ fn webp_disposal_and_blending_match_libwebp() {
555514 #[test]
556515 fn bmp_decodes_pixel_exactly() {
557516 let files = corpus("bmp");
558- if files.is_empty() && skip("bmp") {
559- return;
560- }
517+ assert!(!files.is_empty(), "no bmp stills");
561518 for path in files {
562519 let name = path.file_name().unwrap().to_string_lossy().to_string();
563520 if name.starts_with("embedded-") || name == "os2v2.bmp" {
@@ -587,12 +544,7 @@ fn a_bmp_wrapping_another_format_decodes_to_that_format() {
587544 // implementation-defined, so the two decoders round differently.
588545 for (fixture, bar) in [("embedded-png.bmp", 0u32), ("embedded-jpeg.bmp", 5)] {
589546 let path = fixtures().join(fixture);
590- let Ok(data) = std::fs::read(&path) else {
591- if skip(fixture) {
592- return;
593- }
594- unreachable!()
595- };
547+ let data = std::fs::read(&path).unwrap();
596548 // The payload starts where the file header says the pixels do.
597549 let offset = u32::from_le_bytes([data[10], data[11], data[12], data[13]]) as usize;
598550 let payload = &data[offset..];
@@ -622,10 +574,7 @@ fn a_bmp_wrapping_another_format_decodes_to_that_format() {
622574 fn an_os2_v2_header_reads_as_the_same_picture() {
623575 let short = fixtures().join("os2v2.bmp");
624576 let long = fixtures().join("os2v1.bmp");
625- let (Ok(short), Ok(long)) = (std::fs::read(&short), std::fs::read(&long)) else {
626- skip("os2v2.bmp");
627- return;
628- };
577+ let (short, long) = (std::fs::read(&short).unwrap(), std::fs::read(&long).unwrap());
629578 assert!(
630579 image::load_from_memory(&short).is_err(),
631580 "the incumbent now reads a 16-byte header; this test's premise is stale"
@@ -649,9 +598,7 @@ fn tiff_decodes_pixel_exactly() {
649598 let mut files = corpus("tiff");
650599 files.extend(corpus("tif"));
651600 files.sort();
652- if files.is_empty() && skip("tiff") {
653- return;
654- }
601+ assert!(!files.is_empty(), "no tiff stills");
655602 for path in files {
656603 let name = path.file_name().unwrap().to_string_lossy().to_string();
657604 if name == "palette4.tiff" {
@@ -681,13 +628,10 @@ fn tiff_decodes_pixel_exactly() {
681628 /// lossless, so the associated file must decode to the straight one exactly.
682629 #[test]
683630 fn an_associated_alpha_tiff_reads_unpremultiplied() {
684- let (Ok(assoc), Ok(straight)) = (
685- std::fs::read(fixtures().join("rgba8-assoc.tiff")),
686- std::fs::read(fixtures().join("rgba8.tiff")),
687- ) else {
688- skip("rgba8-assoc.tiff");
689- return;
690- };
631+ let (assoc, straight) = (
632+ std::fs::read(fixtures().join("rgba8-assoc.tiff")).unwrap(),
633+ std::fs::read(fixtures().join("rgba8.tiff")).unwrap(),
634+ );
691635 let ours = ec_image::decode(&assoc).expect("rgba8-assoc.tiff");
692636 let reference = ec_image::decode(&straight).expect("rgba8.tiff");
693637 // Under a zero alpha the colour is gone for good -- premultiplying by zero
@@ -721,13 +665,10 @@ fn an_associated_alpha_tiff_reads_unpremultiplied() {
721665 /// when the corpus was generated.
722666 #[test]
723667 fn a_four_bit_tiff_palette_reads_as_ffmpeg_reads_it() {
724- let (Ok(narrow), Ok(wide)) = (
725- std::fs::read(fixtures().join("palette4.tiff")),
726- std::fs::read(fixtures().join("palette4-golden.png")),
727- ) else {
728- skip("palette4.tiff");
729- return;
730- };
668+ let (narrow, wide) = (
669+ std::fs::read(fixtures().join("palette4.tiff")).unwrap(),
670+ std::fs::read(fixtures().join("palette4-golden.png")).unwrap(),
671+ );
731672 assert!(
732673 image::load_from_memory(&narrow).is_err(),
733674 "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() {
366366 fn png_encoder_size_against_image_on_the_still_fixture() {
367367 let path =
368368 std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/data/stills/source.png");
369- let Ok(bytes) = std::fs::read(&path) else {
370- eprintln!("skipped: {} not generated", path.display());
371- return;
372- };
369+ let bytes = std::fs::read(&path).unwrap();
373370 let src = image::load_from_memory(&bytes).unwrap().to_rgb8();
374371 let (w, h) = src.dimensions();
375372 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 @@
44
55 mod differential;
66 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+5 -10
@@ -1,19 +1,14 @@
11 #!/usr/bin/env bash
2-# seed.sh: fill fuzz/corpus/<target>/ from the repo's PGS fixture.
3-#
4-# fixtures/subs/pgs-1080p.sup is a real disc's 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 the
6-# seeds are mostly rejects, which still steer the mutator. Corpus lives under fuzz/corpus.
72 set -euo pipefail
83
94 FUZZ_DIR=$(cd -- "$(dirname -- "$0")" && pwd)
105 ROOT=$(cd -- "$FUZZ_DIR/../../.." && pwd)
11-SUBS="$ROOT/fixtures/subs"
12-[ -f "$SUBS/pgs-1080p.sup" ] || { echo "seed.sh: $SUBS/pgs-1080p.sup missing; run scripts/link-fixtures.sh" >&2; exit 2; }
6+SUP="${EC_FIXTURES:-$ROOT/fixtures}/open/fate/sub/pgs_sub.sup"
7+[ -f "$SUP" ] || { echo "seed.sh: $SUP missing; run scripts/fixtures.sh" >&2; exit 2; }
138
149 CORPUS="$FUZZ_DIR/corpus"
1510 mkdir -p "$CORPUS"/{segments,rle,compose}
16-head -c 65536 "$SUBS/pgs-1080p.sup" > "$CORPUS/segments/pgs-1080p"
17-head -c 4096 "$SUBS/pgs-1080p.sup" > "$CORPUS/compose/pgs-1080p"
18-head -c 4096 "$SUBS/pgs-1080p.sup" > "$CORPUS/rle/pgs-1080p"
11+head -c 65536 "$SUP" > "$CORPUS/segments/pgs_sub"
12+head -c 4096 "$SUP" > "$CORPUS/compose/pgs_sub"
13+head -c 4096 "$SUP" > "$CORPUS/rle/pgs_sub"
1914 echo "ec-pgs seeds written"
crates/ec-subs/Cargo.tomlmodified+1 -0
@@ -10,5 +10,6 @@ authors.workspace = true
1010 ec-core.workspace = true
1111
1212 [dev-dependencies]
13+ec-testkit.workspace = true
1314 ec-ass = { path = "../ec-ass", version = "0.1.0" }
1415 ec-pgs = { path = "../ec-pgs", version = "0.1.0" }
crates/ec-subs/fuzz/seed.shmodified+3 -7
@@ -1,19 +1,15 @@
11 #!/usr/bin/env bash
2-# seed.sh: fill fuzz/corpus/<target>/ from the repo's subtitle fixtures.
3-#
4-# fixtures/subs/real.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.
62 set -euo pipefail
73
84 FUZZ_DIR=$(cd -- "$(dirname -- "$0")" && pwd)
95 ROOT=$(cd -- "$FUZZ_DIR/../../.." && pwd)
10-SUBS="$ROOT/fixtures/subs"
11-[ -d "$SUBS" ] || { echo "seed.sh: $SUBS missing; run scripts/link-fixtures.sh" >&2; exit 2; }
6+SUBS="${EC_FIXTURES:-$ROOT/fixtures}/subs"
7+[ -f "$SUBS/TOS-en.srt" ] || { echo "seed.sh: $SUBS/TOS-en.srt missing; run scripts/fixtures.sh" >&2; exit 2; }
128
139 CORPUS="$FUZZ_DIR/corpus"
1410 mkdir -p "$CORPUS"/{srt,webvtt,markup,ir}
1511
16-python3 -I - "$SUBS/real.srt" "$CORPUS" <<'PY'
12+python3 -I - "$SUBS/TOS-en.srt" "$CORPUS" <<'PY'
1713 import os, sys
1814
1915 srt, corpus = sys.argv[1], sys.argv[2]
crates/ec-subs/tests/real_library.rs → crates/ec-subs/tests/open_media.rsrenamed+9 -44
@@ -1,38 +1,16 @@
1-//! The three parsers against streams taken out of the user's own library.
2-//!
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-
111 use ec_subs::{SourceFormat, plain_text};
122
13-fn fixture(name: &str) -> Option<Vec<u8>> {
14- let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
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- }
3+fn fixture(rel: &str) -> Vec<u8> {
4+ std::fs::read(ec_testkit::fixture(rel)).unwrap()
245 }
256
267 #[test]
278 fn a_real_subrip_track_parses_whole() {
28- let Some(bytes) = fixture("real.srt") else {
29- return;
30- };
9+ let bytes = fixture("subs/TOS-en.srt");
3110 let track = ec_subs::srt::parse(&bytes).unwrap();
3211 assert_eq!(track.source, Some(SourceFormat::Srt));
3312 assert!(track.cues.len() > 100, "{} cues", track.cues.len());
3413 assert_eq!(track.skipped, 0, "a whole file should have no torn blocks");
35- // Every cue is up for a positive time and says something.
3614 for cue in &track.cues {
3715 assert!(cue.end_us >= cue.start_us);
3816 assert!(
@@ -41,7 +19,6 @@ fn a_real_subrip_track_parses_whole() {
4119 cue.start_us
4220 );
4321 }
44- // A subtitle track runs forwards.
4522 assert!(
4623 track
4724 .cues
@@ -52,16 +29,12 @@ fn a_real_subrip_track_parses_whole() {
5229
5330 #[test]
5431 fn a_real_ass_script_parses_whole() {
55- let Some(bytes) = fixture("real.ass") else {
56- return;
57- };
32+ let bytes = fixture("subs/tos-en.ass");
5833 let track = ec_ass::parse(&bytes).unwrap();
5934 assert_eq!(track.source, Some(SourceFormat::AssOrSsa));
6035 assert!(!track.styles.is_empty(), "a script declares styles");
6136 assert!(track.cues.len() > 100, "{} cues", track.cues.len());
6237 assert_eq!(track.skipped, 0, "a whole script should have no torn rows");
63- // Every cue names a style the script declared, and most say words: a
64- // signs-and-songs script has drawing-only lines, which are not words.
6538 let with_text = track
6639 .cues
6740 .iter()
@@ -80,19 +53,15 @@ fn a_real_ass_script_parses_whole() {
8053 "cue names undeclared style {style:?}"
8154 );
8255 }
83- // Override tags never leak into the words.
8456 let text = plain_text(&cue.segments);
8557 assert!(!text.contains("{\\"), "override tag in text: {text:?}");
8658 }
87- // The header is replayable as a Matroska `CodecPrivate`.
8859 assert!(track.extradata.windows(8).any(|w| w == b"[Events]"));
8960 }
9061
9162 #[test]
9263 fn a_real_pgs_stream_decodes_to_plausible_bitmaps() {
93- let Some(bytes) = fixture("pgs-1080p.sup") else {
94- return;
95- };
64+ let bytes = fixture("open/fate/sub/pgs_sub.sup");
9665 let mut decoder = ec_pgs::PgsDecoder::new();
9766 decoder.push(&bytes).unwrap();
9867 let mut frames = 0;
@@ -100,10 +69,9 @@ fn a_real_pgs_stream_decodes_to_plausible_bitmaps() {
10069 let mut coverage_max = 0.0f64;
10170 while let Some(frame) = decoder.take_frame() {
10271 frames += 1;
103- // A disc composes against its own video frame, and this one is HD.
104- assert_eq!((frame.width, frame.height), (1920, 1080));
72+ let (w, h) = (frame.width as usize, frame.height as usize);
10573 let stride = frame.planes[0].stride;
106- assert_eq!(stride, 1920 * 4);
74+ assert_eq!(stride, w * 4);
10775 let opaque = frame.planes[0]
10876 .data
10977 .as_chunks::<4>()
@@ -112,20 +80,17 @@ fn a_real_pgs_stream_decodes_to_plausible_bitmaps() {
11280 .filter(|p| p[3] > 0)
11381 .count();
11482 if opaque == 0 {
115- // An erase display set: a set that composes nothing at all.
11683 continue;
11784 }
11885 painted += 1;
119- let coverage = opaque as f64 / (1920.0 * 1080.0);
86+ let coverage = opaque as f64 / (w * h) as f64;
12087 coverage_max = coverage_max.max(coverage);
121- // Subtitles are lines of text over a film: ink, not a filled canvas.
12288 assert!(
12389 coverage > 0.000_1 && coverage < 0.25,
12490 "display set {frames} covers {:.3}% of the canvas",
12591 coverage * 100.0
12692 );
127- // The ink sits in the lower or upper band, never as a single stray row.
128- let rows = (0..1080)
93+ let rows = (0..h)
12994 .filter(|y| {
13095 frame.planes[0].data[y * stride..(y + 1) * stride]
13196 .as_chunks::<4>()