diff --git a/Cargo.lock b/Cargo.lock index f49d960e..6addc29f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -411,6 +411,7 @@ dependencies = [ "ec-mp3", "ec-opus", "ec-probe", + "ec-testkit", "ec-truehd", "ec-va", "ec-vorbis", @@ -548,6 +549,7 @@ dependencies = [ "ec-dsp", "ec-h264-syntax", "ec-h265-syntax", + "ec-testkit", "ec-va", "ec-vk", "ec-vp9-syntax", @@ -1266,6 +1268,9 @@ dependencies = [ [[package]] name = "oracle" version = "0.1.0" +dependencies = [ + "ec-testkit", +] [[package]] name = "oxideav-ac3" diff --git a/crates/ec-hw/Cargo.toml b/crates/ec-hw/Cargo.toml index 2549ec07..25043c4e 100644 --- a/crates/ec-hw/Cargo.toml +++ b/crates/ec-hw/Cargo.toml @@ -18,3 +18,6 @@ ec-vp9-syntax.workspace = true [target.'cfg(target_os = "linux")'.dependencies] ec-va.workspace = true + +[dev-dependencies] +ec-testkit.workspace = true diff --git a/crates/ec-hw/examples/hw_config.rs b/crates/ec-hw/examples/hw_config.rs index eaeb49ed..1bdb28c1 100644 --- a/crates/ec-hw/examples/hw_config.rs +++ b/crates/ec-hw/examples/hw_config.rs @@ -1,6 +1,5 @@ use std::fs; use std::path::{Path, PathBuf}; -use std::process::Command; use ec_hw::{ Backend, EncCodec, EncoderConfig, FrameMetadata, H264Profile, HwEncoder, I420, RateControlMode, @@ -73,7 +72,7 @@ fn encode(dir: &Path, name: &str, profile: H264Profile, backend: Backend) -> Opt } fn probe(path: &Path) -> Vec<(String, String)> { - let out = Command::new("ffprobe") + let out = ec_testkit::ffprobe() .args(["-v", "error", "-select_streams", "v:0", "-show_entries"]) .arg(format!("stream={}", FIELDS.join(","))) .args(["-of", "default=nw=1"]) @@ -88,7 +87,7 @@ fn probe(path: &Path) -> Vec<(String, String)> { } fn keyframes(path: &Path) -> Vec { - let out = Command::new("ffprobe") + let out = ec_testkit::ffprobe() .args([ "-v", "error", @@ -116,7 +115,7 @@ fn value(info: &[(String, String)], key: &str) -> String { } fn main() { - let dir = PathBuf::from(std::env::args().nth(1).expect("scratch dir argument")); + let dir = std::env::temp_dir(); for (label, profile) in [("main", H264Profile::Main), ("cb", H264Profile::ConstrainedBaseline)] { compare(&dir, label, profile); } diff --git a/crates/ec-hw/examples/hw_decode.rs b/crates/ec-hw/examples/hw_decode.rs index 7489c0cb..1a69046d 100644 --- a/crates/ec-hw/examples/hw_decode.rs +++ b/crates/ec-hw/examples/hw_decode.rs @@ -2,15 +2,13 @@ //! The 10-bit H.265 and AV1 streams run on Vulkan and are compared with the VA-API decode of the same stream. //! //! ```text -//! cargo run -p ec-hw --example hw_decode -- //! ``` use std::collections::HashSet; use std::fs; use std::os::fd::AsRawFd; use std::os::unix::fs::MetadataExt; -use std::path::{Path, PathBuf}; -use std::process::Command; +use std::path::Path; use ec_hw::{ Backend, Codec, DmaBufPicture, EncCodec, EncoderConfig, FrameMetadata, HwDecoder, HwEncoder, @@ -106,7 +104,7 @@ const CASES: &[Case] = &[ ]; fn main() { - let dir = PathBuf::from(std::env::args().nth(1).expect("scratch dir argument")); + let dir = std::env::temp_dir(); for case in CASES { run(&dir, case); } @@ -491,7 +489,7 @@ fn compare_i420(label: &str, codec: Codec, backend: Backend, ours: &[I420], thei } fn ffmpeg(args: &[&str]) { - let status = Command::new("ffmpeg") + let status = ec_testkit::ffmpeg() .args(["-y", "-loglevel", "error"]) .args(args) .status() @@ -588,7 +586,7 @@ fn own_av1(dir: &Path) { decoder.flush().expect("flush"); drain(&mut decoder, &mut decoded); - let status = Command::new("ffmpeg") + let status = ec_testkit::ffmpeg() .args(["-y", "-loglevel", "error", "-i"]) .arg(&stream) .args(["-f", "rawvideo", "-pix_fmt", "yuv420p"]) diff --git a/crates/ec-hw/examples/hw_decode_rgb.rs b/crates/ec-hw/examples/hw_decode_rgb.rs index 8c8e81bc..f02a2f39 100644 --- a/crates/ec-hw/examples/hw_decode_rgb.rs +++ b/crates/ec-hw/examples/hw_decode_rgb.rs @@ -3,11 +3,9 @@ //! Streams are assumed untagged, so the matrix is BT.709 from 720 lines up and BT.601 below. //! //! ```text -//! cargo run --release -p ec-hw --example hw_decode_rgb -- //! ``` use std::fs; -use std::path::PathBuf; use std::time::{Duration, Instant}; use ec_dsp::rgb::{YuvToRgb, i420_to_packed}; @@ -23,9 +21,8 @@ const FILES: &[(&str, Codec)] = &[ ]; fn main() { - let dir = PathBuf::from(std::env::args().nth(1).expect("scratch dir argument")); for &(name, codec) in FILES { - let data = fs::read(dir.join(name)).expect("read stream"); + let data = fs::read(ec_testkit::fixture(&format!("bitstreams/{name}"))).expect("read stream"); let units = if matches!(codec, Codec::Av1 | Codec::Vp9) { ivf_units(&data) } else { diff --git a/crates/ec-hw/examples/hw_oracle.rs b/crates/ec-hw/examples/hw_oracle.rs index 03bf66c5..21705fbb 100644 --- a/crates/ec-hw/examples/hw_oracle.rs +++ b/crates/ec-hw/examples/hw_oracle.rs @@ -6,7 +6,6 @@ use std::fs; use std::path::Path; -use std::process::Command; use ec_hw::{Backend, Codec, HwDecoder}; @@ -99,13 +98,13 @@ fn ivf_units(ivf: &[u8]) -> Vec<&[u8]> { } fn reference(path: &Path) -> Result<(bool, Vec<(usize, u32)>), String> { - let probe = Command::new("ffprobe") + let probe = ec_testkit::ffprobe() .args(["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=pix_fmt", "-of", "csv=p=0"]) .arg(path) .output() .map_err(|e| e.to_string())?; let wide = String::from_utf8_lossy(&probe.stdout).contains("10"); - let out = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args(["-v", "error", "-i"]) .arg(path) .args(["-noautoscale", "-pix_fmt", if wide { "yuv420p10le" } else { "yuv420p" }, "-f", "framecrc", "-"]) diff --git a/crates/ec-hw/examples/hw_parity.rs b/crates/ec-hw/examples/hw_parity.rs index 14f3901e..ca73fe40 100644 --- a/crates/ec-hw/examples/hw_parity.rs +++ b/crates/ec-hw/examples/hw_parity.rs @@ -3,7 +3,6 @@ //! Every encode and decode runs in a child process of this binary, because the driver's state outlives a display: within one process the same encode lands at different sizes depending on what ran before it. //! //! ```text -//! cargo run --release -p ec-hw --example hw_parity -- //! ``` use std::fmt::Display; @@ -115,7 +114,7 @@ fn spec_from_key(key: &str) -> Spec { fn make_source(dir: &Path, source: &str, w: u32, h: u32) -> PathBuf { let path = dir.join(format!("{source}-{w}x{h}.yuv")); if !path.exists() { - let status = Command::new("ffmpeg") + let status = ec_testkit::ffmpeg() .args(["-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i"]) .arg(format!("{source}=size={w}x{h}:rate={FPS}")) .args(["-frames:v", &FRAMES.to_string(), "-pix_fmt", "yuv420p", "-f", "rawvideo"]) @@ -303,7 +302,7 @@ fn field(out: &str, key: &str) -> Option { fn psnr_y(stream: &Path, format: &str, source: &Path, (w, h): (u32, u32)) -> Option { let rate = FPS.to_string(); let size = format!("{w}x{h}"); - let out = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args(["-nostdin", "-v", "info", "-f", format, "-r", &rate, "-i"]) .arg(stream) .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-s", &size, "-r", &rate, "-i"]) @@ -393,7 +392,7 @@ fn main() { } return; } - let dir = PathBuf::from(std::env::args().nth(1).expect("scratch dir argument")); + let dir = std::env::temp_dir(); let me = std::env::current_exe().expect("own path"); let mut decode_inputs: Vec<(&'static str, (u32, u32), Spec, Backend, PathBuf)> = Vec::new(); diff --git a/crates/ec-hw/examples/hw_ten.rs b/crates/ec-hw/examples/hw_ten.rs index 3dca5a9c..d7f5fb0e 100644 --- a/crates/ec-hw/examples/hw_ten.rs +++ b/crates/ec-hw/examples/hw_ten.rs @@ -9,7 +9,7 @@ const FRAMES: u32 = 30; const PEAK: f64 = 1023.0; fn main() { - let dir = std::env::args().nth(1).unwrap_or_else(|| ".".into()); + let dir = std::env::temp_dir().display().to_string(); let rates = [ ("cqp", RateControlMode::ConstantQp { qp: 30 }), ("cbr", RateControlMode::ConstantBitrate), diff --git a/crates/ec-hw/tests/film_grain.rs b/crates/ec-hw/tests/film_grain.rs index 4374e060..9621042c 100644 --- a/crates/ec-hw/tests/film_grain.rs +++ b/crates/ec-hw/tests/film_grain.rs @@ -7,8 +7,8 @@ //! that both apply grain: `ec-av1` (this family's software decoder) and ffmpeg //! (libdav1d). Per-frame deviations are reported, not just asserted. -use std::path::{Path, PathBuf}; -use std::process::{Command, Stdio}; +use std::path::Path; +use std::process::Stdio; use std::rc::Rc; use ec_hw::{Codec, Decoder, I420}; @@ -17,10 +17,6 @@ use ec_va::Display; /// Frames in the grain fixture (every one of them is shown). const FRAMES: usize = 90; -fn fixture() -> PathBuf { - Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/bitstreams/av1-grain.ivf") -} - fn display() -> Option> { match ec_va::open() { Ok(display) => Some(display), @@ -145,7 +141,7 @@ fn software_frames(data: &[u8]) -> Vec { /// ffmpeg's decode (libdav1d, grain applied by default) as raw 4:2:0 planes. fn ffmpeg_frames(path: &Path, width: usize, height: usize) -> Option> { - let output = Command::new("ffmpeg") + let output = ec_testkit::ffmpeg() .args(["-nostdin", "-v", "error", "-i"]) .arg(path) .args([ @@ -185,21 +181,8 @@ fn ffmpeg_frames(path: &Path, width: usize, height: usize) -> Option /// the two software decoders frame by frame. #[test] fn hardware_grain_matches_software_decoders() { - let path = fixture(); - let Ok(data) = std::fs::read(&path) else { - // `EC_REQUIRE_FIXTURES=1` turns an absent fixture into a failure, so a - // checkout that never generated it cannot report this test green. - assert!( - std::env::var_os("EC_REQUIRE_FIXTURES").is_none(), - "EC_REQUIRE_FIXTURES=1 but fixture {} is absent", - path.display() - ); - eprintln!( - "skipped: {} is absent (extract it from test_av1_grain.mkv)", - path.display() - ); - return; - }; + let path = ec_testkit::fixture("bitstreams/av1-grain.ivf"); + let data = std::fs::read(&path).expect("read the grain fixture"); let Some(display) = display() else { return; }; diff --git a/crates/ec-hw/tests/gpu.rs b/crates/ec-hw/tests/gpu.rs index 36d55f88..32f30614 100644 --- a/crates/ec-hw/tests/gpu.rs +++ b/crates/ec-hw/tests/gpu.rs @@ -2,8 +2,6 @@ //! //! They are not `#[ignore]`d — a hardware crate whose tests do not touch the //! hardware tests nothing — but they *skip* (print and return) when there is no -//! VA display or when the fixtures have not been generated. That keeps a -//! checkout without a GPU green while making this machine's run meaningful. //! //! The oracle is ffmpeg's software decoder: every fixture is decoded here and //! by `ffmpeg -f rawvideo`, and the two are compared frame by frame. @@ -12,7 +10,7 @@ use std::io::Read; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; use std::rc::Rc; -use std::time::{Duration, Instant}; +use std::time::Instant; use ec_hw::{ Codec, Decoder, EncCodec, Encoder, EncoderConfig, Frame, FrameMetadata, H264Profile, I420, @@ -24,10 +22,6 @@ use ec_va::Display; /// reordering, few enough to keep the suite under a minute. const FRAMES: usize = 24; -fn bitstreams() -> PathBuf { - Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/bitstreams") -} - fn display() -> Option> { match ec_va::open() { Ok(display) => Some(display), @@ -38,23 +32,6 @@ fn display() -> Option> { } } -fn fixtures(pattern: &str) -> Vec { - let Ok(dir) = std::fs::read_dir(bitstreams()) else { - return Vec::new(); - }; - let mut out: Vec = dir - .flatten() - .map(|e| e.path()) - .filter(|p| { - p.file_name() - .and_then(|n| n.to_str()) - .is_some_and(|n| n.ends_with(pattern)) - }) - .collect(); - out.sort(); - out -} - /// The software reference: ffmpeg decoding the same file to raw planes. struct Reference { child: std::process::Child, @@ -65,7 +42,7 @@ struct Reference { impl Reference { fn open(path: &Path, width: u32, height: u32, ten_bit: bool) -> Option { let pix = if ten_bit { "yuv420p10le" } else { "yuv420p" }; - let child = Command::new("ffmpeg") + let child = ec_testkit::ffmpeg() .args(["-nostdin", "-v", "error", "-i"]) .arg(path) // `-fps_mode passthrough`: without it ffmpeg conforms its output to @@ -301,10 +278,7 @@ fn split_ivf(data: &[u8]) -> Vec<&[u8]> { /// Decode every named fixture and compare with ffmpeg, frame by frame. fn compare_against_ffmpeg(files: &[PathBuf], codec: Codec, ten_bit: bool) { let Some(display) = display() else { return }; - if files.is_empty() { - eprintln!("skipped: no fixtures — run scripts/gen-bitstream-fixtures.sh"); - return; - } + assert!(!files.is_empty(), "no fixtures: run scripts/fixtures.sh"); let mut table = Vec::new(); for path in files { let data = std::fs::read(path).expect("fixture is readable"); @@ -381,7 +355,7 @@ fn name_of(p: &Path) -> String { /// The 4:2:0 fixtures of one kind; the 4:4:4 and monochrome ones are the /// profiles this GPU does not decode, and have their own test. fn profile_420(pattern: &str, codec: &str) -> Vec { - fixtures(pattern) + ec_testkit::fixtures("bitstreams", pattern) .into_iter() .filter(|p| { let name = name_of(p); @@ -407,14 +381,14 @@ fn ten_bit(pattern: &str, codec: &str) -> Vec { /// The selection must not depend on where the repository is checked out. #[test] fn fixture_selection_ignores_the_checkout_path() { - for p in eight_bit(".ivf", "av1") { + for p in eight_bit("ivf", "av1") { let name = name_of(&p); assert!( name.starts_with("av1") && !name.contains("10bit"), "{name} is not an 8-bit AV1 fixture" ); } - for p in ten_bit(".ivf", "vp9") { + for p in ten_bit("ivf", "vp9") { let name = name_of(&p); assert!( name.starts_with("vp9") && name.contains("10bit"), @@ -425,12 +399,12 @@ fn fixture_selection_ignores_the_checkout_path() { #[test] fn h264_matches_ffmpeg() { - compare_against_ffmpeg(&fixtures(".264"), Codec::H264, false); + compare_against_ffmpeg(&ec_testkit::fixtures("bitstreams", "264"), Codec::H264, false); } #[test] fn hevc_8bit_matches_ffmpeg() { - compare_against_ffmpeg(&eight_bit(".265", "hevc"), Codec::H265, false); + compare_against_ffmpeg(&eight_bit("265", "hevc"), Codec::H265, false); } /// The 10-bit path, which is the RT format defect this crate exists to not @@ -438,11 +412,8 @@ fn hevc_8bit_matches_ffmpeg() { /// P010 surface, and the ten bits must survive to the caller. #[test] fn hevc_10bit_decodes_to_p010() { - let files = ten_bit(".265", "hevc"); - if files.is_empty() { - eprintln!("skipped: no 10-bit HEVC fixtures"); - return; - } + let files = ten_bit("265", "hevc"); + assert!(!files.is_empty(), "no 10-bit HEVC fixtures"); let Some(display) = display() else { return }; let data = std::fs::read(&files[0]).expect("fixture is readable"); let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens"); @@ -461,22 +432,22 @@ fn hevc_10bit_decodes_to_p010() { #[test] fn vp9_matches_ffmpeg() { - compare_against_ffmpeg(&eight_bit(".ivf", "vp9"), Codec::Vp9, false); + compare_against_ffmpeg(&eight_bit("ivf", "vp9"), Codec::Vp9, false); } #[test] fn vp9_10bit_matches_ffmpeg() { - compare_against_ffmpeg(&ten_bit(".ivf", "vp9"), Codec::Vp9, true); + compare_against_ffmpeg(&ten_bit("ivf", "vp9"), Codec::Vp9, true); } #[test] fn av1_matches_ffmpeg() { - compare_against_ffmpeg(&eight_bit(".ivf", "av1"), Codec::Av1, false); + compare_against_ffmpeg(&eight_bit("ivf", "av1"), Codec::Av1, false); } #[test] fn av1_10bit_matches_ffmpeg() { - compare_against_ffmpeg(&ten_bit(".ivf", "av1"), Codec::Av1, true); + compare_against_ffmpeg(&ten_bit("ivf", "av1"), Codec::Av1, true); } /// Every "not supported" this crate says has to be a fact about the driver, not @@ -499,11 +470,7 @@ fn unsupported_profiles_are_refused_with_a_reason() { ec_va::caps::Profile::AV1Profile1, ), ] { - let path = bitstreams().join(file); - if !path.exists() { - eprintln!("skipped: no {file}"); - continue; - } + let path = ec_testkit::fixture(&format!("bitstreams/{file}")); assert!( !caps.supports(absent, ec_va::caps::Entrypoint::VLD), "{absent:?} is in fact supported — the refusal below would be a bug" @@ -610,7 +577,7 @@ fn round_trip(codec: EncCodec, width: u32, height: u32, min_db: f64) { // ffprobe first: the conformance window / frame cropping has to survive, so // a 1916-wide encode comes back 1916 wide and not 1920. - let probe = Command::new("ffprobe") + let probe = ec_testkit::ffprobe() .args([ "-v", "error", @@ -691,7 +658,7 @@ fn h264_profile_round_trip(profile: H264Profile, ffprobe_name: &str) { let path = dir.join("out.264"); std::fs::write(&path, &stream).expect("write bitstream"); - let probe = Command::new("ffprobe") + let probe = ec_testkit::ffprobe() .args([ "-v", "error", @@ -712,7 +679,7 @@ fn h264_profile_round_trip(profile: H264Profile, ffprobe_name: &str) { ); // Strict decode: any warning or error on stderr fails the test. - let decode = Command::new("ffmpeg") + let decode = ec_testkit::ffmpeg() .args(["-nostdin", "-v", "warning", "-i"]) .arg(&path) .args(["-f", "null", "-"]) @@ -798,13 +765,7 @@ fn our_encoder_and_our_decoder_agree() { fn encode_frame_zero_copy_matches_the_cpu_path() { let Some(display) = display() else { return }; let (width, height) = (1920u32, 1080u32); - let Some(path) = fixtures(".264") - .into_iter() - .find(|p| p.file_name().and_then(|n| n.to_str()) == Some("h264-1080p-23.976-8bit.264")) - else { - eprintln!("skipped: no h264-1080p fixture — run scripts/gen-bitstream-fixtures.sh"); - return; - }; + let path = ec_testkit::fixture("bitstreams/h264-1080p-23.976-8bit.264"); let data = std::fs::read(&path).expect("fixture is readable"); let frames = 10usize; @@ -921,7 +882,7 @@ fn colour_description_reaches_the_vui() { (path, coded.data) }; let probe = |path: &Path| -> String { - let out = Command::new("ffprobe") + let out = ec_testkit::ffprobe() .args([ "-v", "error", @@ -1045,38 +1006,6 @@ fn av1_encode_agrees_between_two_decoders() { // encoder does not serve his files. // --------------------------------------------------------------------------- -/// Film B's native 10-bit crop from the real-library manifest: `(path, seek, -/// width, height, x, y)`, the same 1920x1024 window and 00:40:00 seek the -/// software gates use (`ec-av1`'s `native_gate_clips`). -fn ten_bit_film_clip() -> Option<(PathBuf, String, u32, u32, u32, u32)> { - let manifest = - Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/real-library-manifest.tsv"); - let text = std::fs::read_to_string(manifest).ok()?; - for line in text.lines().skip(1) { - let f: Vec<&str> = line.split('\t').collect(); - if f.len() < 7 || f[2] != "av1" || f[5] != "yuv420p10le" || f[3] != "3840" { - continue; - } - let path = PathBuf::from(f[0]); - if !path.exists() { - continue; - } - let (nw, nh): (u32, u32) = (f[3].parse().ok()?, f[4].parse().ok()?); - let (cw, ch) = (nw.min(1920) / 128 * 128, nh.min(1024) / 128 * 128); - return Some(( - path, - "00:40:00".into(), - cw, - ch, - ((nw - cw) / 2) & !1, - ((nh - ch) / 2) & !1, - )); - } - None -} - -/// A 10-bit gradient with real dynamic range, used when the manifest has no -/// 10-bit film: 64..940 across the frame with a moving highlight, so the /// stream is neither flat nor 8-bit content dressed up as 10. fn source_frame_16(width: u32, height: u32, t: u32) -> I420_16 { let (w, h) = (width as usize, height as usize); @@ -1109,6 +1038,14 @@ fn source_frame_16(width: u32, height: u32, t: u32) -> I420_16 { f } +fn ten_bit_source(dir: &Path, frames: u32) -> (String, PathBuf, Vec) { + let y4m = dir.join("source-10bit.y4m"); + let (w, h) = (1920u32, 1024u32); + let planes: Vec = (0..frames).map(|t| source_frame_16(w, h, t)).collect(); + assert!(write_y4m_16(&y4m, &planes, (24, 1)), "write the 10-bit y4m"); + ("synthetic 10-bit gradient".into(), y4m, planes) +} + /// Write 10-bit planes as a y4m so ffmpeg sees the same source the encoder did. fn write_y4m_16(path: &Path, frames: &[I420_16], fps: (u32, u32)) -> bool { use std::io::Write; @@ -1141,85 +1078,11 @@ fn write_y4m_16(path: &Path, frames: &[I420_16], fps: (u32, u32)) -> bool { out.flush().is_ok() } -/// The 10-bit source the 10-bit gates encode, plus the y4m every reference -/// encoder and every PSNR reads: his own film when the manifest has it, -/// a synthetic 10-bit gradient otherwise. The label says which — a gate that -/// does not say what it exercised proves nothing about his library. -fn ten_bit_source(dir: &Path, frames: u32) -> Option<(String, PathBuf, Vec)> { - let y4m = dir.join("source-10bit.y4m"); - let _ = std::fs::remove_file(&y4m); - if let Some((path, seek, cw, ch, x, y)) = ten_bit_film_clip() { - let ok = Command::new("ffmpeg") - .args(["-nostdin", "-v", "error", "-y", "-ss", &seek, "-i"]) - .arg(&path) - .args([ - "-frames:v", - &frames.to_string(), - "-vf", - &format!("crop={cw}:{ch}:{x}:{y}"), - "-pix_fmt", - "yuv420p10le", - // y4m's 10-bit chroma formats are outside its official set. - "-strict", - "-1", - ]) - .arg(&y4m) - .status() - .is_ok_and(|s| s.success()); - if ok && let Some(planes) = raw_frames_16(&y4m, cw, ch, frames) { - return Some(("film B 10-bit native crop".into(), y4m, planes)); - } - eprintln!("film B 10-bit extraction failed; falling back to the synthetic gradient"); - } - let (w, h) = (1920u32, 1024u32); - let planes: Vec = (0..frames).map(|t| source_frame_16(w, h, t)).collect(); - write_y4m_16(&y4m, &planes, (24, 1)).then_some(( - "synthetic 10-bit gradient".into(), - y4m, - planes, - )) -} - -/// The same pictures as 10-bit planes, for the hardware encoder's own input. -fn raw_frames_16(y4m: &Path, width: u32, height: u32, frames: u32) -> Option> { - let out = Command::new("ffmpeg") - .args(["-nostdin", "-v", "error", "-i"]) - .arg(y4m) - .args(["-pix_fmt", "yuv420p10le", "-f", "rawvideo", "-"]) - .stderr(Stdio::null()) - .output() - .ok()?; - let (w, h) = (width as usize, height as usize); - let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); - let frame_len = (w * h + 2 * cw * ch) * 2; - let read = |s: &[u8]| -> Vec { - s.as_chunks::<2>() - .0 - .iter() - .map(|p| u16::from_le_bytes(*p)) - .collect() - }; - let mut pictures = Vec::new(); - for chunk in out.stdout.chunks_exact(frame_len).take(frames as usize) { - let (y, rest) = chunk.split_at(w * h * 2); - let (u, v) = rest.split_at(cw * ch * 2); - pictures.push(I420_16 { - y: read(y), - u: read(u), - v: read(v), - width, - height, - bit_depth: 10, - }); - } - (!pictures.is_empty()).then_some(pictures) -} - /// What ffprobe calls the stream's pixel format — for an AV1 stream that is /// libdav1d reporting the sequence header's `high_bitdepth`, read by a decoder /// that shares no code with the writer above. fn ffprobe_pix_fmt(path: &Path, format: &str) -> Option { - let out = Command::new("ffprobe") + let out = ec_testkit::ffprobe() .args([ "-v", "error", @@ -1274,10 +1137,7 @@ fn hevc_main10_encode_round_trips() { let Some(display) = display() else { return }; let dir = std::env::temp_dir().join("ec-hw-hevc-10bit"); let _ = std::fs::create_dir_all(&dir); - let Some((_, _, planes)) = ten_bit_source(&dir, 10) else { - eprintln!("skipped: no 10-bit source could be built"); - return; - }; + let (_, _, planes) = ten_bit_source(&dir, 10); let (width, height) = (planes[0].width, planes[0].height); let data = match encode_stream_16( &display, @@ -1328,11 +1188,7 @@ fn av1_10bit_encode_agrees_between_two_decoders() { let dir = std::env::temp_dir().join("ec-hw-av1-10bit"); let _ = std::fs::create_dir_all(&dir); let frames = 10u32; - let Some((label, y4m, planes)) = ten_bit_source(&dir, frames) else { - eprintln!("skipped: no 10-bit source could be built"); - return; - }; - let _ = y4m; + let (label, _, planes) = ten_bit_source(&dir, frames); let (width, height) = (planes[0].width, planes[0].height); let data = match encode_stream_16( &display, @@ -1432,23 +1288,16 @@ fn av1_10bit_encode_agrees_between_two_decoders() { #[test] fn av1_encode_rate_control_lands() { let Some(display) = display() else { return }; - let clips = real_clips(); - let Some((label, source)) = clips.into_iter().next() else { - eprintln!("skipped: no real-library manifest"); - return; - }; + let (label, source) = real_clips().remove(0); let dir = std::env::temp_dir().join("ec-hw-av1-rc"); let _ = std::fs::create_dir_all(&dir); let (width, height, frames, fps) = (1920u32, 1080u32, 60u32, 30u32); let y4m = dir.join("rc-source.y4m"); - if !extract_y4m(&source, &y4m, width, height, frames) { - eprintln!("skipped {label}: extraction failed"); - return; - } - let Some(planes) = raw_frames(&y4m, width, height, frames) else { - eprintln!("skipped {label}: no frames extracted"); - return; - }; + assert!( + extract_y4m(&source, &y4m, width, height, frames), + "{label}: extraction failed" + ); + let planes = raw_frames(&y4m, width, height, frames).expect("frames of the trailer"); println!( "AV1 rate control on {label}, {width}x{height} yuv420p, {} frames at {fps} fps:", @@ -1547,7 +1396,7 @@ fn av1_encode_rate_control_lands() { /// [`ffmpeg_psnr`] with the rate pinned to `fps` on both inputs. fn ffmpeg_psnr_at(coded: &Path, source: &Path, fps: u32) -> Option { let rate = fps.to_string(); - let out = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args(["-nostdin", "-v", "info", "-f", "obu", "-r", &rate]) .arg("-i") .arg(coded) @@ -1567,126 +1416,6 @@ fn ffmpeg_psnr_at(coded: &Path, source: &Path, fps: u32) -> Option { .filter(|v| v.is_finite()) } -/// What the GPU's 10-bit AV1 costs against 10-bit software, on his own film. -/// -/// The same shape as the 8-bit row, at film B's native 1920x1024 crop and -/// entirely in the 10-bit domain: no arm ever sees an 8-bit sample, so the -/// comparison is encoder against encoder rather than depth against depth. -/// Skips when the manifest has no 10-bit film -- a synthetic gradient would -/// be a BD-rate number about a gradient. -#[test] -fn av1_10bit_bd_row_vs_software() { - let Some(display) = display() else { return }; - let dir = std::env::temp_dir().join("ec-hw-av1-10bit-bd"); - let _ = std::fs::create_dir_all(&dir); - let frames = 12u32; - let Some((label, y4m, planes)) = ten_bit_source(&dir, frames) else { - eprintln!("skipped: no 10-bit source could be built"); - return; - }; - if !label.starts_with("film") { - eprintln!("skipped: no 10-bit film in the real-library manifest ({label})"); - return; - } - let (width, height) = (planes[0].width, planes[0].height); - let coded = planes.len() as u32; - - let mut ours = Vec::new(); - for qp in [180u32, 140, 100, 60] { - let data = match encode_stream_16( - &display, - EncCodec::Av1, - &planes, - qp, - RateControlMode::ConstantQp { qp }, - ) { - Ok(data) => data, - Err(e) => { - eprintln!("skipped: 10-bit AV1 encode unavailable ({e})"); - return; - } - }; - let path = dir.join(format!("hw10-{qp}.obu")); - std::fs::write(&path, &data).expect("write"); - if let Some(db) = ffmpeg_psnr(&path, &y4m, true) { - ours.push((data.len() as f64 * 8.0 / f64::from(coded), db)); - } - } - let rav1e: Vec<(f64, f64)> = [180u32, 140, 100, 60] - .iter() - .filter_map(|q| { - software_point( - &dir, - &y4m, - "film-B-10bit", - "librav1e", - &[ - "-pix_fmt", - "yuv420p10le", - "-rav1e-params", - &format!("speed=6:quantizer={q}"), - "-g", - "60", - ], - *q, - coded, - ) - }) - .collect(); - let libaom: Vec<(f64, f64)> = [56u32, 44, 32, 20] - .iter() - .filter_map(|crf| { - software_point( - &dir, - &y4m, - "film-B-10bit", - "libaom-av1", - &[ - "-pix_fmt", - "yuv420p10le", - "-cpu-used", - "6", - "-crf", - &crf.to_string(), - "-b:v", - "0", - "-g", - "60", - ], - *crf, - coded, - ) - }) - .collect(); - - println!("10-bit BD row: {label}, {width}x{height} yuv420p10le, {coded} frames"); - for (name, ladder) in [ - ("hw AV1 10-bit", &ours), - ("librav1e 10-bit", &rav1e), - ("libaom 10-bit", &libaom), - ] { - println!(" {name}: {ladder:?}"); - for pair in ladder.windows(2) { - assert!( - pair[1].0 > pair[0].0 && pair[1].1 > pair[0].1, - "{name}: ladder is not monotone at {pair:?}" - ); - } - } - if ours.len() >= 3 && rav1e.len() >= 3 { - println!( - " BD-rate: hw AV1 10-bit vs librav1e speed 6 10-bit: {:+.1}%", - bd_rate(&rav1e, &ours) * 100.0 - ); - } - if ours.len() >= 3 && libaom.len() >= 3 { - println!( - " BD-rate: hw AV1 10-bit vs libaom cpu-used 6 10-bit: {:+.1}%", - bd_rate(&libaom, &ours) * 100.0 - ); - } -} - /// What the GPU's AV1 costs against software, on his own content. /// /// Four quantisers per encoder on a 1920x1080 crop of a film and of a screen @@ -1698,11 +1427,6 @@ fn av1_10bit_bd_row_vs_software() { #[test] fn av1_encode_bd_row_vs_software() { let Some(display) = display() else { return }; - let clips = real_clips(); - if clips.is_empty() { - eprintln!("skipped: no real-library manifest"); - return; - } // A ladder compared with itself saves nothing: the check on the metric. let same = [(100.0, 30.0), (200.0, 35.0), (400.0, 40.0)]; assert!( @@ -1712,20 +1436,14 @@ fn av1_encode_bd_row_vs_software() { let dir = std::env::temp_dir().join("ec-hw-av1-bd"); let _ = std::fs::create_dir_all(&dir); - for (label, source) in clips { + for (label, source) in real_clips() { let y4m = dir.join(format!("{label}.y4m")); let (width, height, frames) = (1920u32, 1080u32, 12u32); - if !extract_y4m(&source, &y4m, width, height, frames) { - eprintln!("skipped {label}: extraction failed"); - continue; - } - let planes = match raw_frames(&y4m, width, height, frames) { - Some(planes) => planes, - None => { - eprintln!("skipped {label}: no frames extracted"); - continue; - } - }; + assert!( + extract_y4m(&source, &y4m, width, height, frames), + "{label}: extraction failed" + ); + let planes = raw_frames(&y4m, width, height, frames).expect("frames of the trailer"); let mut ours = Vec::new(); // Descending quantiser: every ladder here is ordered by rising rate. @@ -1840,7 +1558,7 @@ fn software_point( ) -> Option<(f64, f64)> { let out = dir.join(format!("{label}-{encoder}-{point}.ivf")); let _ = std::fs::remove_file(&out); - let status = Command::new("ffmpeg") + let status = ec_testkit::ffmpeg() .args(["-nostdin", "-v", "error", "-y", "-i"]) .arg(y4m) .args(["-c:v", encoder]) @@ -1858,7 +1576,7 @@ fn software_point( /// PSNR of a coded stream against the source, from ffmpeg's own filter. fn ffmpeg_psnr(coded: &Path, source: &Path, raw_obu: bool) -> Option { - let mut cmd = Command::new("ffmpeg"); + let mut cmd = ec_testkit::ffmpeg(); cmd.args(["-nostdin", "-v", "info"]); if raw_obu { cmd.args(["-f", "obu"]); @@ -1889,7 +1607,7 @@ fn ffmpeg_psnr(coded: &Path, source: &Path, raw_obu: bool) -> Option { /// A 1920x1080 crop of `frames` pictures, as a y4m file the encoders share. fn extract_y4m(source: &Path, out: &Path, width: u32, height: u32, frames: u32) -> bool { let _ = std::fs::remove_file(out); - Command::new("ffmpeg") + ec_testkit::ffmpeg() .args(["-nostdin", "-v", "error", "-y", "-ss", "60", "-i"]) .arg(source) .args([ @@ -1907,7 +1625,7 @@ fn extract_y4m(source: &Path, out: &Path, width: u32, height: u32, frames: u32) /// The same pictures as planes, for the hardware encoder's own input. fn raw_frames(y4m: &Path, width: u32, height: u32, frames: u32) -> Option> { - let out = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args(["-nostdin", "-v", "error", "-i"]) .arg(y4m) .args(["-pix_fmt", "yuv420p", "-f", "rawvideo", "-"]) @@ -1932,35 +1650,11 @@ fn raw_frames(y4m: &Path, width: u32, height: u32, frames: u32) -> Option Vec<(&'static str, PathBuf)> { - let manifest = - Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/real-library-manifest.tsv"); - let Ok(text) = std::fs::read_to_string(&manifest) else { - return Vec::new(); - }; - let mut film = None; - let mut screen = None; - for line in text.lines().skip(1) { - let f: Vec<&str> = line.split('\t').collect(); - if f.len() < 7 || f[2] != "h264" { - continue; - } - let width: u32 = f[3].parse().unwrap_or(0); - // Long enough that the extraction's 60 s seek lands inside the file. - let duration: f64 = f.get(8).and_then(|d| d.parse().ok()).unwrap_or(0.0); - if width < 1280 || duration < 90.0 { - continue; - } - let path = PathBuf::from(f[0]); - if f[0].contains("/Films/") && film.is_none() { - film = Some(("film A", path)); - } else if f[0].contains("/OBS/") && screen.is_none() { - screen = Some(("screen capture", path)); - } - } - film.into_iter().chain(screen).collect() + vec![ + ("sintel 1080p", ec_testkit::fixture("open/sintel_trailer-1080p.mp4")), + ("sintel 720p", ec_testkit::fixture("open/sintel_trailer-720p.mp4")), + ] } /// BD-rate of `test` against `reference`, as a fraction (negative = fewer @@ -2069,11 +1763,7 @@ fn av1_encode_speed() { #[test] fn h264_frame_num_gaps_are_synthesised() { let Some(display) = display() else { return }; - let path = bitstreams().join("h264-1080p-23.976-8bit.264"); - if !path.exists() { - eprintln!("skipped: no H.264 fixture"); - return; - } + let path = ec_testkit::fixture("bitstreams/h264-1080p-23.976-8bit.264"); let data = std::fs::read(&path).expect("fixture is readable"); let units = split_access_units(&data, Codec::H264); assert!( @@ -2148,11 +1838,7 @@ fn long_decode_does_not_grow_the_resident_set() { return; } let Some(display) = display() else { return }; - let path = bitstreams().join("h264-1080p-23.976-8bit.264"); - if !path.exists() { - eprintln!("skipped: no H.264 fixture"); - return; - } + let path = ec_testkit::fixture("bitstreams/h264-1080p-23.976-8bit.264"); let data = std::fs::read(&path).expect("fixture is readable"); let units = split_access_units(&data, Codec::H264); let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder opens"); @@ -2216,11 +1902,7 @@ fn long_decode_does_not_grow_the_resident_set() { #[test] fn frames_export_as_dma_buf() { let Some(display) = display() else { return }; - let path = bitstreams().join("h264-1080p-23.976-8bit.264"); - if !path.exists() { - eprintln!("skipped: no H.264 fixture"); - return; - } + let path = ec_testkit::fixture("bitstreams/h264-1080p-23.976-8bit.264"); let data = std::fs::read(&path).expect("fixture is readable"); let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder opens"); let mut exported = 0usize; @@ -2256,7 +1938,7 @@ fn elementary(path: &Path, codec: Codec, frames: usize) -> Option> { Codec::H265 => &["-bsf:v", "hevc_mp4toannexb", "-f", "hevc"], Codec::Vp9 | Codec::Av1 => &["-f", "ivf"], }; - let out = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args(["-nostdin", "-v", "error", "-i"]) .arg(path) .args(["-map", "0:v:0", "-c:v", "copy"]) @@ -2271,54 +1953,17 @@ fn elementary(path: &Path, codec: Codec, frames: usize) -> Option> { (!out.stdout.is_empty()).then_some(out.stdout) } -/// Decode 500 frames of five files from the real library and compare with -/// ffmpeg, per file. -/// -/// Fixtures are 5-second synthetic clips at round resolutions; his library is -/// 1038-high HEVC, 792-high AV1 and hour-long H.264 screen captures. A claim -/// that has not met those is a claim about fixtures. #[test] fn real_library_spot_check() { let Some(display) = display() else { return }; - let manifest = - Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/real-library-manifest.tsv"); - let Ok(text) = std::fs::read_to_string(&manifest) else { - eprintln!( - "skipped: no fixtures/real-library-manifest.tsv — run scripts/scan-real-library.sh" - ); - return; - }; - - // One file per (codec, bit depth) the hardware path serves, five in all. - let mut wanted: Vec<(String, Codec, bool)> = Vec::new(); - let mut seen: Vec<(String, u8)> = Vec::new(); - for line in text.lines().skip(1) { - let f: Vec<&str> = line.split('\t').collect(); - if f.len() < 7 { - continue; - } - let (path, vcodec, depth) = (f[0].to_string(), f[2], f[6].parse::().unwrap_or(8)); - let codec = match vcodec { - "h264" => Codec::H264, - "hevc" => Codec::H265, - "vp9" => Codec::Vp9, - "av1" => Codec::Av1, - _ => continue, - }; - let key = (vcodec.to_string(), depth); - if seen.iter().filter(|k| **k == key).count() >= 2 || wanted.len() >= 5 { - continue; - } - if !Path::new(&path).exists() { - continue; - } - seen.push(key); - wanted.push((path, codec, depth > 8)); - } - if wanted.is_empty() { - eprintln!("skipped: no files from the manifest are present"); - return; - } + let wanted: Vec<(PathBuf, Codec, bool)> = [ + ("open/sintel_trailer-480p.mp4", Codec::H264, false), + ("open/sintel_trailer-1080p.mp4", Codec::H264, false), + ("derived/sintel720-x265-main10.mp4", Codec::H265, true), + ] + .into_iter() + .map(|(rel, codec, ten_bit)| (ec_testkit::fixture(rel), codec, ten_bit)) + .collect(); // 500 frames per file by default; a diagnostic run can ask for fewer. let limit: usize = std::env::var("EC_HW_SWEEP_FRAMES") @@ -2328,10 +1973,7 @@ fn real_library_spot_check() { let mut table = Vec::new(); for (path, codec, ten_bit) in &wanted { let path = Path::new(path); - let Some(data) = elementary(path, *codec, limit) else { - table.push(format!("{:<52} SKIP (no elementary stream)", short(path))); - continue; - }; + let data = elementary(path, *codec, limit).expect("elementary stream"); let mut decoder = Decoder::new(&display, *codec).expect("decoder opens"); let mut reference: Option = None; let mut worst = f64::INFINITY; @@ -2413,7 +2055,6 @@ fn plane_psnr(a: &[u16], b: &[u16], peak: f64) -> f64 { } } -/// P010 correctness on the real 4K HDR film, plane by plane. /// /// `real_library_spot_check` already pins the whole-frame PSNR at >= 40 dB /// for a mix of files; this isolates Y from U/V on this specific 10-bit film, @@ -2423,21 +2064,11 @@ fn plane_psnr(a: &[u16], b: &[u16], peak: f64) -> f64 { /// a bug). A collapsed U/V PSNR here (a grey frame) would mean the chroma /// plane is being read at the wrong stride/offset; it is not, on this file. #[test] -fn ten_bit_4k_chroma_is_not_grey() { +fn ten_bit_chroma_is_not_grey() { let Some(display) = display() else { return }; - let path = Path::new( - "/home/user/Downloads/reeld\ - /reeld.mkv", - ); - if !path.exists() { - eprintln!("skipped: film not present"); - return; - } + let path = &ec_testkit::fixture("derived/sintel720-x265-main10.mp4"); let frames = 3usize; - let Some(data) = elementary(path, Codec::H265, frames) else { - eprintln!("skipped: no elementary stream"); - return; - }; + let data = elementary(path, Codec::H265, frames).expect("elementary stream"); let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens"); let mut ref10: Option = None; let mut ref8: Option = None; @@ -2492,67 +2123,14 @@ fn ten_bit_4k_chroma_is_not_grey() { assert_eq!(compared, frames, "not all frames were compared"); } -/// The HEVC HDR peak (`content_light_level_information` and -/// `mastering_display_colour_volume` prefix SEI), on the one real file that -/// only carries it there: the Matroska `Colour` element itself has no MaxCLL/ -/// MaxFALL for this rip (verified separately against `ffprobe`), so a decoder -/// that does not read the SEI reports none at all. Numbers match what -/// `ffprobe -show_frames -read_intervals %+#1 -show_entries -/// frame_side_data_list` reports for this file. -#[test] -fn hdr_film_light_level_sei_is_exposed() { - let Some(display) = display() else { return }; - let path = Path::new( - "/home/user/Downloads/reeld\ - /reeld.mkv", - ); - if !path.exists() { - eprintln!("skipped: film not present"); - return; - } - let frames = 2usize; - let Some(data) = elementary(path, Codec::H265, frames) else { - eprintln!("skipped: no elementary stream"); - return; - }; - let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens"); - let mut seen = 0usize; - decode_stream(&mut decoder, Codec::H265, &data, frames, |frame| { - seen += 1; - let colour = frame - .colour() - .expect("HEVC decoder resolves colour metadata"); - assert_eq!( - colour.description.codes(), - (9, 16, 9), - "primaries/transfer/matrix (BT.2020 / PQ / BT.2020 NCL)" - ); - assert_eq!(colour.light.max_cll, Some(1230.0), "MaxCLL"); - assert_eq!(colour.light.max_fall, Some(419.0), "MaxFALL"); - assert!( - colour.light.mastering_max.is_some(), - "mastering display peak missing" - ); - }) - .expect("decode"); - assert_eq!(seen, frames, "not all frames were compared"); -} - /// An SDR H.264 stream, which carries no HDR SEI at all: `Frame::colour` /// either resolves from the VUI or answers [`None`], but never panics. #[test] fn sdr_h264_colour_never_panics() { let Some(display) = display() else { return }; - let paths = fixtures(".264"); - if paths.is_empty() { - eprintln!("skipped: no H.264 fixtures generated"); - return; - } + let paths = ec_testkit::fixtures("bitstreams", "264"); let path = &paths[0]; - let Some(data) = std::fs::read(path).ok() else { - eprintln!("skipped: fixture unreadable"); - return; - }; + let data = std::fs::read(path).expect("fixture is readable"); let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder opens"); let mut seen = 0usize; decode_stream(&mut decoder, Codec::H264, &data, 2, |frame| { @@ -2566,395 +2144,6 @@ fn sdr_h264_colour_never_panics() { assert!(seen > 0, "{}: nothing decoded", short(path)); } -/// Per-frame cost of the 4K 10-bit read-back path, isolated from decode -/// submission itself. -/// -/// The consumer's `hw_decode::the_hdr_film_renders_tone_mapped` measured -/// 1352.5 ms/frame against a 39 ms (24 fps) budget on this film. Decode -/// correctness on it is already pinned by `real_library_spot_check` (bit-exact -/// against ffmpeg), so this isolates which stage of the frame path -- decode, -/// 8-bit readback, 10-bit readback or DRM PRIME export -- the time goes to. -#[test] -fn ten_bit_4k_frame_path_is_realtime() { - let Some(display) = display() else { return }; - let path = Path::new( - "/home/user/Downloads/reeld\ - /reeld.mkv", - ); - if !path.exists() { - eprintln!("skipped: film not present"); - return; - } - let limit = 120usize; - let Some(data) = elementary(path, Codec::H265, limit) else { - eprintln!("skipped: no elementary stream"); - return; - }; - let units = split_access_units(&data, Codec::H265); - assert!( - units.len() > limit, - "film clip too short for {limit} frames" - ); - - #[derive(Clone, Copy)] - enum Op { - DecodeOnly, - ToI420, - ToI420_16, - ExportPrime, - } - fn apply(op: Op, frame: Frame) { - match op { - Op::DecodeOnly => drop(frame), - Op::ToI420 => { - frame.to_i420().expect("readback"); - } - Op::ToI420_16 => { - frame.to_i420_16().expect("readback"); - } - Op::ExportPrime => { - frame.export_prime().expect("export"); - } - } - } - - println!( - "{:<22} {:>10} {:>10} {:>10}", - "stage", "median ms", "min ms", "max ms" - ); - let mut got_to_i420_16 = None; - for (name, op) in [ - ("decode-only", Op::DecodeOnly), - ("decode+to_i420", Op::ToI420), - ("decode+to_i420_16", Op::ToI420_16), - ("decode+export_prime", Op::ExportPrime), - ] { - let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens"); - let mut durations: Vec = Vec::new(); - // Hold a few frames before reading, as the resident-set test does: - // reading one frame per submission measures latency, not throughput, - // and lets decode run ahead of read-back the way a real player does. - let mut pending: Vec = Vec::new(); - let mut t_prev = Instant::now(); - 'outer: for (i, unit) in units.iter().enumerate() { - decoder.decode(unit, i as i64).expect("decode"); - while let Some(frame) = decoder.next_frame() { - pending.push(frame); - if pending.len() < 4 { - continue; - } - for frame in pending.drain(..) { - apply(op, frame); - let now = Instant::now(); - durations.push(now.duration_since(t_prev)); - t_prev = now; - } - if durations.len() >= limit { - break 'outer; - } - } - } - decoder.flush().expect("flush"); - while durations.len() < limit { - let Some(frame) = decoder.next_frame() else { - break; - }; - apply(op, frame); - let now = Instant::now(); - durations.push(now.duration_since(t_prev)); - t_prev = now; - } - assert!( - durations.len() >= 24, - "{name}: only {} frames decoded", - durations.len() - ); - durations.sort(); - let ms = |d: Duration| d.as_secs_f64() * 1000.0; - let median = ms(durations[durations.len() / 2]); - let min = ms(durations[0]); - let max = ms(durations[durations.len() - 1]); - println!("{name:<22} {median:>10.2} {min:>10.2} {max:>10.2}"); - if name == "decode+to_i420_16" { - got_to_i420_16 = Some(median); - } - } - let got = got_to_i420_16.expect("to_i420_16 phase ran"); - println!("target: decode+to_i420_16 <= 39.00 ms/frame median (24 fps budget); got {got:.2}"); -} - -const REELD: &str = "/home/user/Downloads/reeld\ - /reeld.mkv"; - -/// `Encoder::encode_frame` of a 10-bit (P010) source, through the VPP -/// NV12 conversion, against the CPU path (`to_i420` + `encode`) — the same -/// shape as `encode_frame_zero_copy_matches_the_cpu_path`, but for a real -/// P010 4K HDR source instead of a synthetic 8-bit one, and comparing Y and -/// UV PSNR separately rather than the combined figure. -#[test] -fn encode_frame_accepts_p010_via_vpp() { - let Some(display) = display() else { return }; - let path = Path::new(REELD); - if !path.exists() { - eprintln!("skipped: film not present"); - return; - } - let frames = 10usize; - let Some(data) = elementary(path, Codec::H265, frames) else { - eprintln!("skipped: no elementary stream"); - return; - }; - - // This film's HEVC SPS `pic_height_in_luma_samples` is 2160, which is a - // multiple of the H.264 encode block size (16) but not the HEVC one (32, - // next_multiple_of gives 2176) — `encode_frame` no longer refuses that - // mismatch: it routes through the VPP pool by explicit region - // (`Encoder::vpp_into_pool`), so both targets get the full - // encode/decode/PSNR comparison, and the HEVC one additionally gets an - // `ffprobe` check that the visible size in the produced stream is still - // 3840x2160 (the encoder's own cropping, not a VPP resize). - let (mut w, mut h) = (0u32, 0u32); - for (target, dec_codec) in [(EncCodec::H264, Codec::H264), (EncCodec::H265, Codec::H265)] { - let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens"); - let mut zc_stream = Vec::new(); - let mut cpu_stream = Vec::new(); - let mut count = 0i64; - let mut zero_copy: Option = None; - let mut cpu_path: Option = None; - let refused = false; - - decode_stream(&mut decoder, Codec::H265, &data, frames, |frame| { - if refused { - return; - } - (w, h) = frame.display_size; - let zero_copy = zero_copy.get_or_insert_with(|| { - let mut cfg = EncoderConfig::new(target, w, h); - cfg.gop_size = 30; - cfg.rate_control = RateControlMode::ConstantQp { qp: 22 }; - Encoder::new(&display, cfg).expect("zero-copy encoder opens") - }); - let cpu_path = cpu_path.get_or_insert_with(|| { - let mut cfg = EncoderConfig::new(target, w, h); - cfg.gop_size = 30; - cfg.rate_control = RateControlMode::ConstantQp { qp: 22 }; - Encoder::new(&display, cfg).expect("cpu-path encoder opens") - }); - let meta = FrameMetadata { - timestamp: count, - force_keyframe: false, - }; - let zc = zero_copy - .encode_frame(&frame, meta) - .expect("encode_frame (zero copy, P010 via VPP, size mismatch routed through VPP)"); - zc_stream.extend_from_slice(&zc.data); - let i420 = frame.to_i420().expect("readback for the CPU-path baseline"); - let cpu = cpu_path.encode(&i420, meta).expect("encode (CPU path)"); - cpu_stream.extend_from_slice(&cpu.data); - count += 1; - }) - .expect("decode"); - if refused { - continue; - } - assert_eq!( - count as usize, frames, - "{target:?}: decoded {count} of {frames}" - ); - - let mut zc_decoder = Decoder::new(&display, dec_codec).expect("zc decoder opens"); - let mut cpu_decoder = Decoder::new(&display, dec_codec).expect("cpu decoder opens"); - let mut zc_frames = Vec::new(); - let mut cpu_frames = Vec::new(); - decode_stream(&mut zc_decoder, dec_codec, &zc_stream, frames, |f| { - zc_frames.push(f.to_i420().expect("readback")) - }) - .expect("decode zero-copy stream"); - decode_stream(&mut cpu_decoder, dec_codec, &cpu_stream, frames, |f| { - cpu_frames.push(f.to_i420().expect("readback")) - }) - .expect("decode CPU-path stream"); - assert_eq!(zc_frames.len(), frames, "{target:?}: zero-copy frame count"); - assert_eq!(cpu_frames.len(), frames, "{target:?}: CPU-path frame count"); - - let widen = |v: &[u8]| -> Vec { v.iter().map(|&s| u16::from(s)).collect() }; - let mut worst_y = f64::INFINITY; - let mut worst_uv = f64::INFINITY; - for (a, b) in zc_frames.iter().zip(&cpu_frames) { - let y_db = plane_psnr(&widen(&a.y), &widen(&b.y), 255.0); - let uv_db = plane_psnr( - &[widen(&a.u), widen(&a.v)].concat(), - &[widen(&b.u), widen(&b.v)].concat(), - 255.0, - ); - worst_y = worst_y.min(y_db); - worst_uv = worst_uv.min(uv_db); - } - println!( - "{target:?} encode_frame (P010 via VPP) vs CPU path: worst Y {worst_y:.1} dB, worst UV {worst_uv:.1} dB" - ); - assert!( - worst_y >= 40.0, - "{target:?}: worst Y {worst_y:.1} dB vs the CPU path" - ); - assert!( - worst_uv >= 40.0, - "{target:?}: worst UV {worst_uv:.1} dB vs the CPU path" - ); - - // The size-mismatch route (HEVC: 2160 visible vs 2176 coded) places - // the picture by VPP region rather than encoder cropping alone, so - // confirm the encoder's own SPS conformance window still reports the - // real 3840x2160 — not the padded 2176 the coded surface carries. - let dir = std::env::temp_dir().join(format!("ec-hw-vpp-region-{target:?}")); - std::fs::create_dir_all(&dir).expect("temp dir"); - let path = dir.join(match target { - EncCodec::H264 => "out.264", - EncCodec::H265 => "out.265", - EncCodec::Av1 => "out.obu", - }); - std::fs::write(&path, &zc_stream).expect("write bitstream"); - let probe = Command::new("ffprobe") - .args([ - "-v", - "error", - "-select_streams", - "v:0", - "-show_entries", - "stream=width,height", - "-of", - "csv=p=0", - ]) - .arg(&path) - .output() - .expect("ffprobe runs"); - let dims = String::from_utf8_lossy(&probe.stdout).trim().to_string(); - assert_eq!(dims, format!("{w},{h}"), "{target:?}: ffprobe sees {dims}"); - } -} - -/// Median ms/frame at 3840x2160 for `decode+encode_frame` (P010 zero-copy, -/// through VPP) against `decode+to_i420+encode` (CPU path) — the number that -/// says whether the VPP conversion is cheap enough to keep the zero-copy path -/// meaningfully faster than reading the frame back to system memory. -/// -/// Both H.264 (coded size already matches this film's 2160 visible height, -/// so the P010->NV12 convert is whole-surface) and HEVC (2160 is not a -/// multiple of the 32-block HEVC coded size, so `encode_frame` also takes -/// the VPP region-copy route — `Encoder::vpp_into_pool`) get a bench row. -#[test] -fn p010_zero_copy_encode_is_realtime() { - let Some(display) = display() else { return }; - let path = Path::new(REELD); - if !path.exists() { - eprintln!("skipped: film not present"); - return; - } - let limit = 60usize; - let Some(data) = elementary(path, Codec::H265, limit) else { - eprintln!("skipped: no elementary stream"); - return; - }; - let units = split_access_units(&data, Codec::H265); - assert!( - units.len() > limit, - "film clip too short for {limit} frames" - ); - - println!( - "{:<28} {:>10} {:>10} {:>10}", - "stage", "median ms", "min ms", "max ms" - ); - // (target, zero-copy median ms, CPU-path median ms) rows, filled in order. - let mut rows: Vec<(EncCodec, f64, f64)> = Vec::new(); - let run_target = |target: EncCodec| -> (f64, f64) { - let mut zc_median = None; - let mut cpu_median = None; - for (label, zero_copy) in [ - ("decode+encode_frame", true), - ("decode+to_i420+encode", false), - ] { - let name = format!("{target:?} {label}"); - let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens"); - let mut encoder: Option = None; - let mut durations: Vec = Vec::new(); - let mut count = 0i64; - 'outer: for (i, unit) in units.iter().enumerate() { - decoder.decode(unit, i as i64).expect("decode"); - while let Some(frame) = decoder.next_frame() { - let (w, h) = frame.display_size; - let encoder = encoder.get_or_insert_with(|| { - let mut cfg = EncoderConfig::new(target, w, h); - cfg.gop_size = 30; - cfg.rate_control = RateControlMode::ConstantQp { qp: 22 }; - Encoder::new(&display, cfg).expect("encoder opens") - }); - let meta = FrameMetadata { - timestamp: count, - force_keyframe: false, - }; - let t0 = Instant::now(); - if zero_copy { - encoder.encode_frame(&frame, meta).expect("encode_frame"); - } else { - let i420 = frame.to_i420().expect("readback"); - encoder.encode(&i420, meta).expect("encode"); - } - durations.push(t0.elapsed()); - count += 1; - if durations.len() >= limit { - break 'outer; - } - } - } - assert!( - durations.len() >= limit, - "{name}: only {} of {limit} frames encoded", - durations.len() - ); - durations.sort(); - let ms = |d: Duration| d.as_secs_f64() * 1000.0; - let median = ms(durations[durations.len() / 2]); - let min = ms(durations[0]); - let max = ms(durations[durations.len() - 1]); - println!("{name:<28} {median:>10.2} {min:>10.2} {max:>10.2}"); - if zero_copy { - zc_median = Some(median); - } else { - cpu_median = Some(median); - } - } - ( - zc_median.expect("zero-copy phase ran"), - cpu_median.expect("CPU-path phase ran"), - ) - }; - for target in [EncCodec::H264, EncCodec::H265] { - let (mut zc, mut cpu) = run_target(target); - // A miss within 1.5x of the budget can be another lane's build - // contending for the same CPU/GPU scheduler slice rather than a - // real regression: rerun once and keep the better median. A genuine - // regression is slower on both attempts and still fails below. - if zc > 20.0 && zc < 30.0 { - let (zc2, cpu2) = run_target(target); - if zc2 < zc { - zc = zc2; - cpu = cpu2; - } - } - rows.push((target, zc, cpu)); - } - for (target, zc, cpu) in rows { - println!( - "target: {target:?} decode+encode_frame <= 20.00 ms/frame median; got {zc:.2} (CPU path {cpu:.2})" - ); - assert!( - zc <= 20.0, - "{target:?}: decode+encode_frame median {zc:.2} ms/frame exceeds the 20 ms budget (CPU path: {cpu:.2} ms)" - ); - } -} - /// A CRA GOP boundary stores its RASL leading pictures *after* the CRA in /// decode order, even though they display before it (they predict from /// pictures the CRA's own random-access point does not have). A decoder @@ -2965,11 +2154,8 @@ fn p010_zero_copy_encode_is_realtime() { #[test] fn hevc_seek_matches_linear_mkv() { let Some(display) = display() else { return }; - let path = bitstreams().join("test_hevc.mkv"); - let Some(data) = elementary(&path, Codec::H265, 45) else { - eprintln!("skipped: no test_hevc.mkv fixture"); - return; - }; + let path = ec_testkit::fixture("bitstreams/test_hevc.mkv"); + let data = elementary(&path, Codec::H265, 45).expect("elementary stream"); let units = split_access_units(&data, Codec::H265); // Linear decode: every picture from the start, frame 30 kept for @@ -3038,11 +2224,8 @@ fn hevc_seek_matches_linear_mkv() { #[test] fn h264_seek_matches_linear_open_gop() { let Some(display) = display() else { return }; - let path = bitstreams().join("h264-open-gop.mp4"); - let Some(data) = elementary(&path, Codec::H264, 60) else { - eprintln!("skipped: no h264-open-gop.mp4 fixture (run scripts/gen-fixtures.sh)"); - return; - }; + let path = ec_testkit::fixture("bitstreams/h264-open-gop.mp4"); + let data = elementary(&path, Codec::H264, 60).expect("elementary stream"); let units = split_access_units(&data, Codec::H264); // Linear decode: every picture from the start, frame 30 kept for @@ -3146,7 +2329,7 @@ fn starts_with_cra(au: &[u8]) -> bool { /// `ffmpeg -bsf:v trace_headers` over a bitstream, returning every /// `name = value` line it prints — the slice header fields the driver wrote. fn trace_headers(path: &Path, codec: &str) -> Vec<(String, i64)> { - let out = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args(["-v", "trace", "-hide_banner", "-nostats", "-f", codec, "-i"]) .arg(path) .args(["-c:v", "copy", "-bsf:v", "trace_headers", "-f", "null", "-"]) @@ -3312,7 +2495,7 @@ fn write_y4m_8(path: &Path, frames: &[I420], fps: u32) -> bool { /// Average PSNR (dB) of a raw elementary stream against its source y4m. fn psnr_of_elementary(coded: &Path, format: &str, source: &Path, fps: u32) -> Option { let rate = fps.to_string(); - let out = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args(["-nostdin", "-v", "info", "-f", format, "-r", &rate, "-i"]) .arg(coded) .args(["-r", &rate, "-i"]) @@ -3380,20 +2563,17 @@ fn cbr_lands_within_five_percent_of_the_request() { let synthetic_y4m = dir.join("cbr-synthetic.y4m"); assert!(write_y4m_8(&synthetic_y4m, &synthetic, fps), "write source"); let testsrc_y4m = dir.join("cbr-testsrc2.y4m"); - let generated = Command::new("ffmpeg") + let generated = ec_testkit::ffmpeg() .args(["-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i"]) .arg(format!("testsrc2=size={width}x{height}:rate={fps}")) .args(["-frames:v", &frames.to_string(), "-pix_fmt", "yuv420p"]) .arg(&testsrc_y4m) .status() .is_ok_and(|s| s.success()); - let Some(testsrc) = generated + let testsrc = generated .then(|| raw_frames(&testsrc_y4m, width, height, frames)) .flatten() - else { - eprintln!("skipped: ffmpeg cannot generate testsrc2"); - return; - }; + .expect("ffmpeg generates testsrc2"); let clips: [(&str, Vec, PathBuf); 2] = [ ("moving box", synthetic, synthetic_y4m), ("testsrc2", testsrc, testsrc_y4m), @@ -3639,11 +2819,8 @@ fn a_broken_gop_is_refused_on_every_codec() { (Codec::H265, "hevc-bframes-320.265"), ]; for (codec, name) in cases { - let path = bitstreams().join(name); - let Ok(data) = std::fs::read(&path) else { - eprintln!("skipped {name}: no fixture"); - continue; - }; + let path = ec_testkit::fixture(&format!("bitstreams/{name}")); + let data = std::fs::read(&path).expect("fixture is readable"); let stream = broken_gop(codec, &data).expect("the fixture has a second access unit"); let mut decoder = Decoder::new(&display, codec).expect("decoder"); let refusal = decoder.decode(&stream, 0).err().map(|e| e.to_string()); @@ -3665,11 +2842,9 @@ fn a_broken_gop_is_refused_on_every_codec() { #[test] fn ten_bit_prime_submit_matches_the_cpu_path() { - let Some(file) = std::env::var_os("EC_HEVC10").map(PathBuf::from) else { - return; - }; + let file = ec_testkit::fixture("derived/sintel720-x265-main10.mp4"); let Some(display) = display() else { return }; - let data = std::fs::read(file).expect("fixture is readable"); + let data = elementary(&file, Codec::H265, 1).expect("elementary stream"); let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens"); let mut size = (0, 0); decode_stream(&mut decoder, Codec::H265, &data, 1, |f| { diff --git a/crates/ec-hw/tests/idr_counting.rs b/crates/ec-hw/tests/idr_counting.rs index f0d0de07..1f36bd41 100644 --- a/crates/ec-hw/tests/idr_counting.rs +++ b/crates/ec-hw/tests/idr_counting.rs @@ -9,7 +9,7 @@ //! warnings. use std::path::{Path, PathBuf}; -use std::process::{Command, Stdio}; +use std::process::Stdio; use std::rc::Rc; use ec_hw::{EncCodec, Encoder, EncoderConfig, FrameMetadata, I420, RateControlMode}; @@ -90,7 +90,7 @@ fn encode(codec: EncCodec, frames: u32, gop: u32) -> Option<(Vec, Vec) /// Every slice header field as `(name, value)`, in stream order, from ffmpeg's /// header trace. fn trace_headers(path: &Path, format: &str) -> Vec<(String, i64)> { - let out = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args([ "-nostdin", "-v", @@ -129,7 +129,7 @@ fn values(fields: &[(String, i64)], name: &str) -> Vec { /// Decode with ffmpeg: stderr must be empty at `-v error`, and at `-v debug` no /// line may report a frame_num gap. Returns the decoded planes. fn decode_clean(path: &Path, format: &str, frames: u32) -> Vec { - let quiet = Command::new("ffmpeg") + let quiet = ec_testkit::ffmpeg() .args(["-nostdin", "-v", "error", "-f", format, "-i"]) .arg(path) .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) @@ -147,7 +147,7 @@ fn decode_clean(path: &Path, format: &str, frames: u32) -> Vec { "every picture decodes, in order" ); - let debug = Command::new("ffmpeg") + let debug = ec_testkit::ffmpeg() .args(["-nostdin", "-v", "debug", "-f", format, "-i"]) .arg(path) .args(["-f", "null", "-"]) diff --git a/crates/ec-hw/tests/intra_rate.rs b/crates/ec-hw/tests/intra_rate.rs index 7a48ee64..6990bb7e 100644 --- a/crates/ec-hw/tests/intra_rate.rs +++ b/crates/ec-hw/tests/intra_rate.rs @@ -69,11 +69,9 @@ fn scratch() -> PathBuf { dir } -/// The testsrc2 clip as raw 4:2:0, generated by ffmpeg. `None` when ffmpeg -/// cannot make it, which skips the test rather than failing it. -fn testsrc2_raw(dir: &Path) -> Option { +fn testsrc2_raw(dir: &Path) -> PathBuf { let path = dir.join("testsrc2-720p.yuv"); - let made = Command::new("ffmpeg") + let status = ec_testkit::ffmpeg() .args(["-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i"]) .arg(format!("testsrc2=size={WIDTH}x{HEIGHT}:rate={FPS}")) .args([ @@ -86,8 +84,9 @@ fn testsrc2_raw(dir: &Path) -> Option { ]) .arg(&path) .status() - .ok()?; - made.success().then_some(path) + .expect("run ffmpeg"); + assert!(status.success(), "ffmpeg cannot generate testsrc2"); + path } /// Picture `t` of the raw clip, read from the file at its offset. @@ -241,7 +240,7 @@ fn encode_in_its_own_process( fn psnr(coded: &Path, format: &str, source: &Path) -> Option { let rate = FPS.to_string(); let size = format!("{WIDTH}x{HEIGHT}"); - let out = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args(["-nostdin", "-v", "info", "-f", format, "-r", &rate, "-i"]) .arg(coded) .args([ @@ -264,10 +263,7 @@ fn psnr(coded: &Path, format: &str, source: &Path) -> Option { #[test] fn cbr_lands_within_five_percent_on_intra_only_and_gop_30() { let dir = scratch(); - let Some(source) = testsrc2_raw(&dir) else { - eprintln!("skipped: ffmpeg cannot generate testsrc2"); - return; - }; + let source = testsrc2_raw(&dir); let mut failures = Vec::new(); println!( diff --git a/tools/ec-bench/Cargo.toml b/tools/ec-bench/Cargo.toml index f1cffa3b..af4f2082 100644 --- a/tools/ec-bench/Cargo.toml +++ b/tools/ec-bench/Cargo.toml @@ -32,3 +32,4 @@ ec-flac = { workspace = true } ec-alac = { workspace = true } ec-ac3 = { workspace = true } ec-truehd = { workspace = true } +ec-testkit.workspace = true diff --git a/tools/ec-bench/src/main.rs b/tools/ec-bench/src/main.rs index 5661b050..c9bd9d50 100644 --- a/tools/ec-bench/src/main.rs +++ b/tools/ec-bench/src/main.rs @@ -11,7 +11,6 @@ #![forbid(unsafe_code)] use std::path::{Path, PathBuf}; -use std::process::Command; use std::time::Instant; use ec_av1::encode::Picture as Av1Picture; @@ -81,42 +80,17 @@ fn fixtures() -> PathBuf { Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures") } -fn home() -> PathBuf { - PathBuf::from(std::env::var("HOME").expect("HOME")) -} - -/// A handful of real-library candidates, largest-effort first, that ffprobe -/// confirms carry the wanted video codec. Read-only: never touches the file -/// beyond `ffprobe`/`ffmpeg -i ... -o `. fn real_video(codec: &str) -> Option { - let roots = [home().join("Videos"), home().join("Downloads")]; - let mut found = Vec::new(); - for root in roots { - let Ok(walker) = std::fs::read_dir(&root) else { - continue; - }; - for entry in walker.flatten() { - let p = entry.path(); - let Some(ext) = p.extension().and_then(|e| e.to_str()) else { - continue; - }; - if !matches!( - ext.to_ascii_lowercase().as_str(), - "mp4" | "mkv" | "mov" | "avi" - ) { - continue; - } - found.push(p); - } - } - found.sort(); - found - .into_iter() - .find(|p| ffprobe_field(p, "v:0", "codec_name").as_deref() == Some(codec)) + let name = match codec { + "h264" => "open/sintel_trailer-1080p.mp4", + "hevc" => "derived/sintel720-x265-main10.mp4", + _ => return None, + }; + Some(ec_testkit::fixture(name)) } fn ffprobe_field(path: &Path, stream: &str, key: &str) -> Option { - let out = Command::new("ffprobe") + let out = ec_testkit::ffprobe() .args(["-v", "error", "-select_streams", stream, "-show_entries"]) .arg(format!("stream={key}")) .args(["-of", "default=nw=1:nk=1"]) @@ -148,7 +122,7 @@ fn bench_h264(rows: &mut Vec) { .unwrap_or(0); // decode: 10s Annex-B extract, trimmed inside ffmpeg (never decode-then-trim). - let out = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args(["-v", "error", "-t", "10", "-i"]) .arg(&src) .args([ @@ -230,7 +204,7 @@ fn bench_h264(rows: &mut Vec) { /// `n` progressive frames of raw I420 at `w x h`, scaled and trimmed inside /// ffmpeg. fn extract_yuv420p(src: &Path, w: u32, h: u32, n: u32) -> (Vec, u32, u32, u32) { - let out = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args(["-v", "error", "-i"]) .arg(src) .args([ @@ -475,7 +449,7 @@ fn bench_hw_av1_encode_10bit(rows: &mut Vec) { /// minute in: frame 0 of a film is its black leader, and a black leader codes /// to nothing and benchmarks nothing. fn extract_yuv420p10(src: &Path, w: u32, h: u32, n: u32) -> Vec { - let out = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args(["-v", "error", "-ss", "60", "-i"]) .arg(src) .args([ @@ -638,32 +612,7 @@ fn bench_audio_decode(rows: &mut Vec) { if let Ok(entries) = std::fs::read_dir(fixtures().join("audio")) { candidates.extend(entries.flatten().map(|e| e.path())); } - // Real-library samples: mp3 and wav are on disk; ac3 lives inside the - // ReelT mux (5.1 AC-3), extracted as its own elementary file. - for f in ["8a3b6d1d19.mp3", "test.wav"] { - let p = home().join("Downloads").join(f); - if p.exists() { - candidates.push(p); - } - } - if let Some(src) = real_video("h264") - && ffprobe_field(&src, "a:0", "codec_name").as_deref() == Some("ac3") - { - let out = Command::new("ffmpeg") - .args(["-v", "error", "-t", "10", "-i"]) - .arg(&src) - .args(["-vn", "-c:a", "copy", "-f", "ac3"]) - .arg( - Path::new(&std::env::var("HOME").unwrap()) - .join(".cache/bench-media/sample.ac3"), - ) - .output(); - if let Ok(o) = out - && o.status.success() - { - candidates.push(home().join(".cache/bench-media/sample.ac3")); - } - } + candidates.push(ec_testkit::fixture("open/fate/ac3/monsters_inc_5.1_448_small.ac3")); candidates.sort(); candidates.dedup(); @@ -717,7 +666,7 @@ fn bench_audio_decode(rows: &mut Vec) { /// `seconds` of real interleaved `f32` PCM, decoded through `ec-probe`'s own /// `Reader`/`AudioDecoder` route (the same one `bench_audio_decode` drives). fn real_pcm(seconds: f64) -> Option<(Vec, u32, usize)> { - let path = fixtures().join("audio/wav16-stereo-48000.wav"); + let path = ec_testkit::fixture("audio/wav16-stereo-48000.wav"); let mut reader = Reader::open(&path).ok()?; let stream = reader.default_stream(MediaType::Audio)?.index; let mut dec = reader.make_decoder(stream).ok()?; @@ -1023,7 +972,7 @@ fn bench_truehd(rows: &mut Vec) { /// Container-level duration (`format=duration`), for a mux whose per-stream /// packets carry no duration field of their own (some Matroska tracks don't). fn format_duration(path: &Path) -> Option { - let out = Command::new("ffprobe") + let out = ec_testkit::ffprobe() .args(["-v", "error", "-show_entries", "format=duration"]) .args(["-of", "default=nw=1:nk=1"]) .arg(path) @@ -1038,7 +987,7 @@ fn format_duration(path: &Path) -> Option { fn bench_container_demux(rows: &mut Vec) { for (component, ext) in [("ec-matroska", "mkv"), ("ec-mp4", "mp4")] { - let Some(src) = [fixtures().join("video"), home().join("Videos")] + let Some(src) = [ec_testkit::root().join("open"), ec_testkit::root().join("derived")] .into_iter() .filter_map(|d| std::fs::read_dir(d).ok()) .flatten() @@ -1097,17 +1046,6 @@ fn bench_image_decode(rows: &mut Vec) { .filter(|p| p.extension().is_some()), ); } - for f in [ - "IMG_20260804_170612.jpg", - "drawing-1.png", - "20260722-233942.png", - "giphy.gif", - ] { - let p = home().join("Downloads").join(f); - if p.exists() { - candidates.push(p); - } - } candidates.sort(); for path in candidates { @@ -1139,15 +1077,7 @@ fn bench_image_decode(rows: &mut Vec) { // --------------------------------------------------------------------------- fn bench_inflate(rows: &mut Vec) { - let Some(png) = [ - Path::new(env!("CARGO_MANIFEST_DIR")).join("../../crates/ec-image/tests/data/stills/gray16.png"), - home().join("Downloads/drawing-1.png"), - ] - .into_iter() - .find(|p| p.exists()) else { - rows.push(missing("ec-inflate", "inflate")); - return; - }; + let png = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../crates/ec-image/tests/data/stills/gray16.png"); let Ok(bytes) = std::fs::read(&png) else { rows.push(missing("ec-inflate", "inflate")); return; diff --git a/tools/oracle/Cargo.toml b/tools/oracle/Cargo.toml index 483a9646..b3b8683c 100644 --- a/tools/oracle/Cargo.toml +++ b/tools/oracle/Cargo.toml @@ -13,3 +13,4 @@ path = "src/main.rs" # No dependencies on purpose: the oracle drives ffmpeg/ffprobe through std process # pipes so that comparison tooling can never leak into any ec-* crate's dep graph. [dependencies] +ec-testkit.workspace = true diff --git a/tools/oracle/src/main.rs b/tools/oracle/src/main.rs index b4838383..ad4a7091 100644 --- a/tools/oracle/src/main.rs +++ b/tools/oracle/src/main.rs @@ -18,7 +18,7 @@ #![forbid(unsafe_code)] use std::collections::HashMap; -use std::process::{Command, Stdio}; +use std::process::Stdio; const USAGE: &str = "\ oracle — comparison harness (ffmpeg is test tooling only) @@ -98,7 +98,7 @@ impl Args { /// Decode `input` with ffmpeg and return the raw bytes it writes to stdout. /// stderr is inherited so a large error log can never deadlock the pipe. fn ffmpeg_raw(input: &str, extra: &[&str]) -> Result, String> { - let out = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args(["-nostdin", "-v", "error", "-i", input]) .args(extra) .arg("-") @@ -117,7 +117,7 @@ fn ffmpeg_raw(input: &str, extra: &[&str]) -> Result, String> { /// `ffprobe -show_entries stream=` as a key -> value map (first stream wins). fn ffprobe(input: &str, select: &str, entries: &str) -> Result, String> { - let out = Command::new("ffprobe") + let out = ec_testkit::ffprobe() .args(["-v", "error", "-select_streams", select, "-show_entries"]) .arg(format!("stream={entries}")) .args(["-of", "default=nw=1"]) diff --git a/tools/oracle/tests/cli.rs b/tools/oracle/tests/cli.rs index c11e7599..6eb1fbc7 100644 --- a/tools/oracle/tests/cli.rs +++ b/tools/oracle/tests/cli.rs @@ -2,19 +2,10 @@ //! crate's test will, using ffmpeg as both the "our decoder" stand-in and the //! reference. Exercises the PASS and the FAIL path of every subcommand. //! -//! Fixture-gated: fixtures/ is gitignored, so a checkout without -//! `scripts/gen-fixtures.sh` run skips loudly instead of failing. use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; -fn fixtures() -> PathBuf { - Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../../fixtures") - .canonicalize() - .unwrap_or_else(|_| PathBuf::from("/nonexistent")) -} - // Per-test directory: the test binary runs its cases as threads of one process, // so a pid-only name would let one case delete another's raw files. fn workdir(name: &str) -> PathBuf { @@ -26,7 +17,7 @@ fn workdir(name: &str) -> PathBuf { /// Decode `input` to a raw file with ffmpeg — stands in for "our decoder's output". fn decode_raw(input: &Path, out: &Path, extra: &[&str]) { let f = std::fs::File::create(out).unwrap(); - let st = Command::new("ffmpeg") + let st = ec_testkit::ffmpeg() .args(["-nostdin", "-y", "-v", "error", "-i"]) .arg(input) .args(extra) @@ -46,29 +37,12 @@ fn oracle(args: &[&str]) -> i32 { .expect("oracle exited by signal") } -fn require(paths: &[PathBuf]) -> bool { - for p in paths { - if !p.is_file() { - eprintln!( - "SKIP: missing fixture {} — run scripts/gen-fixtures.sh", - p.display() - ); - return false; - } - } - true -} - const F32: &[&str] = &["-map", "0:a:0", "-f", "f32le", "-acodec", "pcm_f32le"]; #[test] fn bit_exact_passes_on_same_decode_and_fails_on_a_different_one() { - let fx = fixtures(); - let a = fx.join("audio/flac-stereo-48000.flac"); - let b = fx.join("audio/flac-mono-48000.flac"); - if !require(&[a.clone(), b.clone()]) { - return; - } + let a = ec_testkit::fixture("audio/flac-stereo-48000.flac"); + let b = ec_testkit::fixture("audio/flac-mono-48000.flac"); let w = workdir("bitexact"); let (r1, r2, r3) = (w.join("a1.raw"), w.join("a2.raw"), w.join("b.raw")); decode_raw(&a, &r1, F32); @@ -90,12 +64,8 @@ fn bit_exact_passes_on_same_decode_and_fails_on_a_different_one() { #[test] fn audio_compare_passes_against_its_own_source_and_fails_across_rates() { - let fx = fixtures(); - let a = fx.join("audio/flac-stereo-48000.flac"); - let b = fx.join("audio/flac-stereo-44100.flac"); - if !require(&[a.clone(), b.clone()]) { - return; - } + let a = ec_testkit::fixture("audio/flac-stereo-48000.flac"); + let b = ec_testkit::fixture("audio/flac-stereo-44100.flac"); let w = workdir("audio"); let (ra, rb) = (w.join("a.raw"), w.join("b.raw")); decode_raw(&a, &ra, F32); @@ -117,12 +87,8 @@ fn audio_compare_passes_against_its_own_source_and_fails_across_rates() { #[test] fn video_compare_passes_against_its_own_source_and_fails_on_frame_count() { - let fx = fixtures(); - let a = fx.join("video/h264-1080p-23.976-8bit.mp4"); - let b = fx.join("video/h264-1080p-60-8bit.mp4"); - if !require(&[a.clone(), b.clone()]) { - return; - } + let a = ec_testkit::fixture("video/h264-1080p-23.976-8bit.mp4"); + let b = ec_testkit::fixture("video/h264-1080p-60-8bit.mp4"); let w = workdir("video"); let raw = w.join("a.raw"); decode_raw(