forge
Explore
Log in

Don't you dare go Hollow

ec-av1 tests: migrate to ec_testkit (ffmpeg/ffprobe, fixtures), drop have_ffmpeg/library_fixture skip helpers and manifest/real-library probes, aomdec-free conformance reads fixtures/vectors/av1-aom

Browse files at this commit

6f9d280422866699d62f457620de25a533136d56Ahmet Kaan GümüşParent: ed03c2f
Cargo.lockmodified+1 -0
@@ -374,6 +374,7 @@ dependencies = [
374 "bytemuck",374 "bytemuck",
375 "ec-av1-syntax",375 "ec-av1-syntax",
376 "ec-core",376 "ec-core",
377+ "ec-testkit",
377 "stats_alloc",378 "stats_alloc",
378 "tracking-allocator",379 "tracking-allocator",
379 ]380 ]
crates/ec-av1/Cargo.tomlmodified+1 -0
@@ -21,6 +21,7 @@ default = ["gate-counters"]
21 gate-counters = []21 gate-counters = []
22 22
23 [dev-dependencies]23 [dev-dependencies]
24+ec-testkit.workspace = true
24 # `nightly` only makes StatsAlloc::new const, so it can be a #[global_allocator] static.25 # `nightly` only makes StatsAlloc::new const, so it can be a #[global_allocator] static.
25 stats_alloc = { version = "0.1.10", features = ["nightly"] }26 stats_alloc = { version = "0.1.10", features = ["nightly"] }
26 tracking-allocator = "0.4.0"27 tracking-allocator = "0.4.0"
crates/ec-av1/src/decode/tests.rsmodified+4 -43
@@ -3011,36 +3011,13 @@ fn a_non_split_inter_sb_partition_refuses_by_name_instead_of_desyncing() {
3011 // name (that module is another lane's territory this round, and the3011 // name (that module is another lane's territory this round, and the
3012 // helpers are `#[cfg(test)]`-private to it).3012 // helpers are `#[cfg(test)]`-private to it).
3013 use crate::probe::run_with_stdin;3013 use crate::probe::run_with_stdin;
3014-use std::process::{Command, Stdio};3014+
3015-
3016-/// Whether ffmpeg is on PATH. Absence normally SKIPs, but
3017-/// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every
3018-/// aomenc gate decodes its stream through ffmpeg and is meaningless
3019-/// without it -- turns it into a hard failure. Without this the require
3020-/// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first
3021-/// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg
3022-/// printed SKIP and reported green (class gate-skips-on-its-own-failure).
3023-fn have_ffmpeg() -> bool {
3024- let present = Command::new("ffmpeg")
3025- .arg("-version")
3026- .stdout(Stdio::null())
3027- .stderr(Stdio::null())
3028- .status()
3029- .is_ok_and(|s| s.success());
3030- assert!(
3031- present
3032- || (!crate::envflags::env_flag!("EC_AV1_REQUIRE_FFMPEG")
3033- && !crate::envflags::env_flag!("EC_AV1_REQUIRE_AOMENC")),
3034- "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH"
3035- );
3036- present
3037-}
3038 3015
3039 /// Decodes one AV1 OBU stream with ffmpeg and hands back its one 4:2:03016 /// Decodes one AV1 OBU stream with ffmpeg and hands back its one 4:2:0
3040 /// frame's planes, at ffmpeg's own (coded, block-padded) size.3017 /// frame's planes, at ffmpeg's own (coded, block-padded) size.
3041 fn ffmpeg_decode(stream: &[u8], width: usize, height: usize) -> Picture {3018 fn ffmpeg_decode(stream: &[u8], width: usize, height: usize) -> Picture {
3042 let out = run_with_stdin(3019 let out = run_with_stdin(
3043- Command::new("ffmpeg").args([3020+ ec_testkit::ffmpeg().args([
3044 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",3021 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
3045 ]),3022 ]),
3046 stream,3023 stream,
@@ -3079,7 +3056,7 @@ fn ffmpeg_decode_sequence(
3079 frames: usize,3056 frames: usize,
3080 ) -> Vec<Picture> {3057 ) -> Vec<Picture> {
3081 let out = run_with_stdin(3058 let out = run_with_stdin(
3082- Command::new("ffmpeg").args([3059+ ec_testkit::ffmpeg().args([
3083 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",3060 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
3084 ]),3061 ]),
3085 stream,3062 stream,
@@ -3134,7 +3111,7 @@ fn ffprobe_size(stream: &[u8]) -> (u32, u32) {
3134 ));3111 ));
3135 let _ = std::fs::remove_file(&path);3112 let _ = std::fs::remove_file(&path);
3136 std::fs::write(&path, stream).expect("writing the probe stream");3113 std::fs::write(&path, stream).expect("writing the probe stream");
3137- let out = Command::new("ffprobe")3114+ let out = ec_testkit::ffprobe()
3138 .args([3115 .args([
3139 "-v",3116 "-v",
3140 "error",3117 "error",
@@ -3169,10 +3146,6 @@ fn ffprobe_size(stream: &[u8]) -> (u32, u32) {
3169 #[test]3146 #[test]
3170 fn ffmpeg_and_this_decoder_agree_on_a_key_frame() {3147 fn ffmpeg_and_this_decoder_agree_on_a_key_frame() {
3171 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)3148 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)
3172- if !have_ffmpeg() {
3173- eprintln!("SKIP ffmpeg_and_this_decoder_agree_on_a_key_frame: no ffmpeg");
3174- return;
3175- }
3176 use crate::encode::encode_key_frame_with_ctx;3149 use crate::encode::encode_key_frame_with_ctx;
3177 for &(width, height) in &[(64usize, 64usize), (216, 96), (40, 32)] {3150 for &(width, height) in &[(64usize, 64usize), (216, 96), (40, 32)] {
3178 let picture = round_trip_test_card(width, height);3151 let picture = round_trip_test_card(width, height);
@@ -3217,14 +3190,6 @@ fn ffmpeg_and_this_decoder_agree_on_a_key_frame() {
3217 #[test]3190 #[test]
3218 fn a_filter_intra_key_frame_decodes_pixel_exact_through_ffmpeg() {3191 fn a_filter_intra_key_frame_decodes_pixel_exact_through_ffmpeg() {
3219 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)3192 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)
3220- if !crate::encode::filter_intra_on() {
3221- eprintln!("SKIP a_filter_intra_key_frame...: EC_AV1_FILTER_INTRA=0");
3222- return;
3223- }
3224- if !have_ffmpeg() {
3225- eprintln!("SKIP a_filter_intra_key_frame...: no ffmpeg");
3226- return;
3227- }
3228 let (width, height) = (128usize, 128usize);3193 let (width, height) = (128usize, 128usize);
3229 // Smooth, slowly curving content: what the recursive filter modes are3194 // Smooth, slowly curving content: what the recursive filter modes are
3230 // for, and what a plain directional prediction leaves residual on.3195 // for, and what a plain directional prediction leaves residual on.
@@ -3747,10 +3712,6 @@ fn a_nearmv_block_predicts_from_the_stacks_second_candidate() {
3747 #[test]3712 #[test]
3748 fn ffmpeg_and_this_decoder_agree_on_a_gop() {3713 fn ffmpeg_and_this_decoder_agree_on_a_gop() {
3749 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)3714 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)
3750- if !have_ffmpeg() {
3751- eprintln!("SKIP ffmpeg_and_this_decoder_agree_on_a_gop: no ffmpeg");
3752- return;
3753- }
3754 use crate::encode::encode_sequence_with_ctx;3715 use crate::encode::encode_sequence_with_ctx;
3755 let (width, height) = (128usize, 64usize);3716 let (width, height) = (128usize, 64usize);
3756 let pictures: Vec<_> = (0..3)3717 let pictures: Vec<_> = (0..3)
crates/ec-av1/src/encode/more_tests.rsmodified+5 -2674

Diff too large; view file

@@ -1,7 +1,6 @@
1 use super::*;1 use super::*;
2 use super::tests::*;2 use super::tests::*;
3-use crate::intra::{D45_PRED, NON_DIRECTIONAL};3+
4-use std::process::Command;
5 4
6 5
7 /// lane-ab128: the 128 root's four AB shapes -- `PARTITION_HORZ_A` (two6 /// lane-ab128: the 128 root's four AB shapes -- `PARTITION_HORZ_A` (two
@@ -23,15 +22,11 @@ use std::process::Command;
23 /// Runs only inside `superblock_size_global_suite`.22 /// Runs only inside `superblock_size_global_suite`.
24 pub(super) fn a_128_root_ab_shapes_decode_exact_through_both_decoders() {23 pub(super) fn a_128_root_ab_shapes_decode_exact_through_both_decoders() {
25 let _knobs = crate::speed::knob_write();24 let _knobs = crate::speed::knob_write();
26- if !have_ffmpeg() {
27- eprintln!("SKIP: no ffmpeg");
28- return;
29- }
30 force_sb128(true);25 force_sb128(true);
31 let dir = std::env::temp_dir().join(format!("ec-av1-ab128-{}", std::process::id()));26 let dir = std::env::temp_dir().join(format!("ec-av1-ab128-{}", std::process::id()));
32 std::fs::create_dir_all(&dir).unwrap();27 std::fs::create_dir_all(&dir).unwrap();
33 let clip = dir.join("testsrc2-1280x768.y4m");28 let clip = dir.join("testsrc2-1280x768.y4m");
34- let ok = Command::new("ffmpeg")29+ let ok = ec_testkit::ffmpeg()
35 .args(["-v", "error", "-y", "-f", "lavfi"])30 .args(["-v", "error", "-y", "-f", "lavfi"])
36 .args(["-i", "testsrc2=size=1280x768:rate=24"])31 .args(["-i", "testsrc2=size=1280x768:rate=24"])
37 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])32 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
@@ -331,94 +326,6 @@ use std::process::Command;
331 assert!(written_all > 0.0);326 assert!(written_all > 0.0);
332 }327 }
333 328
334- /// Step (2) of the pricer lane: the same census, but on the REAL clips
335- /// the BD gate scores -- one film clip and the screen capture -- so the
336- /// question the film/screen split raises can be answered from data. Real
337- /// tables (`EC_AV1_PRICE_FRAME_CDFS=1`) make both film clips smaller and
338- /// the screen capture larger, and the census says why: on a screen
339- /// capture the frame's own starting tables are the tables of a frame that
340- /// coded PALETTE and long runs of zero blocks, so they are far from the
341- /// tables the writer ends the frame with; the pricer error does not fall
342- /// the way it does on film.
343- ///
344- /// Not a gate -- it prints. Run it once per mode:
345- /// EC_AV1_PRICE_FRAME_CDFS=0 cargo test -p ec-av1 --release --lib -- \
346- /// --ignored pricer_error_census_on_clips --nocapture
347- #[test]
348- #[ignore = "reads the real library, needs ffmpeg"]
349- fn pricer_error_census_on_clips() {
350- let _knobs = crate::speed::knob_write();
351- if !have_ffmpeg() {
352- eprintln!("SKIP pricer_error_census_on_clips: no ffmpeg");
353- return;
354- }
355- // lane-av1clipprobe: the crate's one fixture root (EC_FIXTURES first),
356- // so this probe reads the same tree the preflight validates. Its
357- // `assert!(!clips.is_empty())` below was already a hard failure, so no
358- // skip shape changes here — only the root does.
359- let fixtures = crate::library_fixture::root();
360- let mut clips: Vec<(String, std::path::PathBuf)> = Vec::new();
361- let film = fixtures.join("video/h264-1080p-23.976-8bit.mp4");
362- if film.exists() {
363- clips.push(("film 1080p".to_string(), film));
364- }
365- if let Ok(manifest) = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv"))
366- && let Some(p) = manifest
367- .lines()
368- .skip(1)
369- .filter_map(|l| l.split('\t').next())
370- .find(|p| {
371- p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists()
372- })
373- {
374- clips.push(("screen".to_string(), std::path::PathBuf::from(p)));
375- }
376- assert!(!clips.is_empty(), "no source clip available");
377- let (width, height, frames) = (640usize, 384usize, 6usize);
378- for (name, path) in &clips {
379- let fctx = &crate::decode::FrameCtx::for_encoder();
380- let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames);
381- SCREEN_FRAMES.iter().for_each(|c| {
382- c.store(0, std::sync::atomic::Ordering::Relaxed);
383- });
384- let _ = crate::tile::take_pricing_hits();
385- crate::tile::pricer_census_on();
386- let _ = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap();
387- let rows = crate::tile::take_pricer_census();
388- let (price_default, price_real) = crate::tile::take_pricing_hits();
389- let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed);
390- println!(
391- "\n## {name} ({frames} frames at {width}x{height}, q=100): screen frames \
392- {screen_on}, pricer armings default={price_default} real={price_real}"
393- );
394- println!("| set | nz | blocks | priced bits | written bits | error |");
395- println!("|---|---|---|---|---|---|");
396- let (mut priced_all, mut written_all) = (0.0, 0.0);
397- for ((set, bucket), (blocks, priced, written)) in &rows {
398- priced_all += priced;
399- written_all += written;
400- println!(
401- "| {set} | {} | {blocks} | {priced:.0} | {written:.0} | {:+.1}% |",
402- crate::tile::census_bucket_label(*bucket),
403- if *written > 0.0 {
404- (priced - written) / written * 100.0
405- } else {
406- 0.0
407- }
408- );
409- }
410- println!(
411- "| ALL | | {} | {priced_all:.0} | {written_all:.0} | {:+.1}% |",
412- rows.values().map(|r| r.0).sum::<u64>(),
413- (priced_all - written_all) / written_all * 100.0
414- );
415- assert!(
416- written_all > 0.0,
417- "{name}: the census saw no transform block"
418- );
419- }
420- }
421-
422 /// Low motion has to actually buy something: at least one inter frame of329 /// Low motion has to actually buy something: at least one inter frame of
423 /// a panning sequence has to cost fewer bytes than the key frame that330 /// a panning sequence has to cost fewer bytes than the key frame that
424 /// starts it, and the inter-block share it prints has to be non-zero --331 /// starts it, and the inter-block share it prints has to be non-zero --
@@ -459,446 +366,6 @@ use std::process::Command;
459 );366 );
460 }367 }
461 368
462- /// A manual perf probe, not a gate: prints where a key frame's and an
463- /// inter frame's time goes, coarse stage by coarse stage, so a perf lane
464- /// measures before it optimizes rather than guessing. Run with
465- /// `cargo test -p ec-av1 --release stage_timing_breakdown -- --ignored --nocapture`.
466- #[test]
467- #[ignore = "a perf probe, not a gate"]
468- fn stage_timing_breakdown() {
469- let _knobs = crate::speed::knob_read();
470- let fctx = &crate::decode::FrameCtx::for_encoder();
471- use std::time::Instant;
472-
473- for &(width, height) in &[(1920usize, 1080usize), (3840, 2160)] {
474- let picture = test_card(width, height);
475-
476- let t = Instant::now();
477- let dc_only =
478- encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[DC_PRED], fctx).unwrap();
479- let dc_only_t = t.elapsed();
480-
481- let t = Instant::now();
482- let non_directional =
483- encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &NON_DIRECTIONAL, fctx)
484- .unwrap();
485- let non_directional_t = t.elapsed();
486-
487- let t = Instant::now();
488- let all_modes = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
489- let all_modes_t = t.elapsed();
490-
491- eprintln!(
492- "\n=== key frame {width}x{height} ===\n\
493- 1 mode (DC only): {dc_only_t:>9.2?} ({} bytes)\n\
494- 7 modes (non-directional): {non_directional_t:>9.2?} ({} bytes)\n\
495- 13 modes (default search): {all_modes_t:>9.2?} ({} bytes)",
496- dc_only.stream.len(),
497- non_directional.stream.len(),
498- all_modes.stream.len(),
499- );
500-
501- // One inter frame predicting off the key frame's own
502- // reconstruction, the (256, 256)-padded surface encode_sequence
503- // itself would hand encode_inter_frame.
504- let padded_ref = all_modes.reconstruction.padded_to(SUPERBLOCK);
505- let padded_pic = picture.padded_to(SUPERBLOCK);
506- let t = Instant::now();
507- let inter = encode_inter_frame(
508- &padded_pic,
509- &padded_ref,
510- 100,
511- 0.5,
512- 1,
513- flat_order_hints(1, 0, false),
514- (width, height),
515- None,
516- None,
517- None,
518- None,
519- fctx,
520- None,
521- &[],
522- )
523- .unwrap();
524- let inter_t = t.elapsed();
525- eprintln!(
526- "inter frame vs its own key frame: {inter_t:>9.2?} ({} bytes, inter share \
527- {:.2})",
528- inter.stream.len(),
529- inter.inter_block_share
530- );
531- }
532-
533- // Isolated per-call cost of the trial pipeline's own stages, at both
534- // transform sizes the search runs, averaged over enough calls to
535- // rise above `Instant::now`'s own noise.
536- for side in [16usize, 32] {
537- const N: u32 = 20_000;
538- let residual: Vec<i32> = (0..side * side)
539- .map(|i| ((i * 37 % 61) as i32) - 30)
540- .collect();
541-
542- let t = Instant::now();
543- let mut levels = Vec::new();
544- for _ in 0..N {
545- levels = forward_and_quantize(&residual, side, 8, 100, 0.5);
546- }
547- let forward_t = t.elapsed() / N;
548-
549- let t = Instant::now();
550- for _ in 0..N {
551- std::hint::black_box(crate::transform::dequant_and_inverse(&levels, side, 8, 100));
552- }
553- let inverse_t = t.elapsed() / N;
554-
555- let set = if side == 32 {
556- crate::cdf_state::TxbSet::Luma32
557- } else {
558- crate::cdf_state::TxbSet::Luma16
559- };
560- let t = Instant::now();
561- for _ in 0..N {
562- std::hint::black_box(crate::tile::coeff_bits(&levels, set, 2, 0, 0));
563- }
564- let entropy_t = t.elapsed() / N;
565-
566- let above = vec![128u8; side * 2];
567- let left = vec![128u8; side * 2];
568- let mut prediction = vec![0u8; side * side];
569- let t = Instant::now();
570- for _ in 0..N {
571- intra_predict_u8(
572- D45_PRED,
573- 0,
574- Some(&above),
575- Some(&left),
576- Some(128),
577- side,
578- side,
579- false,
580- false,
581- &mut prediction,
582- fctx,
583- );
584- }
585- let predict_t = t.elapsed() / N;
586-
587- eprintln!(
588- "\n=== per-call cost at {side}x{side}, averaged over {N} calls ===\n\
589- predict (1 directional mode): {predict_t:>9.2?}\n\
590- forward_and_quantize: {forward_t:>9.2?}\n\
591- dequant_and_inverse: {inverse_t:>9.2?}\n\
592- coeff_bits: {entropy_t:>9.2?}"
593- );
594- }
595- }
596-
597- /// Breaks one inter frame's own cost into the four [`STAGE_NS`] buckets
598- /// plus what is left over once buckets 0/2/3 are subtracted.
599- ///
600- /// lane-av1probes: the two search-shaped buckets OVERLAP and the old
601- /// print denied it. Bucket 0 is not "the motion search": `stage_since(0,
602- /// ..)` fires only after `find_best_new_mv` and the global-MV search
603- /// (`encode.rs:11959`, `:12080`), so it is the NEWMV/GLOBAL sub-search
604- /// alone. Bucket 1 is EVERY `crate::mc::predict` call, from the search's
605- /// candidates *and* from a committed inter block's final prediction --
606- /// and that final prediction runs OUTSIDE any bucket-0 region. So bucket 1
607- /// is neither inside bucket 0 nor smaller than it, and a print that shows
608- /// it as "motion search (of which interpolation ...)" necessarily shows
609- /// a sub-number bigger than its parent. Measured: bucket 0 = 17.82 ms,
610- /// bucket 1 = 148.63 ms.
611- ///
612- /// Which number is real: BOTH timers are right; only the old ARITHMETIC
613- /// was wrong. Bucket 1 is now printed as its own top-level row, the
614- /// overlap is stated, and the residual is labelled for what it is -- it
615- /// absorbs the committed block's own interpolation, so it is not a pure
616- /// "13-mode intra candidate loop" figure either.
617- ///
618- /// `cargo test -p ec-av1 --release stage_timing_breakdown_inter -- --ignored --nocapture`.
619- #[test]
620- #[ignore = "a perf probe, not a gate"]
621- fn stage_timing_breakdown_inter() {
622- let _knobs = crate::speed::knob_read();
623- let fctx = &crate::decode::FrameCtx::for_encoder();
624- use std::time::Instant;
625-
626- let (width, height) = (1280usize, 720);
627- let picture = test_card(width, height);
628- let key = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
629- let padded_ref = key.reconstruction.padded_to(SUPERBLOCK);
630- let padded_pic = picture.padded_to(SUPERBLOCK);
631-
632- stage_reset();
633- let t = Instant::now();
634- let inter = encode_inter_frame(
635- &padded_pic,
636- &padded_ref,
637- 100,
638- 0.5,
639- 1,
640- flat_order_hints(1, 0, false),
641- (width, height),
642- None,
643- None,
644- None,
645- None,
646- fctx,
647- None,
648- &[],
649- )
650- .unwrap();
651- let total_t = t.elapsed();
652- let [motion_search, interpolation, transform_quant, entropy] = stage_read();
653- // Buckets 0 and 2 and 3 are disjoint and additive. Bucket 1 (every
654- // `mc::predict` call) is NOT added: it overlaps bucket 0 wherever a
655- // search candidate calls predict, and it also covers the committed
656- // block's final prediction, which no other bucket times. Adding it
657- // would double-count the overlap; leaving it out puts the committed
658- // prediction (and the intra candidate loop, RD glue, and the symbol
659- // lookups outside `coeff_bits`) into the residual, which is what the
660- // residual has always been.
661- let accounted = motion_search + transform_quant + entropy;
662- let other = total_t.saturating_sub(accounted);
663- let overlap = interpolation.saturating_sub(motion_search);
664-
665- eprintln!(
666- "\n=== inter frame {width}x{height}, one frame ===\n\
667- total: {total_t:>9.2?} ({} bytes)\n\
668- NEWMV/GLOBAL sub-search (bucket 0): {motion_search:>9.2?}\n\
669- transform + quantize (bucket 2): {transform_quant:>9.2?}\n\
670- coeff_bits, entropy pricing (bucket 3): {entropy:>9.2?}\n\
671- buckets 0+2+3 accounted: {accounted:>9.2?}\n\
672- \n\
673- OVERLAPPING, not additive: every mc::predict call (bucket 1) {interpolation:>9.2?}\n\
674- \x20 -- of which {overlap:>9.2?} is OUTSIDE bucket 0 (a committed\n\
675- \x20 inter block's final prediction, which no bucket above times)\n\
676- \x20 and the rest is the search candidates' interpolation, already\n\
677- \x20 inside bucket 0. It is deliberately NOT added to the total.\n\
678- \n\
679- residual (13-mode intra candidate loop, the committed block's\n\
680- \x20 interpolation above, NEARESTMV's own predict, RD glue): {other:>9.2?}",
681- inter.stream.len(),
682- );
683- }
684-
685- /// The quality gate [`Search::top_k`]'s lever lives or dies by: three real
686- /// frames (a dark/flat one, a detailed one, a normal film one) at two
687- /// `base_q_idx` values, encoded with the mode search unpruned (`top_k =
688- /// None`, the baseline this same build produces without
689- /// `EC_AV1_PRUNE_K` set) and with it pruned to each of a few `K`, bytes
690- /// and luma PSNR compared side by side. Not a gate itself -- the numbers
691- /// go in the lane report, which is where "ship as default" is decided --
692- /// so it stays `#[ignore]`, run by hand with real clips on this machine.
693- /// `cargo test -p ec-av1 --release prune_k_quality_sweep -- --ignored --nocapture`.
694- #[test]
695- // The three clip paths are HARD-CODED ABSOLUTES under /home/user, not
696- // env-driven: off this workstation every row prints `SKIP <label>: <path>
697- // not present on this machine` and the run exits 0 with no numbers. It is
698- // a local-run probe; there is no fleet-host configuration that makes it
699- // measure anything.
700- #[ignore = "local-run only: the three clips are hard-coded /home/user paths, so off this workstation it SKIPs every row and prints nothing"]
701- pub(super) fn prune_k_quality_sweep() {
702- let _knobs = crate::speed::knob_read();
703- let fctx = &crate::decode::FrameCtx::for_encoder();
704- if !have_ffmpeg() {
705- eprintln!("SKIP prune_k_quality_sweep: no ffmpeg");
706- return;
707- }
708- let (width, height) = (640usize, 352usize);
709- let frames: &[(&str, &str, &str)] = &[
710- // (label, clip, seek) -- a near-black scene, a busy one, and an
711- // ordinary film frame, each from a different real file.
712- (
713- "dark/flat",
714- "/home/user/Videos/reela.mp4",
715- "3",
716- ),
717- (
718- "detailed",
719- "/home/user/Downloads/reelb.mkv",
720- "1200",
721- ),
722- (
723- "film",
724- "/home/user/Videos/Films/reelc.mkv",
725- "600",
726- ),
727- ];
728- for &(label, clip, skip) in frames {
729- if !std::path::Path::new(clip).exists() {
730- eprintln!("SKIP {label}: {clip} not present on this machine");
731- continue;
732- }
733- let picture = clip_frame(clip, skip, width, height);
734- for &q in &[60u8, 150] {
735- // Note (process-global, not a memory question): this is
736- // a single-threaded #[ignore] probe, run by hand, never
737- // alongside other tests that read Search::top_k.
738- set_test_top_k_override(None);
739- let baseline = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
740- let baseline_psnr = psnr(&baseline.reconstruction.y, &picture.y);
741- eprint!(
742- "{label:9} q={q:3} baseline {:6} bytes {:6.2} dB",
743- baseline.stream.len(),
744- baseline_psnr
745- );
746- for &k in &[3usize, 4, 6] {
747- set_test_top_k_override(Some(k));
748- let pruned = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
749- let pruned_psnr = psnr(&pruned.reconstruction.y, &picture.y);
750- eprint!(
751- " K={k} {:6} bytes {:6.2} dB ({:+.3} dB)",
752- pruned.stream.len(),
753- pruned_psnr,
754- pruned_psnr - baseline_psnr
755- );
756- }
757- eprintln!();
758- }
759- }
760- set_test_top_k_override(None);
761- }
762-
763- /// Two consecutive decoded frames from one clip, for an inter-frame
764- /// sweep -- [`clip_frame`] alone only ever gives one.
765- pub(super) fn clip_frame_pair(clip: &str, skip: &str, width: usize, height: usize) -> [Picture; 2] {
766- let out = Command::new("ffmpeg")
767- .args(["-v", "error", "-ss", skip, "-i", clip, "-frames:v", "2"])
768- .args(["-vf", &format!("scale={width}:{height}")])
769- .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]).output()
770- .expect("ffmpeg failed to run");
771- assert!(
772- out.status.success(),
773- "ffmpeg: {}",
774- String::from_utf8_lossy(&out.stderr)
775- );
776- let (luma, chroma) = (width * height, width * height / 4);
777- let frame_len = luma + 2 * chroma;
778- assert_eq!(out.stdout.len(), frame_len * 2, "expected two 4:2:0 frames");
779- std::array::from_fn(|i| {
780- let bytes = &out.stdout[i * frame_len..][..frame_len];
781- Picture {
782- width,
783- height,
784- y: bytes[..luma].iter().map(|&v| u16::from(v)).collect(),
785- u: bytes[luma..luma + chroma]
786- .iter()
787- .map(|&v| u16::from(v))
788- .collect(),
789- v: bytes[luma + chroma..]
790- .iter()
791- .map(|&v| u16::from(v))
792- .collect(),
793- }
794- })
795- }
796-
797- /// The quality gate [`INTER_PRUNE_TOP_K`] lives or dies by: the same
798- /// three real clips as [`prune_k_quality_sweep`], but coding a key frame
799- /// then one inter frame off it (`search_inter_block`'s own intra
800- /// candidates are what [`prune_by_sad`] prunes here, not the key-frame
801- /// loop), at 1280x704 -- a whole number of 64x64 superblocks, so no
802- /// padding step complicates the comparison. Prints bytes and luma PSNR
803- /// for the inter frame alone, unpruned vs each `K`.
804- /// `cargo test -p ec-av1 --release prune_k_quality_sweep_inter -- --ignored --nocapture`.
805- #[test]
806- // Same hard-coded /home/user clip paths as `prune_k_quality_sweep`;
807- // off this workstation it SKIPs all three rows and prints nothing.
808- #[ignore = "local-run only: the three clips are hard-coded /home/user paths, so off this workstation it SKIPs every row and prints nothing"]
809- pub(super) fn prune_k_quality_sweep_inter() {
810- let _knobs = crate::speed::knob_read();
811- let fctx = &crate::decode::FrameCtx::for_encoder();
812- if !have_ffmpeg() {
813- eprintln!("SKIP prune_k_quality_sweep_inter: no ffmpeg");
814- return;
815- }
816- let (width, height) = (1280usize, 704usize);
817- let frames: &[(&str, &str, &str)] = &[
818- (
819- "dark/flat",
820- "/home/user/Videos/reela.mp4",
821- "3",
822- ),
823- (
824- "detailed",
825- "/home/user/Downloads/reelb.mkv",
826- "1200",
827- ),
828- (
829- "film",
830- "/home/user/Videos/Films/reelc.mkv",
831- "600",
832- ),
833- ];
834- for &(label, clip, skip) in frames {
835- if !std::path::Path::new(clip).exists() {
836- eprintln!("SKIP {label}: {clip} not present on this machine");
837- continue;
838- }
839- let [key_source, inter_source] = clip_frame_pair(clip, skip, width, height);
840- for &q in &[60u8, 150] {
841- // Note (process-global, not a memory question): a
842- // single-threaded #[ignore] probe, run by hand, never
843- // alongside other tests that read Search::top_k.
844- set_test_top_k_override_inter(None);
845- let key = encode_key_frame_with_ctx(&key_source, q, 0.5, fctx).unwrap();
846- let baseline = encode_inter_frame(
847- &inter_source,
848- &key.reconstruction,
849- q,
850- 0.5,
851- 1,
852- flat_order_hints(1, 0, false),
853- (width, height),
854- None,
855- None,
856- None,
857- None,
858- fctx,
859- None,
860- &[],
861- )
862- .unwrap();
863- let baseline_psnr = psnr(&baseline.reconstruction.y, &inter_source.y);
864- eprint!(
865- "{label:9} q={q:3} baseline {:6} bytes {:6.2} dB",
866- baseline.stream.len(),
867- baseline_psnr
868- );
869- for &k in &[3usize, 4, 6] {
870- set_test_top_k_override_inter(Some(k));
871- let pruned = encode_inter_frame(
872- &inter_source,
873- &key.reconstruction,
874- q,
875- 0.5,
876- 1,
877- flat_order_hints(1, 0, false),
878- (width, height),
879- None,
880- None,
881- None,
882- None,
883- fctx,
884- None,
885- &[],
886- )
887- .unwrap();
888- let pruned_psnr = psnr(&pruned.reconstruction.y, &inter_source.y);
889- eprint!(
890- " K={k} {:6} bytes {:6.2} dB ({:+.3} dB)",
891- pruned.stream.len(),
892- pruned_psnr,
893- pruned_psnr - baseline_psnr
894- );
895- }
896- eprintln!();
897- }
898- }
899- set_test_top_k_override_inter(None);
900- }
901-
902 /// `frames` consecutive pictures out of a real clip, scaled to a whole369 /// `frames` consecutive pictures out of a real clip, scaled to a whole
903 /// number of 32x32 blocks. Generalizes [`clip_frame`]/[`clip_frame_pair`]370 /// number of 32x32 blocks. Generalizes [`clip_frame`]/[`clip_frame_pair`]
904 /// to an arbitrary count for the fixture regression gate below.371 /// to an arbitrary count for the fixture regression gate below.
@@ -938,210 +405,6 @@ use std::process::Command;
938 crate::probe::source(clip, skip, vf, width, height, frames)405 crate::probe::source(clip, skip, vf, width, height, frames)
939 }406 }
940 407
941- /// The standing regression gate on real content: 12 frames of a real
942- /// clip (`fixtures/video/h264-1080p-23.976-8bit.mp4`, decoded down to
943- /// this crate's own input regardless of its own source codec), encoded
944- /// as an AV1 GOP and checked against three numeric floors so a
945- /// compatibility or quality regression fails the suite instead of
946- /// waiting for a downstream repo's gate to catch it (as happened for a
947- /// padded-size inter `FrameHeader` dav1d rejected, and a 1280x720 export
948- /// refusal, both caught only that way).
949- ///
950- /// 640x384 is a whole number of 32x32 blocks (no straddle edge case;
951- /// that geometry is already covered elsewhere), chosen only so encode
952- /// time and gate numbers are not muddied by an edge-block class this
953- /// test is not about.
954- ///
955- /// Measured 2026-08-27 at q=100: stream 69861 bytes, average luma PSNR
956- /// 45.41 dB across the 12 decoded frames vs the source. Floor/ceiling
957- /// below carry a margin off those measured numbers (PSNR floor =
958- /// measured - 0.5 dB; byte ceiling = measured * 1.15).
959- #[test]
960- fn real_clip_encodes_within_its_quality_and_size_budget() {
961- let _knobs = crate::speed::knob_read();
962- let fctx = &crate::decode::FrameCtx::for_encoder();
963- if !have_ffmpeg() {
964- eprintln!("SKIP real_clip_encodes_within_its_quality_and_size_budget: no ffmpeg");
965- return;
966- }
967- // lane-av1clipprobe: the clip's absence was a bare `clip.exists()`
968- // -> SKIP with no env escape, so this gate reported green on a tree
969- // with no root `fixtures/`. The probe prints that one line (naming the
970- // resolved path) and fails under the require envs.
971- let Some(clip) = crate::library_fixture::require(
972- "video/h264-1080p-23.976-8bit.mp4",
973- "real_clip_encodes_within_its_quality_and_size_budget",
974- ) else {
975- return;
976- };
977- let (width, height, frame_count) = (640usize, 384usize, 12usize);
978- let source = clip_frames(clip.to_str().unwrap(), "0", width, height, frame_count);
979- let encoded = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap();
980- assert_eq!(encoded.frames.len(), frame_count);
981-
982- // Gate 1: a real AV1 decoder (dav1d, via ffmpeg) accepts the whole
983- // stream and hands back every frame -- a stream a downstream
984- // decoder refuses is the exact class of regression this gate
985- // exists for.
986- let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frame_count);
987- assert_eq!(decoded.len(), frame_count, "dav1d decoded every frame");
988-
989- // Gate 2: quality vs the source did not silently collapse.
990- let mean_psnr: f64 = decoded
991- .iter()
992- .zip(&source)
993- .map(|(d, s)| psnr(&d.y, &s.y))
994- .sum::<f64>()
995- / frame_count as f64;
996- assert!(
997- mean_psnr >= 44.91,
998- "mean luma PSNR {mean_psnr:.2} dB fell below the 44.91 dB floor"
999- );
1000-
1001- // Gate 3: the stream did not silently bloat.
1002- assert!(
1003- encoded.stream.len() <= 80_340,
1004- "stream grew to {} bytes, over the 80340-byte ceiling",
1005- encoded.stream.len()
1006- );
1007- }
1008-
1009- /// Sibling of `real_clip_encodes_within_its_quality_and_size_budget` at a
1010- /// straddle size: 640x384 is exact on both axes (32-aligned), so
1011- /// `Quadrant::Split` never fires there and the 16x16 `NEARESTMV` leaf
1012- /// path landed in e19bb47 goes unexercised by real, mixed intra/inter
1013- /// content. 704x400 has 400 mod 32 == 16 -- the same "exactly half
1014- /// straddle" class as `a_sequence_round_trips_at_the_exactly_half_
1015- /// straddle_size`'s 1280x720, but that test is a synthetic panned test
1016- /// card; this one is the real-clip gate, same three floors.
1017- ///
1018- /// Measured 2026-08-27 at q=100, 8 frames: stream 54525 bytes, average
1019- /// luma PSNR 45.48 dB across the 8 decoded frames vs the source.
1020- /// Floor/ceiling below carry the same margin as the sibling test (PSNR
1021- /// floor = measured - 0.5 dB; byte ceiling = measured * 1.15).
1022- #[test]
1023- fn real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size() {
1024- let _knobs = crate::speed::knob_read();
1025- let fctx = &crate::decode::FrameCtx::for_encoder();
1026- if !have_ffmpeg() {
1027- eprintln!(
1028- "SKIP real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size: \
1029- no ffmpeg"
1030- );
1031- return;
1032- }
1033- // lane-av1clipprobe: see the sibling gate above -- the bare
1034- // `clip.exists()` -> SKIP had no env escape.
1035- let Some(clip) = crate::library_fixture::require(
1036- "video/h264-1080p-23.976-8bit.mp4",
1037- "real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size",
1038- ) else {
1039- return;
1040- };
1041- let (width, height, frame_count) = (704usize, 400usize, 8usize);
1042- let source = clip_frames(clip.to_str().unwrap(), "0", width, height, frame_count);
1043- let encoded = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap();
1044- assert_eq!(encoded.frames.len(), frame_count);
1045-
1046- // Gate 1: a real AV1 decoder (dav1d, via ffmpeg) accepts the whole
1047- // stream and hands back every frame.
1048- let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frame_count);
1049- assert_eq!(decoded.len(), frame_count, "dav1d decoded every frame");
1050-
1051- // Gate 2: quality vs the source did not silently collapse.
1052- let mean_psnr: f64 = decoded
1053- .iter()
1054- .zip(&source)
1055- .map(|(d, s)| psnr(&d.y, &s.y))
1056- .sum::<f64>()
1057- / frame_count as f64;
1058- assert!(
1059- mean_psnr >= 44.98,
1060- "mean luma PSNR {mean_psnr:.2} dB fell below the 44.98 dB floor"
1061- );
1062-
1063- // Gate 3: the stream did not silently bloat.
1064- assert!(
1065- encoded.stream.len() <= 62_703,
1066- "stream grew to {} bytes, over the 62703-byte ceiling",
1067- encoded.stream.len()
1068- );
1069- }
1070-
1071- /// The replica-shaped path: 24 frames, 1280x720, one key frame followed
1072- /// by inter frames -- the same GOP shape [`encode_sequence`] gives the
1073- /// facade -- timed end to end, so the edith export-time projection is a
1074- /// real number rather than a guess from the isolated key/inter numbers
1075- /// above. Run with and without `EC_AV1_PRUNE_K` set to compare.
1076- /// `cargo test -p ec-av1 --release sequence_bench_sanity -- --ignored --nocapture`.
1077- #[test]
1078- #[ignore = "a perf probe, not a gate"]
1079- fn sequence_bench_sanity() {
1080- let _knobs = crate::speed::knob_read();
1081- let fctx = &crate::decode::FrameCtx::for_encoder();
1082- use std::time::Instant;
1083- let (width, height) = (1280usize, 720usize);
1084- let pictures: Vec<Picture> = (0..24)
1085- .map(|i| panned_test_card(width, height, i * 3))
1086- .collect();
1087- let t = Instant::now();
1088- let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
1089- let elapsed = t.elapsed();
1090- let total_bytes: usize = encoded.frames.iter().map(|f| f.stream.len()).sum();
1091- eprintln!(
1092- "24 frames @ 1280x720: {elapsed:>9.2?} total, {:>9.2?}/frame, {total_bytes} bytes",
1093- elapsed / 24
1094- );
1095- }
1096-
1097- /// The `base_q_idx` calibration sweep for `lane-av1-ratectl` -- feeds the
1098- /// `Quality`/`BytesPerFrame` rate-control surface in `encoder.rs`, not a
1099- /// gate itself. `cargo test -p ec-av1 --release calibration_sweep_base_q_idx
1100- /// -- --ignored --nocapture`.
1101- #[test]
1102- #[ignore = "a calibration probe, not a gate"]
1103- fn calibration_sweep_base_q_idx() {
1104- let _knobs = crate::speed::knob_read();
1105- let fctx = &crate::decode::FrameCtx::for_encoder();
1106- if !have_ffmpeg() {
1107- eprintln!("SKIP calibration_sweep_base_q_idx: no ffmpeg");
1108- return;
1109- }
1110- let (width, height, frames) = (640usize, 384usize, 12usize);
1111- for clip in [
1112- "h264-1080p-23.976-8bit.mp4", // film-ish, 23.976fps
1113- "h264-1080p-60-8bit.mp4", // higher motion, 60fps
1114- ] {
1115- // lane-av1clipprobe: the crate's one fixture root and its one
1116- // presence probe -- the bare `path.exists()` -> SKIP -> `continue`
1117- // had no env escape, and with every clip absent the sweep looped
1118- // zero times and passed.
1119- let Some(path) = crate::library_fixture::require(
1120- &format!("video/{clip}"),
1121- &format!("calibration_sweep_base_q_idx: {clip}"),
1122- ) else {
1123- continue;
1124- };
1125- let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames);
1126- eprintln!("--- {clip} ---");
1127- for q in [40u8, 70, 100, 130, 160, 190, 220, 240] {
1128- let encoded = encode_sequence_with_ctx(&source, q, 0.5, fctx).unwrap();
1129- let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frames);
1130- let mean_psnr: f64 = decoded
1131- .iter()
1132- .zip(&source)
1133- .map(|(d, s)| psnr(&d.y, &s.y))
1134- .sum::<f64>()
1135- / frames as f64;
1136- let bytes_per_px = encoded.stream.len() as f64 / (width * height * frames) as f64;
1137- eprintln!(
1138- "q={q:3} bytes={:7} bytes/px={bytes_per_px:.5} psnr={mean_psnr:.2} dB",
1139- encoded.stream.len()
1140- );
1141- }
1142- }
1143- }
1144-
1145 // -----------------------------------------------------------------------408 // -----------------------------------------------------------------------
1146 // The encoder's standing BD-rate baseline against libaom and rav1e.409 // The encoder's standing BD-rate baseline against libaom and rav1e.
1147 // Every PSNR below is measured on FFMPEG-DECODED pixels, never on an410 // Every PSNR below is measured on FFMPEG-DECODED pixels, never on an
@@ -1197,7 +460,7 @@ use std::process::Command;
1197 std::process::id()460 std::process::id()
1198 ));461 ));
1199 let start = std::time::Instant::now();462 let start = std::time::Instant::now();
1200- let out = Command::new("ffmpeg")463+ let out = ec_testkit::ffmpeg()
1201 .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"])464 .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"])
1202 .args(["-s", &format!("{width}x{height}"), "-r", "24", "-i"])465 .args(["-s", &format!("{width}x{height}"), "-r", "24", "-i"])
1203 .arg(&raw_path)466 .arg(&raw_path)
@@ -1529,19 +792,10 @@ use std::process::Command;
1529 let _knobs = crate::speed::knob_write();792 let _knobs = crate::speed::knob_write();
1530 let was = crate::speed::speed();793 let was = crate::speed::speed();
1531 crate::speed::set_speed(0);794 crate::speed::set_speed(0);
1532- if !have_ffmpeg() {
1533- eprintln!("SKIP the_encoders_own_streams_are_byte_identical_to_their_pins: no ffmpeg");
1534- return;
1535- }
1536 // lane-av1clipprobe: the bare `clip.exists()` -> SKIP had no env escape,795 // lane-av1clipprobe: the bare `clip.exists()` -> SKIP had no env escape,
1537 // so a tree with no root `fixtures/` reported this gate green having796 // so a tree with no root `fixtures/` reported this gate green having
1538 // compared nothing at all.797 // compared nothing at all.
1539- let Some(clip) = crate::library_fixture::require(798+ let clip = ec_testkit::fixture("open/sintel_trailer-1080p.mp4");
1540- "video/h264-1080p-23.976-8bit.mp4",
1541- "the_encoders_own_streams_are_byte_identical_to_their_pins",
1542- ) else {
1543- return;
1544- };
1545 let source = clip_frames(clip.to_str().unwrap(), "0", 640, 384, 4);799 let source = clip_frames(clip.to_str().unwrap(), "0", 640, 384, 4);
1546 // FNV-1a over the stream: a witness that every coded bit is where it800 // FNV-1a over the stream: a witness that every coded bit is where it
1547 // was, which a byte count alone is not.801 // was, which a byte count alone is not.
@@ -1677,943 +931,6 @@ use std::process::Command;
1677 }931 }
1678 }932 }
1679 933
1680- /// The sweep behind [`screen_content`]'s constants
1681- /// (`unswept-decision-constants`), on the SAME five clips
1682- /// [`bd_rate_screen_native`] keeps off (`native_gate_clips`) and at the
1683- /// same native crop: for each colour bound N the share of 16x16 luma
1684- /// blocks with 2..=N distinct colours, and the share of those whose
1685- /// per-pixel variance also clears a floor V -- libaom's
1686- /// `av1_set_screen_content_options` counts the variance-cleared blocks
1687- /// too (its `counts_2`, which gates intrabc), and without that term a
1688- /// smooth dark film frame reads as screen content.
1689- /// `cargo test -p ec-av1 --release --lib -- --ignored probe_screen_detect --nocapture`
1690- #[test]
1691- #[ignore = "reads the real library"]
1692- fn probe_screen_detect() {
1693- let _knobs = crate::speed::knob_read();
1694- if !have_ffmpeg() {
1695- eprintln!("SKIP probe_screen_detect: no ffmpeg");
1696- return;
1697- }
1698- let limits = [4usize, 8, 16, 32, 64, 128];
1699- let floors = [0u64, 4, 16, 64, 256];
1700- // The census of one clip at one size: mean share, over the frames, of
1701- // 16x16 blocks with 2..=N colours whose per-pixel variance is > V.
1702- let census = |label: &str, frames: &[Picture], cw: usize, ch: usize| {
1703- let mut acc = [[0f64; 5]; 6];
1704- for picture in frames {
1705- let y: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
1706- let mut hit = [[0usize; 5]; 6];
1707- let mut blocks = 0usize;
1708- for by in (0..ch).step_by(16) {
1709- for bx in (0..cw).step_by(16) {
1710- let mut seen = [false; 256];
1711- let (mut colors, mut sum, mut sq) = (0usize, 0u64, 0u64);
1712- for row in 0..16 {
1713- for col in 0..16 {
1714- let v = y[(by + row) * cw + bx + col];
1715- sum += u64::from(v);
1716- sq += u64::from(v) * u64::from(v);
1717- if !seen[usize::from(v)] {
1718- seen[usize::from(v)] = true;
1719- colors += 1;
1720- }
1721- }
1722- }
1723- let var = (sq - sum * sum / 256) / 256;
1724- blocks += 1;
1725- for (li, &limit) in limits.iter().enumerate() {
1726- if colors > 1 && colors <= limit {
1727- for (fi, &floor) in floors.iter().enumerate() {
1728- hit[li][fi] += usize::from(var > floor);
1729- }
1730- }
1731- }
1732- }
1733- }
1734- for li in 0..6 {
1735- for fi in 0..5 {
1736- acc[li][fi] += 100.0 * hit[li][fi] as f64 / blocks.max(1) as f64;
1737- }
1738- }
1739- }
1740- let n = frames.len().max(1) as f64;
1741- eprintln!(
1742- "{label} {cw}x{ch}, {} frames -- share of 16x16 blocks with 2..=N colours and per-pixel var > V:",
1743- frames.len()
1744- );
1745- eprintln!(
1746- " N \\ V |{}",
1747- floors.iter().map(|f| format!("{f:>8}")).collect::<String>()
1748- );
1749- for (li, &limit) in limits.iter().enumerate() {
1750- eprintln!(
1751- " {limit:>5} |{}",
1752- (0..5)
1753- .map(|fi| format!("{:>7.1}%", acc[li][fi] / n))
1754- .collect::<String>()
1755- );
1756- }
1757- };
1758- for (name, path, seek) in native_gate_clips() {
1759- let Some((nw, nh)) = probe_dims(&path) else {
1760- eprintln!("SKIP {name}: ffprobe gave no size");
1761- continue;
1762- };
1763- let cw = nw.min(1920) / 128 * 128;
1764- let ch = nh.min(1024) / 128 * 128;
1765- let (x, y0) = (((nw - cw) / 2) & !1, ((nh - ch) / 2) & !1);
1766- let frames = clip_frames_vf(
1767- &path,
1768- &seek,
1769- &format!("crop={cw}:{ch}:{x}:{y0}"),
1770- cw,
1771- ch,
1772- 12,
1773- );
1774- census(&name, &frames, cw, ch);
1775- // The 640x384 gate scales instead of cropping, and the scaling
1776- // changes the census (bars smooth out): the constants have to
1777- // separate at BOTH sizes.
1778- let small = clip_frames(&path, &seek, 640, 384, 12);
1779- census(&name, &small, 640, 384);
1780- }
1781- }
1782-
1783- /// The detector against the WHOLE real library (class
1784- /// `unswept-decision-constants`, user rule "his data is the gate"):
1785- /// every VIDEO row of `fixtures/real-library-manifest.tsv` -- plus the
1786- /// two colour-bar fixtures as anchors -- decoded at 10/50/90% of its
1787- /// duration, four frames each, 8-bit 4:2:0, at native size or a
1788- /// 1920x1080 centred crop when larger (the crop keeps a capture's exact
1789- /// repeats, which a downscale destroys -- class `gate-recipe-confound`).
1790- /// Prints per file and offset the share of qualifying 16x16 blocks, the
1791- /// [`screen_content`] verdict and a content hint (mean luma, luma
1792- /// standard deviation, inter MAD), then sweeps the colour bound against
1793- /// the variance floor over the whole library: for each (N, V) the worst
1794- /// (highest) share among the camera/film rows against the best (lowest)
1795- /// among the screen-recording rows, so the rule with the widest gap can
1796- /// be read off. Rows carry the manifest index, codec and size only --
1797- /// no titles, no home paths.
1798- /// `cargo test -p ec-av1 --release --lib -- --ignored probe_screen_library --nocapture`
1799- #[test]
1800- #[ignore = "reads the real library"]
1801- fn probe_screen_library() {
1802- let _knobs = crate::speed::knob_read();
1803- if !have_ffmpeg() {
1804- eprintln!("SKIP probe_screen_library: no ffmpeg");
1805- return;
1806- }
1807- // lane-av1clipprobe: the crate's one fixture root (EC_FIXTURES first).
1808- let fixtures = crate::library_fixture::root();
1809- let Ok(manifest) = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv"))
1810- else {
1811- eprintln!("SKIP probe_screen_library: no real-library manifest");
1812- return;
1813- };
1814- let limits = [4usize, 8, 16, 32, 64];
1815- let floors = [0u64, 4, 8, 16, 32, 64, 128];
1816- // Whatever ffmpeg gave us, without the exact-count assertion the
1817- // gate loaders make: a seek near the end of a clip returns fewer
1818- // frames, and that is a row to print, not a panic.
1819- let decode =
1820- |clip: &str, seek: &str, vf: &str, w: usize, h: usize, n: usize| -> Vec<Picture> {
1821- let out = Command::new("ffmpeg")
1822- .args(["-v", "error", "-ss", seek, "-i", clip])
1823- .args(["-frames:v", &n.to_string()])
1824- .args(["-vf", vf])
1825- .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]).output();
1826- let Ok(out) = out else { return Vec::new() };
1827- if !out.status.success() {
1828- return Vec::new();
1829- }
1830- let (luma, chroma) = (w * h, w * h / 4);
1831- let frame_len = luma + 2 * chroma;
1832- (0..out.stdout.len() / frame_len)
1833- .map(|i| {
1834- let b = &out.stdout[i * frame_len..][..frame_len];
1835- Picture {
1836- width: w,
1837- height: h,
1838- y: b[..luma].iter().map(|&v| u16::from(v)).collect(),
1839- u: b[luma..luma + chroma]
1840- .iter()
1841- .map(|&v| u16::from(v))
1842- .collect(),
1843- v: b[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
1844- }
1845- })
1846- .collect()
1847- };
1848- // Share (%) of 16x16 blocks with 2..=N colours and per-pixel
1849- // variance > V, for every (N, V) of the sweep grid, over one frame.
1850- let census = |y: &[u8], w: usize, h: usize| -> [[f64; 7]; 5] {
1851- let mut hit = [[0usize; 7]; 5];
1852- let mut blocks = 0usize;
1853- for by in (0..h).step_by(16) {
1854- for bx in (0..w).step_by(16) {
1855- let (bh, bw) = ((h - by).min(16), (w - bx).min(16));
1856- let mut seen = [false; 256];
1857- let (mut colors, mut sum, mut sq) = (0usize, 0u64, 0u64);
1858- for row in 0..bh {
1859- for col in 0..bw {
1860- let v = y[(by + row) * w + bx + col];
1861- sum += u64::from(v);
1862- sq += u64::from(v) * u64::from(v);
1863- if !seen[usize::from(v)] {
1864- seen[usize::from(v)] = true;
1865- colors += 1;
1866- }
1867- }
1868- }
1869- let n = (bh * bw) as u64;
1870- let var = (sq - sum * sum / n) / n;
1871- blocks += 1;
1872- for (li, &limit) in limits.iter().enumerate() {
1873- if colors > 1 && colors <= limit {
1874- for (fi, &floor) in floors.iter().enumerate() {
1875- hit[li][fi] += usize::from(var > floor);
1876- }
1877- }
1878- }
1879- }
1880- }
1881- let mut out = [[0f64; 7]; 5];
1882- for li in 0..5 {
1883- for fi in 0..7 {
1884- out[li][fi] = 100.0 * hit[li][fi] as f64 / blocks.max(1) as f64;
1885- }
1886- }
1887- out
1888- };
1889- // (index, label, path, duration, screen-by-its-own-content). The
1890- // OBS directory and the OBS file-name shape ("YYYY-MM-DD HH-MM-SS")
1891- // are desktop recordings; everything else in this library is camera
1892- // or film material.
1893- let mut rows: Vec<(String, String, String, f64, bool)> = Vec::new();
1894- for (label, file) in [
1895- ("bars 1080p", "h264-1080p-23.976-8bit.mp4"),
1896- ("bars 2160p", "h264-2160p-23.976-8bit.mp4"),
1897- ] {
1898- let path = fixtures.join("video").join(file);
1899- if path.exists() {
1900- rows.push((
1901- "fx".into(),
1902- label.into(),
1903- path.to_str().unwrap().into(),
1904- 10.0,
1905- false,
1906- ));
1907- }
1908- }
1909- for (i, line) in manifest.lines().skip(1).enumerate() {
1910- let f: Vec<&str> = line.split('\t').collect();
1911- if f.len() < 10 {
1912- continue;
1913- }
1914- let (path, codec) = (f[0], f[2]);
1915- if codec == "-" || codec.is_empty() {
1916- continue;
1917- }
1918- let (Ok(w), Ok(h)) = (f[3].parse::<usize>(), f[4].parse::<usize>()) else {
1919- eprintln!("SKIP {}: manifest carries no coded size", i + 1);
1920- continue;
1921- };
1922- if !std::path::Path::new(path).exists() {
1923- eprintln!("SKIP {}: file is gone", i + 1);
1924- continue;
1925- }
1926- let name = path.rsplit('/').next().unwrap_or(path);
1927- let is_capture = path.contains("/OBS/")
1928- || (name.len() > 19
1929- && name.as_bytes()[4] == b'-'
1930- && name.as_bytes()[7] == b'-'
1931- && name.as_bytes()[10] == b' '
1932- && name.as_bytes()[13] == b'-');
1933- rows.push((
1934- format!("{}", i + 1),
1935- format!("{codec} {w}x{h}"),
1936- path.to_string(),
1937- f[8].parse::<f64>().unwrap_or(0.0),
1938- is_capture,
1939- ));
1940- }
1941- // Per (N, V): the worst camera/film row and the best screen row, so
1942- // the separation of the whole library is one subtraction.
1943- let (mut cam_max, mut scr_min) = ([[0f64; 7]; 5], [[100f64; 7]; 5]);
1944- eprintln!(
1945- "| idx | codec size | class | offset | qualifying blocks | verdict | mean/sd/MAD |"
1946- );
1947- for (idx, label, path, dur, is_capture) in &rows {
1948- let Some((nw, nh)) = probe_dims(path) else {
1949- eprintln!("SKIP {idx}: ffprobe gave no size");
1950- continue;
1951- };
1952- let (cw, ch) = (nw.min(1920) & !1, nh.min(1080) & !1);
1953- let (x, y0) = (((nw - cw) / 2) & !1, ((nh - ch) / 2) & !1);
1954- let vf = format!("crop={cw}:{ch}:{x}:{y0}");
1955- let mut file_grid = [[0f64; 7]; 5];
1956- let mut file_frames = 0usize;
1957- for pct in [10u32, 50, 90] {
1958- let seek = format!("{:.3}", dur * f64::from(pct) / 100.0);
1959- let frames = decode(path, &seek, &vf, cw, ch, 4);
1960- if frames.is_empty() {
1961- eprintln!(
1962- "| {idx} | {label} | {} | {pct}% | SKIP: ffmpeg decoded no frame here |",
1963- if *is_capture { "screen" } else { "camera" }
1964- );
1965- continue;
1966- }
1967- let (mut share, mut yes, mut mean, mut sd, mut mad) =
1968- (0f64, 0usize, 0f64, 0f64, 0f64);
1969- let mut prev: Option<Vec<u8>> = None;
1970- for picture in &frames {
1971- let y: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
1972- let grid = census(&y, cw, ch);
1973- for li in 0..5 {
1974- for fi in 0..7 {
1975- file_grid[li][fi] += grid[li][fi];
1976- }
1977- }
1978- file_frames += 1;
1979- // The shipped rule is (16 colours, var > 16): grid row 2,
1980- // floor 16 is column 3.
1981- share += grid[2][3];
1982- yes += usize::from(screen_content(&y, cw, cw, ch));
1983- let n = y.len() as f64;
1984- let sum: f64 = y.iter().map(|&v| f64::from(v)).sum();
1985- let sq: f64 = y.iter().map(|&v| f64::from(v) * f64::from(v)).sum();
1986- mean += sum / n;
1987- sd += (sq / n - (sum / n) * (sum / n)).max(0.0).sqrt();
1988- if let Some(p) = &prev {
1989- mad += p
1990- .iter()
1991- .zip(&y)
1992- .map(|(&a, &b)| f64::from(a.abs_diff(b)))
1993- .sum::<f64>()
1994- / n;
1995- }
1996- prev = Some(y);
1997- }
1998- let f = frames.len() as f64;
1999- eprintln!(
2000- "| {idx} | {label} | {} | {pct}% | {:.1}% | {} ({yes}/{} frames) | {:.0}/{:.1}/{:.2} |",
2001- if *is_capture { "screen" } else { "camera" },
2002- share / f,
2003- if yes * 2 > frames.len() {
2004- "SCREEN"
2005- } else {
2006- "camera"
2007- },
2008- frames.len(),
2009- mean / f,
2010- sd / f,
2011- mad / (f - 1.0).max(1.0),
2012- );
2013- }
2014- if file_frames == 0 {
2015- continue;
2016- }
2017- for li in 0..5 {
2018- for fi in 0..7 {
2019- let s = file_grid[li][fi] / file_frames as f64;
2020- match is_capture {
2021- true => scr_min[li][fi] = scr_min[li][fi].min(s),
2022- false => cam_max[li][fi] = cam_max[li][fi].max(s),
2023- }
2024- }
2025- }
2026- }
2027- eprintln!(
2028- "sweep over the whole library -- worst camera/film share vs best screen share, per (N colours, var > V):"
2029- );
2030- eprintln!(
2031- " N \\ V |{}",
2032- floors
2033- .iter()
2034- .map(|f| format!("{:>18}", format!("V>{f}")))
2035- .collect::<String>()
2036- );
2037- let (mut best, mut best_rule) = (f64::MIN, (16usize, 16u64));
2038- for (li, &limit) in limits.iter().enumerate() {
2039- let mut row = String::new();
2040- for fi in 0..7 {
2041- let (c, s) = (cam_max[li][fi], scr_min[li][fi]);
2042- row.push_str(&format!("{:>18}", format!("{c:.1}/{s:.1} {:+.1}", s - c)));
2043- if s - c > best {
2044- best = s - c;
2045- best_rule = (limit, floors[fi]);
2046- }
2047- }
2048- eprintln!(" {limit:>5} |{row}");
2049- }
2050- // The threshold sits at the midpoint of the widest gap; the shipped
2051- // constant is its reciprocal in whole parts of the frame.
2052- let (li, fi) = (
2053- limits.iter().position(|&l| l == best_rule.0).unwrap(),
2054- floors.iter().position(|&f| f == best_rule.1).unwrap(),
2055- );
2056- let mid = (cam_max[li][fi] + scr_min[li][fi]) / 2.0;
2057- eprintln!(
2058- "widest split: {} colours, var > {}, gap {:+.1} points (camera <= {:.1}%, screen >= {:.1}%); threshold {:.1}% = EC_AV1_SCREEN_PCT {}",
2059- best_rule.0,
2060- best_rule.1,
2061- best,
2062- cam_max[li][fi],
2063- scr_min[li][fi],
2064- mid,
2065- (100.0 / mid.max(0.1)).round() as usize,
2066- );
2067- }
2068-
2069- /// The missing instrument: what this encoder costs against libaom and
2070- /// rav1e at matched fidelity, and how long it takes to get there.
2071- ///
2072- /// Recipe, identical on all three sides: 12 consecutive frames of each
2073- /// clip scaled to 640x384 (a whole number of superblocks), one key frame
2074- /// then 11 inter frames (`-g 12`, matching our own sequence shape), one
2075- /// tile, `-threads 1`, no film grain synthesis (neither reference enables
2076- /// it by default), 4:2:0 8-bit in and out. Reference points:
2077- /// libaom-av1: `-cpu-used 6 -b:v 0 -crf {5,20,35,45}`
2078- /// librav1e: `-rav1e-params speed=6:quantizer={50,100,150,200}:
2079- /// tile_cols=1:tile_rows=1:threads=1`
2080- /// ours: `base_q_idx {60,90,120,150}`. Every PSNR is all-plane, on
2081- /// ffmpeg-decoded frames of each encoder's own stream.
2082- ///
2083- /// Measured 2026-09-06 after the in-loop filters (lane-av1filt: per-frame
2084- /// deblocking levels and CDEF strengths, both chosen by re-decoding the
2085- /// coded tile -- `crate::filter_search`), 12 frames, this box (wall = the
2086- /// four encodes of that ladder together):
2087- ///
2088- /// | clip | ours (q 150/120/90/60) | BD-rate vs libaom | vs rav1e | wall ours:aom:rav1e |
2089- /// |---|---|---|---|---|
2090- /// | 1080p fixture | 42.11 dB/17774 B .. 50.99 dB/76838 B | +143.6% | +94.0% | 9.2s:1.1s:2.6s |
2091- /// | 2160p fixture | 42.84 dB/12480 B .. 51.43 dB/46557 B | +179.5% | +128.8% | 8.6s:1.0s:2.2s |
2092- /// | screen capture | 39.76 dB/9536 B .. 48.87 dB/29189 B | +88.0% | +21.5% | 7.2s:1.0s:2.1s |
2093- ///
2094- /// Re-measured 2026-09-06 after lane-av1fwd, which changed only how long
2095- /// the encoder takes -- every stream it writes is byte-identical, so the
2096- /// BD columns are this box's own re-run of the same recipe rather than a
2097- /// quality move (+141.3/+174.2/+88.9 vs libaom, +91.9/+124.5/+21.6 vs
2098- /// rav1e). What moved is the wall of the four encodes:
2099- ///
2100- /// | clip | wall ours before | after | instructions:u before -> after |
2101- /// |---|---|---|---|
2102- /// | 1080p fixture | 9.2s | 7.2s | 191.5G -> 139.8G (-27.0%) |
2103- /// | 2160p fixture | 8.6s | 6.9s | 183.5G -> 136.4G (-25.6%) |
2104- /// | screen capture | 7.2s | 6.7s | 157.2G -> 122.5G (-22.1%) |
2105- ///
2106- /// Three exact steps, none of which touches a coded bit: the coefficient
2107- /// rate pricer stopped rebuilding every CDF table per candidate
2108- /// (`tile::coeff_bits`), the filter search stopped re-decoding its own
2109- /// tile once per candidate (`decode::FilterReplay`), and the forward
2110- /// transform stopped transforming the all-zero residual that 70% of its
2111- /// calls carry.
2112- ///
2113- /// The three steps of that lane, same recipe (vs libaom, then vs rav1e):
2114- ///
2115- /// | step | 1080p | 2160p | screen |
2116- /// |---|---|---|---|
2117- /// | no in-loop filter | +234.0 / +171.9 | +260.3 / +203.2 | +318.5 / +155.3 |
2118- /// | + deblocking | +198.2 / +143.1 | +218.1 / +162.4 | +136.9 / +52.7 |
2119- /// | + CDEF | +143.6 / +94.0 | +179.5 / +128.8 | +88.0 / +21.5 |
2120- ///
2121- /// Re-measured for the record 2026-09-07 (lane-av1resweep), after
2122- /// [`LAMBDA_SCALE`] moved 0.05 -> 0.0275 and the two var-tx depth
2123- /// searches ([`tx32_depth_search`], [`compound_var_tx`]) became defaults
2124- /// -- all three decided on the REAL film rows of
2125- /// [`bd_rate_screen_native`], which this downscaled recipe does not
2126- /// carry:
2127- ///
2128- /// | clip | BD vs libaom | BD vs rav1e | wall ours:libaom:rav1e |
2129- /// |---|---|---|---|
2130- /// | bars 1080p | +68.8% | +26.2% | 5.8s:1.2s:2.7s |
2131- /// | bars 2160p | +81.6% | +41.5% | 4.8s:1.0s:2.2s |
2132- /// | screen capture | +49.1% | -4.3% | 5.5s:1.0s:2.1s |
2133- ///
2134- /// RE-RECORDED 2026-09-07 (lane-av1pyrdef), with the coding pyramid the
2135- /// DEFAULT of the sequence path this gate codes through -- the bars are
2136- /// non-screen so they take it, the capture is gated flat:
2137- ///
2138- /// | clip | effective pyramid | BD vs libaom | BD vs rav1e | wall |
2139- /// |---|---|---|---|---|
2140- /// | bars 1080p | 4:-16:8 | +84.7% | +39.9% | 5.1s:1.1s:2.6s |
2141- /// | bars 2160p | 4:-16:8 | +124.4% | +75.2% | 4.4s:1.0s:2.8s |
2142- /// | screen capture | none (gated) | +49.1% | -4.3% | 6.5s:1.2s:2.3s |
2143- ///
2144- /// Those are, to the byte, the numbers lane-av1pyrgate recorded for the
2145- /// same clips under `EC_AV1_PYRAMID=4:-16:8 EC_AV1_GATE_FACADE=1` -- the
2146- /// facade arm -- which is what "one mini-GOP driver, two entry points"
2147- /// means here. This downscaled recipe HATES the pyramid (as it hates
2148- /// every knob the real film rows of `bd_rate_screen_native` keep, which
2149- /// is why it decides nothing); `EC_AV1_PYRAMID=0` restores the flat rows
2150- /// above. The capture's row is the flat row to the byte in both runs --
2151- /// that equality IS the content gate.
2152- ///
2153- /// Loop restoration is NOT in yet: it is the one filter whose parameters
2154- /// are per restoration UNIT inside the tile payload, so it needs both
2155- /// tile writers to code `lr` syntax and an encoder-visible post-CDEF
2156- /// buffer to solve against -- neither of which this frame-header-level
2157- /// search reaches.
2158- ///
2159- /// The baseline it replaced, before an inter frame's blocks chose their
2160- /// own partition, was +501.4/+504.4/+440.9 against libaom and
2161- /// +364.4/+401.0/+206.0 against rav1e at 5.1/4.6/5.9 s.
2162- ///
2163- /// So: roughly 2.5-3x libaom's rate and 1.5-2x rav1e's at matched
2164- /// fidelity, while spending far more time than either (the partition
2165- /// search's own cost, uncut: see the two intra-pruning variants measured
2166- /// and rejected in the lane report). No
2167- /// threshold is asserted yet -- this run sets the baseline; the gate
2168- /// asserts four monotone points per ladder, and at EVERY ladder point of
2169- /// EVERY clip it decodes our stream twice -- with ffmpeg and with our own
2170- /// `crate::stream::decode_stream` -- and asserts the encoder's
2171- /// reconstruction, ffmpeg's decode and our decode sample-exact in Y, U
2172- /// and V over every shown frame in display order. A failure names the
2173- /// clip, the q, the frame, the plane and the first differing sample.
2174- /// (Under `EC_AV1_PYRAMID` the frames come out of the streaming facade,
2175- /// which exposes no per-packet reconstruction, so that path asserts the
2176- /// two decoders against each other on all three planes.)
2177- ///
2178- /// Run:
2179- /// cargo test -p ec-av1 --release --lib -- --ignored \
2180- /// bd_rate_vs_libaom_and_rav1e --nocapture
2181- #[test]
2182- #[ignore = "the encoder BD-rate baseline: minutes per clip, needs ffmpeg"]
2183- fn bd_rate_vs_libaom_and_rav1e() {
2184- let _knobs = crate::speed::knob_write();
2185- if !have_ffmpeg() {
2186- eprintln!("SKIP bd_rate_vs_libaom_and_rav1e: no ffmpeg");
2187- return;
2188- }
2189- // lane-av1clipprobe: the crate's one fixture root (EC_FIXTURES first).
2190- let fixtures = crate::library_fixture::root();
2191- let mut clips: Vec<(String, std::path::PathBuf)> = Vec::new();
2192- // testsrc2 COLOUR BARS, not film -- labelled so no reader takes these
2193- // rows for real content (the real rows live in the native gate).
2194- for (label, name) in [
2195- ("bars 1080p", "h264-1080p-23.976-8bit.mp4"),
2196- ("bars 2160p", "h264-2160p-23.976-8bit.mp4"),
2197- ] {
2198- // lane-av1clipprobe: the one probe, so a missing clip is RED under
2199- // the require envs instead of a drop-with-no-escape.
2200- if let Some(path) = crate::library_fixture::require(
2201- &format!("video/{name}"),
2202- &format!("bd_rate_vs_libaom_and_rav1e: {label}"),
2203- ) {
2204- clips.push((label.to_string(), path));
2205- }
2206- }
2207- // Screen capture: the repo carries no screen-capture fixture, so take
2208- // the first OBS recording the real-library manifest names.
2209- match std::fs::read_to_string(fixtures.join("real-library-manifest.tsv")) {
2210- Ok(manifest) => {
2211- let screen = manifest
2212- .lines()
2213- .skip(1)
2214- .filter_map(|l| l.split('\t').next())
2215- .find(|p| {
2216- p.contains("/OBS/")
2217- && p.ends_with(".mkv")
2218- && std::path::Path::new(p).exists()
2219- });
2220- match screen {
2221- Some(p) => clips.push((
2222- format!("screen capture ({})", p.rsplit('/').next().unwrap_or(p)),
2223- std::path::PathBuf::from(p),
2224- )),
2225- None => {
2226- eprintln!("SKIP screen capture: no OBS recording in the manifest exists")
2227- }
2228- }
2229- }
2230- Err(e) => eprintln!("SKIP screen capture: no real-library manifest ({e})"),
2231- }
2232- assert!(!clips.is_empty(), "no source clip available");
2233-
2234- let (width, height, frames) = (640usize, 384usize, 12usize);
2235- let aom_points: Vec<Vec<String>> = [5, 20, 35, 45]
2236- .iter()
2237- .map(|q| {
2238- ["-cpu-used", "6", "-b:v", "0", "-crf", &q.to_string()]
2239- .map(String::from)
2240- .to_vec()
2241- })
2242- .collect();
2243- let rav1e_points: Vec<Vec<String>> = [50, 100, 150, 200]
2244- .iter()
2245- .map(|q| {
2246- vec![
2247- "-rav1e-params".to_string(),
2248- format!("speed=6:quantizer={q}:tile_cols=1:tile_rows=1:threads=1"),
2249- ]
2250- })
2251- .collect();
2252- println!(
2253- "\n{frames} frames of each clip at {width}x{height}, gop={frames}, 1 tile, 1 thread"
2254- );
2255- println!(
2256- "| clip | ours PSNR/bytes per point | BD-rate vs libaom | BD-rate vs rav1e | wall ours:libaom:rav1e |"
2257- );
2258- println!("|---|---|---|---|---|");
2259- for (name, path) in &clips {
2260- let fctx = &crate::decode::FrameCtx::for_encoder();
2261- let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames);
2262- let _ = take_partition_hits();
2263- let _ = crate::tile::take_palette_hits();
2264- SCREEN_FRAMES.iter().for_each(|c| {
2265- c.store(0, std::sync::atomic::Ordering::Relaxed);
2266- });
2267- let _ = take_uv_mode_hits();
2268- let _ = crate::tile::take_inter_mode_hits();
2269- let _ = crate::tile::take_drl_hits();
2270- let _ = crate::tile::take_ref_hits();
2271- let _ = crate::tile::take_compound_mode_hits();
2272- let _ = crate::tile::take_compound_pair_hits();
2273- let _ = crate::tile::take_compound_size_hits();
2274- let _ = crate::tile::take_compound_leaf_mode_hits();
2275- let _ = take_b64_root_hits();
2276- let _ = take_b64_residual_hits();
2277- let _ = take_b64_compound_hits();
2278- let _ = crate::motion::take_census();
2279- // The entry-surface arm: run the SAME ladder through the
2280- // streaming facade the editor's export calls, which must print
2281- // the same BD numbers as the sequence path -- byte for byte the
2282- // same stream now that both drive one mini-GOP driver
2283- // (lane-av1pyrdef).
2284- let facade = std::env::var_os("EC_AV1_GATE_FACADE").is_some();
2285- let (ours, ours_wall) = match facade {
2286- false => our_ladder(name, &source, width, height, fctx),
2287- true => {
2288- let pyramid = crate::encoder::Pyramid::from_env();
2289- let (ladder, wall, counts, bytes, effective) =
2290- our_ladder_facade(name, &source, width, height, pyramid);
2291- eprintln!(
2292- "{name}: facade, pyramid requested {pyramid:?} effective \
2293- {effective:?} -- frames key {} arf {} leaf {} \
2294- show_existing {}; bytes key {} arf {} leaf {} show_existing {}",
2295- counts[0],
2296- counts[1],
2297- counts[2],
2298- counts[3],
2299- bytes[0],
2300- bytes[1],
2301- bytes[2],
2302- bytes[3],
2303- );
2304- (ladder, wall)
2305- }
2306- };
2307- // How often the inter split actually fired over this clip's four
2308- // encodes, against the whole 32x32 that was the only outcome
2309- // before (gate-blind-to-feature).
2310- let [whole32, split32, whole16, split16] = take_partition_hits();
2311- // Which inter modes actually fired over this clip's four encodes,
2312- // and at which DRL index -- a mode nobody picks is a mode the BD
2313- // number cannot be crediting (gate-blind-to-feature).
2314- let [nearest, near, global, new] = crate::tile::take_inter_mode_hits();
2315- let [drl0, drl1, drl2, drl3] = crate::tile::take_drl_hits();
2316- let refs = crate::tile::take_ref_hits();
2317- let modes_total = (nearest + near + global + new).max(1);
2318- eprintln!(
2319- "{name}: inter modes NEAREST {nearest} ({:.1}%) NEAR {near} ({:.1}%) \
2320- GLOBAL {global} ({:.1}%) NEW {new} ({:.1}%); drl idx 0/1/2/3+ \
2321- {drl0}/{drl1}/{drl2}/{drl3}",
2322- 100.0 * nearest as f64 / modes_total as f64,
2323- 100.0 * near as f64 / modes_total as f64,
2324- 100.0 * global as f64 / modes_total as f64,
2325- 100.0 * new as f64 / modes_total as f64,
2326- );
2327- // The compound census: what share of the coded inter blocks took
2328- // a compound reference at all, which compound mode they took, and
2329- // which pair (gate-blind-to-feature -- a compound mode nobody
2330- // picks cannot be what a BD number credits).
2331- // The 64x64 root's own fire shares (lane-b64/tx64/b64b): how many
2332- // superblocks were left whole at all, and how many of those coded
2333- // a residual or took a compound reference.
2334- let (roots, root_res, root_comp) = (
2335- take_b64_root_hits(),
2336- take_b64_residual_hits(),
2337- take_b64_compound_hits(),
2338- );
2339- eprintln!(
2340- "{name}: 64x64 roots {roots} (with a residual {root_res}, compound {root_comp})"
2341- );
2342- let comp_modes = crate::tile::take_compound_mode_hits();
2343- let comp_pairs = crate::tile::take_compound_pair_hits();
2344- let comp_sizes = crate::tile::take_compound_size_hits();
2345- let comp_leaf = crate::tile::take_compound_leaf_mode_hits();
2346- let comp_total: usize = comp_modes.iter().sum();
2347- eprintln!(
2348- "{name}: compound {comp_total} of {} inter blocks ({:.1}%); modes \
2349- NEAREST_NEAREST {} NEAR_NEAR {} NEAREST_NEW {} NEW_NEAREST {} \
2350- GLOBAL_GLOBAL {} NEW_NEW {}; pairs LAST+GOLDEN {} LAST+ALTREF {}",
2351- modes_total + comp_total,
2352- 100.0 * comp_total as f64 / (modes_total + comp_total) as f64,
2353- comp_modes[0],
2354- comp_modes[1],
2355- comp_modes[2],
2356- comp_modes[3],
2357- comp_modes[6],
2358- comp_modes[7],
2359- comp_pairs[3],
2360- comp_pairs[6],
2361- );
2362- eprintln!(
2363- "{name}: leaf (16x16 and below) compound modes NEAREST_NEAREST {} \
2364- NEAR_NEAR {} NEAREST_NEW {} NEW_NEAREST {} GLOBAL_GLOBAL {} NEW_NEW {}",
2365- comp_leaf[0], comp_leaf[1], comp_leaf[2], comp_leaf[3], comp_leaf[6], comp_leaf[7],
2366- );
2367- eprintln!(
2368- "{name}: compound by size 8x8 {} 16x16 {} 32x32 {}",
2369- comp_sizes[1], comp_sizes[2], comp_sizes[3],
2370- );
2371- // Where the wall-owning stage actually goes: how many candidate
2372- // evaluations (one `mc::predict` + SAD each) a search spends, how
2373- // many of them are subpel, and how often the winner is the seed
2374- // it started from -- the census the seeded search is judged by.
2375- let [
2376- calls,
2377- evals,
2378- subpel,
2379- rounds,
2380- near_pred,
2381- unmoved,
2382- widest,
2383- widest_moves,
2384- ] = crate::motion::take_census();
2385- let per = |n: u64| n as f64 / calls.max(1) as f64;
2386- eprintln!(
2387- "{name}: motion search {calls} calls, {evals} candidate evals ({:.1}/call, \
2388- {:.1}% of them subpel), {rounds} integer rounds ({:.2}/call); winner within \
2389- +-1 pel of pred_mv {:.1}%, winner = starting seed {:.1}%",
2390- per(evals),
2391- 100.0 * subpel as f64 / evals.max(1) as f64,
2392- per(rounds),
2393- 100.0 * near_pred as f64 / calls.max(1) as f64,
2394- 100.0 * unmoved as f64 / calls.max(1) as f64,
2395- );
2396- // lane-newmv, class `instrument at bound`: how often the winner
2397- // was walked to at the log stage's own WIDEST step -- a high
2398- // share means the search stops where its step lets it, not where
2399- // the content is.
2400- eprintln!(
2401- "{name}: motion search moved at the widest step in {:.1}% of calls ({:.2} such moves/call)",
2402- 100.0 * widest as f64 / calls.max(1) as f64,
2403- per(widest_moves),
2404- );
2405- eprintln!(
2406- "{name}: references LAST {} GOLDEN {} (LAST2 {} LAST3 {} BWD {} ALT2 {} ALT {})",
2407- refs[0], refs[3], refs[1], refs[2], refs[4], refs[5], refs[6]
2408- );
2409- eprintln!(
2410- "{name}: inter 32x32 split into 16s {split32} of {} blocks ({:.1}%); \
2411- 16x16 leaves split into 8s {split16} of {} ({:.1}%)",
2412- whole32 + split32,
2413- 100.0 * split32 as f64 / (whole32 + split32).max(1) as f64,
2414- whole16 + split16,
2415- 100.0 * split16 as f64 / (whole16 + split16).max(1) as f64
2416- );
2417- // The deblocking level each of this clip's frames chose
2418- // (lane-av1filt): 0 everywhere would mean the filter never fires.
2419- let levels = crate::filter_search::take_chosen_levels();
2420- type Chosen = ((u8, u8), (u8, u8), (u8, u8));
2421- let mean = |f: fn(&Chosen) -> u8| {
2422- levels.iter().map(|l| f(l) as f64).sum::<f64>() / levels.len().max(1) as f64
2423- };
2424- eprintln!(
2425- "{name}: over {} frames -- deblock luma mean {:.1} chroma {:.1}; \
2426- cdef luma pri {:.1}/sec {:.1}, chroma pri {:.1}/sec {:.1}",
2427- levels.len(),
2428- mean(|l| l.0.0),
2429- mean(|l| l.0.1),
2430- mean(|l| l.1.0),
2431- mean(|l| l.1.1),
2432- mean(|l| l.2.0),
2433- mean(|l| l.2.1),
2434- );
2435- // How many strength presets each frame's CDEF list carried and
2436- // how the 64x64 units spread over them (lane-av1lr): `bits 0`
2437- // everywhere would mean the per-unit choice never fires.
2438- let presets = crate::filter_search::take_cdef_presets();
2439- let mut by_bits = [0usize; 4];
2440- for (b, _) in &presets {
2441- by_bits[usize::from(*b)] += 1;
2442- }
2443- let units: usize = presets.iter().flat_map(|(_, c)| c).sum();
2444- let on_extra: usize = presets.iter().flat_map(|(_, c)| c.iter().skip(1)).sum();
2445- eprintln!(
2446- "{name}: cdef_bits frames {}/{}/{}/{} (0/1/2/3); {} of {} 64x64 units \
2447- on a non-default preset ({:.1}%)",
2448- by_bits[0],
2449- by_bits[1],
2450- by_bits[2],
2451- by_bits[3],
2452- on_extra,
2453- units,
2454- 100.0 * on_extra as f64 / units.max(1) as f64
2455- );
2456- // How the 64x64 luma restoration units split between
2457- // RESTORE_NONE and Wiener (lane-av1lr).
2458- let (lr_none, lr_wiener) = crate::filter_search::take_lr_histogram();
2459- eprintln!(
2460- "{name}: lr units none={lr_none} wiener={lr_wiener} ({:.1}% restored)",
2461- 100.0 * lr_wiener as f64 / (lr_none + lr_wiener).max(1) as f64
2462- );
2463- // Which chroma modes the search actually wins with, against the
2464- // unconditional DC_PRED that was the only outcome before
2465- // (gate-blind-to-feature).
2466- // Screen-content detection and the palette it turns on
2467- // (gate-blind-to-feature): how many frames set
2468- // `allow_screen_content_tools`, how many blocks took a palette,
2469- // and of what size. A film clip must print `screen frames on=0`.
2470- let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed);
2471- let screen_off = SCREEN_FRAMES[0].load(std::sync::atomic::Ordering::Relaxed);
2472- // Which tables the SEARCH priced against, per frame arming
2473- // (`tile::arm_pricing_cdfs`): the default tables or the frame's
2474- // real starting ones. A film clip must show every inter arming on
2475- // the real side, a screen clip none of them.
2476- let (price_default, price_real) = crate::tile::take_pricing_hits();
2477- eprintln!("{name}: pricer armings default={price_default} real={price_real}");
2478- let palette = crate::tile::take_palette_hits();
2479- eprintln!(
2480- "{name}: screen frames on={screen_on} off={screen_off}; palette blocks {} sizes {}",
2481- palette[0],
2482- (2..=8)
2483- .filter(|&n| palette[n] > 0)
2484- .map(|n| format!("{n}={}", palette[n]))
2485- .collect::<Vec<_>>()
2486- .join(" ")
2487- );
2488- // The CfL alpha histogram (lane-av1cfl): one entry per chroma
2489- // plane of every `UV_CFL_PRED` block, by |alpha_q3|. A tool that
2490- // only ever fires at one magnitude is a search that never left
2491- // its first candidate (gate-blind-to-feature).
2492- // The luma angle-delta histogram (lane-av1cfl): how many
2493- // directional blocks won at each delta. All-zero would mean the
2494- // refinement never beat the base angle.
2495- let deltas = take_angle_delta_hits();
2496- if deltas.iter().sum::<usize>() > 0 {
2497- eprintln!(
2498- "{name}: angle_delta_y {}",
2499- deltas
2500- .iter()
2501- .enumerate()
2502- .map(|(d, &n)| format!("{:+}={n}", d as i32 - 3))
2503- .collect::<Vec<_>>()
2504- .join(" ")
2505- );
2506- }
2507- let alphas = take_cfl_alpha_hits();
2508- if alphas.iter().sum::<usize>() > 0 {
2509- eprintln!(
2510- "{name}: cfl |alpha| {}",
2511- alphas
2512- .iter()
2513- .enumerate()
2514- .filter(|&(_, &n)| n > 0)
2515- .map(|(a, &n)| format!("{a}={n}"))
2516- .collect::<Vec<_>>()
2517- .join(" ")
2518- );
2519- }
2520- let palette_uv = crate::tile::take_palette_uv_hits();
2521- eprintln!(
2522- "{name}: chroma palette blocks {} sizes {}",
2523- palette_uv[0],
2524- (2..=8)
2525- .filter(|&n| palette_uv[n] > 0)
2526- .map(|n| format!("{n}={}", palette_uv[n]))
2527- .collect::<Vec<_>>()
2528- .join(" ")
2529- );
2530- let uv = take_uv_mode_hits();
2531- let uv_total: usize = uv.iter().sum();
2532- eprintln!(
2533- "{name}: uv modes {}",
2534- uv.iter()
2535- .enumerate()
2536- .filter(|&(_, &n)| n > 0)
2537- .map(|(m, &n)| format!(
2538- "{}={n} ({:.1}%)",
2539- UV_MODE_NAMES[m],
2540- 100.0 * n as f64 / uv_total.max(1) as f64
2541- ))
2542- .collect::<Vec<_>>()
2543- .join(" ")
2544- );
2545- // Which transform depth the intra blocks of this clip's key
2546- // frames resolved to (lane-av1tx): depth 0 is one transform over
2547- // the whole block, 1 and 2 its halvings.
2548- let depths = take_tx_depth_hits();
2549- let depth_total: usize = depths.iter().sum();
2550- eprintln!(
2551- "{name}: intra tx depths {}",
2552- depths
2553- .iter()
2554- .enumerate()
2555- .map(|(d, &n)| format!(
2556- "{d}={n} ({:.1}%)",
2557- 100.0 * n as f64 / depth_total.max(1) as f64
2558- ))
2559- .collect::<Vec<_>>()
2560- .join(" ")
2561- );
2562- print_inter_tx_census(name);
2563- // lane-av1obmc: how many blocks actually CODED a motion_mode
2564- // symbol and which value they took, by footprint -- "OBMC is on"
2565- // as a measurement rather than a claim (class
2566- // `gate-blind-to-feature`).
2567- let mm = crate::tile::take_motion_mode_hits();
2568- eprintln!(
2569- "{name}: motion_mode 32x32 SIMPLE={} OBMC={} WARP={} | 16x16 SIMPLE={} OBMC={} \
2570- WARP={} | 8x8 SIMPLE={} OBMC={} WARP={} ({:.1}% OBMC / {:.1}% WARP of {} \
2571- eligible)",
2572- mm[0],
2573- mm[1],
2574- mm[2],
2575- mm[3],
2576- mm[4],
2577- mm[5],
2578- mm[6],
2579- mm[7],
2580- mm[8],
2581- 100.0 * (mm[1] + mm[4] + mm[7]) as f64 / mm.iter().sum::<usize>().max(1) as f64,
2582- 100.0 * (mm[2] + mm[5] + mm[8]) as f64 / mm.iter().sum::<usize>().max(1) as f64,
2583- mm.iter().sum::<usize>(),
2584- );
2585- let (aom, aom_wall) =
2586- external_ladder(&source, width, height, "libaom-av1", &aom_points);
2587- let (rav1e, rav1e_wall) =
2588- external_ladder(&source, width, height, "librav1e", &rav1e_points);
2589- assert_monotone(&format!("{name}: ours"), &ours);
2590- assert_monotone(&format!("{name}: libaom"), &aom);
2591- assert_monotone(&format!("{name}: rav1e"), &rav1e);
2592- let points = ours
2593- .iter()
2594- .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
2595- .collect::<Vec<_>>()
2596- .join(", ");
2597- println!(
2598- "| {name} | {points} | {:+.1}% | {:+.1}% | {ours_wall:.1}s:{aom_wall:.1}s:{rav1e_wall:.1}s |",
2599- bd_rate(&aom, &ours) * 100.0,
2600- bd_rate(&rav1e, &ours) * 100.0,
2601- );
2602- println!(
2603- "| references | libaom {} | rav1e {} | | |",
2604- aom.iter()
2605- .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
2606- .collect::<Vec<_>>()
2607- .join(", "),
2608- rav1e
2609- .iter()
2610- .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
2611- .collect::<Vec<_>>()
2612- .join(", "),
2613- );
2614- }
2615- assert_ladder_decodes();
2616- }
2617 /// Which var-tx depth this clip's INTER blocks resolved to (lane-av1tx2,934 /// Which var-tx depth this clip's INTER blocks resolved to (lane-av1tx2,
2618 /// split by block class in lane-av1txdepth): depth 0 is one transform over935 /// split by block class in lane-av1txdepth): depth 0 is one transform over
2619 /// the whole block, 1 its four halves; the classes are the 16x16/8x8936 /// the whole block, 1 its four halves; the classes are the 16x16/8x8
@@ -2735,634 +1052,6 @@ use std::process::Command;
2735 Some((format!("crop={cw}:{ch}:{x}:{y}"), cw, ch))1052 Some((format!("crop={cw}:{ch}:{x}:{y}"), cw, ch))
2736 }1053 }
2737 1054
2738- /// The rows of [`bd_rate_screen_native`] -- (label, path, seek) -- shared
2739- /// with `probe_screen_detect` so the detector sweep measures exactly the
2740- /// clips the keep table is read off. Selector env vars as documented on
2741- /// the gate; a missing clip prints a SKIP and drops its row.
2742- pub(super) fn native_gate_clips() -> Vec<(String, String, String)> {
2743- // lane-av1clipprobe: the crate's one fixture root (EC_FIXTURES first).
2744- let fixtures = crate::library_fixture::root();
2745- let on = |k: &str| std::env::var(k).ok().as_deref() == Some("1");
2746- let (film, film4k, screen) = (
2747- on("EC_AV1_NATIVE_FILM"),
2748- on("EC_AV1_NATIVE_FILM4K"),
2749- on("EC_AV1_NATIVE_SCREEN"),
2750- );
2751- // No selector at all means every clip; any selector means that subset.
2752- let all = !(film || film4k || screen);
2753- // (label, path, seek). The two `testsrc2` fixtures are COLOUR BARS,
2754- // not film -- they print as "bars" so no reader takes them for real
2755- // content -- and the two rows below them are the real AV1 films.
2756- let mut clips: Vec<(String, String, String)> = Vec::new();
2757- for (want, label, file) in [
2758- (all || film, "bars 1080p", "h264-1080p-23.976-8bit.mp4"),
2759- (all || film4k, "bars 2160p", "h264-2160p-23.976-8bit.mp4"),
2760- ] {
2761- if !want {
2762- continue;
2763- }
2764- // lane-av1clipprobe: the one probe, so a missing clip is RED under
2765- // the require envs instead of a dropped row with no escape.
2766- if let Some(path) = crate::library_fixture::require(
2767- &format!("video/{file}"),
2768- &format!("the native BD-rate gate: {label}"),
2769- ) {
2770- clips.push((
2771- label.to_string(),
2772- path.to_str().unwrap().to_string(),
2773- "0".into(),
2774- ));
2775- }
2776- }
2777- let manifest = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv"));
2778- // The real films, taken out of the real-library manifest by codec and
2779- // coded width so no title and no home path lives in this file. Each
2780- // seek is PINNED (class `seeded fixture not reproducible`) at a
2781- // moving, non-black window -- a black leader would make every arm
2782- // read +0.000 (class `flat sample window`). Both sources are 10-bit
2783- // (one HDR10/PQ); the loader's plain `-pix_fmt yuv420p` conversion is
2784- // what all three encoders see, so the comparison stays
2785- // encoder-vs-encoder.
2786- let pick = |width: &str| -> Option<String> {
2787- let m = manifest.as_ref().ok()?;
2788- m.lines()
2789- .skip(1)
2790- .map(|l| l.split('\t').collect::<Vec<_>>())
2791- .find(|f| {
2792- f.len() > 4
2793- && f[2] == "av1"
2794- && f[3] == width
2795- && std::path::Path::new(f[0]).exists()
2796- })
2797- .map(|f| f[0].to_string())
2798- };
2799- for (want, label, width, seek) in [
2800- (all || film, "film A (1080p source)", "1920", "00:35:00"),
2801- (
2802- all || film4k,
2803- "film B (2160p HDR source)",
2804- "3840",
2805- "00:40:00",
2806- ),
2807- ] {
2808- if !want {
2809- continue;
2810- }
2811- match pick(width) {
2812- Some(path) => clips.push((label.to_string(), path, seek.to_string())),
2813- None => eprintln!("SKIP {label}: no {width}-wide AV1 source in the manifest"),
2814- }
2815- }
2816- if all || screen {
2817- match &manifest {
2818- Ok(manifest) => match manifest
2819- .lines()
2820- .skip(1)
2821- .filter_map(|l| l.split('\t').next())
2822- .find(|p| {
2823- p.contains("/OBS/")
2824- && p.ends_with(".mkv")
2825- && std::path::Path::new(p).exists()
2826- }) {
2827- Some(p) => clips.push((
2828- format!("screen capture ({})", p.rsplit('/').next().unwrap_or(p)),
2829- p.to_string(),
2830- "0".into(),
2831- )),
2832- None => {
2833- eprintln!("SKIP screen capture: no OBS recording in the manifest exists")
2834- }
2835- },
2836- Err(e) => eprintln!("SKIP screen capture: no real-library manifest ({e})"),
2837- }
2838- }
2839- clips
2840- }
2841-
2842- /// The NATIVE-resolution arm of the BD gate (all three clips). The default gate
2843- /// downscales the OBS capture to 640x384, which destroys exactly the
2844- /// pixel-identical 16x16 repeats intrabc and (part of) the palette exist
2845- /// for (class `gate-recipe-confound`), so every screen-tool decision taken
2846- /// on that recipe is taken on content the tool cannot serve. This arm
2847- /// crops -- never scales -- a superblock-aligned window out of the middle
2848- /// of the capture at its own resolution (at most 1920x1024, so the wall
2849- /// stays in the minutes) and runs the same 12-frame, four-quantizer
2850- /// ladder against libaom `cpu-used 6` and rav1e `speed=6`, one tile, one
2851- /// thread, with the same three-way (encoder / ffmpeg / our decoder)
2852- /// sample-exactness assertion `our_ladder` makes.
2853- ///
2854- /// It is its own `--ignored` test so the default gate's wall does not
2855- /// grow. Every variant is an environment knob, and each of those is a
2856- /// `OnceLock` read once per process, so a variant is a separate run:
2857- ///
2858- /// cargo test -p ec-av1 --release --lib -- --ignored \
2859- /// bd_rate_screen_native --nocapture # baseline
2860- /// EC_AV1_INTRABC=1 ... same command # intra block copy
2861- /// EC_AV1_PAL_MAXCOLORS=256 ... same command # palette bound
2862- /// EC_AV1_TILES=1:1 EC_AV1_TILE_THREADS=4 ... # 2x2 tiles
2863- /// EC_AV1_PYRAMID=0 ... same command # no coding pyramid
2864- /// EC_AV1_GOP_LAYOUT=fixed ... same command # no tail absorbing
2865- /// EC_AV1_GATE_FACADE=1 ... same command # the facade arm
2866- ///
2867- /// The coding pyramid is the DEFAULT of the sequence path this arm codes
2868- /// through (lane-av1pyrdef); the run prints the requested and the
2869- /// effective pyramid per clip, and a screen clip's effective one is
2870- /// `None`. `EC_AV1_GATE_FACADE=1` runs the same ladder through the
2871- /// streaming facade instead, which prints the per-level frame and byte
2872- /// census and asserts ffmpeg's decode against our own decoder on all
2873- /// three planes in display order; both arms code the same bytes
2874- /// (`encoder::tests::the_facade_codes_the_same_bytes_as_encode_sequence`).
2875- ///
2876- /// WHICH ROWS ARE REAL CONTENT: the `bars 1080p` / `bars 2160p` rows are
2877- /// the repo fixtures `scripts/gen-fixtures.sh` builds with ffmpeg
2878- /// `testsrc2` -- COLOUR BARS, ~90% of whose 16x16 cells have no intra
2879- /// cost -- so every "film" column in the historical tables of this file
2880- /// is that generator, not film. The real content is `film A`, `film B`
2881- /// (native crops out of the two AV1 films the real-library manifest
2882- /// names, at a pinned seek; added 2026-09-07) and the screen capture. A
2883- /// decision only the bars rows support is not supported.
2884- ///
2885- /// Measured 2026-09-07, the five rows before and after the screen
2886- /// detector grew libaom's variance term ([`screen_var`]) -- before it,
2887- /// BOTH real films were classified as screen content on 48/48 frames, so
2888- /// their coefficients were priced against the DEFAULT CDFs and the
2889- /// palette search ran over film; after, both are non-screen (0/48) and
2890- /// the capture is unchanged at 48/48:
2891- ///
2892- /// | clip | vs libaom before -> after | vs rav1e before -> after | wall ours |
2893- /// |---|---|---|---|
2894- /// | bars 1080p | +15.6% -> +15.6% | -1.7% -> -1.7% | 37.9s |
2895- /// | bars 2160p | +46.5% -> +46.5% | +18.8% -> +18.8% | 33.9s |
2896- /// | film A | +69.5% -> +69.0% | +37.7% -> +37.5% | 72s -> 64.4s |
2897- /// | film B | +102.4% -> +100.0% | +63.4% -> +61.5% | 72s -> 67.9s |
2898- /// | screen capture | +51.0% -> +51.0% | -14.5% -> -14.5% | 27.5s |
2899- ///
2900- /// Both bars rows and the capture are byte-identical across that change
2901- /// (their classification never moved); the palette search over film was
2902- /// costing roughly a tenth of the film rows' wall.
2903- ///
2904- /// CONFIRM RUN 2026-09-07 (lane-av1pyrdef), with the pyramid now the
2905- /// sequence path's default -- the four non-screen rows take `4:-16:8`,
2906- /// the capture is gated flat and does not move a byte:
2907- ///
2908- /// | clip | effective | flat -> default | vs rav1e | wall ours:libaom:rav1e |
2909- /// |---|---|---|---|---|
2910- /// | bars 1080p | 4:-16:8 | +16.4% -> +21.5% | -1.1% -> +3.7% | 37.8s:8.4s:16.4s |
2911- /// | bars 2160p | 4:-16:8 | +48.2% -> +48.3% | +20.4% -> +20.4% | 32.2s:5.6s:16.2s |
2912- /// | film A | 4:-16:8 | +62.8% -> +54.1% | +32.5% -> +24.2% | 58.9s:9.5s:13.6s |
2913- /// | film B | 4:-16:8 | +86.3% -> +82.6% | +50.5% -> +47.4% | 63.2s:18.7s:16.4s |
2914- /// | screen capture | none (gated) | +50.1% -> +50.1% | -15.4% -> -15.4% | 31.1s:8.4s:11.3s |
2915- ///
2916- /// Every row lands on lane-av1pyrgate's facade-arm number to the digit,
2917- /// which is the point of the shared driver: the two entry points code one
2918- /// stream. The bars rows are fixtures (recorded, never a decision); the
2919- /// two real films are what the pyramid ships for.
2920- ///
2921- /// All five gate clips are rows by default. `EC_AV1_NATIVE_FILM=1`,
2922- /// `EC_AV1_NATIVE_FILM4K=1` and `EC_AV1_NATIVE_SCREEN=1` select a subset:
2923- /// setting any one of them keeps only the selected rows (the two 1080p
2924- /// rows, the two 2160p rows, the capture row respectively). A missing
2925- /// real film SKIPs its row; it never fails the gate.
2926- #[test]
2927- #[ignore = "the native-resolution BD arm: minutes per row, needs ffmpeg"]
2928- fn bd_rate_screen_native() {
2929- let _knobs = crate::speed::knob_read();
2930- native_bd_arm("bd_rate_screen_native", 12, false);
2931- }
2932-
2933- /// The LONG-GOP arm of the native BD gate: the same recipe as
2934- /// [`bd_rate_screen_native`] over the two real film rows only, but 48
2935- /// pictures with `gop = 48` (`encode_sequence` sets `gop =
2936- /// pictures.len()`, and `external_ladder` passes ffmpeg `-g 48`, which
2937- /// reaches libaom as `--kf-max-dist=48` and rav1e as
2938- /// `key_frame_interval=48`), so every encoder sees one key frame and 47
2939- /// inter pictures.
2940- ///
2941- /// WHY IT EXISTS: `bd_rate_screen_native` codes 12 frames with `gop =
2942- /// 12`, and `Av1Encoder::encode_frames` cuts a mini-GOP at every key
2943- /// frame (`encoder.rs`), so ANY [`crate::encoder::Pyramid::mini_gop`]
2944- /// above 12 codes the same stream there -- the shipped `16` was measured
2945- /// as "one hidden ARF per 12-picture GOP", never as a real 16-picture
2946- /// group (class `instrument at bound` / `gate blind to feature`). The
2947- /// user's exports are long GOPs, so the pyramid shape is decided here.
2948- ///
2949- /// cargo test -p ec-av1 --release --lib -- --ignored \
2950- /// bd_rate_film_long_gop --nocapture
2951- ///
2952- /// `EC_AV1_NATIVE_FILM=1` keeps only film A, `EC_AV1_NATIVE_FILM4K=1`
2953- /// only film B; `EC_AV1_PYRAMID=<mini_gop>:<arf>:<leaf>` picks the shape.
2954- /// Read every row off the log's own "pyramid requested/effective" print,
2955- /// never off the argument order of the runs (lane-pyr3 misattributed
2956- /// three rows that way).
2957- ///
2958- /// Table: `lanes/pyr4.sweep.txt`.
2959- #[test]
2960- #[ignore = "the long-GOP native BD arm: ~7 minutes per film row, needs ffmpeg"]
2961- fn bd_rate_film_long_gop() {
2962- let _knobs = crate::speed::knob_write();
2963- native_bd_arm("bd_rate_film_long_gop", 48, true);
2964- }
2965-
2966- /// The shared driver of the two native BD arms above: `frames` pictures
2967- /// per row (the sequence's `gop` is the same number, so one key frame),
2968- /// four quantizers, `films_only` dropping every row but the two real
2969- /// films.
2970- pub(super) fn native_bd_arm(label: &str, frames: usize, films_only: bool) {
2971- if !have_ffmpeg() {
2972- eprintln!("SKIP {label}: no ffmpeg");
2973- return;
2974- }
2975- let mut clips = native_gate_clips();
2976- if films_only {
2977- clips.retain(|(name, _, _)| name.starts_with("film "));
2978- }
2979- if clips.is_empty() {
2980- eprintln!("SKIP {label}: no clip");
2981- return;
2982- }
2983-
2984- let aom_points: Vec<Vec<String>> = [5, 20, 35, 45]
2985- .iter()
2986- .map(|q| {
2987- ["-cpu-used", "6", "-b:v", "0", "-crf", &q.to_string()]
2988- .map(String::from)
2989- .to_vec()
crates/ec-av1/src/encode/tests.rsmodified+13 -252
@@ -1,4 +1,3 @@
1- use super::more_tests::*;
2 1
3 /// Every (site, frame type, block side) the census can be called with2 /// Every (site, frame type, block side) the census can be called with
4 /// lands in its own ten-counter bucket, inside the array (class3 /// lands in its own ten-counter bucket, inside the array (class
@@ -628,7 +627,6 @@
628 use super::*;627 use super::*;
629 use crate::intra::{D45_PRED, D135_PRED, H_PRED, KEY_FRAME_MODES, NON_DIRECTIONAL, V_PRED};628 use crate::intra::{D45_PRED, D135_PRED, H_PRED, KEY_FRAME_MODES, NON_DIRECTIONAL, V_PRED};
630 use crate::probe::run_with_stdin;629 use crate::probe::run_with_stdin;
631- use std::process::{Command, Stdio};
632 630
633 /// Every rectangular shape this decoder codes, at every position a block631 /// Every rectangular shape this decoder codes, at every position a block
634 /// of that shape can sit inside a 64x64 superblock: [`Reach::of_rect`]632 /// of that shape can sit inside a 64x64 superblock: [`Reach::of_rect`]
@@ -748,46 +746,10 @@
748 }746 }
749 }747 }
750 748
751- /// Whether ffmpeg is on PATH. Absence normally SKIPs, but
752- /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every
753- /// aomenc gate decodes its stream through ffmpeg and is meaningless
754- /// without it -- turns it into a hard failure. Without this the require
755- /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first
756- /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg
757- /// printed SKIP and reported green (class gate-skips-on-its-own-failure).
758- pub(super) fn have_ffmpeg() -> bool {
759- let present = Command::new("ffmpeg")
760- .arg("-version")
761- .stdout(Stdio::null())
762- .stderr(Stdio::null())
763- .status()
764- .is_ok_and(|s| s.success());
765- assert!(
766- present
767- || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none()
768- && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()),
769- "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH"
770- );
771- present
772- }
773-
774- /// Whether this ffmpeg was built with `encoder` (lane-pareto2: the
775- /// SVT-AV1 Pareto rows are skipped, never failed, on a build without it).
776- pub(super) fn have_encoder(encoder: &str) -> bool {
777- Command::new("ffmpeg")
778- .args(["-hide_banner", "-encoders"])
779- .stderr(Stdio::null()).output()
780- .is_ok_and(|o| {
781- String::from_utf8_lossy(&o.stdout)
782- .lines()
783- .any(|l| l.split_whitespace().nth(1) == Some(encoder))
784- })
785- }
786-
787 /// Decodes an AV1 OBU stream with ffmpeg and hands back the three planes.749 /// Decodes an AV1 OBU stream with ffmpeg and hands back the three planes.
788 pub(super) fn ffmpeg_decode(stream: &[u8], width: usize, height: usize) -> Picture {750 pub(super) fn ffmpeg_decode(stream: &[u8], width: usize, height: usize) -> Picture {
789 let out = run_with_stdin(751 let out = run_with_stdin(
790- Command::new("ffmpeg").args([752+ ec_testkit::ffmpeg().args([
791 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",753 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
792 ]),754 ]),
793 stream,755 stream,
@@ -953,10 +915,6 @@
953 assert_eq!(ours[0].u, encoded.reconstruction.u, "our decoder: U");915 assert_eq!(ours[0].u, encoded.reconstruction.u, "our decoder: U");
954 assert_eq!(ours[0].v, encoded.reconstruction.v, "our decoder: V");916 assert_eq!(ours[0].v, encoded.reconstruction.v, "our decoder: V");
955 917
956- if !have_ffmpeg() {
957- eprintln!("SKIP the ffmpeg half: no ffmpeg");
958- return;
959- }
960 let decoded = ffmpeg_decode(&encoded.stream, width, height);918 let decoded = ffmpeg_decode(&encoded.stream, width, height);
961 assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma");919 assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma");
962 assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U");920 assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U");
@@ -973,10 +931,6 @@
973 fn ffmpeg_decodes_exactly_what_the_encoder_reconstructed() {931 fn ffmpeg_decodes_exactly_what_the_encoder_reconstructed() {
974 let _knobs = crate::speed::knob_read();932 let _knobs = crate::speed::knob_read();
975 let fctx = &crate::decode::FrameCtx::for_encoder();933 let fctx = &crate::decode::FrameCtx::for_encoder();
976- if !have_ffmpeg() {
977- eprintln!("SKIP ffmpeg_decodes_exactly_what_the_encoder_reconstructed: no ffmpeg");
978- return;
979- }
980 for &(width, height) in &[934 for &(width, height) in &[
981 (64usize, 64usize),935 (64usize, 64usize),
982 (96, 64),936 (96, 64),
@@ -1096,10 +1050,6 @@
1096 assert_eq!(via_us[0].y, encoded.reconstruction.y, "our decoder: luma");1050 assert_eq!(via_us[0].y, encoded.reconstruction.y, "our decoder: luma");
1097 assert_eq!(via_us[0].u, encoded.reconstruction.u, "our decoder: U");1051 assert_eq!(via_us[0].u, encoded.reconstruction.u, "our decoder: U");
1098 assert_eq!(via_us[0].v, encoded.reconstruction.v, "our decoder: V");1052 assert_eq!(via_us[0].v, encoded.reconstruction.v, "our decoder: V");
1099- if !have_ffmpeg() {
1100- eprintln!("SKIP the ffmpeg half: no ffmpeg");
1101- return;
1102- }
1103 let decoded = ffmpeg_decode(&encoded.stream, width, height);1053 let decoded = ffmpeg_decode(&encoded.stream, width, height);
1104 assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma");1054 assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma");
1105 assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U");1055 assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U");
@@ -1158,7 +1108,7 @@
1158 "our decoder: GOP frame {i} luma"1108 "our decoder: GOP frame {i} luma"
1159 );1109 );
1160 }1110 }
1161- if have_ffmpeg() {1111+ {
1162 let ff = ffmpeg_decode_sequence(&gop.stream, width, height, moved.len());1112 let ff = ffmpeg_decode_sequence(&gop.stream, width, height, moved.len());
1163 assert_eq!(ff.len(), gop.frames.len(), "ffmpeg: GOP frame count");1113 assert_eq!(ff.len(), gop.frames.len(), "ffmpeg: GOP frame count");
1164 for (i, (theirs, frame)) in ff.iter().zip(gop.frames.iter()).enumerate() {1114 for (i, (theirs, frame)) in ff.iter().zip(gop.frames.iter()).enumerate() {
@@ -1415,70 +1365,6 @@
1415 eprintln!("{NAME}: {fired} chroma palette block(s) round-tripped");1365 eprintln!("{NAME}: {fired} chroma palette block(s) round-tripped");
1416 }1366 }
1417 1367
1418- /// The lane's keep-rule measurement: the gate's own screen capture, one
1419- /// KEY FRAME, coded with and without `allow_intrabc` at four quantizers.
1420- /// Setting the bit forces deblocking, CDEF and loop restoration off for
1421- /// that frame, so the table is exactly the filter loss against the bytes
1422- /// the copied blocks save.
1423- #[test]
1424- #[ignore = "needs the real-library manifest and ffmpeg"]
1425- fn probe_intrabc_key_frame() {
1426- let _knobs = crate::speed::knob_write();
1427- let fctx = &crate::decode::FrameCtx::for_encoder();
1428- // lane-av1clipprobe: the manifest is a real-library file, so it
1429- // resolves through the crate's one fixture root (EC_FIXTURES first)
1430- // and its absence is reported by the one probe instead of an inline
1431- // SKIP that named no path. A file that IS there but unreadable is not
1432- // an absence, so it is a hard error rather than a second silent skip.
1433- let Some(manifest_path) =
1434- crate::library_fixture::require("real-library-manifest.tsv", "probe_intrabc_key_frame")
1435- else {
1436- return;
1437- };
1438- let manifest = std::fs::read_to_string(&manifest_path).unwrap_or_else(|e| {
1439- panic!(
1440- "probe_intrabc_key_frame: {} is present but unreadable ({e})",
1441- manifest_path.display()
1442- )
1443- });
1444- let Some(clip) = manifest
1445- .lines()
1446- .skip(1)
1447- .filter_map(|l| l.split('\t').next())
1448- .find(|p| {
1449- p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists()
1450- })
1451- else {
1452- eprintln!("SKIP probe_intrabc_key_frame: no OBS recording");
1453- return;
1454- };
1455- let (width, height) = (1280usize, 768usize);
1456- let picture = clip_frame(clip, "0", width, height);
1457- eprintln!("| base_q_idx | intrabc | bytes | PSNR | blocks | searches/found/won |");
1458- for q in [5u8, 20, 35, 45] {
1459- for on in [false, true] {
1460- force_intrabc(Some(on));
1461- let _ = crate::tile::take_intrabc_hits();
1462- let _ = take_intrabc_search();
1463- let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
1464- let hits = crate::tile::take_intrabc_hits();
1465- let search = take_intrabc_search();
1466- eprintln!(
1467- "| {q} | {} | {} | {:.2} dB | {} (dv hist {:?}) | {}/{}/{} |",
1468- if encoded.allow_intrabc { "on" } else { "off" },
1469- encoded.stream.len(),
1470- psnr_all(&encoded.reconstruction, &picture),
1471- hits[0],
1472- &hits[1..],
1473- search[0],
1474- search[1],
1475- search[2],
1476- );
1477- }
1478- }
1479- force_intrabc(None);
1480- }
1481-
1482 /// lane-av1ibc's own end-to-end check: a repeated-pattern screen card1368 /// lane-av1ibc's own end-to-end check: a repeated-pattern screen card
1483 /// sets `allow_intrabc` (so every in-loop filter is off), blocks really1369 /// sets `allow_intrabc` (so every in-loop filter is off), blocks really
1484 /// take a block vector (fire count + DV histogram, class1370 /// take a block vector (fire count + DV histogram, class
@@ -1526,10 +1412,6 @@
1526 assert_eq!(via_us[0].y, encoded.reconstruction.y, "our decoder: luma");1412 assert_eq!(via_us[0].y, encoded.reconstruction.y, "our decoder: luma");
1527 assert_eq!(via_us[0].u, encoded.reconstruction.u, "our decoder: U");1413 assert_eq!(via_us[0].u, encoded.reconstruction.u, "our decoder: U");
1528 assert_eq!(via_us[0].v, encoded.reconstruction.v, "our decoder: V");1414 assert_eq!(via_us[0].v, encoded.reconstruction.v, "our decoder: V");
1529- if !have_ffmpeg() {
1530- eprintln!("SKIP the ffmpeg half: no ffmpeg");
1531- return;
1532- }
1533 let decoded = ffmpeg_decode(&encoded.stream, width, height);1415 let decoded = ffmpeg_decode(&encoded.stream, width, height);
1534 assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma");1416 assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma");
1535 assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U");1417 assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U");
@@ -1548,12 +1430,6 @@
1548 fn a_nearestmv_block_with_one_nonzero_coefficient_decodes_clean() {1430 fn a_nearestmv_block_with_one_nonzero_coefficient_decodes_clean() {
1549 let _knobs = crate::speed::knob_write();1431 let _knobs = crate::speed::knob_write();
1550 let fctx = &crate::decode::FrameCtx::for_encoder();1432 let fctx = &crate::decode::FrameCtx::for_encoder();
1551- if !have_ffmpeg() {
1552- eprintln!(
1553- "SKIP a_nearestmv_block_with_one_nonzero_coefficient_decodes_clean: no ffmpeg"
1554- );
1555- return;
1556- }
1557 let (width, height) = (64usize, 64usize);1433 let (width, height) = (64usize, 64usize);
1558 let picture = Picture::grey(width, height);1434 let picture = Picture::grey(width, height);
1559 let key = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();1435 let key = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
@@ -1649,7 +1525,7 @@
1649 ));1525 ));
1650 let _ = std::fs::remove_file(&path);1526 let _ = std::fs::remove_file(&path);
1651 std::fs::write(&path, stream).expect("writing the probe stream");1527 std::fs::write(&path, stream).expect("writing the probe stream");
1652- let out = Command::new("ffprobe")1528+ let out = ec_testkit::ffprobe()
1653 .args([1529 .args([
1654 "-v",1530 "-v",
1655 "error",1531 "error",
@@ -1720,10 +1596,6 @@
1720 fn a_frame_round_trips_at_its_own_size() {1596 fn a_frame_round_trips_at_its_own_size() {
1721 let _knobs = crate::speed::knob_read();1597 let _knobs = crate::speed::knob_read();
1722 let fctx = &crate::decode::FrameCtx::for_encoder();1598 let fctx = &crate::decode::FrameCtx::for_encoder();
1723- if !have_ffmpeg() {
1724- eprintln!("SKIP a_frame_round_trips_at_its_own_size: no ffmpeg");
1725- return;
1726- }
1727 // 854x480 is covered separately by1599 // 854x480 is covered separately by
1728 // `an_854x480_picture_round_trips_through_its_padding`, which its own1600 // `an_854x480_picture_round_trips_through_its_padding`, which its own
1729 // doc comment explains was worth keeping as its own test.1601 // doc comment explains was worth keeping as its own test.
@@ -1787,9 +1659,6 @@
1787 fn an_854x480_picture_round_trips_through_its_padding() {1659 fn an_854x480_picture_round_trips_through_its_padding() {
1788 let _knobs = crate::speed::knob_read();1660 let _knobs = crate::speed::knob_read();
1789 let fctx = &crate::decode::FrameCtx::for_encoder();1661 let fctx = &crate::decode::FrameCtx::for_encoder();
1790- if !have_ffmpeg() {
1791- return;
1792- }
1793 let (width, height) = (854usize, 480usize);1662 let (width, height) = (854usize, 480usize);
1794 let picture = test_card(width, height);1663 let picture = test_card(width, height);
1795 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();1664 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
@@ -2096,10 +1965,6 @@
2096 fn sequence_round_trips_at_a_non_multiple_size() {1965 fn sequence_round_trips_at_a_non_multiple_size() {
2097 let _knobs = crate::speed::knob_read();1966 let _knobs = crate::speed::knob_read();
2098 let fctx = &crate::decode::FrameCtx::for_encoder();1967 let fctx = &crate::decode::FrameCtx::for_encoder();
2099- if !have_ffmpeg() {
2100- eprintln!("SKIP sequence_round_trips_at_a_non_multiple_size: no ffmpeg");
2101- return;
2102- }
2103 let (width, height) = (160usize, 96usize);1968 let (width, height) = (160usize, 96usize);
2104 let pictures: Vec<Picture> = (0..3)1969 let pictures: Vec<Picture> = (0..3)
2105 .map(|i| panned_test_card(width, height, i * 3))1970 .map(|i| panned_test_card(width, height, i * 3))
@@ -2140,10 +2005,6 @@
2140 fn a_sequence_round_trips_at_the_exactly_half_straddle_size() {2005 fn a_sequence_round_trips_at_the_exactly_half_straddle_size() {
2141 let _knobs = crate::speed::knob_read();2006 let _knobs = crate::speed::knob_read();
2142 let fctx = &crate::decode::FrameCtx::for_encoder();2007 let fctx = &crate::decode::FrameCtx::for_encoder();
2143- if !have_ffmpeg() {
2144- eprintln!("SKIP a_sequence_round_trips_at_the_exactly_half_straddle_size: no ffmpeg");
2145- return;
2146- }
2147 let (width, height) = (1280usize, 720usize);2008 let (width, height) = (1280usize, 720usize);
2148 let pictures: Vec<Picture> = (0..3)2009 let pictures: Vec<Picture> = (0..3)
2149 .map(|i| panned_test_card(width, height, i * 3))2010 .map(|i| panned_test_card(width, height, i * 3))
@@ -2207,13 +2068,6 @@
2207 fn a_640x360_half_straddle_round_trips_through_ffmpeg_across_three_frames() {2068 fn a_640x360_half_straddle_round_trips_through_ffmpeg_across_three_frames() {
2208 let _knobs = crate::speed::knob_read();2069 let _knobs = crate::speed::knob_read();
2209 let fctx = &crate::decode::FrameCtx::for_encoder();2070 let fctx = &crate::decode::FrameCtx::for_encoder();
2210- if !have_ffmpeg() {
2211- eprintln!(
2212- "SKIP a_640x360_half_straddle_round_trips_through_ffmpeg_across_three_frames: \
2213- no ffmpeg"
2214- );
2215- return;
2216- }
2217 let (width, height) = (640usize, 360usize);2071 let (width, height) = (640usize, 360usize);
2218 for shift in [0i64, 7, 19] {2072 for shift in [0i64, 7, 19] {
2219 let picture = panned_test_card(width, height, shift);2073 let picture = panned_test_card(width, height, shift);
@@ -2233,12 +2087,6 @@
2233 fn a_640x360_half_straddle_sequence_round_trips_through_ffmpeg() {2087 fn a_640x360_half_straddle_sequence_round_trips_through_ffmpeg() {
2234 let _knobs = crate::speed::knob_read();2088 let _knobs = crate::speed::knob_read();
2235 let fctx = &crate::decode::FrameCtx::for_encoder();2089 let fctx = &crate::decode::FrameCtx::for_encoder();
2236- if !have_ffmpeg() {
2237- eprintln!(
2238- "SKIP a_640x360_half_straddle_sequence_round_trips_through_ffmpeg: no ffmpeg"
2239- );
2240- return;
2241- }
2242 let (width, height) = (640usize, 360usize);2090 let (width, height) = (640usize, 360usize);
2243 let pictures: Vec<Picture> = (0..4)2091 let pictures: Vec<Picture> = (0..4)
2244 .map(|i| panned_test_card(width, height, i * 3))2092 .map(|i| panned_test_card(width, height, i * 3))
@@ -2259,7 +2107,7 @@
2259 2107
2260 /// One frame of a real clip, scaled to a whole number of 32x32 blocks.2108 /// One frame of a real clip, scaled to a whole number of 32x32 blocks.
2261 pub(super) fn clip_frame(clip: &str, skip: &str, width: usize, height: usize) -> Picture {2109 pub(super) fn clip_frame(clip: &str, skip: &str, width: usize, height: usize) -> Picture {
2262- let out = Command::new("ffmpeg")2110+ let out = ec_testkit::ffmpeg()
2263 .args(["-v", "error", "-ss", skip, "-i", clip, "-frames:v", "1"])2111 .args(["-v", "error", "-ss", skip, "-i", clip, "-frames:v", "1"])
2264 .args(["-vf", &format!("scale={width}:{height}")])2112 .args(["-vf", &format!("scale={width}:{height}")])
2265 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]).output()2113 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]).output()
@@ -2451,10 +2299,6 @@
2451 fn every_mode_decodes_to_what_the_encoder_predicted() {2299 fn every_mode_decodes_to_what_the_encoder_predicted() {
2452 let _knobs = crate::speed::knob_write();2300 let _knobs = crate::speed::knob_write();
2453 let fctx = &crate::decode::FrameCtx::for_encoder();2301 let fctx = &crate::decode::FrameCtx::for_encoder();
2454- if !have_ffmpeg() {
2455- eprintln!("SKIP every_mode_decodes_to_what_the_encoder_predicted: no ffmpeg");
2456- return;
2457- }
2458 // A mode ablation measures the MODE search: a filter-intra block is2302 // A mode ablation measures the MODE search: a filter-intra block is
2459 // coded `DC_PRED` whatever mode the arm forces, so it would fail the2303 // coded `DC_PRED` whatever mode the arm forces, so it would fail the
2460 // "the encoder coded something else" check for a reason that is not2304 // "the encoder coded something else" check for a reason that is not
@@ -3000,10 +2844,6 @@
3000 fn a_single_axis_straddle_round_trips_through_ffmpeg() {2844 fn a_single_axis_straddle_round_trips_through_ffmpeg() {
3001 let _knobs = crate::speed::knob_read();2845 let _knobs = crate::speed::knob_read();
3002 let fctx = &crate::decode::FrameCtx::for_encoder();2846 let fctx = &crate::decode::FrameCtx::for_encoder();
3003- if !have_ffmpeg() {
3004- eprintln!("SKIP a_single_axis_straddle_round_trips_through_ffmpeg: no ffmpeg");
3005- return;
3006- }
3007 let (width, height) = (40usize, 32usize);2847 let (width, height) = (40usize, 32usize);
3008 let picture = test_card(width, height);2848 let picture = test_card(width, height);
3009 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();2849 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
@@ -3020,47 +2860,6 @@
3020 assert_eq!(decoded.v, encoded.reconstruction.v, "V");2860 assert_eq!(decoded.v, encoded.reconstruction.v, "V");
3021 }2861 }
3022 2862
3023- /// A frame of real video, rather than a picture built to be easy.
3024- ///
3025- /// `EC_AV1_CLIP` names the clip and `EC_AV1_CLIP_SKIP` how far into it to
3026- /// seek; ffmpeg decodes one frame, crops it to the block grid, and the
3027- /// encoder's reconstruction has to survive the same equality gate as the
3028- /// synthetic pictures — real video reaches contexts a test card does not.
3029- #[test]
3030- fn a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed() {
3031- let _knobs = crate::speed::knob_read();
3032- let fctx = &crate::decode::FrameCtx::for_encoder();
3033- let Ok(clip) = std::env::var("EC_AV1_CLIP") else {
3034- eprintln!(
3035- "SKIP a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed: \
3036- set EC_AV1_CLIP to a clip"
3037- );
3038- return;
3039- };
3040- if !have_ffmpeg() {
3041- eprintln!(
3042- "SKIP a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed: no ffmpeg"
3043- );
3044- return;
3045- }
3046- let skip = std::env::var("EC_AV1_CLIP_SKIP").unwrap_or_else(|_| "0".into());
3047- // A 4:2:0 frame cropped to whole 32x32 blocks, in a size that keeps the
3048- // test quick while still spanning many superblocks.
3049- let (width, height) = (640usize, 352usize);
3050- let picture = clip_frame(&clip, &skip, width, height);
3051-
3052- let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
3053- let decoded = ffmpeg_decode(&encoded.stream, width, height);
3054- assert_eq!(decoded.y, encoded.reconstruction.y, "luma");
3055- assert_eq!(decoded.u, encoded.reconstruction.u, "U");
3056- assert_eq!(decoded.v, encoded.reconstruction.v, "V");
3057- eprintln!(
3058- "{} bytes, luma PSNR {:.2} dB",
3059- encoded.stream.len(),
3060- psnr(&decoded.y, &picture.y)
3061- );
3062- }
3063-
3064 /// [`test_card`], panned `shift` samples to the right (wrapping), so a2863 /// [`test_card`], panned `shift` samples to the right (wrapping), so a
3065 /// sequence of these is a translation a motion search can actually find2864 /// sequence of these is a translation a motion search can actually find
3066 /// — the content [`test_card`] itself draws, not a fresh pattern, so an2865 /// — the content [`test_card`] itself draws, not a fresh pattern, so an
@@ -3103,7 +2902,7 @@
3103 frames: usize,2902 frames: usize,
3104 ) -> Vec<Picture> {2903 ) -> Vec<Picture> {
3105 let out = run_with_stdin(2904 let out = run_with_stdin(
3106- Command::new("ffmpeg").args([2905+ ec_testkit::ffmpeg().args([
3107 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",2906 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
3108 ]),2907 ]),
3109 stream,2908 stream,
@@ -3154,12 +2953,6 @@
3154 fn every_frame_of_a_sequence_decodes_to_what_the_encoder_reconstructed() {2953 fn every_frame_of_a_sequence_decodes_to_what_the_encoder_reconstructed() {
3155 let _knobs = crate::speed::knob_read();2954 let _knobs = crate::speed::knob_read();
3156 let fctx = &crate::decode::FrameCtx::for_encoder();2955 let fctx = &crate::decode::FrameCtx::for_encoder();
3157- if !have_ffmpeg() {
3158- eprintln!(
3159- "SKIP every_frame_of_a_sequence_decodes_to_what_the_encoder_reconstructed: no ffmpeg"
3160- );
3161- return;
3162- }
3163 let (width, height) = (128usize, 64usize);2956 let (width, height) = (128usize, 64usize);
3164 let pictures: Vec<Picture> = (0..5)2957 let pictures: Vec<Picture> = (0..5)
3165 .map(|i| panned_test_card(width, height, i * 3))2958 .map(|i| panned_test_card(width, height, i * 3))
@@ -3240,10 +3033,6 @@
3240 /// Runs only inside `superblock_size_global_suite`.3033 /// Runs only inside `superblock_size_global_suite`.
3241 fn a_128_superblock_clip_whose_root_search_codes_128x128_blocks_decodes_exact() {3034 fn a_128_superblock_clip_whose_root_search_codes_128x128_blocks_decodes_exact() {
3242 let _knobs = crate::speed::knob_write();3035 let _knobs = crate::speed::knob_write();
3243- if !have_ffmpeg() {
3244- eprintln!("SKIP: no ffmpeg");
3245- return;
3246- }
3247 force_sb128(true);3036 force_sb128(true);
3248 let dir = std::env::temp_dir().join(format!("ec-av1-b128-{}", std::process::id()));3037 let dir = std::env::temp_dir().join(format!("ec-av1-b128-{}", std::process::id()));
3249 std::fs::create_dir_all(&dir).unwrap();3038 std::fs::create_dir_all(&dir).unwrap();
@@ -3251,7 +3040,7 @@
3251 // A slow horizontal pan over a still pattern: whole 128x128 regions3040 // A slow horizontal pan over a still pattern: whole 128x128 regions
3252 // share one motion vector, which is exactly what a 128 root can code3041 // share one motion vector, which is exactly what a 128 root can code
3253 // as one block and four 64 roots cannot.3042 // as one block and four 64 roots cannot.
3254- let ok = Command::new("ffmpeg")3043+ let ok = ec_testkit::ffmpeg()
3255 .args(["-v", "error", "-y", "-f", "lavfi"])3044 .args(["-v", "error", "-y", "-f", "lavfi"])
3256 .args(["-i", "smptebars=size=1600x768:rate=24"])3045 .args(["-i", "smptebars=size=1600x768:rate=24"])
3257 .args(["-vf", "crop=1280:768:'min(n*2,300)':0", "-frames:v", "8"])3046 .args(["-vf", "crop=1280:768:'min(n*2,300)':0", "-frames:v", "8"])
@@ -3339,15 +3128,11 @@
3339 /// Runs only inside `superblock_size_global_suite`.3128 /// Runs only inside `superblock_size_global_suite`.
3340 fn a_128_root_block_with_a_real_residual_decodes_exact_through_both_decoders() {3129 fn a_128_root_block_with_a_real_residual_decodes_exact_through_both_decoders() {
3341 let _knobs = crate::speed::knob_write();3130 let _knobs = crate::speed::knob_write();
3342- if !have_ffmpeg() {
3343- eprintln!("SKIP: no ffmpeg");
3344- return;
3345- }
3346 force_sb128(true);3131 force_sb128(true);
3347 let dir = std::env::temp_dir().join(format!("ec-av1-b128r-{}", std::process::id()));3132 let dir = std::env::temp_dir().join(format!("ec-av1-b128r-{}", std::process::id()));
3348 std::fs::create_dir_all(&dir).unwrap();3133 std::fs::create_dir_all(&dir).unwrap();
3349 let clip = dir.join("smpte-pan-1280x768.y4m");3134 let clip = dir.join("smpte-pan-1280x768.y4m");
3350- let ok = Command::new("ffmpeg")3135+ let ok = ec_testkit::ffmpeg()
3351 .args(["-v", "error", "-y", "-f", "lavfi"])3136 .args(["-v", "error", "-y", "-f", "lavfi"])
3352 .args(["-i", "smptebars=size=1600x768:rate=24"])3137 .args(["-i", "smptebars=size=1600x768:rate=24"])
3353 .args(["-vf", "crop=1280:768:'min(n*2,300)':0", "-frames:v", "8"])3138 .args(["-vf", "crop=1280:768:'min(n*2,300)':0", "-frames:v", "8"])
@@ -3433,17 +3218,13 @@
3433 /// Runs only inside `superblock_size_global_suite`.3218 /// Runs only inside `superblock_size_global_suite`.
3434 fn a_128_root_residual_block_under_a_per_unit_cdef_list_decodes_exact() {3219 fn a_128_root_residual_block_under_a_per_unit_cdef_list_decodes_exact() {
3435 let _knobs = crate::speed::knob_write();3220 let _knobs = crate::speed::knob_write();
3436- if !have_ffmpeg() {
3437- eprintln!("SKIP: no ffmpeg");
3438- return;
3439- }
3440 force_sb128(true);3221 force_sb128(true);
3441 let dir = std::env::temp_dir().join(format!("ec-av1-edge128-{}", std::process::id()));3222 let dir = std::env::temp_dir().join(format!("ec-av1-edge128-{}", std::process::id()));
3442 std::fs::create_dir_all(&dir).unwrap();3223 std::fs::create_dir_all(&dir).unwrap();
3443 let clip = dir.join("testsrc2-1280x768.y4m");3224 let clip = dir.join("testsrc2-1280x768.y4m");
3444 // Detailed synthetic content: its CDEF search spends more than one3225 // Detailed synthetic content: its CDEF search spends more than one
3445 // strength pair, which is what puts a `cdef_idx` literal in the tile.3226 // strength pair, which is what puts a `cdef_idx` literal in the tile.
3446- let ok = Command::new("ffmpeg")3227+ let ok = ec_testkit::ffmpeg()
3447 .args(["-v", "error", "-y", "-f", "lavfi"])3228 .args(["-v", "error", "-y", "-f", "lavfi"])
3448 .args(["-i", "testsrc2=size=1280x768:rate=24"])3229 .args(["-i", "testsrc2=size=1280x768:rate=24"])
3449 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])3230 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
@@ -3519,15 +3300,11 @@
3519 /// Runs only inside `superblock_size_global_suite`.3300 /// Runs only inside `superblock_size_global_suite`.
3520 fn a_rect128_half_with_a_real_residual_decodes_exact_through_both_decoders() {3301 fn a_rect128_half_with_a_real_residual_decodes_exact_through_both_decoders() {
3521 let _knobs = crate::speed::knob_write();3302 let _knobs = crate::speed::knob_write();
3522- if !have_ffmpeg() {
3523- eprintln!("SKIP: no ffmpeg");
3524- return;
3525- }
3526 force_sb128(true);3303 force_sb128(true);
3527 let dir = std::env::temp_dir().join(format!("ec-av1-rectres-{}", std::process::id()));3304 let dir = std::env::temp_dir().join(format!("ec-av1-rectres-{}", std::process::id()));
3528 std::fs::create_dir_all(&dir).unwrap();3305 std::fs::create_dir_all(&dir).unwrap();
3529 let clip = dir.join("smpte-pan-1280x768.y4m");3306 let clip = dir.join("smpte-pan-1280x768.y4m");
3530- let ok = Command::new("ffmpeg")3307+ let ok = ec_testkit::ffmpeg()
3531 .args(["-v", "error", "-y", "-f", "lavfi"])3308 .args(["-v", "error", "-y", "-f", "lavfi"])
3532 .args(["-i", "smptebars=size=1600x768:rate=24"])3309 .args(["-i", "smptebars=size=1600x768:rate=24"])
3533 .args(["-vf", "crop=1280:768:'min(n*2,300)':0", "-frames:v", "8"])3310 .args(["-vf", "crop=1280:768:'min(n*2,300)':0", "-frames:v", "8"])
@@ -3603,15 +3380,11 @@
3603 /// Runs only inside `superblock_size_global_suite`.3380 /// Runs only inside `superblock_size_global_suite`.
3604 fn an_ab128_piece_with_a_real_residual_decodes_exact_through_both_decoders() {3381 fn an_ab128_piece_with_a_real_residual_decodes_exact_through_both_decoders() {
3605 let _knobs = crate::speed::knob_write();3382 let _knobs = crate::speed::knob_write();
3606- if !have_ffmpeg() {
3607- eprintln!("SKIP: no ffmpeg");
3608- return;
3609- }
3610 force_sb128(true);3383 force_sb128(true);
3611 let dir = std::env::temp_dir().join(format!("ec-av1-rectres-ab-{}", std::process::id()));3384 let dir = std::env::temp_dir().join(format!("ec-av1-rectres-ab-{}", std::process::id()));
3612 std::fs::create_dir_all(&dir).unwrap();3385 std::fs::create_dir_all(&dir).unwrap();
3613 let clip = dir.join("testsrc2-1280x768.y4m");3386 let clip = dir.join("testsrc2-1280x768.y4m");
3614- let ok = Command::new("ffmpeg")3387+ let ok = ec_testkit::ffmpeg()
3615 .args(["-v", "error", "-y", "-f", "lavfi"])3388 .args(["-v", "error", "-y", "-f", "lavfi"])
3616 .args(["-i", "testsrc2=size=1280x768:rate=24"])3389 .args(["-i", "testsrc2=size=1280x768:rate=24"])
3617 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])3390 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
@@ -3687,17 +3460,13 @@
3687 /// Runs only inside `superblock_size_global_suite`.3460 /// Runs only inside `superblock_size_global_suite`.
3688 fn a_rect128_residual_half_under_a_per_unit_cdef_list_decodes_exact() {3461 fn a_rect128_residual_half_under_a_per_unit_cdef_list_decodes_exact() {
3689 let _knobs = crate::speed::knob_write();3462 let _knobs = crate::speed::knob_write();
3690- if !have_ffmpeg() {
3691- eprintln!("SKIP: no ffmpeg");
3692- return;
3693- }
3694 force_sb128(true);3463 force_sb128(true);
3695 let dir = std::env::temp_dir().join(format!("ec-av1-rectres-cdef-{}", std::process::id()));3464 let dir = std::env::temp_dir().join(format!("ec-av1-rectres-cdef-{}", std::process::id()));
3696 std::fs::create_dir_all(&dir).unwrap();3465 std::fs::create_dir_all(&dir).unwrap();
3697 let clip = dir.join("testsrc2-1280x768.y4m");3466 let clip = dir.join("testsrc2-1280x768.y4m");
3698 // Detailed synthetic content: its CDEF search spends more than one3467 // Detailed synthetic content: its CDEF search spends more than one
3699 // strength pair, which is what puts a `cdef_idx` literal in the tile.3468 // strength pair, which is what puts a `cdef_idx` literal in the tile.
3700- let ok = Command::new("ffmpeg")3469+ let ok = ec_testkit::ffmpeg()
3701 .args(["-v", "error", "-y", "-f", "lavfi"])3470 .args(["-v", "error", "-y", "-f", "lavfi"])
3702 .args(["-i", "testsrc2=size=1280x768:rate=24"])3471 .args(["-i", "testsrc2=size=1280x768:rate=24"])
3703 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])3472 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
@@ -3767,10 +3536,6 @@
3767 /// Runs only inside `superblock_size_global_suite`.3536 /// Runs only inside `superblock_size_global_suite`.
3768 fn a_128_root_compound_block_decodes_exact_through_both_decoders() {3537 fn a_128_root_compound_block_decodes_exact_through_both_decoders() {
3769 let _knobs = crate::speed::knob_write();3538 let _knobs = crate::speed::knob_write();
3770- if !have_ffmpeg() {
3771- eprintln!("SKIP: no ffmpeg");
3772- return;
3773- }
3774 force_sb128(true);3539 force_sb128(true);
3775 let dir = std::env::temp_dir().join(format!("ec-av1-b128c-{}", std::process::id()));3540 let dir = std::env::temp_dir().join(format!("ec-av1-b128c-{}", std::process::id()));
3776 std::fs::create_dir_all(&dir).unwrap();3541 std::fs::create_dir_all(&dir).unwrap();
@@ -3778,7 +3543,7 @@
3778 // Moving objects that occlude each other: a pan is coded by one3543 // Moving objects that occlude each other: a pan is coded by one
3779 // reference outright, and a compound pair only pays where the two3544 // reference outright, and a compound pair only pays where the two
3780 // references disagree.3545 // references disagree.
3781- let ok = Command::new("ffmpeg")3546+ let ok = ec_testkit::ffmpeg()
3782 .args(["-v", "error", "-y", "-f", "lavfi"])3547 .args(["-v", "error", "-y", "-f", "lavfi"])
3783 .args(["-i", "testsrc2=size=1280x768:rate=24"])3548 .args(["-i", "testsrc2=size=1280x768:rate=24"])
3784 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])3549 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
@@ -3858,15 +3623,11 @@
3858 /// Runs only inside `superblock_size_global_suite`.3623 /// Runs only inside `superblock_size_global_suite`.
3859 fn a_128_root_horz_and_vert_halves_decode_exact_through_both_decoders() {3624 fn a_128_root_horz_and_vert_halves_decode_exact_through_both_decoders() {
3860 let _knobs = crate::speed::knob_write();3625 let _knobs = crate::speed::knob_write();
3861- if !have_ffmpeg() {
3862- eprintln!("SKIP: no ffmpeg");
3863- return;
3864- }
3865 force_sb128(true);3626 force_sb128(true);
3866 let dir = std::env::temp_dir().join(format!("ec-av1-b128hv-{}", std::process::id()));3627 let dir = std::env::temp_dir().join(format!("ec-av1-b128hv-{}", std::process::id()));
3867 std::fs::create_dir_all(&dir).unwrap();3628 std::fs::create_dir_all(&dir).unwrap();
3868 let clip = dir.join("testsrc2-1280x768.y4m");3629 let clip = dir.join("testsrc2-1280x768.y4m");
3869- let ok = Command::new("ffmpeg")3630+ let ok = ec_testkit::ffmpeg()
3870 .args(["-v", "error", "-y", "-f", "lavfi"])3631 .args(["-v", "error", "-y", "-f", "lavfi"])
3871 .args(["-i", "testsrc2=size=1280x768:rate=24"])3632 .args(["-i", "testsrc2=size=1280x768:rate=24"])
3872 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])3633 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
crates/ec-av1/src/encoder/tests.rsmodified+26 -174
@@ -1,28 +1,4 @@
1 use super::*;1 use super::*;
2- use std::process::{Command, Stdio};
3-
4- /// Whether ffmpeg is on PATH. Absence normally SKIPs, but
5- /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every
6- /// aomenc gate decodes its stream through ffmpeg and is meaningless
7- /// without it -- turns it into a hard failure. Without this the require
8- /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first
9- /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg
10- /// printed SKIP and reported green (class gate-skips-on-its-own-failure).
11- fn have_ffmpeg() -> bool {
12- let present = Command::new("ffmpeg")
13- .arg("-version")
14- .stdout(Stdio::null())
15- .stderr(Stdio::null())
16- .status()
17- .is_ok_and(|s| s.success());
18- assert!(
19- present
20- || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none()
21- && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()),
22- "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH"
23- );
24- present
25- }
26 2
27 fn test_card(width: usize, height: usize, shift: usize) -> Picture {3 fn test_card(width: usize, height: usize, shift: usize) -> Picture {
28 let mut picture = Picture::grey(width, height);4 let mut picture = Picture::grey(width, height);
@@ -332,7 +308,7 @@
332 fn the_facade_codes_the_same_bytes_as_encode_sequence() {308 fn the_facade_codes_the_same_bytes_as_encode_sequence() {
333 let _knobs = crate::speed::knob_read();309 let _knobs = crate::speed::knob_read();
334 let frames = 12usize;310 let frames = 12usize;
335- let film = h264_clip_frames("the facade identity film arm", 640, 384, frames)311+ let film = h264_clip_frames(640, 384, frames)
336 .unwrap_or_else(|| {312 .unwrap_or_else(|| {
337 // The probe inside already printed the ONE line naming the313 // The probe inside already printed the ONE line naming the
338 // resolved path and the escape hatch, so this is a note about314 // resolved path and the escape hatch, so this is a note about
@@ -489,7 +465,7 @@
489 std::ptr::addr_of!(stream) as usize465 std::ptr::addr_of!(stream) as usize
490 ));466 ));
491 std::fs::write(&path, stream).expect("writing the probe stream");467 std::fs::write(&path, stream).expect("writing the probe stream");
492- let out = Command::new("ffprobe")468+ let out = ec_testkit::ffprobe()
493 .args([469 .args([
494 "-v",470 "-v",
495 "error",471 "error",
@@ -529,7 +505,7 @@
529 std::ptr::addr_of!(stream) as usize505 std::ptr::addr_of!(stream) as usize
530 ));506 ));
531 std::fs::write(&path, stream).expect("writing the probe stream");507 std::fs::write(&path, stream).expect("writing the probe stream");
532- let out = Command::new("ffprobe")508+ let out = ec_testkit::ffprobe()
533 .args([509 .args([
534 "-v",510 "-v",
535 "error",511 "error",
@@ -560,10 +536,6 @@
560 #[test]536 #[test]
561 fn thirty_pictures_at_gop_fifteen_decode_to_two_key_frames() {537 fn thirty_pictures_at_gop_fifteen_decode_to_two_key_frames() {
562 let _knobs = crate::speed::knob_read();538 let _knobs = crate::speed::knob_read();
563- if !have_ffmpeg() {
564- eprintln!("SKIP thirty_pictures_at_gop_fifteen_decode_to_two_key_frames: no ffmpeg");
565- return;
566- }
567 let (width, height) = (96usize, 96usize);539 let (width, height) = (96usize, 96usize);
568 let config = EncoderConfig {540 let config = EncoderConfig {
569 width,541 width,
@@ -616,10 +588,6 @@
616 #[test]588 #[test]
617 fn bt709_limited_colour_is_reported_by_ffprobe() {589 fn bt709_limited_colour_is_reported_by_ffprobe() {
618 let _knobs = crate::speed::knob_read();590 let _knobs = crate::speed::knob_read();
619- if !have_ffmpeg() {
620- eprintln!("SKIP bt709_limited_colour_is_reported_by_ffprobe: no ffmpeg");
621- return;
622- }
623 let config = EncoderConfig {591 let config = EncoderConfig {
624 width: 64,592 width: 64,
625 height: 64,593 height: 64,
@@ -641,10 +609,6 @@
641 #[test]609 #[test]
642 fn bt601_limited_colour_is_reported_by_ffprobe() {610 fn bt601_limited_colour_is_reported_by_ffprobe() {
643 let _knobs = crate::speed::knob_read();611 let _knobs = crate::speed::knob_read();
644- if !have_ffmpeg() {
645- eprintln!("SKIP bt601_limited_colour_is_reported_by_ffprobe: no ffmpeg");
646- return;
647- }
648 let config = EncoderConfig {612 let config = EncoderConfig {
649 width: 64,613 width: 64,
650 height: 64,614 height: 64,
@@ -715,15 +679,10 @@
715 /// `EC_AV1_REQUIRE_FFMPEG` / `EC_AV1_REQUIRE_AOMENC` and otherwise prints679 /// `EC_AV1_REQUIRE_FFMPEG` / `EC_AV1_REQUIRE_AOMENC` and otherwise prints
716 /// that ONE line.680 /// that ONE line.
717 fn h264_clip_frames(681 fn h264_clip_frames(
718- what: &str,
719 width: usize,682 width: usize,
720 height: usize,683 height: usize,
721 frames: usize,684 frames: usize,
722 ) -> Option<Vec<Picture>> {685 ) -> Option<Vec<Picture>> {
723- if !have_ffmpeg() {
724- eprintln!("SKIP {what}: no ffmpeg");
725- return None;
726- }
727 // lane-av1speed3: the wall tables below are read on REAL film as686 // lane-av1speed3: the wall tables below are read on REAL film as
728 // well as on the colour-bar fixture (`bars` vs `film` in the BD687 // well as on the colour-bar fixture (`bars` vs `film` in the BD
729 // gate's own vocabulary), and the film crop lives outside the repo --688 // gate's own vocabulary), and the film crop lives outside the repo --
@@ -737,15 +696,14 @@
737 // pointing EC_FIXTURES somewhere the gates do not read.696 // pointing EC_FIXTURES somewhere the gates do not read.
738 let clip = match std::env::var("EC_AV1_WALL_CLIP") {697 let clip = match std::env::var("EC_AV1_WALL_CLIP") {
739 Ok(p) => std::path::PathBuf::from(p),698 Ok(p) => std::path::PathBuf::from(p),
740- Err(_) => crate::library_fixture::path("video/h264-1080p-23.976-8bit.mp4"),699+ Err(_) => ec_testkit::fixture("open/sintel_trailer-1080p.mp4"),
741 };700 };
742 // `what` is the CALLING GATE's name, carried in so that both exits from701 // `what` is the CALLING GATE's name, carried in so that both exits from
743 // this function print exactly one line naming it: the ffmpeg line702 // this function print exactly one line naming it: the ffmpeg line
744 // above, and the probe's line naming the resolved path. Callers703 // above, and the probe's line naming the resolved path. Callers
745 // therefore `return` on `None` WITHOUT printing a second one -- the704 // therefore `return` on `None` WITHOUT printing a second one -- the
746 // second "no fixture" line per gate was the noise that hid this defect.705 // second "no fixture" line per gate was the noise that hid this defect.
747- let clip = crate::library_fixture::require_at(clip, what)?;706+ let out = ec_testkit::ffmpeg()
748- let out = Command::new("ffmpeg")
749 .args(["-v", "error", "-i", clip.to_str().unwrap()])707 .args(["-v", "error", "-i", clip.to_str().unwrap()])
750 .args(["-frames:v", &frames.to_string()])708 .args(["-frames:v", &frames.to_string()])
751 .args(["-vf", &format!("scale={width}:{height}")])709 .args(["-vf", &format!("scale={width}:{height}")])
@@ -792,9 +750,7 @@
792 #[test]750 #[test]
793 fn bytes_per_frame_target_settles_within_20_percent() {751 fn bytes_per_frame_target_settles_within_20_percent() {
794 let _knobs = crate::speed::knob_read();752 let _knobs = crate::speed::knob_read();
795- let Some(pictures) = h264_clip_frames(753+ let Some(pictures) = h264_clip_frames(640,
796- "bytes_per_frame_target_settles_within_20_percent",
797- 640,
798 384,754 384,
799 24,755 24,
800 ) else {756 ) else {
@@ -973,9 +929,7 @@
973 fn bitrate_target_lands_within_5_percent_over_48_frames() {929 fn bitrate_target_lands_within_5_percent_over_48_frames() {
974 let _knobs = crate::speed::knob_read();930 let _knobs = crate::speed::knob_read();
975 let (width, height, frames) = (640usize, 384usize, 48usize);931 let (width, height, frames) = (640usize, 384usize, 48usize);
976- let Some(pictures) = h264_clip_frames(932+ let Some(pictures) = h264_clip_frames(width,
977- "bitrate_target_lands_within_5_percent_over_48_frames",
978- width,
979 height,933 height,
980 frames,934 frames,
981 ) else {935 ) else {
@@ -1140,9 +1094,7 @@
1140 #[test]1094 #[test]
1141 fn bytes_per_frame_controller_never_oscillates_past_its_clamp() {1095 fn bytes_per_frame_controller_never_oscillates_past_its_clamp() {
1142 let _knobs = crate::speed::knob_read();1096 let _knobs = crate::speed::knob_read();
1143- let Some(pictures) = h264_clip_frames(1097+ let Some(pictures) = h264_clip_frames(640,
1144- "bytes_per_frame_controller_never_oscillates_past_its_clamp",
1145- 640,
1146 384,1098 384,
1147 24,1099 24,
1148 ) else {1100 ) else {
@@ -1217,7 +1169,7 @@
1217 std::ptr::addr_of!(stream) as usize1169 std::ptr::addr_of!(stream) as usize
1218 ));1170 ));
1219 std::fs::write(&path, stream).expect("writing the decode probe stream");1171 std::fs::write(&path, stream).expect("writing the decode probe stream");
1220- let out = Command::new("ffmpeg")1172+ let out = ec_testkit::ffmpeg()
1221 .args(["-v", "error", "-f", "obu", "-i"])1173 .args(["-v", "error", "-f", "obu", "-i"])
1222 .arg(&path)1174 .arg(&path)
1223 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]).output()1175 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]).output()
@@ -1312,10 +1264,6 @@
1312 );1264 );
1313 let ours = crate::stream::decode_stream(&stream).expect("our decoder");1265 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
1314 assert_eq!(ours.len(), sources.len(), "{NAME}: our decoder's frames");1266 assert_eq!(ours.len(), sources.len(), "{NAME}: our decoder's frames");
1315- if !have_ffmpeg() {
1316- eprintln!("SKIP the ffmpeg half of {NAME}: no ffmpeg");
1317- return;
1318- }
1319 let theirs = ffmpeg_decode_planes(&stream, width, height);1267 let theirs = ffmpeg_decode_planes(&stream, width, height);
1320 assert_eq!(theirs.len(), sources.len(), "{NAME}: ffmpeg's frames");1268 assert_eq!(theirs.len(), sources.len(), "{NAME}: ffmpeg's frames");
1321 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {1269 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
@@ -1525,10 +1473,6 @@
1525 sources.len(),1473 sources.len(),
1526 "our decoder's display-order count"1474 "our decoder's display-order count"
1527 );1475 );
1528- if !have_ffmpeg() {
1529- eprintln!("SKIP the ffmpeg half of the LAST2 witness: no ffmpeg");
1530- return;
1531- }
1532 let theirs = ffmpeg_decode_luma(&stream, width, height);1476 let theirs = ffmpeg_decode_luma(&stream, width, height);
1533 assert_eq!(theirs.len(), sources.len(), "ffmpeg's display-order count");1477 assert_eq!(theirs.len(), sources.len(), "ffmpeg's display-order count");
1534 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {1478 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
@@ -1673,9 +1617,6 @@
1673 n,1617 n,
1674 "{n} pictures at gop {gop}: our decoder's count"1618 "{n} pictures at gop {gop}: our decoder's count"
1675 );1619 );
1676- if !have_ffmpeg() {
1677- continue;
1678- }
1679 let theirs = ffmpeg_decode_luma(&held, width, height);1620 let theirs = ffmpeg_decode_luma(&held, width, height);
1680 assert_eq!(theirs.len(), n, "{n} pictures at gop {gop}: ffmpeg's count");1621 assert_eq!(theirs.len(), n, "{n} pictures at gop {gop}: ffmpeg's count");
1681 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {1622 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
@@ -1704,7 +1645,7 @@
1704 );1645 );
1705 let ours = crate::stream::decode_stream(&symmetric).expect("our decoder");1646 let ours = crate::stream::decode_stream(&symmetric).expect("our decoder");
1706 assert_eq!(ours.len(), 17, "the symmetric arm's display-order count");1647 assert_eq!(ours.len(), 17, "the symmetric arm's display-order count");
1707- if have_ffmpeg() {1648+ {
1708 let theirs = ffmpeg_decode_luma(&symmetric, width, height);1649 let theirs = ffmpeg_decode_luma(&symmetric, width, height);
1709 assert_eq!(theirs.len(), 17, "the symmetric arm's ffmpeg count");1650 assert_eq!(theirs.len(), 17, "the symmetric arm's ffmpeg count");
1710 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {1651 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
@@ -1779,9 +1720,6 @@
1779 n,1720 n,
1780 "{n} pictures at gop {gop} mode {mode}: our count"1721 "{n} pictures at gop {gop} mode {mode}: our count"
1781 );1722 );
1782- if !have_ffmpeg() {
1783- continue;
1784- }
1785 let theirs = ffmpeg_decode_luma(&on, width, height);1723 let theirs = ffmpeg_decode_luma(&on, width, height);
1786 assert_eq!(1724 assert_eq!(
1787 theirs.len(),1725 theirs.len(),
@@ -1919,9 +1857,6 @@
1919 );1857 );
1920 let ours = crate::stream::decode_stream(&on).expect("our decoder");1858 let ours = crate::stream::decode_stream(&on).expect("our decoder");
1921 assert_eq!(ours.len(), 17, "mode {mode}: our decoder's picture count");1859 assert_eq!(ours.len(), 17, "mode {mode}: our decoder's picture count");
1922- if !have_ffmpeg() {
1923- continue;
1924- }
1925 let theirs = ffmpeg_decode_luma(&on, width, height);1860 let theirs = ffmpeg_decode_luma(&on, width, height);
1926 assert_eq!(theirs.len(), 17, "mode {mode}: ffmpeg's picture count");1861 assert_eq!(theirs.len(), 17, "mode {mode}: ffmpeg's picture count");
1927 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {1862 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
@@ -2017,10 +1952,6 @@
2017 sources.len(),1952 sources.len(),
2018 "our decoder's display-order count"1953 "our decoder's display-order count"
2019 );1954 );
2020- if !have_ffmpeg() {
2021- eprintln!("SKIP the ffmpeg half of the pyramid round trip: no ffmpeg");
2022- return;
2023- }
2024 let theirs = ffmpeg_decode_luma(&stream, width, height);1955 let theirs = ffmpeg_decode_luma(&stream, width, height);
2025 assert_eq!(theirs.len(), sources.len(), "ffmpeg's display-order count");1956 assert_eq!(theirs.len(), sources.len(), "ffmpeg's display-order count");
2026 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {1957 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
@@ -2104,10 +2035,6 @@
2104 crate::decode::part128_split_hits() >= 4,2035 crate::decode::part128_split_hits() >= 4,
2105 "our decoder read no 128x128 superblock root"2036 "our decoder read no 128x128 superblock root"
2106 );2037 );
2107- if !have_ffmpeg() {
2108- eprintln!("SKIP the ffmpeg half: no ffmpeg");
2109- return;
2110- }
2111 let theirs = ffmpeg_decode_luma(&stream, width, height);2038 let theirs = ffmpeg_decode_luma(&stream, width, height);
2112 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");2039 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
2113 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {2040 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
@@ -2147,10 +2074,6 @@
2147 2074
2148 let ours = crate::stream::decode_stream(&stream).expect("our decoder");2075 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
2149 assert_eq!(ours.len(), sources.len(), "our decoder's frames");2076 assert_eq!(ours.len(), sources.len(), "our decoder's frames");
2150- if !have_ffmpeg() {
2151- eprintln!("SKIP the ffmpeg half: no ffmpeg");
2152- return;
2153- }
2154 let theirs = ffmpeg_decode_luma(&stream, width, height);2077 let theirs = ffmpeg_decode_luma(&stream, width, height);
2155 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");2078 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
2156 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {2079 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
@@ -2223,10 +2146,6 @@
2223 2146
2224 let ours = crate::stream::decode_stream(&stream).expect("our decoder");2147 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
2225 assert_eq!(ours.len(), sources.len(), "our decoder's frames");2148 assert_eq!(ours.len(), sources.len(), "our decoder's frames");
2226- if !have_ffmpeg() {
2227- eprintln!("SKIP the ffmpeg half: no ffmpeg");
2228- return;
2229- }
2230 let theirs = ffmpeg_decode_luma(&stream, width, height);2149 let theirs = ffmpeg_decode_luma(&stream, width, height);
2231 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");2150 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
2232 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {2151 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
@@ -2287,10 +2206,6 @@
2287 2206
2288 let ours = crate::stream::decode_stream(&stream).expect("our decoder");2207 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
2289 assert_eq!(ours.len(), sources.len(), "our decoder's frames");2208 assert_eq!(ours.len(), sources.len(), "our decoder's frames");
2290- if !have_ffmpeg() {
2291- eprintln!("SKIP the ffmpeg half: no ffmpeg");
2292- return;
2293- }
2294 let theirs = ffmpeg_decode_luma(&stream, width, height);2209 let theirs = ffmpeg_decode_luma(&stream, width, height);
2295 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");2210 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
2296 for (i, (ours_i, theirs_i)) in ours.iter().zip(&theirs).enumerate() {2211 for (i, (ours_i, theirs_i)) in ours.iter().zip(&theirs).enumerate() {
@@ -2343,10 +2258,6 @@
2343 }2258 }
2344 let ours = crate::stream::decode_stream(&stream).expect("our decoder");2259 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
2345 assert_eq!(ours.len(), sources.len(), "our decoder's frames");2260 assert_eq!(ours.len(), sources.len(), "our decoder's frames");
2346- if !have_ffmpeg() {
2347- eprintln!("SKIP the ffmpeg half: no ffmpeg");
2348- return;
2349- }
2350 let theirs = ffmpeg_decode_luma(&stream, width, height);2261 let theirs = ffmpeg_decode_luma(&stream, width, height);
2351 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");2262 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
2352 for (i, (ours_i, theirs_i)) in ours.iter().zip(&theirs).enumerate() {2263 for (i, (ours_i, theirs_i)) in ours.iter().zip(&theirs).enumerate() {
@@ -2415,10 +2326,6 @@
2415 2326
2416 let ours = crate::stream::decode_stream(&stream).expect("our decoder");2327 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
2417 assert_eq!(ours.len(), sources.len(), "our decoder's frames");2328 assert_eq!(ours.len(), sources.len(), "our decoder's frames");
2418- if !have_ffmpeg() {
2419- eprintln!("SKIP the ffmpeg half: no ffmpeg");
2420- return;
2421- }
2422 let theirs = ffmpeg_decode_luma(&stream, width, height);2329 let theirs = ffmpeg_decode_luma(&stream, width, height);
2423 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");2330 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
2424 for (i, (ours_i, theirs_i)) in ours.iter().zip(&theirs).enumerate() {2331 for (i, (ours_i, theirs_i)) in ours.iter().zip(&theirs).enumerate() {
@@ -2489,10 +2396,6 @@
2489 2396
2490 let ours = crate::stream::decode_stream(&stream).expect("our decoder");2397 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
2491 assert_eq!(ours.len(), sources.len(), "our decoder's frames");2398 assert_eq!(ours.len(), sources.len(), "our decoder's frames");
2492- if !have_ffmpeg() {
2493- eprintln!("SKIP the ffmpeg half: no ffmpeg");
2494- return;
2495- }
2496 let theirs = ffmpeg_decode_luma(&stream, width, height);2399 let theirs = ffmpeg_decode_luma(&stream, width, height);
2497 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");2400 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
2498 for (i, (ours_i, theirs_i)) in ours.iter().zip(&theirs).enumerate() {2401 for (i, (ours_i, theirs_i)) in ours.iter().zip(&theirs).enumerate() {
@@ -2581,10 +2484,6 @@
2581 2484
2582 let ours = crate::stream::decode_stream(&stream).expect("our decoder");2485 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
2583 assert_eq!(ours.len(), sources.len(), "{layout}: our decoder's frames");2486 assert_eq!(ours.len(), sources.len(), "{layout}: our decoder's frames");
2584- if !have_ffmpeg() {
2585- eprintln!("SKIP the ffmpeg half of {layout}: no ffmpeg");
2586- continue;
2587- }
2588 let theirs = ffmpeg_decode_luma(&stream, width, height);2487 let theirs = ffmpeg_decode_luma(&stream, width, height);
2589 assert_eq!(theirs.len(), sources.len(), "{layout}: ffmpeg's frames");2488 assert_eq!(theirs.len(), sources.len(), "{layout}: ffmpeg's frames");
2590 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {2489 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
@@ -2667,15 +2566,10 @@
2667 levels >= 2,2566 levels >= 2,
2668 "the quantizer grid was flat ({levels} level(s)): no delta_qindex was coded"2567 "the quantizer grid was flat ({levels} level(s)): no delta_qindex was coded"
2669 );2568 );
2670- } else {
2671- eprintln!(
2672- "SKIP the fire count at preset {}: no tpl map",
2673- crate::speed::speed()
2674- );
2675 }2569 }
2676 let ours = crate::stream::decode_stream(&stream).expect("our decoder");2570 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
2677 assert_eq!(ours.len(), sources.len(), "our decoder's frames");2571 assert_eq!(ours.len(), sources.len(), "our decoder's frames");
2678- if have_ffmpeg() {2572+ {
2679 let theirs = ffmpeg_decode_luma(&stream, width, height);2573 let theirs = ffmpeg_decode_luma(&stream, width, height);
2680 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");2574 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
2681 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {2575 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
@@ -2697,8 +2591,6 @@
2697 b.len()2591 b.len()
2698 );2592 );
2699 }2593 }
2700- } else {
2701- eprintln!("SKIP the ffmpeg half: no ffmpeg");
2702 }2594 }
2703 crate::encode::set_deltaq_res(None);2595 crate::encode::set_deltaq_res(None);
2704 eprintln!(2596 eprintln!(
@@ -2788,15 +2680,10 @@
2788 "no luma transform unit took {name}: {hits:?}"2680 "no luma transform unit took {name}: {hits:?}"
2789 );2681 );
2790 }2682 }
2791- } else {
2792- eprintln!(
2793- "SKIP the five-type fire count at preset {}: {hits:?}",
2794- crate::speed::speed()
2795- );
2796 }2683 }
2797 let ours = crate::stream::decode_stream(&stream).expect("our decoder");2684 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
2798 assert_eq!(ours.len(), sources.len(), "our decoder's frames");2685 assert_eq!(ours.len(), sources.len(), "our decoder's frames");
2799- if have_ffmpeg() {2686+ {
2800 let theirs = ffmpeg_decode_luma(&stream, width, height);2687 let theirs = ffmpeg_decode_luma(&stream, width, height);
2801 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");2688 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
2802 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {2689 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
@@ -2818,8 +2705,6 @@
2818 b.len()2705 b.len()
2819 );2706 );
2820 }2707 }
2821- } else {
2822- eprintln!("SKIP the ffmpeg half: no ffmpeg");
2823 }2708 }
2824 crate::encode::force_screen(None);2709 crate::encode::force_screen(None);
2825 eprintln!("tx_type witness: hits {hits:?}, {} bytes", stream.len());2710 eprintln!("tx_type witness: hits {hits:?}, {} bytes", stream.len());
@@ -2887,7 +2772,7 @@
2887 }2772 }
2888 let ours = crate::stream::decode_stream(&stream).expect("our decoder");2773 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
2889 assert_eq!(ours.len(), sources.len(), "our decoder's frames");2774 assert_eq!(ours.len(), sources.len(), "our decoder's frames");
2890- if have_ffmpeg() {2775+ {
2891 let theirs = ffmpeg_decode_luma(&stream, width, height);2776 let theirs = ffmpeg_decode_luma(&stream, width, height);
2892 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");2777 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
2893 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {2778 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
@@ -2909,8 +2794,6 @@
2909 b.len()2794 b.len()
2910 );2795 );
2911 }2796 }
2912- } else {
2913- eprintln!("SKIP the ffmpeg half: no ffmpeg");
2914 }2797 }
2915 eprintln!(2798 eprintln!(
2916 "inter tx_type witness: hits {hits:?}, {} bytes",2799 "inter tx_type witness: hits {hits:?}, {} bytes",
@@ -3008,15 +2891,10 @@
3008 inter.iter().sum::<usize>() > 0,2891 inter.iter().sum::<usize>() > 0,
3009 "the clip coded no inter luma transform unit at all: {inter:?}"2892 "the clip coded no inter luma transform unit at all: {inter:?}"
3010 );2893 );
3011- } else {
3012- eprintln!(
3013- "SKIP the wide-alphabet fire count at preset {}",
3014- crate::speed::speed()
3015- );
3016 }2894 }
3017 let ours = crate::stream::decode_stream(&stream).expect("our decoder");2895 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
3018 assert_eq!(ours.len(), sources.len(), "our decoder's frames");2896 assert_eq!(ours.len(), sources.len(), "our decoder's frames");
3019- if have_ffmpeg() {2897+ {
3020 let theirs = ffmpeg_decode_luma(&stream, width, height);2898 let theirs = ffmpeg_decode_luma(&stream, width, height);
3021 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");2899 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
3022 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {2900 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
@@ -3038,8 +2916,6 @@
3038 b.len()2916 b.len()
3039 );2917 );
3040 }2918 }
3041- } else {
3042- eprintln!("SKIP the ffmpeg half: no ffmpeg");
3043 }2919 }
3044 }2920 }
3045 /// lane-intertx's witness: on a clip the screen detector calls2921 /// lane-intertx's witness: on a clip the screen detector calls
@@ -3117,7 +2993,7 @@
3117 );2993 );
3118 let ours = crate::stream::decode_stream(&stream).expect("our decoder");2994 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
3119 assert_eq!(ours.len(), sources.len(), "our decoder's frames");2995 assert_eq!(ours.len(), sources.len(), "our decoder's frames");
3120- if have_ffmpeg() {2996+ {
3121 let theirs = ffmpeg_decode_planes(&stream, width, height);2997 let theirs = ffmpeg_decode_planes(&stream, width, height);
3122 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");2998 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
3123 let (cw, ch) = (width / 2, height / 2);2999 let (cw, ch) = (width / 2, height / 2);
@@ -3140,8 +3016,6 @@
3140 }3016 }
3141 }3017 }
3142 }3018 }
3143- } else {
3144- eprintln!("SKIP the ffmpeg half: no ffmpeg");
3145 }3019 }
3146 }3020 }
3147 3021
@@ -3184,7 +3058,7 @@
3184 sources.len(),3058 sources.len(),
3185 "speed {speed}: our decoder's frames"3059 "speed {speed}: our decoder's frames"
3186 );3060 );
3187- if have_ffmpeg() {3061+ {
3188 let theirs = ffmpeg_decode_luma(&stream, width, height);3062 let theirs = ffmpeg_decode_luma(&stream, width, height);
3189 assert_eq!(3063 assert_eq!(
3190 theirs.len(),3064 theirs.len(),
@@ -3211,8 +3085,6 @@
3211 b.len()3085 b.len()
3212 );3086 );
3213 }3087 }
3214- } else {
3215- eprintln!("SKIP the ffmpeg half of speed {speed}: no ffmpeg");
3216 }3088 }
3217 eprintln!(3089 eprintln!(
3218 "speed {speed}: {} bytes [{}]",3090 "speed {speed}: {} bytes [{}]",
@@ -3239,7 +3111,7 @@
3239 fn tile_wall_table_at_1080p() {3111 fn tile_wall_table_at_1080p() {
3240 let _knobs = crate::speed::knob_write();3112 let _knobs = crate::speed::knob_write();
3241 let (width, height) = (1920usize, 1080usize);3113 let (width, height) = (1920usize, 1080usize);
3242- let Some(sources) = h264_clip_frames("tile_wall_table_at_1080p", width, height, 8) else {3114+ let Some(sources) = h264_clip_frames(width, height, 8) else {
3243 return;3115 return;
3244 };3116 };
3245 let layouts = [(0u32, 0u32), (1, 0), (1, 1), (2, 1)];3117 let layouts = [(0u32, 0u32), (1, 0), (1, 1), (2, 1)];
@@ -3478,7 +3350,7 @@
3478 }3350 }
3479 // Real gate content, where the CDEF preset search actually chooses3351 // Real gate content, where the CDEF preset search actually chooses
3480 // `bits > 0` and the tile is re-coded, one tile and four.3352 // `bits > 0` and the tile is re-coded, one tile and four.
3481- if let Some(sources) = h264_clip_frames("the gate-clip arm", 640, 384, 3) {3353+ if let Some(sources) = h264_clip_frames(640, 384, 3) {
3482 run(&sources, 640, 384, (0, 0));3354 run(&sources, 640, 384, (0, 0));
3483 run(&sources, 640, 384, (1, 1));3355 run(&sources, 640, 384, (1, 1));
3484 }3356 }
@@ -3527,7 +3399,7 @@
3527 (cols_log2, rows_log2): (u32, u32),3399 (cols_log2, rows_log2): (u32, u32),
3528 threads: &[usize],3400 threads: &[usize],
3529 ) {3401 ) {
3530- let Some(sources) = h264_clip_frames("the filter-stage breakdown", width, height, frames)3402+ let Some(sources) = h264_clip_frames(width, height, frames)
3531 else {3403 else {
3532 return;3404 return;
3533 };3405 };
@@ -3598,7 +3470,7 @@
3598 layouts: &[(u32, u32)],3470 layouts: &[(u32, u32)],
3599 threads: &[usize],3471 threads: &[usize],
3600 ) {3472 ) {
3601- let Some(sources) = h264_clip_frames("the tile-search wall table", width, height, frames)3473+ let Some(sources) = h264_clip_frames(width, height, frames)
3602 else {3474 else {
3603 return;3475 return;
3604 };3476 };
@@ -3695,7 +3567,7 @@
3695 layouts: &[(u32, u32)],3567 layouts: &[(u32, u32)],
3696 threads: &[usize],3568 threads: &[usize],
3697 ) {3569 ) {
3698- let listed = Command::new("ffmpeg")3570+ let listed = ec_testkit::ffmpeg()
3699 .args(["-hide_banner", "-encoders"]).output();3571 .args(["-hide_banner", "-encoders"]).output();
3700 let has_rav1e = listed3572 let has_rav1e = listed
3701 .map(|o| String::from_utf8_lossy(&o.stdout).contains("librav1e"))3573 .map(|o| String::from_utf8_lossy(&o.stdout).contains("librav1e"))
@@ -3705,16 +3577,8 @@
3705 // message and could not fail under any require env. The two causes are3577 // message and could not fail under any require env. The two causes are
3706 // now separate, and only the clip goes through the fixture probe, so3578 // now separate, and only the clip goes through the fixture probe, so
3707 // either way this helper prints exactly ONE line.3579 // either way this helper prints exactly ONE line.
3708- if !has_rav1e {3580+ assert!(has_rav1e, "ffmpeg has no librav1e encoder");
3709- eprintln!("SKIP the rav1e reference: ffmpeg has no librav1e encoder");3581+ let clip = ec_testkit::fixture("open/sintel_trailer-1080p.mp4");
3710- return;
3711- }
3712- let Some(clip) = crate::library_fixture::require(
3713- "video/h264-1080p-23.976-8bit.mp4",
3714- "the rav1e reference",
3715- ) else {
3716- return;
3717- };
3718 eprintln!("| rav1e layout | threads | wall | fps | bytes |");3582 eprintln!("| rav1e layout | threads | wall | fps | bytes |");
3719 for &(c, r) in layouts {3583 for &(c, r) in layouts {
3720 for &t in threads {3584 for &t in threads {
@@ -3726,7 +3590,7 @@
3726 1 << r3590 1 << r
3727 );3591 );
3728 let start = std::time::Instant::now();3592 let start = std::time::Instant::now();
3729- let status = Command::new("ffmpeg")3593+ let status = ec_testkit::ffmpeg()
3730 .args(["-v", "error", "-y", "-i", clip.to_str().unwrap()])3594 .args(["-v", "error", "-y", "-i", clip.to_str().unwrap()])
3731 .args(["-frames:v", &frames.to_string()])3595 .args(["-frames:v", &frames.to_string()])
3732 .args(["-vf", &format!("scale={width}:{height}")])3596 .args(["-vf", &format!("scale={width}:{height}")])
@@ -3790,9 +3654,7 @@
3790 fn a_1080p_multi_tile_stream_decodes_sample_exact_through_both_decoders() {3654 fn a_1080p_multi_tile_stream_decodes_sample_exact_through_both_decoders() {
3791 let _knobs = crate::speed::knob_read();3655 let _knobs = crate::speed::knob_read();
3792 let (width, height) = (1920usize, 1080usize);3656 let (width, height) = (1920usize, 1080usize);
3793- let Some(sources) = h264_clip_frames(3657+ let Some(sources) = h264_clip_frames(width,
3794- "a_1080p_multi_tile_stream_decodes_sample_exact_through_both_decoders",
3795- width,
3796 height,3658 height,
3797 3,3659 3,
3798 ) else {3660 ) else {
@@ -3816,10 +3678,6 @@
3816 }3678 }
3817 let ours = crate::stream::decode_stream(&stream).expect("our decoder");3679 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
3818 assert_eq!(ours.len(), sources.len(), "{layout}: our decoder's frames");3680 assert_eq!(ours.len(), sources.len(), "{layout}: our decoder's frames");
3819- if !have_ffmpeg() {
3820- eprintln!("SKIP the ffmpeg half of 1080p {layout}: no ffmpeg");
3821- continue;
3822- }
3823 let theirs = ffmpeg_decode_luma(&stream, width, height);3681 let theirs = ffmpeg_decode_luma(&stream, width, height);
3824 assert_eq!(theirs.len(), sources.len(), "{layout}: ffmpeg's frames");3682 assert_eq!(theirs.len(), sources.len(), "{layout}: ffmpeg's frames");
3825 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {3683 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
@@ -3849,14 +3707,8 @@
3849 #[test]3707 #[test]
3850 fn quality_target_is_monotone_in_bytes_and_psnr() {3708 fn quality_target_is_monotone_in_bytes_and_psnr() {
3851 let _knobs = crate::speed::knob_read();3709 let _knobs = crate::speed::knob_read();
3852- if !have_ffmpeg() {
3853- eprintln!("SKIP quality_target_is_monotone_in_bytes_and_psnr: no ffmpeg");
3854- return;
3855- }
3856 let (width, height) = (640, 384);3710 let (width, height) = (640, 384);
3857- let Some(pictures) = h264_clip_frames(3711+ let Some(pictures) = h264_clip_frames(width,
3858- "quality_target_is_monotone_in_bytes_and_psnr",
3859- width,
3860 height,3712 height,
3861 8,3713 8,
3862 ) else {3714 ) else {
crates/ec-av1/src/lib.rsmodified+0 -2
@@ -39,8 +39,6 @@ mod filter_search;
39 pub mod frame;39 pub mod frame;
40 mod hits;40 mod hits;
41 pub mod intra;41 pub mod intra;
42-#[cfg(test)]
43-mod library_fixture;
44 pub mod mc;42 pub mod mc;
45 pub mod motion;43 pub mod motion;
46 mod motion_field;44 mod motion_field;
crates/ec-av1/src/library_fixture.rsdeleted+0 -161
@@ -1,161 +0,0 @@
1-//! Where a REAL-LIBRARY fixture is read from, and the one presence probe every
2-//! gate that needs one routes through.
3-//!
4-//! The clips these gates read (`h264-1080p-23.976-8bit.mp4`,
5-//! `h264-2160p-23.976-8bit.mp4`, `real-library-manifest.tsv`) are
6-//! multi-megabyte encodes of a shared library, not pins: they cannot be
7-//! committed under `crates/<crate>/fixtures/` the way the `.obu` pins are
8-//! ([`crate_pin`](crate::stream)), so they live in the gitignored ROOT
9-//! `fixtures/` — `.gitignore:2`. A linked worktree therefore never has that
10-//! directory, and a gate that skips on its absence reports GREEN having
11-//! asserted nothing: the class `lane-av1skipfix` closed for the pins, still open
12-//! for the clips.
13-//!
14-//! TWO defects met here, both of which this module closes:
15-//!
16-//! 1. **Silent skip.** `h264_clip_frames` and each gate's own
17-//! `if !clip.exists() { eprintln!("SKIP …"); return; }` skipped with no env
18-//! escape, so `EC_AV1_REQUIRE_FFMPEG=1` — a batch run's way of saying "this
19-//! gate must actually run" — did not make the ABSENT CLIP a failure. The
20-//! `a_1080p_multi_tile_stream_decodes_sample_exact_through_both_decoders`
21-//! gate printed `SKIP the 1080p tile round trip: no fixture` and libtest
22-//! reported `ok` on a tree with no root `fixtures/` at all.
23-//!
24-//! 2. **Two roots.** `scripts/verify-fixture-library.sh` validates
25-//! `$EC_FIXTURES` (defaulting to `$ROOT/fixtures`) while these gates read
26-//! `$ROOT/fixtures` unconditionally. Pointing the preflight at a library
27-//! elsewhere reported `resolve 0 missing` and `GREEN` while the clip gates'
28-//! root was absent — GREEN with an absent root, the exact false green this
29-//! module exists to kill. So [`root`] honours `EC_FIXTURES` FIRST: the
30-//! preflight and the gates now resolve the same tree, and when it is unset
31-//! the preflight's default IS the gates' root, so its mode-(i) finding fires
32-//! exactly when the clip gates will skip.
33-//!
34-//! The shape is the crate's existing convention, not a new one: the
35-//! assert-under-require / print-one-line-otherwise probe is the same one
36-//! `crates/ec-h264/tests/conformance.rs::require_fixtures` and the per-crate
37-//! `require_fixture` helpers use, and the file's own presence check lives HERE,
38-//! inside the probe that owns it — a bare `clip.exists()` at a call site is
39-//! precisely what the anti-regression scan for the sibling (tool) class
40-//! rejects.
41-
42-use std::path::{Path, PathBuf};
43-
44-/// The envs that turn an absent library clip into a hard failure.
45-///
46-/// * `EC_REQUIRE_FIXTURES` — the fleet-wide convention, the same one
47-/// `scripts/verify-fixture-library.sh` and every per-crate `require_fixture`
48-/// honour, and the one `EC_REQUIRE_FIXTURES=1` in the preflight's docs names.
49-/// * `EC_AV1_REQUIRE_FFMPEG` / `EC_AV1_REQUIRE_AOMENC` — this crate's own
50-/// requirement flags ([`have_ffmpeg`](crate::encode::tests::have_ffmpeg)).
51-/// Every gate reachable through [`require`] also decodes its result through
52-/// ffmpeg, so a batch that sets them has already said the gate must run; a
53-/// missing clip must not be the softer failure.
54-///
55-/// All three are checked, not just one: a run that sets only the preflight's
56-/// env, and a run that sets only this crate's, both get the failure.
57-fn required() -> bool {
58- std::env::var_os("EC_REQUIRE_FIXTURES").is_some()
59- || std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_some()
60- || std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_some()
61-}
62-
63-/// The fixture root the tests read, in precedence order:
64-///
65-/// 1. `EC_FIXTURES` — the same variable `scripts/verify-fixture-library.sh`
66-/// resolves, so its verdict and these gates' bytes are the same tree. This
67-/// is the half of the two-roots mismatch that the preflight cannot fix from
68-/// its side.
69-/// 2. `<crate>/../../fixtures` — the gitignored root `fixtures/`, the default
70-/// the preflight uses when `EC_FIXTURES` is unset.
71-pub fn root() -> PathBuf {
72- match std::env::var_os("EC_FIXTURES") {
73- Some(p) if !p.is_empty() => PathBuf::from(p),
74- _ => Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures"),
75- }
76-}
77-
78-/// `require` on a path relative to [`root`]:
79-/// `require("video/h264-1080p-23.976-8bit.mp4", …)`. The literal is
80-/// LIBRARY-RELATIVE, which is the row shape `scripts/gen-fixture-library.sh`
81-/// reads back out of this file, so the preflight keeps resolving these paths.
82-pub fn path(rel: &str) -> PathBuf {
83- root().join(rel)
84-}
85-
86-/// The one presence probe for a library fixture. Returns the path when the file
87-/// is there. When it is not:
88-///
89-/// * under [`required()`] — PANIC, naming the resolved path, so the gate is RED
90-/// instead of green-with-nothing-checked;
91-/// * otherwise — prints exactly ONE `SKIP` line naming the resolved path and the
92-/// three ways out (link the library, point `EC_FIXTURES` at it, or set a
93-/// require env), and returns `None`.
94-///
95-/// A caller that gets `None` must `return` WITHOUT printing a second line: the
96-/// path and the escape hatch are already on the one line above, and a second
97-/// "no fixture" line is the noise that hid this defect from a reading of the
98-/// output.
99-pub fn require(rel: &str, what: &str) -> Option<PathBuf> {
100- require_at(path(rel), what)
101-}
102-
103-/// [`require`] for a path the caller resolved itself — an `EC_AV1_WALL_CLIP`
104-/// override, which names a clip OUTSIDE any library root, so it must not be
105-/// joined onto one.
106-pub fn require_at(clip: PathBuf, what: &str) -> Option<PathBuf> {
107- if clip.is_file() {
108- return Some(clip);
109- }
110- assert!(
111- !required(),
112- "{what}: the library clip is absent at {} -- this gate would prove nothing. A linked \
113- worktree has no gitignored root `fixtures/`: run scripts/link-fixtures.sh, or point \
114- EC_FIXTURES at a library root, or set EC_REQUIRE_FIXTURES=1 / EC_AV1_REQUIRE_FFMPEG=1 \
115- only on a tree that really has the library.",
116- clip.display()
117- );
118- eprintln!(
119- "SKIP {what}: {} absent at {} -- this gate proved nothing; run \
120- scripts/link-fixtures.sh, point EC_FIXTURES at a library root, or set \
121- EC_REQUIRE_FIXTURES=1 / EC_AV1_REQUIRE_FFMPEG=1 to make this a failure.",
122- clip.file_name().unwrap_or_default().to_string_lossy(),
123- clip.display()
124- );
125- None
126-}
127-
128-#[cfg(test)]
129-mod tests {
130- use super::*;
131-
132- /// The two-roots reconciliation, asserted on the RESOLVER rather than
133- /// described in prose: with `EC_FIXTURES` set, [`root`] is that directory and
134- /// NOT `<crate>/../../fixtures`. (The variable is process-constant in this
135- /// crate — nothing calls `set_var` — so the assertion holds for whatever the
136- /// batch exported; it is the precedence, not a particular value, that is
137- /// under test.)
138- #[test]
139- fn the_resolver_follows_ec_fixtures_over_the_gitignored_root() {
140- let root = super::root();
141- if let Some(p) = std::env::var_os("EC_FIXTURES")
142- && !p.is_empty()
143- {
144- assert_eq!(
145- root,
146- PathBuf::from(p),
147- "EC_FIXTURES must win over the default root"
148- );
149- } else {
150- assert!(
151- root.ends_with("../../fixtures"),
152- "the default root is the gitignored <crate>/../../fixtures, got {}",
153- root.display()
154- );
155- }
156- assert_eq!(
157- super::path("video/h264-1080p-23.976-8bit.mp4"),
158- root.join("video/h264-1080p-23.976-8bit.mp4")
159- );
160- }
161-}
crates/ec-av1/src/stack_budget.rsmodified+0 -1
@@ -458,7 +458,6 @@ mod tests {
458 ("frame.rs", include_str!("frame.rs")),458 ("frame.rs", include_str!("frame.rs")),
459 ("hits.rs", include_str!("hits.rs")),459 ("hits.rs", include_str!("hits.rs")),
460 ("intra.rs", include_str!("intra.rs")),460 ("intra.rs", include_str!("intra.rs")),
461- ("library_fixture.rs", include_str!("library_fixture.rs")),
462 ("mc.rs", include_str!("mc.rs")),461 ("mc.rs", include_str!("mc.rs")),
463 ("motion.rs", include_str!("motion.rs")),462 ("motion.rs", include_str!("motion.rs")),
464 ("motion_field.rs", include_str!("motion_field.rs")),463 ("motion_field.rs", include_str!("motion_field.rs")),
crates/ec-av1/src/tile/tests.rsmodified+2 -114
@@ -8,7 +8,7 @@ use ec_av1_syntax::{
8 FrameHeader, FrameType, LoopFilterParams, PRIMARY_REF_NONE, QuantizationParams, TileInfo,8 FrameHeader, FrameType, LoopFilterParams, PRIMARY_REF_NONE, QuantizationParams, TileInfo,
9 TxMode,9 TxMode,
10 };10 };
11-use std::process::{Command, Stdio};11+
12 12
13 /// A 64x64 sequence with every tool this writer does not code turned off:13 /// A 64x64 sequence with every tool this writer does not code turned off:
14 /// 64x64 superblocks, no CDEF, no loop restoration, no superres, no filter14 /// 64x64 superblocks, no CDEF, no loop restoration, no superres, no filter
@@ -73,33 +73,10 @@ fn flat_key_frame() -> FrameHeader {
73 }73 }
74 }74 }
75 75
76-/// Whether ffmpeg is on PATH. Absence normally SKIPs, but
77-/// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every
78-/// aomenc gate decodes its stream through ffmpeg and is meaningless
79-/// without it -- turns it into a hard failure. Without this the require
80-/// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first
81-/// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg
82-/// printed SKIP and reported green (class gate-skips-on-its-own-failure).
83-fn have_ffmpeg() -> bool {
84- let present = Command::new("ffmpeg")
85- .arg("-version")
86- .stdout(Stdio::null())
87- .stderr(Stdio::null())
88- .status()
89- .is_ok_and(|s| s.success());
90- assert!(
91- present
92- || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none()
93- && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()),
94- "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH"
95- );
96- present
97-}
98-
99 /// Decodes an AV1 OBU stream with ffmpeg and hands back the planes.76 /// Decodes an AV1 OBU stream with ffmpeg and hands back the planes.
100 fn ffmpeg_decode(stream: &[u8], w: usize, h: usize) -> Vec<u8> {77 fn ffmpeg_decode(stream: &[u8], w: usize, h: usize) -> Vec<u8> {
101 let out = run_with_stdin(78 let out = run_with_stdin(
102- Command::new("ffmpeg").args([79+ ec_testkit::ffmpeg().args([
103 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",80 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
104 ]),81 ]),
105 stream,82 stream,
@@ -120,10 +97,6 @@ fn ffmpeg_decode(stream: &[u8], w: usize, h: usize) -> Vec<u8> {
120 97
121 #[test]98 #[test]
122 fn flat_key_frame_decodes_to_mid_grey() {99 fn flat_key_frame_decodes_to_mid_grey() {
123- if !have_ffmpeg() {
124- eprintln!("SKIP flat_key_frame_decodes_to_mid_grey: no ffmpeg on PATH");
125- return;
126- }
127 let seq = sequence_64();100 let seq = sequence_64();
128 let header = flat_key_frame();101 let header = flat_key_frame();
129 let tile = flat_key_frame_tile(header.mi_cols, header.mi_rows).unwrap();102 let tile = flat_key_frame_tile(header.mi_cols, header.mi_rows).unwrap();
@@ -199,10 +172,6 @@ const DECODED_AT_Q100: [(i32, u8); 28] = [
199 172
200 #[test]173 #[test]
201 fn a_dc_coefficient_moves_the_whole_block_off_mid_grey() {174 fn a_dc_coefficient_moves_the_whole_block_off_mid_grey() {
202- if !have_ffmpeg() {
203- eprintln!("SKIP a_dc_coefficient_moves_the_whole_block_off_mid_grey: no ffmpeg");
204- return;
205- }
206 let mut seen = Vec::new();175 let mut seen = Vec::new();
207 for (level, want) in DECODED_AT_Q100 {176 for (level, want) in DECODED_AT_Q100 {
208 let planes = decode_dc_frame(level);177 let planes = decode_dc_frame(level);
@@ -320,10 +289,6 @@ fn dc_residual(level: i32) -> i32 {
320 /// still decodes to the grey its own level asks for.289 /// still decodes to the grey its own level asks for.
321 #[test]290 #[test]
322 fn each_superblock_decodes_to_the_grey_its_own_level_asks_for() {291 fn each_superblock_decodes_to_the_grey_its_own_level_asks_for() {
323- if !have_ffmpeg() {
324- eprintln!("SKIP each_superblock_decodes_to_the_grey_its_own_level_asks_for: no ffmpeg");
325- return;
326- }
327 // Read in raster order the two grids put a positive, a negative and a292 // Read in raster order the two grids put a positive, a negative and a
328 // cancelling sign context in front of the bottom-right block, and a293 // cancelling sign context in front of the bottom-right block, and a
329 // leaning-down one in front of the second grid's right and bottom294 // leaning-down one in front of the second grid's right and bottom
@@ -410,10 +375,6 @@ fn split_residual(level: i32) -> i32 {
410 /// on the grey their own level and their neighbours ask for.375 /// on the grey their own level and their neighbours ask for.
411 #[test]376 #[test]
412 fn a_split_superblock_decodes_each_quadrant_on_its_own_level() {377 fn a_split_superblock_decodes_each_quadrant_on_its_own_level() {
413- if !have_ffmpeg() {
414- eprintln!("SKIP a_split_superblock_decodes_each_quadrant_on_its_own_level: no ffmpeg");
415- return;
416- }
417 // Four by four 32x32 blocks over two by two superblocks, so the walk378 // Four by four 32x32 blocks over two by two superblocks, so the walk
418 // crosses superblock boundaries in both directions, and signs that379 // crosses superblock boundaries in both directions, and signs that
419 // alternate so the DC sign context lands on all three of its values.380 // alternate so the DC sign context lands on all three of its values.
@@ -548,12 +509,6 @@ fn assert_mean_is_mid_grey(block: &[Vec<u8>]) {
548 /// end-of-block position or the level contexts breaks one of those.509 /// end-of-block position or the level contexts breaks one of those.
549 #[test]510 #[test]
550 fn a_coefficient_off_the_origin_selects_its_own_basis_function() {511 fn a_coefficient_off_the_origin_selects_its_own_basis_function() {
551- if !have_ffmpeg() {
552- eprintln!(
553- "SKIP a_coefficient_off_the_origin_selects_its_own_basis_function: no ffmpeg"
554- );
555- return;
556- }
557 let blocks = vec![512 let blocks = vec![
558 vec![Coeff {513 vec![Coeff {
559 row: 0,514 row: 0,
@@ -624,10 +579,6 @@ fn a_coefficient_off_the_origin_selects_its_own_basis_function() {
624 /// with neighbours that carry levels rather than zeros.579 /// with neighbours that carry levels rather than zeros.
625 #[test]580 #[test]
626 fn a_coefficient_in_the_far_corner_reaches_the_last_end_of_block_group() {581 fn a_coefficient_in_the_far_corner_reaches_the_last_end_of_block_group() {
627- if !have_ffmpeg() {
628- eprintln!("SKIP a_coefficient_in_the_far_corner_reaches_the_last_end_of_block_group");
629- return;
630- }
631 let block = vec![582 let block = vec![
632 Coeff {583 Coeff {
633 row: 31,584 row: 31,
@@ -766,10 +717,6 @@ fn the_price_grows_with_the_levels() {
766 /// with no neighbours still averages to mid-grey.717 /// with no neighbours still averages to mid-grey.
767 #[test]718 #[test]
768 fn every_quadrant_carries_its_own_coefficients() {719 fn every_quadrant_carries_its_own_coefficients() {
769- if !have_ffmpeg() {
770- eprintln!("SKIP every_quadrant_carries_its_own_coefficients: no ffmpeg");
771- return;
772- }
773 let blocks = vec![720 let blocks = vec![
774 vec![721 vec![
775 Coeff {722 Coeff {
@@ -861,10 +808,6 @@ fn mean(block: &[Vec<u8>]) -> f64 {
861 /// may reach the other plane or luma.808 /// may reach the other plane or luma.
862 #[test]809 #[test]
863 fn each_chroma_plane_codes_its_own_basis_function() {810 fn each_chroma_plane_codes_its_own_basis_function() {
864- if !have_ffmpeg() {
865- eprintln!("SKIP each_chroma_plane_codes_its_own_basis_function: no ffmpeg");
866- return;
867- }
868 let mut blocks = vec![BlockCoeffs::default(); 4];811 let mut blocks = vec![BlockCoeffs::default(); 4];
869 blocks[0].u = vec![Coeff {812 blocks[0].u = vec![Coeff {
870 row: 0,813 row: 0,
@@ -931,10 +874,6 @@ fn each_chroma_plane_codes_its_own_basis_function() {
931 /// still lean the way each block's own DC asks.874 /// still lean the way each block's own DC asks.
932 #[test]875 #[test]
933 fn chroma_dc_signs_read_their_neighbours() {876 fn chroma_dc_signs_read_their_neighbours() {
934- if !have_ffmpeg() {
935- eprintln!("SKIP chroma_dc_signs_read_their_neighbours: no ffmpeg");
936- return;
937- }
938 let dc = |level| {877 let dc = |level| {
939 vec![Coeff {878 vec![Coeff {
940 row: 0,879 row: 0,
@@ -1168,10 +1107,6 @@ fn the_golomb_tail_reads_back_as_the_level_it_was_written_for() {
1168 /// the syntax, or off by one desyncs the decoder outright.1107 /// the syntax, or off by one desyncs the decoder outright.
1169 #[test]1108 #[test]
1170 fn levels_above_the_base_range_tail_carry_a_golomb_tail() {1109 fn levels_above_the_base_range_tail_carry_a_golomb_tail() {
1171- if !have_ffmpeg() {
1172- eprintln!("SKIP levels_above_the_base_range_tail_carry_a_golomb_tail: no ffmpeg");
1173- return;
1174- }
1175 let mut brighter = Vec::new();1110 let mut brighter = Vec::new();
1176 let mut darker = Vec::new();1111 let mut darker = Vec::new();
1177 for level in [10, 14, 18, 31, 60, 400] {1112 for level in [10, 14, 18, 31, 60, 400] {
@@ -1230,10 +1165,6 @@ fn decode_luma_sb(width: usize, height: usize, sbs: &[Superblock]) -> Vec<Vec<u8
1230 /// where the next one begins.1165 /// where the next one begins.
1231 #[test]1166 #[test]
1232 fn a_whole_superblock_covers_all_four_of_its_quadrants() {1167 fn a_whole_superblock_covers_all_four_of_its_quadrants() {
1233- if !have_ffmpeg() {
1234- eprintln!("SKIP a_whole_superblock_covers_all_four_of_its_quadrants: no ffmpeg");
1235- return;
1236- }
1237 let across = BlockCoeffs::from(vec![Coeff {1168 let across = BlockCoeffs::from(vec![Coeff {
1238 row: 0,1169 row: 0,
1239 col: 1,1170 col: 1,
@@ -1289,10 +1220,6 @@ fn a_whole_superblock_covers_all_four_of_its_quadrants() {
1289 /// a 32x32 block that merely carries the same coefficients.1220 /// a 32x32 block that merely carries the same coefficients.
1290 #[test]1221 #[test]
1291 fn a_quadrant_splits_into_four_sixteens() {1222 fn a_quadrant_splits_into_four_sixteens() {
1292- if !have_ffmpeg() {
1293- eprintln!("SKIP a_quadrant_splits_into_four_sixteens: no ffmpeg");
1294- return;
1295- }
1296 let dc = |level: i32| {1223 let dc = |level: i32| {
1297 BlockCoeffs::from(vec![Coeff {1224 BlockCoeffs::from(vec![Coeff {
1298 row: 0,1225 row: 0,
@@ -1376,13 +1303,6 @@ fn a_whole_superblock_at_the_frame_edge_is_refused() {
1376 1303
1377 #[test]1304 #[test]
1378 fn a_frame_that_is_not_a_whole_number_of_superblocks_codes_every_block() {1305 fn a_frame_that_is_not_a_whole_number_of_superblocks_codes_every_block() {
1379- if !have_ffmpeg() {
1380- eprintln!(
1381- "SKIP a_frame_that_is_not_a_whole_number_of_superblocks_codes_every_block: no \
1382- ffmpeg"
1383- );
1384- return;
1385- }
1386 let blocks: Vec<BlockCoeffs> = (0..6)1306 let blocks: Vec<BlockCoeffs> = (0..6)
1387 .map(|i| {1307 .map(|i| {
1388 let (row, col) = if i % 2 == 0 { (0, 1) } else { (1, 0) };1308 let (row, col) = if i % 2 == 0 { (0, 1) } else { (1, 0) };
@@ -1417,10 +1337,6 @@ fn a_frame_that_is_not_a_whole_number_of_superblocks_codes_every_block() {
1417 /// a real-decoder test before this one.1337 /// a real-decoder test before this one.
1418 #[test]1338 #[test]
1419 fn a_frame_that_hangs_off_the_bottom_codes_every_block() {1339 fn a_frame_that_hangs_off_the_bottom_codes_every_block() {
1420- if !have_ffmpeg() {
1421- eprintln!("SKIP a_frame_that_hangs_off_the_bottom_codes_every_block: no ffmpeg");
1422- return;
1423- }
1424 let blocks: Vec<BlockCoeffs> = (0..6)1340 let blocks: Vec<BlockCoeffs> = (0..6)
1425 .map(|i| {1341 .map(|i| {
1426 let (row, col) = if i % 2 == 0 { (0, 1) } else { (1, 0) };1342 let (row, col) = if i % 2 == 0 { (0, 1) } else { (1, 0) };
@@ -1472,10 +1388,6 @@ fn a_frame_that_is_not_a_whole_number_of_blocks_is_refused() {
1472 /// two empty blocks stop mirroring their neighbours.1388 /// two empty blocks stop mirroring their neighbours.
1473 #[test]1389 #[test]
1474 fn directional_modes_predict_from_the_neighbours_they_name() {1390 fn directional_modes_predict_from_the_neighbours_they_name() {
1475- if !have_ffmpeg() {
1476- eprintln!("SKIP directional_modes_predict_from_the_neighbours_they_name: no ffmpeg");
1477- return;
1478- }
1479 let gradient = BlockCoeffs {1391 let gradient = BlockCoeffs {
1480 luma: vec![Coeff {1392 luma: vec![Coeff {
1481 row: 1,1393 row: 1,
@@ -1889,12 +1801,6 @@ fn negating_the_levels_negates_the_residual() {
1889 /// to agree, not most of them.1801 /// to agree, not most of them.
1890 #[test]1802 #[test]
1891 fn the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_32x32_block() {1803 fn the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_32x32_block() {
1892- if !have_ffmpeg() {
1893- eprintln!(
1894- "SKIP the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_32x32_block: no ffmpeg"
1895- );
1896- return;
1897- }
1898 // A DC, two low-frequency terms of each orientation, a diagonal and a1804 // A DC, two low-frequency terms of each orientation, a diagonal and a
1899 // far corner, with both signs among them.1805 // far corner, with both signs among them.
1900 let coeffs = [1806 let coeffs = [
@@ -1953,12 +1859,6 @@ fn the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_32x32_block() {
1953 /// on, and nothing else in the crate exercises it against a decoder.1859 /// on, and nothing else in the crate exercises it against a decoder.
1954 #[test]1860 #[test]
1955 fn the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_16x16_block() {1861 fn the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_16x16_block() {
1956- if !have_ffmpeg() {
1957- eprintln!(
1958- "SKIP the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_16x16_block: no ffmpeg"
1959- );
1960- return;
1961- }
1962 let coeffs = [1862 let coeffs = [
1963 (0u8, 0u8, 9i32),1863 (0u8, 0u8, 9i32),
1964 (0, 1, -14),1864 (0, 1, -14),
@@ -2022,12 +1922,6 @@ fn the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_16x16_block() {
2022 /// that read the missing half as anything else would disagree here.1922 /// that read the missing half as anything else would disagree here.
2023 #[test]1923 #[test]
2024 fn the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_64x64_block() {1924 fn the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_64x64_block() {
2025- if !have_ffmpeg() {
2026- eprintln!(
2027- "SKIP the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_64x64_block: no ffmpeg"
2028- );
2029- return;
2030- }
2031 let coeffs = [1925 let coeffs = [
2032 (0u8, 0u8, 12i32),1926 (0u8, 0u8, 12i32),
2033 (0, 2, -9),1927 (0, 2, -9),
@@ -2104,12 +1998,6 @@ fn a_dc_level_is_worth_half_as_much_each_time_the_transform_doubles() {
2104 /// rather than a scrambler.1998 /// rather than a scrambler.
2105 #[test]1999 #[test]
2106 fn a_quantized_picture_decodes_to_what_the_encoder_reconstructed() {2000 fn a_quantized_picture_decodes_to_what_the_encoder_reconstructed() {
2107- if !have_ffmpeg() {
2108- eprintln!(
2109- "SKIP a_quantized_picture_decodes_to_what_the_encoder_reconstructed: no ffmpeg"
2110- );
2111- return;
2112- }
2113 // A gradient, a ripple and a corner patch: low frequencies, a mid one2001 // A gradient, a ripple and a corner patch: low frequencies, a mid one
2114 // and an edge, none of them a basis function of the transform.2002 // and an edge, none of them a basis function of the transform.
2115 let mut residual = vec![0i32; 32 * 32];2003 let mut residual = vec![0i32; 32 * 32];
crates/ec-av1/tests/aom_conformance.rsmodified+4 -32
@@ -2,7 +2,7 @@
2 //!2 //!
3 //! The vectors are the `av1-1-b8-*` and `av1-1-b10-*` files listed in libaom's3 //! The vectors are the `av1-1-b8-*` and `av1-1-b10-*` files listed in libaom's
4 //! `test/test_vectors.cc`, fetched from the `aom-test-data` bucket into the4 //! `test/test_vectors.cc`, fetched from the `aom-test-data` bucket into the
5-//! directory named by `EC_AV1_AOM_DIR`. Each `<name>.ivf` (or `.mkv`) comes with a5+//! `fixtures/vectors/av1-aom`. Each `<name>.ivf` (or `.mkv`) comes with a
6 //! `<name>.md5` file: one line per SHOWN frame, `md5 <name>-WxH-NNNN.i420`.6 //! `<name>.md5` file: one line per SHOWN frame, `md5 <name>-WxH-NNNN.i420`.
7 //! The digest covers the cropped planes (Y, then U, then V; chroma `(w+1)/2` by7 //! The digest covers the cropped planes (Y, then U, then V; chroma `(w+1)/2` by
8 //! `(h+1)/2`; Y only for monochrome) and, above 8 bits, each sample is two8 //! `(h+1)/2`; Y only for monochrome) and, above 8 bits, each sample is two
@@ -20,15 +20,12 @@
20 //! panics without naming an unsupported feature. The first mismatching frame20 //! panics without naming an unsupported feature. The first mismatching frame
21 //! is listed by vector name.21 //! is listed by vector name.
22 //!22 //!
23-//! Without `EC_AV1_AOM_DIR` the test uses `fixtures/av1-aom` if present, else skips loudly. With `EC_REQUIRE_FIXTURES`23+//! A missing directory fails the test.
24-//! set, a missing directory is a failure.
25 24
26 use ec_av1::stream::decode_stream_with;25 use ec_av1::stream::decode_stream_with;
27 use ec_av1_syntax::Av1Parser;26 use ec_av1_syntax::Av1Parser;
28 use std::path::PathBuf;27 use std::path::PathBuf;
29 28
30-/// Environment variable naming the directory of fetched vectors and md5 files.
31-const DIR_VAR: &str = "EC_AV1_AOM_DIR";
32 29
33 // ------------------------------------------------------------------ MD5 ----30 // ------------------------------------------------------------------ MD5 ----
34 31
@@ -333,30 +330,10 @@ fn check_vector(name: &str, frames: &[&[u8]], expected: &[String]) -> Outcome {
333 }330 }
334 }331 }
335 332
336-/// `EC_AV1_AOM_DIR`, else the workspace's `fixtures/av1-aom` when it exists.
337-fn vector_dir() -> Option<PathBuf> {
338- std::env::var_os(DIR_VAR).map(PathBuf::from).or_else(|| {
339- let local = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/av1-aom");
340- local.is_dir().then_some(local)
341- })
342-}
343-
344 #[test]333 #[test]
345 fn aom_vectors_match_per_frame_md5() {334 fn aom_vectors_match_per_frame_md5() {
346- let require = std::env::var_os("EC_REQUIRE_FIXTURES").is_some();335+ let dir = ec_testkit::fixture("vectors/av1-aom");
347- let Some(dir) = vector_dir() else {336+ let entries = std::fs::read_dir(&dir).expect("vector directory");
348- assert!(!require, "EC_REQUIRE_FIXTURES=1 but {DIR_VAR} is not set and fixtures/av1-aom is missing");
349- eprintln!("SKIP aom_conformance: {DIR_VAR} is not set (libaom av1-1-b8/b10 vectors)");
350- return;
351- };
352- let entries = match std::fs::read_dir(&dir) {
353- Ok(e) => e,
354- Err(e) => {
355- assert!(!require, "EC_REQUIRE_FIXTURES=1 but {}: {e}", dir.display());
356- eprintln!("SKIP aom_conformance: {}: {e}", dir.display());
357- return;
358- }
359- };
360 let mut md5_files: Vec<PathBuf> = entries337 let mut md5_files: Vec<PathBuf> = entries
361 .filter_map(|e| e.ok().map(|e| e.path()))338 .filter_map(|e| e.ok().map(|e| e.path()))
362 .filter(|p| p.extension().is_some_and(|x| x == "md5"))339 .filter(|p| p.extension().is_some_and(|x| x == "md5"))
@@ -366,11 +343,6 @@ fn aom_vectors_match_per_frame_md5() {
366 })343 })
367 .collect();344 .collect();
368 md5_files.sort();345 md5_files.sort();
369- if md5_files.is_empty() {
370- assert!(!require, "EC_REQUIRE_FIXTURES=1 but no av1-1-b* .md5 files in {}", dir.display());
371- eprintln!("SKIP aom_conformance: no av1-1-b* .md5 files in {}", dir.display());
372- return;
373- }
374 346
375 let mut exact = Vec::new();347 let mut exact = Vec::new();
376 let mut refused = Vec::new();348 let mut refused = Vec::new();
crates/ec-av1/tests/real_library.rsmodified+17 -56
@@ -1,20 +1,10 @@
1-//! The personal media library, AV1 half: every `av1` row of1+//! The open-media AV1 check: the first `FRAMES` shown pictures of the sintel
2-//! `fixtures/real-library-manifest.tsv` is extracted as a low-overhead OBU2+//! trailer as an SVT-AV1 IVF stream are decoded and compared sample for sample with
3-//! stream, its first `FRAMES` shown pictures are decoded (film grain applied,3+//! ffmpeg's `libdav1d` decoder.
4-//! as the decoder outputs it), and each frame is compared sample for sample with
5-//! ffmpeg's `libdav1d` decoder at the same pixel format.
6-//!
7-//! Every file either decodes bit-exactly, is refused by name (a pixel format
8-//! outside 4:2:0 8/10-bit, or a decoder refusal that says "unsupported", such as
9-//! profile 1 or 2), or fails. A refusal is reported, not counted as a failure.
10-//!
11-//! LOCAL ONLY and ignored: the manifest is generated from the user's own media
12-//! by `scripts/scan-real-library.sh` and is gitignored, so no other host has it.
13-//! cargo test -p ec-av1 --test real_library -- --ignored --nocapture
14 4
15 use std::io::Read;5 use std::io::Read;
16 use std::path::{Path, PathBuf};6 use std::path::{Path, PathBuf};
17-use std::process::{Child, ChildStdout, Command, Stdio};7+use std::process::{Child, ChildStdout, Stdio};
18 8
19 use ec_av1::encode::Picture;9 use ec_av1::encode::Picture;
20 10
@@ -24,15 +14,6 @@ const FRAMES: usize = 300;
24 /// Pixel formats inside the decoder's scope: 4:2:0 at 8 or 10 bits.14 /// Pixel formats inside the decoder's scope: 4:2:0 at 8 or 10 bits.
25 const IN_SCOPE_PIX_FMTS: [&str; 2] = ["yuv420p", "yuv420p10le"];15 const IN_SCOPE_PIX_FMTS: [&str; 2] = ["yuv420p", "yuv420p10le"];
26 16
27-fn have_ffmpeg() -> bool {
28- Command::new("ffmpeg")
29- .arg("-version")
30- .stdout(Stdio::null())
31- .stderr(Stdio::null())
32- .status()
33- .is_ok_and(|s| s.success())
34-}
35-
36 fn scratch(tag: &str) -> PathBuf {17 fn scratch(tag: &str) -> PathBuf {
37 let base = std::env::var_os("TMPDIR").map_or_else(std::env::temp_dir, PathBuf::from);18 let base = std::env::var_os("TMPDIR").map_or_else(std::env::temp_dir, PathBuf::from);
38 let dir = base.join(format!("ec-av1-{tag}-{}", std::process::id()));19 let dir = base.join(format!("ec-av1-{tag}-{}", std::process::id()));
@@ -40,7 +21,7 @@ fn scratch(tag: &str) -> PathBuf {
40 dir21 dir
41 }22 }
42 23
43-/// One manifest row: the columns the sweep reads.24+/// One input clip: the columns the sweep reads.
44 struct Entry {25 struct Entry {
45 path: PathBuf,26 path: PathBuf,
46 container: String,27 container: String,
@@ -49,31 +30,14 @@ struct Entry {
49 pix_fmt: String,30 pix_fmt: String,
50 }31 }
51 32
52-fn manifest_av1_entries() -> Vec<Entry> {33+fn open_entries() -> Vec<Entry> {
53- let manifest =34+ vec![Entry {
54- Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/real-library-manifest.tsv");35+ path: ec_testkit::fixture("derived/sintel720-svtav1.ivf"),
55- let text = std::fs::read_to_string(&manifest).unwrap_or_else(|e| {36+ container: "ivf".to_string(),
56- panic!(37+ width: "1280".to_string(),
57- "{}: {e}. This test sweeps the personal library; generate the manifest with \38+ height: "720".to_string(),
58- scripts/scan-real-library.sh on the machine that holds the media.",39+ pix_fmt: "yuv420p".to_string(),
59- manifest.display()40+ }]
60- )
61- });
62- let mut out = Vec::new();
63- for line in text.lines().skip(1) {
64- let f: Vec<&str> = line.split('\t').collect();
65- if f.len() < 6 || f[2] != "av1" || !Path::new(f[0]).is_file() {
66- continue;
67- }
68- out.push(Entry {
69- path: PathBuf::from(f[0]),
70- container: f[1].to_string(),
71- width: f[3].to_string(),
72- height: f[4].to_string(),
73- pix_fmt: f[5].to_string(),
74- });
75- }
76- out
77 }41 }
78 42
79 /// The planes of a picture as the bytes of a planar rawvideo frame: one byte per43 /// The planes of a picture as the bytes of a planar rawvideo frame: one byte per
@@ -187,7 +151,7 @@ fn short_name(path: &Path) -> String {
187 151
188 /// Extracts the first `FRAMES` pictures of the video as a low-overhead OBU stream.152 /// Extracts the first `FRAMES` pictures of the video as a low-overhead OBU stream.
189 fn extract(src: &Path, dst: &Path) -> bool {153 fn extract(src: &Path, dst: &Path) -> bool {
190- Command::new("ffmpeg")154+ ec_testkit::ffmpeg()
191 .args(["-v", "error", "-y", "-i"])155 .args(["-v", "error", "-y", "-i"])
192 .arg(src)156 .arg(src)
193 .args([157 .args([
@@ -208,7 +172,7 @@ fn extract(src: &Path, dst: &Path) -> bool {
208 /// Decodes one OBU stream and compares it with ffmpeg's libdav1d output.172 /// Decodes one OBU stream and compares it with ffmpeg's libdav1d output.
209 fn sweep_file(es: &Path, pix_fmt: &str, bit_depth: u32) -> Result<Sweep, String> {173 fn sweep_file(es: &Path, pix_fmt: &str, bit_depth: u32) -> Result<Sweep, String> {
210 let bps = if bit_depth > 8 { 2 } else { 1 };174 let bps = if bit_depth > 8 { 2 } else { 1 };
211- let mut child = Command::new("ffmpeg")175+ let mut child = ec_testkit::ffmpeg()
212 .args(["-v", "error", "-c:v", "libdav1d", "-i"])176 .args(["-v", "error", "-c:v", "libdav1d", "-i"])
213 .arg(es)177 .arg(es)
214 .args([178 .args([
@@ -253,11 +217,8 @@ fn sweep_file(es: &Path, pix_fmt: &str, bit_depth: u32) -> Result<Sweep, String>
253 }217 }
254 218
255 #[test]219 #[test]
256-#[ignore = "sweeps the PERSONAL media library (fixtures/real-library-manifest.tsv, av1 rows) through ffmpeg/libdav1d; minutes of wall time. Local only: run with --ignored."]220+fn sintel_av1_stream_matches_ffmpeg() {
257-fn real_library_av1_streams_match_ffmpeg() {221+ let entries = open_entries();
258- assert!(have_ffmpeg(), "ffmpeg is required to sweep the library");
259- let entries = manifest_av1_entries();
260- assert!(!entries.is_empty(), "the manifest lists no av1 rows");
261 let dir = scratch("real-library-av1");222 let dir = scratch("real-library-av1");
262 let mut table = String::new();223 let mut table = String::new();
263 let mut decoded = 0usize;224 let mut decoded = 0usize;
crates/ec-av1/tests/yuv422_dav1d.rsmodified+3 -21
@@ -6,12 +6,10 @@
6 //! sizes (176x96, 200x120, 330x190) next to the 352x288 clip that first showed6 //! sizes (176x96, 200x120, 330x190) next to the 352x288 clip that first showed
7 //! the right-edge chroma defect (8 bit, CDEF and LR off, frame 3).7 //! the right-edge chroma defect (8 bit, CDEF and LR off, frame 3).
8 //!8 //!
9-//! The test SKIPs when ffmpeg lacks the `libaom-av1` encoder or the `libdav1d`
10-//! decoder.
11 9
12 use ec_av1::encode::Picture;10 use ec_av1::encode::Picture;
13 use std::path::{Path, PathBuf};11 use std::path::{Path, PathBuf};
14-use std::process::{Command, Stdio};12+use std::process::Stdio;
15 13
16 const FRAMES: usize = 6;14 const FRAMES: usize = 6;
17 15
@@ -81,18 +79,6 @@ fn cases() -> Vec<Case> {
81 v79 v
82 }80 }
83 81
84-/// Whether ffmpeg has both `libaom-av1` (encode) and `libdav1d` (decode).
85-fn have_tools() -> bool {
86- let list = |flag: &str| -> String {
87- Command::new("ffmpeg")
88- .args(["-hide_banner", flag])
89- .output()
90- .map(|o| String::from_utf8_lossy(&o.stdout).into_owned())
91- .unwrap_or_default()
92- };
93- list("-encoders").contains("libaom-av1") && list("-decoders").contains("libdav1d")
94-}
95-
96 fn scratch(tag: &str) -> PathBuf {82 fn scratch(tag: &str) -> PathBuf {
97 let base = std::env::var_os("TMPDIR").map_or_else(std::env::temp_dir, PathBuf::from);83 let base = std::env::var_os("TMPDIR").map_or_else(std::env::temp_dir, PathBuf::from);
98 let dir = base.join(format!("ec-av1-422-{tag}-{}", std::process::id()));84 let dir = base.join(format!("ec-av1-422-{tag}-{}", std::process::id()));
@@ -105,7 +91,7 @@ fn encode(case: &Case, path: &Path) {
105 let src = if case.seed % 2 == 1 { "testsrc2" } else { "mandelbrot" };91 let src = if case.seed % 2 == 1 { "testsrc2" } else { "mandelbrot" };
106 let source = format!("{src}=size={}x{}:rate=25", case.width, case.height);92 let source = format!("{src}=size={}x{}:rate=25", case.width, case.height);
107 let noise = format!("noise=alls=12:allf=t:all_seed={}", 1000 + case.seed);93 let noise = format!("noise=alls=12:allf=t:all_seed={}", 1000 + case.seed);
108- let mut cmd = Command::new("ffmpeg");94+ let mut cmd = ec_testkit::ffmpeg();
109 cmd.args([95 cmd.args([
110 "-v", "error", "-y", "-f", "lavfi", "-i", &source, "-vf",96 "-v", "error", "-y", "-f", "lavfi", "-i", &source, "-vf",
111 &noise, "-frames:v", &FRAMES.to_string(), "-c:v", "libaom-av1",97 &noise, "-frames:v", &FRAMES.to_string(), "-c:v", "libaom-av1",
@@ -151,7 +137,7 @@ fn split_frames(case: &Case, raw: &[u8]) -> Vec<(Vec<u16>, Vec<u16>, Vec<u16>)>
151 }137 }
152 138
153 fn dav1d_decode(case: &Case, path: &Path) -> Vec<(Vec<u16>, Vec<u16>, Vec<u16>)> {139 fn dav1d_decode(case: &Case, path: &Path) -> Vec<(Vec<u16>, Vec<u16>, Vec<u16>)> {
154- let out = Command::new("ffmpeg")140+ let out = ec_testkit::ffmpeg()
155 .args(["-v", "error", "-c:v", "libdav1d", "-i"])141 .args(["-v", "error", "-c:v", "libdav1d", "-i"])
156 .arg(path)142 .arg(path)
157 .args(["-f", "rawvideo", "-pix_fmt", case.pix_fmt(), "-"])143 .args(["-f", "rawvideo", "-pix_fmt", case.pix_fmt(), "-"])
@@ -212,10 +198,6 @@ fn compare(case: &Case, ours: &[Picture], oracle: &[(Vec<u16>, Vec<u16>, Vec<u16
212 198
213 #[test]199 #[test]
214 fn yuv422_matches_dav1d_byte_exact() {200 fn yuv422_matches_dav1d_byte_exact() {
215- if !have_tools() {
216- eprintln!("SKIP yuv422_matches_dav1d_byte_exact: ffmpeg lacks libaom-av1 or libdav1d");
217- return;
218- }
219 let dir = scratch("cases");201 let dir = scratch("cases");
220 let mut failures = Vec::new();202 let mut failures = Vec::new();
221 for case in cases() {203 for case in cases() {