From 064c3af07775c5dbee37594f2c925c3a7c3b340e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 2 Dec 2026 04:44:07 +0300 Subject: [PATCH] Test fixtures via ec-testkit in mp4/mpegts/matroska/riff/ogg/probe: ffmpeg from the pinned bundle, missing fixture or ffmpeg fails instead of skipping, real-library and $HOME media tests replaced by open clips or deleted --- Cargo.lock | 6 + crates/ec-matroska/Cargo.toml | 1 + crates/ec-matroska/fuzz/seed.sh | 8 +- crates/ec-matroska/tests/dts.rs | 21 +- crates/ec-matroska/tests/field_order.rs | 37 +- crates/ec-matroska/tests/hdr_metadata.rs | 21 +- crates/ec-matroska/tests/matroska.rs | 797 +-------------------- crates/ec-mp4/Cargo.toml | 3 + crates/ec-mp4/fuzz/seed.sh | 10 +- crates/ec-mp4/tests/data/gen.sh | 8 +- crates/ec-mp4/tests/it/chapters.rs | 5 +- crates/ec-mp4/tests/it/dts.rs | 25 +- crates/ec-mp4/tests/it/edit_trim.rs | 69 +- crates/ec-mp4/tests/it/edith_parity.rs | 51 +- crates/ec-mp4/tests/it/mp4.rs | 178 +---- crates/ec-mp4/tests/it/mux_entries.rs | 64 +- crates/ec-mp4/tests/it/prores_entries.rs | 13 +- crates/ec-mp4/tests/it/qt_pcm_hdr.rs | 47 +- crates/ec-mpegts/Cargo.toml | 3 + crates/ec-mpegts/tests/data/gen.sh | 22 +- crates/ec-mpegts/tests/data/gen_ps.sh | 20 +- crates/ec-mpegts/tests/it/common.rs | 65 +- crates/ec-mpegts/tests/it/dts.rs | 10 +- crates/ec-mpegts/tests/it/ffmpeg_parity.rs | 41 +- crates/ec-mpegts/tests/it/mpeg2.rs | 11 +- crates/ec-mpegts/tests/it/ps.rs | 71 +- crates/ec-mpegts/tests/it/truehd.rs | 35 +- crates/ec-ogg/Cargo.toml | 3 + crates/ec-ogg/fuzz/seed.sh | 6 +- crates/ec-ogg/tests/ogg.rs | 50 +- crates/ec-ogg/tests/real_library.rs | 121 +--- crates/ec-probe/Cargo.toml | 3 + crates/ec-probe/src/lib.rs | 7 +- crates/ec-probe/tests/dts.rs | 29 +- crates/ec-probe/tests/legacy_audio.rs | 10 +- crates/ec-probe/tests/library.rs | 452 +----------- crates/ec-probe/tests/matrix.rs | 36 +- crates/ec-riff/Cargo.toml | 1 + crates/ec-riff/fuzz/seed.sh | 4 +- crates/ec-riff/tests/it/avi_raw_dv.rs | 31 +- crates/ec-riff/tests/it/avi_video.rs | 49 +- crates/ec-riff/tests/it/common.rs | 11 +- crates/ec-riff/tests/it/dts.rs | 12 +- crates/ec-riff/tests/it/mov_raw.rs | 26 +- crates/ec-riff/tests/it/wav.rs | 7 +- 45 files changed, 325 insertions(+), 2175 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index cc823cef..1228ba3d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -563,6 +563,7 @@ dependencies = [ "ec-core", "ec-inflate", "ec-mp4", + "ec-testkit", ] [[package]] @@ -589,6 +590,7 @@ name = "ec-mp4" version = "0.1.0" dependencies = [ "ec-core", + "ec-testkit", ] [[package]] @@ -616,6 +618,7 @@ dependencies = [ "ec-dvdsub", "ec-h264-syntax", "ec-h265-syntax", + "ec-testkit", "ec-truehd", ] @@ -624,6 +627,7 @@ name = "ec-ogg" version = "0.1.0" dependencies = [ "ec-core", + "ec-testkit", ] [[package]] @@ -672,6 +676,7 @@ dependencies = [ "ec-opus", "ec-pcm-ext", "ec-riff", + "ec-testkit", "ec-truehd", "ec-vorbis", ] @@ -695,6 +700,7 @@ dependencies = [ "ec-dv", "ec-mjpeg", "ec-mp4", + "ec-testkit", ] [[package]] diff --git a/crates/ec-matroska/Cargo.toml b/crates/ec-matroska/Cargo.toml index fe7329f5..1245a03a 100644 --- a/crates/ec-matroska/Cargo.toml +++ b/crates/ec-matroska/Cargo.toml @@ -11,6 +11,7 @@ ec-core.workspace = true ec-inflate.workspace = true [dev-dependencies] +ec-testkit.workspace = true ec-mp4.workspace = true ec-aac.workspace = true ec-ac3.workspace = true diff --git a/crates/ec-matroska/fuzz/seed.sh b/crates/ec-matroska/fuzz/seed.sh index 912e8322..7723cb03 100755 --- a/crates/ec-matroska/fuzz/seed.sh +++ b/crates/ec-matroska/fuzz/seed.sh @@ -11,9 +11,11 @@ # Corpus lives under fuzz/corpus, which is git-ignored. set -euo pipefail +FF=${EC_FFMPEG:-$HOME/.cache/ec-ffmpeg/ffmpeg} + FUZZ_DIR=$(cd -- "$(dirname -- "$0")" && pwd) -FIXTURES=$(cd -- "$FUZZ_DIR/../../.." && pwd)/fixtures -[ -d "$FIXTURES/audio" ] || { echo "seed.sh: $FIXTURES/audio missing; run scripts/link-fixtures.sh" >&2; exit 2; } +FIXTURES=${EC_FIXTURES:-$(cd -- "$FUZZ_DIR/../../.." && pwd)/fixtures} +[ -d "$FIXTURES/audio" ] || { echo "seed.sh: $FIXTURES/audio missing; run scripts/fixtures.sh" >&2; exit 2; } OPEN_DIR="$FUZZ_DIR/corpus/open_tracks" DEMUX_DIR="$FUZZ_DIR/corpus/demux_packets" @@ -32,7 +34,7 @@ for src in "$FIXTURES"/audio/*.mka "$FIXTURES"/audio/*.mkv "$FIXTURES"/video/*.m if [ "$(stat -c %s "$src")" -le "$MAX" ]; then cp "$src" "$SCRATCH/$stem.mkv" else - ffmpeg -v error -y -t 0.2 -i "$src" -c copy "$SCRATCH/$stem.mkv" + "$FF" -v error -y -t 0.2 -i "$src" -c copy "$SCRATCH/$stem.mkv" fi seed="$SCRATCH/$stem.mkv" size=$(stat -c %s "$seed") diff --git a/crates/ec-matroska/tests/dts.rs b/crates/ec-matroska/tests/dts.rs index 8cc4fd78..9b81d285 100644 --- a/crates/ec-matroska/tests/dts.rs +++ b/crates/ec-matroska/tests/dts.rs @@ -4,23 +4,18 @@ use std::io::Cursor; use std::path::PathBuf; -use std::process::Command; use ec_core::{CodecId, Demuxer, MediaParameters, Muxer}; use ec_matroska::{MatroskaDemuxer, MatroskaMuxer}; -fn required() -> bool { - std::env::var_os("EC_REQUIRE_FIXTURES").is_some_and(|v| !v.is_empty() && v != "0") -} - /// A DTS stream muxed by ffmpeg into `ext`'s container, plus the raw frames. -fn ffmpeg_dts(ext: &str, channels: &str) -> Option<(Vec, Vec)> { +fn ffmpeg_dts(ext: &str, channels: &str) -> (Vec, Vec) { let dir: PathBuf = std::env::temp_dir().join("ec-matroska-dts"); std::fs::create_dir_all(&dir).unwrap(); let out = dir.join(format!("{}-{channels}.{ext}", std::process::id())); let raw = dir.join(format!("{}-{channels}.dts", std::process::id())); let run = |args: &[&str]| { - Command::new("ffmpeg") + ec_testkit::ffmpeg() .args(["-v", "error", "-y"]) .args(args) .output() @@ -45,15 +40,11 @@ fn ffmpeg_dts(ext: &str, channels: &str) -> Option<(Vec, Vec)> { "copy", raw.to_str().unwrap(), ]); - if !ok { - assert!(!required(), "ffmpeg cannot make a DTS fixture"); - eprintln!("skip: no ffmpeg with the dca encoder"); - return None; - } + assert!(ok, "ffmpeg cannot make a DTS fixture"); let pair = (std::fs::read(&out).unwrap(), std::fs::read(&raw).unwrap()); let _ = std::fs::remove_file(out); let _ = std::fs::remove_file(raw); - Some(pair) + pair } fn demux_all(bytes: Vec) -> (MatroskaDemuxer>>, Vec) { @@ -66,9 +57,7 @@ fn demux_all(bytes: Vec) -> (MatroskaDemuxer>>, Vec bool { - assert!( - std::env::var_os("EC_REQUIRE_FIXTURES").is_none(), - "EC_REQUIRE_FIXTURES set but: {why}" - ); - eprintln!("skip: {why}"); - true -} - -fn source(name: &str, encoder: &str) -> Option<(PathBuf, Vec, Vec)> { - let enc = Command::new("ffmpeg") +fn source(name: &str, encoder: &str) -> (PathBuf, Vec, Vec) { + let enc = ec_testkit::ffmpeg() .args(["-hide_banner", "-encoders"]) .output(); let have = enc.is_ok_and(|o| String::from_utf8_lossy(&o.stdout).contains(&format!(" {encoder} "))); - if !have { - skip(&format!("no ffmpeg or no {encoder}")); - return None; - } + assert!(have, "ffmpeg has no {encoder} encoder"); let dir = std::env::temp_dir().join(format!("ec-field-order-{name}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); let src = dir.join("src.mp4"); - let ok = Command::new("ffmpeg") + let ok = ec_testkit::ffmpeg() .args(["-hide_banner", "-v", "error", "-y", "-f", "lavfi", "-i"]) .arg("testsrc2=size=320x240:rate=25:duration=1") .args(["-c:v", encoder, "-pix_fmt", "yuv420p", "-f", "mp4"]) @@ -56,7 +42,7 @@ fn source(name: &str, encoder: &str) -> Option<(PathBuf, Vec, Vec panic!("{e}"), } } - Some((dir, streams, packets)) + (dir, streams, packets) } fn mux_mp4(dst: &Path, s: &[StreamInfo], p: &[Packet], order: Option>) { @@ -88,7 +74,7 @@ fn mux_mkv(dst: &Path, s: &[StreamInfo], p: &[Packet], order: Option String { - let out = Command::new("ffprobe") + let out = ec_testkit::ffprobe() .args(["-v", "error", "-select_streams", "v:0", "-show_entries"]) .arg("stream=field_order") .args(["-of", "csv=p=0"]) @@ -111,14 +97,7 @@ fn mkv_order(path: &Path) -> Option { } fn run(name: &str, encoder: &str, unstated: &str) { - let Some((dir, s, p)) = source(name, encoder) else { - return; - }; - let ffprobe = Command::new("ffprobe").arg("-version").output().is_ok(); - if !ffprobe { - skip("no ffprobe"); - return; - } + let (dir, s, p) = source(name, encoder); let cases = [ (None, "progressive", Some(Interlace::Progressive)), ( diff --git a/crates/ec-matroska/tests/hdr_metadata.rs b/crates/ec-matroska/tests/hdr_metadata.rs index 2b31f897..b00ac58e 100644 --- a/crates/ec-matroska/tests/hdr_metadata.rs +++ b/crates/ec-matroska/tests/hdr_metadata.rs @@ -5,7 +5,6 @@ use std::fs::File; use std::io::{BufReader, BufWriter}; use std::path::Path; -use std::process::Command; use ec_core::{ContentLight, Demuxer, Error, MasteringPrimaries, Muxer, Packet, StreamInfo}; use ec_matroska::{MatroskaDemuxer, MatroskaMuxer}; @@ -45,23 +44,17 @@ fn mux(dst: &Path, s: &[StreamInfo], p: &[Packet], light: Option) #[test] fn hevc_main10_mastering_metadata_in_mkv() { - let enc = Command::new("ffmpeg").args(["-hide_banner", "-encoders"]).output(); - if !enc.is_ok_and(|o| String::from_utf8_lossy(&o.stdout).contains(" libx265 ")) - || Command::new("ffprobe").arg("-version").output().is_err() - { - assert!( - std::env::var_os("EC_REQUIRE_FIXTURES").is_none(), - "EC_REQUIRE_FIXTURES set but no ffmpeg with libx265" - ); - eprintln!("skip: no ffmpeg/ffprobe/libx265"); - return; - } + let enc = ec_testkit::ffmpeg().args(["-hide_banner", "-encoders"]).output(); + assert!( + enc.is_ok_and(|o| String::from_utf8_lossy(&o.stdout).contains(" libx265 ")), + "ffmpeg has no libx265 encoder" + ); let dir = std::env::temp_dir().join(format!("ec-mkv-hdr-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); let src = dir.join("src.mp4"); assert!( - Command::new("ffmpeg") + ec_testkit::ffmpeg() .args(["-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=size=320x240:rate=25:duration=1"]) .args(["-c:v", "libx265", "-pix_fmt", "yuv420p10le", "-tag:v", "hvc1"]) .args(["-x265-params", "log-level=error:colorprim=bt2020:transfer=smpte2084:colormatrix=bt2020nc"]) @@ -89,7 +82,7 @@ fn hevc_main10_mastering_metadata_in_mkv() { let dst = dir.join("hdr.mkv"); mux(&dst, &streams, &packets, Some(light())); - let out = Command::new("ffprobe") + let out = ec_testkit::ffprobe() .args(["-v", "error", "-show_streams", "-show_frames", "-read_intervals", "%+#1", "-of", "json"]) .arg(&dst) .output() diff --git a/crates/ec-matroska/tests/matroska.rs b/crates/ec-matroska/tests/matroska.rs index 762f4fbf..86e0680a 100644 --- a/crates/ec-matroska/tests/matroska.rs +++ b/crates/ec-matroska/tests/matroska.rs @@ -6,10 +6,9 @@ use std::fs::File; use std::io::{BufReader, Cursor}; use std::path::{Path, PathBuf}; -use std::process::Command; use ec_core::{ - CodecId, Demuxer, Error, MediaParameters, MediaType, Muxer, Packet, SeekMode, StreamInfo, + CodecId, Demuxer, Error, MediaParameters, Muxer, Packet, SeekMode, StreamInfo, TimeBase, Timestamp, }; use ec_matroska::{MatroskaDemuxer, MatroskaMuxer}; @@ -89,7 +88,7 @@ fn truehd_codec_id_round_trips_through_remux() { } fn fixtures() -> PathBuf { - Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures") + ec_testkit::root() } fn work() -> PathBuf { @@ -103,7 +102,7 @@ fn work() -> PathBuf { /// this crate claims are exactly the ones that have to be exercised. fn matroska_fixtures() -> Vec { let mut files: Vec = std::fs::read_dir(fixtures().join("video")) - .expect("fixtures/video (run scripts/gen-fixtures.sh)") + .expect("fixtures/video (run scripts/fixtures.sh)") .filter_map(|e| e.ok().map(|e| e.path())) .filter(|p| { let name = p.to_string_lossy(); @@ -217,7 +216,7 @@ fn make_derived(dst: &Path, args: &[&str]) -> bool { return true; } let tmp = dst.with_file_name(format!("tmp-{}-{name}", std::process::id())); - let ok = Command::new("ffmpeg") + let ok = ec_testkit::ffmpeg() .args(["-v", "error", "-y"]) .args(args) .arg(&tmp) @@ -233,7 +232,7 @@ fn make_derived(dst: &Path, args: &[&str]) -> bool { /// The fields a remux must not change, as ffprobe reads them back. fn probe(path: &Path) -> String { - let out = Command::new("ffprobe") + let out = ec_testkit::ffprobe() .args([ "-v", "error", @@ -256,7 +255,7 @@ fn probe(path: &Path) -> String { } fn duration(path: &Path) -> f64 { - let out = Command::new("ffprobe") + let out = ec_testkit::ffprobe() .args([ "-v", "error", @@ -456,7 +455,7 @@ fn every_fixture_remuxes_into_a_file_ffprobe_and_ffmpeg_agree_with() { a_seek_to_the_beginning_lands_on_the_first_packet(&dst); // ...and it decodes, which is the only claim a field compare cannot make. - let decode = Command::new("ffmpeg") + let decode = ec_testkit::ffmpeg() .args(["-v", "error", "-i"]) .arg(&dst) .args(["-f", "null", "-"]) @@ -556,178 +555,6 @@ fn a_hundred_random_seeks_land_at_or_before_their_target_on_one_reader() { println!("{}", table.join("\n")); } -/// A sweep of the real library: ten films, one per directory so a 60-episode -/// series counts once, each demuxed end to end and its packet counts compared -/// with ffprobe's. Ignored by default because it reads tens of gigabytes. -/// -/// Run it with `cargo test -p ec-matroska --release --test matroska -- --ignored -/// --nocapture`. -#[test] -#[ignore = "reads the real library end to end"] -fn real_library_spot_sweep() { - let manifest = std::fs::read_to_string(fixtures().join("real-library-manifest.tsv")) - .expect("fixtures/real-library-manifest.tsv"); - let mut seen: Vec = Vec::new(); - let mut files: Vec = Vec::new(); - for line in manifest.lines().skip(1) { - let mut cols = line.split('\t'); - let (Some(path), Some(container)) = (cols.next(), cols.next()) else { - continue; - }; - let path = PathBuf::from(path); - if !container.contains("matroska") || !path.exists() { - continue; - } - // One per directory: a series of sixty episodes is one shape, not sixty. - let dir = path - .parent() - .unwrap_or(Path::new("/")) - .to_string_lossy() - .into_owned(); - if seen.contains(&dir) { - continue; - } - seen.push(dir); - files.push(path); - } - assert!( - files.len() >= 10, - "only {} Matroska directories", - files.len() - ); - let step = (files.len() / 10).max(1); - let picked: Vec = files.into_iter().step_by(step).take(10).collect(); - - let mut table = Vec::new(); - for path in &picked { - let mut demuxer = - MatroskaDemuxer::new(BufReader::new(File::open(path).expect("film opens"))) - .expect("demuxes"); - let streams: Vec = demuxer - .streams() - .iter() - .map(|s| s.params.codec.name().to_string()) - .collect(); - let text: Vec = demuxer - .streams() - .iter() - .filter(|s| { - matches!( - s.params.codec, - ec_core::CodecId::Srt | ec_core::CodecId::Ass | ec_core::CodecId::WebVtt - ) - }) - .map(|s| s.index) - .collect(); - let mut counts = vec![0usize; streams.len()]; - let mut checked = Vec::new(); - loop { - match demuxer.next_packet() { - Ok(p) => { - counts[p.stream as usize] += 1; - // A text track under `ContentEncodings` that came back - // still compressed is not UTF-8, which is the cheapest - // proof the zlib path ran. - if text.contains(&p.stream) && !checked.contains(&p.stream) { - checked.push(p.stream); - assert!( - std::str::from_utf8(&p.data).is_ok(), - "{}: stream {} is not text", - path.display(), - p.stream - ); - } - } - Err(Error::Eof) => break, - Err(e) => panic!("{}: {e}", path.display()), - } - } - // ffprobe counts the same packets on the same file; the picture track is - // first in both and is the one compared exactly. - let out = Command::new("ffprobe") - .args([ - "-v", - "error", - "-count_packets", - "-show_entries", - "stream=nb_read_packets", - "-of", - "csv=p=0", - ]) - .arg(path) - .output() - .expect("ffprobe runs"); - let theirs: Vec = String::from_utf8_lossy(&out.stdout) - .lines() - // ffprobe leaves a trailing separator on a row whose fields it - // padded; the count is the first number on the line. - .filter_map(|l| l.trim().trim_end_matches(',').parse().ok()) - .collect(); - assert_eq!( - counts.first(), - theirs.first(), - "{}: picture packet count", - path.display() - ); - assert!(counts.iter().sum::() > 0); - - // ...and twenty seeks spread over the film, on one more reader, each - // landing on a random-access point at or before its target. A film is - // where a cue table is worth having: the fixtures are two seconds long - // and every one of their clusters is a keyframe. - let mut demuxer = - MatroskaDemuxer::new(BufReader::new(File::open(path).expect("film opens"))) - .expect("demuxes"); - let stream = demuxer.streams()[0].index; - // Where the picture actually starts: a film whose video track begins at - // 83 ms has nothing earlier to land on, and that is not a failed seek. - let first = loop { - let packet = demuxer.next_packet().expect("a first keyframe"); - if packet.stream == stream && packet.flags.keyframe { - break packet.time_base.rescale( - packet.pts.unwrap_or(0), - TimeBase::MILLIS, - ec_core::Rounding::Down, - ); - } - }; - let secs = duration(path).max(1.0); - for i in 0..20 { - let target_ms = (secs * 1000.0 * f64::from(i) / 20.0) as i64; - demuxer - .seek( - stream, - Timestamp::new(target_ms, TimeBase::MILLIS), - SeekMode::SyncBefore, - ) - .unwrap_or_else(|e| panic!("{}: seek to {target_ms}ms: {e}", path.display())); - let packet = loop { - match demuxer.next_packet() { - Ok(p) if p.stream == stream => break p, - Ok(_) => continue, - Err(e) => panic!("{}: after seek: {e}", path.display()), - } - }; - let ms = packet.time_base.rescale( - packet.pts.unwrap_or(0), - TimeBase::MILLIS, - ec_core::Rounding::Down, - ); - assert!( - packet.flags.keyframe && (ms <= target_ms || ms == first), - "{}: seek to {target_ms}ms landed at {ms}ms, key {}", - path.display(), - packet.flags.keyframe - ); - } - table.push(format!( - "{:<64} {streams:?} ours {counts:?} ffprobe {theirs:?}", - path.file_name().unwrap().to_string_lossy() - )); - } - println!("{}", table.join("\n")); -} - /// A file whose *first* cluster holds only sound: seeking its audio track to /// the beginning lands on that block, not on the first cue. /// @@ -857,616 +684,6 @@ fn matroska_prefix_class(data: &[u8]) -> (&'static str, u64) { } } -/// Where our own demuxer's seek lands on a real 5.1 E-AC-3 Matroska, in -/// *timestamp* -- split from decode, per the round's charter: this measures -/// only [`MatroskaDemuxer::seek`] plus the first packet's `pts`, against what -/// `ffprobe` reports for the same track near the same instant. If this lands -/// exact, the +0.145 s the consumer measured is downstream of the demuxer -/// (the AC-3 decoder or its frame-count bookkeeping in `engine`), not here. -/// -/// Skipped, not failed, without the film: a claim about his library cannot be -/// made by a machine that does not have it. -#[test] -fn seek_landing_on_his_eac3_film_matches_ffprobe() { - same_class_sweep( - "/home/user/Downloads/reeld/reeld.mkv", - &[600.0, 610.0], - 40.0, - ); - // Same-class sweep (round charter task 3): an Opus 5.1 Matroska, a codec - // that already goes through this crate's demuxer -- if this lands as - // tight as the E-AC-3 one, the demuxer's seek is not codec-specific and - // the +0.145 s the consumer measured on the E-AC-3 path is downstream of - // it either way. - same_class_sweep( - "/home/user/Downloads/reelb.mkv", - &[600.0, 610.0], - 20.0, - ); -} - -/// `A_OPUS` with no `DefaultDuration` and 8-frame laces (ReelC, seeAlso -/// `demux.rs::codec_frame_ticks`): a `SyncBefore` landing mid-lace has to -/// report the true pts of the frame it lands on -- base-pts-for-every-frame- -/// in-the-lace collapsed every mid-lace landing onto the lace's first frame, -/// up to 140 ms early. -#[test] -fn seek_lands_on_the_true_frame_in_a_laced_opus_track() { - same_class_sweep( - "/home/user/Videos/Films/reelc.mkv", - &[123.4, 600.0, 1800.0, 4500.0], - 20.0, - ); -} - -/// Where our own demuxer's seek lands on `path`, in *timestamp* -- split from -/// decode, per the round's charter: this measures only -/// [`MatroskaDemuxer::seek`] plus the first packet's `pts`, against what -/// `ffprobe` reports for the same track near the same instant. -/// -/// Skipped, not failed, without the film: a claim about his library cannot be -/// made by a machine that does not have it. -fn same_class_sweep(path: &str, wants: &[f64], tolerance_ms: f64) { - let film = Path::new(path); - if !film.exists() { - eprintln!("skipped: {path} is not present"); - return; - } - let mut demux = - MatroskaDemuxer::new(BufReader::new(File::open(film).expect("opens"))).expect("demuxes"); - let audio = demux - .streams() - .iter() - .find(|s| s.params.codec.media_type() == MediaType::Audio) - .expect("the film has an audio stream") - .clone(); - - for &want in wants { - let target = Timestamp::new( - (want * audio.time_base.den() as f64 / audio.time_base.num() as f64).round() as i64, - audio.time_base, - ); - demux - .seek(audio.index, target, SeekMode::SyncBefore) - .expect("seek"); - let landed = loop { - let packet = demux.next_packet().expect("a packet after the seek"); - if packet.stream == audio.index { - break packet.pts.expect("audio packet carries a pts"); - } - }; - let our_secs = landed as f64 * audio.time_base.num() as f64 / audio.time_base.den() as f64; - // `SyncBefore`'s own contract: the landed frame is at or before the - // target, and no further before it than a lace's worth of drift. - assert!( - our_secs <= want + 1e-6, - "{path}: SyncBefore landed at {our_secs:.3}s, after the {want}s it was asked for" - ); - assert!( - want - our_secs <= tolerance_ms / 1000.0, - "{path}: wanted {want}s, landed {our_secs:.3}s -- {:.1} ms short, over the {tolerance_ms} ms budget", - (want - our_secs) * 1000.0 - ); - - let ffprobe = Command::new("ffprobe") - .args([ - "-v", - "error", - "-select_streams", - "a:0", - "-show_entries", - "packet=pts_time", - "-of", - "csv=p=0", - "-read_intervals", - ]) - .arg(format!("{want}%+#1")) - .arg(film) - .output(); - let Ok(ffprobe) = ffprobe else { - eprintln!("skipped ffprobe cross-check: ffprobe not runnable"); - eprintln!("want {want}s, our demuxer landed at {our_secs:.3}s (pts {landed})"); - continue; - }; - let reference: f64 = String::from_utf8_lossy(&ffprobe.stdout) - .lines() - .next() - .unwrap_or("") - .trim() - .parse() - .unwrap_or(f64::NAN); - eprintln!( - "want {want}s: our demuxer landed {our_secs:.3}s (pts {landed}), ffprobe's own packet at {reference:.3}s" - ); - } -} - -/// Same-class sweep (round charter task, "same-class sweep" line): every -/// Matroska in his real library whose audio is one of the laced-frame -/// families this round's fix touches (Opus, AAC, FLAC, Vorbis), landed on at -/// two points each and printed as a table. `SyncBefore`'s own contract -- -/// never land after the target -- is the one thing asserted for every file; -/// how close under it a codec this round did not give a bitstream-derived -/// duration to (FLAC, Vorbis) lands is reported, not enforced, since those -/// two still fall back to the pre-fix `DefaultDuration`-or-zero step. -/// -/// Ignored: 79 files, two seeks and an `ffprobe`-free landing check each -- -/// slow enough that it does not belong in the default run, real enough that -/// it should not be skipped either. -#[test] -#[ignore = "sweeps his real library, run manually with --ignored"] -fn laced_audio_sweep_across_his_library() { - // lane-h264reallib: `fixtures()` like every sibling, instead of a - // hardcoded absolute path into the primary checkout. The absolute form - // silently defeated worktree isolation: a run in a worktree or a gate tree - // read the MAIN checkout's manifest, so this test measured a different - // tree's library than the one it was compiled from. - let manifest = &fixtures().join("real-library-manifest.tsv"); - let Ok(rows) = std::fs::read_to_string(manifest) else { - eprintln!("skipped: {} not present", manifest.display()); - return; - }; - for line in rows.lines().skip(1) { - let cols: Vec<&str> = line.split('\t').collect(); - let [path, container, _v, _w, _h, _pf, _bd, acodecs, duration, ..] = cols[..] else { - continue; - }; - if container != "matroska,webm" - || !["opus", "aac", "flac", "vorbis"] - .iter() - .any(|c| acodecs.contains(c)) - { - continue; - } - let Ok(duration) = duration.parse::() else { - continue; - }; - let film = Path::new(path); - if !film.exists() { - continue; - } - let Ok(mut demux) = MatroskaDemuxer::new(BufReader::new(File::open(film).expect("opens"))) - else { - eprintln!("{path}: failed to open"); - continue; - }; - let Some(audio) = demux - .streams() - .iter() - .find(|s| s.params.codec.media_type() == MediaType::Audio) - .cloned() - else { - continue; - }; - for frac in [0.3, 0.7] { - let want = duration * frac; - let target = Timestamp::new( - (want * audio.time_base.den() as f64 / audio.time_base.num() as f64).round() as i64, - audio.time_base, - ); - if demux - .seek(audio.index, target, SeekMode::SyncBefore) - .is_err() - { - eprintln!("{path} ({acodecs}) @ {want:.1}s: seek failed"); - continue; - } - let landed = loop { - match demux.next_packet() { - Ok(packet) if packet.stream == audio.index => break packet.pts, - Ok(_) => continue, - Err(_) => break None, - } - }; - let our_secs = landed.map(|pts| { - pts as f64 * audio.time_base.num() as f64 / audio.time_base.den() as f64 - }); - // Not asserted here (unlike the two targeted tests above): a want - // that falls before this file's first audio packet legitimately - // lands after it -- `seek`'s own documented fallback, "nothing - // earlier to decode from" -- so an after-target landing is - // reported, not failed, for a sweep that does not hand-pick times - // deep inside each file's audio. - eprintln!( - "{path} ({acodecs}) @ {want:.1}s: landed {:.3}", - our_secs.unwrap_or(f64::NAN) - ); - } - } -} - -/// `ffprobe` reports MaxCLL 1230 / MaxFALL 419 for this real HDR10 film, but -/// that reading comes from `[SIDE_DATA]` on the first *frame* (a -/// `content_light_level_information` HEVC SEI message inside the bitstream), -/// not from the container's own `Colour` element. This file's `Colour` -/// element genuinely carries no `MaxCLL`/`MaxFALL`/`MasteringMetadata` -/// children (checked with `ffprobe -show_entries stream=side_data_list`, -/// which comes back empty) — so a demuxer-only reader is correct to return -/// `None` here, and the consumer's brightness-metadata gap is downstream, in -/// whether anything reads the HEVC SEI (`ec_core::color::hevc_sei_light` -/// exists and round-trips in `ec-h265-syntax`, but nothing in this workspace -/// calls it from a real decode path yet). -#[test] -#[ignore = "reads a real local file, not a CI fixture"] -fn real_hdr_film_container_states_no_light_metadata() { - use ec_core::{Demuxer, MediaParameters}; - use ec_matroska::MatroskaDemuxer; - let path = "/home/user/Downloads/reeld/reeld.mkv"; - if !std::path::Path::new(path).exists() { - eprintln!("skipped: film not present"); - return; - } - let f = std::fs::File::open(path).expect("open"); - let demux = MatroskaDemuxer::new(f).expect("demux opens"); - let mut checked = false; - for s in demux.streams() { - if let MediaParameters::Video(v) = &s.params.media { - println!("color = {:?}", v.color); - println!("light = {:?}", v.light); - // BT.2020 non-constant luminance, PQ transfer, BT.2020 primaries — - // this much the Colour element does carry, and it must match - // ffprobe's color_space/color_primaries/color_transfer. - assert_eq!(v.color.matrix, 9, "expected bt2020nc"); - assert_eq!(v.color.transfer, 16, "expected smpte2084 (PQ)"); - assert_eq!(v.color.primaries, 9, "expected bt2020"); - assert_eq!( - v.light, - ec_core::color::ContentLight::default(), - "the Colour element has no light metadata for this file — a \ - non-default reading here would mean either ffprobe or this \ - reader started finding it in the container and the doc \ - comment above is stale" - ); - checked = true; - } - } - assert!(checked, "no video stream found"); -} - -// ===== mkv-vs-mp4 audio A/B (mkv-audio-timing) ===== -// -// The consumer sweep found: same OBS recording's `.mkv` leg scores far below -// its sibling `.mp4` leg on channel-0 correlation from t=0, and 5.1 AC-3/E-AC-3 -// tracks that are only ever carried in Matroska score near zero. These tests -// isolate whether that is packet delivery out of `ec-matroska` (order, -// duplication, pts) or the shared decoder crate, and which physical channel -// our 5.1 decode calls "channel 0". - -use ec_aac::AacDecoder; -use ec_ac3::Ac3Decoder; - -/// Opens whichever container `path` actually is — both crates implement the -/// same `Demuxer` trait, so the rest of the harness never has to know which. -fn open_any(path: &Path) -> Box { - use std::io::Read; - let mut head = [0u8; 12]; - File::open(path) - .expect("open") - .read_exact(&mut head) - .expect("read head"); - if ec_mp4::is_mp4(&head) { - Box::new( - ec_mp4::Mp4Demuxer::new(BufReader::new(File::open(path).expect("open"))) - .expect("mp4 opens"), - ) - } else { - Box::new( - MatroskaDemuxer::new(BufReader::new(File::open(path).expect("open"))) - .expect("mkv opens"), - ) - } -} - -/// The first stream of `codec`'s extradata plus its packets, `(pts, data)`, -/// in the order the container's own demuxer hands them back — capped so a -/// multi-gigabyte recording does not have to be decoded whole. -/// The track's CodecPrivate, sample rate, and its (timestamp, payload) packets. -type AudioTrack = (Option>, u32, Vec<(i64, Vec)>); - -fn audio_track(path: &Path, codec: CodecId) -> Option { - let mut d = open_any(path); - let s = d.streams().iter().find(|s| s.params.codec == codec)?; - let idx = s.index; - let extradata = s.params.extradata.as_ref().map(|b| b.to_vec()); - let rate = s.params.audio()?.sample_rate; - let mut pkts = Vec::new(); - loop { - match d.next_packet() { - Ok(p) if p.stream == idx => { - pkts.push((p.pts.unwrap_or(0), p.data.to_vec())); - if pkts.len() >= 2_000 { - break; - } - } - Ok(_) => continue, - Err(_) => break, - } - } - Some((extradata, rate, pkts)) -} - -/// Our AAC decode of a container's access units, interleaved-to-planar. -fn decode_aac(extradata: &[u8], pkts: &[(i64, Vec)]) -> Vec> { - let mut decoder = AacDecoder::with_config_bytes(extradata).expect("AudioSpecificConfig parses"); - let mut planes: Vec> = Vec::new(); - for (_, au) in pkts { - let Ok(frame) = decoder.decode(au, None) else { - continue; - }; - let ch = usize::from(frame.channels); - if ch == 0 { - continue; - } - if planes.is_empty() { - planes = vec![Vec::new(); ch]; - } - for (i, v) in frame.samples.iter().enumerate() { - planes[i % ch].push(*v); - } - } - planes -} - -/// Our AC-3/E-AC-3 decode of a container's frames, interleaved-to-planar. -fn decode_ac3(pkts: &[(i64, Vec)]) -> Vec> { - let mut decoder = Ac3Decoder::new(); - let mut planes: Vec> = Vec::new(); - for (_, data) in pkts { - let Ok(frame) = decoder.decode_frame(data) else { - continue; - }; - let ch = frame.channels(); - if ch == 0 { - continue; - } - if planes.is_empty() { - planes = vec![Vec::new(); ch]; - } - let samples: Vec = frame.data[0] - .as_chunks::<4>() - .0 - .iter() - .map(|c| f32::from_le_bytes(*c)) - .collect(); - for (i, v) in samples.iter().enumerate() { - planes[i % ch].push(*v); - } - } - planes -} - -fn have_ffmpeg() -> bool { - Command::new("ffmpeg") - .arg("-version") - .output() - .is_ok_and(|o| o.status.success()) -} - -/// ffmpeg's decode of a file's first audio stream, planar by channel. -fn ffmpeg_decode_planar(path: &Path, channels: usize) -> Vec> { - let out = Command::new("ffmpeg") - .args(["-v", "error", "-i"]) - .arg(path) - .args([ - "-map", - "0:a:0", - "-t", - "20", - "-f", - "f32le", - "-acodec", - "pcm_f32le", - "-", - ]) - .output() - .expect("ffmpeg runs"); - assert!( - out.status.success(), - "ffmpeg decode failed: {}", - String::from_utf8_lossy(&out.stderr) - ); - let samples: Vec = out - .stdout - .as_chunks::<4>() - .0 - .iter() - .map(|c| f32::from_le_bytes(*c)) - .collect(); - let mut planes = vec![Vec::with_capacity(samples.len() / channels.max(1)); channels]; - for (i, v) in samples.iter().enumerate() { - planes[i % channels].push(*v); - } - planes -} - -fn correlation(a: &[f32], b: &[f32]) -> f64 { - let n = a.len().min(b.len()); - if n < 1024 { - return 0.0; - } - let (a, b) = (&a[..n], &b[..n]); - let ma = a.iter().map(|v| f64::from(*v)).sum::() / n as f64; - let mb = b.iter().map(|v| f64::from(*v)).sum::() / n as f64; - let (mut num, mut da, mut db) = (0.0f64, 0.0f64, 0.0f64); - for i in 0..n { - let (x, y) = (f64::from(a[i]) - ma, f64::from(b[i]) - mb); - num += x * y; - da += x * x; - db += y * y; - } - let den = (da * db).sqrt(); - if den == 0.0 { 0.0 } else { num / den } -} - -/// Best correlation over a bounded lag search from the start of both -/// streams — the whole point here is t=0 alignment, so no whole-file window -/// slide is needed, just enough lag to absorb container/codec delay. -const LAG_MAX: i64 = 4_000; -const WINDOW: usize = 100_000; - -fn best_lag_correlation(ours: &[f32], theirs: &[f32]) -> (i64, f64) { - let mut best_abs = -1.0f64; - let mut best = (0i64, 0.0f64); - for lag in -LAG_MAX..=LAG_MAX { - let (oa, ob) = if lag >= 0 { - (0usize, lag as usize) - } else { - ((-lag) as usize, 0usize) - }; - let len = WINDOW - .min(ours.len().saturating_sub(oa)) - .min(theirs.len().saturating_sub(ob)); - if len < 1024 { - continue; - } - let c = correlation(&ours[oa..oa + len], &theirs[ob..ob + len]); - if c.abs() > best_abs { - best_abs = c.abs(); - best = (lag, c); - } - } - best -} - -/// mkv vs mp4: the same recording's AAC stream, decoded through each -/// container's own demux path, ours-vs-ours and each vs ffmpeg. Isolates the -/// consumer sweep's "same channel 0, same track, `.mkv` corr 0.06-0.34 but -/// sibling `.mp4` 0.76-0.92" finding to this crate's packet delivery or to -/// the shared AAC decoder. -/// -/// Run with `cargo test -p ec-matroska --test matroska mkv_vs_mp4_aac_pipeline -- --ignored --nocapture`. -#[test] -#[ignore = "reads the real library, mkv-audio-timing A/B"] -fn mkv_vs_mp4_aac_pipeline() { - if !have_ffmpeg() { - eprintln!("skipped: no ffmpeg"); - return; - } - let obs = Path::new("/home/user/Videos/OBS"); - let stems = [ - "2026-07-25 02-09-04", - "2026-08-17 01-57-17", - "2026-08-17 11-01-56", - ]; - let mut any = false; - for stem in stems { - let mkv = obs.join(format!("{stem}.mkv")); - let mp4 = obs.join(format!("{stem}.mp4")); - if !mkv.exists() || !mp4.exists() { - continue; - } - any = true; - println!("=== {stem} ==="); - let (mkv_asc, mkv_rate, mkv_pkts) = audio_track(&mkv, CodecId::Aac).expect("mkv aac track"); - let (mp4_asc, mp4_rate, mp4_pkts) = audio_track(&mp4, CodecId::Aac).expect("mp4 aac track"); - println!( - "mkv asc={:02x?} rate={mkv_rate} packets={} bytes={}", - mkv_asc, - mkv_pkts.len(), - mkv_pkts.iter().map(|(_, d)| d.len()).sum::() - ); - println!( - "mp4 asc={:02x?} rate={mp4_rate} packets={} bytes={}", - mp4_asc, - mp4_pkts.len(), - mp4_pkts.iter().map(|(_, d)| d.len()).sum::() - ); - println!( - "mkv first5 pts = {:?}", - mkv_pkts.iter().take(5).map(|(p, _)| *p).collect::>() - ); - println!( - "mp4 first5 pts = {:?}", - mp4_pkts.iter().take(5).map(|(p, _)| *p).collect::>() - ); - let (mut out_of_order, mut dup) = (0, 0); - for w in mkv_pkts.windows(2) { - if w[1].0 < w[0].0 { - out_of_order += 1; - } - if w[1].0 == w[0].0 { - dup += 1; - } - } - println!("mkv out_of_order={out_of_order} dup_pts={dup}"); - - let mkv_planes = decode_aac(mkv_asc.as_deref().unwrap_or(&[]), &mkv_pkts); - let mp4_planes = decode_aac(mp4_asc.as_deref().unwrap_or(&[]), &mp4_pkts); - assert!( - !mkv_planes.is_empty() && !mp4_planes.is_empty(), - "{stem}: decode produced no channels (mkv {} ch, mp4 {} ch)", - mkv_planes.len(), - mp4_planes.len() - ); - - let (lag, c_mm) = best_lag_correlation(&mkv_planes[0], &mp4_planes[0]); - let mkv_ff = ffmpeg_decode_planar(&mkv, mkv_planes.len()); - let mp4_ff = ffmpeg_decode_planar(&mp4, mp4_planes.len()); - let (_, c_mkv_ff) = best_lag_correlation(&mkv_planes[0], &mkv_ff[0]); - let (_, c_mp4_ff) = best_lag_correlation(&mp4_planes[0], &mp4_ff[0]); - println!( - "{stem}: mkv-vs-mp4(ours) corr={c_mm:.4} lag={lag}; mkv-vs-ffmpeg corr={c_mkv_ff:.4}; mp4-vs-ffmpeg corr={c_mp4_ff:.4}" - ); - } - assert!(any, "no OBS mkv/mp4 pairs present"); -} - -/// The two mkv-only 5.1 real-library rows the consumer sweep flagged -/// (E-AC-3 and AC-3): our decode of every channel against ffmpeg's channel -/// 0, so a channel-order mismatch (mkv hands a different physical channel -/// first than ffmpeg calls "channel 0") shows up as a non-zero-index best -/// match instead of a flat near-zero across all of them. -/// -/// Run with `cargo test -p ec-matroska --test matroska mkv_51_channel_order -- --ignored --nocapture`. -#[test] -#[ignore = "reads the real library, mkv-audio-timing A/B"] -fn mkv_51_channel_order() { - if !have_ffmpeg() { - eprintln!("skipped: no ffmpeg"); - return; - } - let files: [(&str, CodecId); 2] = [ - ( - "/home/user/Downloads/reelf/reelf.mkv", - CodecId::EAc3, - ), - ( - "/home/user/Downloads/reelg/reelg.mkv", - CodecId::Ac3, - ), - ]; - let mut any = false; - for (path, codec) in files { - let path = Path::new(path); - if !path.exists() { - eprintln!("skipped: {} absent", path.display()); - continue; - } - any = true; - let (_, _rate, pkts) = audio_track(path, codec).expect("audio track"); - println!( - "{}: first5 pts = {:?}", - path.file_name().unwrap().to_string_lossy(), - pkts.iter().take(5).map(|(p, _)| *p).collect::>() - ); - let planes = decode_ac3(&pkts); - assert!( - !planes.is_empty(), - "{}: no channels decoded", - path.display() - ); - let ffref = ffmpeg_decode_planar(path, planes.len()); - for (i, ch) in planes.iter().enumerate() { - let (lag, c) = best_lag_correlation(ch, &ffref[0]); - println!( - "{}: our ch{i} vs ffmpeg ch0 corr={c:.4} lag={lag}", - path.file_name().unwrap().to_string_lossy() - ); - } - } - assert!(any, "no 5.1 mkv fixtures present"); -} - /// An EBML element with its size written in eight bytes. fn ebml_el(id: &[u8], body: &[u8]) -> Vec { let mut out = id.to_vec(); diff --git a/crates/ec-mp4/Cargo.toml b/crates/ec-mp4/Cargo.toml index d6d7c950..f7dc6aec 100644 --- a/crates/ec-mp4/Cargo.toml +++ b/crates/ec-mp4/Cargo.toml @@ -8,3 +8,6 @@ authors.workspace = true [dependencies] ec-core.workspace = true + +[dev-dependencies] +ec-testkit.workspace = true diff --git a/crates/ec-mp4/fuzz/seed.sh b/crates/ec-mp4/fuzz/seed.sh index d91ba4de..94783f53 100755 --- a/crates/ec-mp4/fuzz/seed.sh +++ b/crates/ec-mp4/fuzz/seed.sh @@ -11,10 +11,12 @@ # Corpus lives under fuzz/corpus, which is git-ignored. set -euo pipefail +FF=${EC_FFMPEG:-$HOME/.cache/ec-ffmpeg/ffmpeg} + FUZZ_DIR=$(cd -- "$(dirname -- "$0")" && pwd) -FIXTURES=$(cd -- "$FUZZ_DIR/../../.." && pwd)/fixtures -[ -d "$FIXTURES" ] || { echo "seed.sh: $FIXTURES missing; run scripts/link-fixtures.sh" >&2; exit 2; } -command -v ffmpeg >/dev/null || { echo "seed.sh: ffmpeg needed for the small video seeds" >&2; exit 2; } +FIXTURES=${EC_FIXTURES:-$(cd -- "$FUZZ_DIR/../../.." && pwd)/fixtures} +[ -d "$FIXTURES" ] || { echo "seed.sh: $FIXTURES missing; run scripts/fixtures.sh" >&2; exit 2; } +[ -x "$FF" ] || { echo "seed.sh: ffmpeg needed for the small video seeds" >&2; exit 2; } MP4_DIR="$FUZZ_DIR/corpus/demux_mp4" ESDS_DIR="$FUZZ_DIR/corpus/esds_parse" @@ -34,7 +36,7 @@ for src in "$FIXTURES"/audio/*.mp4 "$FIXTURES"/audio/*.m4a "$FIXTURES"/audio/*.m # Shorten until it fits: a 4K intra frame alone can be most of a megabyte. cut="" for secs in 0.2 0.05 0.01; do - ffmpeg -v error -y -t "$secs" -i "$src" -c copy -map 0 -movflags +faststart "$TMP/$stem.mp4" \ + "$FF" -v error -y -t "$secs" -i "$src" -c copy -map 0 -movflags +faststart "$TMP/$stem.mp4" \ || { echo "seed.sh: ffmpeg could not cut $src" >&2; exit 2; } if [ "$(stat -c %s "$TMP/$stem.mp4")" -le "$LIMIT" ]; then cut=1; break; fi done diff --git a/crates/ec-mp4/tests/data/gen.sh b/crates/ec-mp4/tests/data/gen.sh index 866540cc..dd4560ce 100755 --- a/crates/ec-mp4/tests/data/gen.sh +++ b/crates/ec-mp4/tests/data/gen.sh @@ -18,15 +18,19 @@ # Usage: crates/ec-mp4/tests/data/gen.sh set -euo pipefail +FF=${EC_FFMPEG:-$HOME/.cache/ec-ffmpeg/ffmpeg} +FP=$(dirname "$FF")/ffprobe +export FF FP + here=$(cd -- "$(dirname -- "$0")" && pwd) src=$(mktemp --suffix=.mp4) trap 'rm -f -- "$src"' EXIT -ffmpeg -nostdin -y -v error -f lavfi \ +"$FF" -nostdin -y -v error -f lavfi \ -i "testsrc2=size=320x240:rate=24:duration=1" \ -c:v libx264 -profile:v baseline -pix_fmt yuv420p "$src" for deg in 0 90 180 270 45; do - ffmpeg -nostdin -y -v error -display_rotation "$deg" -i "$src" \ + "$FF" -nostdin -y -v error -display_rotation "$deg" -i "$src" \ -c copy "$here/rot$deg.mp4" done diff --git a/crates/ec-mp4/tests/it/chapters.rs b/crates/ec-mp4/tests/it/chapters.rs index 5251dc1a..d0a2f774 100644 --- a/crates/ec-mp4/tests/it/chapters.rs +++ b/crates/ec-mp4/tests/it/chapters.rs @@ -4,7 +4,6 @@ use std::io::Cursor; use std::path::PathBuf; -use std::process::Command; use ec_core::{ AudioParameters, Buf, ChannelLayout, CodecId, CodecParameters, Demuxer, MediaParameters, Muxer, Packet, @@ -43,11 +42,11 @@ fn ffprobe_chapters(bytes: &[u8], name: &str) -> Vec<(i64, String)> { std::fs::create_dir_all(&dir).unwrap(); let path: PathBuf = dir.join(name); std::fs::write(&path, bytes).unwrap(); - let out = Command::new("ffprobe") + let out = ec_testkit::ffprobe() .args(["-v", "error", "-show_chapters", "-of", "default"]) .arg(&path) .output() - .expect("ffprobe on PATH"); + .expect("ffprobe runs"); assert!(out.status.success(), "ffprobe failed: {:?}", out.stderr); let text = String::from_utf8_lossy(&out.stdout); let mut chapters = Vec::new(); diff --git a/crates/ec-mp4/tests/it/dts.rs b/crates/ec-mp4/tests/it/dts.rs index e1222919..3f2d700b 100644 --- a/crates/ec-mp4/tests/it/dts.rs +++ b/crates/ec-mp4/tests/it/dts.rs @@ -3,32 +3,23 @@ //! rate and channels the `ddts` box states; the writer round-trips `dtsc`. use std::io::Cursor; -use std::process::Command; use ec_core::{Buf, CodecId, Demuxer, MediaParameters, Muxer}; use ec_mp4::{Mp4Demuxer, Mp4Muxer}; -fn required() -> bool { - std::env::var_os("EC_REQUIRE_FIXTURES").is_some_and(|v| !v.is_empty() && v != "0") -} - -fn ffmpeg_mp4(tag: &str) -> Option> { +fn ffmpeg_mp4(tag: &str) -> Vec { let out = std::env::temp_dir().join(format!("ec-mp4-dts-{tag}-{}.mp4", std::process::id())); - let ok = Command::new("ffmpeg") + let ok = ec_testkit::ffmpeg() .args(["-v", "error", "-y", "-f", "lavfi", "-i"]) .arg("sine=frequency=440:sample_rate=48000:duration=0.5") .args(["-ac", "2", "-c:a", "dca", "-strict", "-2"]) .arg(&out) .output() .is_ok_and(|o| o.status.success()); - if !ok { - assert!(!required(), "ffmpeg cannot make a DTS mp4"); - eprintln!("skip: no ffmpeg with the dca encoder"); - return None; - } + assert!(ok, "ffmpeg cannot make a DTS mp4"); let bytes = std::fs::read(&out).unwrap(); let _ = std::fs::remove_file(out); - Some(bytes) + bytes } fn packets(d: &mut Mp4Demuxer>>) -> Vec { @@ -56,9 +47,7 @@ fn ddts(rate: u32, mask: u16) -> Vec { #[test] fn ffmpeg_dts_in_mp4a_is_dts() { - let Some(bytes) = ffmpeg_mp4("a") else { - return; - }; + let bytes = ffmpeg_mp4("a"); let mut d = Mp4Demuxer::new(Cursor::new(bytes)).unwrap(); assert_eq!(d.streams()[0].params.codec, CodecId::Dts); assert_eq!(audio(&d), (48_000, 2)); @@ -67,9 +56,7 @@ fn ffmpeg_dts_in_mp4a_is_dts() { #[test] fn dtsc_entry_round_trips_with_ddts_rate_and_channels() { - let Some(bytes) = ffmpeg_mp4("b") else { - return; - }; + let bytes = ffmpeg_mp4("b"); let mut d = Mp4Demuxer::new(Cursor::new(bytes)).unwrap(); let pkts = packets(&mut d); let mut info = d.streams()[0].clone(); diff --git a/crates/ec-mp4/tests/it/edit_trim.rs b/crates/ec-mp4/tests/it/edit_trim.rs index f297ee50..964ca28f 100644 --- a/crates/ec-mp4/tests/it/edit_trim.rs +++ b/crates/ec-mp4/tests/it/edit_trim.rs @@ -50,18 +50,19 @@ fn default_output() -> Vec { muxer.into_inner().into_inner() } -/// The MD5 of `bytes`, from the `md5sum` tool. A missing tool skips the check. -fn md5_of(bytes: &[u8]) -> Option { +/// The MD5 of `bytes`, from the `md5sum` tool. +fn md5_of(bytes: &[u8]) -> String { let dir = std::env::temp_dir().join("ec-mp4-edit-trim"); - std::fs::create_dir_all(&dir).ok()?; + std::fs::create_dir_all(&dir).expect("work dir"); let path = dir.join(format!("md5-{}.mp4", std::process::id())); - std::fs::write(&path, bytes).ok()?; - let out = Command::new("md5sum").arg(&path).output().ok()?; + std::fs::write(&path, bytes).expect("write"); + let out = Command::new("md5sum").arg(&path).output().expect("md5sum runs"); let _ = std::fs::remove_file(&path); String::from_utf8_lossy(&out.stdout) .split_whitespace() .next() - .map(str::to_string) + .expect("md5sum output") + .to_string() } /// Pinned before `set_edit` was added: the default output of the AAC priming @@ -70,11 +71,11 @@ const DEFAULT_AAC_PRIMING_MD5: &str = "2ba0fd44a7dfa3b69cb60d7aceb71753"; #[test] fn default_aac_priming_output_is_byte_identical() { - let bytes = default_output(); - match md5_of(&bytes) { - Some(sum) => assert_eq!(sum, DEFAULT_AAC_PRIMING_MD5, "default output changed"), - None => eprintln!("skip: md5sum is not installed"), - } + assert_eq!( + md5_of(&default_output()), + DEFAULT_AAC_PRIMING_MD5, + "default output changed" + ); } /// The big-endian `u32` at `offset` into the payload of the first `kind` box in @@ -85,10 +86,9 @@ fn payload_u32(bytes: &[u8], kind: &[u8; 4], offset: usize) -> Option { Some(u32::from_be_bytes([raw[0], raw[1], raw[2], raw[3]])) } -/// `key=value` lines from `ffprobe`, keyed by name. `None` where ffprobe is not -/// installed, which skips the check. -fn ffprobe_fields(path: &Path, select: &str, entries: &str) -> Option> { - let out = Command::new("ffprobe") +/// `key=value` lines from `ffprobe`, keyed by name. +fn ffprobe_fields(path: &Path, select: &str, entries: &str) -> Vec<(String, String)> { + let out = ec_testkit::ffprobe() .args([ "-v", "error", @@ -100,14 +100,12 @@ fn ffprobe_fields(path: &Path, select: &str, entries: &str) -> Option f64 { @@ -164,20 +162,15 @@ fn set_edit_trims_the_audio_edit_to_its_stated_length() { .join(format!("trim-{}.mp4", std::process::id())); std::fs::create_dir_all(path.parent().expect("dir")).expect("work dir"); std::fs::write(&path, &bytes).expect("write"); - let stream_fields = ffprobe_fields(&path, "a:0", "stream=start_time,duration"); - if let Some(fields) = stream_fields { - let frame = 1024.0 / 48_000.0; - let want = f64::from(PICTURE) / 48_000.0; - let duration = field(&fields, "duration"); - let start = field(&fields, "start_time"); - eprintln!("ffprobe a:0 start_time {start} duration {duration} (picture {want})"); - assert!( - (duration - want).abs() <= frame, - "stream duration {duration} against the picture's {want}" - ); - assert!(start.abs() < 1e-6, "start_time {start} is not zero"); - } else { - eprintln!("skip ffprobe: not installed"); - } + let fields = ffprobe_fields(&path, "a:0", "stream=start_time,duration"); + let frame = 1024.0 / 48_000.0; + let want = f64::from(PICTURE) / 48_000.0; + let duration = field(&fields, "duration"); + let start = field(&fields, "start_time"); + assert!( + (duration - want).abs() <= frame, + "stream duration {duration} against the picture's {want}" + ); + assert!(start.abs() < 1e-6, "start_time {start} is not zero"); let _ = std::fs::remove_file(&path); } diff --git a/crates/ec-mp4/tests/it/edith_parity.rs b/crates/ec-mp4/tests/it/edith_parity.rs index 1de89333..cdaa152a 100644 --- a/crates/ec-mp4/tests/it/edith_parity.rs +++ b/crates/ec-mp4/tests/it/edith_parity.rs @@ -3,15 +3,7 @@ //! for field. This is the swap criterion for edith's `mp4::` demuxer: identical //! packet bytes, identical timestamps, identical stream metadata. //! -//! The corpus is three sets, each optional where it is not in the checkout: -//! -//! - `fixtures/` (video, audio and the derived shapes): always, through the -//! usual `../../fixtures` symlink. -//! - edith's `assets/*.mp4|mov|m4a` when `EC_EDITH_ASSETS` names the directory -//! (default `/home/user/Documents/Code/Rust/edith/assets`; skipped with a -//! note when absent). -//! - the generated cases from `scripts/gen-mp4-parity-corpus.sh` when -//! `EC_MP4_PARITY_CORPUS` names its output directory. +//! The corpus is the generated `mp4corpus/` family under the fixtures root. //! //! Per track, the comparison is: codec, coded size, sample rate, channels, //! timebase, rotation, and per sample the byte offset, size, presentation time @@ -29,7 +21,6 @@ use std::collections::HashMap; use std::fs::File; use std::io::BufReader; use std::path::{Path, PathBuf}; -use std::process::Command; use ec_core::{CodecId, Demuxer, MediaParameters}; use ec_mp4::{Mp4Demuxer, Sample}; @@ -58,7 +49,7 @@ fn records(text: &str, first: &str) -> Vec { } fn ffprobe(path: &Path, entries: &str, first: &str) -> Vec { - let out = Command::new("ffprobe") + let out = ec_testkit::ffprobe() .args(["-v", "error", "-show_entries", entries, "-of", "default=nw=1"]) .arg(path) .output() @@ -129,7 +120,7 @@ fn probe_streams(path: &Path, rotations: &HashMap) -> Vec /// stream dump. The `side_data=rotation` entry query is not used: on a 2 GB film /// ffprobe spends minutes decoding for it, while the JSON dump is immediate. fn rotations(path: &Path) -> HashMap { - let out = Command::new("ffprobe") + let out = ec_testkit::ffprobe() .args(["-v", "error", "-show_streams", "-of", "json"]) .arg(path) .output() @@ -354,33 +345,7 @@ fn collect(dir: &Path, files: &mut Vec) { fn corpus() -> Vec { let mut files = Vec::new(); - collect(&Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures"), &mut files); - let assets = std::env::var("EC_EDITH_ASSETS") - .unwrap_or_else(|_| "/home/user/Documents/Code/Rust/edith/assets".into()); - if Path::new(&assets).is_dir() { - collect(Path::new(&assets), &mut files); - } else { - eprintln!("edith_parity: no edith assets at {assets}; skipped"); - } - // The real library: the local films the scan recorded as mp4-family, when - // they are still on this machine. A missing file is skipped, as the scan does. - if let Ok(manifest) = std::fs::read_to_string( - Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/real-library-manifest.tsv"), - ) { - for line in manifest.lines().skip(1) { - let mut fields = line.split('\t'); - let (Some(path), Some(container)) = (fields.next(), fields.next()) else { - continue; - }; - if container.contains("mp4") && Path::new(path).is_file() { - files.push(PathBuf::from(path)); - } - } - } - match std::env::var("EC_MP4_PARITY_CORPUS") { - Ok(dir) => collect(Path::new(&dir), &mut files), - Err(_) => eprintln!("edith_parity: EC_MP4_PARITY_CORPUS unset; generated cases skipped"), - } + collect(&ec_testkit::root().join("mp4corpus"), &mut files); files.sort(); files.dedup(); files @@ -389,7 +354,7 @@ fn corpus() -> Vec { #[test] fn every_corpus_file_matches_ffprobe_sample_for_sample() { let files = corpus(); - assert!(!files.is_empty(), "no mp4/mov corpus; run scripts/link-fixtures.sh"); + assert!(!files.is_empty(), "no mp4/mov corpus; run scripts/fixtures.sh"); let mut report = Vec::new(); let mut failures = Vec::new(); for path in &files { @@ -415,16 +380,14 @@ fn every_corpus_file_matches_ffprobe_sample_for_sample() { /// order. #[test] fn edith_trim_and_display_order_read_the_known_fixtures() { - let aac = Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../../fixtures/audio/aac-mp4-stereo-48000.mp4"); + let aac = ec_testkit::fixture("audio/aac-mp4-stereo-48000.mp4"); let demuxer = Mp4Demuxer::new(BufReader::new(File::open(&aac).expect("fixture"))) .expect("the fixture demuxes"); assert_eq!(demuxer.presentation_trim(0), Some(1024)); assert_eq!(demuxer.first_frame_sample(0), 2, "the trim lands on packet 2"); assert!(demuxer.sync_in_display_order(0).is_empty(), "no ctts, no reorder"); - let gop = Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../../fixtures/video/h264-open-gop.mp4"); + let gop = ec_testkit::fixture("video/h264-open-gop.mp4"); let demuxer = Mp4Demuxer::new(BufReader::new(File::open(&gop).expect("fixture"))) .expect("the fixture demuxes"); let syncs = demuxer.sync_in_display_order(0); diff --git a/crates/ec-mp4/tests/it/mp4.rs b/crates/ec-mp4/tests/it/mp4.rs index fb35f8da..fd87da36 100644 --- a/crates/ec-mp4/tests/it/mp4.rs +++ b/crates/ec-mp4/tests/it/mp4.rs @@ -7,7 +7,6 @@ use std::fs::File; use std::io::{BufReader, BufWriter, Cursor}; use std::path::{Path, PathBuf}; -use std::process::Command; use ec_core::{ Buf, CodecId, Demuxer, Error, MediaParameters, Muxer, Packet, SeekMode, StreamInfo, TimeBase, @@ -18,7 +17,7 @@ use ec_mp4::{Mp4Demuxer, Mp4Muxer}; use crate::common::ffmpeg_name; fn fixtures() -> PathBuf { - Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures") + ec_testkit::root() } fn work() -> PathBuf { @@ -48,7 +47,7 @@ fn riff_avi_is_not_reported_as_a_truncated_mp4() { /// One ffprobe field per stream, in stream order. fn probe_field(path: &Path, entries: &str) -> Vec { - let out = Command::new("ffprobe") + let out = ec_testkit::ffprobe() .args(["-v", "error", "-show_entries", entries, "-of", "csv=p=0"]) .arg(path) .output() @@ -111,7 +110,7 @@ fn mp4_fixtures() -> Vec { .iter() .flat_map(|dir| { std::fs::read_dir(fixtures().join(dir)) - .expect("fixtures (run scripts/gen-fixtures.sh)") + .expect("fixtures (run scripts/fixtures.sh)") .filter_map(|e| e.ok().map(|e| e.path())) }) .filter(|p| { @@ -185,7 +184,7 @@ fn make_derived(dst: &Path, args: &[&str]) -> bool { return true; } let tmp = dst.with_file_name(format!("tmp-{}-{name}", std::process::id())); - let ok = Command::new("ffmpeg") + let ok = ec_testkit::ffmpeg() .args(["-v", "error", "-y"]) .args(args) .arg(&tmp) @@ -326,7 +325,7 @@ fn every_fixture_remuxes_into_a_file_ffprobe_and_ffmpeg_agree_with() { ); // ...and it decodes, which is the only claim a field compare cannot make. - let decode = Command::new("ffmpeg") + let decode = ec_testkit::ffmpeg() .args(["-v", "error", "-i"]) .arg(&dst) .args(["-f", "null", "-"]) @@ -411,7 +410,7 @@ fn the_hand_written_extensions_come_out_as_ffprobe_reads_them() { "colr nclx read back" ); let side = String::from_utf8_lossy( - &Command::new("ffprobe") + &ec_testkit::ffprobe() .args(["-v", "error", "-show_streams", "-of", "json"]) .arg(&dst) .output() @@ -470,7 +469,7 @@ fn the_hand_written_extensions_come_out_as_ffprobe_reads_them() { assert_eq!(probe_field(&dst, "stream=codec_name"), vec!["mov_text"]); assert_eq!(probe_field(&dst, "stream_tags=language"), vec!["tur"]); let text = String::from_utf8_lossy( - &Command::new("ffmpeg") + &ec_testkit::ffmpeg() .args(["-v", "error", "-i"]) .arg(&dst) .args(["-f", "srt", "-"]) @@ -527,7 +526,7 @@ fn an_aac_tracks_audio_specific_config_survives_as_bytes() { fn a_non_aac_mp4a_entry_is_not_dropped() { let dst = work().join("mp3-in-mp4.mp4"); let src = fixtures().join("audio/mp3-stereo-44100.mp3"); - let ok = Command::new("ffmpeg") + let ok = ec_testkit::ffmpeg() .args(["-v", "error", "-y", "-i"]) .arg(&src) .args(["-c", "copy"]) @@ -653,11 +652,7 @@ fn a_truncated_file_is_need_more() { #[test] fn truncated_prefixes_are_need_more_or_eof() { - let mut paths = vec![fixtures().join("audio/aac-mp4-stereo-48000.mp4")]; - let real = PathBuf::from("/home/user/Downloads/reelj (11).mp4"); - if real.exists() { - paths.push(real); - } + let paths = [fixtures().join("audio/aac-mp4-stereo-48000.mp4")]; for path in paths { let data = std::fs::read(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display())); @@ -789,114 +784,6 @@ fn aac_priming_round_trips_through_an_elst() { ); } -/// The real library, end to end: every mp4-family file the manifest lists -/// demuxes to EOF with the packet counts ffprobe counts. -/// -/// Ignored by default because it reads eleven gigabytes. Run it with -/// `cargo test -p ec-mp4 --release --test it mp4::the_real_library -- --ignored --nocapture`. -#[test] -#[ignore = "reads the real library end to end"] -fn the_real_library_demuxes_to_eof() { - let manifest = std::fs::read_to_string(fixtures().join("real-library-manifest.tsv")) - .expect("the real-library manifest (run scripts/scan-real-library.sh)"); - let files: Vec<&str> = manifest - .lines() - .skip(1) - .filter_map(|line| { - let mut fields = line.split('\t'); - let path = fields.next()?; - fields.next()?.contains("mp4").then_some(path) - }) - .collect(); - assert!(!files.is_empty(), "no mp4-family files in the manifest"); - - let mut table = Vec::new(); - let mut failed = Vec::new(); - for path in files { - let path = Path::new(path); - if !path.exists() { - table.push(format!("{:<58} GONE", name_of(path))); - continue; - } - let mut demuxer = open(path); - let kinds: Vec = demuxer.streams().iter().map(|s| s.params.codec).collect(); - let mut ours = vec![0u64; kinds.len()]; - loop { - match demuxer.next_packet() { - Ok(packet) => ours[packet.stream as usize] += 1, - Err(Error::Eof) => break, - Err(e) => { - failed.push(format!("{}: {e}", name_of(path))); - break; - } - } - } - // ffprobe counts the same packets on the same file. Two shapes are not - // a disagreement: cover art, which ffmpeg lists as an attached-picture - // video stream and which is metadata rather than a track; and a track - // whose last sample ffmpeg hands out one fewer of than its sample table - // states (`nb_frames`) — where ours equals the table, the table is what - // the file says. - let counted = Command::new("ffprobe") - .args([ - "-v", - "error", - "-count_packets", - "-show_entries", - "stream=codec_type,nb_read_packets,nb_frames:stream_disposition=attached_pic", - "-of", - "csv=p=0", - ]) - .arg(path) - .output() - .expect("ffprobe runs"); - // One line a stream: type, packets counted, frames the sample table - // states, and whether it is cover art. - let rows: Vec> = String::from_utf8_lossy(&counted.stdout) - .lines() - .map(|l| { - l.split(',') - .map(|f| f.trim().to_string()) - .collect::>() - }) - .filter(|row| { - matches!( - row.first().map(String::as_str), - Some("video" | "audio" | "subtitle") - ) && row.get(3).map(String::as_str) != Some("1") - }) - .collect(); - let theirs: Vec = rows - .iter() - .map(|r| r.get(1).and_then(|n| n.parse().ok()).unwrap_or(0)) - .collect(); - let tables: Vec = rows - .iter() - .map(|r| r.get(2).and_then(|n| n.parse().ok()).unwrap_or(0)) - .collect(); - let same = ours == theirs; - let by_table = !same && ours == tables; - if !same && !by_table { - failed.push(format!( - "{}: ours {ours:?} against ffprobe {theirs:?}", - name_of(path) - )); - } - table.push(format!( - "{:<58} {:<18} ours {ours:?} ffprobe {theirs:?} {}", - name_of(path), - kinds.iter().map(|c| c.name()).collect::>().join("+"), - match (same, by_table) { - (true, _) => "PASS".to_string(), - (_, true) => format!("PASS (sample table {tables:?})"), - _ => "FAIL".to_string(), - } - )); - } - println!("{}", table.join("\n")); - assert!(failed.is_empty(), "{}", failed.join("\n")); -} - fn name_of(path: &Path) -> String { let name = path.file_name().unwrap_or_default().to_string_lossy(); name.chars().take(56).collect() @@ -905,7 +792,7 @@ fn name_of(path: &Path) -> String { /// The extradata ffprobe reads out of a stream, as bytes: its `-show_data` /// hexdump, which is the only place it prints the octets themselves. fn probe_extradata(path: &Path, stream: &str) -> Vec { - let out = Command::new("ffprobe") + let out = ec_testkit::ffprobe() .args([ "-v", "error", @@ -992,51 +879,6 @@ fn quicktime_sound_description_states_its_esds_inside_wave() { assert_eq!(got, iso_extra, "QuickTime and ISO read different extradata"); } -/// The real exports this shape was found in: set `EC_MP4_QT_MOV` to a -/// colon-separated list of `.mov` files to check this crate against ffprobe on -/// files that are not in the corpus. -#[test] -fn real_quicktime_exports_demux_like_ffprobe_says() { - let Ok(list) = std::env::var("EC_MP4_QT_MOV") else { - return; - }; - for path in list.split(':').filter(|p| !p.is_empty()).map(Path::new) { - assert!(path.exists(), "{}: not there", path.display()); - let want = probe_extradata(path, "a:0"); - let demuxer = open(path); - let audio = demuxer - .streams() - .iter() - .find(|s| matches!(s.params.media, MediaParameters::Audio(_))) - .unwrap_or_else(|| panic!("{}: no sound track", path.display())); - let MediaParameters::Audio(params) = &audio.params.media else { - unreachable!() - }; - let rate = probe_field(path, "stream=sample_rate") - .into_iter() - .find(|f| !f.is_empty() && f != "N/A") - .and_then(|f| f.trim().parse::().ok()) - .expect("ffprobe states a sample rate"); - assert_eq!(audio.params.codec, CodecId::Aac, "{}", path.display()); - assert_eq!(params.sample_rate, rate, "{}", path.display()); - let got = audio - .params - .extradata - .as_ref() - .map(|b| b.as_ref().to_vec()) - .unwrap_or_default(); - assert_eq!(got, want, "{}: extradata", path.display()); - println!( - "{}: {:?} {} Hz {} ch, extradata {}", - path.display(), - audio.params.codec, - params.sample_rate, - params.layout.channel_count(), - got.len() - ); - } -} - /// A box with a four-character type and its payload, sized the way ISOBMFF sizes it. fn boxed(kind: &[u8; 4], payload: &[u8]) -> Vec { let mut out = ((payload.len() + 8) as u32).to_be_bytes().to_vec(); diff --git a/crates/ec-mp4/tests/it/mux_entries.rs b/crates/ec-mp4/tests/it/mux_entries.rs index 96639f58..65ca6124 100644 --- a/crates/ec-mp4/tests/it/mux_entries.rs +++ b/crates/ec-mp4/tests/it/mux_entries.rs @@ -4,14 +4,10 @@ //! our file to the same samples as the source, since the packets are the same //! bytes. This crate's own demuxer reads our file back to the same packets with //! the same timestamps and keyframe flags. -//! -//! A case is skipped, not failed, where ffmpeg or the encoder it needs is not -//! built in, the way the other ffmpeg-backed tests skip. use std::fs::File; use std::io::{BufReader, BufWriter}; use std::path::{Path, PathBuf}; -use std::process::Command; use ec_core::{Demuxer, Error, Muxer, Packet}; use ec_mp4::{Mp4Demuxer, Mp4Muxer}; @@ -197,33 +193,22 @@ fn work(case: &Case) -> PathBuf { dir } -/// Whether `tool` runs at all. -fn have(tool: &str) -> bool { - Command::new(tool) - .arg("-version") - .output() - .is_ok_and(|o| o.status.success()) -} - /// Whether ffmpeg was built with `encoder`. fn has_encoder(encoder: &str) -> bool { - Command::new("ffmpeg") + ec_testkit::ffmpeg() .args(["-hide_banner", "-encoders"]) .output() .is_ok_and(|o| String::from_utf8_lossy(&o.stdout).contains(&format!(" {encoder} "))) } -/// Makes the source for `case` at `path`, or says why it cannot. `false` is a -/// skip. -fn make_source(case: &Case, path: &Path) -> bool { - if !has_encoder(case.encoder) { - eprintln!( - "skip {}: ffmpeg has no {} encoder", - case.entry, case.encoder - ); - return false; - } - let ok = Command::new("ffmpeg") +/// Makes the source for `case` at `path`. +fn make_source(case: &Case, path: &Path) { + assert!( + has_encoder(case.encoder), + "ffmpeg has no {} encoder", + case.encoder + ); + let ok = ec_testkit::ffmpeg() .args(["-hide_banner", "-v", "error", "-y"]) .args(case.args) .args(["-f", "mp4"]) @@ -232,7 +217,6 @@ fn make_source(case: &Case, path: &Path) -> bool { .expect("ffmpeg runs") .success(); assert!(ok, "ffmpeg could not make the {} source", case.entry); - true } /// Every packet of `path`, and the streams it declares. @@ -306,7 +290,7 @@ fn remux(src: &Path, dst: &Path) { /// ffprobe's stderr for `path`, with the full-decode check ffmpeg runs over it. fn ffprobe_stderr(path: &Path) -> String { - let out = Command::new("ffprobe") + let out = ec_testkit::ffprobe() .args(["-v", "error", "-show_streams", "-show_format"]) .arg(path) .output() @@ -316,7 +300,7 @@ fn ffprobe_stderr(path: &Path) -> String { /// One ffprobe CSV field list per stream, for `entries` (`stream=...`). fn probe_lines(path: &Path, entries: &str) -> Vec { - let out = Command::new("ffprobe") + let out = ec_testkit::ffprobe() .args(["-v", "error", "-show_entries", entries, "-of", "csv=p=0"]) .arg(path) .output() @@ -339,7 +323,7 @@ fn duration(path: &Path) -> f64 { /// `MD5=...`. Any stderr from the decode is returned too: a clean file says /// nothing. fn decoded_md5(path: &Path, map: &str) -> (String, String) { - let out = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args(["-hide_banner", "-v", "error", "-i"]) .arg(path) .args(["-map", map, "-f", "md5", "-"]) @@ -352,16 +336,10 @@ fn decoded_md5(path: &Path, map: &str) -> (String, String) { } fn run_case(case: &Case) { - if !have("ffmpeg") || !have("ffprobe") { - eprintln!("skip {}: ffmpeg or ffprobe is not installed", case.entry); - return; - } let dir = work(case); let src = dir.join("source.mp4"); let out = dir.join("ours.mp4"); - if !make_source(case, &src) { - return; - } + make_source(case, &src); remux(&src, &out); // (a) ffprobe reads our file cleanly and states what the source states. @@ -468,16 +446,10 @@ fn every_entry_is_ffprobe_clean_decodes_equal_and_round_trips() { #[test] fn opus_pre_skip_is_written_without_a_caller_asking() { let case = &CASES[7]; - if !have("ffmpeg") || !have("ffprobe") { - eprintln!("skip {}: ffmpeg or ffprobe is not installed", case.entry); - return; - } let dir = work(case); let src = dir.join("source.mp4"); let out = dir.join("bare.mp4"); - if !make_source(case, &src) { - return; - } + make_source(case, &src); let (streams, packets) = read_all(&src); let shifts = Vec::new(); write_out(&out, &streams, &packets, &shifts, false); @@ -500,16 +472,10 @@ fn opus_pre_skip_is_written_without_a_caller_asking() { #[test] fn alac_bare_cookie_is_written_inside_an_alac_box() { let case = &CASES[6]; - if !have("ffmpeg") || !have("ffprobe") { - eprintln!("skip {}: ffmpeg or ffprobe is not installed", case.entry); - return; - } let dir = work(case); let src = dir.join("source.mp4"); let out = dir.join("bare-cookie.mp4"); - if !make_source(case, &src) { - return; - } + make_source(case, &src); let (mut streams, packets) = read_all(&src); let boxed = streams[0] .params diff --git a/crates/ec-mp4/tests/it/prores_entries.rs b/crates/ec-mp4/tests/it/prores_entries.rs index 7494bb2a..1192dc23 100644 --- a/crates/ec-mp4/tests/it/prores_entries.rs +++ b/crates/ec-mp4/tests/it/prores_entries.rs @@ -1,17 +1,15 @@ //! The ProRes sample entries (`apco apcs apcn apch ap4h ap4x`) read as `CodecId::ProRes`. Each -//! source is a one-frame ffmpeg `prores_ks` mov written at test time; skipped where ffmpeg or the -//! encoder is missing, unless `EC_REQUIRE_FIXTURES` is set. +//! source is a one-frame ffmpeg `prores_ks` mov written at test time. use std::fs::File; use std::io::BufReader; -use std::process::Command; use ec_core::registry::CodecId; use ec_core::Demuxer; use ec_mp4::Mp4Demuxer; fn has_prores_ks() -> bool { - Command::new("ffmpeg") + ec_testkit::ffmpeg() .args(["-hide_banner", "-encoders"]) .output() .map(|o| String::from_utf8_lossy(&o.stdout).contains("prores_ks")) @@ -20,10 +18,7 @@ fn has_prores_ks() -> bool { #[test] fn prores_fourccs_are_recognised() { - if !has_prores_ks() { - assert!(std::env::var_os("EC_REQUIRE_FIXTURES").is_none(), "ffmpeg prores_ks required"); - return; - } + assert!(has_prores_ks(), "ffmpeg prores_ks required"); let dir = std::env::temp_dir().join(format!("ec-mp4-prores-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); for (profile, fmt, fourcc) in [ @@ -35,7 +30,7 @@ fn prores_fourccs_are_recognised() { ("5", "yuv444p10le", "ap4x"), ] { let path = dir.join(format!("{fourcc}.mov")); - let ok = Command::new("ffmpeg") + let ok = ec_testkit::ffmpeg() .args(["-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=size=64x48:rate=25", "-frames:v", "1"]) .args(["-c:v", "prores_ks", "-profile", profile, "-pix_fmt", fmt]) .arg(&path) diff --git a/crates/ec-mp4/tests/it/qt_pcm_hdr.rs b/crates/ec-mp4/tests/it/qt_pcm_hdr.rs index 27f41cc8..eddbc6cf 100644 --- a/crates/ec-mp4/tests/it/qt_pcm_hdr.rs +++ b/crates/ec-mp4/tests/it/qt_pcm_hdr.rs @@ -1,33 +1,24 @@ //! QuickTime PCM sound descriptions (`in24`, `in32`, `fl32` with `wave/enda` //! and `chan`) and the HDR `mdcv`/`clli` boxes, checked against ffmpeg. //! -//! Sources are synthetic (ffmpeg `sine`, `testsrc2`). A case skips where -//! ffmpeg or an encoder is missing, unless `EC_REQUIRE_FIXTURES` is set. +//! Sources are synthetic (ffmpeg `sine`, `testsrc2`). use std::fs::File; use std::io::{BufReader, BufWriter}; use std::path::{Path, PathBuf}; -use std::process::Command; use ec_core::{ContentLight, Demuxer, Error, MasteringPrimaries, Muxer, Packet, StreamInfo}; use ec_mp4::{Mp4Demuxer, Mp4Muxer}; -fn skip(why: &str) -> bool { +fn require_encoder(encoder: &str) { + let out = ec_testkit::ffmpeg() + .args(["-hide_banner", "-encoders"]) + .output() + .expect("ffmpeg runs"); assert!( - std::env::var_os("EC_REQUIRE_FIXTURES").is_none(), - "EC_REQUIRE_FIXTURES set but: {why}" + String::from_utf8_lossy(&out.stdout).contains(&format!(" {encoder} ")), + "ffmpeg has no {encoder} encoder" ); - eprintln!("skip: {why}"); - true -} - -fn have_ffmpeg(encoder: &str) -> bool { - let out = Command::new("ffmpeg") - .args(["-hide_banner", "-encoders"]) - .output(); - let ok = out.is_ok_and(|o| String::from_utf8_lossy(&o.stdout).contains(&format!(" {encoder} "))) - && Command::new("ffprobe").arg("-version").output().is_ok(); - ok || !skip(&format!("no ffmpeg/ffprobe or no {encoder}")) } fn dir(name: &str) -> PathBuf { @@ -72,7 +63,7 @@ fn entry(path: &Path, fourcc: &[u8; 4]) -> Option> { } fn probe(path: &Path, args: &[&str]) -> String { - let out = Command::new("ffprobe") + let out = ec_testkit::ffprobe() .args(["-v", "error"]) .args(args) .arg(path) @@ -83,7 +74,7 @@ fn probe(path: &Path, args: &[&str]) -> String { } fn decoded_md5(path: &Path) -> String { - let out = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args(["-v", "error", "-i"]) .arg(path) .args(["-map", "0:a:0", "-f", "md5", "-"]) @@ -93,12 +84,10 @@ fn decoded_md5(path: &Path) -> String { } fn pcm_case(name: &str, codec: &str, channels: u32, fourcc: &[u8; 4], layout_box: bool) { - if !have_ffmpeg(codec) { - return; - } + require_encoder(codec); let d = dir(name); let src = d.join("src.mov"); - let ok = Command::new("ffmpeg") + let ok = ec_testkit::ffmpeg() .args(["-v", "error", "-y", "-f", "lavfi", "-i", "sine=d=0.5:sample_rate=48000"]) .args(["-ac", &channels.to_string(), "-c:a", codec]) .arg(&src) @@ -169,12 +158,10 @@ fn pcm_sample_entries_are_ffprobe_clean_and_byte_equal() { /// (no `chan`), and one that does gets ffmpeg's. #[test] fn sowt_gets_chan_only_when_asked() { - if !have_ffmpeg("pcm_s16le") { - return; - } + require_encoder("pcm_s16le"); let d = dir("sowt"); let src = d.join("src.mov"); - assert!(Command::new("ffmpeg") + assert!(ec_testkit::ffmpeg() .args(["-v", "error", "-y", "-f", "lavfi", "-i", "sine=d=0.2:sample_rate=48000", "-ac", "2", "-c:a", "pcm_s16le"]) .arg(&src) .status() @@ -203,12 +190,10 @@ fn light() -> ContentLight { /// Main 10 HEVC, remuxed with `mdcv` and `clli`. #[test] fn hevc_main10_mdcv_clli_in_mp4() { - if !have_ffmpeg("libx265") { - return; - } + require_encoder("libx265"); let d = dir("hdr"); let src = d.join("src.mp4"); - assert!(Command::new("ffmpeg") + assert!(ec_testkit::ffmpeg() .args(["-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=size=320x240:rate=25:duration=1"]) .args(["-c:v", "libx265", "-pix_fmt", "yuv420p10le", "-tag:v", "hvc1"]) .args(["-x265-params", "log-level=error:colorprim=bt2020:transfer=smpte2084:colormatrix=bt2020nc"]) diff --git a/crates/ec-mpegts/Cargo.toml b/crates/ec-mpegts/Cargo.toml index c9c70464..22ad19e1 100644 --- a/crates/ec-mpegts/Cargo.toml +++ b/crates/ec-mpegts/Cargo.toml @@ -12,3 +12,6 @@ ec-dvdsub.workspace = true ec-h264-syntax.workspace = true ec-h265-syntax.workspace = true ec-truehd.workspace = true + +[dev-dependencies] +ec-testkit.workspace = true diff --git a/crates/ec-mpegts/tests/data/gen.sh b/crates/ec-mpegts/tests/data/gen.sh index 65cce2db..bfde1dcb 100755 --- a/crates/ec-mpegts/tests/data/gen.sh +++ b/crates/ec-mpegts/tests/data/gen.sh @@ -4,17 +4,21 @@ # expected.txt: # LPCM is hashed over ffmpeg's s16be decode, which is what the demuxer's packets are. set -euo pipefail + +FF=${EC_FFMPEG:-$HOME/.cache/ec-ffmpeg/ffmpeg} +FP=$(dirname "$FF")/ffprobe +export FF FP cd "$(dirname "$0")" V=(-f lavfi -i testsrc2=size=160x120:rate=25:duration=0.6) A=(-f lavfi -i sine=frequency=440:sample_rate=48000:duration=0.6) X=(-c:v libx264 -preset ultrafast -g 12 -bf 2) -ffmpeg -v error -y "${V[@]}" "${A[@]}" "${X[@]}" -c:a aac -f mpegts tiny_h264_aac.ts -ffmpeg -v error -y "${V[@]}" "${A[@]}" "${X[@]}" -c:a ac3 -f mpegts -mpegts_m2ts_mode 1 tiny_h264_ac3.m2ts -ffmpeg -v error -y "${V[@]}" "${A[@]}" "${X[@]}" -c:a eac3 -f mpegts tiny_h264_eac3.ts -ffmpeg -v error -y -f lavfi -i testsrc2=size=160x120:rate=25:duration=0.3 -f lavfi -i sine=frequency=440:sample_rate=48000:duration=0.3 "${X[@]}" -c:a pcm_bluray -f mpegts -mpegts_m2ts_mode 1 tiny_h264_lpcm.m2ts -ffmpeg -v error -y "${V[@]}" "${A[@]}" -c:v libx265 -preset ultrafast -g 12 -x265-params log-level=none -c:a aac -f mpegts tiny_hevc_aac.ts +"$FF" -v error -y "${V[@]}" "${A[@]}" "${X[@]}" -c:a aac -f mpegts tiny_h264_aac.ts +"$FF" -v error -y "${V[@]}" "${A[@]}" "${X[@]}" -c:a ac3 -f mpegts -mpegts_m2ts_mode 1 tiny_h264_ac3.m2ts +"$FF" -v error -y "${V[@]}" "${A[@]}" "${X[@]}" -c:a eac3 -f mpegts tiny_h264_eac3.ts +"$FF" -v error -y -f lavfi -i testsrc2=size=160x120:rate=25:duration=0.3 -f lavfi -i sine=frequency=440:sample_rate=48000:duration=0.3 "${X[@]}" -c:a pcm_bluray -f mpegts -mpegts_m2ts_mode 1 tiny_h264_lpcm.m2ts +"$FF" -v error -y "${V[@]}" "${A[@]}" -c:v libx265 -preset ultrafast -g 12 -x265-params log-level=none -c:a aac -f mpegts tiny_hevc_aac.ts python3 -I - <<'PY' -import subprocess +import os, subprocess def fnv(b): h = 0xcbf29ce484222325 for x in b: @@ -24,10 +28,10 @@ rows = [] for f in ["tiny_h264_aac.ts", "tiny_h264_ac3.m2ts", "tiny_h264_eac3.ts", "tiny_h264_lpcm.m2ts", "tiny_hevc_aac.ts"]: for idx, codec in enumerate(["video", "audio"]): if codec == "audio" and "lpcm" in f: - data = subprocess.run(["ffmpeg","-v","error","-i",f,"-map","0:1","-f","s16be","-"],capture_output=True,check=True).stdout + data = subprocess.run([os.environ["FF"],"-v","error","-i",f,"-map","0:1","-f","s16be","-"],capture_output=True,check=True).stdout else: - data = subprocess.run(["ffmpeg","-v","error","-i",f,"-map",f"0:{idx}","-c","copy","-f","data","-"],capture_output=True,check=True).stdout - pk = subprocess.run(["ffprobe","-v","error","-select_streams",str(idx),"-show_entries","packet=pts","-of","csv=p=0",f],capture_output=True,check=True).stdout.split() + data = subprocess.run([os.environ["FF"],"-v","error","-i",f,"-map",f"0:{idx}","-c","copy","-f","data","-"],capture_output=True,check=True).stdout + pk = subprocess.run([os.environ["FP"],"-v","error","-select_streams",str(idx),"-show_entries","packet=pts","-of","csv=p=0",f],capture_output=True,check=True).stdout.split() rows.append(f"{f} {idx} {len(pk)} {len(data)} {fnv(data):016x}") open("expected.txt","w").write("\n".join(rows) + "\n") PY diff --git a/crates/ec-mpegts/tests/data/gen_ps.sh b/crates/ec-mpegts/tests/data/gen_ps.sh index cbeefd70..67f74b63 100755 --- a/crates/ec-mpegts/tests/data/gen_ps.sh +++ b/crates/ec-mpegts/tests/data/gen_ps.sh @@ -3,15 +3,19 @@ # sources (testsrc2 and sine only). Needs ffmpeg with mpeg2video, mpeg1video, ac3, mp2. # expected_ps.txt: set -euo pipefail + +FF=${EC_FFMPEG:-$HOME/.cache/ec-ffmpeg/ffmpeg} +FP=$(dirname "$FF")/ffprobe +export FF FP cd "$(dirname "$0")" V=(-f lavfi -i testsrc2=size=128x96:rate=25:duration=0.5) A=(-f lavfi -i sine=frequency=440:sample_rate=48000:duration=0.5) -ffmpeg -v error -y "${V[@]}" "${A[@]}" -c:v mpeg2video -g 12 -bf 2 -b:v 150k -c:a ac3 -b:a 96k -f vob ps_mpeg2_ac3.vob -ffmpeg -v error -y "${V[@]}" "${A[@]}" -c:v mpeg1video -g 9 -bf 2 -b:v 120k -c:a mp2 -b:a 96k -f mpeg ps_mpeg1_mp2.mpg -ffmpeg -v error -y "${V[@]}" -c:v mpeg2video -g 12 -bf 2 -b:v 150k -f mpeg2video ps_mpeg2.m2v -ffmpeg -v error -y "${V[@]}" -f lavfi -i sine=frequency=440:sample_rate=48000:duration=0.5 -c:v mpeg2video -g 12 -b:v 150k -c:a pcm_dvd -f vob ps_pcm_dvd.vob +"$FF" -v error -y "${V[@]}" "${A[@]}" -c:v mpeg2video -g 12 -bf 2 -b:v 150k -c:a ac3 -b:a 96k -f vob ps_mpeg2_ac3.vob +"$FF" -v error -y "${V[@]}" "${A[@]}" -c:v mpeg1video -g 9 -bf 2 -b:v 120k -c:a mp2 -b:a 96k -f mpeg ps_mpeg1_mp2.mpg +"$FF" -v error -y "${V[@]}" -c:v mpeg2video -g 12 -bf 2 -b:v 150k -f mpeg2video ps_mpeg2.m2v +"$FF" -v error -y "${V[@]}" -f lavfi -i sine=frequency=440:sample_rate=48000:duration=0.5 -c:v mpeg2video -g 12 -b:v 150k -c:a pcm_dvd -f vob ps_pcm_dvd.vob python3 -I - <<'PY' -import subprocess +import os, subprocess def fnv(b): h = 0xcbf29ce484222325 for x in b: @@ -20,10 +24,10 @@ def fnv(b): rows = [] for f, streams in [("ps_mpeg2_ac3.vob", 2), ("ps_mpeg1_mp2.mpg", 2), ("ps_mpeg2.m2v", 1), ("ps_pcm_dvd.vob", 2)]: for idx in range(streams): - data = subprocess.run(["ffmpeg","-v","error","-i",f,"-map",f"0:{idx}","-c","copy","-f","data","-"],capture_output=True,check=True).stdout + data = subprocess.run([os.environ["FF"],"-v","error","-i",f,"-map",f"0:{idx}","-c","copy","-f","data","-"],capture_output=True,check=True).stdout if "pcm_dvd" in f and idx == 1: - data = subprocess.run(["ffmpeg","-v","error","-i",f,"-map","0:1","-f","s16be","-"],capture_output=True,check=True).stdout - pk = subprocess.run(["ffprobe","-v","error","-select_streams",str(idx),"-show_entries","packet=pts","-of","csv=p=0",f],capture_output=True,check=True).stdout.split() + data = subprocess.run([os.environ["FF"],"-v","error","-i",f,"-map","0:1","-f","s16be","-"],capture_output=True,check=True).stdout + pk = subprocess.run([os.environ["FP"],"-v","error","-select_streams",str(idx),"-show_entries","packet=pts","-of","csv=p=0",f],capture_output=True,check=True).stdout.split() rows.append(f"{f} {idx} {len(pk)} {len(data)} {fnv(data):016x}") open("expected_ps.txt","w").write("\n".join(rows) + "\n") PY diff --git a/crates/ec-mpegts/tests/it/common.rs b/crates/ec-mpegts/tests/it/common.rs index 9461d5be..68cc6637 100644 --- a/crates/ec-mpegts/tests/it/common.rs +++ b/crates/ec-mpegts/tests/it/common.rs @@ -1,43 +1,15 @@ -//! Shared helpers: ffmpeg/ffprobe fixtures, packet dumps and the skip convention -//! (`EC_REQUIRE_FIXTURES` turns a skip into a failure). +//! Shared helpers: ffmpeg fixtures and packet dumps. #![allow(dead_code)] use std::collections::HashMap; use std::fs::File; use std::io::BufReader; use std::path::{Path, PathBuf}; -use std::process::Command; use std::sync::OnceLock; use ec_core::registry::Demuxer; use ec_mpegts::TsDemuxer; -pub fn required() -> bool { - std::env::var_os("EC_REQUIRE_FIXTURES").is_some_and(|v| !v.is_empty() && v != "0") -} - -/// True when ffmpeg and ffprobe can be run; otherwise prints a skip note (or panics -/// when fixtures are required). -pub fn have_ffmpeg() -> bool { - static OK: OnceLock = OnceLock::new(); - let ok = *OK.get_or_init(|| { - ["ffmpeg", "ffprobe"].iter().all(|t| { - Command::new(t) - .arg("-version") - .output() - .is_ok_and(|o| o.status.success()) - }) - }); - if !ok { - assert!( - !required(), - "EC_REQUIRE_FIXTURES is set but ffmpeg/ffprobe are missing" - ); - eprintln!("skip: ffmpeg/ffprobe not available"); - } - ok -} - pub fn fixture_dir() -> PathBuf { static DIR: OnceLock = OnceLock::new(); DIR.get_or_init(|| { @@ -61,9 +33,9 @@ pub const AUDIO_SRC: &[&str] = &[ "sine=frequency=440:sample_rate=48000:duration=3", ]; -/// Runs ffmpeg; `Err` carries stderr. Unavailable encoders are a skip. +/// Runs ffmpeg; `Err` carries stderr. pub fn ffmpeg(args: &[&str], out: &Path) -> Result<(), String> { - let o = Command::new("ffmpeg") + let o = ec_testkit::ffmpeg() .args(["-v", "error", "-y"]) .args(args) .arg(out) @@ -76,30 +48,21 @@ pub fn ffmpeg(args: &[&str], out: &Path) -> Result<(), String> { } } -/// Generates `name` with `args` (input options included) or returns `None` on skip. -pub fn fixture(name: &str, args: &[&str]) -> Option { - if !have_ffmpeg() { - return None; - } +/// Generates `name` with `args` (input options included). +pub fn fixture(name: &str, args: &[&str]) -> PathBuf { // Tests run on threads of one process: one generates a given file at a time. static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); let _guard = LOCK.lock().unwrap_or_else(|e| e.into_inner()); let out = fixture_dir().join(name); if out.exists() { - return Some(out); + return out; } let tmp = fixture_dir().join(format!("{name}.{}.tmp", std::process::id())); - match ffmpeg(args, &tmp) { - Ok(()) => { - std::fs::rename(&tmp, &out).unwrap(); - Some(out) - } - Err(e) => { - assert!(!required(), "ffmpeg failed for {name}: {e}"); - eprintln!("skip {name}: {e}"); - None - } + if let Err(e) = ffmpeg(args, &tmp) { + panic!("ffmpeg failed for {name}: {e}"); } + std::fs::rename(&tmp, &out).unwrap(); + out } pub fn open(path: &Path) -> TsDemuxer> { @@ -143,7 +106,7 @@ pub struct Row { } pub fn ffprobe_rows(path: &Path) -> HashMap)> { - let streams = Command::new("ffprobe") + let streams = ec_testkit::ffprobe() .args([ "-v", "error", @@ -167,7 +130,7 @@ pub fn ffprobe_rows(path: &Path) -> HashMap)> { pid_of.insert(i, p); } } - let pk = Command::new("ffprobe") + let pk = ec_testkit::ffprobe() .args([ "-v", "error", @@ -204,7 +167,7 @@ pub fn ffprobe_rows(path: &Path) -> HashMap)> { /// ffmpeg's stream copy of stream `index`, as one byte string. pub fn ffmpeg_bytes(path: &Path, index: u32) -> Vec { - let o = Command::new("ffmpeg") + let o = ec_testkit::ffmpeg() .args(["-v", "error", "-i"]) .arg(path) .args([ @@ -223,7 +186,7 @@ pub fn ffmpeg_bytes(path: &Path, index: u32) -> Vec { /// ffmpeg's decode of an LPCM stream as big-endian 16-bit samples. pub fn ffmpeg_pcm_s16be(path: &Path, index: u32) -> Vec { - Command::new("ffmpeg") + ec_testkit::ffmpeg() .args(["-v", "error", "-i"]) .arg(path) .args(["-map", &format!("0:{index}"), "-f", "s16be", "-"]) diff --git a/crates/ec-mpegts/tests/it/dts.rs b/crates/ec-mpegts/tests/it/dts.rs index 9e2cff32..6426352a 100644 --- a/crates/ec-mpegts/tests/it/dts.rs +++ b/crates/ec-mpegts/tests/it/dts.rs @@ -7,7 +7,7 @@ use ec_core::CodecId; use ec_core::registry::{Demuxer, MediaParameters}; use ec_mpegts::StreamKind; -fn dts_ts(name: &str, channels: &str) -> Option { +fn dts_ts(name: &str, channels: &str) -> std::path::PathBuf { fixture( name, &[ @@ -28,9 +28,7 @@ fn dts_ts(name: &str, channels: &str) -> Option { } fn check(name: &str, channels: &str, want: usize) { - let Some(p) = dts_ts(name, channels) else { - return; - }; + let p = dts_ts(name, channels); let mut d = open(&p); let streams = d.streams().to_vec(); assert_eq!(streams.len(), 1); @@ -98,9 +96,7 @@ fn rewrite_pmt(ts: &[u8], stream_type: u8, descriptors: &[u8]) -> Vec { #[test] fn dts_hd_stream_types_and_descriptors_map_to_dts() { - let Some(p) = dts_ts("dts_retag.ts", "2") else { - return; - }; + let p = dts_ts("dts_retag.ts", "2"); let ts = std::fs::read(&p).unwrap(); let cases: [(&str, u8, Vec); 5] = [ ("0x82", 0x82, vec![]), diff --git a/crates/ec-mpegts/tests/it/ffmpeg_parity.rs b/crates/ec-mpegts/tests/it/ffmpeg_parity.rs index 6f84970c..17ae7ab0 100644 --- a/crates/ec-mpegts/tests/it/ffmpeg_parity.rs +++ b/crates/ec-mpegts/tests/it/ffmpeg_parity.rs @@ -2,14 +2,13 @@ //! bytes, sizes, timestamps, keyframe flags, duration, plus seek exactness. //! //! Fixtures are generated at test time from synthetic sources (testsrc2, sine). The -//! tests skip, saying so, when ffmpeg is absent and fail instead when -//! `EC_REQUIRE_FIXTURES` is set. + use crate::common::*; use ec_core::registry::{Demuxer, SeekMode}; use ec_core::{CodecId, TimeBase, Timestamp}; -fn v264(name: &str, extra: &[&str], mux: &[&str]) -> Option { +fn v264(name: &str, extra: &[&str], mux: &[&str]) -> std::path::PathBuf { let mut a: Vec<&str> = VIDEO_SRC.to_vec(); a.extend_from_slice(AUDIO_SRC); a.extend_from_slice(&[ @@ -191,7 +190,7 @@ fn cleanup_none() {} /// One test over a table so every case runs and all failures are named. #[test] fn parity_cases() { - type Case = (&'static str, fn() -> Option); + type Case = (&'static str, fn() -> std::path::PathBuf); const CASES: &[Case] = &[ ("h264_aac_ts", || { v264("h264_aac.ts", &["-c:a", "aac"], &["-f", "mpegts"]) @@ -243,7 +242,7 @@ fn parity_cases() { let mut failures = Vec::new(); for &(name, make) in CASES { let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - let Some(p) = make() else { return }; + let p = make(); parity(&p); duration_ok(&p); seek_exact(&p); @@ -257,9 +256,7 @@ fn parity_cases() { #[test] fn mp2_in_ts_is_exposed_as_mp2() { - let Some(p) = v264("h264_mp2.ts", &["-c:a", "mp2"], &["-f", "mpegts"]) else { - return; - }; + let p = v264("h264_mp2.ts", &["-c:a", "mp2"], &["-f", "mpegts"]); let d = open(&p); let audio: Vec<_> = d .streams() @@ -273,7 +270,7 @@ fn mp2_in_ts_is_exposed_as_mp2() { ); assert!(d.tracks().iter().all(|t| t.refusal.is_none())); } -fn audio_only(name: &str, codec: &str, rate: &str, extra: &[&str]) -> Option { +fn audio_only(name: &str, codec: &str, rate: &str, extra: &[&str]) -> std::path::PathBuf { let mut a: Vec<&str> = vec![ "-f", "lavfi", @@ -293,9 +290,7 @@ fn audio_only(name: &str, codec: &str, rate: &str, extra: &[&str]) -> Option Option { +fn hevc(name: &str, audio: &str) -> std::path::PathBuf { let mut a: Vec<&str> = VIDEO_SRC.to_vec(); a.extend_from_slice(AUDIO_SRC); a.extend_from_slice(&[ @@ -346,9 +339,7 @@ fn hevc(name: &str, audio: &str) -> Option { #[test] fn codecs_and_extradata() { - let Some(p) = v264("h264_aac.ts", &["-c:a", "aac"], &["-f", "mpegts"]) else { - return; - }; + let p = v264("h264_aac.ts", &["-c:a", "aac"], &["-f", "mpegts"]); let d = open(&p); let s = d.streams(); assert_eq!(s[0].params.codec, CodecId::H264); @@ -363,7 +354,7 @@ fn codecs_and_extradata() { assert_eq!(s[1].params.audio().unwrap().sample_rate, 48000); } -fn two_programs() -> Option { +fn two_programs() -> std::path::PathBuf { let mut a: Vec<&str> = VIDEO_SRC.to_vec(); a.extend_from_slice(AUDIO_SRC); a.extend_from_slice(&[ @@ -397,7 +388,7 @@ fn two_programs() -> Option { #[test] fn multiple_programs() { - let Some(p) = two_programs() else { return }; + let p = two_programs(); let d = open(&p); let progs = d.programs(); assert_eq!(progs.len(), 2, "{progs:?}"); @@ -437,9 +428,7 @@ fn pts_wrap_is_unwrapped() { "-f", "mpegts", ]); - let Some(p) = fixture("wrap.ts", &a) else { - return; - }; + let p = fixture("wrap.ts", &a); let mut d = open(&p); let pkts = read_all(&mut d); for s in d.streams() { @@ -470,9 +459,7 @@ fn pts_wrap_is_unwrapped() { /// packet not flagged corrupt is one the intact file has. #[test] fn corrupted_and_truncated() { - let Some(p) = v264("h264_aac.ts", &["-c:a", "aac"], &["-f", "mpegts"]) else { - return; - }; + let p = v264("h264_aac.ts", &["-c:a", "aac"], &["-f", "mpegts"]); let good = std::fs::read(&p).unwrap(); let mut d = open(&p); let want = read_all(&mut d); diff --git a/crates/ec-mpegts/tests/it/mpeg2.rs b/crates/ec-mpegts/tests/it/mpeg2.rs index b8de02b1..0e3c403f 100644 --- a/crates/ec-mpegts/tests/it/mpeg2.rs +++ b/crates/ec-mpegts/tests/it/mpeg2.rs @@ -1,6 +1,6 @@ //! MPEG-1/2 video in transport streams: exposed as `CodecId::Mpeg2Video`, one //! packet per coded picture, parameters from the sequence header. Fixtures come from -//! ffmpeg's synthetic testsrc2 and skip (fail under `EC_REQUIRE_FIXTURES`) without it. +//! ffmpeg's synthetic testsrc2. use crate::common::*; use ec_core::registry::Demuxer; @@ -15,7 +15,7 @@ fn pictures(d: &[u8]) -> Vec { } fn check(codec: &str, name: &str, mpeg2: bool) { - let Some(ts) = fixture( + let ts = fixture( name, &[ "-f", @@ -33,16 +33,13 @@ fn check(codec: &str, name: &str, mpeg2: bool) { "-f", "mpegts", ], - ) else { - return; - }; + ); let es = fixture_dir().join(format!("{name}.m2v")); if let Err(e) = ffmpeg( &["-i", ts.to_str().unwrap(), "-c", "copy", "-f", codec], &es, ) { - assert!(!required(), "es extraction failed: {e}"); - return; + panic!("es extraction failed: {e}"); } let want = std::fs::read(&es).unwrap(); let mut d = open(&ts); diff --git a/crates/ec-mpegts/tests/it/ps.rs b/crates/ec-mpegts/tests/it/ps.rs index e815aefd..7b3b9ec5 100644 --- a/crates/ec-mpegts/tests/it/ps.rs +++ b/crates/ec-mpegts/tests/it/ps.rs @@ -2,8 +2,7 @@ //! ffmpeg's demux on ffmpeg-made files (bytes, sizes, timestamps, key flags), //! duration, seek exactness, SCR resets, PTS wraps and damaged files. //! -//! Fixtures are generated at test time from synthetic sources; the tests skip when -//! ffmpeg is missing and fail instead under `EC_REQUIRE_FIXTURES`. +//! Fixtures are generated at test time from synthetic sources. use std::fs::File; use std::io::BufReader; @@ -61,7 +60,7 @@ fn src(extra_audio: &[&str]) -> Vec<&'static str> { a } -fn mkps(name: &str, video: &[&str], audio: &[&str], mux: &[&str]) -> Option { +fn mkps(name: &str, video: &[&str], audio: &[&str], mux: &[&str]) -> PathBuf { let mut a = src(audio); a.extend_from_slice(video); a.extend_from_slice(audio); @@ -153,7 +152,7 @@ fn parity(path: &Path, slack: i64) { } fn raw_rows(path: &Path) -> Vec { - let o = std::process::Command::new("ffprobe") + let o = ec_testkit::ffprobe() .args([ "-v", "error", @@ -182,7 +181,7 @@ fn raw_rows(path: &Path) -> Vec { } fn ffmpeg_pcm(path: &Path, index: u32, fmt: &str) -> Vec { - std::process::Command::new("ffmpeg") + ec_testkit::ffmpeg() .args(["-v", "error", "-i"]) .arg(path) .args(["-map", &format!("0:{index}"), "-f", fmt, "-"]) @@ -318,7 +317,7 @@ fn seek_exact(path: &Path) { /// exactness). One test over a table: every case runs and all failures are named. #[test] fn ps_parity_cases() { - type Case = (&'static str, fn() -> Option); + type Case = (&'static str, fn() -> std::path::PathBuf); const CASES: &[Case] = &[ ("mpeg1_system_mp2", || { mkps( @@ -466,7 +465,7 @@ fn ps_parity_cases() { let mut failures = Vec::new(); for &(name, make) in CASES { let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - let Some(p) = make() else { return }; + let p = make(); parity(&p, 0); duration_ok(&p); seek_exact(&p); @@ -482,28 +481,24 @@ fn ps_parity_cases() { // mid-stream cannot know the phase: no seek-exactness check for it. #[test] fn pcm_dvd_24() { - let Some(p) = mkps( + let p = mkps( "lpcm24.vob", V2, &["-c:a", "pcm_dvd", "-sample_fmt", "s32"], &["-f", "vob"], - ) else { - return; - }; + ); parity(&p, 0); duration_ok(&p); } #[test] fn dts_is_refused_by_name() { - let Some(p) = mkps( + let p = mkps( "dts.vob", V2, &["-c:a", "dca", "-strict", "-2"], &["-f", "vob"], - ) else { - return; - }; + ); let d = open_ps(&p); assert_eq!(d.streams().len(), 1); let t = d.tracks(); @@ -636,7 +631,7 @@ fn concatenated_vobs_keep_time_monotonic() { #[test] fn concatenated_dvd_files_with_nav_packets() { - let Some(p) = mkps( + let p = mkps( "dvd2.vob", &[ "-vf", @@ -652,17 +647,13 @@ fn concatenated_dvd_files_with_nav_packets() { ], &["-c:a", "ac3", "-ar", "48000"], &["-f", "dvd"], - ) else { - return; - }; + ); check_concat(&std::fs::read(p).unwrap(), 2, None); } #[test] fn starts_mid_gop() { - let Some(p) = mkps("v_ac3.vob", V2, &["-c:a", "ac3"], &["-f", "vob"]) else { - return; - }; + let p = mkps("v_ac3.vob", V2, &["-c:a", "ac3"], &["-f", "vob"]); let orig_bytes = std::fs::read(&p).unwrap(); let mut o = open_ps(&p); let orig = read_ps(&mut o); @@ -883,14 +874,12 @@ fn mutated_files_never_panic() { #[test] fn pts_wrap_is_unwrapped() { - let Some(p) = mkps( + let p = mkps( "wrap.vob", V2, &["-c:a", "ac3"], &["-output_ts_offset", "95442", "-f", "vob"], - ) else { - return; - }; + ); let mut d = open_ps(&p); let v = read_ps(&mut d); let pts: Vec = v @@ -950,7 +939,7 @@ fn video_index(d: &D) -> u32 { } fn frames_by_ffprobe(path: &Path) -> usize { - let o = std::process::Command::new("ffprobe") + let o = ec_testkit::ffprobe() .args(["-v", "error", "-count_frames", "-select_streams", "v:0"]) .args(["-show_entries", "stream=nb_read_frames", "-of", "csv=p=0"]) .arg(path) @@ -994,9 +983,7 @@ fn tail_picture_without_a_timestamp_is_counted() { a.extend_from_slice(&[ "-pix_fmt", "yuv420p", "-map", "1:a", "-c:a", "mp2", "-f", "mpeg", ]); - if let Some(p) = fixture(name, &a) { - cases.push(p); - } + cases.push(fixture(name, &a)); } for path in cases { let mut d = open_ps(&path); @@ -1026,7 +1013,7 @@ fn tail_picture_without_a_timestamp_is_counted() { } /// Two VOBs of 2.4 s joined by bytes: SCR and PTS restart at the join. -fn joined_vob() -> Option<(PathBuf, u64)> { +fn joined_vob() -> (PathBuf, u64) { let mk = |name: &str, vf: &str, hz: &str| { let video = format!("testsrc2=size=352x288:rate=25:duration=2.4{vf}"); let audio = format!("sine=frequency={hz}:sample_rate=48000:duration=2.4"); @@ -1062,8 +1049,8 @@ fn joined_vob() -> Option<(PathBuf, u64)> { ]; fixture(name, &a) }; - let a = mk("pstail-a.vob", "", "440")?; - let b = mk("pstail-b.vob", ",negate", "880")?; + let a = mk("pstail-a.vob", "", "440"); + let b = mk("pstail-b.vob", ",negate", "880"); let out = fixture_dir().join("pstail-join.vob"); let alen = std::fs::metadata(&a).unwrap().len(); if !out.exists() { @@ -1074,14 +1061,12 @@ fn joined_vob() -> Option<(PathBuf, u64)> { std::fs::write(&tmp, bytes).unwrap(); std::fs::rename(&tmp, &out).unwrap(); } - Some((out, alen)) + (out, alen) } #[test] fn joined_vobs_have_the_summed_duration() { - let Some((path, _)) = joined_vob() else { - return; - }; + let (path, _) = joined_vob(); let d = open_ps(&path); let single = open_ps(&fixture_dir().join("pstail-a.vob")); let v = video_index(&d) as usize; @@ -1115,9 +1100,7 @@ fn joined_vobs_have_the_summed_duration() { #[test] fn seeks_on_both_sides_of_a_join_equal_the_sequential_decode() { - let Some((path, _)) = joined_vob() else { - return; - }; + let (path, _) = joined_vob(); let mut d = open_ps(&path); let v = video_index(&d); let all = read_ps(&mut d); @@ -1166,9 +1149,7 @@ fn seeks_on_both_sides_of_a_join_equal_the_sequential_decode() { #[test] fn audio_keeps_its_offset_to_the_video_after_a_join() { - let Some((path, alen)) = joined_vob() else { - return; - }; + let (path, alen) = joined_vob(); let mut d = open_ps(&path); let v = video_index(&d); let a = d @@ -1216,9 +1197,7 @@ fn ts_tail_picture_is_counted() { "-f", "lavfi", "-i", FLASH_SRC, "-c:v", codec, "-b:v", "2M", "-g", "10", "-bf", "2", "-pix_fmt", "yuv420p", "-f", "mpegts", ]; - let Some(path) = fixture(name, &a) else { - continue; - }; + let path = fixture(name, &a); let mut d = open(&path); let v = d .streams() diff --git a/crates/ec-mpegts/tests/it/truehd.rs b/crates/ec-mpegts/tests/it/truehd.rs index 11c689ac..47d88b2e 100644 --- a/crates/ec-mpegts/tests/it/truehd.rs +++ b/crates/ec-mpegts/tests/it/truehd.rs @@ -2,11 +2,9 @@ //! through `ec-truehd` to the PCM ffmpeg decodes from the same file, sample for sample. //! //! The fixture is made at test time by ffmpeg's own TrueHD encoder (a 440 Hz sine, -//! lavfi, no external media). The test skips, saying so, when ffmpeg is absent and -//! fails instead when `EC_REQUIRE_FIXTURES` is set. +//! lavfi, no external media). use std::path::Path; -use std::process::Command; use crate::common::*; use ec_core::registry::Demuxer; @@ -14,7 +12,7 @@ use ec_core::{CodecId, MediaParameters}; use ec_truehd::{AccessUnitHeader, TrueHdDecoder}; /// Stereo 48 kHz TrueHD in M2TS-style TS, as ffmpeg writes it (stream type 0x83). -fn truehd_ts(name: &str, channels: &str) -> Option { +fn truehd_ts(name: &str, channels: &str) -> std::path::PathBuf { let a = [ "-f", "lavfi", @@ -36,7 +34,7 @@ fn truehd_ts(name: &str, channels: &str) -> Option { /// ffmpeg's decode of the first audio stream as interleaved S32 little-endian. fn ffmpeg_s32le(path: &Path) -> Vec { - let out = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args(["-v", "error", "-nostdin", "-i"]) .arg(path) .args(["-map", "0:a:0", "-f", "s32le", "-"]) @@ -62,13 +60,8 @@ fn s32le(bytes: &[u8]) -> Vec { #[test] fn truehd_in_ts_decodes_sample_exact_to_ffmpeg() { - if !have_ffmpeg() { - return; - } - for (name, channels, want) in [("truehd_sine_2ch.ts", "2", 2usize)] { - let Some(path) = truehd_ts(name, channels) else { - return; - }; + for (name, channels, want) in [("truehd_sine_2ch.ts", "2", 2usize)] { + let path = truehd_ts(name, channels); let mut d = open(&path); let all = read_all(&mut d); let stream = d @@ -123,12 +116,7 @@ fn truehd_in_ts_decodes_sample_exact_to_ffmpeg() { fn truehd_packets_match_the_container_packet_form() { // The access units in the TS are the same bytes ffmpeg's stream copy writes out // (the MP4 and Matroska demuxers hand over the same form). - if !have_ffmpeg() { - return; - } - let Some(path) = truehd_ts("truehd_sine_2ch.ts", "2") else { - return; - }; + let path = truehd_ts("truehd_sine_2ch.ts", "2"); let mut d = open(&path); let all = read_all(&mut d); let stream = d @@ -142,7 +130,7 @@ fn truehd_packets_match_the_container_packet_form() { .filter(|p| p.stream == stream) .flat_map(|p| p.data) .collect(); - let o = Command::new("ffmpeg") + let o = ec_testkit::ffmpeg() .args(["-v", "error", "-nostdin", "-i"]) .arg(&path) .args(["-map", "0:a:0", "-c", "copy", "-f", "truehd", "-"]) @@ -263,10 +251,7 @@ fn ts5(prefix: u8, v: u64) -> [u8; 5] { #[test] fn ac3_core_interleaved_in_the_truehd_pid_is_dropped() { - if !have_ffmpeg() { - return; - } - let Some(raw) = fixture( + let raw = fixture( "truehd_sine_2ch.thd", &[ "-f", @@ -284,9 +269,7 @@ fn ac3_core_interleaved_in_the_truehd_pid_is_dropped() { "-f", "truehd", ], - ) else { - return; - }; + ); let aus = split_aus(&std::fs::read(&raw).unwrap()); assert!(aus.len() > 8, "enough access units"); diff --git a/crates/ec-ogg/Cargo.toml b/crates/ec-ogg/Cargo.toml index b6da65c4..758d9aa5 100644 --- a/crates/ec-ogg/Cargo.toml +++ b/crates/ec-ogg/Cargo.toml @@ -8,3 +8,6 @@ authors.workspace = true [dependencies] ec-core.workspace = true + +[dev-dependencies] +ec-testkit.workspace = true diff --git a/crates/ec-ogg/fuzz/seed.sh b/crates/ec-ogg/fuzz/seed.sh index 5c6bee80..c05823e8 100755 --- a/crates/ec-ogg/fuzz/seed.sh +++ b/crates/ec-ogg/fuzz/seed.sh @@ -14,9 +14,9 @@ set -euo pipefail FUZZ_DIR=$(cd -- "$(dirname -- "$0")" && pwd) ROOT=$(cd -- "$FUZZ_DIR/../../.." && pwd) -AUDIO="$ROOT/fixtures/audio" -VORBIS="$ROOT/fixtures/vectors/vorbis-xiph" -[ -d "$AUDIO" ] || { echo "seed.sh: $AUDIO missing; run scripts/link-fixtures.sh" >&2; exit 2; } +AUDIO="${EC_FIXTURES:-$ROOT/fixtures}/audio" +VORBIS="${EC_FIXTURES:-$ROOT/fixtures}/vectors/vorbis-xiph" +[ -d "$AUDIO" ] || { echo "seed.sh: $AUDIO missing; run scripts/fixtures.sh" >&2; exit 2; } CORPUS="$FUZZ_DIR/corpus" mkdir -p "$CORPUS"/{page_parse,demux,demux_raw,mapping,roundtrip} diff --git a/crates/ec-ogg/tests/ogg.rs b/crates/ec-ogg/tests/ogg.rs index 3ba5305a..012beb36 100644 --- a/crates/ec-ogg/tests/ogg.rs +++ b/crates/ec-ogg/tests/ogg.rs @@ -11,7 +11,6 @@ use std::io::Cursor; use std::path::{Path, PathBuf}; -use std::process::Command; use ec_core::{ Buf, CodecId, CodecParameters, Demuxer, MediaParameters, Muxer, Packet, PacketFlags, SeekMode, @@ -29,7 +28,7 @@ fn name_of(p: &std::path::Path) -> String { } fn fixtures() -> PathBuf { - Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/audio") + ec_testkit::root().join("audio") } /// Working directory keyed by test name: these tests are threads of one @@ -43,9 +42,7 @@ fn workdir(test: &str) -> PathBuf { /// Every Ogg fixture on disk, sorted so the table reads the same every run. fn ogg_fixtures() -> Vec { - let Ok(entries) = std::fs::read_dir(fixtures()) else { - return Vec::new(); - }; + let entries = std::fs::read_dir(fixtures()).expect("fixtures/audio (run scripts/fixtures.sh)"); let mut out: Vec = entries .flatten() .map(|e| e.path()) @@ -63,7 +60,7 @@ fn ogg_fixtures() -> Vec { /// Audio packets ffprobe counts in a file — header packets excluded, which is /// also what this demuxer hands out. fn ffprobe_packets(path: &Path) -> u64 { - let out = Command::new("ffprobe") + let out = ec_testkit::ffprobe() .args([ "-v", "error", @@ -86,7 +83,7 @@ fn ffprobe_packets(path: &Path) -> u64 { /// ffprobe's own duration for the file, in seconds. fn ffprobe_duration(path: &Path) -> f64 { - let out = Command::new("ffprobe") + let out = ec_testkit::ffprobe() .args([ "-v", "error", @@ -104,7 +101,7 @@ fn ffprobe_duration(path: &Path) -> f64 { /// Decode a file to raw 32-bit float samples with ffmpeg. Errors are fatal: an /// unreadable file is the failure being tested for. fn decode_pcm(path: &Path) -> Vec { - let out = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args(["-v", "error", "-i"]) .arg(path) .args(["-f", "f32le", "-"]) @@ -121,7 +118,7 @@ fn decode_pcm(path: &Path) -> Vec { /// ffprobe with errors escalated: the structural verdict on a file we wrote. fn ffprobe_clean(path: &Path) -> String { - let out = Command::new("ffprobe") + let out = ec_testkit::ffprobe() .args([ "-v", "error", @@ -161,10 +158,6 @@ fn demux_all(path: &Path) -> (Vec, Vec, u64) { #[test] fn demuxes_every_fixture_to_eof() { let files = ogg_fixtures(); - if files.is_empty() { - eprintln!("fixtures/audio absent (gitignored) — skipping"); - return; - } println!( "{:<28} {:>8} {:>8} {:>10} {:>10}", "file", "ours", "ffprobe", "dur", "ffprobe" @@ -320,10 +313,6 @@ fn remux_case(path: &Path, page_target: Option) { #[test] fn remuxes_every_fixture_bit_identically() { let files = ogg_fixtures(); - if files.is_empty() { - eprintln!("fixtures/audio absent (gitignored) — skipping"); - return; - } for path in &files { remux_case(path, None); } @@ -334,13 +323,10 @@ fn remuxes_every_fixture_bit_identically() { #[test] fn page_size_does_not_change_the_audio() { let files = ogg_fixtures(); - let Some(path) = files + let path = files .iter() .find(|p| name_of(p).contains("vorbis-ogg-stereo-48000")) - else { - eprintln!("fixtures absent — skipping"); - return; - }; + .expect("ogg fixture"); remux_case(path, Some(1)); remux_case(path, Some(1 << 20)); } @@ -348,13 +334,10 @@ fn page_size_does_not_change_the_audio() { #[test] fn damage_costs_one_page_and_no_more() { let files = ogg_fixtures(); - let Some(path) = files + let path = files .iter() .find(|p| name_of(p).contains("vorbis-ogg-stereo-44100")) - else { - eprintln!("fixtures absent — skipping"); - return; - }; + .expect("ogg fixture"); let (_, clean, _) = demux_all(path); let bytes = std::fs::read(path).unwrap(); @@ -407,10 +390,6 @@ fn damage_costs_one_page_and_no_more() { #[test] fn seeks_land_at_or_before_the_target() { let files = ogg_fixtures(); - if files.is_empty() { - eprintln!("fixtures absent — skipping"); - return; - } for path in files.iter().filter(|p| { let n = p.to_string_lossy().to_string(); n.contains("stereo-48000") || n.contains("5.1-44100") @@ -465,15 +444,12 @@ fn seeks_land_at_or_before_the_target() { #[test] fn reads_flac_in_ogg() { let files = ogg_fixtures(); - let Some(source) = files + let source = files .iter() .find(|p| name_of(p).contains("vorbis-ogg-stereo-44100")) - else { - eprintln!("fixtures absent — skipping"); - return; - }; + .expect("ogg fixture"); let path = workdir("flac").join("flac-in.ogg"); - let made = Command::new("ffmpeg") + let made = ec_testkit::ffmpeg() .args(["-v", "error", "-y", "-i"]) .arg(source) .args(["-c:a", "flac", "-f", "ogg"]) diff --git a/crates/ec-ogg/tests/real_library.rs b/crates/ec-ogg/tests/real_library.rs index 9d4c170c..5fc9397d 100644 --- a/crates/ec-ogg/tests/real_library.rs +++ b/crates/ec-ogg/tests/real_library.rs @@ -1,6 +1,5 @@ -//! The personal media library, Ogg half: every `ogg` row of -//! `fixtures/real-library-manifest.tsv` whose audio is Vorbis or Opus is read -//! by [`OggDemuxer`] end to end and compared with ffmpeg/ffprobe. +//! A real Ogg file, `open/sintel_trailer-480p.ogv`, is read by [`OggDemuxer`] +//! end to end and compared with ffmpeg/ffprobe. //! //! Per file the oracle checks: //! - packet count and every packet's size (ffprobe, audio stream 0); @@ -31,25 +30,13 @@ //! //! Scope: demux only. The decoded PCM is not compared here. //! -//! Each file either matches, is refused by name (no logical stream with a -//! known mapping), or fails. A refusal is reported, not counted as a failure. -//! -//! LOCAL ONLY and ignored: the manifest is generated from the user's own media -//! by `scripts/scan-real-library.sh` and is gitignored, so no other host has it. -//! cargo test -p ec-ogg --test real_library -- --ignored --nocapture +//! The file either matches or fails. A refusal is a failure here. -use std::path::{Path, PathBuf}; -use std::process::{Command, Stdio}; +use std::path::Path; use ec_core::Demuxer; use ec_ogg::{Mapping, OggDemuxer, granule_of}; -/// One manifest row: the columns the sweep reads. -struct Entry { - path: PathBuf, - acodecs: String, -} - /// One packet as ffprobe reports it. struct Probed { pts: Option, @@ -64,40 +51,6 @@ enum Verdict { Failed(String), } -fn have(tool: &str) -> bool { - Command::new(tool) - .arg("-version") - .stdout(Stdio::null()) - .stderr(Stdio::null()) - .status() - .is_ok_and(|s| s.success()) -} - -/// The manifest's Ogg rows with Vorbis or Opus audio, or `None` when the -/// manifest itself is absent. -fn manifest_ogg_entries() -> Option> { - let manifest = - Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/real-library-manifest.tsv"); - let text = std::fs::read_to_string(&manifest).ok()?; - let mut out = Vec::new(); - for line in text.lines().skip(1) { - let f: Vec<&str> = line.split('\t').collect(); - if f.len() < 8 || f[1] != "ogg" || !Path::new(f[0]).is_file() { - continue; - } - // The first audio stream decides the mapping this file is checked as. - let first = f[7].split(',').next().unwrap_or_default(); - if first != "vorbis" && first != "opus" { - continue; - } - out.push(Entry { - path: PathBuf::from(f[0]), - acodecs: f[7].to_string(), - }); - } - Some(out) -} - /// Parses an ffprobe csv cell: `N/A` and blanks are absent. fn cell(s: &str) -> Option { let s = s.trim(); @@ -110,7 +63,7 @@ fn cell(s: &str) -> Option { /// Audio stream 0's packets: header packets are not among them, as with ours. fn ffprobe_packets(path: &Path) -> Result, String> { - let out = Command::new("ffprobe") + let out = ec_testkit::ffprobe() .args([ "-v", "error", @@ -145,7 +98,7 @@ fn ffprobe_packets(path: &Path) -> Result, String> { /// ffprobe's stated extradata size for audio stream 0. fn ffprobe_extradata_size(path: &Path) -> Result { - let out = Command::new("ffprobe") + let out = ec_testkit::ffprobe() .args([ "-v", "error", @@ -168,7 +121,7 @@ fn ffprobe_extradata_size(path: &Path) -> Result { /// ffmpeg's concatenated audio packet payloads, copied and not decoded. fn ffmpeg_payload(path: &Path) -> Result, String> { - let out = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args(["-v", "error", "-i"]) .arg(path) .args(["-map", "0:a:0", "-c", "copy", "-f", "data", "-"]) @@ -355,63 +308,11 @@ fn vorbis_header_problem(block: &[u8]) -> Option { None } -fn short_name(path: &Path) -> String { - path.file_name() - .map(|n| n.to_string_lossy().chars().take(38).collect()) - .unwrap_or_default() -} - #[test] -#[ignore = "sweeps the PERSONAL media library (fixtures/real-library-manifest.tsv, ogg rows) through ffmpeg; local only: run with --ignored."] fn real_library_ogg_streams_match_ffmpeg() { - if !have("ffmpeg") || !have("ffprobe") { - eprintln!("skipped: ffmpeg and ffprobe are required to sweep the library"); - return; - } - let Some(entries) = manifest_ogg_entries() else { - eprintln!( - "skipped: no fixtures/real-library-manifest.tsv; generate it with \ - scripts/scan-real-library.sh on the machine that holds the media" - ); - return; - }; - if entries.is_empty() { - eprintln!("skipped: the manifest lists no ogg rows with vorbis or opus audio"); - return; + let path = ec_testkit::fixture("open/sintel_trailer-480p.ogv"); + match check_file(&path) { + Verdict::Match(s) => eprintln!("{}: match: {s}", path.display()), + Verdict::Refused(e) | Verdict::Failed(e) => panic!("{}: {e}", path.display()), } - - let mut table = String::new(); - let mut checked = 0usize; - let mut refused = 0usize; - let mut failures = Vec::new(); - for entry in &entries { - let name = short_name(&entry.path); - let codec = entry.acodecs.split(',').next().unwrap_or_default(); - let verdict = check_file(&entry.path); - let line = match verdict { - Verdict::Match(s) => { - checked += 1; - format!("{name:<38} {codec:<7} match: {s}\n") - } - Verdict::Refused(e) => { - refused += 1; - format!("{name:<38} {codec:<7} refused: {e}\n") - } - Verdict::Failed(e) => { - failures.push(format!("{name}: {e}")); - format!("{name:<38} {codec:<7} FAILED {e}\n") - } - }; - table.push_str(&line); - } - eprintln!("{table}"); - eprintln!( - "real library ogg: {checked} match, {refused} refused by name, {} failed", - failures.len() - ); - assert!(failures.is_empty(), "{failures:#?}"); - assert!( - checked + refused >= 1 && checked >= 1, - "no real Ogg file was checked end to end" - ); } diff --git a/crates/ec-probe/Cargo.toml b/crates/ec-probe/Cargo.toml index d7835c38..6a8aa309 100644 --- a/crates/ec-probe/Cargo.toml +++ b/crates/ec-probe/Cargo.toml @@ -22,3 +22,6 @@ ec-opus = { workspace = true } ec-riff = { workspace = true } ec-truehd = { workspace = true } ec-vorbis = { workspace = true } + +[dev-dependencies] +ec-testkit.workspace = true diff --git a/crates/ec-probe/src/lib.rs b/crates/ec-probe/src/lib.rs index 740fd840..ce9d88e3 100644 --- a/crates/ec-probe/src/lib.rs +++ b/crates/ec-probe/src/lib.rs @@ -1327,12 +1327,7 @@ mod tests { /// s: `1024` samples read straight off as `1024` one-millisecond ticks). #[test] fn duration_converts_initial_padding_out_of_sample_units() { - let path = Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../../fixtures/audio/aac-mka-stereo-48000.mka"); - if !path.exists() { - return; // fixtures are generated, not checked in - } - let reader = Reader::open(&path).unwrap(); + let reader = Reader::open(ec_testkit::fixture("audio/aac-mka-stereo-48000.mka")).unwrap(); let d = reader.duration().expect("a stated duration").as_secs_f64(); assert!((d - 3.0).abs() < 0.1, "duration {d}, want ~3.0s"); } diff --git a/crates/ec-probe/tests/dts.rs b/crates/ec-probe/tests/dts.rs index f48462e5..664ab421 100644 --- a/crates/ec-probe/tests/dts.rs +++ b/crates/ec-probe/tests/dts.rs @@ -4,17 +4,12 @@ //! and channels, and hand back the stream's bytes frame by frame. use std::path::{Path, PathBuf}; -use std::process::Command; use ec_core::CodecId; use ec_core::registry::{MediaType, SeekMode}; use ec_core::timebase::{TimeBase, Timestamp}; use ec_probe::{Format, Reader}; -fn required() -> bool { - std::env::var_os("EC_REQUIRE_FIXTURES").is_some_and(|v| !v.is_empty() && v != "0") -} - fn work() -> PathBuf { let d = std::env::temp_dir().join(format!("ec-probe-dts-{}", std::process::id())); std::fs::create_dir_all(&d).unwrap(); @@ -22,7 +17,7 @@ fn work() -> PathBuf { } fn ffmpeg(args: &[&str], out: &Path) -> bool { - Command::new("ffmpeg") + ec_testkit::ffmpeg() .args(["-v", "error", "-y"]) .args(args) .arg(out) @@ -31,7 +26,7 @@ fn ffmpeg(args: &[&str], out: &Path) -> bool { } /// A raw DTS stream of `channels` channels, 0.5 s at 48 kHz. -fn raw_dts(channels: &str) -> Option> { +fn raw_dts(channels: &str) -> Vec { static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); let _guard = LOCK.lock().unwrap_or_else(|e| e.into_inner()); let path = work().join(format!("{channels}.dts")); @@ -50,12 +45,8 @@ fn raw_dts(channels: &str) -> Option> { ], &path, ); - if !ok { - assert!(!required(), "ffmpeg cannot make a DTS fixture"); - eprintln!("skip: no ffmpeg with the dca encoder"); - return None; - } - std::fs::read(&path).ok() + assert!(ok, "ffmpeg cannot make a DTS fixture"); + std::fs::read(&path).unwrap() } fn wav_pcm_tagged(dts: &[u8], rate: u32) -> Vec { @@ -109,9 +100,7 @@ fn check(bytes: &[u8], file: &str, format: Format, channels: usize, want: &[u8]) #[test] fn raw_dts_stereo_and_51() { for (ch, n) in [("2", 2), ("6", 6)] { - let Some(raw) = raw_dts(ch) else { - return; - }; + let raw = raw_dts(ch); assert_eq!(&raw[..4], &[0x7F, 0xFE, 0x80, 0x01]); check(&raw, &format!("raw{ch}.dts"), Format::Dts, n, &raw); } @@ -119,9 +108,7 @@ fn raw_dts_stereo_and_51() { #[test] fn raw_dts_little_endian() { - let Some(raw) = raw_dts("2") else { - return; - }; + let raw = raw_dts("2"); let mut le = raw.clone(); for p in le.as_chunks_mut::<2>().0.iter_mut() { p.swap(0, 1); @@ -131,9 +118,7 @@ fn raw_dts_little_endian() { #[test] fn dts_in_wav_pcm_tag_and_2001_tag() { - let Some(raw) = raw_dts("2") else { - return; - }; + let raw = raw_dts("2"); check( &wav_pcm_tagged(&raw, 48_000), "pcm.wav", diff --git a/crates/ec-probe/tests/legacy_audio.rs b/crates/ec-probe/tests/legacy_audio.rs index a51283bc..0aa66507 100644 --- a/crates/ec-probe/tests/legacy_audio.rs +++ b/crates/ec-probe/tests/legacy_audio.rs @@ -1,19 +1,13 @@ //! IMA/MS ADPCM and G.711 through the probe (Reader + AudioDecoder) from //! ffmpeg-made WAV, AVI and MOV files, compared with ffmpeg's s16 decode. -//! Skips without ffmpeg unless `EC_REQUIRE_FIXTURES=1`. use std::path::PathBuf; -use std::process::Command; use ec_core::registry::MediaType; use ec_probe::{AudioDecoder, Reader}; #[test] fn legacy_audio_decodes_through_the_probe() { - if Command::new("ffmpeg").arg("-version").output().is_err() { - assert!(std::env::var_os("EC_REQUIRE_FIXTURES").is_none(), "ffmpeg missing"); - return; - } let dir: PathBuf = std::env::temp_dir().join(format!("ec-probe-legacy-{}", std::process::id())); std::fs::create_dir_all(&dir).expect("tmp"); let mut n = 0; @@ -30,7 +24,7 @@ fn legacy_audio_decodes_through_the_probe() { ] { for ch in ["1", "2"] { let path = dir.join(format!("{enc}-{ch}.{ext}")); - let o = Command::new("ffmpeg") + let o = ec_testkit::ffmpeg() .args(["-nostdin", "-y", "-v", "error", "-f", "lavfi", "-i"]) .arg("aevalsrc='0.6*sin(2*PI*440*t)+0.2*sin(2*PI*3000*t*t)':s=16000:d=1.1") .args(["-ac", ch, "-c:a", enc]) @@ -38,7 +32,7 @@ fn legacy_audio_decodes_through_the_probe() { .output() .expect("ffmpeg"); assert!(o.status.success(), "{}", String::from_utf8_lossy(&o.stderr)); - let want = Command::new("ffmpeg") + let want = ec_testkit::ffmpeg() .args(["-nostdin", "-v", "error", "-i"]) .arg(&path) .args(["-f", "f32le", "-"]) diff --git a/crates/ec-probe/tests/library.rs b/crates/ec-probe/tests/library.rs index 67a9a2a9..6e3b2adb 100644 --- a/crates/ec-probe/tests/library.rs +++ b/crates/ec-probe/tests/library.rs @@ -1,14 +1,9 @@ -//! His library, not fixtures: open, list, decode and seek real files, and -//! compare what the probe says against ffprobe file by file. -//! -//! Driven by `fixtures/real-library-manifest.tsv` (written by -//! `scripts/scan-real-library.sh`). Files that have since moved are skipped and -//! reported, never failed — the manifest is a snapshot of a moving library. +//! Real AVI and MP3 files from the open fixtures: open, decode and seek them, +//! and compare what the probe says against ffmpeg. use std::fs::File; use std::io::{Read, Seek, SeekFrom}; -use std::path::{Path, PathBuf}; -use std::process::Command; +use std::path::Path; use std::sync::{ Arc, atomic::{AtomicU64, Ordering}, @@ -19,55 +14,6 @@ use ec_core::registry::{CodecId, MediaType, SeekMode}; use ec_core::timebase::{TimeBase, Timestamp}; use ec_probe::Reader; -fn manifest() -> Vec<(PathBuf, String, String, f64)> { - let path = - Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/real-library-manifest.tsv"); - let Ok(text) = std::fs::read_to_string(path) else { - return Vec::new(); - }; - text.lines() - .skip(1) - .filter_map(|line| { - let f: Vec<&str> = line.split('\t').collect(); - let path = PathBuf::from(f.first()?); - let acodecs = f - .get(7) - .filter(|s| **s != "-") - .map_or_else(String::new, |s| (*s).to_string()); - Some(( - path, - (*f.get(1)?).to_string(), - acodecs, - f.get(8)?.parse().unwrap_or(0.0), - )) - }) - .collect() -} - -/// Decode `secs` of audio from the current position; answers sample frames. -fn decode_some(reader: &mut Reader, stream: u32, secs: f64) -> Result { - let mut decoder = reader.make_decoder(stream).map_err(|e| e.to_string())?; - let rate = f64::from(decoder.sample_rate().max(1)); - let want = (secs * rate) as u64; - let mut out = Vec::new(); - let mut frames = 0u64; - while frames < want { - let packet = match reader.next_packet() { - Ok(p) => p, - Err(e) if e.is_eof() => break, - Err(e) => return Err(format!("demux: {e}")), - }; - if packet.stream != stream { - continue; - } - decoder - .decode(&packet, &mut out) - .map_err(|e| format!("decode: {e}"))?; - frames += (out.len() / decoder.channels().max(1)) as u64; - } - Ok(frames) -} - fn decode_window(reader: &mut Reader, stream: u32, secs: f64) -> Result, String> { let mut decoder = reader.make_decoder(stream).map_err(|e| e.to_string())?; let channels = decoder.channels().max(1); @@ -93,7 +39,7 @@ fn decode_window(reader: &mut Reader, stream: u32, secs: f64) -> Result } fn reference_seek_window(path: &Path, at: f64) -> Vec { - let out = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args(["-v", "error", "-ss", &format!("{at:.6}"), "-i"]) .arg(path) .args([ @@ -139,35 +85,6 @@ impl Seek for CountedFile { } } -fn hive_avi_files() -> Vec { - let root = Path::new("/home/user/Downloads"); - let Ok(entries) = std::fs::read_dir(root) else { - return Vec::new(); - }; - let mut files = Vec::new(); - for entry in entries.flatten() { - let path = entry.path(); - if !path - .file_name() - .and_then(|n| n.to_str()) - .is_some_and(|n| n.contains("Hive-CM8")) - { - continue; - } - let Ok(children) = std::fs::read_dir(path) else { - continue; - }; - for child in children.flatten() { - let path = child.path(); - if path.extension().and_then(|e| e.to_str()) == Some("avi") { - files.push(path); - } - } - } - files.sort_by_key(|p| std::fs::metadata(p).map(|m| m.len()).unwrap_or(u64::MAX)); - files -} - fn assert_avi_index_is_bounded(path: &Path) { let file_size = std::fs::metadata(path).expect("AVI metadata").len(); let index_len = ec_riff::AviReader::new(File::open(path).expect("open AVI")) @@ -408,356 +325,23 @@ fn assert_avi_seeks_match_reference(path: &Path) { } } -fn synthetic_mp3_avi() -> Option { - if !Command::new("ffmpeg") - .args(["-version"]) - .output() - .is_ok_and(|out| out.status.success()) - { - eprintln!("reference encoder/decoder absent, skipping synthetic AVI"); - return None; - } - let root = PathBuf::from(std::env::var_os("HOME").expect("HOME")).join(".cache/aviseek"); - std::fs::create_dir_all(&root).expect("create scratch directory"); - let path = root.join(format!("seek-oracle-{}.avi", std::process::id())); - let out = Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - "sine=frequency=997:sample_rate=48000:duration=30", - "-c:a", - "libmp3lame", - "-f", - "avi", - "-y", - ]) - .arg(&path) - .output() - .expect("reference encoder runs"); - assert!( - out.status.success(), - "{}", - String::from_utf8_lossy(&out.stderr) - ); - Some(path) -} - -/// Ten files with sound, standalone audio first, then Matroska — opened, -/// decoded and seeked, with a per-file row in the report. #[test] -fn a_real_library_sweep() { - let files = manifest(); - if files.is_empty() { - eprintln!("no manifest — run scripts/scan-real-library.sh"); - return; - } - // Half standalone audio, half Matroska: the two paths this crate owns, and - // one row per distinct audio codec the library actually holds rather than - // ten copies of the same aac remux. - let standalone = |p: &Path| { - let ext = p.extension().and_then(|e| e.to_str()).unwrap_or(""); - [ - "mp3", "flac", "wav", "ogg", "opus", "m4a", "aac", "mp4", "mov", - ] - .contains(&ext) - }; - let mut chosen: Vec<_> = Vec::new(); - let mut seen = Vec::new(); - for want_mkv in [false, true] { - let mut taken = 0; - for f in &files { - let (p, container, acodecs, _) = f; - if acodecs.is_empty() || !p.exists() || taken >= 5 { - continue; - } - let is_mkv = container.contains("matroska"); - if is_mkv != want_mkv || (!is_mkv && !standalone(p)) { - continue; - } - // One file per (container, codec set): variety beats repetition. - let key = format!("{is_mkv}:{acodecs}"); - if seen.contains(&key) { - continue; - } - seen.push(key); - chosen.push(f); - taken += 1; - } - } - // lane-h264reallib: NOT an `assert!` here. The file's own header, lines - // 5-6, is the spec: "Files that have since moved are skipped and - // reported, never failed -- the manifest is a snapshot of a moving - // library." An empty `chosen` IS the moved-files case, so failing on it - // contradicted the contract this file declares. It was also red on any - // host whose manifest paths no longer resolve, for a reason that had - // nothing to do with the probe. Reported and returned, which is what - // "skipped and reported, never failed" asks for. - if chosen.is_empty() { - eprintln!( - "skipped: no readable file in the manifest (every row has moved or is unreadable)" - ); - return; - } - - let mut rows = Vec::new(); - let mut failures = Vec::new(); - for (path, container, acodecs, duration) in &chosen { - let name = path.file_name().unwrap().to_string_lossy().to_string(); - let mut reader = match Reader::open(path) { - Ok(r) => r, - Err(e) => { - failures.push(format!("{name}: open failed: {e}")); - continue; - } - }; - // The first audio stream that actually decodes, which is what a player - // plays; the ones that do not are named below rather than skipped over. - let audio = reader - .streams() - .iter() - .find(|s| { - s.params.codec.media_type() == MediaType::Audio - && reader.make_decoder(s.index).is_ok() - }) - .or_else(|| reader.default_stream(MediaType::Audio)) - .cloned(); - let Some(audio) = audio else { - failures.push(format!("{name}: no audio stream, ffprobe says {acodecs}")); - continue; - }; - let unsupported = reader.unsupported(); - // Every codec ffprobe lists is either decodable here or named as not. - let listed: Vec = reader - .streams() - .iter() - .filter(|s| s.params.codec.media_type() == MediaType::Audio) - .map(|s| s.params.codec.name().to_string()) - .collect(); - let decoded = decode_some(&mut reader, audio.index, 1.0); - let rate = audio.params.audio().map_or(0, |a| a.sample_rate).max(1); - let landing = if *duration > 4.0 { - let ticks = (duration / 2.0 * f64::from(rate)) as i64; - reader - .seek( - audio.index, - Timestamp::new(ticks, TimeBase::from_rate(rate)), - SeekMode::SyncBefore, - ) - .map(|t| t.as_secs_f64()) - .map_err(|e| e.to_string()) - } else { - Ok(0.0) - }; - let after_seek = landing - .as_ref() - .ok() - .map(|_| decode_some(&mut reader, audio.index, 0.5)); - - let ok = decoded.is_ok() - && landing.is_ok() - && matches!(after_seek, Some(Ok(n)) if n > 0) - && listed.iter().any(|c| acodecs.split(',').any(|a| a == c)); - if !ok { - failures.push(format!( - "{name}: decode {decoded:?} seek {landing:?} after {after_seek:?} \ - codecs {listed:?} vs ffprobe {acodecs}" - )); - } - rows.push(format!( - "{:<52} {:<16} {:<14} {:>7} frames seek->{:>8} {}", - name.chars().take(52).collect::(), - container.split(',').next().unwrap_or(container), - listed.join(","), - decoded.clone().unwrap_or(0), - landing - .as_ref() - .map(|s| format!("{s:.2}s")) - .unwrap_or_else(|e| e.clone()), - match unsupported.is_empty() { - true => "all decodable".to_string(), - false => unsupported - .iter() - .map(|u| format!("unsupported: {} ({})", u.codec.name(), u.reason)) - .collect::>() - .join("; "), - } - )); - } - eprintln!( - "real-library sweep ({} files):\n{}", - rows.len(), - rows.join("\n") - ); - assert!(failures.is_empty(), "{}", failures.join("\n")); -} - -#[test] -fn avi_audio_chunks_end_cleanly_on_real_files() { - let files = [ - "/home/user/Downloads/reele/reele.avi", - "/home/user/Downloads/reele/sample.avi", - ]; - let mut present = 0; - for path in files { - let path = Path::new(path); - if !path.exists() { - continue; - } - present += 1; - let mut reader = Reader::open(path).expect("AVI opens"); - let audio = reader - .default_stream(MediaType::Audio) - .expect("AVI audio stream") - .index; - let (packets, frames, _) = - decode_stream_to_eof(&mut reader, audio, false).unwrap_or_else(|e| { - panic!("{}: {e}", path.display()); - }); - eprintln!( - "{}: open ok, packets {packets}, decode-to-EOF {frames} frames", - path.display() - ); - assert!(packets > 0, "{}: no audio packets", path.display()); - assert!(frames > 0, "{}: no decoded audio", path.display()); - } - if present == 0 { - // The library is his, so a file can leave it; the sibling AVI tests - // skip the same way rather than failing a run on a deleted download. - eprintln!("AVI files absent, skipping"); - } -} - -#[test] -fn avi_ac3_matches_reference_decoder_on_real_sample() { - let path = Path::new( - "/home/user/Downloads/reele/sample.avi", - ); - if !path.exists() { - eprintln!("file not present, skipping"); - return; - } - - let mut reader = Reader::open(path).expect("AVI opens"); +fn avi_audio_chunks_end_cleanly() { + let path = ec_testkit::fixture("derived/sintel720.avi"); + let mut reader = Reader::open(&path).expect("AVI opens"); let audio = reader .default_stream(MediaType::Audio) .expect("AVI audio stream") .index; - let (packets, frames, ours) = - decode_stream_to_eof(&mut reader, audio, true).expect("AVI decodes to EOF"); - assert!(packets > 0, "no packets"); - assert!(frames > 0, "no decoded frames"); - - let out = Command::new("ffmpeg") - .args(["-v", "error", "-i"]) - .arg(path) - .args(["-map", "0:a:0", "-f", "f32le", "-acodec", "pcm_f32le", "-"]) - .output() - .expect("reference decoder runs"); - assert!( - out.status.success(), - "{}", - String::from_utf8_lossy(&out.stderr) - ); - let theirs: Vec = out - .stdout - .as_chunks::<4>().0.iter() - .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])) - .collect(); - let score = corr(&ours, &theirs); - eprintln!( - "{}: open ok, packets {packets}, decode-to-EOF {frames} frames, corr {score:.6}", - path.display() - ); - assert!(score > 0.999, "corr vs reference decoder = {score}"); -} - -#[test] -fn avi_seek_matches_reference_decoder_on_real_files() { - let files = hive_avi_files(); - if files.is_empty() { - eprintln!("AVI files absent, skipping"); - return; - } - for path in files { - assert_avi_seeks_match_reference(&path); - } + let (packets, frames, _) = decode_stream_to_eof(&mut reader, audio, false) + .unwrap_or_else(|e| panic!("{}: {e}", path.display())); + assert!(packets > 0, "{}: no audio packets", path.display()); + assert!(frames > 0, "{}: no decoded audio", path.display()); } #[test] -fn avi_seek_matches_reference_decoder_on_synthetic_mp3() { - let Some(path) = synthetic_mp3_avi() else { - return; - }; - assert_avi_seeks_match_reference(&path); - std::fs::remove_file(path).expect("remove synthetic AVI"); -} - -/// The TrueHD remux in his library: the track decodes through the unified -/// reader, 7.1 at 48 kHz, with the AC-3 track beside it still decoding too. -#[test] -fn a_truehd_track_decodes() { - let Some((path, ..)) = manifest() - .into_iter() - .find(|(p, _, acodecs, _)| acodecs.contains("truehd") && p.exists()) - else { - eprintln!("no TrueHD file in the manifest — skipping"); - return; - }; - let mut reader = Reader::open(&path).expect("open"); - let truehd = reader - .streams() - .iter() - .find(|s| s.params.codec.name() == "truehd") - .cloned() - .expect("the TrueHD track is listed"); - let decoder = reader.make_decoder(truehd.index).expect("truehd decoder"); - assert_eq!(decoder.channels(), 8, "7.1 TrueHD is 8 channels"); - assert_eq!(decoder.sample_rate(), 48_000); - let frames = decode_some(&mut reader, truehd.index, 1.0).expect("decode"); - assert!(frames > 0, "no TrueHD audio came out"); - // ...and the AC-3 track beside it still decodes. - let decodable: Vec<_> = reader - .streams() - .iter() - .filter(|s| s.params.codec.media_type() == MediaType::Audio) - .filter(|s| reader.make_decoder(s.index).is_ok()) - .map(|s| s.params.codec.name()) - .collect(); - assert!( - decodable.contains(&"ac3") || decodable.contains(&"truehd"), - "a file with a TrueHD track and an AC-3 one came out with nothing to play: {decodable:?}" - ); - eprintln!( - "{}: truehd decoded {frames} frames, tracks {decodable:?}", - path.file_name().unwrap().to_string_lossy(), - ); -} - -/// ffprobe's stream count for the same file, as a cross-check that nothing is -/// being hidden. -#[allow(dead_code)] -fn ffprobe_audio_codecs(path: &Path) -> Vec { - let out = Command::new("ffprobe") - .args([ - "-v", - "error", - "-select_streams", - "a", - "-show_entries", - "stream=codec_name", - "-of", - "default=nw=1:nk=1", - ]) - .arg(path) - .output() - .expect("ffprobe"); - String::from_utf8_lossy(&out.stdout) - .lines() - .map(|l| l.trim().to_string()) - .collect() +fn avi_seek_matches_reference_decoder() { + assert_avi_seeks_match_reference(&ec_testkit::fixture("derived/sintel720.avi")); } /// Cover-art (`APIC`) ID3v2 tags shipped by real rippers/taggers put a whole @@ -767,12 +351,8 @@ fn ffprobe_audio_codecs(path: &Path) -> Vec { /// the same first second, not just "it opened". #[test] fn a_cover_art_tagged_mp3_opens() { - let path = Path::new("/home/user/Music/reeli.mp3"); - if !path.exists() { - eprintln!("file not present, skipping"); - return; - } - let mut reader = Reader::open(path).expect("open"); + let path = ec_testkit::fixture("audio/cover-mp3-stereo-44100.mp3"); + let mut reader = Reader::open(&path).expect("open"); let audio = reader .default_stream(MediaType::Audio) .cloned() @@ -804,7 +384,7 @@ fn a_cover_art_tagged_mp3_opens() { let ours = &ours[lead_in as usize..]; assert!(ours.len() as u32 >= rate / 2, "decoded too little audio"); - let out = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args(["-v", "error", "-t", "1", "-i"]) .arg(path) .args(["-map", "0:a:0", "-f", "f32le", "-acodec", "pcm_f32le", "-"]) diff --git a/crates/ec-probe/tests/matrix.rs b/crates/ec-probe/tests/matrix.rs index 6717bba0..61e97d7f 100644 --- a/crates/ec-probe/tests/matrix.rs +++ b/crates/ec-probe/tests/matrix.rs @@ -3,23 +3,21 @@ //! where it says it does after a hundred random seeks — on one reader. //! //! Oracle is ffmpeg/ffprobe (labelled as such: this is not a conformance -//! claim). A missing fixture skips its row rather than failing the suite, so a -//! checkout without generated fixtures still builds and runs. +//! claim). use std::path::{Path, PathBuf}; -use std::process::Command; use ec_core::registry::{MediaType, SeekMode}; use ec_core::timebase::{TimeBase, Timestamp}; use ec_probe::{Format, Reader}; fn fixtures() -> PathBuf { - Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/audio") + ec_testkit::root().join("audio") } /// `ffprobe` on one entry of the first audio stream. fn probe(path: &Path, args: &[&str]) -> String { - let out = Command::new("ffprobe") + let out = ec_testkit::ffprobe() .args(["-v", "error", "-select_streams", "a:0"]) .args(args) .args(["-of", "default=nw=1:nk=1"]) @@ -49,7 +47,7 @@ fn ffprobe_packets(path: &Path) -> u64 { /// Sample frames ffmpeg decodes out of the first audio stream. fn ffmpeg_frames(path: &Path, channels: usize) -> u64 { - let out = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args(["-nostdin", "-v", "error", "-i"]) .arg(path) .args(["-map", "0:a:0", "-f", "f32le", "-"]) @@ -116,9 +114,6 @@ fn every_fixture_probes_decodes_and_counts() { let mut rows = Vec::new(); for &(name, format, codec) in MATRIX { let path = fixtures().join(name); - if !path.exists() { - continue; - } let mut reader = Reader::open(&path).unwrap_or_else(|e| panic!("{name}: {e}")); assert_eq!(reader.format(), format, "{name}: format"); let audio = reader @@ -164,7 +159,7 @@ fn every_fixture_probes_decodes_and_counts() { } assert!( checked > 0, - "no fixtures found — run scripts/gen-fixtures.sh" + "no fixtures found — run scripts/fixtures.sh" ); eprintln!("probe matrix ({checked} files):\n{}", rows.join("\n")); } @@ -176,9 +171,6 @@ fn a_hundred_random_seeks_land_where_they_say() { let mut checked = 0; for &(name, _, codec) in MATRIX { let path = fixtures().join(name); - if !path.exists() { - continue; - } let mut reader = Reader::open(&path).expect("open"); let audio = reader .default_stream(MediaType::Audio) @@ -247,7 +239,7 @@ fn a_hundred_random_seeks_land_where_they_say() { } assert!( checked > 0, - "no fixtures found — run scripts/gen-fixtures.sh" + "no fixtures found — run scripts/fixtures.sh" ); eprintln!("100 random seeks each on {checked} files, one reader per file"); } @@ -259,9 +251,6 @@ fn cover_art_is_never_a_video_track() { let mut checked = 0; for name in ["cover-mp3-stereo-44100.mp3", "cover-mp4-stereo-44100.m4a"] { let path = fixtures().join(name); - if !path.exists() { - continue; - } let reader = Reader::open(&path).expect("open"); let video: Vec<_> = reader .streams() @@ -278,16 +267,13 @@ fn cover_art_is_never_a_video_track() { ); checked += 1; } - assert!(checked > 0, "no cover-art fixtures — run gen-fixtures.sh"); + assert!(checked > 0, "no cover-art fixtures — run scripts/fixtures.sh"); } /// The tags an ID3v2-tagged file carries come back off it. #[test] fn id3_tags_come_off_a_real_file() { let path = fixtures().join("cover-mp3-stereo-44100.mp3"); - if !path.exists() { - return; - } let reader = Reader::open(&path).expect("open"); assert_eq!(reader.tags().title.as_deref(), Some("A Tone")); assert_eq!(reader.tags().artist.as_deref(), Some("edith_codecs")); @@ -298,9 +284,6 @@ fn id3_tags_come_off_a_real_file() { #[test] fn a_mislabelled_file_opens_as_what_it_is() { let src = fixtures().join("flac-stereo-48000.flac"); - if !src.exists() { - return; - } let liar = std::env::temp_dir().join("ec-probe-liar.mp3"); std::fs::copy(&src, &liar).expect("copy"); let reader = Reader::open(&liar).expect("open"); @@ -322,9 +305,6 @@ fn the_head_of_a_file_is_exact() { let mut checked = 0; for &(name, _, codec) in MATRIX { let path = fixtures().join(name); - if !path.exists() { - continue; - } let mut reader = Reader::open(&path).expect("open"); let audio = reader .default_stream(MediaType::Audio) @@ -370,6 +350,6 @@ fn the_head_of_a_file_is_exact() { } assert!( checked > 0, - "no fixtures found — run scripts/gen-fixtures.sh" + "no fixtures found — run scripts/fixtures.sh" ); } diff --git a/crates/ec-riff/Cargo.toml b/crates/ec-riff/Cargo.toml index b1e67f4a..c12c6c51 100644 --- a/crates/ec-riff/Cargo.toml +++ b/crates/ec-riff/Cargo.toml @@ -11,5 +11,6 @@ ec-core.workspace = true ec-dv = { path = "../ec-dv", version = "0.1.0" } [dev-dependencies] +ec-testkit.workspace = true ec-mjpeg.workspace = true ec-mp4.workspace = true diff --git a/crates/ec-riff/fuzz/seed.sh b/crates/ec-riff/fuzz/seed.sh index 9af93823..5950b132 100755 --- a/crates/ec-riff/fuzz/seed.sh +++ b/crates/ec-riff/fuzz/seed.sh @@ -11,8 +11,8 @@ set -euo pipefail FUZZ_DIR=$(cd -- "$(dirname -- "$0")" && pwd) -FIXTURES=$(cd -- "$FUZZ_DIR/../../.." && pwd)/fixtures/audio -[ -d "$FIXTURES" ] || { echo "seed.sh: $FIXTURES missing; run scripts/link-fixtures.sh" >&2; exit 2; } +FIXTURES=${EC_FIXTURES:-$(cd -- "$FUZZ_DIR/../../.." && pwd)/fixtures}/audio +[ -d "$FIXTURES" ] || { echo "seed.sh: $FIXTURES missing; run scripts/fixtures.sh" >&2; exit 2; } WAVS=("$FIXTURES"/*.wav) [ -e "${WAVS[0]}" ] || { echo "seed.sh: no *.wav fixtures in $FIXTURES" >&2; exit 2; } diff --git a/crates/ec-riff/tests/it/avi_raw_dv.rs b/crates/ec-riff/tests/it/avi_raw_dv.rs index 27c6c5f2..44fc0cb3 100644 --- a/crates/ec-riff/tests/it/avi_raw_dv.rs +++ b/crates/ec-riff/tests/it/avi_raw_dv.rs @@ -1,28 +1,15 @@ //! Uncompressed video in AVI and DV type-1 AVI (`iavs`). Media is synthetic, written by ffmpeg //! at test time; ffmpeg cannot write type-1 AVI, so that wrapper is built here from a `.dv` -//! file. Without ffmpeg the tests skip unless `EC_REQUIRE_FIXTURES` is set. +//! file. use std::io::Cursor; use std::path::PathBuf; -use std::process::Command; use ec_core::frame::Frame; use ec_core::registry::{CodecId, Decoder, Demuxer, MediaType, SeekMode}; use ec_core::{Error, Timestamp}; use ec_riff::{AviDemuxer, RawVideoDecoder}; -use crate::common::{ffmpeg, frame_bytes, tool_ok}; - -fn oracle() -> bool { - if tool_ok("ffmpeg") { - return true; - } - assert!( - std::env::var_os("EC_REQUIRE_FIXTURES").is_none(), - "ffmpeg missing and EC_REQUIRE_FIXTURES is set" - ); - eprintln!("SKIP: no ffmpeg"); - false -} +use crate::common::{ffmpeg, frame_bytes}; fn scratch(tag: &str) -> PathBuf { let base = std::env::var_os("TMPDIR") @@ -34,7 +21,7 @@ fn scratch(tag: &str) -> PathBuf { } fn ffmpeg_out(args: &[&str]) -> Vec { - let o = Command::new("ffmpeg") + let o = ec_testkit::ffmpeg() .args(["-v", "error", "-nostdin"]) .args(args) .output() @@ -104,9 +91,6 @@ fn expect_parity(path: &std::path::Path, bytes: Vec, ff_pix: &str) { #[test] fn raw_rgb_and_yuv_match_ffmpeg() { - if !oracle() { - return; - } for (tag, size, pix, vtag, ff) in [ ("bgr24", "98x66", "bgr24", None, "bgr24"), ("bgr24odd", "97x65", "bgr24", None, "bgr24"), @@ -157,9 +141,6 @@ fn patch_chunks(bytes: &mut [u8], mut f: impl FnMut(&mut [u8])) { #[test] fn both_row_orders_are_upright() { - if !oracle() { - return; - } let (path, bytes) = make_raw("topdown", "98x66", "bgr24", None); let mut td = bytes.clone(); let strf = td.windows(4).position(|w| w == b"strf").unwrap() + 8; @@ -363,17 +344,11 @@ fn dv_case( #[test] fn dv_type1_pal_splits_video_and_audio() { - if !oracle() { - return; - } dv_case("dvpal", "720x576", "25", (1, 25), b"dvsd", "yuv420p"); } #[test] fn dv_type1_ntsc_splits_video_and_audio() { - if !oracle() { - return; - } dv_case( "dvntsc", "720x480", diff --git a/crates/ec-riff/tests/it/avi_video.rs b/crates/ec-riff/tests/it/avi_video.rs index 234e3a9e..10a6585d 100644 --- a/crates/ec-riff/tests/it/avi_video.rs +++ b/crates/ec-riff/tests/it/avi_video.rs @@ -1,31 +1,15 @@ //! AVI audio+video demuxer tests. Real files are synthetic, written by ffmpeg at test time and //! checked against `ffprobe -show_packets`; the OpenDML, scan and vprp cases are hand-built -//! byte by byte. Without ffmpeg the ffmpeg-backed tests skip unless `EC_REQUIRE_FIXTURES` is set. +//! byte by byte. use std::io::Cursor; use std::path::PathBuf; -use std::process::Command; use ec_core::frame::{Interlace, VideoFrame}; use ec_core::registry::{CodecId, Demuxer, MediaType, SeekMode}; use ec_core::{Error, TimeBase, Timestamp}; use ec_riff::{AviDemuxer, AviIndexKind, is_avi}; -use crate::common::{chunk, ffmpeg, list, tool_ok}; - -// --------------------------------------------------------------------------------------------- -// ffmpeg plumbing - -fn oracle() -> bool { - if tool_ok("ffmpeg") && tool_ok("ffprobe") { - return true; - } - assert!( - std::env::var_os("EC_REQUIRE_FIXTURES").is_none(), - "ffmpeg missing and EC_REQUIRE_FIXTURES is set" - ); - eprintln!("SKIP: no ffmpeg"); - false -} +use crate::common::{chunk, ffmpeg, list}; fn scratch(tag: &str) -> PathBuf { let base = std::env::var_os("TMPDIR") @@ -62,7 +46,7 @@ struct Probe { } fn probe(path: &PathBuf) -> Vec { - let out = Command::new("ffprobe") + let out = ec_testkit::ffprobe() .args(["-v", "error", "-show_packets", "-show_data_hash", "adler32", "-of", "compact=p=0"]) .arg(path) .output() @@ -162,9 +146,6 @@ fn assert_interleaved(got: &[Got]) { #[test] fn mjpeg_pcm() { - if !oracle() { - return; - } let (path, bytes) = make("mjpeg-pcm", &["-c:v", "mjpeg", "-q:v", "3"], &["-c:a", "pcm_s16le"]); assert!(is_avi(&bytes)); let mut d = AviDemuxer::new(Cursor::new(bytes.clone())).unwrap(); @@ -212,9 +193,6 @@ fn compare_video_only(path: &PathBuf, bytes: &[u8]) -> Vec { #[test] fn mjpeg_mp3() { - if !oracle() { - return; - } let (path, bytes) = make("mjpeg-mp3", &["-c:v", "mjpeg"], &["-c:a", "libmp3lame"]); let d = AviDemuxer::new(Cursor::new(bytes.clone())).unwrap(); assert_eq!(d.streams()[1].params.codec, CodecId::Mp3); @@ -227,9 +205,6 @@ fn mjpeg_mp3() { #[test] fn h264_no_bframes_aac() { - if !oracle() { - return; - } let (path, bytes) = make( "h264", &["-c:v", "libx264", "-bf", "0", "-g", "10", "-preset", "ultrafast"], @@ -275,9 +250,6 @@ fn h264_no_bframes_aac() { #[test] fn h264_bframes_decode_order() { - if !oracle() { - return; - } let (path, bytes) = make( "h264b", &["-c:v", "libx264", "-bf", "2", "-g", "12", "-preset", "ultrafast"], @@ -294,9 +266,6 @@ fn h264_bframes_decode_order() { #[test] fn mpeg2_mp2() { - if !oracle() { - return; - } let (path, bytes) = make("mpeg2", &["-c:v", "mpeg2video", "-g", "10", "-bf", "0"], &["-c:a", "mp2"]); let d = AviDemuxer::new(Cursor::new(bytes.clone())).unwrap(); assert_eq!(d.streams()[0].params.codec, CodecId::Mpeg2Video); @@ -307,9 +276,6 @@ fn mpeg2_mp2() { #[test] fn raw_video_is_carried_and_unknown_layouts_refused_by_name() { - if !oracle() { - return; - } for (tag, fmt) in [("yuyv", "yuyv422"), ("bgr24", "bgr24")] { let (_, bytes) = make(tag, &["-c:v", "rawvideo", "-pix_fmt", fmt], &["-c:a", "pcm_s16le"]); let d = AviDemuxer::new(Cursor::new(bytes)).unwrap(); @@ -327,9 +293,6 @@ fn raw_video_is_carried_and_unknown_layouts_refused_by_name() { #[test] fn mpeg4_part2_and_ms_mpeg4_fourccs_map() { - if !oracle() { - return; - } for tag in ["XVID", "xvid", "DIVX", "DX50", "FMP4", "mp4v"] { let path = scratch("mp4v").join(format!("v-{tag}.avi")); let mut args: Vec<&str> = Vec::new(); @@ -357,9 +320,6 @@ fn mpeg4_part2_and_ms_mpeg4_fourccs_map() { #[test] fn truncated_file_without_idx1_scans() { - if !oracle() { - return; - } let (path, bytes) = make("trunc", &["-c:v", "mjpeg"], &["-c:a", "pcm_s16le"]); let full = compare_video_only(&path, &bytes); // Cut in the middle of movi: idx1 is gone, the RIFF and movi sizes lie. @@ -381,9 +341,6 @@ fn truncated_file_without_idx1_scans() { #[test] fn mjpeg_frames_decode_like_ffmpeg() { - if !oracle() { - return; - } let (path, bytes) = make("mjpeg-dec", &["-c:v", "mjpeg", "-q:v", "2"], &["-c:a", "pcm_s16le"]); let raw = scratch("mjpeg-dec").join("o.yuv"); ffmpeg(&[ diff --git a/crates/ec-riff/tests/it/common.rs b/crates/ec-riff/tests/it/common.rs index ebd51fd9..89bb7ce7 100644 --- a/crates/ec-riff/tests/it/common.rs +++ b/crates/ec-riff/tests/it/common.rs @@ -1,6 +1,5 @@ //! Helpers shared by the integration-test modules in this binary. -use std::process::Command; use ec_core::frame::VideoFrame; @@ -20,16 +19,8 @@ pub(crate) fn list(kind: &[u8; 4], body: &[u8]) -> Vec { chunk(b"LIST", &b) } -pub(crate) fn tool_ok(name: &str) -> bool { - Command::new(name) - .arg("-version") - .output() - .map(|o| o.status.success()) - .unwrap_or(false) -} - pub(crate) fn ffmpeg(args: &[&str]) { - let ok = Command::new("ffmpeg") + let ok = ec_testkit::ffmpeg() .args(["-v", "error", "-y", "-nostdin"]) .args(args) .status() diff --git a/crates/ec-riff/tests/it/dts.rs b/crates/ec-riff/tests/it/dts.rs index b9a0495a..193ff786 100644 --- a/crates/ec-riff/tests/it/dts.rs +++ b/crates/ec-riff/tests/it/dts.rs @@ -1,7 +1,6 @@ //! DTS in AVI: the `0x2001` audio format tag is `CodecId::Dts`. use std::io::Cursor; -use std::process::Command; use ec_core::{CodecId, Demuxer, MediaParameters}; use ec_riff::AviDemuxer; @@ -9,21 +8,14 @@ use ec_riff::AviDemuxer; #[test] fn avi_tag_0x2001_is_dts() { let out = std::env::temp_dir().join(format!("ec-riff-dts-{}.avi", std::process::id())); - let ok = Command::new("ffmpeg") + let ok = ec_testkit::ffmpeg() .args(["-v", "error", "-y", "-f", "lavfi", "-i"]) .arg("sine=frequency=440:sample_rate=48000:duration=0.5") .args(["-ac", "2", "-c:a", "dca", "-strict", "-2"]) .arg(&out) .output() .is_ok_and(|o| o.status.success()); - if !ok { - assert!( - std::env::var_os("EC_REQUIRE_FIXTURES").is_none_or(|v| v.is_empty() || v == "0"), - "ffmpeg cannot make a DTS avi" - ); - eprintln!("skip: no ffmpeg with the dca encoder"); - return; - } + assert!(ok, "ffmpeg cannot make a DTS avi"); let bytes = std::fs::read(&out).unwrap(); let _ = std::fs::remove_file(out); let d = AviDemuxer::new(Cursor::new(bytes)).unwrap(); diff --git a/crates/ec-riff/tests/it/mov_raw.rs b/crates/ec-riff/tests/it/mov_raw.rs index 9ebddbf9..0fa263b0 100644 --- a/crates/ec-riff/tests/it/mov_raw.rs +++ b/crates/ec-riff/tests/it/mov_raw.rs @@ -1,32 +1,13 @@ //! Uncompressed video in QuickTime (`raw `, `2vuy`, `yuv2`, `v210`, `v410`, `b16g`), compared -//! with ffmpeg's decode of the same .mov. Media is synthetic. Without ffmpeg the tests skip -//! unless `EC_REQUIRE_FIXTURES` is set. +//! with ffmpeg's decode of the same .mov. Media is synthetic. use std::path::PathBuf; -use std::process::Command; use ec_core::frame::Frame; use ec_core::registry::{CodecId, Decoder, Demuxer}; use ec_riff::RawVideoDecoder; use crate::common::frame_bytes; -fn oracle() -> bool { - if Command::new("ffmpeg") - .arg("-version") - .output() - .map(|o| o.status.success()) - .unwrap_or(false) - { - return true; - } - assert!( - std::env::var_os("EC_REQUIRE_FIXTURES").is_none(), - "ffmpeg missing and EC_REQUIRE_FIXTURES is set" - ); - eprintln!("SKIP: no ffmpeg"); - false -} - fn scratch(tag: &str) -> PathBuf { let base = std::env::var_os("TMPDIR") .map(PathBuf::from) @@ -37,7 +18,7 @@ fn scratch(tag: &str) -> PathBuf { } fn ffmpeg(args: &[&str]) -> Vec { - let o = Command::new("ffmpeg") + let o = ec_testkit::ffmpeg() .args(["-v", "error", "-y", "-nostdin"]) .args(args) .output() @@ -52,9 +33,6 @@ fn ffmpeg(args: &[&str]) -> Vec { #[test] fn mov_raw_layouts_match_ffmpeg() { - if !oracle() { - return; - } // (tag, size, ffmpeg codec, source pix_fmt, expected sample entry, pix_fmt we compare in) for (tag, size, codec, pix, entry, ff) in [ ("rgb24", "98x66", "rawvideo", "rgb24", b"raw ", "rgb24"), diff --git a/crates/ec-riff/tests/it/wav.rs b/crates/ec-riff/tests/it/wav.rs index c8ee48be..a5a5cd18 100644 --- a/crates/ec-riff/tests/it/wav.rs +++ b/crates/ec-riff/tests/it/wav.rs @@ -429,11 +429,8 @@ fn refusals_name_a_real_absence() { #[test] fn reads_every_wav_fixture() { - let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/../../fixtures/audio"); - let Ok(entries) = std::fs::read_dir(dir) else { - eprintln!("fixtures/audio absent (gitignored) — skipping"); - return; - }; + let entries = std::fs::read_dir(ec_testkit::root().join("audio")) + .expect("fixtures/audio (run scripts/fixtures.sh)"); let mut seen = 0; for e in entries.flatten() { let path = e.path();