diff --git a/Cargo.lock b/Cargo.lock index cc823cef..fe04af07 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -374,6 +374,7 @@ dependencies = [ "bytemuck", "ec-av1-syntax", "ec-core", + "ec-testkit", "stats_alloc", "tracking-allocator", ] diff --git a/crates/ec-av1/Cargo.toml b/crates/ec-av1/Cargo.toml index e7237bbc..21a37242 100644 --- a/crates/ec-av1/Cargo.toml +++ b/crates/ec-av1/Cargo.toml @@ -21,6 +21,7 @@ default = ["gate-counters"] gate-counters = [] [dev-dependencies] +ec-testkit.workspace = true # `nightly` only makes StatsAlloc::new const, so it can be a #[global_allocator] static. stats_alloc = { version = "0.1.10", features = ["nightly"] } tracking-allocator = "0.4.0" diff --git a/crates/ec-av1/src/decode/tests.rs b/crates/ec-av1/src/decode/tests.rs index 1323f055..f937af8b 100644 --- a/crates/ec-av1/src/decode/tests.rs +++ b/crates/ec-av1/src/decode/tests.rs @@ -3011,36 +3011,13 @@ fn a_non_split_inter_sb_partition_refuses_by_name_instead_of_desyncing() { // name (that module is another lane's territory this round, and the // helpers are `#[cfg(test)]`-private to it). use crate::probe::run_with_stdin; -use std::process::{Command, Stdio}; - -/// Whether ffmpeg is on PATH. Absence normally SKIPs, but -/// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every -/// aomenc gate decodes its stream through ffmpeg and is meaningless -/// without it -- turns it into a hard failure. Without this the require -/// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first -/// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg -/// printed SKIP and reported green (class gate-skips-on-its-own-failure). -fn have_ffmpeg() -> bool { - let present = Command::new("ffmpeg") - .arg("-version") - .stdout(Stdio::null()) - .stderr(Stdio::null()) - .status() - .is_ok_and(|s| s.success()); - assert!( - present - || (!crate::envflags::env_flag!("EC_AV1_REQUIRE_FFMPEG") - && !crate::envflags::env_flag!("EC_AV1_REQUIRE_AOMENC")), - "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH" - ); - present -} + /// Decodes one AV1 OBU stream with ffmpeg and hands back its one 4:2:0 /// frame's planes, at ffmpeg's own (coded, block-padded) size. fn ffmpeg_decode(stream: &[u8], width: usize, height: usize) -> Picture { let out = run_with_stdin( - Command::new("ffmpeg").args([ + ec_testkit::ffmpeg().args([ "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-", ]), stream, @@ -3079,7 +3056,7 @@ fn ffmpeg_decode_sequence( frames: usize, ) -> Vec { let out = run_with_stdin( - Command::new("ffmpeg").args([ + ec_testkit::ffmpeg().args([ "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-", ]), stream, @@ -3134,7 +3111,7 @@ fn ffprobe_size(stream: &[u8]) -> (u32, u32) { )); let _ = std::fs::remove_file(&path); std::fs::write(&path, stream).expect("writing the probe stream"); - let out = Command::new("ffprobe") + let out = ec_testkit::ffprobe() .args([ "-v", "error", @@ -3169,10 +3146,6 @@ fn ffprobe_size(stream: &[u8]) -> (u32, u32) { #[test] fn ffmpeg_and_this_decoder_agree_on_a_key_frame() { let fctx = &crate::decode::FrameCtx::for_encoder(); // lane-b128: this test ENCODES, so its decode context starts at the superblock size this process encodes at (stale-header class, as `filter_intra_on` below) - if !have_ffmpeg() { - eprintln!("SKIP ffmpeg_and_this_decoder_agree_on_a_key_frame: no ffmpeg"); - return; - } use crate::encode::encode_key_frame_with_ctx; for &(width, height) in &[(64usize, 64usize), (216, 96), (40, 32)] { let picture = round_trip_test_card(width, height); @@ -3217,14 +3190,6 @@ fn ffmpeg_and_this_decoder_agree_on_a_key_frame() { #[test] fn a_filter_intra_key_frame_decodes_pixel_exact_through_ffmpeg() { let fctx = &crate::decode::FrameCtx::for_encoder(); // lane-b128: this test ENCODES, so its decode context starts at the superblock size this process encodes at (stale-header class, as `filter_intra_on` below) - if !crate::encode::filter_intra_on() { - eprintln!("SKIP a_filter_intra_key_frame...: EC_AV1_FILTER_INTRA=0"); - return; - } - if !have_ffmpeg() { - eprintln!("SKIP a_filter_intra_key_frame...: no ffmpeg"); - return; - } let (width, height) = (128usize, 128usize); // Smooth, slowly curving content: what the recursive filter modes are // for, and what a plain directional prediction leaves residual on. @@ -3747,10 +3712,6 @@ fn a_nearmv_block_predicts_from_the_stacks_second_candidate() { #[test] fn ffmpeg_and_this_decoder_agree_on_a_gop() { let fctx = &crate::decode::FrameCtx::for_encoder(); // lane-b128: this test ENCODES, so its decode context starts at the superblock size this process encodes at (stale-header class, as `filter_intra_on` below) - if !have_ffmpeg() { - eprintln!("SKIP ffmpeg_and_this_decoder_agree_on_a_gop: no ffmpeg"); - return; - } use crate::encode::encode_sequence_with_ctx; let (width, height) = (128usize, 64usize); let pictures: Vec<_> = (0..3) diff --git a/crates/ec-av1/src/encode/more_tests.rs b/crates/ec-av1/src/encode/more_tests.rs index dc2f2584..82f00078 100644 --- a/crates/ec-av1/src/encode/more_tests.rs +++ b/crates/ec-av1/src/encode/more_tests.rs @@ -1,7 +1,6 @@ use super::*; use super::tests::*; -use crate::intra::{D45_PRED, NON_DIRECTIONAL}; -use std::process::Command; + /// lane-ab128: the 128 root's four AB shapes -- `PARTITION_HORZ_A` (two @@ -23,15 +22,11 @@ use std::process::Command; /// Runs only inside `superblock_size_global_suite`. pub(super) fn a_128_root_ab_shapes_decode_exact_through_both_decoders() { let _knobs = crate::speed::knob_write(); - if !have_ffmpeg() { - eprintln!("SKIP: no ffmpeg"); - return; - } force_sb128(true); let dir = std::env::temp_dir().join(format!("ec-av1-ab128-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let clip = dir.join("testsrc2-1280x768.y4m"); - let ok = Command::new("ffmpeg") + let ok = ec_testkit::ffmpeg() .args(["-v", "error", "-y", "-f", "lavfi"]) .args(["-i", "testsrc2=size=1280x768:rate=24"]) .args(["-frames:v", "12", "-pix_fmt", "yuv420p"]) @@ -331,94 +326,6 @@ use std::process::Command; assert!(written_all > 0.0); } - /// Step (2) of the pricer lane: the same census, but on the REAL clips - /// the BD gate scores -- one film clip and the screen capture -- so the - /// question the film/screen split raises can be answered from data. Real - /// tables (`EC_AV1_PRICE_FRAME_CDFS=1`) make both film clips smaller and - /// the screen capture larger, and the census says why: on a screen - /// capture the frame's own starting tables are the tables of a frame that - /// coded PALETTE and long runs of zero blocks, so they are far from the - /// tables the writer ends the frame with; the pricer error does not fall - /// the way it does on film. - /// - /// Not a gate -- it prints. Run it once per mode: - /// EC_AV1_PRICE_FRAME_CDFS=0 cargo test -p ec-av1 --release --lib -- \ - /// --ignored pricer_error_census_on_clips --nocapture - #[test] - #[ignore = "reads the real library, needs ffmpeg"] - fn pricer_error_census_on_clips() { - let _knobs = crate::speed::knob_write(); - if !have_ffmpeg() { - eprintln!("SKIP pricer_error_census_on_clips: no ffmpeg"); - return; - } - // lane-av1clipprobe: the crate's one fixture root (EC_FIXTURES first), - // so this probe reads the same tree the preflight validates. Its - // `assert!(!clips.is_empty())` below was already a hard failure, so no - // skip shape changes here — only the root does. - let fixtures = crate::library_fixture::root(); - let mut clips: Vec<(String, std::path::PathBuf)> = Vec::new(); - let film = fixtures.join("video/h264-1080p-23.976-8bit.mp4"); - if film.exists() { - clips.push(("film 1080p".to_string(), film)); - } - if let Ok(manifest) = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv")) - && let Some(p) = manifest - .lines() - .skip(1) - .filter_map(|l| l.split('\t').next()) - .find(|p| { - p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists() - }) - { - clips.push(("screen".to_string(), std::path::PathBuf::from(p))); - } - assert!(!clips.is_empty(), "no source clip available"); - let (width, height, frames) = (640usize, 384usize, 6usize); - for (name, path) in &clips { - let fctx = &crate::decode::FrameCtx::for_encoder(); - let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames); - SCREEN_FRAMES.iter().for_each(|c| { - c.store(0, std::sync::atomic::Ordering::Relaxed); - }); - let _ = crate::tile::take_pricing_hits(); - crate::tile::pricer_census_on(); - let _ = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap(); - let rows = crate::tile::take_pricer_census(); - let (price_default, price_real) = crate::tile::take_pricing_hits(); - let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed); - println!( - "\n## {name} ({frames} frames at {width}x{height}, q=100): screen frames \ - {screen_on}, pricer armings default={price_default} real={price_real}" - ); - println!("| set | nz | blocks | priced bits | written bits | error |"); - println!("|---|---|---|---|---|---|"); - let (mut priced_all, mut written_all) = (0.0, 0.0); - for ((set, bucket), (blocks, priced, written)) in &rows { - priced_all += priced; - written_all += written; - println!( - "| {set} | {} | {blocks} | {priced:.0} | {written:.0} | {:+.1}% |", - crate::tile::census_bucket_label(*bucket), - if *written > 0.0 { - (priced - written) / written * 100.0 - } else { - 0.0 - } - ); - } - println!( - "| ALL | | {} | {priced_all:.0} | {written_all:.0} | {:+.1}% |", - rows.values().map(|r| r.0).sum::(), - (priced_all - written_all) / written_all * 100.0 - ); - assert!( - written_all > 0.0, - "{name}: the census saw no transform block" - ); - } - } - /// Low motion has to actually buy something: at least one inter frame of /// a panning sequence has to cost fewer bytes than the key frame that /// starts it, and the inter-block share it prints has to be non-zero -- @@ -459,446 +366,6 @@ use std::process::Command; ); } - /// A manual perf probe, not a gate: prints where a key frame's and an - /// inter frame's time goes, coarse stage by coarse stage, so a perf lane - /// measures before it optimizes rather than guessing. Run with - /// `cargo test -p ec-av1 --release stage_timing_breakdown -- --ignored --nocapture`. - #[test] - #[ignore = "a perf probe, not a gate"] - fn stage_timing_breakdown() { - let _knobs = crate::speed::knob_read(); - let fctx = &crate::decode::FrameCtx::for_encoder(); - use std::time::Instant; - - for &(width, height) in &[(1920usize, 1080usize), (3840, 2160)] { - let picture = test_card(width, height); - - let t = Instant::now(); - let dc_only = - encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[DC_PRED], fctx).unwrap(); - let dc_only_t = t.elapsed(); - - let t = Instant::now(); - let non_directional = - encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &NON_DIRECTIONAL, fctx) - .unwrap(); - let non_directional_t = t.elapsed(); - - let t = Instant::now(); - let all_modes = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); - let all_modes_t = t.elapsed(); - - eprintln!( - "\n=== key frame {width}x{height} ===\n\ - 1 mode (DC only): {dc_only_t:>9.2?} ({} bytes)\n\ - 7 modes (non-directional): {non_directional_t:>9.2?} ({} bytes)\n\ - 13 modes (default search): {all_modes_t:>9.2?} ({} bytes)", - dc_only.stream.len(), - non_directional.stream.len(), - all_modes.stream.len(), - ); - - // One inter frame predicting off the key frame's own - // reconstruction, the (256, 256)-padded surface encode_sequence - // itself would hand encode_inter_frame. - let padded_ref = all_modes.reconstruction.padded_to(SUPERBLOCK); - let padded_pic = picture.padded_to(SUPERBLOCK); - let t = Instant::now(); - let inter = encode_inter_frame( - &padded_pic, - &padded_ref, - 100, - 0.5, - 1, - flat_order_hints(1, 0, false), - (width, height), - None, - None, - None, - None, - fctx, - None, - &[], - ) - .unwrap(); - let inter_t = t.elapsed(); - eprintln!( - "inter frame vs its own key frame: {inter_t:>9.2?} ({} bytes, inter share \ - {:.2})", - inter.stream.len(), - inter.inter_block_share - ); - } - - // Isolated per-call cost of the trial pipeline's own stages, at both - // transform sizes the search runs, averaged over enough calls to - // rise above `Instant::now`'s own noise. - for side in [16usize, 32] { - const N: u32 = 20_000; - let residual: Vec = (0..side * side) - .map(|i| ((i * 37 % 61) as i32) - 30) - .collect(); - - let t = Instant::now(); - let mut levels = Vec::new(); - for _ in 0..N { - levels = forward_and_quantize(&residual, side, 8, 100, 0.5); - } - let forward_t = t.elapsed() / N; - - let t = Instant::now(); - for _ in 0..N { - std::hint::black_box(crate::transform::dequant_and_inverse(&levels, side, 8, 100)); - } - let inverse_t = t.elapsed() / N; - - let set = if side == 32 { - crate::cdf_state::TxbSet::Luma32 - } else { - crate::cdf_state::TxbSet::Luma16 - }; - let t = Instant::now(); - for _ in 0..N { - std::hint::black_box(crate::tile::coeff_bits(&levels, set, 2, 0, 0)); - } - let entropy_t = t.elapsed() / N; - - let above = vec![128u8; side * 2]; - let left = vec![128u8; side * 2]; - let mut prediction = vec![0u8; side * side]; - let t = Instant::now(); - for _ in 0..N { - intra_predict_u8( - D45_PRED, - 0, - Some(&above), - Some(&left), - Some(128), - side, - side, - false, - false, - &mut prediction, - fctx, - ); - } - let predict_t = t.elapsed() / N; - - eprintln!( - "\n=== per-call cost at {side}x{side}, averaged over {N} calls ===\n\ - predict (1 directional mode): {predict_t:>9.2?}\n\ - forward_and_quantize: {forward_t:>9.2?}\n\ - dequant_and_inverse: {inverse_t:>9.2?}\n\ - coeff_bits: {entropy_t:>9.2?}" - ); - } - } - - /// Breaks one inter frame's own cost into the four [`STAGE_NS`] buckets - /// plus what is left over once buckets 0/2/3 are subtracted. - /// - /// lane-av1probes: the two search-shaped buckets OVERLAP and the old - /// print denied it. Bucket 0 is not "the motion search": `stage_since(0, - /// ..)` fires only after `find_best_new_mv` and the global-MV search - /// (`encode.rs:11959`, `:12080`), so it is the NEWMV/GLOBAL sub-search - /// alone. Bucket 1 is EVERY `crate::mc::predict` call, from the search's - /// candidates *and* from a committed inter block's final prediction -- - /// and that final prediction runs OUTSIDE any bucket-0 region. So bucket 1 - /// is neither inside bucket 0 nor smaller than it, and a print that shows - /// it as "motion search (of which interpolation ...)" necessarily shows - /// a sub-number bigger than its parent. Measured: bucket 0 = 17.82 ms, - /// bucket 1 = 148.63 ms. - /// - /// Which number is real: BOTH timers are right; only the old ARITHMETIC - /// was wrong. Bucket 1 is now printed as its own top-level row, the - /// overlap is stated, and the residual is labelled for what it is -- it - /// absorbs the committed block's own interpolation, so it is not a pure - /// "13-mode intra candidate loop" figure either. - /// - /// `cargo test -p ec-av1 --release stage_timing_breakdown_inter -- --ignored --nocapture`. - #[test] - #[ignore = "a perf probe, not a gate"] - fn stage_timing_breakdown_inter() { - let _knobs = crate::speed::knob_read(); - let fctx = &crate::decode::FrameCtx::for_encoder(); - use std::time::Instant; - - let (width, height) = (1280usize, 720); - let picture = test_card(width, height); - let key = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); - let padded_ref = key.reconstruction.padded_to(SUPERBLOCK); - let padded_pic = picture.padded_to(SUPERBLOCK); - - stage_reset(); - let t = Instant::now(); - let inter = encode_inter_frame( - &padded_pic, - &padded_ref, - 100, - 0.5, - 1, - flat_order_hints(1, 0, false), - (width, height), - None, - None, - None, - None, - fctx, - None, - &[], - ) - .unwrap(); - let total_t = t.elapsed(); - let [motion_search, interpolation, transform_quant, entropy] = stage_read(); - // Buckets 0 and 2 and 3 are disjoint and additive. Bucket 1 (every - // `mc::predict` call) is NOT added: it overlaps bucket 0 wherever a - // search candidate calls predict, and it also covers the committed - // block's final prediction, which no other bucket times. Adding it - // would double-count the overlap; leaving it out puts the committed - // prediction (and the intra candidate loop, RD glue, and the symbol - // lookups outside `coeff_bits`) into the residual, which is what the - // residual has always been. - let accounted = motion_search + transform_quant + entropy; - let other = total_t.saturating_sub(accounted); - let overlap = interpolation.saturating_sub(motion_search); - - eprintln!( - "\n=== inter frame {width}x{height}, one frame ===\n\ - total: {total_t:>9.2?} ({} bytes)\n\ - NEWMV/GLOBAL sub-search (bucket 0): {motion_search:>9.2?}\n\ - transform + quantize (bucket 2): {transform_quant:>9.2?}\n\ - coeff_bits, entropy pricing (bucket 3): {entropy:>9.2?}\n\ - buckets 0+2+3 accounted: {accounted:>9.2?}\n\ - \n\ - OVERLAPPING, not additive: every mc::predict call (bucket 1) {interpolation:>9.2?}\n\ - \x20 -- of which {overlap:>9.2?} is OUTSIDE bucket 0 (a committed\n\ - \x20 inter block's final prediction, which no bucket above times)\n\ - \x20 and the rest is the search candidates' interpolation, already\n\ - \x20 inside bucket 0. It is deliberately NOT added to the total.\n\ - \n\ - residual (13-mode intra candidate loop, the committed block's\n\ - \x20 interpolation above, NEARESTMV's own predict, RD glue): {other:>9.2?}", - inter.stream.len(), - ); - } - - /// The quality gate [`Search::top_k`]'s lever lives or dies by: three real - /// frames (a dark/flat one, a detailed one, a normal film one) at two - /// `base_q_idx` values, encoded with the mode search unpruned (`top_k = - /// None`, the baseline this same build produces without - /// `EC_AV1_PRUNE_K` set) and with it pruned to each of a few `K`, bytes - /// and luma PSNR compared side by side. Not a gate itself -- the numbers - /// go in the lane report, which is where "ship as default" is decided -- - /// so it stays `#[ignore]`, run by hand with real clips on this machine. - /// `cargo test -p ec-av1 --release prune_k_quality_sweep -- --ignored --nocapture`. - #[test] - // The three clip paths are HARD-CODED ABSOLUTES under /home/user, not - // env-driven: off this workstation every row prints `SKIP