diff --git a/Cargo.lock b/Cargo.lock index 235feddb..f49d960e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -368,6 +368,7 @@ version = "0.1.0" dependencies = [ "ec-core", "ec-subs", + "ec-testkit", ] [[package]] @@ -423,6 +424,7 @@ dependencies = [ "ec-h264-syntax", "ec-h265-syntax", "ec-subs", + "ec-testkit", ] [[package]] @@ -473,6 +475,7 @@ dependencies = [ "ec-core", "ec-matroska", "ec-mpegts", + "ec-testkit", ] [[package]] @@ -483,6 +486,7 @@ dependencies = [ "ec-matroska", "ec-mp4", "ec-mpegts", + "ec-testkit", ] [[package]] @@ -555,6 +559,7 @@ version = "0.1.0" dependencies = [ "ec-core", "ec-inflate", + "ec-testkit", "image 0.25.10 (registry+https://github.com/rust-lang/crates.io-index)", "tracking-allocator", ] @@ -730,6 +735,7 @@ dependencies = [ "ec-ass", "ec-core", "ec-pgs", + "ec-testkit", ] [[package]] diff --git a/crates/ec-ass/Cargo.toml b/crates/ec-ass/Cargo.toml index e8a1fbf5..89b1a351 100644 --- a/crates/ec-ass/Cargo.toml +++ b/crates/ec-ass/Cargo.toml @@ -9,3 +9,6 @@ authors.workspace = true [dependencies] ec-core.workspace = true ec-subs = { path = "../ec-subs", version = "0.1.0" } + +[dev-dependencies] +ec-testkit.workspace = true diff --git a/crates/ec-ass/fuzz/seed.sh b/crates/ec-ass/fuzz/seed.sh index ff61e427..c4665787 100755 --- a/crates/ec-ass/fuzz/seed.sh +++ b/crates/ec-ass/fuzz/seed.sh @@ -1,20 +1,15 @@ #!/usr/bin/env bash -# seed.sh: fill fuzz/corpus// from the repo's ASS fixture. -# -# fixtures/subs/real.ass seeds script whole. events and overrides get its Dialogue rows (the lines -# after the first Dialogue: prefix, which is what each of those targets takes as input). styles gets -# the Style rows. Corpus lives under fuzz/corpus, git-ignored. set -euo pipefail FUZZ_DIR=$(cd -- "$(dirname -- "$0")" && pwd) ROOT=$(cd -- "$FUZZ_DIR/../../.." && pwd) -SUBS="$ROOT/fixtures/subs" -[ -d "$SUBS" ] || { echo "seed.sh: $SUBS missing; run scripts/link-fixtures.sh" >&2; exit 2; } +SUBS="${EC_FIXTURES:-$ROOT/fixtures}/subs" +[ -f "$SUBS/tos-en.ass" ] || { echo "seed.sh: $SUBS/tos-en.ass missing; run scripts/fixtures.sh" >&2; exit 2; } CORPUS="$FUZZ_DIR/corpus" mkdir -p "$CORPUS"/{script,styles,events,overrides} -python3 -I - "$SUBS/real.ass" "$CORPUS" <<'PY' +python3 -I - "$SUBS/tos-en.ass" "$CORPUS" <<'PY' import os, sys ass, corpus = sys.argv[1], sys.argv[2] diff --git a/crates/ec-ass/tests/ffmpeg_parity.rs b/crates/ec-ass/tests/ffmpeg_parity.rs index 17cbd291..35fbabf0 100644 --- a/crates/ec-ass/tests/ffmpeg_parity.rs +++ b/crates/ec-ass/tests/ffmpeg_parity.rs @@ -9,11 +9,8 @@ //! `reordered_format.ass` is not compared with ffmpeg. Its demuxer produces no packets at all for a //! script whose Events `Format:` line puts Start before Layer, so there is nothing to compare. Its //! expectations are written out by hand instead. -//! -//! The ffmpeg tests skip loudly when `ffmpeg` or `ffprobe` is not on PATH. use std::path::{Path, PathBuf}; -use std::process::Command; use ec_ass::parse; use ec_subs::{Segment, SubtitleCue, TextAlign, plain_text}; @@ -40,23 +37,6 @@ fn fixture(name: &str) -> Vec { std::fs::read(&path).unwrap_or_else(|e| panic!("reading {}: {e}", path.display())) } -fn tool_present(tool: &str) -> bool { - Command::new(tool) - .arg("-version") - .output() - .map(|o| o.status.success()) - .unwrap_or(false) -} - -/// Both reference tools, or `None` (with a loud note) when either is missing. -fn ffmpeg_available() -> bool { - if tool_present("ffmpeg") && tool_present("ffprobe") { - return true; - } - eprintln!("SKIP: ffmpeg/ffprobe not on PATH; ASS parity with ffmpeg not checked"); - false -} - /// Seconds in ffprobe's decimal form to whole milliseconds. fn ms(seconds: &str) -> i64 { (seconds.trim().parse::().expect("seconds") * 1000.0).round() as i64 @@ -64,7 +44,7 @@ fn ms(seconds: &str) -> i64 { /// `(start_ms, end_ms)` per packet, in the order ffprobe lists them. fn ffprobe_spans(path: &Path) -> Vec<(i64, i64)> { - let out = Command::new("ffprobe") + let out = ec_testkit::ffprobe() .args([ "-v", "error", @@ -101,7 +81,7 @@ fn ffprobe_spans(path: &Path) -> Vec<(i64, i64)> { /// ffmpeg's SRT rendering of the script's cues, words only. fn ffmpeg_srt(path: &Path) -> String { - let out = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args(["-v", "error", "-nostdin", "-i"]) .arg(path) .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)> { #[test] fn cues_match_ffmpeg_timing_order_and_text() { - if !ffmpeg_available() { - return; - } for name in FFMPEG_FIXTURES { let path = data_path(name); let track = parse(&fixture(name)).unwrap_or_else(|e| panic!("{name}: {e}")); diff --git a/crates/ec-cc/Cargo.toml b/crates/ec-cc/Cargo.toml index 50f1cb74..f80a1a9d 100644 --- a/crates/ec-cc/Cargo.toml +++ b/crates/ec-cc/Cargo.toml @@ -11,3 +11,6 @@ ec-core.workspace = true ec-subs = { path = "../ec-subs", version = "0.1.0" } ec-h264-syntax.workspace = true ec-h265-syntax.workspace = true + +[dev-dependencies] +ec-testkit.workspace = true diff --git a/crates/ec-cc/tests/streams.rs b/crates/ec-cc/tests/streams.rs index 904a63e7..5ec02000 100644 --- a/crates/ec-cc/tests/streams.rs +++ b/crates/ec-cc/tests/streams.rs @@ -1,35 +1,11 @@ -//! End-to-end: synthetic captions spliced into ffmpeg-encoded H.264 / HEVC / MPEG-2 streams -//! (with B-frames), extracted in presentation order, decoded, and compared with ffmpeg's own -//! caption decoder. Needs ffmpeg + ffprobe; skipped without them unless EC_REQUIRE_FIXTURES=1. - use ec_cc::extract::{H264Extractor, HevcExtractor, Mpeg2Extractor, NalFormat}; use ec_cc::synth::*; use ec_cc::{CcTriplet, decode_all}; use ec_subs::plain_text; use std::path::PathBuf; -use std::process::Command; const FRAMES: usize = 90; -fn have(tool: &str) -> bool { - Command::new(tool) - .arg("-version") - .output() - .is_ok_and(|o| o.status.success()) -} - -fn require() -> bool { - if have("ffmpeg") && have("ffprobe") { - return true; - } - assert!( - std::env::var("EC_REQUIRE_FIXTURES").is_err(), - "ffmpeg/ffprobe required" - ); - eprintln!("skipping: no ffmpeg"); - false -} - fn tmp(name: &str) -> PathBuf { let d = std::env::temp_dir().join(format!("ec-cc-{}", std::process::id())); std::fs::create_dir_all(&d).unwrap(); @@ -63,7 +39,7 @@ fn caption_frames() -> Vec> { /// Encode a testsrc clip into mkv, return (mkv path, decode-order display indices). fn encode(codec: &[&str], name: &str) -> (PathBuf, Vec) { let mkv = tmp(&format!("{name}.mkv")); - let st = Command::new("ffmpeg") + let st = ec_testkit::ffmpeg() .args([ "-v", "error", @@ -79,7 +55,7 @@ fn encode(codec: &[&str], name: &str) -> (PathBuf, Vec) { .status() .unwrap(); assert!(st.success()); - let out = Command::new("ffprobe") + let out = ec_testkit::ffprobe() .args([ "-v", "error", @@ -109,7 +85,7 @@ fn encode(codec: &[&str], name: &str) -> (PathBuf, Vec) { fn raw(mkv: &PathBuf, fmt: &str, bsf: Option<&str>, name: &str) -> PathBuf { let out = tmp(name); - let mut c = Command::new("ffmpeg"); + let mut c = ec_testkit::ffmpeg(); c.args(["-v", "error", "-y", "-i"]) .arg(mkv) .args(["-c:v", "copy", "-an"]); @@ -145,42 +121,38 @@ fn check(timed: &[ec_cc::TimedCc], captions: &[Vec]) { ); } -fn ffmpeg_cues(path: &PathBuf, demuxer_args: &[&str]) -> Option> { +fn ffmpeg_cues(path: &PathBuf, demuxer_args: &[&str]) -> Vec<(String, f64)> { let srt = tmp("ff.srt"); let mkv = tmp("remux.mp4"); - let st = Command::new("ffmpeg") + let st = ec_testkit::ffmpeg() .args(["-v", "error", "-y", "-framerate", "30", "-i"]) .arg(path) .args(["-c", "copy"]) .arg(&mkv) .status() - .ok()?; - if !st.success() { - return None; - } + .unwrap(); + assert!(st.success()); let spec = format!("movie={}[out0+subcc]", mkv.display()); - let st = Command::new("ffmpeg") + let st = ec_testkit::ffmpeg() .args(["-v", "error", "-y"]) .args(demuxer_args) .args(["-f", "lavfi", "-i", &spec, "-map", "0:s:0", "-f", "srt"]) .arg(&srt) .status() - .ok()?; - if !st.success() { - return None; - } - let text = std::fs::read_to_string(&srt).ok()?; + .unwrap(); + assert!(st.success()); + let text = std::fs::read_to_string(&srt).unwrap(); let mut out = Vec::new(); for block in text.split("\n\n") { let mut l = block.lines(); - l.next()?; + l.next().unwrap(); let Some(tl) = l.next() else { continue }; - let start = tl.split(" --> ").next()?; - let secs = parse_srt(start)?; + let start = tl.split(" --> ").next().unwrap(); + let secs = parse_srt(start); let body: Vec<&str> = l.collect(); out.push((strip(&body.join("\n")), secs)); } - Some(out) + out } fn strip(s: &str) -> String { @@ -197,17 +169,14 @@ fn strip(s: &str) -> String { o.trim().to_string() } -fn parse_srt(s: &str) -> Option { - let (hms, ms) = s.trim().split_once(',')?; +fn parse_srt(s: &str) -> f64 { + let (hms, ms) = s.trim().split_once(',').unwrap(); let p: Vec = hms.split(':').map(|x| x.parse().unwrap()).collect(); - Some(p[0] * 3600.0 + p[1] * 60.0 + p[2] + ms.parse::().ok()? / 1000.0) + p[0] * 3600.0 + p[1] * 60.0 + p[2] + ms.parse::().unwrap() / 1000.0 } fn compare_with_ffmpeg(timed: &[ec_cc::TimedCc], path: &PathBuf) { - let Some(theirs) = ffmpeg_cues(path, &[]) else { - eprintln!("ffmpeg subcc extraction unavailable; skipped comparison"); - return; - }; + let theirs = ffmpeg_cues(path, &[]); let ours = decode_all(timed).cea608; assert!(!theirs.is_empty(), "ffmpeg found no captions"); assert_eq!( @@ -233,9 +202,6 @@ fn compare_with_ffmpeg(timed: &[ec_cc::TimedCc], path: &PathBuf) { #[test] fn h264_with_b_frames() { - if !require() { - return; - } let (mkv, idx) = encode( &[ "-c:v", @@ -268,9 +234,6 @@ fn h264_with_b_frames() { #[test] fn h264_with_container_pts_in_decode_order() { - if !require() { - return; - } let (mkv, idx) = encode(&["-c:v", "libx264", "-bf", "2", "-g", "30"], "h264pts"); let ann = raw(&mkv, "h264", Some("h264_mp4toannexb"), "b.264"); let caps = caption_frames(); @@ -287,9 +250,6 @@ fn h264_with_container_pts_in_decode_order() { #[test] fn hevc_with_b_frames() { - if !require() { - return; - } let (mkv, idx) = encode( &[ "-c:v", @@ -317,9 +277,6 @@ fn hevc_with_b_frames() { #[test] fn mpeg2_atsc_and_dvd_user_data() { - if !require() { - return; - } let (mkv, idx) = encode(&["-c:v", "mpeg2video", "-bf", "2", "-g", "12"], "m2v"); let es = std::fs::read(raw(&mkv, "mpeg2video", None, "a.m2v")).unwrap(); let caps = caption_frames(); diff --git a/crates/ec-dvbsub/Cargo.toml b/crates/ec-dvbsub/Cargo.toml index 38a61263..e8016abc 100644 --- a/crates/ec-dvbsub/Cargo.toml +++ b/crates/ec-dvbsub/Cargo.toml @@ -10,5 +10,6 @@ authors.workspace = true ec-core.workspace = true [dev-dependencies] +ec-testkit.workspace = true ec-matroska.workspace = true ec-mpegts.workspace = true diff --git a/crates/ec-dvbsub/tests/ffmpeg_parity.rs b/crates/ec-dvbsub/tests/ffmpeg_parity.rs index 30f491b5..46cc9528 100644 --- a/crates/ec-dvbsub/tests/ffmpeg_parity.rs +++ b/crates/ec-dvbsub/tests/ffmpeg_parity.rs @@ -1,13 +1,6 @@ -//! Our DVB subtitle decode against ffmpeg's (sub2video frames: `[0:s:0]` out as raw RGBA). -//! -//! Fixtures are tiny files made by `scripts/gen-bitmap-sub-fixtures.sh` from a synthetic -//! 720x576 PGS source (four cues). ffmpeg is the oracle; without it the tests skip loudly, and -//! with `EC_REQUIRE_FIXTURES=1` a missing ffmpeg fails. - use std::fs::File; use std::io::BufReader; use std::path::PathBuf; -use std::process::Command; use ec_core::{Decoder, Demuxer, Error}; use ec_dvbsub::DvbSubDecoder; @@ -21,8 +14,8 @@ struct Oracle { frames: Vec<(f64, Vec)>, } -fn oracle(path: &PathBuf, w: usize, h: usize) -> Option { - let out = Command::new("ffmpeg") +fn oracle(path: &PathBuf, w: usize, h: usize) -> Oracle { + let out = ec_testkit::ffmpeg() .args(["-v", "info", "-nostdin", "-canvas_size", &format!("{w}x{h}"), "-i"]) .arg(path) .args([ @@ -38,18 +31,8 @@ fn oracle(path: &PathBuf, w: usize, h: usize) -> Option { "rgba", "-", ]) - .output(); - let out = match out { - Ok(o) => o, - Err(_) => { - assert!( - std::env::var_os("EC_REQUIRE_FIXTURES").is_none(), - "EC_REQUIRE_FIXTURES=1 but ffmpeg is not installed" - ); - eprintln!("SKIP: ffmpeg not installed"); - return None; - } - }; + .output() + .expect("ffmpeg runs"); assert!(out.status.success(), "ffmpeg failed: {}", String::from_utf8_lossy(&out.stderr)); let text = String::from_utf8_lossy(&out.stderr); let times: Vec = text @@ -59,13 +42,13 @@ fn oracle(path: &PathBuf, w: usize, h: usize) -> Option { .collect(); let fsize = w * h * 4; assert_eq!(out.stdout.len(), times.len() * fsize, "frame count mismatch"); - Some(Oracle { + Oracle { frames: times .iter() .enumerate() .map(|(i, &t)| (t, out.stdout[i * fsize..(i + 1) * fsize].to_vec())) .collect(), - }) + } } fn blank(f: &[u8]) -> bool { @@ -142,7 +125,7 @@ fn compare(ours: &[(Vec, f64, Option)], o: &Oracle, what: &str) { #[test] fn mkv_dvbsub_matches_ffmpeg() { let path = data("dvb.mkv"); - let Some(o) = oracle(&path, 720, 576) else { return }; + let o = oracle(&path, 720, 576); let mut d = ec_matroska::MatroskaDemuxer::new(BufReader::new(File::open(&path).unwrap())).unwrap(); assert_eq!(d.streams()[0].params.codec, ec_core::CodecId::DvbSub); let ours = run_packets(&mut d, 0); @@ -152,7 +135,7 @@ fn mkv_dvbsub_matches_ffmpeg() { #[test] fn ts_private_pes_matches_ffmpeg() { let path = data("dvb.ts"); - let Some(o) = oracle(&path, 720, 576) else { return }; + let o = oracle(&path, 720, 576); let mut d = ec_mpegts::TsDemuxer::new(BufReader::new(File::open(&path).unwrap())).unwrap(); let sub = d .streams() diff --git a/crates/ec-dvdsub/Cargo.toml b/crates/ec-dvdsub/Cargo.toml index 289ed96a..4f264005 100644 --- a/crates/ec-dvdsub/Cargo.toml +++ b/crates/ec-dvdsub/Cargo.toml @@ -10,6 +10,7 @@ authors.workspace = true ec-core.workspace = true [dev-dependencies] +ec-testkit.workspace = true ec-matroska.workspace = true ec-mpegts.workspace = true ec-mp4.workspace = true diff --git a/crates/ec-dvdsub/tests/ffmpeg_parity.rs b/crates/ec-dvdsub/tests/ffmpeg_parity.rs index e7e6eb10..d619cd2c 100644 --- a/crates/ec-dvdsub/tests/ffmpeg_parity.rs +++ b/crates/ec-dvdsub/tests/ffmpeg_parity.rs @@ -1,13 +1,6 @@ -//! Our subpicture decode against ffmpeg's (sub2video frames: `[0:s:0]` out as raw RGBA). -//! -//! Fixtures are tiny files made by `scripts/gen-bitmap-sub-fixtures.sh` from a synthetic -//! 720x576 PGS source (four cues). ffmpeg is the oracle; without it the tests skip loudly, and -//! with `EC_REQUIRE_FIXTURES=1` a missing ffmpeg fails. - use std::fs::File; use std::io::BufReader; use std::path::PathBuf; -use std::process::Command; use ec_core::{Demuxer, Error, Frame, Decoder}; use ec_dvdsub::{DvdSubDecoder, parse_idx, sub_file_units}; @@ -21,8 +14,8 @@ struct Oracle { frames: Vec<(f64, Vec)>, } -fn oracle(path: &PathBuf, w: usize, h: usize) -> Option { - let out = Command::new("ffmpeg") +fn oracle(path: &PathBuf, w: usize, h: usize) -> Oracle { + let out = ec_testkit::ffmpeg() .args(["-v", "info", "-nostdin", "-canvas_size", &format!("{w}x{h}"), "-i"]) .arg(path) .args([ @@ -38,18 +31,8 @@ fn oracle(path: &PathBuf, w: usize, h: usize) -> Option { "rgba", "-", ]) - .output(); - let out = match out { - Ok(o) => o, - Err(_) => { - assert!( - std::env::var_os("EC_REQUIRE_FIXTURES").is_none(), - "EC_REQUIRE_FIXTURES=1 but ffmpeg is not installed" - ); - eprintln!("SKIP: ffmpeg not installed"); - return None; - } - }; + .output() + .expect("ffmpeg runs"); assert!(out.status.success(), "ffmpeg failed: {}", String::from_utf8_lossy(&out.stderr)); let text = String::from_utf8_lossy(&out.stderr); let times: Vec = text @@ -59,13 +42,13 @@ fn oracle(path: &PathBuf, w: usize, h: usize) -> Option { .collect(); let fsize = w * h * 4; assert_eq!(out.stdout.len(), times.len() * fsize, "frame count mismatch"); - Some(Oracle { + Oracle { frames: times .iter() .enumerate() .map(|(i, &t)| (t, out.stdout[i * fsize..(i + 1) * fsize].to_vec())) .collect(), - }) + } } fn blank(f: &[u8]) -> bool { @@ -136,7 +119,7 @@ fn run_packets( #[test] fn mkv_vobsub_matches_ffmpeg() { let path = data("dvd.mkv"); - let Some(o) = oracle(&path, 720, 576) else { return }; + let o = oracle(&path, 720, 576); let mut d = ec_matroska::MatroskaDemuxer::new(BufReader::new(File::open(&path).unwrap())).unwrap(); let info = &d.streams()[0]; let extra = info.params.extradata.as_deref().map(<[u8]>::to_vec); @@ -148,13 +131,13 @@ fn mkv_vobsub_matches_ffmpeg() { compare(&ours, &o, "mkv"); } -fn mkv_oracle() -> Option { +fn mkv_oracle() -> Oracle { oracle(&data("dvd.mkv"), 720, 576) } #[test] fn vob_private_stream_1_matches_ffmpeg() { - let Some(o) = mkv_oracle() else { return }; + let o = mkv_oracle(); let path = data("dvd.vob"); let mut d = ec_mpegts::PsDemuxer::new(BufReader::new(File::open(&path).unwrap())).unwrap(); let sub = d @@ -169,7 +152,7 @@ fn vob_private_stream_1_matches_ffmpeg() { #[test] fn mp4s_esds_matches_ffmpeg() { - let Some(o) = mkv_oracle() else { return }; + let o = mkv_oracle(); let path = data("dvd.mp4"); let mut d = ec_mp4::Mp4Demuxer::new(BufReader::new(File::open(&path).unwrap())).unwrap(); let sub = d @@ -186,7 +169,7 @@ fn mp4s_esds_matches_ffmpeg() { #[test] fn idx_sub_pair_matches_ffmpeg() { - let Some(o) = mkv_oracle() else { return }; + let o = mkv_oracle(); let idx = parse_idx(&std::fs::read(data("dvd.idx")).unwrap()); assert_eq!(idx.size, Some((720, 576))); assert_eq!(idx.languages, vec![("en".to_string(), 0)]); diff --git a/crates/ec-image/Cargo.toml b/crates/ec-image/Cargo.toml index 921567b5..bdb291f5 100644 --- a/crates/ec-image/Cargo.toml +++ b/crates/ec-image/Cargo.toml @@ -11,6 +11,7 @@ ec-core = { workspace = true } ec-inflate = { workspace = true } [dev-dependencies] +ec-testkit.workspace = true # The incumbent, as a differential oracle only: every test decodes the same # bytes both ways and compares pixels. Running it is the point; nothing is # copied from it. diff --git a/crates/ec-image/src/gif_encode.rs b/crates/ec-image/src/gif_encode.rs index 8e38995d..7f96ddbc 100644 --- a/crates/ec-image/src/gif_encode.rs +++ b/crates/ec-image/src/gif_encode.rs @@ -739,20 +739,14 @@ mod tests { } #[test] - fn ffprobe_reads_the_output_when_it_is_installed() { - let probe = std::process::Command::new("ffprobe") - .arg("-version") - .output(); - if probe.is_err() { - return; - } + fn ffprobe_reads_the_output() { let px: Vec = (0..8 * 4) .flat_map(|i: u8| [i * 8, 128, 255 - i * 8, 255]) .collect(); let gif = encode_frames(8, 4, GifOptions::default(), &[(&px, 5), (&px, 5)]); let path = std::env::temp_dir().join(format!("ec-gif-encode-{}.gif", std::process::id())); std::fs::write(&path, &gif).unwrap(); - let out = std::process::Command::new("ffprobe") + let out = ec_testkit::ffprobe() .args(["-v", "error", "-select_streams", "v:0", "-show_entries"]) .args(["stream=width,height", "-of", "csv=p=0"]) .arg(&path) diff --git a/crates/ec-image/tests/fuzz.rs b/crates/ec-image/tests/fuzz.rs index 72702c0b..b8666eb0 100644 --- a/crates/ec-image/tests/fuzz.rs +++ b/crates/ec-image/tests/fuzz.rs @@ -190,10 +190,7 @@ fn repair_png_crcs(data: &mut [u8]) { fn sweep(name: &str, seed_file: &str) { // Mutated headers can claim canvases up to the budget, so a sweep is heavy too. let _heavy = heavy(); - let Ok(seed) = std::fs::read(fixtures().join(seed_file)) else { - eprintln!("skipped: tests/data/stills missing"); - return; - }; + let seed = std::fs::read(fixtures().join(seed_file)).unwrap(); let mut rng = Rng(0x2545_f491_4f6c_dd1d ^ name.len() as u64); let mut decoded = 0usize; for round in 0..ROUNDS { @@ -263,10 +260,7 @@ fn single_seed_sweeps_survive_mutation() { /// disposal state machine, none of which `decode` reaches past frame one. #[test] fn a_gif_animation_survives_mutation() { - let Ok(seed) = std::fs::read(fixtures().join("animated.gif")) else { - eprintln!("skipped: tests/data/stills missing"); - return; - }; + let seed = std::fs::read(fixtures().join("animated.gif")).unwrap(); let _heavy = heavy(); let mut rng = Rng(0x2545_f491_4f6c_dd1d ^ 0x9e37); let mut decoded = 0usize; @@ -292,10 +286,7 @@ fn a_gif_animation_survives_mutation() { /// canvas sized by a different chunk, so a mutation can make the two disagree. #[test] fn an_animated_webp_survives_mutation() { - let Ok(seed) = std::fs::read(fixtures().join("anim-alpha.webp")) else { - eprintln!("skipped: tests/data/stills missing"); - return; - }; + let seed = std::fs::read(fixtures().join("anim-alpha.webp")).unwrap(); let _heavy = heavy(); let mut rng = Rng(0x2545_f491_4f6c_dd1d ^ 0x5eed); let mut decoded = 0usize; diff --git a/crates/ec-image/tests/it/differential.rs b/crates/ec-image/tests/it/differential.rs index dea1cff3..caeb8346 100644 --- a/crates/ec-image/tests/it/differential.rs +++ b/crates/ec-image/tests/it/differential.rs @@ -42,11 +42,6 @@ fn corpus(extension: &str) -> Vec { found } -fn skip(what: &str) -> bool { - eprintln!("skipped: tests/data/stills missing ({what})"); - true -} - /// Largest per-sample difference and Pearson correlation between two buffers. fn compare(ours: &[u8], theirs: &[u8]) -> (u32, f64) { assert_eq!(ours.len(), theirs.len(), "sample counts differ"); @@ -93,9 +88,7 @@ fn psnr(a: &[u8], b: &[u8]) -> f64 { #[test] fn png_decodes_pixel_exactly() { let files = corpus("png"); - if files.is_empty() && skip("png") { - return; - } + assert!(!files.is_empty(), "no png stills"); for path in files { let bytes = std::fs::read(&path).unwrap(); let ours = ec_image::decode(&bytes).unwrap_or_else(|e| panic!("{}: {e}", path.display())); @@ -126,9 +119,7 @@ fn webp_lossless_decodes_pixel_exactly() { .into_iter() .filter(|p| name_of(p).contains("lossless")) .collect(); - if files.is_empty() && skip("webp") { - return; - } + assert!(!files.is_empty(), "no webp stills"); for path in files { let bytes = std::fs::read(&path).unwrap(); let ours = ec_image::decode(&bytes).unwrap_or_else(|e| panic!("{}: {e}", path.display())); @@ -151,9 +142,7 @@ fn webp_lossless_decodes_pixel_exactly() { #[test] fn jpeg_matches_the_incumbent_within_rounding() { let files = corpus("jpg"); - if files.is_empty() && skip("jpg") { - return; - } + assert!(!files.is_empty(), "no jpg stills"); let mut worst = 0u32; for path in files { let bytes = std::fs::read(&path).unwrap(); @@ -194,9 +183,7 @@ fn webp_lossy_reconstructs_at_least_as_well_as_the_incumbent() { .into_iter() .filter(|p| name_of(p).contains("lossy")) .collect(); - if files.is_empty() && skip("webp") { - return; - } + assert!(!files.is_empty(), "no webp stills"); let mut shortfalls: Vec = Vec::new(); for path in files { let name = path.file_name().unwrap().to_string_lossy().to_string(); @@ -258,18 +245,13 @@ fn header_dimensions_match_the_incumbent() { checked += 1; } } - if checked == 0 { - skip("any"); - } + assert!(checked > 0, "no stills"); } #[test] fn an_animated_webp_is_refused_by_name() { let path = fixtures().join("animated.webp"); - let Ok(bytes) = std::fs::read(&path) else { - skip("animated.webp"); - return; - }; + let bytes = std::fs::read(&path).unwrap(); let err = ec_image::decode(&bytes).expect_err("an animation is not a still"); let message = format!("{err}"); assert!(message.contains("animated"), "{message}"); @@ -302,10 +284,7 @@ fn with_exif_orientation(jpeg: &[u8], orientation: u16) -> Vec { #[test] fn exif_orientation_is_reported_and_not_applied() { - let Ok(plain) = std::fs::read(fixtures().join("baseline-444.jpg")) else { - skip("baseline-444.jpg"); - return; - }; + let plain = std::fs::read(fixtures().join("baseline-444.jpg")).unwrap(); let bytes = with_exif_orientation(&plain, 6); let ours = ec_image::decode(&bytes).unwrap(); let theirs = image::load_from_memory(&bytes).unwrap(); @@ -344,10 +323,7 @@ fn every_fixture_decodes() { } } } - if count == 0 { - skip("any"); - return; - } + assert!(count > 0, "no stills"); assert!( failures.is_empty(), "{} failed:\n{}", @@ -359,9 +335,7 @@ fn every_fixture_decodes() { #[test] fn gif_decodes_pixel_exactly() { let files = corpus("gif"); - if files.is_empty() && skip("gif") { - return; - } + assert!(!files.is_empty(), "no gif stills"); for path in files { let bytes = std::fs::read(&path).unwrap(); 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() { use image::AnimationDecoder; let path = fixtures().join("animated.gif"); - if !path.exists() && skip("animated.gif") { - return; - } let bytes = std::fs::read(&path).unwrap(); let ours = ec_image::decode_animation(&bytes).expect("our animation decode"); let theirs: Vec = @@ -433,9 +404,6 @@ fn a_gif_animation_composites_frame_for_frame_like_the_incumbent() { #[test] fn a_still_of_any_format_is_one_frame_of_animation() { let path = fixtures().join("rgb8.png"); - if !path.exists() && skip("rgb8.png") { - return; - } let bytes = std::fs::read(&path).unwrap(); let frames = ec_image::decode_animation(&bytes).expect("decode"); assert_eq!(frames.len(), 1); @@ -455,10 +423,7 @@ fn one_animated_webp(fixture: &str) { use image::AnimationDecoder; let path = fixtures().join(fixture); - let Ok(bytes) = std::fs::read(&path) else { - skip(fixture); - return; - }; + let bytes = std::fs::read(&path).unwrap(); assert!( ec_image::webp::is_animated(&bytes), "the fixture is not an animation" @@ -516,18 +481,12 @@ fn one_animated_webp(fixture: &str) { #[test] fn webp_disposal_and_blending_match_libwebp() { let path = fixtures().join("anim-alpha.webp"); - let Ok(bytes) = std::fs::read(&path) else { - skip("anim-alpha.webp"); - return; - }; + let bytes = std::fs::read(&path).unwrap(); let goldens: Vec = (0..) .map(|i| fixtures().join(format!("anim-alpha-f{i}.png"))) .take_while(|p| p.exists()) .collect(); - if goldens.is_empty() { - skip("anim-alpha-f0.png (libwebp goldens; Pillow not installed?)"); - return; - } + assert!(!goldens.is_empty(), "libwebp goldens missing"); let ours = ec_image::decode_animation(&bytes).expect("our animation decode"); assert_eq!(ours.len(), goldens.len(), "frame count against libwebp"); @@ -555,9 +514,7 @@ fn webp_disposal_and_blending_match_libwebp() { #[test] fn bmp_decodes_pixel_exactly() { let files = corpus("bmp"); - if files.is_empty() && skip("bmp") { - return; - } + assert!(!files.is_empty(), "no bmp stills"); for path in files { let name = path.file_name().unwrap().to_string_lossy().to_string(); if name.starts_with("embedded-") || name == "os2v2.bmp" { @@ -587,12 +544,7 @@ fn a_bmp_wrapping_another_format_decodes_to_that_format() { // implementation-defined, so the two decoders round differently. for (fixture, bar) in [("embedded-png.bmp", 0u32), ("embedded-jpeg.bmp", 5)] { let path = fixtures().join(fixture); - let Ok(data) = std::fs::read(&path) else { - if skip(fixture) { - return; - } - unreachable!() - }; + let data = std::fs::read(&path).unwrap(); // The payload starts where the file header says the pixels do. let offset = u32::from_le_bytes([data[10], data[11], data[12], data[13]]) as usize; let payload = &data[offset..]; @@ -622,10 +574,7 @@ fn a_bmp_wrapping_another_format_decodes_to_that_format() { fn an_os2_v2_header_reads_as_the_same_picture() { let short = fixtures().join("os2v2.bmp"); let long = fixtures().join("os2v1.bmp"); - let (Ok(short), Ok(long)) = (std::fs::read(&short), std::fs::read(&long)) else { - skip("os2v2.bmp"); - return; - }; + let (short, long) = (std::fs::read(&short).unwrap(), std::fs::read(&long).unwrap()); assert!( image::load_from_memory(&short).is_err(), "the incumbent now reads a 16-byte header; this test's premise is stale" @@ -649,9 +598,7 @@ fn tiff_decodes_pixel_exactly() { let mut files = corpus("tiff"); files.extend(corpus("tif")); files.sort(); - if files.is_empty() && skip("tiff") { - return; - } + assert!(!files.is_empty(), "no tiff stills"); for path in files { let name = path.file_name().unwrap().to_string_lossy().to_string(); if name == "palette4.tiff" { @@ -681,13 +628,10 @@ fn tiff_decodes_pixel_exactly() { /// lossless, so the associated file must decode to the straight one exactly. #[test] fn an_associated_alpha_tiff_reads_unpremultiplied() { - let (Ok(assoc), Ok(straight)) = ( - std::fs::read(fixtures().join("rgba8-assoc.tiff")), - std::fs::read(fixtures().join("rgba8.tiff")), - ) else { - skip("rgba8-assoc.tiff"); - return; - }; + let (assoc, straight) = ( + std::fs::read(fixtures().join("rgba8-assoc.tiff")).unwrap(), + std::fs::read(fixtures().join("rgba8.tiff")).unwrap(), + ); let ours = ec_image::decode(&assoc).expect("rgba8-assoc.tiff"); let reference = ec_image::decode(&straight).expect("rgba8.tiff"); // Under a zero alpha the colour is gone for good -- premultiplying by zero @@ -721,13 +665,10 @@ fn an_associated_alpha_tiff_reads_unpremultiplied() { /// when the corpus was generated. #[test] fn a_four_bit_tiff_palette_reads_as_ffmpeg_reads_it() { - let (Ok(narrow), Ok(wide)) = ( - std::fs::read(fixtures().join("palette4.tiff")), - std::fs::read(fixtures().join("palette4-golden.png")), - ) else { - skip("palette4.tiff"); - return; - }; + let (narrow, wide) = ( + std::fs::read(fixtures().join("palette4.tiff")).unwrap(), + std::fs::read(fixtures().join("palette4-golden.png")).unwrap(), + ); assert!( image::load_from_memory(&narrow).is_err(), "the incumbent now reads a 4-bit palette; this test's premise is stale" diff --git a/crates/ec-image/tests/it/gaps.rs b/crates/ec-image/tests/it/gaps.rs index ddc8e253..d4b3aa0a 100644 --- a/crates/ec-image/tests/it/gaps.rs +++ b/crates/ec-image/tests/it/gaps.rs @@ -366,10 +366,7 @@ fn png_encoder_round_trips_bit_exact_and_matches_image_decode() { fn png_encoder_size_against_image_on_the_still_fixture() { let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/data/stills/source.png"); - let Ok(bytes) = std::fs::read(&path) else { - eprintln!("skipped: {} not generated", path.display()); - return; - }; + let bytes = std::fs::read(&path).unwrap(); let src = image::load_from_memory(&bytes).unwrap().to_rgb8(); let (w, h) = src.dimensions(); let ours = ec_image::png_encode::encode_rgb8(w, h, src.as_raw()).unwrap(); diff --git a/crates/ec-image/tests/it/main.rs b/crates/ec-image/tests/it/main.rs index 1f7ee77d..86d2081f 100644 --- a/crates/ec-image/tests/it/main.rs +++ b/crates/ec-image/tests/it/main.rs @@ -4,4 +4,3 @@ mod differential; mod gaps; -mod real_library; diff --git a/crates/ec-image/tests/it/real_library.rs b/crates/ec-image/tests/it/real_library.rs deleted file mode 100644 index 9a2e20b5..00000000 --- a/crates/ec-image/tests/it/real_library.rs +++ /dev/null @@ -1,257 +0,0 @@ -//! The same differential bars, against real pictures on this machine. -//! -//! Generated fixtures come out of two encoders with default settings; a real -//! library has phone JPEGs with EXIF, screenshots, scans and downloads, and -//! those are the files a user actually opens. The sweep is read-only, prints a -//! per-file table, and skips silently when the directories hold no pictures. - -use image::GenericImageView; -use std::path::PathBuf; - -/// Where a real library lives on this machine; absent directories are skipped. -fn library() -> Vec { - let home = std::env::var("HOME").unwrap_or_default(); - ["Videos", "Downloads"] - .iter() - .map(|d| PathBuf::from(&home).join(d)) - .filter(|p| p.is_dir()) - .collect() -} - -/// Every still under `roots`, three directory levels deep, capped. -fn stills(roots: &[PathBuf], cap: usize) -> Vec { - fn walk(dir: &PathBuf, depth: usize, out: &mut Vec) { - if depth == 0 { - return; - } - let Ok(entries) = std::fs::read_dir(dir) else { - return; - }; - for entry in entries.flatten() { - let path = entry.path(); - if path.is_dir() { - walk(&path, depth - 1, out); - } else if let Some(extension) = path.extension() { - let extension = extension.to_string_lossy().to_lowercase(); - if ["png", "jpg", "jpeg", "webp"].contains(&extension.as_str()) { - out.push(path); - } - } - } - } - let mut found = Vec::new(); - for root in roots { - walk(root, 3, &mut found); - } - found.sort(); - found.truncate(cap); - found -} - -#[test] -fn real_pictures_decode_like_the_incumbent() { - let files = stills(&library(), 20); - if files.is_empty() { - eprintln!("skipped: no PNG/JPEG/WebP under ~/Videos or ~/Downloads"); - return; - } - let mut failures = Vec::new(); - for path in &files { - let name = path.file_name().unwrap().to_string_lossy().to_string(); - let bytes = std::fs::read(path).unwrap(); - let started = std::time::Instant::now(); - let ours = match ec_image::decode(&bytes) { - Ok(image) => image, - Err(e) => { - // The incumbent's verdict decides whether this is our failure - // or a file neither crate claims to decode. - if image::load_from_memory(&bytes).is_ok() { - failures.push(format!( - "{name}: we refuse it, the incumbent decodes it ({e})" - )); - } else { - eprintln!("{name:<44} both refuse: {e}"); - } - continue; - } - }; - let ours_ms = started.elapsed().as_secs_f64() * 1000.0; - let theirs = match image::load_from_memory(&bytes) { - Ok(image) => image, - Err(e) => { - eprintln!("{name:<44} we decode it, the incumbent does not ({e})"); - continue; - } - }; - if (ours.width, ours.height) != theirs.dimensions() { - failures.push(format!( - "{name}: {}x{} against the incumbent's {:?}", - ours.width, - ours.height, - theirs.dimensions() - )); - continue; - } - let a = ours.to_rgb8(); - let b = theirs.to_rgb8().into_raw(); - let max = a - .iter() - .zip(&b) - .map(|(&x, &y)| x.abs_diff(y)) - .max() - .unwrap_or(0); - let lossless = path - .extension() - .is_some_and(|e| e.eq_ignore_ascii_case("png")); - eprintln!( - "{name:<44} {}x{} max delta {max:>3} {ours_ms:>7.1} ms", - ours.width, ours.height - ); - let bar = if lossless { 0 } else { 8 }; - if u32::from(max) > bar { - failures.push(format!("{name}: max delta {max}, bar {bar}")); - } - } - assert!( - failures.is_empty(), - "{} of {} real pictures failed:\n{}", - failures.len(), - files.len(), - failures.join("\n") - ); -} - -/// Every GIF on this machine, composited frame for frame against the -/// incumbent. -/// -/// The still sweep above compares RGB, which a GIF's transparent index makes -/// meaningless; an animation is only decoded correctly if the canvas, the -/// disposal method and the alpha all agree, so this one compares RGBA over -/// every frame of every file. -#[test] -fn real_gifs_animate_like_the_incumbent() { - use image::AnimationDecoder; - - let files = walk_extension(&library(), "gif", 20); - if files.is_empty() { - eprintln!("skipped: no GIF under ~/Videos or ~/Downloads"); - return; - } - let mut failures = Vec::new(); - for path in &files { - let name = path.file_name().unwrap().to_string_lossy().to_string(); - let bytes = std::fs::read(path).unwrap(); - let started = std::time::Instant::now(); - let ours = match ec_image::decode_animation(&bytes) { - Ok(frames) => frames, - Err(e) => { - if image::load_from_memory(&bytes).is_ok() { - failures.push(format!( - "{name}: we refuse it, the incumbent decodes it ({e})" - )); - } else { - eprintln!("{name:<44} both refuse: {e}"); - } - continue; - } - }; - let ours_ms = started.elapsed().as_secs_f64() * 1000.0; - let theirs = image::codecs::gif::GifDecoder::new(std::io::Cursor::new(&bytes)) - .and_then(|d| d.into_frames().collect::, _>>()); - let theirs = match theirs { - Ok(frames) => frames, - Err(e) => { - eprintln!("{name:<44} we decode it, the incumbent does not ({e})"); - continue; - } - }; - if ours.len() != theirs.len() { - failures.push(format!( - "{name}: {} frames against the incumbent's {}", - ours.len(), - theirs.len() - )); - continue; - } - let mut worst = None; - for (i, (ours, theirs)) in ours.iter().zip(&theirs).enumerate() { - if (ours.image.width, ours.image.height) != theirs.buffer().dimensions() { - worst = Some(format!( - "frame {i}: {}x{} against {:?}", - ours.image.width, - ours.image.height, - theirs.buffer().dimensions() - )); - break; - } - let a = ours.image.to_rgba8(); - let b = theirs.buffer().as_raw(); - let delta = a - .iter() - .zip(b) - .map(|(&x, &y)| x.abs_diff(y)) - .max() - .unwrap_or(0); - let (num, den) = theirs.delay().numer_denom_ms(); - let ours_ms = f64::from(ours.delay_num) * 1000.0 / f64::from(ours.delay_den); - let theirs_ms = f64::from(num) / f64::from(den); - if delta != 0 { - worst = Some(format!("frame {i}: max delta {delta}, bar 0")); - break; - } - if (ours_ms - theirs_ms).abs() >= 0.5 { - worst = Some(format!( - "frame {i}: {ours_ms} ms against the incumbent's {theirs_ms} ms" - )); - break; - } - } - eprintln!( - "{name:<44} {}x{} {:>3} frames {ours_ms:>7.1} ms {}", - ours[0].image.width, - ours[0].image.height, - ours.len(), - worst.as_deref().unwrap_or("exact") - ); - if let Some(worst) = worst { - failures.push(format!("{name}: {worst}")); - } - } - assert!( - failures.is_empty(), - "{} of {} real GIFs failed:\n{}", - failures.len(), - files.len(), - failures.join("\n") - ); -} - -/// Every file under `roots` with the given extension, three levels deep. -fn walk_extension(roots: &[PathBuf], extension: &str, cap: usize) -> Vec { - fn walk(dir: &PathBuf, want: &str, depth: usize, out: &mut Vec) { - if depth == 0 { - return; - } - let Ok(entries) = std::fs::read_dir(dir) else { - return; - }; - for entry in entries.flatten() { - let path = entry.path(); - if path.is_dir() { - walk(&path, want, depth - 1, out); - } else if path - .extension() - .is_some_and(|e| e.eq_ignore_ascii_case(want)) - { - out.push(path); - } - } - } - let mut found = Vec::new(); - for root in roots { - walk(root, extension, 3, &mut found); - } - found.sort(); - found.truncate(cap); - found -} diff --git a/crates/ec-pgs/fuzz/seed.sh b/crates/ec-pgs/fuzz/seed.sh index 5134a338..772d553a 100755 --- a/crates/ec-pgs/fuzz/seed.sh +++ b/crates/ec-pgs/fuzz/seed.sh @@ -1,19 +1,14 @@ #!/usr/bin/env bash -# seed.sh: fill fuzz/corpus// from the repo's PGS fixture. -# -# fixtures/subs/pgs-1080p.sup is a real disc's display sets. segments gets the file's first 64 KiB -# as is. compose and rle get the same bytes too; those two read their own input layouts, so the -# seeds are mostly rejects, which still steer the mutator. Corpus lives under fuzz/corpus. set -euo pipefail FUZZ_DIR=$(cd -- "$(dirname -- "$0")" && pwd) ROOT=$(cd -- "$FUZZ_DIR/../../.." && pwd) -SUBS="$ROOT/fixtures/subs" -[ -f "$SUBS/pgs-1080p.sup" ] || { echo "seed.sh: $SUBS/pgs-1080p.sup missing; run scripts/link-fixtures.sh" >&2; exit 2; } +SUP="${EC_FIXTURES:-$ROOT/fixtures}/open/fate/sub/pgs_sub.sup" +[ -f "$SUP" ] || { echo "seed.sh: $SUP missing; run scripts/fixtures.sh" >&2; exit 2; } CORPUS="$FUZZ_DIR/corpus" mkdir -p "$CORPUS"/{segments,rle,compose} -head -c 65536 "$SUBS/pgs-1080p.sup" > "$CORPUS/segments/pgs-1080p" -head -c 4096 "$SUBS/pgs-1080p.sup" > "$CORPUS/compose/pgs-1080p" -head -c 4096 "$SUBS/pgs-1080p.sup" > "$CORPUS/rle/pgs-1080p" +head -c 65536 "$SUP" > "$CORPUS/segments/pgs_sub" +head -c 4096 "$SUP" > "$CORPUS/compose/pgs_sub" +head -c 4096 "$SUP" > "$CORPUS/rle/pgs_sub" echo "ec-pgs seeds written" diff --git a/crates/ec-subs/Cargo.toml b/crates/ec-subs/Cargo.toml index e144c83a..e839971a 100644 --- a/crates/ec-subs/Cargo.toml +++ b/crates/ec-subs/Cargo.toml @@ -10,5 +10,6 @@ authors.workspace = true ec-core.workspace = true [dev-dependencies] +ec-testkit.workspace = true ec-ass = { path = "../ec-ass", version = "0.1.0" } ec-pgs = { path = "../ec-pgs", version = "0.1.0" } diff --git a/crates/ec-subs/fuzz/seed.sh b/crates/ec-subs/fuzz/seed.sh index 523ebe9a..a5191b7f 100755 --- a/crates/ec-subs/fuzz/seed.sh +++ b/crates/ec-subs/fuzz/seed.sh @@ -1,19 +1,15 @@ #!/usr/bin/env bash -# seed.sh: fill fuzz/corpus// from the repo's subtitle fixtures. -# -# fixtures/subs/real.srt seeds srt, markup and ir. A WebVTT twin of it (commas become dots, a -# WEBVTT header goes on) seeds webvtt, markup and ir. Corpus lives under fuzz/corpus, git-ignored. set -euo pipefail FUZZ_DIR=$(cd -- "$(dirname -- "$0")" && pwd) ROOT=$(cd -- "$FUZZ_DIR/../../.." && pwd) -SUBS="$ROOT/fixtures/subs" -[ -d "$SUBS" ] || { echo "seed.sh: $SUBS missing; run scripts/link-fixtures.sh" >&2; exit 2; } +SUBS="${EC_FIXTURES:-$ROOT/fixtures}/subs" +[ -f "$SUBS/TOS-en.srt" ] || { echo "seed.sh: $SUBS/TOS-en.srt missing; run scripts/fixtures.sh" >&2; exit 2; } CORPUS="$FUZZ_DIR/corpus" mkdir -p "$CORPUS"/{srt,webvtt,markup,ir} -python3 -I - "$SUBS/real.srt" "$CORPUS" <<'PY' +python3 -I - "$SUBS/TOS-en.srt" "$CORPUS" <<'PY' import os, sys srt, corpus = sys.argv[1], sys.argv[2] diff --git a/crates/ec-subs/tests/real_library.rs b/crates/ec-subs/tests/open_media.rs similarity index 63% rename from crates/ec-subs/tests/real_library.rs rename to crates/ec-subs/tests/open_media.rs index 697e8511..85148006 100644 --- a/crates/ec-subs/tests/real_library.rs +++ b/crates/ec-subs/tests/open_media.rs @@ -1,38 +1,16 @@ -//! The three parsers against streams taken out of the user's own library. -//! -//! Hand-written cases live in the crates' unit tests; what cannot be written by -//! hand is a disc's PGS display set or a fansub's thousand-line ASS script. -//! `scripts/gen-subtitle-fixtures.sh` extracts them (fixtures are gitignored, -//! the script is not), and every test here *skips* when its fixture is absent -//! so a fresh clone still runs green. - -use std::path::PathBuf; - use ec_subs::{SourceFormat, plain_text}; -fn fixture(name: &str) -> Option> { - let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("../../fixtures/subs") - .join(name); - match std::fs::read(&path) { - Ok(bytes) => Some(bytes), - Err(_) => { - eprintln!("skipping: no {name} — run scripts/gen-subtitle-fixtures.sh"); - None - } - } +fn fixture(rel: &str) -> Vec { + std::fs::read(ec_testkit::fixture(rel)).unwrap() } #[test] fn a_real_subrip_track_parses_whole() { - let Some(bytes) = fixture("real.srt") else { - return; - }; + let bytes = fixture("subs/TOS-en.srt"); let track = ec_subs::srt::parse(&bytes).unwrap(); assert_eq!(track.source, Some(SourceFormat::Srt)); assert!(track.cues.len() > 100, "{} cues", track.cues.len()); assert_eq!(track.skipped, 0, "a whole file should have no torn blocks"); - // Every cue is up for a positive time and says something. for cue in &track.cues { assert!(cue.end_us >= cue.start_us); assert!( @@ -41,7 +19,6 @@ fn a_real_subrip_track_parses_whole() { cue.start_us ); } - // A subtitle track runs forwards. assert!( track .cues @@ -52,16 +29,12 @@ fn a_real_subrip_track_parses_whole() { #[test] fn a_real_ass_script_parses_whole() { - let Some(bytes) = fixture("real.ass") else { - return; - }; + let bytes = fixture("subs/tos-en.ass"); let track = ec_ass::parse(&bytes).unwrap(); assert_eq!(track.source, Some(SourceFormat::AssOrSsa)); assert!(!track.styles.is_empty(), "a script declares styles"); assert!(track.cues.len() > 100, "{} cues", track.cues.len()); assert_eq!(track.skipped, 0, "a whole script should have no torn rows"); - // Every cue names a style the script declared, and most say words: a - // signs-and-songs script has drawing-only lines, which are not words. let with_text = track .cues .iter() @@ -80,19 +53,15 @@ fn a_real_ass_script_parses_whole() { "cue names undeclared style {style:?}" ); } - // Override tags never leak into the words. let text = plain_text(&cue.segments); assert!(!text.contains("{\\"), "override tag in text: {text:?}"); } - // The header is replayable as a Matroska `CodecPrivate`. assert!(track.extradata.windows(8).any(|w| w == b"[Events]")); } #[test] fn a_real_pgs_stream_decodes_to_plausible_bitmaps() { - let Some(bytes) = fixture("pgs-1080p.sup") else { - return; - }; + let bytes = fixture("open/fate/sub/pgs_sub.sup"); let mut decoder = ec_pgs::PgsDecoder::new(); decoder.push(&bytes).unwrap(); let mut frames = 0; @@ -100,10 +69,9 @@ fn a_real_pgs_stream_decodes_to_plausible_bitmaps() { let mut coverage_max = 0.0f64; while let Some(frame) = decoder.take_frame() { frames += 1; - // A disc composes against its own video frame, and this one is HD. - assert_eq!((frame.width, frame.height), (1920, 1080)); + let (w, h) = (frame.width as usize, frame.height as usize); let stride = frame.planes[0].stride; - assert_eq!(stride, 1920 * 4); + assert_eq!(stride, w * 4); let opaque = frame.planes[0] .data .as_chunks::<4>() @@ -112,20 +80,17 @@ fn a_real_pgs_stream_decodes_to_plausible_bitmaps() { .filter(|p| p[3] > 0) .count(); if opaque == 0 { - // An erase display set: a set that composes nothing at all. continue; } painted += 1; - let coverage = opaque as f64 / (1920.0 * 1080.0); + let coverage = opaque as f64 / (w * h) as f64; coverage_max = coverage_max.max(coverage); - // Subtitles are lines of text over a film: ink, not a filled canvas. assert!( coverage > 0.000_1 && coverage < 0.25, "display set {frames} covers {:.3}% of the canvas", coverage * 100.0 ); - // The ink sits in the lower or upper band, never as a single stray row. - let rows = (0..1080) + let rows = (0..h) .filter(|y| { frame.planes[0].data[y * stride..(y + 1) * stride] .as_chunks::<4>()