forge
Explore
Log in

Don't you dare go Hollow

ec-av1: delete gate/census scaffolding (gate_coverage, refusal_inventory, t01-t10, gates_a/b, support.rs), tool_cache and aom-oracle scripts; fix fallout

Browse files at this commit

2c5dce01a03209c88722690688f8daf62e8c3379Ahmet Kaan GümüşParent: 47ea150

31 changed files +27 -62534

crates/ec-av1/src/decode/coeffs.rsmodified+0 -9
@@ -4344,15 +4344,6 @@ fn a_var_tx_tree_never_presents_a_leaf_larger_than_the_unit_it_entered() {
4344 // lane-av1refusalspan: this gate is the PROOF for both var-tx refusals, so4344 // lane-av1refusalspan: this gate is the PROOF for both var-tx refusals, so
4345 // it names both and pins both guard sites. The walk below proves the leaf4345 // it names both and pins both guard sites. The walk below proves the leaf
4346 // domain; it never said which two strings that domain was about.4346 // domain; it never said which two strings that domain was about.
4347- for refusal in [
4348- "an inter var-tx tree with a leaf transform larger than 32x32",
4349- "an inter var-tx tree with a leaf transform larger than 64x64",
4350- ] {
4351- assert!(
4352- crate::refusal_inventory::pins_refusal(crate::test_source::module_source("decode"), refusal),
4353- "this gate proves {refusal:?}, but that string is no longer in decode.rs"
4354- );
4355- }
4356 // Every leaf `read_var_tx_size` can reach from `entry`, as (depth, w, h).4347 // Every leaf `read_var_tx_size` can reach from `entry`, as (depth, w, h).
4357 fn reachable(entry: (usize, usize), depth: usize, out: &mut Vec<(usize, usize, usize)>) {4348 fn reachable(entry: (usize, usize), depth: usize, out: &mut Vec<(usize, usize, usize)>) {
4358 out.push((depth, entry.0, entry.1));4349 out.push((depth, entry.0, entry.1));
crates/ec-av1/src/decode/rect.rsmodified+0 -10
@@ -1754,16 +1754,6 @@ pub(super) const BLOCK_SIZES_ALL_WH: [(usize, usize); 22] = [
1754 /// clause rejects before the lookup.1754 /// clause rejects before the lookup.
1755 #[test]1755 #[test]
1756 fn every_shape_that_allows_motion_variation_has_a_motion_mode_cdf_row() {1756 fn every_shape_that_allows_motion_variation_has_a_motion_mode_cdf_row() {
1757- // lane-av1refusalspan: this gate is the PROOF for the refusal below, so it
1758- // names it and pins its guard site.
1759- const REFUSAL: &str = "a motion_mode symbol for a block shape with no CDF row here";
1760- assert!(
1761- crate::refusal_inventory::pins_refusal(
1762- crate::test_source::module_source("decode"),
1763- REFUSAL
1764- ),
1765- "this gate proves {REFUSAL:?}, but that string is no longer in decode.rs"
1766- );
1767 let mut rows = std::collections::BTreeSet::new();1757 let mut rows = std::collections::BTreeSet::new();
1768 let mut excluded = 0;1758 let mut excluded = 0;
1769 for (w, h) in BLOCK_SIZES_ALL_WH {1759 for (w, h) in BLOCK_SIZES_ALL_WH {
crates/ec-av1/src/decode/tests.rsmodified+2 -12
@@ -2433,16 +2433,6 @@ fn an_obmc_neighbour_with_no_recorded_filter_refuses_instead_of_panicking() {
2433 #[test]2433 #[test]
2434 fn every_inter_record_publishes_an_obmc_readable_filter() {2434 fn every_inter_record_publishes_an_obmc_readable_filter() {
2435 let src = crate::test_source::module_source("decode");2435 let src = crate::test_source::module_source("decode");
2436- // lane-av1refusalspan: this gate is the PROOF for the refusal below, so
2437- // it names it and pins its guard site. The sibling test
2438- // `an_obmc_neighbour_with_no_recorded_filter_refuses_instead_of_panicking`
2439- // carries the same string 27k lines away in this file -- exactly the
2440- // reach a window that is not a function boundary used to have.
2441- const REFUSAL: &str = "an OBMC neighbour whose switchable interp filter was never recorded";
2442- assert!(
2443- crate::refusal_inventory::pins_refusal(src, REFUSAL),
2444- "this gate proves {REFUSAL:?}, but that string is no longer in decode.rs"
2445- );
2446 let mut calls = 0usize;2436 let mut calls = 0usize;
2447 for (start, _) in src.match_indices("record_inter_rect_mi(") {2437 for (start, _) in src.match_indices("record_inter_rect_mi(") {
2448 // Skip the definition and the wrapper's own forwarding call.2438 // Skip the definition and the wrapper's own forwarding call.
@@ -3144,7 +3134,7 @@ fn ffprobe_size(stream: &[u8]) -> (u32, u32) {
3144 ));3134 ));
3145 let _ = std::fs::remove_file(&path);3135 let _ = std::fs::remove_file(&path);
3146 std::fs::write(&path, stream).expect("writing the probe stream");3136 std::fs::write(&path, stream).expect("writing the probe stream");
3147- let out = crate::tool_cache::cached_output_io(Command::new("ffprobe")3137+ let out = Command::new("ffprobe")
3148 .args([3138 .args([
3149 "-v",3139 "-v",
3150 "error",3140 "error",
@@ -3157,7 +3147,7 @@ fn ffprobe_size(stream: &[u8]) -> (u32, u32) {
3157 "-of",3147 "-of",
3158 "csv=p=0",3148 "csv=p=0",
3159 ])3149 ])
3160- .arg(&path), None, |c| c.output())3150+ .arg(&path).output()
3161 .expect("ffprobe failed to run");3151 .expect("ffprobe failed to run");
3162 let _ = std::fs::remove_file(&path);3152 let _ = std::fs::remove_file(&path);
3163 assert!(3153 assert!(
crates/ec-av1/src/encode/more_tests.rsmodified+6 -6
@@ -763,10 +763,10 @@ use std::process::Command;
763 /// Two consecutive decoded frames from one clip, for an inter-frame763 /// Two consecutive decoded frames from one clip, for an inter-frame
764 /// sweep -- [`clip_frame`] alone only ever gives one.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] {765 pub(super) fn clip_frame_pair(clip: &str, skip: &str, width: usize, height: usize) -> [Picture; 2] {
766- let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg")766+ let out = Command::new("ffmpeg")
767 .args(["-v", "error", "-ss", skip, "-i", clip, "-frames:v", "2"])767 .args(["-v", "error", "-ss", skip, "-i", clip, "-frames:v", "2"])
768 .args(["-vf", &format!("scale={width}:{height}")])768 .args(["-vf", &format!("scale={width}:{height}")])
769- .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]), None, |c| c.output())769+ .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]).output()
770 .expect("ffmpeg failed to run");770 .expect("ffmpeg failed to run");
771 assert!(771 assert!(
772 out.status.success(),772 out.status.success(),
@@ -1197,7 +1197,7 @@ use std::process::Command;
1197 std::process::id()1197 std::process::id()
1198 ));1198 ));
1199 let start = std::time::Instant::now();1199 let start = std::time::Instant::now();
1200- let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg")1200+ let out = Command::new("ffmpeg")
1201 .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"])1201 .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"])
1202 .args(["-s", &format!("{width}x{height}"), "-r", "24", "-i"])1202 .args(["-s", &format!("{width}x{height}"), "-r", "24", "-i"])
1203 .arg(&raw_path)1203 .arg(&raw_path)
@@ -1205,7 +1205,7 @@ use std::process::Command;
1205 .args(["-g", &source.len().to_string(), "-c:v", encoder])1205 .args(["-g", &source.len().to_string(), "-c:v", encoder])
1206 .args(params)1206 .args(params)
1207 .args(["-f", "obu"])1207 .args(["-f", "obu"])
1208- .arg(&obu), None, |c| c.output())1208+ .arg(&obu).output()
1209 .expect("ffmpeg failed to run");1209 .expect("ffmpeg failed to run");
1210 wall += start.elapsed().as_secs_f64();1210 wall += start.elapsed().as_secs_f64();
1211 assert!(1211 assert!(
@@ -1818,11 +1818,11 @@ use std::process::Command;
1818 // frames, and that is a row to print, not a panic.1818 // frames, and that is a row to print, not a panic.
1819 let decode =1819 let decode =
1820 |clip: &str, seek: &str, vf: &str, w: usize, h: usize, n: usize| -> Vec<Picture> {1820 |clip: &str, seek: &str, vf: &str, w: usize, h: usize, n: usize| -> Vec<Picture> {
1821- let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg")1821+ let out = Command::new("ffmpeg")
1822 .args(["-v", "error", "-ss", seek, "-i", clip])1822 .args(["-v", "error", "-ss", seek, "-i", clip])
1823 .args(["-frames:v", &n.to_string()])1823 .args(["-frames:v", &n.to_string()])
1824 .args(["-vf", vf])1824 .args(["-vf", vf])
1825- .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]), None, |c| c.output());1825+ .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]).output();
1826 let Ok(out) = out else { return Vec::new() };1826 let Ok(out) = out else { return Vec::new() };
1827 if !out.status.success() {1827 if !out.status.success() {
1828 return Vec::new();1828 return Vec::new();
crates/ec-av1/src/encode/tests.rsmodified+6 -6
@@ -774,9 +774,9 @@
774 /// Whether this ffmpeg was built with `encoder` (lane-pareto2: the774 /// Whether this ffmpeg was built with `encoder` (lane-pareto2: the
775 /// SVT-AV1 Pareto rows are skipped, never failed, on a build without it).775 /// SVT-AV1 Pareto rows are skipped, never failed, on a build without it).
776 pub(super) fn have_encoder(encoder: &str) -> bool {776 pub(super) fn have_encoder(encoder: &str) -> bool {
777- crate::tool_cache::cached_output_io(Command::new("ffmpeg")777+ Command::new("ffmpeg")
778 .args(["-hide_banner", "-encoders"])778 .args(["-hide_banner", "-encoders"])
779- .stderr(Stdio::null()), None, |c| c.output())779+ .stderr(Stdio::null()).output()
780 .is_ok_and(|o| {780 .is_ok_and(|o| {
781 String::from_utf8_lossy(&o.stdout)781 String::from_utf8_lossy(&o.stdout)
782 .lines()782 .lines()
@@ -1649,7 +1649,7 @@
1649 ));1649 ));
1650 let _ = std::fs::remove_file(&path);1650 let _ = std::fs::remove_file(&path);
1651 std::fs::write(&path, stream).expect("writing the probe stream");1651 std::fs::write(&path, stream).expect("writing the probe stream");
1652- let out = crate::tool_cache::cached_output_io(Command::new("ffprobe")1652+ let out = Command::new("ffprobe")
1653 .args([1653 .args([
1654 "-v",1654 "-v",
1655 "error",1655 "error",
@@ -1662,7 +1662,7 @@
1662 "-of",1662 "-of",
1663 "csv=p=0",1663 "csv=p=0",
1664 ])1664 ])
1665- .arg(&path), None, |c| c.output())1665+ .arg(&path).output()
1666 .expect("ffprobe failed to run");1666 .expect("ffprobe failed to run");
1667 let _ = std::fs::remove_file(&path);1667 let _ = std::fs::remove_file(&path);
1668 assert!(1668 assert!(
@@ -2259,10 +2259,10 @@
2259 2259
2260 /// One frame of a real clip, scaled to a whole number of 32x32 blocks.2260 /// 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 {2261 pub(super) fn clip_frame(clip: &str, skip: &str, width: usize, height: usize) -> Picture {
2262- let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg")2262+ let out = Command::new("ffmpeg")
2263 .args(["-v", "error", "-ss", skip, "-i", clip, "-frames:v", "1"])2263 .args(["-v", "error", "-ss", skip, "-i", clip, "-frames:v", "1"])
2264 .args(["-vf", &format!("scale={width}:{height}")])2264 .args(["-vf", &format!("scale={width}:{height}")])
2265- .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]), None, |c| c.output())2265+ .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]).output()
2266 .expect("ffmpeg failed to run");2266 .expect("ffmpeg failed to run");
2267 assert!(2267 assert!(
2268 out.status.success(),2268 out.status.success(),
crates/ec-av1/src/encoder/tests.rsmodified+12 -33
@@ -489,7 +489,7 @@
489 std::ptr::addr_of!(stream) as usize489 std::ptr::addr_of!(stream) as usize
490 ));490 ));
491 std::fs::write(&path, stream).expect("writing the probe stream");491 std::fs::write(&path, stream).expect("writing the probe stream");
492- let out = crate::tool_cache::cached_output_io(Command::new("ffprobe")492+ let out = Command::new("ffprobe")
493 .args([493 .args([
494 "-v",494 "-v",
495 "error",495 "error",
@@ -502,7 +502,7 @@
502 "-of",502 "-of",
503 "csv=p=0",503 "csv=p=0",
504 ])504 ])
505- .arg(&path), None, |c| c.output())505+ .arg(&path).output()
506 .expect("ffprobe failed to run");506 .expect("ffprobe failed to run");
507 let _ = std::fs::remove_file(&path);507 let _ = std::fs::remove_file(&path);
508 assert!(508 assert!(
@@ -529,7 +529,7 @@
529 std::ptr::addr_of!(stream) as usize529 std::ptr::addr_of!(stream) as usize
530 ));530 ));
531 std::fs::write(&path, stream).expect("writing the probe stream");531 std::fs::write(&path, stream).expect("writing the probe stream");
532- let out = crate::tool_cache::cached_output_io(Command::new("ffprobe")532+ let out = Command::new("ffprobe")
533 .args([533 .args([
534 "-v",534 "-v",
535 "error",535 "error",
@@ -542,7 +542,7 @@
542 "-of",542 "-of",
543 "csv=p=0",543 "csv=p=0",
544 ])544 ])
545- .arg(&path), None, |c| c.output())545+ .arg(&path).output()
546 .expect("ffprobe failed to run");546 .expect("ffprobe failed to run");
547 let _ = std::fs::remove_file(&path);547 let _ = std::fs::remove_file(&path);
548 assert!(548 assert!(
@@ -745,11 +745,11 @@
745 // therefore `return` on `None` WITHOUT printing a second one -- the745 // therefore `return` on `None` WITHOUT printing a second one -- the
746 // second "no fixture" line per gate was the noise that hid this defect.746 // second "no fixture" line per gate was the noise that hid this defect.
747 let clip = crate::library_fixture::require_at(clip, what)?;747 let clip = crate::library_fixture::require_at(clip, what)?;
748- let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg")748+ let out = Command::new("ffmpeg")
749 .args(["-v", "error", "-i", clip.to_str().unwrap()])749 .args(["-v", "error", "-i", clip.to_str().unwrap()])
750 .args(["-frames:v", &frames.to_string()])750 .args(["-frames:v", &frames.to_string()])
751 .args(["-vf", &format!("scale={width}:{height}")])751 .args(["-vf", &format!("scale={width}:{height}")])
752- .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]), None, |c| c.output())752+ .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]).output()
753 .expect("ffmpeg failed to run");753 .expect("ffmpeg failed to run");
754 assert!(754 assert!(
755 out.status.success(),755 out.status.success(),
@@ -1217,10 +1217,10 @@
1217 std::ptr::addr_of!(stream) as usize1217 std::ptr::addr_of!(stream) as usize
1218 ));1218 ));
1219 std::fs::write(&path, stream).expect("writing the decode probe stream");1219 std::fs::write(&path, stream).expect("writing the decode probe stream");
1220- let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg")1220+ let out = Command::new("ffmpeg")
1221 .args(["-v", "error", "-f", "obu", "-i"])1221 .args(["-v", "error", "-f", "obu", "-i"])
1222 .arg(&path)1222 .arg(&path)
1223- .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]), None, |c| c.output())1223+ .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]).output()
1224 .expect("ffmpeg failed to run");1224 .expect("ffmpeg failed to run");
1225 let _ = std::fs::remove_file(&path);1225 let _ = std::fs::remove_file(&path);
1226 assert!(1226 assert!(
@@ -1269,7 +1269,6 @@
1269 fn a_palette_block_cut_by_the_frame_edge_decodes_exactly_through_ffmpeg() {1269 fn a_palette_block_cut_by_the_frame_edge_decodes_exactly_through_ffmpeg() {
1270 const NAME: &str = "a_palette_block_cut_by_the_frame_edge_decodes_exactly_through_ffmpeg";1270 const NAME: &str = "a_palette_block_cut_by_the_frame_edge_decodes_exactly_through_ffmpeg";
1271 let _knobs = crate::speed::knob_read();1271 let _knobs = crate::speed::knob_read();
1272- let _gate_lock = crate::stream::tests::lock_gate_counters();
1273 let (width, height) = (384usize, 152usize);1272 let (width, height) = (384usize, 152usize);
1274 // A 16-px two-tone checkerboard: every 16x16 and 32x32 block holds at1273 // A 16-px two-tone checkerboard: every 16x16 and 32x32 block holds at
1275 // most two luma values, so the palette arm wins across the WHOLE1274 // most two luma values, so the palette arm wins across the WHOLE
@@ -2073,7 +2072,6 @@
2073 /// Runs only inside `superblock_size_global_suite`.2072 /// Runs only inside `superblock_size_global_suite`.
2074 pub(crate) fn a_static_clip_codes_128x128_superblock_roots_and_decodes_sample_exact() {2073 pub(crate) fn a_static_clip_codes_128x128_superblock_roots_and_decodes_sample_exact() {
2075 let _knobs = crate::speed::knob_write();2074 let _knobs = crate::speed::knob_write();
2076- let _gate_lock = crate::stream::tests::lock_gate_counters();
2077 crate::encode::force_sb128(true);2075 crate::encode::force_sb128(true);
2078 let (width, height) = (256usize, 128usize);2076 let (width, height) = (256usize, 128usize);
2079 let still = test_card(width, height, 0);2077 let still = test_card(width, height, 0);
@@ -2121,7 +2119,6 @@
2121 #[test]2119 #[test]
2122 fn a_static_clip_codes_64x64_roots_and_decodes_sample_exact() {2120 fn a_static_clip_codes_64x64_roots_and_decodes_sample_exact() {
2123 let _knobs = crate::speed::knob_write();2121 let _knobs = crate::speed::knob_write();
2124- let _gate_lock = crate::stream::tests::lock_gate_counters();
2125 let (width, height) = (256usize, 128usize);2122 let (width, height) = (256usize, 128usize);
2126 let still = test_card(width, height, 0);2123 let still = test_card(width, height, 0);
2127 let sources: Vec<Picture> = (0..3).map(|_| still.clone()).collect();2124 let sources: Vec<Picture> = (0..3).map(|_| still.clone()).collect();
@@ -2190,7 +2187,6 @@
2190 #[test]2187 #[test]
2191 fn a_dc_stepped_clip_codes_a_64x64_residual_and_decodes_sample_exact() {2188 fn a_dc_stepped_clip_codes_a_64x64_residual_and_decodes_sample_exact() {
2192 let _knobs = crate::speed::knob_write();2189 let _knobs = crate::speed::knob_write();
2193- let _gate_lock = crate::stream::tests::lock_gate_counters();
2194 let (width, height) = (256usize, 128usize);2190 let (width, height) = (256usize, 128usize);
2195 let still = test_card(width, height, 0);2191 let still = test_card(width, height, 0);
2196 let sources: Vec<Picture> = (0..3)2192 let sources: Vec<Picture> = (0..3)
@@ -2264,7 +2260,6 @@
2264 #[test]2260 #[test]
2265 fn a_non_superblock_aligned_clip_codes_edge_64x64_roots_and_decodes_sample_exact() {2261 fn a_non_superblock_aligned_clip_codes_edge_64x64_roots_and_decodes_sample_exact() {
2266 let _knobs = crate::speed::knob_write();2262 let _knobs = crate::speed::knob_write();
2267- let _gate_lock = crate::stream::tests::lock_gate_counters();
2268 let (width, height) = (232usize, 168usize);2263 let (width, height) = (232usize, 168usize);
2269 let still = test_card(width, height, 0);2264 let still = test_card(width, height, 0);
2270 let sources: Vec<Picture> = (0..3).map(|_| still.clone()).collect();2265 let sources: Vec<Picture> = (0..3).map(|_| still.clone()).collect();
@@ -2330,7 +2325,6 @@
2330 #[test]2325 #[test]
2331 fn a_1080p_shaped_clip_straddles_at_every_block_size_and_decodes_sample_exact() {2326 fn a_1080p_shaped_clip_straddles_at_every_block_size_and_decodes_sample_exact() {
2332 let _knobs = crate::speed::knob_write();2327 let _knobs = crate::speed::knob_write();
2333- let _gate_lock = crate::stream::tests::lock_gate_counters();
2334 let (width, height) = (384usize, 216usize);2328 let (width, height) = (384usize, 216usize);
2335 let sources: Vec<Picture> = (0..3).map(|i| test_card(width, height, i)).collect();2329 let sources: Vec<Picture> = (0..3).map(|i| test_card(width, height, i)).collect();
2336 let config = EncoderConfig {2330 let config = EncoderConfig {
@@ -2387,7 +2381,6 @@
2387 #[test]2381 #[test]
2388 fn a_high_frequency_clip_splits_the_64x64_roots_luma_and_decodes_sample_exact() {2382 fn a_high_frequency_clip_splits_the_64x64_roots_luma_and_decodes_sample_exact() {
2389 let _knobs = crate::speed::knob_write();2383 let _knobs = crate::speed::knob_write();
2390- let _gate_lock = crate::stream::tests::lock_gate_counters();
2391 let (width, height) = (256usize, 128usize);2384 let (width, height) = (256usize, 128usize);
2392 let still = test_card(width, height, 0);2385 let still = test_card(width, height, 0);
2393 let sources: Vec<Picture> = (0..4)2386 let sources: Vec<Picture> = (0..4)
@@ -2460,7 +2453,6 @@
2460 #[test]2453 #[test]
2461 fn a_crossfade_clip_codes_a_compound_64x64_root_and_decodes_sample_exact() {2454 fn a_crossfade_clip_codes_a_compound_64x64_root_and_decodes_sample_exact() {
2462 let _knobs = crate::speed::knob_write();2455 let _knobs = crate::speed::knob_write();
2463- let _gate_lock = crate::stream::tests::lock_gate_counters();
2464 let (width, height) = (256usize, 128usize);2456 let (width, height) = (256usize, 128usize);
2465 let (a, b) = (test_card(width, height, 0), test_card(width, height, 24));2457 let (a, b) = (test_card(width, height, 0), test_card(width, height, 24));
2466 let sources: Vec<Picture> = (0..9)2458 let sources: Vec<Picture> = (0..9)
@@ -2630,7 +2622,6 @@
2630 // `knob_write`, not `knob_read`: the override below is2622 // `knob_write`, not `knob_read`: the override below is
2631 // process-global and every other test's bytes move under it.2623 // process-global and every other test's bytes move under it.
2632 let _knobs = crate::speed::knob_write();2624 let _knobs = crate::speed::knob_write();
2633- let _gate_lock = crate::stream::tests::lock_gate_counters();
2634 crate::encode::set_deltaq_res(Some(2));2625 crate::encode::set_deltaq_res(Some(2));
2635 let (width, height) = (640usize, 384usize);2626 let (width, height) = (640usize, 384usize);
2636 // The gate's own moving test card, with a 128x128 patch of fine2627 // The gate's own moving test card, with a 128x128 patch of fine
@@ -2730,7 +2721,6 @@
2730 // type search is SCREEN-ONLY (`encode::tx_type_candidates`).2721 // type search is SCREEN-ONLY (`encode::tx_type_candidates`).
2731 let _knobs = crate::speed::knob_write();2722 let _knobs = crate::speed::knob_write();
2732 crate::encode::force_screen(Some(true));2723 crate::encode::force_screen(Some(true));
2733- let _gate_lock = crate::stream::tests::lock_gate_counters();
2734 let (width, height) = (320usize, 192usize);2724 let (width, height) = (320usize, 192usize);
2735 // Sharp horizontal and vertical steps: a vertical edge is what an2725 // Sharp horizontal and vertical steps: a vertical edge is what an
2736 // `ADST` column pass beats a `DCT` one on, a horizontal edge the2726 // `ADST` column pass beats a `DCT` one on, a horizontal edge the
@@ -2847,7 +2837,6 @@
2847 // this turns it on process-globally under the same exclusive lock the2837 // this turns it on process-globally under the same exclusive lock the
2848 // presets take.2838 // presets take.
2849 let _knobs = crate::speed::knob_write();2839 let _knobs = crate::speed::knob_write();
2850- let _gate_lock = crate::stream::tests::lock_gate_counters();
2851 crate::encode::set_inter_tx_search(Some(true));2840 crate::encode::set_inter_tx_search(Some(true));
2852 let (width, height) = (320usize, 192usize);2841 let (width, height) = (320usize, 192usize);
2853 // Sharp steps that MOVE: the motion-compensated residual along a2842 // Sharp steps that MOVE: the motion-compensated residual along a
@@ -2945,7 +2934,6 @@
2945 // Every lever below is process-global: the same exclusive lock the2934 // Every lever below is process-global: the same exclusive lock the
2946 // presets take.2935 // presets take.
2947 let _knobs = crate::speed::knob_write();2936 let _knobs = crate::speed::knob_write();
2948- let _gate_lock = crate::stream::tests::lock_gate_counters();
2949 crate::encode::set_intra_tx_search(Some(true));2937 crate::encode::set_intra_tx_search(Some(true));
2950 crate::encode::set_inter_tx_search(Some(true));2938 crate::encode::set_inter_tx_search(Some(true));
2951 crate::encode::set_wide_tx_set(Some(true));2939 crate::encode::set_wide_tx_set(Some(true));
@@ -3067,7 +3055,6 @@
3067 #[ignore = "sets process-global search levers: run it alone"]3055 #[ignore = "sets process-global search levers: run it alone"]
3068 fn a_non_screen_inter_clip_codes_a_one_d_type_both_decoders_read_every_plane_exactly() {3056 fn a_non_screen_inter_clip_codes_a_one_d_type_both_decoders_read_every_plane_exactly() {
3069 let _knobs = crate::speed::knob_write();3057 let _knobs = crate::speed::knob_write();
3070- let _gate_lock = crate::stream::tests::lock_gate_counters();
3071 crate::encode::set_intra_tx_search(Some(true));3058 crate::encode::set_intra_tx_search(Some(true));
3072 crate::encode::set_inter_tx_search(Some(true));3059 crate::encode::set_inter_tx_search(Some(true));
3073 crate::encode::set_wide_tx_set(Some(true));3060 crate::encode::set_wide_tx_set(Some(true));
@@ -3173,7 +3160,6 @@
3173 #[ignore = "sets the process-global speed preset: run it alone"]3160 #[ignore = "sets the process-global speed preset: run it alone"]
3174 fn every_speed_preset_decodes_sample_exact_through_both_decoders() {3161 fn every_speed_preset_decodes_sample_exact_through_both_decoders() {
3175 let _knobs = crate::speed::knob_write();3162 let _knobs = crate::speed::knob_write();
3176- let _gate_lock = crate::stream::tests::lock_gate_counters();
3177 let (width, height) = (640usize, 384usize);3163 let (width, height) = (640usize, 384usize);
3178 let sources: Vec<Picture> = (0..4).map(|t| test_card(width, height, t * 3)).collect();3164 let sources: Vec<Picture> = (0..4).map(|t| test_card(width, height, t * 3)).collect();
3179 let mut sizes: Vec<(u8, usize)> = Vec::new();3165 let mut sizes: Vec<(u8, usize)> = Vec::new();
@@ -3252,7 +3238,6 @@
3252 #[ignore = "wall table, 16 cells x 2 passes at 1080p: 27 min measured; needs a host with >=8 cores"]3238 #[ignore = "wall table, 16 cells x 2 passes at 1080p: 27 min measured; needs a host with >=8 cores"]
3253 fn tile_wall_table_at_1080p() {3239 fn tile_wall_table_at_1080p() {
3254 let _knobs = crate::speed::knob_write();3240 let _knobs = crate::speed::knob_write();
3255- let _gate_lock = crate::stream::tests::lock_gate_counters();
3256 let (width, height) = (1920usize, 1080usize);3241 let (width, height) = (1920usize, 1080usize);
3257 let Some(sources) = h264_clip_frames("tile_wall_table_at_1080p", width, height, 8) else {3242 let Some(sources) = h264_clip_frames("tile_wall_table_at_1080p", width, height, 8) else {
3258 return;3243 return;
@@ -3302,7 +3287,6 @@
3302 #[test]3287 #[test]
3303 fn tile_bytes_do_not_depend_on_the_thread_count() {3288 fn tile_bytes_do_not_depend_on_the_thread_count() {
3304 let _knobs = crate::speed::knob_write();3289 let _knobs = crate::speed::knob_write();
3305- let _gate_lock = crate::stream::tests::lock_gate_counters();
3306 let (width, height) = (320usize, 192usize);3290 let (width, height) = (320usize, 192usize);
3307 let sources: Vec<Picture> = (0..3).map(|t| test_card(width, height, t * 3)).collect();3291 let sources: Vec<Picture> = (0..3).map(|t| test_card(width, height, t * 3)).collect();
3308 let coded = |threads: usize, cols_log2: u32, rows_log2: u32| {3292 let coded = |threads: usize, cols_log2: u32, rows_log2: u32| {
@@ -3384,7 +3368,6 @@
3384 #[test]3368 #[test]
3385 fn filter_stage_bytes_do_not_depend_on_the_thread_count() {3369 fn filter_stage_bytes_do_not_depend_on_the_thread_count() {
3386 let _knobs = crate::speed::knob_write();3370 let _knobs = crate::speed::knob_write();
3387- let _gate_lock = crate::stream::tests::lock_gate_counters();
3388 let (width, height) = (384usize, 288usize);3371 let (width, height) = (384usize, 288usize);
3389 let sources: Vec<Picture> = (0..4).map(|t| test_card(width, height, t * 3)).collect();3372 let sources: Vec<Picture> = (0..4).map(|t| test_card(width, height, t * 3)).collect();
3390 let coded = |threads: usize| {3373 let coded = |threads: usize| {
@@ -3426,7 +3409,6 @@
3426 #[test]3409 #[test]
3427 fn filter_replay_codes_the_same_stream_as_a_full_decode() {3410 fn filter_replay_codes_the_same_stream_as_a_full_decode() {
3428 let _knobs = crate::speed::knob_read();3411 let _knobs = crate::speed::knob_read();
3429- let _gate_lock = crate::stream::tests::lock_gate_counters();
3430 let run = |width: usize, height: usize, off: bool| {3412 let run = |width: usize, height: usize, off: bool| {
3431 let sources: Vec<Picture> = (0..4).map(|t| test_card(width, height, t * 3)).collect();3413 let sources: Vec<Picture> = (0..4).map(|t| test_card(width, height, t * 3)).collect();
3432 crate::decode::set_filter_replay_disabled(off);3414 crate::decode::set_filter_replay_disabled(off);
@@ -3472,7 +3454,6 @@
3472 #[test]3454 #[test]
3473 fn filter_replay_final_matches_the_capture_decode() {3455 fn filter_replay_final_matches_the_capture_decode() {
3474 let _knobs = crate::speed::knob_read();3456 let _knobs = crate::speed::knob_read();
3475- let _gate_lock = crate::stream::tests::lock_gate_counters();
3476 let run = |sources: &[Picture], width: usize, height: usize, tiles: (u32, u32)| {3457 let run = |sources: &[Picture], width: usize, height: usize, tiles: (u32, u32)| {
3477 let config = EncoderConfig {3458 let config = EncoderConfig {
3478 width,3459 width,
@@ -3546,7 +3527,6 @@
3546 (cols_log2, rows_log2): (u32, u32),3527 (cols_log2, rows_log2): (u32, u32),
3547 threads: &[usize],3528 threads: &[usize],
3548 ) {3529 ) {
3549- let _gate_lock = crate::stream::tests::lock_gate_counters();
3550 let Some(sources) = h264_clip_frames("the filter-stage breakdown", width, height, frames)3530 let Some(sources) = h264_clip_frames("the filter-stage breakdown", width, height, frames)
3551 else {3531 else {
3552 return;3532 return;
@@ -3618,7 +3598,6 @@
3618 layouts: &[(u32, u32)],3598 layouts: &[(u32, u32)],
3619 threads: &[usize],3599 threads: &[usize],
3620 ) {3600 ) {
3621- let _gate_lock = crate::stream::tests::lock_gate_counters();
3622 let Some(sources) = h264_clip_frames("the tile-search wall table", width, height, frames)3601 let Some(sources) = h264_clip_frames("the tile-search wall table", width, height, frames)
3623 else {3602 else {
3624 return;3603 return;
@@ -3716,8 +3695,8 @@
3716 layouts: &[(u32, u32)],3695 layouts: &[(u32, u32)],
3717 threads: &[usize],3696 threads: &[usize],
3718 ) {3697 ) {
3719- let listed = crate::tool_cache::cached_output_io(Command::new("ffmpeg")3698+ let listed = Command::new("ffmpeg")
3720- .args(["-hide_banner", "-encoders"]), None, |c| c.output());3699+ .args(["-hide_banner", "-encoders"]).output();
3721 let has_rav1e = listed3700 let has_rav1e = listed
3722 .map(|o| String::from_utf8_lossy(&o.stdout).contains("librav1e"))3701 .map(|o| String::from_utf8_lossy(&o.stdout).contains("librav1e"))
3723 .unwrap_or(false);3702 .unwrap_or(false);
@@ -3747,12 +3726,12 @@
3747 1 << r3726 1 << r
3748 );3727 );
3749 let start = std::time::Instant::now();3728 let start = std::time::Instant::now();
3750- let status = crate::tool_cache::cached_output_io(Command::new("ffmpeg")3729+ let status = Command::new("ffmpeg")
3751 .args(["-v", "error", "-y", "-i", clip.to_str().unwrap()])3730 .args(["-v", "error", "-y", "-i", clip.to_str().unwrap()])
3752 .args(["-frames:v", &frames.to_string()])3731 .args(["-frames:v", &frames.to_string()])
3753 .args(["-vf", &format!("scale={width}:{height}")])3732 .args(["-vf", &format!("scale={width}:{height}")])
3754 .args(["-c:v", "librav1e", "-rav1e-params", &params])3733 .args(["-c:v", "librav1e", "-rav1e-params", &params])
3755- .arg(out.to_str().unwrap()), None, |c| c.output())3734+ .arg(out.to_str().unwrap()).output()
3756 .expect("ffmpeg failed to run");3735 .expect("ffmpeg failed to run");
3757 let secs = start.elapsed().as_secs_f64();3736 let secs = start.elapsed().as_secs_f64();
3758 if !status.status.success() {3737 if !status.status.success() {
crates/ec-av1/src/gate_coverage.rsdeleted+0 -2775

Diff too large; view file

@@ -1,2775 +0,0 @@
1-//! A guard over the real-aomenc gates' own encoder recipes.
2-//!
3-//! Every gate in [`crate::stream`] that runs a real `aomenc` picks its coding
4-//! tools with `--enable-*=0/1` flags, and a flag left off the command line
5-//! takes aomenc's default. That default is `1` for essentially every tool in
6-//! [`TOOL_UNIVERSE`] on a non-realtime build -- `default_extra_cfg` in
7-//! `av1/av1_cx_iface.c` is all-ones across the seq-level tool fields, and this
8-//! oracle is built with `CONFIG_REALTIME_ONLY 0`. But a `1` default is NOT
9-//! the same as the tool reaching the stream, and the rest of this file's
10-//! "defaulted means unknown" rule rests on that gap: palette and intrabc are
11-//! gated on CONTENT (`encoder.c:2079` derives `allow_screen_content_tools`
12-//! from block counts, and `seq_force_screen_content_tools` is left at the
13-//! adaptive `SELECT_SCREEN_CONTENT_TOOLS`), and `speed_features.c` masks
14-//! several tools OFF again per `--cpu-used`. A `1` default proves the encoder
15-//! was ALLOWED the tool, never that any block used it.
16-//!
17-//! With that default in place it is possible -- and it happened -- for a
18-//! coding tool to be switched *off in every single gate*, so that no real
19-//! stream in this repository ever exercised it and a corner-cut in the
20-//! decoder survived twenty gates unnoticed: `reconstruct`'s
21-//! `smooth_neighbor` was hardcoded `false`, wrong whenever a directional
22-//! block neighbours a smooth-mode one, and invisible because all twenty
23-//! gates passed `--enable-smooth-intra=0` (lane-chroma r1, 2026-08-30).
24-//!
25-//! The test below re-derives that set from the gate source and pins it. A tool
26-//! that is switched off in every gate and on in none is *provably never
27-//! exercised* by a real stream, and belongs on [`NEVER_EXERCISED`] with a
28-//! reason. Landing the decode support for one means enabling it in that
29-//! feature's gate, which shrinks the derived set and fails this test until the
30-//! list is updated -- the point being that the shrink is noticed.
31-
32-// TILING is deliberately NOT in this derivation (lane-tiles r11): the check
33-// keys on `--enable-<tool>=0/1`, and `--tile-columns=<log2>` has no such
34-// shape -- a `--tile-columns=` presence check would also read `=0` (one tile)
35-// as coverage, which is the opposite of what it would claim. It needs no
36-// entry either: measured 2026-09-29 (lane-av1distwtd r2), 19 of the 146
37-// census-selected gate bodies spell `--tile-columns`/`--tile-rows` with a
38-// nonzero log2 -- 9 assert the parsed `tile_info` in the same body and 10
39-// more delegate to a shared helper that asserts it -- and
40-// `run_multi_tile_gate` covers a 2D grid with the coding tools ON at both
41-// bit depths.
42-
43-/// aomenc coding tools that no real-`aomenc` gate is proven to exercise:
44-/// switched off in every gate that names them, and on in none.
45-///
46-/// A gate that simply leaves the flag off its command line does NOT close the
47-/// hole. aomenc's default for these is content-dependent -- palette and
48-/// intrabc only come on for screen content -- so "defaulted" means "unknown",
49-/// not "exercised", and treating it as coverage would retire the entry
50-/// without a single stream proving the decoder ever saw the tool. Only an
51-/// explicit `--enable-<tool>=1` in a gate that then asserts the feature fired
52-/// closes one.
53-///
54-/// Each entry is `(flag, why)`. Removing an entry is how a lane records that
55-/// its tool is now covered by a real stream.
56-#[cfg(test)]
57-const NEVER_EXERCISED: &[(&str, &str)] = &[
58- // `enable-intrabc` LEFT this list on 2026-09-02 (lane-kf900 r6). The
59- // premise it carried -- "every real stream's intrabc block sits under
60- // TX_MODE_SELECT" -- was false: with `--enable-tx-size-search=0` aomenc
61- // codes intrabc blocks under TX_MODE_LARGEST, and
62- // `a_real_aomenc_screen_key_frame_reads_use_intrabc_on_rect_strips`
63- // spells `--enable-intrabc=1` and decodes three such 8-bit streams whole-
64- // frame pixel-exact against ffmpeg, with the block counter asserted > 0.
65- // Re-verified 2026-09-17 (lane-av1-intrabc) at main f715d70c: 185 rect
66- // `use_intrabc` symbols read, and 5 blocks took the DV path -- 4 of them
67- // DECODED whole-frame pixel-exact across 4 arms (7 frames compared, 0
68- // mismatches). The fifth is the testsrc2 rectangle-strip arm, which reads
69- // the symbol and then refuses by name (the `intrabc_hits` bump happens on
70- // the READ), so "5 blocks decoded" would overcount: 4 decoded + 1 refused,
71- // exactly the single `refused == 1` the gate asserts.
72-];
73-
74-/// The `--enable-*` tools this decoder cares about, whether or not any gate
75-/// names one. A flag no gate mentions is *defaulted*, i.e. unknown, and by the
76-/// rule above unknown is not coverage -- so the universe is fixed here rather
77-/// than derived from the gate source, which would silently shrink to whatever
78-/// the gates happen to spell.
79-#[cfg(test)]
80-const TOOL_UNIVERSE: &[&str] = &[
81- "enable-1to4-partitions",
82- "enable-ab-partitions",
83- "enable-angle-delta",
84- "enable-cdef",
85- "enable-cfl-intra",
86- "enable-dist-wtd-comp",
87- "enable-dual-filter",
88- "enable-filter-intra",
89- "enable-flip-idtx",
90- "enable-global-motion",
91- "enable-interintra-comp",
92- "enable-intra-edge-filter",
93- "enable-intrabc",
94- "enable-masked-comp",
95- "enable-obmc",
96- "enable-order-hint",
97- "enable-paeth-intra",
98- "enable-palette",
99- "enable-rect-partitions",
100- "enable-rect-tx",
101- "enable-ref-frame-mvs",
102- "enable-restoration",
103- "enable-smooth-intra",
104- "enable-superres",
105- "enable-tx64",
106- "enable-warped-motion",
107-];
108-
109-/// How a non-boolean aomenc knob reads as "the tool is on".
110-#[cfg(test)]
111-#[derive(Clone, Copy, PartialEq)]
112-enum On {
113- /// Any non-zero value enables the tool (`--tile-columns=1`, `--loopfilter-control=1`).
114- NonZero,
115- /// The tool's search only runs at or below this speed (`--cpu-used`).
116- AtMost(u32),
117-}
118-
119-/// Coding tools aomenc drives through a spelling [`TOOL_UNIVERSE`] does not
120-/// cover, listed with their aomenc default.
121-///
122-/// lane-covbd's derivation read `--enable-*` flags only, so a tool a gate pins
123-/// off through another spelling was invisible: every gate that named
124-/// `--enable-tx-size-search` passed `--enable-tx-size-search=0` when this was
125-/// written, and the real-stream PANIC hiding behind that pin was found by
126-/// lane-ab16, not by this guard. `--loopfilter-control=0`,
127-/// `--tile-columns=0` and a `--cpu-used` high enough to switch a search off are
128-/// the same shape. `enable-tx-size-search` has since been SETTLED, in both
129-/// directions -- see the entry below and `print_tx_size_search_census`.
130-///
131-/// The "all 49" count is GONE as of 2026-09-29 (lane-av1distwtd r2) and is
132-/// deliberately not replaced by a number here: it is a snapshot that rots
133-/// every time a recipe changes. The live count is a TEST
134-/// ([`print_tx_size_search_census`], below), not prose, so it cannot go stale
135-/// silently -- re-run it and read the numbers rather than trusting a comment.
136-///
137-/// Each entry is `(tool, spellings, aomenc default, what counts as on)`. The
138-/// "defaulted means unknown" rule of [`NEVER_EXERCISED`] applies unchanged: a
139-/// default of `1` does not prove the encoder picked the tool for any stream, so
140-/// only a gate that spells an on-value at that bit depth retires an entry.
141-// `enable-tx-size-search` SETTLED 2026-09-29 (lane-av1txsearch), by
142-// measurement rather than by a name-shaped guess. The r3 note here said the
143-// count was a FLOOR: 9 gate bodies built the flag into a `format!`
144-// variable that neither `flags_in` nor `settings_in` could see, because
145-// both scan for a literal `"--flag=value"` inside one segment. The method
146-// r3 asked for is now [`spelling_values`] -> [`bound_values`], and it
147-// resolves all of them; `print_tx_size_search_census` asserts the
148-// unresolvable count is ZERO, so the floor cannot come back unnoticed.
149-//
150-// THE ENTRY IS RETIRED, on an ARRIVAL ASSERT rather than on the spelling.
151-// `a_real_aomenc_stream_with_a_1d_tx_class_on_a_rect_transform_decodes_pixel_exact`
152-// spells `--enable-tx-size-search=1` as a literal and hard-asserts
153-// `compared_tx_depths > 0` -- "never produced a nonzero tx depth on a
154-// compared attempt -- the flag did not arrive". `tx_depth` is read ONLY
155-// under the frame header's `tx_mode_select` bit (spec 5.11.16,
156-// `decode.rs`: the read is guarded by `tx_select_inter`), so a nonzero
157-// counter IS the parsed tx-size-search behaviour, not a proxy for it.
158-// Measured run of that gate on this tree (aom 3.13.3): 12 pixel-exact
159-// decodes, 0 named refusals, 6 of the 12 at 10 BIT, 219 rect coefficient
160-// TUs on compared attempts, and `flag arrival: ... tx depths 53` -- so the
161-// tool is exercised at BOTH depths, and the assertion is not vacuous.
162-//
163-// The `tx_select_inter_gate` twins
164-// (`a_real_aomenc_inter_sequence_with_tx_select_decodes_pixel_exact{,_10bit}`)
165-// are the stronger witness still: they DELIBERATELY omit the flag
166-// ("DELIBERATELY ABSENT: --enable-tx-size-search=0") and assert
167-// `decode::txfm_split_hits()` moved, proving the var-tx `txfm_split` tree
168-// of spec 5.11.17 is read -- an inter transform is then a recursive split
169-// tree, which is the whole content of the tool.
170-#[cfg(test)]
171-const DEFAULT_ON_TOOLS: &[(&str, &[&str], &str, On)] = &[
172- (
173- "enable-tx-size-search",
174- &["enable-tx-size-search"],
175- "1",
176- On::NonZero,
177- ),
178- (
179- "enable-directional-intra",
180- &["enable-directional-intra"],
181- "1",
182- On::NonZero,
183- ),
184- (
185- "enable-smooth-interintra",
186- &["enable-smooth-interintra"],
187- "1",
188- On::NonZero,
189- ),
190- (
191- "enable-interintra-wedge",
192- &["enable-interintra-wedge"],
193- "1",
194- On::NonZero,
195- ),
196- (
197- "enable-diff-wtd-comp",
198- &["enable-diff-wtd-comp"],
199- "1",
200- On::NonZero,
201- ),
202- (
203- "enable-onesided-comp",
204- &["enable-onesided-comp"],
205- "1",
206- On::NonZero,
207- ),
208- ("enable-fwd-kf", &["enable-fwd-kf"], "0", On::NonZero),
209- ("deblocking", &["loopfilter-control"], "1", On::NonZero),
210- (
211- "multi-tile",
212- &["tile-columns", "tile-rows"],
213- "0",
214- On::NonZero,
215- ),
216- ("intrabc-search", &["cpu-used"], "0", On::AtMost(2)),
217-];
218-
219-/// Non-`--enable-*` spellings that drive a [`TOOL_UNIVERSE`] tool.
220-///
221-/// `--superres-mode=1` is how every superres gate switches superres on;
222-/// without this map they read as an `enable-superres` hole while a real stream
223-/// exercises the tool (lane-covbd deferred exactly this). The count was "all
224-/// three" until 2026-09-29 (lane-av1distwtd r2), which measured SIX gates
225-/// spelling a nonzero `--superres-mode` (5 among the 146 census-selected
226-/// bodies, plus `a_superres_census_over_six_real_streams_...`). No count is
227-/// given here for the same reason as `enable-tx-size-search` above: it rots.
228-/// Worth noting the alias is the ONLY positive evidence for superres, and
229-/// those gates do assert arrival -- `superres_hits` / `predict_scaled_hits`
230-/// are read in five of them -- so this one is a healthy alias, not a
231-/// spelling-only one.
232-#[cfg(test)]
233-const ALIASES: &[(&str, &str)] = &[("superres-mode", "enable-superres")];
234-
235-/// Coverage is per (tool x bit depth), not per tool.
236-///
237-/// lane-hbdinter found two 10-bit-only defects (SGR box sums unscaled, Wiener
238-/// clamp pinned at the 8-bit bound) that survived the "10-bit bit-exact"
239-/// milestone because every 10-bit gate passed `--enable-restoration=0`:
240-/// `enable-restoration` is positively exercised -- at 8 bits only. A tool the
241-/// 8-bit gates cover says nothing about the high-bit-depth path through the
242-/// same code, so the two lists below are pinned separately.
243-///
244-/// Each entry is `(flag, why)`. A gate that passes `--enable-<tool>=1` at that
245-/// depth retires the entry, and this test fails until it is deleted.
246-#[cfg(test)]
247-const NEVER_EXERCISED_8BIT: &[(&str, &str)] = &[
248- // `enable-cfl-intra` LEFT both lists on 2026-09-02 (lane-reelckf r1): the
249- // sb128 skipped-CfL / 1:4-chroma gate passes `--enable-cfl-intra=1` at 8
250- // AND 10 bits and pixel-compares both arms.
251- // `enable-dist-wtd-comp` LEFT this list on 2026-09-29 (lane-av1distwtd).
252- // The entry's stated reason was WRONG: the distance-weighted compound
253- // combine is not unimplemented -- `compound::dist_wtd_comp_weight_assign`
254- // (lane-av1comp) and `mc::combine_compound`'s weighted path have been in
255- // the tree for a long time. What was missing was a stream CARRYING the
256- // tool, and `a_distance_weighted_compound_stream_decodes_pixel_exact`
257- // (stream.rs) now supplies one: it spells `--enable-dist-wtd-comp=1` and
258- // asserts the PARSED sequence header carries `enable_jnt_comp == true`
259- // (and `false` from the same recipe with `=0`, so the bit is proven to
260- // move with the flag), that `dist_wtd_comp_hits() > 0` -- the
261- // `compound_idx == 0` arm, the only branch whose blend weights are not the
262- // constant (8, 8) -- and pixel-compares every frame against the oracle.
263- // The existing lane-cwarp compound-warp gates already SPELLED `=1` and
264- // the census still read this entry as open, so the hole was a missing
265- // witness, not a missing flag.
266- // `enable-dual-filter` LEFT this list on 2026-09-29 (lane-av1distwtd r3),
267- // paid by a DETECTOR fix rather than by a new gate. The r2 audit found
268- // this entry's reason false on both halves. It is spelled -- as `=0`, by
269- // `real_aomenc_1to4_streams_...` and
270- // `a_real_aomenc_inter_sequence_with_32x32_level_1to4_strips_...` -- so
271- // "never spelled" was wrong; and a stream IS proven to carry the tool,
272- // because `a_real_aomenc_dual_filter_obmc_8x8_inter_sequence_decodes_pixel_exact`
273- // spells `--enable-dual-filter=1` and hard-asserts
274- // `decode::dual_filter_diff_hits()` moved, the differing-direction arrival
275- // assert (`resolve_interp_filter` in decode.rs). That gate builds its
276- // stream through `inter_sb_none_gate`, so it spells none of the three
277- // tokens `gate_bodies()` used to filter on and was INVISIBLE to the
278- // census; r3 made `gate_bodies()` resolve calls as well as spellings, and
279- // `the_detector_sees_the_gates_the_spelling_filter_missed` pins that.
280- // Supporting measurement: with the flag left off the command line the
281- // parsed sequence header already carries `enable_dual_filter = true`
282- // (6855 B), while `--enable-dual-filter=0` parses false and encodes
283- // different bytes (6874 B) -- so the gates pinning it `=0` were removing
284- // the tool and the ones leaving it defaulted carry it.
285- //
286- // `enable-flip-idtx` LEFT this list the same day, also by detector fix.
287- // `a_real_aomenc_stream_with_a_1d_tx_class_on_a_rect_transform_decodes_pixel_exact`
288- // spells `=1` and hard-asserts `compared_class1 > 0` ("--enable-flip-idtx=1
289- // never produced a V_DCT/H_DCT transform on a compared attempt"). Its
290- // recipe is parameterised on `ten_bit` and names BOTH fixture formats, so
291- // `is_ten_bit` filed the whole body 10-bit-ONLY and the 8-bit bucket
292- // never saw it -- the lane-defon/reelckf blind spot through a THIRD
293- // spelling, which r3 taught `covers_both_depths` to recognise as the
294- // pair-of-formats marker. Measured run of that gate: 12 pixel-exact
295- // decodes, 6 of them 8-bit, 219 rect coefficient TUs of which 10 carry a
296- // 1D tx class.
297- // `enable-global-motion` LEFT this list on 2026-09-25 (lane-av1gwarp12 r2):
298- // `a_real_affine_global_motion_stream_decodes_pixel_exact` loops
299- // `for depth in [8u32, 10u32]` passing `--enable-global-motion=1` and
300- // pixel-compares both depths, so the 8-bit hole has been closed since
301- // lane-gmaffine r1 -- the entry survived because no suite ran a tree
302- // containing both the gate and this test until the ROTZOOM suite.
303- // The 12-bit ROTZOOM gate rides the high-depth bucket via `encode_12bit(`
304- // in `is_ten_bit`, so it plays no part in this retirement.
305- // `enable-rect-tx` -- reason RE-VERIFIED 2026-09-29 (lane-av1distwtd
306- // r2), both halves still TRUE, and the second half is now PROVEN rather
307- // than asserted. (1) "never spelled": measured across all 146
308- // census-selected gate bodies, zero spell `--enable-rect-tx` at either
309- // depth -- the only `--enable-*` tool in [`TOOL_UNIVERSE`] with no
310- // spelling anywhere. (2) "reach the decoder only through partition
311- // shape": aom 3.13.3 has no sequence-header bit for it. `enable_rect_tx`
312- // is an `AV1E_SET_ENABLE_RECT_TX` encoder-search control
313- // (`av1_cx_iface.c:2125`, copied to `txfm_cfg->enable_rect_tx` at
314- // `av1_cx_iface.c:1483`) and is read ONLY inside `tx_search.c`
315- // (lines 2568/2662/2686/2710/2956); `bitstream.c` writes no such bit, and
316- // this crate's `SequenceHeader` (`ec-av1-syntax/src/sequence.rs`) has no
317- // such field. The decoder's own gate is `is_rect_tx_allowed`, derived
318- // from partition shape -- exactly what this reason says. A gate can
319- // therefore never prove this tool by naming the flag, only by proving a
320- // rect transform unit fired (`rect_partition_hits` /
321- // `rect_coeff_tu_hits`, which lane-rect1d's gate does assert).
322- // `enable-rect-tx` LEFT this list on 2026-09-29 (merge wave 2,
323- // lane-av1toolgates). Both halves of the reason recorded above still hold
324- // as statements about the FLAG, and the second is exactly why the closing
325- // evidence is a parsed shape and not a spelling: `enable_rect_tx` has no
326- // sequence-header bit, so a decoder path can never be proven by naming the
327- // flag -- only by proving a rect transform unit fired.
328- // `a_real_aomenc_8bit_stream_with_a_rect_transform_decodes_pixel_exact`
329- // (and its 10-bit twin) now spell `--enable-rect-tx=1` in their OWN test
330- // bodies -- inline on purpose, because a helper-owned recipe collapses
331- // both gates into one helper segment that `is_ten_bit` files 10-bit, and
332- // the 8-bit hole would stay open -- and prove the tool on the PARSED
333- // shape: `rect_partition_hits()` and `rect_coeff_tu_hits()` are both
334- // asserted > 0 over arms that decoded AND pixel-compared, and each
335- // counter is mutation-proven red on its own message.
336- // Census on the merged tree (`print_never_exercised_per_bit_depth`):
337- // 255 real-aomenc gate bodies, NEVER_EXERCISED derived EMPTY at 8 bits
338- // and at 10 bits -- 0 of 26 tools -- so this list is empty on the same
339- // evidence, not by deletion of a claim.
340-];
341-
342-#[cfg(test)]
343-const NEVER_EXERCISED_10BIT: &[(&str, &str)] = &[
344- // lane-cwarp's 10-bit compound-global-warp gate closed `enable-global-motion`
345- // and `enable-dist-wtd-comp` at 10 bits without deleting their entries here,
346- // so this list was already stale (and this test already red) at main 9c35ecc;
347- // lane-tiles r11's multi-tile 10-bit gates then closed `enable-ab-partitions`,
348- // `enable-rect-partitions` and `enable-restoration` at 10 bits. All five
349- // deleted together.
350-
351- // The "Only 4 of the 45 real-aomenc gates encode at 10 bits" sentence that
352- // stood here is STALE (lane-av1distwtd r2, 2026-09-29), and understated
353- // the high-depth bucket by more than an order of magnitude. Measured
354- // against this tree with `gate_bodies()`' own filter: 146 selected gate
355- // bodies, of which 83 are classified 10-bit-or-higher by `is_ten_bit`.
356- // The historical point stands -- those gates pin the pixel filters and
357- // the intra tool set off far more often than not -- but the counts a
358- // reader would check them against no longer exist.
359- // Every entry the 8-bit list carries is a hole here too. lane-hbdgates r1
360- // closed six of the seven 8-bit-only entries with real 10-bit gates
361- // paeth-intra, intra-edge-filter, rect-partitions, ab-partitions); its
362- // seventh, the 10-bit LR gate, was `#[ignore]`d on that branch and passes
363- // un-ignored on main, which carries the fix.
364- // `enable-restoration` LEFT this list on 2026-09-01: lane-hbdinter's
365- // 10-bit inter gate passes `--enable-restoration=1` and asserts a real
366- // Wiener/SGR unit fired, which is what caught the two defects (SGR box
367- // sums never brought back to the 8-bit scale, Wiener clamp at the wrong
368- // bound). `enable-dist-wtd-comp` and `enable-global-motion` left it the
369- // same day for the same reason: lane-cwarp's 10-bit compound global-warp
370- // gate passes `=1` for both. `enable-1to4-partitions` left it on 2026-09-02:
371- // lane-tx64x16 r4's 32-level 1:4 gate has a 10-bit arm that asserts both
372- // orientations and coded strips inside pixel-exact attempts.
373- // `enable-dual-filter` -- reason CORRECTED 2026-09-29 (lane-av1distwtd
374- // r3), and this entry STAYS while its 8-bit twin was retired. That is the
375- // honest outcome, not an oversight: after the r3 detector fix the 8-bit
376- // bucket sees the tool exercised and the 10-bit bucket still does not.
377- // The only `=1` witness is
378- // `a_real_aomenc_dual_filter_obmc_8x8_inter_sequence_decodes_pixel_exact`,
379- // and it calls `inter_sb_none_gate(NAME, false, ...)` -- `false` is the
380- // `ten_bit` parameter, so that gate builds an 8-bit stream only. Its
381- // sibling `a_real_aomenc_10bit_inter_sequence_with_a_whole_superblock_block_decodes_pixel_exact`
382- // passes `true`, and the 8x8-leaf pair likewise, but none of those spells
383- // `--enable-dual-filter=1`. So: exercised at 8 bits (arrival assert
384- // `dual_filter_diff_hits()` moved, `resolve_interp_filter` in decode.rs),
385- // NOT exercised at 10 bits. Retiring this entry needs a 10-bit arm of that
386- // gate -- pass `true` to `inter_sb_none_gate` and assert the differing-
387- // direction counter still moves there.
388- //
389- // The two numbers in the `enable-flip-idtx` retirement below were
390- // RE-MEASURED 2026-09-29 (lane-av1distwtd r2) by running the gate, and
391- // both still hold exactly: "pixel-compares six 10-bit decodes" (the run
392- // reports 12 pixel-exact decodes, 6 of them 10-bit) and "10 of its rect
393- // coefficient TUs carry a 1D tx class" (219 rect coefficient TUs on
394- // compared attempts, 10 of them 1D). The gate also hard-asserts
395- // `compared_class1 > 0`, so its "passes =1 at both depths" is backed by an
396- // arrival assert, not just a spelling.
397- // `enable-dual-filter` LEFT this list on 2026-09-29 (merge wave 2,
398- // lane-av1dualfilter10), by exactly the 10-bit arm the note above names.
399- // `a_real_aomenc_10bit_dual_filter_obmc_8x8_inter_sequence_decodes_pixel_exact`
400- // spells `--enable-dual-filter=1` in its own body and hard-asserts the
401- // arrival counter `decode::dual_filter_diff_hits()` moved at 10 BITS, so
402- // the entry is closed at the depth it was held open at, not by a spelling
403- // alone.
404- // `enable-flip-idtx` LEFT this list on 2026-09-02 (lane-rect1d r1):
405- // `a_real_aomenc_stream_with_a_1d_tx_class_on_a_rect_transform_decodes_pixel_exact`
406- // passes `=1` at both depths and pixel-compares six 10-bit decodes, so the
407- // flip/identity/1D transform types are proven to reach a real 10-bit stream
408- // this decoder reconstructs exactly (10 of its rect coefficient TUs carry a
409- // 1D tx class).
410- // `enable-intrabc` LEFT this 10-bit list on 2026-09-02 (lane-kf900 r6).
411- // The entry it first rested on was a flag spelling -- the palette gate's
412- // `smptebars-screen-txs-cq40/cq55` arms pass `--enable-intrabc=1` -- and
413- // lane-av1-intrabc MEASURED that those arms decode ZERO intrabc blocks at
414- // both depths, so they retired the entry without a stream carrying the
415- // tool (class `tool-disabled-in-every-gate`, the same defect this list
416- // exists for). The closing evidence is now
417- // `an_sb128_screen_stream_with_intrabc_decodes_pixel_exact`: its sb128
418- // screen recipes run at 10 bits and hard-assert a decoded intrabc block
419- // per depth (4-6 per arm), every frame pixel-compared against ffmpeg's own
420- // 10-bit decode.
421- // `enable-rect-tx` LEFT this list on 2026-09-29 (merge wave 2,
422- // lane-av1toolgates), together with its 8-bit twin, by
423- // `a_real_aomenc_10bit_stream_with_a_rect_transform_decodes_pixel_exact`:
424- // the depth is spelled in the test's OWN body, which is what files it in
425- // the 10-bit bucket, and the witness is the parsed shape
426- // (`rect_partition_hits()` / `rect_coeff_tu_hits()` > 0 over arms that
427- // decoded AND pixel-compared). See the 8-bit list for why the flag alone
428- // could never have been the evidence.
429-];
430-
431-/// [`DEFAULT_ON_TOOLS`] entries no 8-bit gate spells on, with the reason.
432-///
433-/// Each entry is `(tool, why)`; the reason states whether the tool is pinned
434-/// OFF in every gate that names it (a hard hole -- no stream can carry it) or
435-/// merely defaulted (unknown, and unknown is not coverage).
436-#[cfg(test)]
437-const NEVER_ON_8BIT: &[(&str, &str)] = &[];
438-
439-/// [`DEFAULT_ON_TOOLS`] entries no 10-bit gate spells on, with the reason.
440-#[cfg(test)]
441-const NEVER_ON_10BIT: &[(&str, &str)] = &[];
442-
443-#[cfg(test)]
444-mod tests {
445- use super::{
446- ALIASES, DEFAULT_ON_TOOLS, NEVER_EXERCISED, NEVER_EXERCISED_8BIT, NEVER_EXERCISED_10BIT,
447- NEVER_ON_8BIT, NEVER_ON_10BIT, On, TOOL_UNIVERSE,
448- };
449- use std::collections::{BTreeMap, BTreeSet};
450-
451- /// Whether `body` contains a call to the `fn` named `name`.
452- ///
453- /// The name must not be the tail of a longer identifier, or
454- /// `inter_sb_none_gate` would "call" `sb_none_gate`.
455- fn calls_fn(body: &str, name: &str) -> bool {
456- let ident = |b: u8| b.is_ascii_alphanumeric() || b == b'_';
457- let mut at = 0usize;
458- while let Some(rel) = body[at..].find(name) {
459- let start = at + rel;
460- let end = start + name.len();
461- let starts_clean = start == 0 || !ident(body.as_bytes()[start - 1]);
462- if starts_clean && body[end..].starts_with('(') {
463- return true;
464- }
465- at = end;
466- }
467- false
468- }
469-
470- /// Every `fn` defined in `stream.rs`'s test module, as `(name, body)`.
471- ///
472- /// The census reasons about whole `#[`-segments (see [`gate_bodies`]) but
473- /// has to know which segment DEFINES or CALLS an encoder-driving `fn`, and
474- /// the only way to answer that is to name the units.
475- fn fn_units(src: &'static str) -> Vec<(&'static str, &'static str)> {
476- const OPEN: &str = "\n fn ";
477- let mut units = Vec::new();
478- let mut at = 0usize;
479- while let Some(rel) = src[at..].find(OPEN) {
480- let head = at + rel + OPEN.len();
481- let Some(paren) = src[head..].find('(') else {
482- break;
483- };
484- let close = src[head..]
485- .find("\n }\n")
486- .map_or(src.len(), |e| head + e);
487- units.push((&src[head..head + paren], &src[head..close]));
488- at = close.max(head + paren + 1);
489- }
490- units
491- }
492-
493- /// Names of every `fn` in `stream.rs` that drives the real `aomenc`,
494- /// DIRECTLY (it mentions `aomenc_path()`) or by DELEGATING to one.
495- ///
496- /// lane-av1distwtd r3: the transitive closure is the whole point. A gate
497- /// that hands its recipe to a shared helper (`inter_sb_none_gate` and
498- /// friends) never spells `--passes=1` itself, so the old token filter
499- /// dropped it -- 165 of 311 segments, 6 of which spell `--enable-X=1`.
500- /// That is not a coverage fact, it is a segmentation fact, and it is what
501- /// kept `enable-dual-filter` on the never-exercised lists while a named
502- /// gate exercised the tool and hard-asserted the arrival.
503- fn encoder_fns(src: &'static str) -> BTreeSet<&'static str> {
504- let units = fn_units(src);
505- let mut enc: BTreeSet<&'static str> = units
506- .iter()
507- .filter(|(_, body)| body.contains("aomenc_path()"))
508- .map(|(name, _)| *name)
509- .collect();
510- // Fixpoint: `inter_sb_none_gate` is an encoder fn because it names
511- // `aomenc_path()`; the `#[test]` that only CALLS it is a gate too.
512- loop {
513- let mut grew = false;
514- for (name, body) in &units {
515- if enc.contains(name) {
516- continue;
517- }
518- if enc.iter().any(|e| calls_fn(body, e)) {
519- enc.insert(name);
520- grew = true;
521- }
522- }
523- if !grew {
524- return enc;
525- }
526- }
527- }
528-
529- /// The token spellings the filter used before it resolved calls. Kept as a
530- /// floor: a gate is still recognised by these even if the call graph
531- /// misses it, so the fix can only ever ADD gates, never lose one.
532- fn legacy_gate_tokens(body: &str) -> bool {
533- body.contains("\"--passes=1\"")
534- || body.contains("ten_bit_tool_gate(")
535- || body.contains("encode_10bit_gradients")
536- }
537-
538- /// Bodies of the real-aomenc gates: a `fn` body that drives the real
539- /// `aomenc`, however it gets there. Split on the attribute that opens a
540- /// test.
541- ///
542- /// lane-av1distwtd r3: a segment qualifies if it spells one of the
543- /// [`legacy_gate_tokens`] OR names an encoder `fn` -- either by defining
544- /// one (it mentions `aomenc_path()`) or by calling one. Recognition by
545- /// CALL is what a helper-delegating gate needs: its flags live in the
546- /// helper it calls, and it is invisible to a spelling-only filter.
547- fn gate_bodies() -> Vec<&'static str> {
548- let src = crate::test_source::module_source("stream");
549- let enc = encoder_fns(src);
550- let gates: Vec<&str> = src
551- .split("\n #[")
552- // lane-hbdgates r1: an `#[ignore]`d gate exercises nothing, so it
553- // must not close a hole. Its body is the segment that opens with
554- // the ignore attribute.
555- .filter(|body| !body.starts_with("ignore"))
556- // lane-av1distwtd r3: a segment qualifies by what it SPELLS
557- // (`legacy_gate_tokens`) or by what it CALLS. `calls_fn` is
558- // deliberately the weak half of an OR, so the fix can only add
559- // gates -- it can never stop recognising one the old filter did.
560- .filter(|body| {
561- legacy_gate_tokens(body)
562- || body.contains("aomenc_path()")
563- || enc.iter().any(|e| calls_fn(body, e))
564- })
565- .collect();
566- assert!(
567- gates.len() >= 20,
568- "expected the real-aomenc gates, found {}",
569- gates.len()
570- );
571- gates
572- }
573-
574- /// `--enable-<flag>=<value>` settings spelled inside one gate body.
575- fn flags_in(gate: &str) -> BTreeMap<String, char> {
576- let mut here = BTreeMap::new();
577- for (i, _) in gate.match_indices("\"--enable-") {
578- let rest = &gate[i + 3..];
579- let Some(end) = rest.find('"') else { continue };
580- let Some((flag, value)) = rest[..end].split_once('=') else {
581- continue;
582- };
583- let Some(value) = value.chars().next() else {
584- continue;
585- };
586- here.insert(flag.to_owned(), value);
587- }
588- here
589- }
590-
591- /// Every `--flag=value` spelled inside one gate body, values kept whole
592- /// (`--cpu-used=4`, `--tile-columns=2`), not just their first character.
593- fn settings_in(gate: &str) -> BTreeMap<String, String> {
594- let mut here = BTreeMap::new();
595- for (i, _) in gate.match_indices("\"--") {
596- let rest = &gate[i + 3..];
597- let Some(end) = rest.find('"') else { continue };
598- let Some((flag, value)) = rest[..end].split_once('=') else {
599- continue;
600- };
601- here.insert(flag.to_owned(), value.to_owned());
602- }
603- here
604- }
605-
606- /// The values a `--<flag>={var}` TEMPLATE can take in one gate body, from
607- /// the local binding of `var`.
608- ///
609- /// lane-av1txsearch: `settings_in` reads a `--flag=value` string LITERAL,
610- /// so a flag a gate builds with `format!` was invisible to it -- 10 gate
611- /// bodies spell `--enable-tx-size-search` only this way, and the census
612- /// filed them as "defaulted", i.e. unknown in BOTH directions. The
613- /// bindings that actually exist in `stream.rs` are four shapes, and each
614- /// is resolved from the gate's own text rather than from the variable's
615- /// name:
616- ///
617- /// 1. `let <var> = if <attempt> == 0 { "0" } else { "1" };` -- an
618- /// attempt-indexed arm; the QUOTED values in the initializer are
619- /// collected. Bare integers in the initializer (`attempt % 2`) are
620- /// deliberately NOT read as flag values.
621- /// 2. `for <var> in [0usize, 1]` / `["0", "1"]` -- a loop over both
622- /// values; every element of the array is collected.
623- /// 3. `for (<var>, <other>) in [("1", 8u8), ("0", 8u8), ...]` -- a
624- /// tuple-destructured loop; only the element at `<var>`'s POSITION is
625- /// collected from each tuple, so the arm table's bit-depth column is
626- /// not read as a flag value.
627- /// 4. `u8::from(<a>.<field>)` over a struct-literal arm table whose
628- /// `field: true` / `field: false` rows are the flag values.
629- ///
630- /// `None` means the binding is NOT in this body -- the variable is a
631- /// parameter of a shared helper and its value is bound at the CALL SITE,
632- /// which lives in a different `#[`-segment. That is a real limit of a
633- /// per-segment census and is reported as unknown rather than guessed:
634- /// inferring the value from the variable's name is the exact failure this
635- /// function exists to remove.
636- fn bound_values(body: &str, var: &str) -> Option<BTreeSet<char>> {
637- // Quoted single digits: `"0"`, `"1"`.
638- let quoted_digits = |t: &str| -> BTreeSet<char> {
639- let mut out = BTreeSet::new();
640- let mut at = 0usize;
641- while let Some(rel) = t[at..].find('"') {
642- let start = at + rel + 1;
643- let Some(end) = t[start..].find('"') else {
644- break;
645- };
646- let literal = &t[start..start + end];
647- if literal.len() == 1
648- && let Some(c) = literal.chars().next()
649- && c.is_ascii_digit() {
650- out.insert(c);
651- }
652- at = start + end + 1;
653- }
654- out
655- };
656- // Bare integer literals: `0usize`, `1`, `8u8`. Whole tokens only, so
657- // `10u8` contributes nothing rather than a bogus `1`.
658- let bare_digits = |t: &str| -> BTreeSet<char> {
659- let mut out = BTreeSet::new();
660- let bytes = t.as_bytes();
661- let mut i = 0usize;
662- while i < bytes.len() {
663- if !bytes[i].is_ascii_digit() {
664- i += 1;
665- continue;
666- }
667- let start = i;
668- while i < bytes.len() && bytes[i].is_ascii_digit() {
669- i += 1;
670- }
671- let clean_before = start == 0 || !is_ident_byte(bytes[start - 1]);
672- // A typed literal's suffix (`0usize`, `8u8`, `1u32`) belongs to
673- // the same token, so a run of LOWERCASE letters right after
674- // the digit is a type, not a different identifier. Anything
675- // else -- a multi-digit `10u8`, a camelCase `1x` -- is not a
676- // flag value and is rejected.
677- let rest = &t[i..];
678- let suffix = rest
679- .bytes()
680- .take_while(|b| b.is_ascii_lowercase() || *b == b'_')
681- .count();
682- let clean_after = i >= bytes.len()
683- || !is_ident_byte(bytes[i])
684- || (suffix > 0
685- && i + suffix < bytes.len()
686- && !is_ident_byte(bytes[i + suffix]));
687- if clean_before && clean_after && i - start == 1 {
688- out.insert(bytes[start] as char);
689- }
690- }
691- out
692- };
693- // Split a comma-separated list at TOP level only, so `("1", 8u8)`
694- // stays one element.
695- fn split_top(t: &str) -> Vec<&str> {
696- let mut out = Vec::new();
697- let (mut depth, mut start) = (0i32, 0usize);
698- for (i, c) in t.char_indices() {
699- match c {
700- '(' | '[' | '{' => depth += 1,
701- ')' | ']' | '}' => depth -= 1,
702- ',' if depth == 0 => {
703- out.push(t[start..i].trim());
704- start = i + 1;
705- }
706- _ => {}
707- }
708- }
709- if start < t.len() {
710- out.push(t[start..].trim());
711- }
712- out
713- }
714- // The body of the `[...]` that FOLLOWS `head` in `text`. Scoped to
715- // the header rather than searching from the start of the body: a
716- // gate's first `[` may be an unrelated array, and brackets that do
717- // not balance across a whole gate body would leave the depth count
718- // never returning to zero.
719- fn loop_array_after<'a>(text: &'a str, head: &str) -> Option<&'a str> {
720- let at = text.find(head)? + head.len();
721- let open = at + text[at..].find('[')?;
722- let mut depth = 0i32;
723- for (i, c) in text[open..].char_indices() {
724- match c {
725- '[' => depth += 1,
726- ']' => {
727- depth -= 1;
728- if depth == 0 {
729- return Some(&text[open + 1..open + i]);
730- }
731- }
732- _ => {}
733- }
734- }
735- None
736- }
737- let mut found: Option<BTreeSet<char>> = None;
738- let mut merge = |set: BTreeSet<char>| match &mut found {
739- Some(all) => all.extend(set),
740- None => found = Some(set),
741- };
742- // (1) `let <var> = if ... { "0" } else { "1" };` -- quoted values only.
743- if let Some(at) = body.find(&format!("let {var} =")) {
744- let init = &body[at..];
745- let end = init.find(';').unwrap_or(init.len());
746- merge(quoted_digits(&init[..end]));
747- }
748- // (2) `for <var> in [...]` -- every element of the array.
749- if let Some(array) = loop_array_after(body, &format!("for {var} in ")) {
750- merge(bare_digits(array));
751- merge(quoted_digits(array));
752- }
753- // (3) `for (<var>, ...) in [(...), ...]` -- only `<var>`'s column.
754- if let Some(at) = body.find("for (") {
755- let head = &body[at..];
756- if let Some(close) = head.find(')') {
757- let pattern = &head["for (".len()..close];
758- if let Some(pos) = pattern.split(',').position(|p| p.trim() == var) {
759- let header = format!("for ({pattern}) in ");
760- if let Some(array) = loop_array_after(body, &header) {
761- let mut set: BTreeSet<char> = BTreeSet::new();
762- for tuple in split_top(array) {
763- let Some(inner) =
764- tuple.strip_prefix('(').and_then(|t| t.strip_suffix(')'))
765- else {
766- continue;
767- };
768- let fields = split_top(inner);
769- let Some(field) = fields.get(pos) else {
770- continue;
771- };
772- set.extend(bare_digits(field));
773- set.extend(quoted_digits(field));
774- }
775- merge(set);
776- }
777- }
778- }
779- }
780- // (3b) `for (<var>, ...) in <ident>` where `<ident>` is a `let`
781- // binding in this same body -- the arm table hoisted OUT of the
782- // loop header, so the `for` line NAMES the array instead of
783- // spelling it. Strategy (3) alone silently reads past the `for`
784- // line to the next `[` in the body (an unrelated `&[..]` flag
785- // list), finds no digits, and returns an empty set: the gate is
786- // then filed as UNRESOLVED even though both of its arms sit
787- // verbatim in the source. Measured: the 128x96 4:4:4 lossy
788- // tx-size-search gate, whose `for (label, search, ...) in arms`
789- // drove `print_tx_size_search_census`'s `unresolvable == 0`
790- // assertion red on merge. The `=` hop matters: the binding's
791- // TYPE annotation is itself bracketed
792- // (`[(&str, &str, TxMode, usize, u64); 2]`), so scanning for the
793- // first `[` after the name would return the type.
794- // `<var>`'s column, read off the arm table a hoisted `for` line
795- // NAMES rather than spells. Returns `None` unless the body really
796- // has that shape, so an unrecognised loop is left to the other
797- // strategies instead of being read as "no values".
798- let named_column = |pos: usize| -> Option<BTreeSet<char>> {
799- let at = body.find("for (")?;
800- let head = &body[at..];
801- let close = head.find(')')?;
802- let after = head[close + 1..].trim_start().strip_prefix("in ")?;
803- let name: &str = after
804- .split(|c: char| !is_ident_byte(c as u8))
805- .next()
806- .filter(|n| !n.is_empty() && !n.starts_with(|c: char| c.is_ascii_digit()))?;
807- let decl = body.find(&format!("let {name}"))?;
808- let after_name = decl + "let ".len() + name.len();
809- // `let arms_foo` must not answer for `let arms`.
810- if body[after_name..]
811- .chars()
812- .next()
813- .is_some_and(|c| is_ident_byte(c as u8))
814- {
815- return None;
816- }
817- // Hop the `=`: the binding's TYPE annotation is itself
818- // bracketed, so the first `[` after the name is the type.
819- let eq = after_name + body[after_name..].find('=')?;
820- let open = eq + 1 + body[eq + 1..].find('[')?;
821- let mut depth = 0i32;
822- for (i, c) in body[open..].char_indices() {
823- match c {
824- '[' => depth += 1,
825- ']' => {
826- depth -= 1;
827- if depth == 0 {
828- let mut set: BTreeSet<char> = Default::default();
829- for tuple in split_top(&body[open + 1..open + i]) {
830- let Some(inner) =
831- tuple.strip_prefix('(').and_then(|t| t.strip_suffix(')'))
832- else {
833- continue;
834- };
835- let fields = split_top(inner);
836- let Some(field) = fields.get(pos) else {
837- continue;
838- };
839- set.extend(bare_digits(field));
840- set.extend(quoted_digits(field));
841- }
842- return Some(set);
843- }
844- }
845- _ => {}
846- }
847- }
848- None
849- };
850- if let Some(at) = body.find("for (") {
851- let head = &body[at..];
852- if let Some(close) = head.find(')') {
853- let pattern = &head["for (".len()..close];
854- if let Some(pos) = pattern.split(',').position(|p| p.trim() == var)
855- && let Some(set) = named_column(pos) {
856- merge(set);
857- }
858- }
859- }
860- // (4) `u8::from(<a>.<field>)` over a struct-literal arm table.
861- for (i, _) in body.match_indices("u8::from(") {
862- let arg = &body[i + "u8::from(".len()..];
863- let Some(close) = arg.find(')') else { continue };
864- let field = arg[..close].rsplit('.').next().unwrap_or_default().trim();
865- if field.is_empty() || !field.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
866- continue;
867- }
868- let mut set = BTreeSet::new();
869- for (row, value) in [("true", '1'), ("false", '0')] {
870- if body.contains(&format!("{field}: {row}")) {
871- set.insert(value);
872- }
873- }
874- merge(set);
875- }
876- found
877- }
878-
879- fn is_ident_byte(b: u8) -> bool {
880- b.is_ascii_alphanumeric() || b == b'_'
881- }
882-
883- /// Values of one [`DEFAULT_ON_TOOLS`] spelling in one gate body: the
884- /// literal `--<spelling>=<digit>` spellings plus every value a `format!`
885- /// template built from a local binding resolves to.
886- ///
887- /// A gate that reaches BOTH values counts ON, not off: it builds a `=1`
888- /// stream on some attempt, which is what the census asks for. This is the
889- /// file's standing "any spelling that says on wins" rule
890- /// (`--tile-columns=0 --tile-rows=1` is a multi-tile stream), now applied
891- /// across a loop's arms as well as across spellings.
892- fn spelling_values(gate: &str, spelling: &str) -> BTreeSet<char> {
893- let mut out = BTreeSet::new();
894- // A literal `"--<spelling>=<digit>"`: the needle ends at the `=`, so
895- // the value starts AT the needle's length, not three characters in.
896- let literal = format!("\"--{spelling}=");
897- for (i, _) in gate.match_indices(&literal) {
898- let rest = &gate[i + literal.len()..];
899- let Some(end) = rest.find('"') else { continue };
900- if let Some(c) = rest[..end].chars().next()
901- && c.is_ascii_digit() {
902- out.insert(c);
903- }
904- }
905- // A template `format!("--<spelling>={<var>}")`: the placeholder name
906- // is the part between the braces, and its VALUE is whatever the
907- // binding of `<var>` in this same body reaches.
908- let template = format!("format!(\"--{spelling}=");
909- for (i, _) in gate.match_indices(&template) {
910- let rest = &gate[i + template.len()..];
911- let Some(end) = rest.find('"') else { continue };
912- let Some(var) = rest[..end]
913- .strip_prefix('{')
914- .and_then(|v| v.strip_suffix('}'))
915- else {
916- continue;
917- };
918- if var.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
919- out.extend(bound_values(gate, var).unwrap_or_default());
920- }
921- }
922- out
923- }
924-
925- /// Whether a gate body spells one [`DEFAULT_ON_TOOLS`] entry on / off,
926- /// over [`spelling_values`] -- so a `format!`-built flag is classified
927- /// instead of being filed as "defaulted".
928- fn resolved_on_state(gate: &str, spellings: &[&str], on: On) -> Option<bool> {
929- let mut state = None;
930- for spelling in spellings {
931- for c in spelling_values(gate, spelling) {
932- let value = c.to_digit(10).unwrap_or(0);
933- let is_on = match on {
934- On::NonZero => value != 0,
935- On::AtMost(limit) => value <= limit,
936- };
937- state = Some(state.unwrap_or(false) || is_on);
938- }
939- }
940- state
941- }
942-
943- /// `--enable-*` settings per real-aomenc gate, derived from the gate
944- /// source: `flag -> (turned off in N gates, turned on in N, defaulted in N)`.
945- fn tool_settings() -> (usize, BTreeMap<String, (usize, usize, usize)>) {
946- let gates = gate_bodies();
947-
948- let mut per_tool: BTreeMap<String, (usize, usize, usize)> = BTreeMap::new();
949- let mut names: BTreeSet<String> = BTreeSet::new();
950- let mut seen: Vec<BTreeMap<String, char>> = Vec::new();
951- for gate in &gates {
952- let here = flags_in(gate);
953- names.extend(here.keys().cloned());
954- seen.push(here);
955- }
956- for name in names {
957- let off = seen.iter().filter(|g| g.get(&name) == Some(&'0')).count();
958- let on = seen.iter().filter(|g| g.get(&name) == Some(&'1')).count();
959- per_tool.insert(name, (off, on, gates.len() - off - on));
960- }
961- (gates.len(), per_tool)
962- }
963-
964- #[test]
965- fn every_gate_disabling_a_tool_is_a_listed_coverage_hole() {
966- let (gate_count, per_tool) = tool_settings();
967- // A hole OPENS when every gate names the flag and every one of them
968- // says 0 -- then no real stream can exercise the tool.
969- let derived: BTreeSet<&str> = per_tool
970- .iter()
971- .filter(|&(_, &(off, on, defaulted))| off == gate_count && on == 0 && defaulted == 0)
972- .map(|(name, _)| name.as_str())
973- .collect();
974- // A hole CLOSES only on positive evidence: some gate passes `=1`.
975- // A gate that merely leaves the flag off its command line proves
976- // nothing -- aomenc's default for palette and intrabc is content-
977- // dependent -- so "defaulted" must not retire an entry, or a listing
978- // would disappear the moment an unrelated gate is added.
979- let exercised: BTreeSet<&str> = per_tool
980- .iter()
981- .filter(|&(_, &(_, on, _))| on > 0)
982- .map(|(name, _)| name.as_str())
983- .collect();
984- let listed: BTreeSet<&str> = NEVER_EXERCISED.iter().map(|&(flag, _)| flag).collect();
985-
986- let unlisted: Vec<&&str> = derived.difference(&listed).collect();
987- assert!(
988- unlisted.is_empty(),
989- "these aomenc tools are switched off in all {gate_count} real-aomenc gates and on in \
990- none, so no real stream exercises them, and they are not listed in NEVER_EXERCISED: \
991- {unlisted:?} -- either enable the tool with `=1` in its own gate or add it to the \
992- list with a reason"
993- );
994- let stale: Vec<&&str> = listed.intersection(&exercised).collect();
995- assert!(
996- stale.is_empty(),
997- "NEVER_EXERCISED lists {stale:?}, but a gate now passes `=1` for them -- delete \
998- those entries, the coverage hole is closed"
999- );
1000- }
1001-
1002- /// The derivation is only meaningful if a flag left off a gate's command
1003- /// line really does mean "aomenc's default", i.e. the parser above is
1004- /// reading whole flags and not fragments.
1005- #[test]
1006- fn tool_settings_reads_whole_flags() {
1007- let (gate_count, per_tool) = tool_settings();
1008- assert!(
1009- per_tool.contains_key("enable-cdef"),
1010- "expected --enable-cdef among the gate flags"
1011- );
1012- for (name, &(off, on, defaulted)) in &per_tool {
1013- assert!(
1014- !name.is_empty() && !name.contains(['"', '=']),
1015- "malformed flag {name:?}"
1016- );
1017- assert_eq!(
1018- off + on + defaulted,
1019- gate_count,
1020- "{name} counts do not cover every gate"
1021- );
1022- }
1023- }
1024-
1025- /// A gate encodes at 10 bits when its recipe says so: the shared 10-bit
1026- /// helper, an explicit `--bit-depth=10`/`--input-bit-depth=10`, or a
1027- /// `yuv420p10le` fixture handed to aomenc. Everything else is aomenc's
1028- /// 8-bit default.
1029- /// lane-defon r1: a gate helper parameterised on `bit_depth` builds BOTH
1030- /// an 8-bit and a 10-bit stream from one recipe, so its flags cover both
1031- /// depths -- classifying it by the 10-bit strings inside its conditional
1032- /// alone hid `--enable-tx-size-search=1` from the 8-bit list.
1033- /// lane-reelckf r1: the same blind spot with the other spelling -- a gate
1034- /// that loops `for depth in [8usize, 10]` builds BOTH streams from one
1035- /// recipe, but its `yuv420p10le` arm made `is_ten_bit` classify it as
1036- /// 10-bit only, hiding `--enable-cfl-intra=1` from the 8-bit list.
1037- /// lane-av1-intrabc r1: the shared recipe helper
1038- /// `screen_intrabc_stream_at_depth` is parameterised on `depth` and sits in
1039- /// the segment that opens at the PRECEDING gate's `#[test]`, so without
1040- /// this marker that gate's own 8-bit-only flags read as 10-bit-only -- the
1041- /// lane-defon/reelckf blind spot with `depth` spelled instead of
1042- /// `bit_depth`. Three gates share the helper, at both depths.
1043- /// lane-av1distwtd r3: the THIRD spelling of the same blind spot, still
1044- /// live after lane-defon and lane-reelckf. A recipe parameterised on
1045- /// `ten_bit` names BOTH fixture formats in one body -- `let pix_fmt = if
1046- /// ten_bit { "yuv420p10le" } else { "yuv420p" };` -- so `is_ten_bit` saw
1047- /// the 10-bit arm and filed the whole body 10-bit-ONLY, hiding its 8-bit
1048- /// arm from the 8-bit bucket. The marker is the PAIR OF FORMATS, not the
1049- /// parameter name: a body spelling both pixel formats builds streams at
1050- /// both depths, whatever it calls the flag. The quotes matter -- a bare
1051- /// `yuv420p` substring test also matches `yuv420p10le` and would fire on
1052- /// every 10-bit gate, retiring entries on no evidence.
1053- ///
1054- /// This is what mis-filed `a_real_aomenc_stream_with_a_1d_tx_class_on_a_rect_transform_decodes_pixel_exact`
1055- /// and kept `enable-flip-idtx` on the 8-bit list while that gate ran 6
1056- /// pixel-exact 8-bit decodes through it.
1057- fn covers_both_depths(body: &str) -> bool {
1058- body.contains("if bit_depth == 10")
1059- || body.contains("if depth == 10")
1060- || body.contains("for depth in [8usize, 10]")
1061- || (body.contains("\"yuv420p\"") && body.contains("\"yuv420p10le\""))
1062- }
1063-
1064- /// lane-av1distwtd r3: the detector fix, pinned. A detector change with
1065- /// no test can only be shown to find MORE, never to stop missing, so this
1066- /// asserts the three gates the two blind spots actually hid are now seen
1067- /// -- the two `enable-dual-filter` witnesses and the `enable-flip-idtx`
1068- /// both-depths gate -- and that the fix is strictly ADDITIVE against the
1069- /// old spelling-only filter.
1070- #[test]
1071- fn the_detector_sees_the_gates_the_spelling_filter_missed() {
1072- let src = crate::test_source::module_source("stream");
1073- let gates = gate_bodies();
1074- // The helper-delegation half: each of these builds its stream through
1075- // `inter_sb_none_gate` and spells none of `legacy_gate_tokens`, so the
1076- // old filter dropped both while each hard-asserts its tool arrived.
1077- for name in [
1078- "a_real_aomenc_dual_filter_obmc_8x8_inter_sequence_decodes_pixel_exact",
1079- "a_real_obmc_stream_reads_a_recorded_switchable_filter_for_every_neighbour",
1080- ] {
1081- let body = gates
1082- .iter()
1083- .find(|b| b.contains(name))
1084- .unwrap_or_else(|| panic!("{name}: not seen by gate_bodies()"));
1085- assert_eq!(
1086- flags_in(body).get("enable-dual-filter"),
1087- Some(&'1'),
1088- "{name}: seen, but its --enable-dual-filter=1 spelling is not visible to \
1089- flags_in, so recognising the gate would not retire the entry"
1090- );
1091- }
1092- // The both-depths half: this gate's recipe is parameterised on `ten_bit`
1093- // and names both fixture formats, so `covers_both_depths` must credit
1094- // it to the 8-bit bucket, not just the 10-bit one.
1095- let flip = gates
1096- .iter()
1097- .find(|b| b.contains("a_real_aomenc_stream_with_a_1d_tx_class_on_a_rect_transform"))
1098- .expect("the flip-idtx gate must be seen");
1099- assert!(
1100- covers_both_depths(flip),
1101- "the flip-idtx gate spells both fixture formats, so covers_both_depths must \
1102- credit it to the 8-bit bucket as well"
1103- );
1104- assert!(
1105- covers_depth(flip, false) && covers_depth(flip, true),
1106- "the flip-idtx gate must cover BOTH depths"
1107- );
1108- // Strictly additive: every segment the old spelling-only filter kept
1109- // is still kept, so the fix cannot have cost the census a gate.
1110- let legacy_only: Vec<&str> = src
1111- .split("\n #[")
1112- .filter(|b| !b.starts_with("ignore") && legacy_gate_tokens(b))
1113- .collect();
1114- assert!(
1115- legacy_only.len() < gates.len(),
1116- "the call-resolving filter found {} gates, the old spelling-only filter found \
1117- {} -- the fix is expected to ADD gates, never to drop one",
1118- gates.len(),
1119- legacy_only.len()
1120- );
1121- for body in &legacy_only {
1122- assert!(
1123- gates.contains(body),
1124- "a gate the spelling-only filter recognised is no longer recognised: \
1125- {:?}",
1126- &body[..body.len().min(60)]
1127- );
1128- }
1129- }
1130-
1131- /// Whether a gate body drives a stream at this depth.
1132- fn covers_depth(body: &str, ten_bit: bool) -> bool {
1133- covers_both_depths(body) || is_ten_bit(body) == ten_bit
1134- }
1135-
1136- fn is_ten_bit(body: &str) -> bool {
1137- // The lists pin two buckets, 8-bit and high-bit-depth; 12-bit gates
1138- // count in the high-depth bucket (lane-av1gwarp12's ROTZOOM gate was
1139- // the first 12-bit gate to positively enable a listed tool, and the
1140- // 10-bit-only spellings mis-filed it as 8-bit).
1141- body.contains("encode_10bit_gradients")
1142- || body.contains("ten_bit_tool_gate(")
1143- || body.contains("--bit-depth=10")
1144- || body.contains("--input-bit-depth=10")
1145- || body.contains("yuv420p10le")
1146- || body.contains("encode_12bit(")
1147- || body.contains("--bit-depth=12")
1148- || body.contains("--input-bit-depth=12")
1149- || body.contains("yuv420p12le")
1150- }
1151-
1152- /// Flags a gate positively enables (`=1`), at gates of the given depth.
1153- fn enabled_at(ten_bit: bool) -> BTreeSet<String> {
1154- let mut on = BTreeSet::new();
1155- for gate in gate_bodies() {
1156- if !covers_depth(gate, ten_bit) {
1157- continue;
1158- }
1159- for (flag, value) in flags_in(gate) {
1160- if value == '1' {
1161- on.insert(flag);
1162- }
1163- }
1164- // A tool driven by its own spelling counts as exercised.
1165- let here = settings_in(gate);
1166- for (alias, tool) in ALIASES {
1167- if here.get(*alias).is_some_and(|v| v != "0") {
1168- on.insert((*tool).to_owned());
1169- }
1170- }
1171- }
1172- on
1173- }
1174-
1175- /// The tools of [`TOOL_UNIVERSE`] that no gate of this depth enables.
1176- fn never_exercised_at(ten_bit: bool) -> BTreeSet<&'static str> {
1177- let on = enabled_at(ten_bit);
1178- TOOL_UNIVERSE
1179- .iter()
1180- .copied()
1181- .filter(|t| !on.contains(*t))
1182- .collect()
1183- }
1184-
1185- fn check_depth(ten_bit: bool, listed: &[(&str, &str)]) {
1186- let derived = never_exercised_at(ten_bit);
1187- let listed: BTreeSet<&str> = listed.iter().map(|&(flag, _)| flag).collect();
1188- let depth = if ten_bit { "10-bit" } else { "8-bit" };
1189- let unlisted: Vec<&&str> = derived.difference(&listed).collect();
1190- assert!(
1191- unlisted.is_empty(),
1192- "no {depth} gate passes `=1` for {unlisted:?}, so no real {depth} stream exercises \
1193- them -- enable the tool in a {depth} gate that asserts it fired, or list it"
1194- );
1195- let stale: Vec<&&str> = listed.difference(&derived).collect();
1196- assert!(
1197- stale.is_empty(),
1198- "the {depth} list still names {stale:?}, but a {depth} gate now passes `=1` for them \
1199- -- delete those entries, the coverage hole is closed"
1200- );
1201- }
1202-
1203- #[test]
1204- fn never_exercised_8bit_matches_the_gate_recipes() {
1205- check_depth(false, NEVER_EXERCISED_8BIT);
1206- }
1207-
1208- #[test]
1209- fn never_exercised_10bit_matches_the_gate_recipes() {
1210- check_depth(true, NEVER_EXERCISED_10BIT);
1211- }
1212-
1213- /// `cargo test -p ec-av1 --lib gate_coverage -- --nocapture` prints both
1214- /// lists, so the per-depth holes can be read without opening this file.
1215- #[test]
1216- fn print_never_exercised_per_bit_depth() {
1217- let ten: Vec<&str> = gate_bodies()
1218- .into_iter()
1219- .filter(|b| is_ten_bit(b))
1220- .collect();
1221- let total = gate_bodies().len();
1222- println!(
1223- "gate_coverage: {} real-aomenc gates, {} of them 10-bit",
1224- total,
1225- ten.len()
1226- );
1227- for (label, ten_bit) in [("8BIT", false), ("10BIT", true)] {
1228- let holes = never_exercised_at(ten_bit);
1229- println!(
1230- "NEVER_EXERCISED_{label} ({} of {}):",
1231- holes.len(),
1232- TOOL_UNIVERSE.len()
1233- );
1234- for flag in &holes {
1235- println!(" --{flag}");
1236- }
1237- }
1238- }
1239-
1240- /// [`DEFAULT_ON_TOOLS`] per depth: `tool -> (off in N gates, on in N, defaulted in N)`.
1241- fn default_on_settings(
1242- ten_bit: bool,
1243- ) -> (usize, BTreeMap<&'static str, (usize, usize, usize)>) {
1244- let gates: Vec<&str> = gate_bodies()
1245- .into_iter()
1246- .filter(|b| covers_depth(b, ten_bit))
1247- .collect();
1248- let mut per_tool = BTreeMap::new();
1249- for &(tool, spellings, _, on) in DEFAULT_ON_TOOLS {
1250- // lane-av1txsearch: `resolved_on_state`, not `default_on_state` --
1251- // the literal-only reader filed every `format!`-built flag as
1252- // "defaulted", which is unknown rather than measured.
1253- let states: Vec<Option<bool>> = gates
1254- .iter()
1255- .map(|g| resolved_on_state(g, spellings, on))
1256- .collect();
1257- let turned_on = states.iter().filter(|s| **s == Some(true)).count();
1258- let turned_off = states.iter().filter(|s| **s == Some(false)).count();
1259- per_tool.insert(
1260- tool,
1261- (turned_off, turned_on, gates.len() - turned_off - turned_on),
1262- );
1263- }
1264- (gates.len(), per_tool)
1265- }
1266-
1267- /// The [`DEFAULT_ON_TOOLS`] no gate of this depth positively enables.
1268- fn never_on_at(ten_bit: bool) -> BTreeSet<&'static str> {
1269- default_on_settings(ten_bit)
1270- .1
1271- .into_iter()
1272- .filter(|&(_, (_, on, _))| on == 0)
1273- .map(|(tool, _)| tool)
1274- .collect()
1275- }
1276-
1277- fn check_default_on(ten_bit: bool, listed: &[(&str, &str)]) {
1278- let derived = never_on_at(ten_bit);
1279- let listed: BTreeSet<&str> = listed.iter().map(|&(tool, _)| tool).collect();
1280- let depth = if ten_bit { "10-bit" } else { "8-bit" };
1281- let unlisted: Vec<&&str> = derived.difference(&listed).collect();
1282- assert!(
1283- unlisted.is_empty(),
1284- "no {depth} gate spells an on-value for {unlisted:?}, so no real {depth} stream is \
1285- proven to carry them -- switch the tool on in a {depth} gate that asserts it fired, \
1286- or list it with a reason"
1287- );
1288- let stale: Vec<&&str> = listed.difference(&derived).collect();
1289- assert!(
1290- stale.is_empty(),
1291- "the {depth} default-on list still names {stale:?}, but a {depth} gate now switches \
1292- them on -- delete those entries, the coverage hole is closed"
1293- );
1294- }
1295-
1296- #[test]
1297- fn never_on_8bit_matches_the_gate_recipes() {
1298- check_default_on(false, NEVER_ON_8BIT);
1299- }
1300-
1301- #[test]
1302- fn never_on_10bit_matches_the_gate_recipes() {
1303- check_default_on(true, NEVER_ON_10BIT);
1304- }
1305-
1306- /// A tool must not be pinned twice: [`TOOL_UNIVERSE`] already derives the
1307- /// `--enable-*` spellings under the `=1` rule.
1308- #[test]
1309- fn default_on_tools_do_not_duplicate_the_universe() {
1310- for &(tool, spellings, _, _) in DEFAULT_ON_TOOLS {
1311- assert!(
1312- !TOOL_UNIVERSE.contains(&tool),
1313- "{tool} is already covered by TOOL_UNIVERSE"
1314- );
1315- assert!(!spellings.is_empty(), "{tool} has no aomenc spelling");
1316- }
1317- for (alias, tool) in ALIASES {
1318- assert!(
1319- TOOL_UNIVERSE.contains(tool),
1320- "alias --{alias} names {tool}, which is not a TOOL_UNIVERSE tool"
1321- );
1322- }
1323- }
1324-
1325- /// `cargo test -p ec-av1 --lib gate_coverage -- --nocapture` prints the
1326- /// default-on holes with their off/defaulted split.
1327- #[test]
1328- fn print_never_on_per_bit_depth() {
1329- for (label, ten_bit) in [("8BIT", false), ("10BIT", true)] {
1330- let (gate_count, per_tool) = default_on_settings(ten_bit);
1331- let holes = never_on_at(ten_bit);
1332- println!(
1333- "NEVER_ON_{label} ({} of {}, over {gate_count} {label} gates):",
1334- holes.len(),
1335- DEFAULT_ON_TOOLS.len()
1336- );
1337- for tool in &holes {
1338- let (off, _, defaulted) = per_tool[tool];
1339- let spellings = DEFAULT_ON_TOOLS
1340- .iter()
1341- .find(|e| e.0 == *tool)
1342- .map(|e| e.1.join(","))
1343- .unwrap_or_default();
1344- println!(
1345- " {tool} (--{spellings}): off in {off}, defaulted in {defaulted}, on in 0"
1346- );
1347- }
1348- }
1349- }
1350-
1351- /// lane-av1txsearch: the `enable-tx-size-search` census, MEASURED rather
1352- /// than floored. Prints, per gate body, the values the resolver reads for
1353- /// the flag -- literal spellings and `format!` templates alike -- and the
1354- /// three-way split at the end. Re-run it after any gate recipe change:
1355- ///
1356- /// `cargo test -p ec-av1 --lib gate_coverage::tests::print_tx_size_search_census -- --nocapture`
1357- #[test]
1358- fn print_tx_size_search_census() {
1359- const TOOL: &str = "enable-tx-size-search";
1360- let (zero, one, both, unresolvable, unnamed) = {
1361- let (mut zero, mut one, mut both, mut unresolvable, mut unnamed) =
1362- (0usize, 0usize, 0usize, 0usize, 0usize);
1363- for gate in gate_bodies() {
1364- let values = spelling_values(gate, TOOL);
1365- let name = gate
1366- .split("fn ")
1367- .nth(1)
1368- .and_then(|s| s.split('(').next())
1369- .unwrap_or("<segment>")
1370- .to_owned();
1371- let state = match (values.contains(&'0'), values.contains(&'1')) {
1372- (false, false) => {
1373- unnamed += 1;
1374- "not named (defaulted)"
1375- }
1376- (true, false) => {
1377- zero += 1;
1378- "=0"
1379- }
1380- (false, true) => {
1381- one += 1;
1382- "=1"
1383- }
1384- (true, true) => {
1385- both += 1;
1386- "=0 and =1 (one arm each)"
1387- }
1388- };
1389- let via = if gate.contains(&format!("format!(\"--{TOOL}=")) {
1390- " [format! template resolved]"
1391- } else {
1392- ""
1393- };
1394- // A segment that does not open at a `#[test]` is glued non-test helper
1395- // text from a split module (the support helpers have no attribute between
1396- // them), so its `format!` parameter is not a gate's own value.
1397- let helper = if gate.starts_with("test]")
1398- && gate.contains(&format!("format!(\"--{TOOL}="))
1399- && values.is_empty()
1400- {
1401- " [UNRESOLVED: variable is a shared helper's parameter]"
1402- } else {
1403- ""
1404- };
1405- if !helper.is_empty() {
1406- unresolvable += 1;
1407- unnamed -= 1;
1408- }
1409- println!("{name}: {state}{via}{helper}");
1410- }
1411- (zero, one, both, unresolvable, unnamed)
1412- };
1413- let total = gate_bodies().len();
1414- println!(
1415- "enable-tx-size-search over {total} census-selected gate bodies: \
1416- =0 only {zero}, =1 only {one}, both {both}, unresolvable {unresolvable}, \
1417- not named {unnamed}"
1418- );
1419- assert_eq!(
1420- unresolvable, 0,
1421- "{unresolvable} gate bodies build --{TOOL} into a variable this census cannot bind -- \
1422- the count is a floor again, and an unknown direction is the failure mode this file \
1423- exists to prevent"
1424- );
1425- }
1426-
1427- /// lane-av1txsearch: the RED-BEFORE proof for the template resolver, in
1428- /// both directions, on the gate bodies that actually exist.
1429- ///
1430- /// Direction 1 -- a `format!`-built value MOVES the classification. Each
1431- /// case below takes a real gate body, mutates only the bound value, and
1432- /// asserts the resolved state changed. A resolver that found nothing
1433- /// would read every one of these as "not named" and fail all four.
1434- ///
1435- /// Direction 2 -- a spelling the LITERAL reader already saw still
1436- /// classifies. Without this half, a resolver that overwrote the literal
1437- /// path would pass direction 1 while losing the 15 `=1` gates the census
1438- /// already counted.
1439- #[test]
1440- fn the_resolver_binds_a_format_built_flag_in_both_directions() {
1441- let gates = gate_bodies();
1442- let find = |needle: &str| -> &'static str {
1443- gates
1444- .iter()
1445- .copied()
1446- .find(|b| b.contains(needle))
1447- .unwrap_or_else(|| panic!("no gate body contains {needle:?}"))
1448- };
1449- // Direction 1, one per template shape.
1450- let cases = [
1451- (
1452- "format!(\"--enable-tx-size-search={txs}\")",
1453- "for txs in [0usize, 1]",
1454- "for txs in [0usize, 0]",
1455- "a_real_aomenc_palette_stream_with_8x8_leaves_decodes_pixel_exact",
1456- ),
1457- (
1458- "format!(\"--enable-tx-size-search={tx_search}\")",
1459- "if attempt % 2 == 0 { \"0\" } else { \"1\" }",
1460- "if attempt % 2 == 0 { \"0\" } else { \"0\" }",
1461- "a_real_aomenc_inter_sequence_with_a_coded_rectangular_residual_decodes_pixel_exact",
1462- ),
1463- (
1464- "format!(\"--enable-tx-size-search={tx_search}\")",
1465- "for (tx_search, bit_depth) in [(\"1\", 8u8), (\"0\", 8u8), (\"1\", 10u8)]",
1466- "for (tx_search, bit_depth) in [(\"0\", 8u8), (\"0\", 8u8), (\"0\", 10u8)]",
1467- "a_real_aomenc_stream_with_filter_intra_on_a_sub8_rect_leaf_decodes_pixel_exact",
1468- ),
1469- // The arm table hoisted OUT of the `for` line into a named
1470- // `let` -- the shape lane-av1lossy128x96 writes, and the one
1471- // that reads as UNRESOLVED unless the `for` line's collection
1472- // name is followed back to its binding. Without this case a
1473- // resolver that only understood inline arrays passes the
1474- // three above and still cannot bind this gate.
1475- (
1476- "format!(\"--enable-tx-size-search={search}\")",
1477- "\"tx size search on\",\n \"1\",",
1478- "\"tx size search on\",\n \"0\",",
1479- "a_real_aomenc_444_whole_64_root_tx_size_search_stream_decodes_pixel_exact_at_128x96",
1480- ),
1481- ];
1482- for (template, from, to, name) in cases {
1483- let body = find(name);
1484- assert!(
1485- body.contains(template),
1486- "{name} does not spell {template}, so this case proves nothing"
1487- );
1488- assert!(
1489- body.contains(from),
1490- "{name} does not contain the source binding {from:?}"
1491- );
1492- let before = spelling_values(body, "enable-tx-size-search");
1493- let mutated = body.replace(from, to);
1494- assert_ne!(
1495- mutated, body,
1496- "the mutation {from:?} -> {to:?} changed nothing"
1497- );
1498- let after = spelling_values(&mutated, "enable-tx-size-search");
1499- assert_eq!(
1500- before,
1501- BTreeSet::from(['0', '1']),
1502- "{name}: the unmutated body should resolve to both values, got {before:?}"
1503- );
1504- assert_eq!(
1505- after,
1506- BTreeSet::from(['0']),
1507- "{name}: mutating the bound value {from:?} -> {to:?} did not move the \
1508- classification (still {after:?}) -- the resolver is not reading the binding"
1509- );
1510- }
1511- // Direction 2: every gate the LITERAL reader already classified as
1512- // `=1` still is. Asserted as CONTAINMENT, not equality: a segment may
1513- // spell the flag twice (`=0` in the base recipe, `=1` as the per-arm
1514- // override), and the old reader took the last one while the resolver
1515- // takes the set. The claim being pinned is "still on", which is the
1516- // direction a regression would lose.
1517- let mut pinned = 0usize;
1518- for gate in &gates {
1519- if !gate.contains("\"--enable-tx-size-search=1\"") {
1520- continue;
1521- }
1522- pinned += 1;
1523- assert!(
1524- spelling_values(gate, "enable-tx-size-search").contains(&'1'),
1525- "a gate that literally spells --enable-tx-size-search=1 is no longer \
1526- classified on: {:?}",
1527- &gate[..gate.len().min(80)]
1528- );
1529- }
1530- assert!(
1531- pinned >= 10,
1532- "expected the literal `=1` gates to still be there, found {pinned}"
1533- );
1534- }
1535-
1536- /// lane-av1oracleskip: the ORACLE-PRESENCE SCAN — the mechanical
1537- /// anti-regression for the skip class this lane closed.
1538- ///
1539- /// Why a scan and not a review rule: the r2 sweep found FIVE gates that
1540- /// had been added with the bare `if aomdec_path().is_file() { …compare… }`
1541- /// shape AFTER the first fix had already routed thirteen sites — every one
1542- /// of them compiled, passed review and reported green with the oracle
1543- /// compare silently skipped, under `EC_AV1_REQUIRE_AOMENC=1`. A guard
1544- /// written the old way re-opens the class the moment it merges, so the
1545- /// only thing that holds is a check that reads the source itself.
1546- ///
1547- /// The rule: a TOOL PRESENCE CHECK (`aomenc_path().is_file()`,
1548- /// `aomdec_path().is_file()`, `affine_aomenc_path().is_file()`, plain or
1549- /// `!…` inverted) may appear ONLY
1550- /// 1. inside the body of the probe that owns that path
1551- /// (`have_aomenc`, `aomdec_available`, `have_affine_aomenc`) — that
1552- /// is where the assert-last and the env escape live, and
1553- /// 2. inside an `assert!` (the deliberate hard-failure form), or
1554- /// 3. in a comment, which cannot execute.
1555- /// Anything else is a skip with no env escape, and the test fails naming
1556- /// the exact `file:line`.
1557- ///
1558- /// THE FLOOR. A source scan that matches nothing is the false-pass shape
1559- /// this crate has been bitten by twice (a `format!` brace escape, and
1560- /// `args.find(')')` stopping at the wrong paren), so the scan refuses to
1561- /// pass unless it actually inspected a plausible number of sites: the
1562- /// count is printed and asserted against `MIN_SITES`. A probe that moved
1563- /// out of the scan's reach, or a matcher broken by a rename, reds here
1564- /// instead of reporting a clean bill of health.
1565- #[test]
1566- fn no_tool_presence_check_outside_its_probe() {
1567- /// Below this, the scan is not looking at the tree it thinks it is.
1568- /// Five is the STRUCTURAL floor: three probes (whose existence the span
1569- /// assert below already pins) plus the two hard `assert!` sites. Doc
1570- /// comments mentioning the old shape come and go with the prose, so
1571- /// they are counted but never load-bearing here.
1572- const MIN_SITES: usize = 5;
1573- /// (file, the line that opens the probe owning that path)
1574- const PROBES: &[(&str, &str)] = &[
1575- ("stream.rs", "fn have_aomenc()"),
1576- ("stream.rs", "fn aomdec_available("),
1577- ("stream.rs", "fn have_affine_aomenc()"),
1578- ];
1579- const PATHS: &[&str] = &[
1580- "aomenc_path().is_file()",
1581- "aomdec_path().is_file()",
1582- "affine_aomenc_path().is_file()",
1583- ];
1584- let files: [(&str, &str); 3] = [
1585- ("stream.rs", crate::test_source::module_source("stream")),
1586- ("decode.rs", crate::test_source::module_source("decode")),
1587- ("encode.rs", crate::test_source::module_source("encode")),
1588- ];
1589-
1590- // The line range each probe body owns: from its opener to the first
1591- // following line that closes it at column 0.
1592- let mut probe_spans: Vec<(usize, usize)> = Vec::new();
1593- for (name, src) in files {
1594- let lines: Vec<&str> = src.lines().collect();
1595- for (probe_file, opener) in PROBES {
1596- if *probe_file != name {
1597- continue;
1598- }
1599- let Some(start) = lines.iter().position(|l| l.contains(opener)).map(|i| i + 1)
1600- else {
1601- continue;
1602- };
1603- let end = lines
1604- .iter()
1605- .skip(start)
1606- .position(|l| l.trim_end() == "}")
1607- .map(|off| start + off)
1608- .unwrap_or(lines.len());
1609- probe_spans.push((start, end));
1610- }
1611- }
1612- assert!(
1613- probe_spans.len() == PROBES.len(),
1614- "the oracle-presence scan recognised {} of the {} probe bodies it is meant to \
1615- exempt ({probe_spans:?}); a renamed or moved probe would silently exempt every \
1616- site in the crate, so it reds here",
1617- probe_spans.len(),
1618- PROBES.len()
1619- );
1620-
1621- let mut sites = 0usize;
1622- let mut allowed = 0usize;
1623- let mut per_pattern: BTreeMap<&str, usize> = PATHS.iter().map(|p| (*p, 0)).collect();
1624- let mut offenders: Vec<String> = Vec::new();
1625- for (name, src) in files {
1626- for (i, line) in src.lines().enumerate() {
1627- // LONGEST match wins: `affine_aomenc_path().is_file()` CONTAINS
1628- // `aomenc_path().is_file()`, so a first-match scan credits the
1629- // affine probe's line to the aomenc pattern and the per-pattern
1630- // floor below reds on a pattern that is very much present. (It
1631- // did, on the first run of this test — which is the floor
1632- // earning its place.)
1633- let Some(path) = PATHS
1634- .iter()
1635- .filter(|p| line.contains(**p))
1636- .max_by_key(|p| p.len())
1637- else {
1638- continue;
1639- };
1640- sites += 1;
1641- *per_pattern.get_mut(path).expect("pattern came from PATHS") += 1;
1642- let lineno = i + 1;
1643- let trimmed = line.trim_start();
1644- let in_probe = probe_spans
1645- .iter()
1646- .any(|(start, end)| lineno >= *start && lineno <= *end);
1647- let in_assert = trimmed.starts_with("assert!")
1648- || trimmed.starts_with("aomdec_path().is_file(),")
1649- || trimmed.starts_with("aomenc_path().is_file(),")
1650- || trimmed.starts_with("affine_aomenc_path().is_file(),");
1651- let in_comment = trimmed.starts_with("//");
1652- if in_probe || in_assert || in_comment {
1653- allowed += 1;
1654- } else {
1655- offenders.push(format!(
1656- "{name}:{lineno}: {}\n a tool presence check outside its probe — \
1657- route it through the probe that owns this path (`have_aomenc`, \
1658- `aomdec_available`, `have_affine_aomenc`): a bare `{path}` skips the \
1659- gate with NO env escape, so under EC_AV1_REQUIRE_AOMENC=1 the gate still \
1660- reports green with the oracle compare never run.",
1661- line.trim()
1662- ));
1663- }
1664- }
1665- }
1666- println!(
1667- "oracle-presence scan: {sites} site(s) inspected, {allowed} in a probe / assert / \
1668- comment, {} offender(s); per pattern {per_pattern:?}",
1669- offenders.len()
1670- );
1671- // PER-PATTERN floor: a total count can hide one broken matcher (mutate
1672- // ONE pattern and the other two still add up), so each of the three
1673- // path patterns must be found at least once -- which the probe bodies
1674- // guarantee, since each probe contains its own path's presence check.
1675- let never_matched: Vec<&str> = per_pattern
1676- .iter()
1677- .filter(|(_, n)| **n == 0)
1678- .map(|(p, _)| *p)
1679- .collect();
1680- assert!(
1681- never_matched.is_empty(),
1682- "the oracle-presence scan matched NOTHING for {never_matched:?}: that pattern is \
1683- stale (renamed helper, `exists()` instead of `is_file()`, a `format!` escape) and \
1684- the gates it was meant to police would pass unreviewed. Matched per pattern: \
1685- {per_pattern:?}"
1686- );
1687- assert!(
1688- sites >= MIN_SITES,
1689- "the oracle-presence scan inspected only {sites} site(s), below its floor of \
1690- {MIN_SITES}: the matcher has stopped matching this tree (renamed path helper, a \
1691- `format!` escape, a moved probe), and with no floor this would pass while scanning \
1692- nothing — the false-pass shape this crate has been bitten by twice"
1693- );
1694- assert!(
1695- offenders.is_empty(),
1696- "{} bare tool presence check(s) outside a probe — each one is a gate that can report \
1697- green without running the oracle compare:\n {}",
1698- offenders.len(),
1699- offenders.join("\n ")
1700- );
1701- }
1702-}
1703-
1704-/// lane-av1pins5 r5: the PIN INVENTORY.
1705-///
1706-/// The r3 inventory this replaces matched only two call shapes --
1707-/// `crate_pin("X")` and `pin_dir().join("X")` -- both SINGLE-NAME. A gate that
1708-/// reads a whole DIRECTORY of pins through a `concat!` literal and then formats
1709-/// a name at runtime (`format!("{fixtures}/{n}.obu")`) matched neither, so
1710-/// `pinned_warp_stream_decodes_pixel_exact` and its 14 uncommitted pins were
1711-/// invisible to it, and r3 reported "the machine-local-pin population is zero".
1712-/// It was not. This enumerator resolves all four shapes.
1713-///
1714-/// Ownership, stated because two lanes touch this: THIS scanner owns the
1715-/// ENUMERATION (which gates read which pins, from source). The fixture-preflight
1716-/// lane owns the FILE INVENTORY on a runner (does each referenced path exist on
1717-/// the box). Different questions; both must agree, and this one is the stricter of
1718-/// the two because it fails on an uncommitted pin whether or not some runner
1719-/// happens to have a copy.
1720-#[cfg(test)]
1721-mod pin_inventory {
1722- /// One pin a gate reads, and where it came from.
1723- pub struct PinRead {
1724- pub gate: String,
1725- pub file: String,
1726- pub shape: &'static str,
1727- }
1728-
1729- /// Split `src` into `(fn_name, body)` for every `fn name(` at the gate indent.
1730- fn gate_bodies(src: &str) -> Vec<(String, &'static str)> {
1731- let mut out = Vec::new();
1732- let mut cur: Option<(String, usize)> = None;
1733- for (i, line) in src.lines().enumerate() {
1734- let t = line.trim_start();
1735- if let Some(rest) = t.strip_prefix("fn ")
1736- && let Some(name) = rest.split('(').next()
1737- && !name.contains(' ') {
1738- cur = Some((name.to_string(), i));
1739- }
1740- // A `#[test]`/`#[ignore]` line is never a closing brace, so the fn
1741- // ends at the first line that is exactly four-space `}`.
1742- if let Some((name, start)) = &cur
1743- && i > *start && line == " }" {
1744- let body = src
1745- .lines()
1746- .skip(*start)
1747- .take(i - *start + 1)
1748- .collect::<Vec<_>>()
1749- .join("\n");
1750- out.push((name.clone(), &*Box::leak(body.into_boxed_str())));
1751- cur = None;
1752- }
1753- }
1754- out
1755- }
1756-
1757- /// Every pin every gate reads, across all four shapes.
1758- pub fn pins_read(src: &str) -> Vec<PinRead> {
1759- let mut out = Vec::new();
1760- for (gate, body) in gate_bodies(src) {
1761- // (a) crate_pin("X") and (b) pin_dir().join("X") -- single name.
1762- for m in body.match_indices("crate_pin(\"") {
1763- let rest = &body[m.0 + 11..];
1764- if let Some(e) = rest.find('"') {
1765- out.push(PinRead {
1766- gate: gate.clone(),
1767- file: rest[..e].to_string(),
1768- shape: "crate_pin",
1769- });
1770- }
1771- }
1772- for m in body.match_indices("pin_dir().join(\"") {
1773- let rest = &body[m.0 + 16..];
1774- if let Some(e) = rest.find('"') {
1775- out.push(PinRead {
1776- gate: gate.clone(),
1777- file: rest[..e].to_string(),
1778- shape: "pin_dir_machine_local",
1779- });
1780- }
1781- }
1782- // (c) a whole-file concat! literal to a named pin:
1783- // concat!(env!("CARGO_MANIFEST_DIR"), "/../../fixtures/X.obu")
1784- for m in body.match_indices("/../../fixtures/") {
1785- let rest = &body[m.0 + 16..];
1786- if let Some(e) = rest.find('"') {
1787- out.push(PinRead {
1788- gate: gate.clone(),
1789- file: rest[..e].to_string(),
1790- shape: "concat_literal_machine_local",
1791- });
1792- }
1793- }
1794- // (d) the shape that hid 14 pins: a DIRECTORY literal bound to a
1795- // local, plus a runtime `format!("{var}/{n}.ext")` over a
1796- // literal name array. Resolve the array's names.
1797- for (vi, line) in body.lines().enumerate() {
1798- let tl = line.trim();
1799- // `let fixtures = concat!(env!("CARGO_MANIFEST_DIR"), "/../../fixtures");`
1800- // -> the bound name is whatever sits between `let ` and the `=`.
1801- let var = match (
1802- tl.find("concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/../../fixtures\")"),
1803- tl.find('='),
1804- ) {
1805- (Some(a), Some(eq)) if eq < a => tl[4..eq].trim().to_string(),
1806- _ => continue,
1807- };
1808- if var.is_empty() {
1809- continue;
1810- }
1811- // `format!("{fixtures}/{n}.obu")` -- built by concatenation, not
1812- // by `format!`: escaping `{{`/`}}` to emit literal braces here is
1813- // exactly the bug that made this shape resolve to 0 pins on the
1814- // first run of the scanner.
1815- let marker = ["format!(\"", "{", &var, "}/{n}"].concat();
1816- let Some(pos) = body.find(&marker) else {
1817- continue;
1818- };
1819- // Walk back from the format! to the `[ ... ].iter()` array and
1820- // take every quoted name in it.
1821- let head = &body[..pos];
1822- let Some(bracket) = head.rfind('[') else {
1823- continue;
1824- };
1825- let names: Vec<String> = head[bracket..]
1826- .split('"')
1827- .skip(1)
1828- .step_by(2)
1829- .filter(|s| !s.is_empty() && !s.contains(' ') && *s != "]")
1830- .map(|s| s.to_string())
1831- .collect();
1832- // `.obu` -- SLICE up to the closing quote. (Stringifying the
1833- // `find` index instead produced names like `warp-mismatch4`.)
1834- let tail = &body[pos + marker.len()..];
1835- let ext = tail
1836- .find('"')
1837- .map(|e| tail[..e].to_string())
1838- .unwrap_or_default();
1839- for n in names {
1840- out.push(PinRead {
1841- gate: gate.clone(),
1842- file: format!("{n}{ext}"),
1843- shape: "concat_dir_runtime_name",
1844- });
1845- }
1846- let _ = vi;
1847- }
1848- // (e) the shape this very fix INTRODUCED:
1849- // `.map(|n| crate_pin(&format!("{n}.obu")))`. Rewriting the
1850- // directory literal as a committed-path lookup made the gate
1851- // correct and simultaneously invisible -- `crate_pin("` no
1852- // longer appears, so shape (a) found nothing and the
1853- // enumerator reported a CLEAN tree while 14 pins were read. A
1854- // false pass is worse than the original gap: the original at
1855- // least showed up in a filesystem audit. Caught here by the
1856- // `reads.len()` floor in the invariant test.
1857- for m in body.match_indices("crate_pin(&format!(") {
1858- let rest = &body[m.0 + 19..];
1859- let Some(close) = rest.find(')') else {
1860- continue;
1861- };
1862- let call = &rest[..close];
1863- if !call.contains('"') {
1864- continue;
1865- }
1866- let head = &body[..m.0];
1867- let Some(bracket) = head.rfind('[') else {
1868- continue;
1869- };
1870- let names: Vec<String> = head[bracket..]
1871- .split('"')
1872- .skip(1)
1873- .step_by(2)
1874- .filter(|x| !x.is_empty() && !x.contains(' ') && *x != "]")
1875- .map(|x| x.to_string())
1876- .collect();
1877- // the literal inside the format!, e.g. `{n}.obu`
1878- let lit = call.split('"').nth(1).unwrap_or("");
1879- let ext = lit
1880- .split_once("}")
1881- .map(|(_, e)| e.to_string())
1882- .unwrap_or_default();
1883- for n in names {
1884- out.push(PinRead {
1885- gate: gate.clone(),
1886- file: format!("{n}{ext}"),
1887- shape: "crate_pin_runtime_name",
1888- });
1889- }
1890- }
1891- }
1892- out
1893- }
1894-
1895- /// Does this shape resolve through `crate_pin`, i.e. the COMMITTED
1896- /// crate-local copy? Both the literal form and the runtime-name form do --
1897- /// only the two `pin_dir`/root-`concat!` forms are machine-local.
1898- pub fn resolves_committed(shape: &str) -> bool {
1899- matches!(shape, "crate_pin" | "crate_pin_runtime_name")
1900- }
1901-
1902- /// Is `file` present as a committed crate-local fixture?
1903- pub fn is_committed(file: &str) -> bool {
1904- std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1905- .join("fixtures")
1906- .join(file)
1907- .is_file()
1908- }
1909-}
1910-
1911-#[cfg(test)]
1912-mod pin_inventory_tests {
1913- use super::pin_inventory::{is_committed, pins_read};
1914-
1915- /// The scanner must be able to SEE the directory-literal shape. Run over a
1916- /// SYNTHETIC source, not the live tree: r5 removed that shape from
1917- /// `pinned_warp_stream_decodes_pixel_exact`, so a test that asserted it
1918- /// against the live file would rot the moment the fix landed -- which is
1919- /// precisely how a scanner loses its edge and reports a clean tree again.
1920- /// A capability test must have its own input.
1921- #[test]
1922- fn the_pin_scanner_sees_the_directory_literal_shape() {
1923- let synthetic = r#"
1924- #[test]
1925- fn a_gate_using_the_old_shape() {
1926- let fixtures = concat!(env!("CARGO_MANIFEST_DIR"), "/../../fixtures");
1927- let paths: Vec<String> = match std::env::var("EC_AV1_GATE_DUMP_PIN") {
1928- Ok(p) => vec![p],
1929- Err(_) => [
1930- "warp-mismatch",
1931- "ii-flake-1",
1932- "rect-flake-3",
1933- ]
1934- .iter()
1935- .map(|n| format!("{fixtures}/{n}.obu"))
1936- .collect(),
1937- };
1938- for path in paths {
1939- check(&path);
1940- }
1941- }
1942-"#;
1943- let reads = pins_read(synthetic);
1944- let names: Vec<&str> = reads.iter().map(|r| r.file.as_str()).collect();
1945- assert_eq!(
1946- names,
1947- vec!["warp-mismatch.obu", "ii-flake-1.obu", "rect-flake-3.obu"],
1948- "the directory-literal + runtime-name shape resolved to {names:?} -- a scanner \
1949- that cannot see this shape is how 14 uncommitted pins survived three rounds"
1950- );
1951- assert!(
1952- reads.iter().all(|r| r.shape == "concat_dir_runtime_name"),
1953- "the synthetic pins were attributed to the wrong shape: {:?}",
1954- reads.iter().map(|r| r.shape).collect::<Vec<_>>()
1955- );
1956- }
1957-
1958- /// The other three shapes resolve too -- same reasoning, same synthetic input,
1959- /// so the capability survives the tree being fixed.
1960- #[test]
1961- fn the_pin_scanner_sees_every_shape() {
1962- let synthetic = r#"
1963- #[test]
1964- fn shapes() {
1965- let a = crate_pin("golden3-pin.obu");
1966- let b = pin_dir().join("sbpart-pin.obu");
1967- let c = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../../fixtures/x.obu"));
1968- }
1969-"#;
1970- let mut names: Vec<String> = pins_read(synthetic)
1971- .iter()
1972- .map(|r| format!("{}|{}", r.file, r.shape))
1973- .collect();
1974- names.sort();
1975- assert_eq!(
1976- names,
1977- vec![
1978- "golden3-pin.obu|crate_pin",
1979- "sbpart-pin.obu|pin_dir_machine_local",
1980- "x.obu|concat_literal_machine_local",
1981- ],
1982- "shape coverage changed: {names:?}"
1983- );
1984- }
1985-
1986- /// THE INVARIANT, on the live tree: every pin a gate reads is a COMMITTED
1987- /// crate-local copy, and NO gate reads through a machine-local shape. This is
1988- /// the check the r3 manifest could not express.
1989- #[test]
1990- fn every_pin_a_gate_reads_is_committed_under_the_crate() {
1991- let src = crate::test_source::module_source("stream");
1992- let reads = pins_read(src);
1993- assert!(
1994- reads.len() >= 20,
1995- "the enumerator found only {} pin reads in stream.rs -- it has lost a shape, \
1996- which is the failure mode that let 14 pins go unseen",
1997- reads.len()
1998- );
1999- let uncommitted: Vec<String> = reads
2000- .iter()
crates/ec-av1/src/lib.rsmodified+0 -6
@@ -37,9 +37,6 @@ mod film_grain;
37 pub use film_grain::apply_film_grain;37 pub use film_grain::apply_film_grain;
38 mod filter_search;38 mod filter_search;
39 pub mod frame;39 pub mod frame;
40-// Test-only: the real-library fixture root and the one presence probe every
41-// gate that needs a clip routes through.
42-mod gate_coverage;
43 mod hits;40 mod hits;
44 pub mod intra;41 pub mod intra;
45 #[cfg(test)]42 #[cfg(test)]
@@ -54,7 +51,6 @@ mod par;
54 pub mod probe;51 pub mod probe;
55 pub mod qm;52 pub mod qm;
56 pub mod quant;53 pub mod quant;
57-mod refusal_inventory;
58 mod restoration;54 mod restoration;
59 pub mod sequence;55 pub mod sequence;
60 pub mod speed;56 pub mod speed;
@@ -63,8 +59,6 @@ pub mod stream;
63 mod superres;59 mod superres;
64 #[cfg(test)]60 #[cfg(test)]
65 mod test_source;61 mod test_source;
66-#[cfg(test)]
67-pub(crate) mod tool_cache;
68 pub mod tile;62 pub mod tile;
69 mod timeline;63 mod timeline;
70 pub mod transform;64 pub mod transform;
crates/ec-av1/src/probe.rsmodified+0 -5
@@ -135,11 +135,6 @@ pub fn source(
135 /// aomenc/ffmpeg over an at-most-a-few-MB fixture: seconds, not minutes.135 /// aomenc/ffmpeg over an at-most-a-few-MB fixture: seconds, not minutes.
136 #[cfg(test)]136 #[cfg(test)]
137 pub(crate) fn run_with_stdin(cmd: &mut Command, input: &[u8]) -> std::process::Output {137 pub(crate) fn run_with_stdin(cmd: &mut Command, input: &[u8]) -> std::process::Output {
138- crate::tool_cache::cached_output(cmd, Some(input), |c| run_child_with_stdin(c, input))
139-}
140-
141-#[cfg(test)]
142-fn run_child_with_stdin(cmd: &mut Command, input: &[u8]) -> std::process::Output {
143 use std::io::{Read, Write};138 use std::io::{Read, Write};
144 use std::process::Stdio;139 use std::process::Stdio;
145 use std::time::{Duration, Instant};140 use std::time::{Duration, Instant};
crates/ec-av1/src/refusal_inventory.rsdeleted+0 -2957

Diff too large; view file

@@ -1,2957 +0,0 @@
1-//! An inventory of what this decoder refuses, and a check on the claims those
2-//! refusals make.
3-//!
4-//! Two rules this repository keeps learning the hard way:
5-//!
6-//! 1. A refusal string is a **claim**. "This encoder never writes one" asserts
7-//! that a real encoder cannot emit the case -- and one such string was
8-//! disproved by the very gate that carried it (the wedge-interintra hang,
9-//! 2026-08-30): the refusal was written from a mismatching frame's header
10-//! state, so it named a correlate rather than the defect. Any refusal
11-//! phrased as a capability claim about the ENCODER, rather than about this
12-//! decoder, needs evidence, and this module makes the set of such strings
13-//! explicit instead of letting it grow quietly.
14-//! 2. Refusals accumulate silently. A lane that adds one to unblock itself is
15-//! doing the right thing (refuse by name rather than desync), but the total
16-//! is the distance to a decoder that handles a default-settings stream, and
17-//! nobody sees a total that nothing prints.
18-//!
19-//! So the test below re-derives every `unsupported(...)` reason reachable on
20-//! the decode path -- `decode.rs` and `stream.rs` -- and pins it. Adding or
21-//! removing a refusal fails until the list is updated, which is the point: the
22-//! diff of this file is the decoder's capability delta, in one place, in
23-//! English.
24-
25-#[cfg(test)]
26-const CAPABILITY_CLAIMS: &[&str] = &[
27- // lane-hdrlossless ENUMERATION: this guard is a claim about THIS
28- // decoder's gate, not about the encoder -- `filter_intra_size_class_rect`
29- // admits no arm with a 64 axis (libaom `av1_filter_intra_allowed_bsize`
30- // is "both sides <= 32"), and the strips it protects are exactly
31- // `(64, 32)`/`(32, 64)`, which fall to its `_ => None` arm. So the
32- // `filter_intra.is_some()` guard in `decode_block_rect` is unreachable;
33- // the proof is `a_sb_level_horz_vert_strip_admits_no_filter_intra_symbol`,
34- // which enumerates every arm of the table. Kept as a named pin (not
35- // deleted) per the repo convention for proven-unreachable guards.
36- "filter intra on a superblock-level HORZ/VERT strip (never expected -- av1_filter_intra_allowed_bsize caps at 32x32)",
37-];
38-
39-#[cfg(test)]
40-const REFUSALS: &[&str] = &[
41- // lane-av1-444 c4's rect/1:4 chroma port added two shape guards whose
42- // strings never landed here (continuation 8's suite run caught the
43- // drift); both are decoder-side "no table for that shape yet" guards on
44- // 4:4:4 rect strips, same family as the rect luma/chroma entries below.
45- // lane-av1-refusalaudit: the 64-axis one is PROVEN unreachable -- its
46- // chroma-unit table covers every conformant strip unit in both supported
47- // chroma formats (enumeration in PROVEN; the witness2 hunt reached
48- // nothing). The chroma-size one below is still live.
49- "a 64-axis strip whose chroma unit has no coefficient table",
50- "a rectangular chroma transform whose size has no coefficient table",
51- "a coded HORZ/VERT strip whose chroma transform has no rect coefficient tables here",
52- "a split intra strip whose transform unit is {tx_w}x{tx_h} (no luma coefficient tables for that shape here)",
53- "an OBMC neighbour whose switchable interp filter was never recorded",
54- "a rectangular inter luma transform unit whose shape has no coefficient table set here",
55- "a rectangular inter chroma transform unit whose shape has no coefficient table set here",
56- "a rectangular transform unit whose shape has no coefficient scan table here",
57- "a 32x32 partition type this decoder does not code (value={part32})",
58- "a Golomb tail longer than this decoder reads",
59- "a tx_type symbol outside its CDF's own set: {t}",
60- "an INTER 32x32 partition type this decoder does not code (value={part32})",
61- "a superblock-level partition value outside PARTITION_NONE..PARTITION_VERT_4",
62- "a 128x128 superblock partition value outside the 8-symbol alphabet",
63- "an inter var-tx tree with a leaf transform larger than 64x64",
64- "CfL, filter intra or a palette on a 128-root HORZ/VERT intra block (every one of their size gates caps at 64x64 or below, so none of these symbols exists there)",
65- // lane-av1unwritten + lane-av1subsizesweep: the BLOCK_INVALID subsize
66- // refusal that mirrors libaom's own (decodeframe.c:1456). The source
67- // string carries escaped quotes around the libaom citation and this
68- // table is matched against the scanner's collected form, so the quotes
69- // stay escaped here the way the scanner keeps them.
70- "a block size 4x8, 8x16 or 16x4 (or 8x4 at 4:4:0) has no chroma plane block at this frame's subsampling mode (libaom: \\\"Block size %dx%d invalid with this subsampling mode\\\", av1/decoder/decodeframe.c:1456, refusing by the same rule)",
71- // lane-t900 r23: palette RECONSTRUCTION now covers the key-frame paths
72- // (earlier lanes), the intra-in-inter square/rect paths (r22) and the
73- // 8x8 LEAF inside an inter frame (this round, gate
74- // `a_screen_stream_with_palette_8x8_leaves_in_inter_frames_decodes_pixel_exact`),
75- // which is why the (UV) string is gone from the decoder entirely -- the
76- // leaf was its only site. The (Y) one survived as the defensive
77- // `palette.is_none()` guard in `read_intra_mode`/`read_intra_mode_rect`
78- // until lane-t900 r33 DELETED both arms: all eight call sites hand the
79- // reader a real ctx/cache pair, so no stream could reach either (audit
80- // `every_read_intra_mode_call_site_hands_the_reader_a_palette_cache`,
81- // which keeps that invariant now the refusal is gone).
82- // lane-av1-ibcrect: `intra block copy on a HORZ/VERT/1:4 rect intra strip
83- // (reconstruction is not ported at this shape)` is GONE -- lane-av1-intrabc
84- // and lane-av1-rect14 reconstructed the 16x16/32x32-level strips, and this
85- // lane ported the last site, `decode_block_128rect`'s 128-root HORZ/VERT
86- // strip (`decode_intrabc_128rect`; a 128 root has no 1:4 arm at all).
87- // Witness:
88- // `an_sb128_rect_strip_with_intrabc_decodes_pixel_exact` (real aomenc
89- // sb128 screen streams coding `use_intrabc` on BLOCK_128X64 strips,
90- // pixel-exact vs ffmpeg).
91- // lane-av1txr: `a sub-8x8 leaf that uses intrabc (…)` is GONE -- the
92- // capability landed in this lane (4x4 / 4x8 / 8x4 intrabc leaves read the
93- // DV and reconstruct a frame copy + the INTER residual; the sub-8x8
94- // intrabc leaf witnesses in `stream.rs` and the `warped.obu` /
95- // `allintra.obu` traces). Its census gate
96- // (`a_sub8_leaf_census_over_intrabc_screen_streams_measures_the_sub8_refusal`)
97- // still runs: it now reports `reached = 0` with the same non-vacuous
98- // premise (allow_intrabc frames + decoded sub-8 leaves).
99- // lane-av112bit: the blanket 12-bit refusal is REPLACED by the named
100- // refusals below -- the witnessed paths (intra stack, dequant/
101- // transforms at the 12-bit tables, deblock, CDEF, Wiener+SGR
102- // restoration, translational subpel MC through the parameterised
103- // round_0/round_1) are lifted by the lane's byte-exact ffmpeg gates.
104- // lane-av112bitc: compound joined the witnessed set (six-frame 12-bit
105- // compound stream byte-exact vs ffmpeg; the combines already absorbed
106- // the CONV_BUF gain drop through `INTER_POST_ROUND - delta`).
107- // lane-av112bitg: film grain joined the witnessed set (two-frame
108- // `--film-grain-test=5` stream byte-exact vs ffmpeg; the gate that
109- // replaced the refusal is
110- // `a_real_aomenc_12bit_film_grain_stream_decodes_pixel_exact`).
111- // lane-av112bitw: warp joined too -- the refusal left all three decision
112- // sites (compound, 16x16+, 8x8 leaf): `warp::warp_round_0` implements
113- // convolve.h's 12-bit `round_0` bump (3 -> 5), and both the single-ref
114- // witness (`a_12bit_warped_motion_stream_decodes_pixel_exact`, the exact
115- // recipe that refused pre-lift) and the rotating-mandelbrot
116- // compound-warp witness
117- // (`a_real_compound_global_warp_12bit_stream_decodes_pixel_exact`, 28
118- // compound warp blocks) are byte-exact vs ffmpeg.
119- // lane-av1screen12: screen content tools LEFT the 12-bit refusal set. The
120- // string was "a 12-bit frame with screen content tools
121- // (allow_screen_content_tools=1: neither palette nor intrabc has a 12-bit
122- // witness)" -- a guard BROADER than the gap it named, because
123- // `allow_screen_content_tools` only opens the `palette_y_mode` /
124- // `palette_uv_mode` symbols and the leaf `use_intrabc` symbol, and both
125- // reconstructions are already depth-parameterised
126- // (`read_palette_colors_y` / `_uv` read at `bit_depth(fctx)`, the
127- // colour-index map writes u16 samples). Three 12-bit arms decode
128- // BYTE-EXACT against the instrumented `aomdec --rawvideo` and against
129- // ffmpeg, each with a +1 control on the oracle's own bytes:
130- // `a_real_aomenc_12bit_screen_content_palette_stream_decodes_pixel_exact`
131- // (pin `screen12_palette.obu`, 2 frames, 76 palette / 43 palette-UV),
132- // `a_real_aomenc_12bit_intrabc_screen_stream_decodes_pixel_exact` (pin
133- // `screen12_intrabc.obu`, 1 frame, `allow_intrabc = 1`, 36 palette /
134- // 34 palette-UV / 11 intrabc blocks) and
135- // `a_real_aomenc_12bit_lossless_screen_content_stream_decodes_pixel_exact`
136- // (pin `screen12_lossless_palette.obu`, 2 frames, 80 palette /
137- // 59 palette-UV, `CodedLossless` AND screen content in the same frame).
138- // The companion "12-bit intrabc has no producer" note was a RECIPE
139- // artefact: libaom sets that frame-header bit from its content detector
140- // (`encoder.c:2404`), so an untiled `smptebars=size=128x96` source gives
141- // `allow_intrabc = 0` with AND without `--tune-content=screen`, while the
142- // 256x192 `-vf tile=2x2` source gives `= 1` at 8, 10 and 12 bits.
143- // lane-av1txr-r2 added, lane-av1-qmatrix RETIRED: the third member of the
144- // silent-garbage family (`using_qmatrix`/`qm_y`/`qm_u`/`qm_v`, refused by
145- // name at the frame header) now DEQUANTISES through libaom's
146- // `iwt_matrix_ref`/`get_dqv` port (`crate::qm`): the parsed 4-bit levels
147- // select per-plane matrices, 1D/identity transforms and lossless blocks
148- // stay flat. Witness:
149- // `a_real_aomenc_quantisation_matrix_stream_decodes_pixel_exact`.
150- // lane-lossless/lane-lossless2: a lossless frame (base_q_idx 0) decodes
151- // sample-exact, KEY and INTER -- TX_4X4 with the Walsh-Hadamard transform
152- // on every plane, no `tx_type` symbol, `is_cfl_allowed` narrowed to a
153- // BLOCK_4X4 chroma plane block, and the chroma plane walked as 4x4 units
154- // plane-major inside each mu chunk (gates
155- // `a_lossless_libaom_key_frame_decodes_sample_exact` /
156- // `a_lossless_libaom_inter_frame_decodes_sample_exact`). The refusal
157- // that stood here for a frame whose SEGMENTS disagree ("the TX_4X4/WHT
158- // rules are per segment there") is LIFTED too: lane-av1mixloss ports the
159- // per-segment table (libaom `decodeframe.c:5205`), and
160- // `a_real_aomenc_mixed_lossless_segment_frame_decodes_sample_exact`
161- // proves a real aq-mode stream sample-exact.
162- "a frame OBU with no tile group",
163- "a frame naming primary_ref_frame at a reference slot with no saved CDF state",
164- "a frame with no mode-info grid",
165- "a frame whose segmentation enables SEG_LVL_REF_FRAME/SKIP/GLOBALMV (this decoder reads segment_id but never lets a segment override a block's reference, skip or mode)",
166- // Still live, but NARROWED: lane-rectres r1 added the 32x32-level 1:4
167- // strips (32x8 / 8x32) to `rect_inter_residual_supported` -- THE shape both
168- // 10-bit 3840x1608 film cuts and every measured 1080p offset stopped on
169- // (gate `a_real_aomenc_inter_sequence_with_32x32_level_1to4_strips_codes_\
170- // their_rect_residual`). The string stays because the shapes below 8x8 and
171- // the AB-partition footprints still have no rectangular residual path.
172- "a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual coding",
173- "a reference frame selected with no picture at this frame's own ref_frame_idx slot for it",
174- "a reference picture outside the 2x down / 16x up scaling limits",
175- "a show_existing_frame header naming an empty reference slot",
176- "an inter var-tx tree with a leaf transform larger than 32x32",
177- // lane-intrainter r1 lifted the >=16x16 square case (per-TU intra
178- // prediction + coefficients, gate
179- // `a_real_aomenc_inter_sequence_with_a_split_transform_intra_block_decodes_pixel_exact`);
180- // lane-leaf8tx r4 lifted the 8x8 leaf's TX_4X4 2x2 grid (gate
181- // `a_real_aomenc_inter_sequence_with_an_angle_delta_8x8_intra_leaf_decodes_pixel_exact`).
182- "an inter frame with no key frame before it",
183- // lane-inter16ab r1 lifted the AB half and r2 the 1:4 half (four 16x4 /
184- // 4x16 inter strips, their 8x4/4x8 chroma pair built from BOTH strips'
185- // motion vectors -- gate
186- // `a_real_aomenc_inter_sequence_with_16x16_level_1to4_partitions_decodes_pixel_exact`).
187- // Two narrower refusals are what is left of that shape:
188- "an inter 16x16-level partition value outside NONE/HORZ/VERT/SPLIT/AB/1:4",
189- // r2 residue: `vartx_leaves` is a list of SQUARE units, and
190- // `sub_tx_size_map[TX_16X4]` is the rectangular TX_8X4 -- the split tree
191- // and its per-unit residual reader both need rect leaves.
192- // r2 residue: `decode_intra_rect_in_inter` codes chroma at the strip's own
193- // halved footprint, which for a 16x4 strip is an 8x2 transform libaom
194- // never wrote (its chroma is the PAIR's 8x4, coded by the odd strip).
195- // lane-sub8x4 r3 narrowed this to "a strip with no chroma-pair record";
196- // lane-wit16x4 r1 put it back at FULL width (r3's witness counters were
197- // phantoms of a desync, class `refusal-lifted-without-a-gate`) behind
198- // an opt-in. lane-t900 r6 NARROWED it again -- the opt-in is
199- // gone -- on a real 10-bit 1920x792 128-superblock film witness that
200- // decodes 14/14 decode-order frames exact vs aomdec and 12/12 shown frames
201- // exact vs ffmpeg while the arm fires 78 16x4 + 149 4x16 (108 chroma-
202- // paired): gate
203- // `a_10bit_128sb_film_frames_with_warp_cdef_and_interintra_decode_pixel_exact`.
204- // What still refuses is a 16x4/4x16 strip with NO chroma-pair record and
205- // every other sub-8 shape.
206- "an intra 16x4/4x16 strip inside an inter 16x16-level 1:4 partition (its 4:2:0 chroma pair is coded once for two strips; only the inter path implements that pairing)",
207- "an intra mode this decoder does not code (round 2)",
208- // lane-intrarect r1 lifted the whole-shape refusal that stood here (the
209- // inter path's intra arm now routes 2:1 strips through `decode_rect_split`);
210- // what is left is the 1:4 shape, whose `bsize_to_tx_size_cat` breaks the
211- // size-group/category diagonal the 2:1 shapes share.
212- "an intra-coded {bw}x{bh} block on the inter block path (no size-group/tx-category row for that shape here)",
213- // lane-t900 r21 NARROWED this: the string used to guard EVERY rect intra
214- // strip of a screen-content inter frame, and a real
215- // `--tune-content=screen` stream reached it on an 8x16 (8-bit) / 16x8
216- // (10-bit) strip. The 2:1 reader now codes the palette syntax itself and
217- // the 1:4 arm goes through `read_intra_mode_rect`, which already did --
218- // both arms of gate
219- // `a_real_aomenc_screen_inter_sequence_codes_palette_syntax_on_rect_intra_strips`
220- // decode ten frames pixel-exact with the strips counted. What still
221- // lane-t900 r22 NARROWED it again: the 16x4/4x16 arm is LIFTED (that arm
222- // routes through `decode_rect4_16_strip`, which reads the palette syntax
223- // itself -- the premise was stale), gated by
224- // `a_screen_stream_with_16x4_intra_strips_in_inter_frames_decodes_pixel_exact`.
225- // What still refuses is the 128-root half of a screen-content frame, whose
226- // body (`decode_block_128rect`) reads no palette syntax and for which no
227- // `--sb-size=128` screen witness exists yet.
228- // lane-t900 r32: the 128-root arm is LIFTED. r31's enumeration
229- // (`no_block_footprint_with_a_128_pixel_side_can_carry_palette_syntax`) is
230- // its proof -- `av1_allow_palette`'s `bw > 64 || bh > 64` bound means a
231- // 128x64/64x128 half codes NO palette syntax at all, so a screen-content
232- // frame's half is byte-identical in syntax to the non-screen twin gate
233- // `an_intra_coded_128_half_inside_an_inter_frame_decodes_pixel_exact`
234- // already decodes pixel-exact. Nothing of this string remains.
235- // lane-t900 r32: the residue of the LIFTED "an intrabc block under
236- // TxMode::Select". The inter var-tx tree is read in full, but the intra
237- // luma reconstruct loop it feeds is a UNIFORM grid of one square
238- // transform, so a tree resolving to mixed leaf sizes would be
239- // reconstructed at the wrong stride. Neither arm of
240- // `an_intrabc_block_under_tx_mode_select_decodes_pixel_exact` reaches it
241- // (both resolve uniform), so it is unwitnessed and stays live.
242- // lane-av1-ibcvtx: LIFTED. The t900 census's own maxp32 recipe class,
243- // retargeted at testsrc2 content with `--max-partition-size=64`, reaches
244- // mixed trees on the first encode (12-recipe hunt, 5/12 recipes hit).
245- // The luma reconstruct now walks the tree's own leaf list per leaf, and
246- // the block's chroma inherits the co-located luma unit's coded tx type
247- // (`av1_get_tx_type`, blockd.h:1278 -- that inheritance was missing on
248- // the uniform multi-TU intrabc path too). Gate:
249- // `a_real_aomenc_intrabc_mixed_vartx_tree_decodes_without_the_mixed_leaf_refusal`.
250- // Its census gate
251- // (`an_intrabc_vartx_census_measures_the_mixed_leaf_refusal`) survives as
252- // the witness that the premise is still exercised -- `reached` is 0 by
253- // construction now.
254- "a motion_mode symbol for a block shape with no CDF row here",
255-];
256-
257-/// The refusals that have a PROVING test, and its name.
258-///
259-/// A refusal with no such test is an unmeasured claim: nothing in the suite
260-/// distinguishes "this case never happens" from "no stream we decode has
261-/// reached it yet". A proving test is one of two shapes:
262-///
263-/// * a WITNESS gate -- a real stream reaches the shape, decodes exact, and the
264-/// refusal is gone (the good case), or
265-/// * a CENSUS gate -- N real streams decode with the refusal firing 0 times
266-/// while the counters for the sibling shapes it names fire, so the claim is
267-/// measured against the domain the decoder is actually handed.
268-///
269-/// The count printed by [`tests::every_proven_refusal_names_a_test_that_exists`]
270-/// is the honest numerator over the inventory below.
271-///
272-/// # lane-av1-hdr: which pins are `spec-conformant` vs a real gap
273-///
274-/// A negative gate proves our refusal FIRES by name on a hand-built stream; it
275-/// does not prove libaom would reject the same stream. This lane read the
276-/// libaom counterpart for the header/reference cluster and recorded the
277-/// verdict (`lanes/av1hdr.report.md` §3). The spec-conformant pins (libaom
278-/// errors identically) are, with their libaom site:
279-///
280-/// * `primary_ref_frame` empty slot -- `decodeframe.c:5075` `AOM_CODEC_CORRUPT_FRAME`.
281-/// * `show_existing_frame` empty slot -- `decodeframe.c:4651` `AOM_CODEC_UNSUP_BITSTREAM`.
282-/// * reference selected with no picture -- `decodeframe.c:5027` `AOM_CODEC_CORRUPT_FRAME`.
283-/// * inter frame with no key frame before -- same site (`decodeframe.c:5008`).
284-/// * no mode-info grid -- no libaom error site; a 0-sized frame cannot be coded.
285-///
286-/// The two that are NOT spec-conformant, and are kept as named capability gaps
287-/// with an assessment (a real gap libaom accepts, no reachable witness here):
288-/// a reference picture whose height differs (libaom SCALES,
289-/// `decodeframe.c:5089`). A third one -- a frame mixing lossless and lossy
290-/// segments (libaom decodes it per segment, `decodeframe.c:5205`) -- was the
291-/// same kind of gap until lane-av1mixloss ported the per-segment table; its
292-/// refusal is gone and
293-/// `a_real_aomenc_mixed_lossless_segment_frame_decodes_sample_exact` is the
294-/// witness.
295-#[cfg(test)]
296-/// Which KIND of proof each [`PROVEN`] row carries.
297-///
298-/// A 2-tuple made every row look equally proven, which is the whole defect:
299-/// a row whose gate drives a hand-built stream into the guard and a row
300-/// whose gate sweeps an alphabet and shows nothing reaches it are held to
301-/// the same standard and read the same way. `label()` is what the tests
302-/// print, so the distinction is visible in the suite's own output.
303-///
304-/// lane-av1refusalclaim r3 also proposed a third variant, `TablePin`
305-/// ("the arms are pinned exactly but the domain the table is REACHED over
306-/// is unestablished"). It is deliberately NOT carried: the one row it was
307-/// minted for now has a gate that establishes the reach domain
308-/// (`every_chroma_unit_decode_block_rect_can_present_has_a_coefficient_table`
309-/// reads the eight `decode_block_rect` call sites' own literal `bw`/`bh`,
310-/// pins the resulting chroma table exactly, and asserts the `(4,8)`/`(8,4)`
311-/// residual is UNPRODUCIBLE), so `Enumeration` is the honest tag and a
312-/// variant with no row would be dead weight. Re-add it the day a gate really
313-/// pins a table without measuring its caller domain -- and give it a row.
314-#[cfg(test)]
315-enum Proof {
316- /// A written stream REACHES the guard and is refused by this exact
317- /// string: the gate goes RED if the guard is removed.
318- NegativeGate,
319- /// The gate enumerates every input the guard can be reached over and
320- /// shows that none of them reaches it: it proves UNREACHABILITY, so it
321- /// is GREEN if the guard is removed.
322- Enumeration,
323-}
324-
325-#[cfg(test)]
326-impl Proof {
327- fn label(&self) -> &'static str {
328- match self {
329- Proof::NegativeGate => "NEGATIVE (reaches the guard; red on removal)",
330- Proof::Enumeration => "ENUMERATION (proves unreachability; green on removal)",
331- }
332- }
333-}
334-
335-#[cfg(test)]
336-const PROVEN: &[(&str, &str, Proof)] = &[
337- // lane-t900 r20, census: three real streams present exactly the 18
338- // `(side, write_w, write_h)` triples `INTER_BLOCK_SHAPES` lists, and
339- // `rect_inter_residual_supported` covers every rectangular one -- the only
340- // footprints `reject_residual` is set for.
341- // lane-av1-witness2 (8 more inter encodes: banded and busy content,
342- // --max-partition-size=32, a single-ref arm, cq 20..45, cpu-used 0..1):
343- // no refusal -- every rect strip the encoder produced sat inside the
344- // supported set. Static half, from the same hunt: the supported list plus
345- // the partition walker's piece set (SB pieces 64x32/32x64/64x16/16x64,
346- // the 32- and 16-level rect/1:4/AB twins, 128 halves tiled as two
347- // TX_64X64) enumerate every rect footprint AV1 partitioning can present;
348- // 1:4 stops at 64 because the 128 root has no 1:4 symbol. No conformant
349- // stream can name an unsupported footprint.
350- (
351- "a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual coding",
352- "a_block_shape_census_over_three_real_streams_leaves_the_rect_residual_refusal_unreachable",
353- Proof::Enumeration,
354- ),
355- // lane-t900 r20, census: the shapes that can reach `decode_intra_rect_in_inter`'s
356- // size-group/tx-category lookup are the ten rectangular census shapes with
357- // `8 <= min` and `max <= 64` (a sub-8 footprint and a 128-px one take
358- // earlier branches), and every one of them has a row.
359- (
360- "an intra-coded {bw}x{bh} block on the inter block path (no size-group/tx-category row for that shape here)",
361- "every_intra_in_inter_shape_the_census_lists_has_a_size_group_row",
362- Proof::Enumeration,
363- ),
364- // lane-t900 r20, census: the only sub-8 footprints three real streams
365- // present are the 16x4/4x16 strips of a 16x16-level 1:4 partition, whose
366- // caller records the chroma pair for every strip, while the supported path
367- // fires on both orientations inside streams that decode with no refusal.
368- (
369- "an intra 16x4/4x16 strip inside an inter 16x16-level 1:4 partition (its 4:2:0 chroma pair is coded once for two strips; only the inter path implements that pairing)",
370- "a_sub8_footprint_census_over_real_streams_leaves_the_intra_16x4_pairing_refusal_unreachable",
371- Proof::Enumeration,
372- ),
373- // lane-t900 r20, census: the rect transform tables and scans, enumerated
374- // over the shapes the measured block-shape domain hands each helper (block
375- // footprint, 4:2:0 chroma unit, rect var-tx leaf, clamped coded corner).
376- // lane-av1-witness2 (8 inter encodes, --enable-tx-size-search=1, rect+1:4
377- // on, --min-partition-size=4, 4:2:0 and 4:4:4, sb 64/128, cq 10..45,
378- // cpu-used 0..2): no refusal while the domain was genuinely exercised --
379- // whole-block 32x8 inter TUs and sub-8 rect pieces decoded. The fourteen
380- // rect shapes the enumeration covers are the whole alphabet, so the `_`
381- // arm has no conformant input.
382- (
383- "a rectangular inter luma transform unit whose shape has no coefficient table set here",
384- "every_rect_transform_shape_the_census_lists_has_a_coefficient_table_and_scan",
385- Proof::Enumeration,
386- ),
387- (
388- "a rectangular inter chroma transform unit whose shape has no coefficient table set here",
389- "every_rect_transform_shape_the_census_lists_has_a_coefficient_table_and_scan",
390- Proof::Enumeration,
391- ),
392- (
393- "a rectangular transform unit whose shape has no coefficient scan table here",
394- "every_rect_transform_shape_the_census_lists_has_a_coefficient_table_and_scan",
395- Proof::Enumeration,
396- ),
397- // lane-t900 r21, enumeration: a var-tx leaf is never larger than the unit
398- // the tree was entered with, and both callers enter at or below their own
399- // ceiling (the one case that does not, a 64px block at TX_64X64, is the
400- // `single` whole-block case the refusal is guarded by).
401- (
402- "an inter var-tx tree with a leaf transform larger than 32x32",
403- "a_var_tx_tree_never_presents_a_leaf_larger_than_the_unit_it_entered",
404- Proof::Enumeration,
405- ),
406- (
407- "an inter var-tx tree with a leaf transform larger than 64x64",
408- "a_var_tx_tree_never_presents_a_leaf_larger_than_the_unit_it_entered",
409- Proof::Enumeration,
410- ),
411- // Pre-existing proofs, registered by lane-t900 r21: a negative gate (a
412- // hand-built 12-bit sequence header is refused BY THIS EXACT STRING rather
413- // than decoded wrong) and a witness gate (a real aomenc screen key frame
414- // reaches intrabc on a rect strip, so the refusal names a shape a real
415- // encoder does write).
416- // lane-t900 r21, enumeration: `partition_w32` is a ten-symbol CDF and
417- // `partition_w128` an eight-symbol one, and every `match` carrying one of
418- // these three fallbacks has an arm for each value of its own alphabet, so
419- // no stream can reach them.
420- (
421- "a 32x32 partition type this decoder does not code (value={part32})",
422- "every_partition_value_of_an_enumerated_alphabet_has_an_arm",
423- Proof::Enumeration,
424- ),
425- (
426- "an INTER 32x32 partition type this decoder does not code (value={part32})",
427- "every_partition_value_of_an_enumerated_alphabet_has_an_arm",
428- Proof::Enumeration,
429- ),
430- (
431- "a 128x128 superblock partition value outside the 8-symbol alphabet",
432- "every_partition_value_of_an_enumerated_alphabet_has_an_arm",
433- Proof::Enumeration,
434- ),
435- // lane-t900 r24, enumeration: the key-frame superblock root's own `match`
436- // has an arm for all ten `partition_w64` values.
437- (
438- "a superblock-level partition value outside PARTITION_NONE..PARTITION_VERT_4",
439- "every_partition_value_of_an_enumerated_alphabet_has_an_arm",
440- Proof::Enumeration,
441- ),
442- // lane-t900 r24, enumeration: the inter 16x16-level if/else chain's
443- // branches name all ten `partition_w16` values between them.
444- (
445- "an inter 16x16-level partition value outside NONE/HORZ/VERT/SPLIT/AB/1:4",
446- "every_partition_value_of_an_if_chain_alphabet_is_named_by_a_branch",
447- Proof::Enumeration,
448- ),
449- // lane-t900 r24, enumeration: every (CDF width, symbol) pair a tx_type row
450- // can present maps to a distinct member of that width's own set.
451- (
452- "a tx_type symbol outside its CDF's own set: {t}",
453- "every_tx_type_symbol_of_every_cdf_width_maps_into_its_own_set",
454- Proof::Enumeration,
455- ),
456- // lane-t900 r24 + lane-av1txr RE-PIN, measured: the reader covers spec
457- // 5.11.40's whole value domain (`0..=(1 << 20) - 2`, both ends of every
458- // prefix length), so no CONFORMANT symbol stream reaches it -- but the
459- // string IS reachable as a SYMPTOM: a frame this decoder desyncs on
460- // (measured: a real libaom monochrome key frame, gate
461- // `a_real_libaom_monochrome_key_frame_is_refused_by_name` at
462- // `stream.rs`) leaves the reader mid-symbol and the next `read_golomb`
463- // reports this tail. The claim below therefore pins the reader's value
464- // coverage, NOT the string's unreachability.
465- (
466- "a Golomb tail longer than this decoder reads",
467- "read_golomb_reads_every_value_a_conformant_stream_can_carry",
468- Proof::Enumeration,
469- ),
470- // lane-t900 r25, enumeration: `parse_tile_group` is the only producer of
471- // the `tiles` vector `decode_stream` tests, and its success path always
472- // pushes at least one `Tile` -- swept over a real frame OBU's tile payload
473- // truncated from empty upwards.
474- (
475- "a frame OBU with no tile group",
476- "a_frame_obu_that_parses_always_carries_at_least_one_tile",
477- Proof::Enumeration,
478- ),
479- // lane-t900 r25, negative gates: hand-built streams that reach each
480- // refusal by name and output no picture (a `show_existing_frame` header
481- // over all 8 empty slots; a stream that opens on an inter frame).
482- (
483- "a show_existing_frame header naming an empty reference slot",
484- "a_show_existing_frame_header_naming_an_empty_slot_is_refused_by_name",
485- Proof::NegativeGate,
486- ),
487- (
488- "an inter frame with no key frame before it",
489- "an_inter_frame_opening_a_stream_is_refused_by_name",
490- Proof::NegativeGate,
491- ),
492- // lane-t900 r25, enumeration: a motion_mode/obmc symbol is read only under
493- // `is_motion_variation_allowed_bsize` (min side >= 8), and each of the 17
494- // `BLOCK_SIZES_ALL` footprints that clause admits maps to a distinct row of
495- // the 17-row table.
496- (
497- "a motion_mode symbol for a block shape with no CDF row here",
498- "every_shape_that_allows_motion_variation_has_a_motion_mode_cdf_row",
499- Proof::Enumeration,
500- ),
501- // lane-av112bit: real-aomenc 12-bit streams, each refused by name
502- // (the gates encode with aomenc --bit-depth=12 and assert the exact
503- // string; the pixel witnesses are the same battery's Ok arms).
504- // lane-av112bitc: the compound pair left with its refusal -- the
505- // six-frame compound stream now DECODES byte-exact
506- // (`a_real_aomenc_12bit_compound_inter_sequence_decodes_pixel_exact`).
507- // lane-av112bitg: the grain refusal left with its witness -- the
508- // two-frame 12-bit grain stream now DECODES byte-exact
509- // (`a_real_aomenc_12bit_film_grain_stream_decodes_pixel_exact`).
510- // lane-av112bitw: the warp pair left too -- its gate now WITNESSES
511- // (`a_12bit_warped_motion_stream_decodes_pixel_exact`, the same recipe
512- // that refused pre-lift) and the compound-warp arm witnesses through
513- // `a_real_compound_global_warp_12bit_stream_decodes_pixel_exact`
514- // (hard `compound_warp_hits > 0`).
515- // lane-av1422lift: the 4:2:2 sequence-header refusal is GONE and so is
516- // this pairing. The tuple named `a_non_420_subsampled_sequence_header_is_
517- // refused_by_name` as the gate that refused (1,0); that gate asserted a
518- // REFUSAL STRING, so it could not fail on a tree where 4:2:2 decode was
519- // completely broken -- it passed unchanged on the broken tree and would
520- // have kept passing if the port had been reverted. Its replacement
521- // `a_real_422_key_frame_and_inter_sequence_decode_pixel_exact` (and the
522- // corpus battery `the_pinned_422_corpus_cells_decode_pixel_exact`) assert
523- // BYTE-EXACT planes against ffmpeg on real 4:2:2 streams, with the
524- // per-plane coefficient-unit census as the non-vacuity arm.
525- // lane-av1txr-r2 paired, lane-av1-qmatrix RETIRED with its gate: the
526- // refusal's witness is now
527- // `a_real_aomenc_quantisation_matrix_stream_decodes_pixel_exact`, which
528- // asserts the qm-on stream DECODES pixel-exact vs ffmpeg and the
529- // matrices were really applied (census counters), while the qm-off
530- // control stays exact and flat.
531- // lane-av1-ibcrect: the pairing for "intra block copy on a HORZ/VERT/1:4
532- // rect intra strip (reconstruction is not ported at this shape)" is GONE
533- // with the string -- lane-av1-intrabc/rect14 reconstructed the
534- // 16x16/32x32-level strips and this lane ported the last site,
535- // `decode_block_128rect`'s 128-root strip. Witness:
536- // `an_sb128_rect_strip_with_intrabc_decodes_pixel_exact`.
537- // lane-t900 r26, enumeration: a y_mode symbol comes from a 13-symbol CDF
538- // and all three guards refuse 13 and above.
539- (
540- "an intra mode this decoder does not code (round 2)",
541- "every_intra_mode_symbol_of_the_y_mode_alphabet_is_coded",
542- Proof::Enumeration,
543- ),
544- // lane-t900 r26, enumeration: `compute_image_size` is 0 only for a zero
545- // frame width/height, which no path a header can code produces (swept
546- // through the real reader per axis, superres division enumerated).
547- (
548- "a frame with no mode-info grid",
549- "every_frame_size_a_header_can_code_has_a_mode_info_grid",
550- Proof::Enumeration,
551- ),
552- // lane-t900 r26, negative gates: written streams that reach each refusal
553- // by name (a 64x32 inter frame over a 64x64 reference; a stream opening on
554- // a non-error-resilient inter frame whose primary_ref slot is empty, over
555- // all 8 slots) with the picture/CDF slot invariant enumerated alongside.
556- // lane-t900 r27, negative gate + structural note: every non-`LAST_FRAME`
557- // reference resolves through `ref_planes`, where an empty slot refuses by
558- // name (swept over all six such references). The STREAM-level witness is
559- // out of reach of this crate's writers -- a shown key frame refreshes all
560- // eight slots and nothing ever clears one, and a stream opening on an
561- // inter frame is stopped one guard earlier -- so the reachable premise is
562- // a HIDDEN key frame with a partial `refresh_frame_flags`, which
563- // `write_frame_header` cannot write. That gap is the open half.
564- (
565- "a reference frame selected with no picture at this frame's own ref_frame_idx slot for it",
566- "a_selected_reference_with_an_empty_ref_frame_idx_slot_refuses_by_name",
567- Proof::NegativeGate,
568- ),
569- // lane-t900 r27, negative gate + census: a written key frame carrying
570- // each of the three mode-overriding features (over three segment ids) is
571- // refused by name with no picture; and real aomenc recipes never enable
572- // one. lane-av1seglvl re-scoped the census: beyond r27's six 1-pass
573- // no-lag recipes it now parses EVERY frame header's feature table over
574- // alt-ref-lag and genuine two-pass arms (`--aq-mode=1/2`, cq45 and the
575- // branch's own high-q cq63, screen + film sources) -- the shapes that
576- // reach `configure_static_seg_features`, the only setter of ALT_LF/
577- // REF_FRAME/SKIP in the tree, which is gated on `hl_sf.static_segmentation`
578- // ("Always set to 0", speed_features.h) and the second pass
579- // (encoder_utils.c:738). What aomenc codes is `SEG_LVL_ALT_Q` tables and
580- // `segment_id` symbols, and nothing else; the map-inheritance defect that
581- // census surfaced (verbatim copy, decodemv.c:342) is fixed and witnessed
582- // by `a_real_aomenc_segmentation_stream_with_map_inheritance_decodes_ // pixel_exact`.
583- // lane-av1-witness2 re-confirmed the census on the current aomenc build:
584- // it has no --enable-segmentation flag at all (aq-mode is the only
585- // segmentation driver; aq-mode 4 is out of range for the build), and 8
586- // aq-mode recipes (1/2/3, + --delta-lf-mode=1, 4:4:4, banded content)
587- // wrote SEG_LVL_ALT_Q tables and segment_id symbols where segmentation
588- // engaged, decoded clean, and never coded one of the three
589- // mode-overriding features.
590- (
591- "a frame whose segmentation enables SEG_LVL_REF_FRAME/SKIP/GLOBALMV (this decoder reads segment_id but never lets a segment override a block's reference, skip or mode)",
592- "a_frame_whose_segmentation_overrides_a_block_mode_is_refused_by_name",
593- Proof::NegativeGate,
594- ),
595- // lane-t900 r27, structural audit + witness: `record_inter_rect_mi` is the
596- // single writer of the interp-filter neighbour band, and no call site
597- // stamps the `[3, 3]` sentinel on an INTER cell (the audit tokenises each
598- // site's arguments); two real `--enable-obmc=1 --enable-dual-filter=1
599- // --cpu-used=0` streams then decode with 237 band reads over ~115 OBMC
600- // blocks each and the refusal firing 0 times (gate
601- // `a_real_obmc_stream_reads_a_recorded_switchable_filter_for_every_neighbour`).
602- // At `--cpu-used=4` aomenc settles on a frame-level fixed filter and the
603- // band is never read -- the speed is load-bearing in that gate.
604- (
605- "an OBMC neighbour whose switchable interp filter was never recorded",
606- "every_inter_record_publishes_an_obmc_readable_filter",
607- Proof::Enumeration,
608- ),
609- // lane-t900 r28: all three scaled-reference (superres) refusals -- the
610- // 8x8 partition leaf, the sub-8x8 inter block and warp -- are LIFTED and
611- // gone from this inventory. The gate
612- // `real_superres_streams_with_sub8_leaf8_and_warp_decode_pixel_exact`
613- // decodes both lifted shapes byte-exact vs ffmpeg, and the census now
614- // asserts none of the three strings comes back.
615- // lane-t900 r33, enumeration: the five callers of `decode_rect_split` pass
616- // the ten rect footprints with `8 <= min` and `max <= 64`, and every one of
617- // them has a chroma table and -- at every tx depth -- a luma arm. The two
618- // shape classes that would miss one (a 128-sided half, a sub-8 strip) have
619- // readers that are not among those callers.
620- (
621- "a coded HORZ/VERT strip whose chroma transform has no rect coefficient tables here",
622- "every_rect_strip_shape_the_split_path_codes_has_a_luma_and_chroma_table",
623- Proof::Enumeration,
624- ),
625- (
626- "a split intra strip whose transform unit is {tx_w}x{tx_h} (no luma coefficient tables for that shape here)",
627- "every_rect_strip_shape_the_split_path_codes_has_a_luma_and_chroma_table",
628- Proof::Enumeration,
629- ),
630- // lane-av1-refusalaudit, enumeration + witness2 hunt: decode_block_rect64's
631- // chroma-unit table covers every conformant 64-axis strip unit in both
632- // supported chroma formats -- at 4:4:4 the strips 64x32/32x64/64x16/16x64
633- // tile to (32,32)/(32,16)/(16,32); at 4:2:0 the halved footprints land on
634- // (32,16)/(16,32)/(32,8)/(8,32). A 128-root half is
635- // `decode_block_128rect`'s, and the 128 root has no 1:4 arm. The hunt (8
636- // real aomenc key-frame encodes: screen+intrabc, rect+1:4, sb 64 and 128,
637- // cq 10..63, cpu-used 0..2) never reached the arm; the three streams that
638- // decode to completion never enter decode_block_rect64 at all.
639- (
640- "a 64-axis strip whose chroma unit has no coefficient table",
641- "every_chroma_unit_a_64_axis_strip_can_present_has_a_coefficient_table",
642- Proof::Enumeration,
643- ),
644- // lane-av1rect8x16, enumeration: `decode_block_rect`'s `_` arm. The nine
645- // textual `decode_block_rect(` matches are 1 declaration + 8 call sites
646- // (this test's `assert_eq!(sites, 8)` counts the calls); all eight pass
647- // `bw`/`bh` as integer LITERALS and every one of them is
648- // a 32-level `PARTITION_HORZ`/`VERT`/`HORZ_A`/`_B`/`VERT_A`/`_B` arm of
649- // `read_sb128_root`'s `match part32`, so the caller shape set is exactly
650- // {32x16, 16x32} and their chroma halves under the three subsamplings an
651- // AV1 `color_config` can carry are {(16,8), (8,16), (16,16), (8,32),
652- // (32,16), (16,32)} -- every one of which has a row. The shape the
653- // sibling sweep left open, a 4:2:0 8x16 luma strip's (4,8) chroma, is
654- // NOT reachable here: a 16-level 2:1 luma strip is read by
655- // `decode_leaf_rect`, which carries the (4,8)/(8,4) rows itself
656- // (decode.rs:15409-15420). Measured, not assumed: 840 real aomenc 4:2:0
657- // key-frame encodes, 826 of whose parsed leaf lists carry a coded
658- // 16-level 2:1 luma strip (`horz_vert_intra_hits()`, which fires only
659- // at the three `decode_leaf_rect` strip sites), decoded to completion
660- // with this string firing 0 times.
661- (
662- "a rectangular chroma transform whose size has no coefficient table",
663- "every_chroma_unit_decode_block_rect_can_present_has_a_coefficient_table",
664- Proof::Enumeration,
665- ),
666- // lane-t900 r33, enumeration: each of the four symbols this guard tests is
667- // read under a size gate that no 128-pixel side passes (the call site's
668- // literal `cfl=false`, `filter_intra_size_class_rect`'s table, and
669- // `palette_bsize_ctx_wh`'s bound).
670- (
671- "CfL, filter intra or a palette on a 128-root HORZ/VERT intra block (every one of their size gates caps at 64x64 or below, so none of these symbols exists there)",
672- "no_128_root_half_reads_a_cfl_filter_intra_or_palette_symbol",
673- Proof::Enumeration,
674- ),
675- // lane-av1txr: the sub-8x8 intrabc refusal this census pinned is GONE (the
676- // capability landed; see the note in `REFUSALS`). The census gate survives
677- // as the witness that its premise is still exercised -- `reached` is 0 by
678- // construction now.
679- // lane-t900 r33, CENSUS: four quantisers of the recipe that reaches the
680- // intrabc var-tx tree at all read it for 5 blocks in total, every one of
681- // which resolved to a UNIFORM leaf size, with the frames pixel-exact.
682- // lane-av1-ibcvtx: the mixed-leaf refusal is LIFTED (see the note in
683- // `REFUSALS`); the pair above moved out with the string. The capability
684- // gate is
685- // `a_real_aomenc_intrabc_mixed_vartx_tree_decodes_without_the_mixed_leaf_refusal`,
686- // which pins the frame's residual sample mismatch against ffmpeg to the
687- // named second defect (a non-intrabc uniform-tree block elsewhere in the
688- // stream) so the pin tightens automatically when that defect is fixed.
689- (
690- "a reference picture outside the 2x down / 16x up scaling limits",
691- "an_inter_frame_shorter_than_its_reference_is_refused_by_name",
692- Proof::NegativeGate,
693- ),
694- (
695- "a frame naming primary_ref_frame at a reference slot with no saved CDF state",
696- "an_inter_frame_naming_an_unrefreshed_primary_ref_slot_is_refused_by_name",
697- Proof::NegativeGate,
698- ),
699- // lane-av1bookkeep W1-4, NEGATIVE: the BLOCK_INVALID subsize refusal
700- // (`refuse_invalid_plane_block`, decode.rs). It is libaom's own rule
701- // (`get_plane_block_size` -> `AOM_CODEC_CORRUPT_FRAME`, decodeframe.c:1456)
702- // applied to a stream whose header and tile disagree. The pin is a 4:2:2
703- // sequence header over a 4:2:0 key frame's tile, whose partition symbols
704- // name 8x16 -- a subsize with no chroma plane block at ss (1,0) -- so the
705- // guard FIRES, by name, and the gate also drives a genuine 4:2:2 pin that
706- // must still decode, so it cannot pass by refusing everything. The gate's
707- // body quotes the refusal WHOLE (not just the libaom citation inside it),
708- // which is what makes this row an anchor the checker can hold.
709- (
710- "a block size 4x8, 8x16 or 16x4 (or 8x4 at 4:4:0) has no chroma plane block at this frame's subsampling mode (libaom: \\\"Block size %dx%d invalid with this subsampling mode\\\", av1/decoder/decodeframe.c:1456, refusing by the same rule)",
711- "a_422_header_over_a_420_tile_refuses_the_subsize_libaom_calls_corrupt",
712- Proof::NegativeGate,
713- ),
714- // lane-av1bookkeep W1-4, ENUMERATION: the LONE capability claim. The guard
715- // in `decode_block_rect` fires only when `filter_intra.is_some()`, and that
716- // flag is `Some` only where `filter_intra_size_class_rect` says so. The
717- // strips the guard protects are `(64, 32)` / `(32, 64)`;
718- // `av1_filter_intra_allowed_bsize` caps both sides at 32x32, so no conformant
719- // stream offers the symbol there. The gate walks every EXPLICIT arm of the
720- // table (none admits a 64 axis), drives the square-delegate's callee
721- // `filter_intra_size_class` at 32 and 64 directly, and quotes the claim's
722- // leading clause in its own body.
723- (
724- "filter intra on a superblock-level HORZ/VERT strip (never expected -- av1_filter_intra_allowed_bsize caps at 32x32)",
725- "a_sb_level_horz_vert_strip_admits_no_filter_intra_symbol",
726- Proof::Enumeration,
727- ),
728-];
729-
730-/// Gates whose `Err` arm turns a decode failure into a printed SKIP rather than
731-/// a test failure.
732-///
733-/// A gate named `..._decodes_pixel_exact` that cannot decode has failed, and
734-/// swallowing the error keeps the suite green while the gate proves nothing --
735-/// the same vacuum as a gate whose feature never fires, arrived at from the
736-/// other side. The list is the exact pin of the gates still shaped that way, so
737-/// the set cannot grow; a converted gate is DELETED from it.
738-///
739-/// lane-av1skipfix: emptied. The last four (`filter_intra`, the two
740-/// `deblocking` gates, and `gradients_stream_with_cdef`) were converted to the
741-/// attempt-loop pattern -- several recipes, at least one required to decode, the
742-/// feature counter hard-asserted on a pixel-compared attempt, a decode error on
743-/// every attempt a hard failure carrying its refusal text. None of the four had
744-/// a genuinely absent capability: every recipe family decoded, the refusals the
745-/// old arms swallowed were a named *screen-content* refusal on one recipe and a
746-/// stale premise on the CDEF gate (a single-superblock frame cannot make libaom
747-/// write `cdef_bits > 0`, so the old recipe never read a `cdef_idx` at all).
748-#[cfg(test)]
749-const GATES_THAT_SKIP_ON_A_DECODE_ERROR: &[&str] = &[];
750-
751-/// Source text with Rust's line continuations dropped and every whitespace run
752-/// collapsed to one space -- the form rustc gives a multi-line literal -- so a
753-/// refusal written across three source lines is still findable in a body, and
754-/// a gate's quote of it still matches the guard's spelling.
755-#[cfg(test)]
756-fn squash_source(s: &str) -> String {
757- let mut out = String::with_capacity(s.len());
758- let mut pending_space = false;
759- for (i, c) in s.char_indices() {
760- if c == '\\' {
761- let rest = &s[i + 1..];
762- if rest.contains('\n')
763- && rest
764- .chars()
765- .take_while(|c| *c != '\n')
766- .all(|c| c == ' ' || c == '\t' || c == '\r')
767- {
768- continue;
769- }
770- }
771- if c.is_whitespace() {
772- pending_space = true;
773- continue;
774- }
775- if pending_space && !out.is_empty() {
776- out.push(' ');
777- }
778- pending_space = false;
779- out.push(c);
780- }
781- out
782-}
783-
784-/// Does `src` carry `refusal`?
785-///
786-/// Lane-av1refusalspan: a proving gate quotes the refusal it proves, and this
787-/// is how it pins that quote to the guard that still carries the string. Both
788-/// sides are squashed, so a literal written over two lines with a `\`
789-/// continuation still matches.
790-#[cfg(test)]
791-pub(crate) fn pins_refusal(src: &str, refusal: &str) -> bool {
792- squash_source(src).contains(&squash_source(refusal))
793-}
794-
795-#[cfg(test)]
796-mod tests {
797- use super::{
798- CAPABILITY_CLAIMS, GATES_THAT_SKIP_ON_A_DECODE_ERROR, PROVEN, Proof, REFUSALS,
799- squash_source,
800- };
801- use std::collections::BTreeSet;
802-
803- /// Every distinct `unsupported(...)` reason on the decode path.
804- ///
805- /// Both sources use the same shape -- `stream.rs` calls
806- /// `Error::unsupported(context, reason)` and `decode.rs` a local
807- /// `unsupported(reason)` helper -- so the reason is always the LAST string
808- /// literal of the call, and Rust's `\` line continuations inside it are
809- /// joined the way rustc joins them.
810- fn decode_path_refusals() -> BTreeSet<String> {
811- let mut found = BTreeSet::new();
812- for src in [crate::test_source::module_source("decode"), crate::test_source::module_source("stream")] {
813- let bytes = src.as_bytes();
814- for (start, _) in src.match_indices("unsupported(") {
815- // `Error::unsupported(` and the bare helper both end here.
816- let mut i = start + "unsupported(".len();
817- // `unsupported(format!("..."))` is the same refusal, one layer in.
818- if src[i..].starts_with("format!(") {
819- i += "format!(".len();
820- }
821- let mut last: Option<String> = None;
822- loop {
823- while i < bytes.len() && (bytes[i] as char).is_whitespace() {
824- i += 1;
825- }
826- if i >= bytes.len() || bytes[i] != b'"' {
827- break;
828- }
829- i += 1;
830- let mut lit = String::new();
831- while i < bytes.len() && bytes[i] != b'"' {
832- if bytes[i] == b'\\' {
833- // A backslash-newline continuation drops the newline
834- // and the indentation that follows it.
835- if bytes.get(i + 1) == Some(&b'\n') {
836- i += 2;
837- while i < bytes.len() && matches!(bytes[i], b' ' | b'\t') {
838- i += 1;
839- }
840- continue;
841- }
842- lit.push(bytes[i] as char);
843- lit.push(bytes[i + 1] as char);
844- i += 2;
845- continue;
846- }
847- lit.push(bytes[i] as char);
848- i += 1;
849- }
850- i += 1;
851- last = Some(lit);
852- while i < bytes.len() && (bytes[i] as char).is_whitespace() {
853- i += 1;
854- }
855- if i < bytes.len() && bytes[i] == b',' {
856- i += 1;
857- continue;
858- }
859- break;
860- }
861- if let Some(reason) = last {
862- // `Error::unsupported`'s first argument is the context
863- // ("AV1 tile"), which is not a reason.
864- if reason != "AV1 tile" {
865- found.insert(reason);
866- }
867- }
868- }
869- }
870- found
871- }
872-
873- #[test]
874- fn the_decode_path_refuses_exactly_the_listed_cases() {
875- let found = decode_path_refusals();
876- let listed: BTreeSet<String> = CAPABILITY_CLAIMS
877- .iter()
878- .chain(REFUSALS)
879- .map(|&s| s.to_owned())
880- .collect();
881- assert!(
882- found.len() >= 30,
883- "the refusal scan found only {} reasons -- it is broken, not the decoder",
884- found.len()
885- );
886-
887- let added: Vec<&String> = found.difference(&listed).collect();
888- assert!(
889- added.is_empty(),
890- "new decode-path refusals are not in the inventory: {added:#?}\n\
891- Add each to REFUSALS -- or, if it claims something about what an ENCODER can \
892- emit, to CAPABILITY_CLAIMS, which requires evidence that the case is genuinely \
893- unreachable rather than merely unseen."
894- );
895- let removed: Vec<&String> = listed.difference(&found).collect();
896- assert!(
897- removed.is_empty(),
898- "these refusals are listed but no longer in the decode path: {removed:#?}\n\
899- Delete them from the inventory -- the capability landed, which is the good case."
900- );
901- }
902-
903- /// A refusal may say what THIS DECODER does not do. Saying what an encoder
904- /// never emits is a claim about the world, and this repository has already
905- /// shipped one that was false.
906- #[test]
907- fn capability_claims_are_declared_not_scattered() {
908- let claimy: Vec<String> = decode_path_refusals()
909- .into_iter()
910- .filter(|r| r.contains("never writes") || r.contains("never expected"))
911- .collect();
912- let declared: BTreeSet<&str> = CAPABILITY_CLAIMS.iter().copied().collect();
913- for reason in &claimy {
914- assert!(
915- declared.contains(reason.as_str()),
916- "{reason:?} claims an encoder never emits this case but is not in \
917- CAPABILITY_CLAIMS. Such a claim needs a gate that proves the case is \
918- unreachable; until it has one, phrase the refusal as what this decoder \
919- does not decode."
920- );
921- }
922- }
923-
924- /// No NEW gate may quietly turn a decode error into a skip.
925- #[test]
926- fn gates_that_swallow_a_decode_error_are_declared() {
927- let src = crate::test_source::module_source("stream");
928- let mut found: BTreeSet<String> = BTreeSet::new();
929- for (i, _) in src.match_indices("\"SKIP ") {
930- let rest = &src[i + "\"SKIP ".len()..];
931- let Some(colon) = rest.find(':') else {
932- continue;
933- };
934- let name = &rest[..colon];
935- if !name
936- .chars()
937- .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
938- {
939- continue;
940- }
941- // The tail of the message says what was skipped. Only "{e}" -- the
942- // decode error itself -- is the shape this test is about; "no
943- // ffmpeg"/"no aomenc" are tool absence, governed by
944- // EC_AV1_REQUIRE_AOMENC instead.
945- let Some(end) = rest.find("\"") else { continue };
946- if rest[colon..end].contains("{e}") {
947- found.insert(name.to_owned());
948- }
949- }
950- let listed: BTreeSet<&str> = GATES_THAT_SKIP_ON_A_DECODE_ERROR.iter().copied().collect();
951- let added: Vec<&String> = found
952- .iter()
953- .filter(|n| !listed.contains(n.as_str()))
954- .collect();
955- assert!(
956- added.is_empty(),
957- "these gates turn a decode error into a printed SKIP and are not declared: \
958- {added:#?}\nA gate that cannot decode has failed -- assert on the error, or use \
959- the attempt-loop pattern (several fixtures, at least one must decode, firing count \
960- hard-asserted)."
961- );
962- let stale: Vec<&&str> = listed.iter().filter(|n| !found.contains(**n)).collect();
963- assert!(
964- stale.is_empty(),
965- "{stale:#?} no longer swallow a decode error -- delete them from the list."
966- );
967- }
968-
969- /// The partition alphabet, in CDF symbol order.
970- const PARTITION_NAMES: [&str; 10] = [
971- "PARTITION_NONE",
972- "PARTITION_HORZ",
973- "PARTITION_VERT",
974- "PARTITION_SPLIT",
975- "PARTITION_HORZ_A",
976- "PARTITION_HORZ_B",
977- "PARTITION_VERT_A",
978- "PARTITION_VERT_B",
979- "PARTITION_HORZ_4",
980- "PARTITION_VERT_4",
981- ];
982-
983- /// The partition values a `match` arm pattern -- or an `if` chain's
984- /// condition -- names: its own tokens, plus every value of an inclusive
985- /// range (`(PARTITION_HORZ_A..=PARTITION_VERT_B).contains(&p)` is four
986- /// values in one). Tokenised, never `contains()`d: a misspelled constant
987- /// in a match pattern is an irrefutable binding that compiles and swallows
988- /// the alphabet, and a substring check would call that covered.
989- fn partition_values_named(head: &str) -> BTreeSet<usize> {
990- let mut out = BTreeSet::new();
991- let idx: Vec<usize> = head
992- .split(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
993- .filter_map(|tok| PARTITION_NAMES.iter().position(|n| *n == tok))
994- .collect();
995- if head.contains("..=") && idx.len() == 2 {
996- for v in idx[0]..=idx[1] {
997- out.insert(v);
998- }
999- }
1000- out.extend(idx);
1001- out
1002- }
1003-
1004- /// The partition alphabets, enumerated against the arms that code them.
1005- ///
1006- /// A partition value is a CDF symbol, and `SymbolDecoder::symbol_fixed`
1007- /// cannot return one outside `0..nsyms` -- so a `match` whose arms cover
1008- /// its whole alphabet has an unreachable fallback, and the refusal that
1009- /// fallback carries names a value no stream can present. This test finds
1010- /// each such `match` by the refusal in its OWN fallback arm (rather than
1011- /// by line number, which drifts) and enumerates the alphabet against the
1012- /// arm patterns, ranges included.
1013- ///
1014- /// The refusals stay in the code: a partition value is a `usize`, so the
1015- /// match needs a fallback arm, and a named refusal is a better one than a
1016- /// panic (class `branch-dropped-as-unreachable`). What this removes is the
1017- /// UNMEASURED part of the claim.
1018- ///
1019- /// Not every partition fallback belongs here: the ones that name a shape
1020- /// this decoder genuinely does not code yet (the 128-root consumers) are
1021- /// live refusals, and the 16x16-level inter chain is an `if`/`else if`
1022- /// ladder rather than a match, so it needs its own enumerator.
1023- #[test]
1024- fn every_partition_value_of_an_enumerated_alphabet_has_an_arm() {
1025- // (the refusal in the fallback arm, the alphabet its CDF codes)
1026- let blocks: [(&str, usize); 4] = [
1027- (
1028- "a 32x32 partition type this decoder does not code",
1029- crate::cdf::PARTITION_W32[0].len() - 1,
1030- ),
1031- (
1032- "an INTER 32x32 partition type this decoder does not code",
1033- crate::cdf::PARTITION_W32[0].len() - 1,
1034- ),
1035- (
1036- "a 128x128 superblock partition value outside the 8-symbol alphabet",
1037- crate::cdf::PARTITION_W128[0].len() - 1,
1038- ),
1039- // lane-t900 r24: the key-frame superblock root. Its `part` is
1040- // either a `partition_w64` symbol or, at a frame edge, one of the
1041- // three gathered outcomes (PARTITION_HORZ, PARTITION_VERT,
1042- // PARTITION_SPLIT) -- all inside the same ten-value alphabet.
1043- (
1044- "a superblock-level partition value outside PARTITION_NONE..PARTITION_VERT_4",
1045- crate::cdf::PARTITION_W64[0].len() - 1,
1046- ),
1047- ];
1048- let src = crate::test_source::module_source("decode");
1049- let lines: Vec<&str> = src.lines().collect();
1050- let indent = |l: &str| l.len() - l.trim_start().len();
1051- let mut found = 0usize;
1052- for (i, line) in lines.iter().enumerate() {
1053- let t = line.trim();
1054- if !(t.starts_with("match part") && t.ends_with('{')) {
1055- continue;
1056- }
1057- let outer = indent(line);
1058- let close = " ".repeat(outer) + "}";
1059- let (mut arms, mut fallback) = (BTreeSet::new(), String::new());
1060- let mut in_fallback = false;
1061- for l in &lines[i + 1..] {
1062- if *l == close {
1063- break;
1064- }
1065- // Arm patterns sit exactly one level in; anything deeper is an
1066- // arm's body, nested matches and `part == PARTITION_*` reads
1067- // included.
1068- if indent(l) != outer + 4 && !l.trim().is_empty() {
1069- if in_fallback {
1070- fallback.push_str(l.trim());
1071- }
1072- continue;
1073- }
1074- if !l.contains("=>") {
1075- continue;
1076- }
1077- in_fallback = l.trim_start().starts_with("_ =>");
1078- arms.extend(partition_values_named(l.split("=>").next().unwrap_or("")));
1079- }
1080- let Some((reason, alphabet)) =
1081- blocks.iter().find(|(reason, _)| fallback.contains(reason))
1082- else {
1083- continue;
1084- };
1085- found += 1;
1086- let missing: Vec<usize> = (0..*alphabet).filter(|v| !arms.contains(v)).collect();
1087- assert!(
1088- missing.is_empty(),
1089- "the `match` at decode.rs:{} refuses {reason:?} but has no arm for {:?} -- that \
1090- is a real gap in its {alphabet}-value alphabet, not a dead refusal",
1091- i + 1,
1092- missing
1093- .iter()
1094- .map(|v| PARTITION_NAMES[*v])
1095- .collect::<Vec<_>>()
1096- );
1097- }
1098- assert_eq!(
1099- found,
1100- blocks.len(),
1101- "not every enumerated partition refusal was located in decode.rs"
1102- );
1103- }
1104-
1105- /// The same enumeration for a partition refusal that sits in an `if`
1106- /// chain rather than a `match` fallback.
1107- ///
1108- /// The inter 16x16-level ladder tests `part16` against constants arm by
1109- /// arm and refuses in its second-to-last branch, with `PARTITION_SPLIT`
1110- /// left to the final `else`. Nothing about that shape is weaker than a
1111- /// `match`: `part16` is a `partition_w16` symbol (or, at a frame edge, a
1112- /// gathered value of the same alphabet), so if the chain's conditions
1113- /// between them name every value of that alphabet, the refusing branch is
1114- /// unreachable.
1115- ///
1116- /// The conditions are read from the source, tokenised (never
1117- /// substring-matched -- lane-t900 r21), and a condition carrying `&&` is
1118- /// rejected outright: a value it names is only conditionally handled, and
1119- /// counting it would overstate the coverage.
1120- #[test]
1121- fn every_partition_value_of_an_if_chain_alphabet_is_named_by_a_branch() {
1122- // (the refusal in the chain's refusing branch, the alphabet its CDF codes)
1123- let chains: [(&str, usize); 1] = [(
1124- "an inter 16x16-level partition value outside NONE/HORZ/VERT/SPLIT/AB/1:4",
1125- crate::cdf::PARTITION_W16[0].len() - 1,
1126- )];
1127-
1128- let src = crate::test_source::module_source("decode");
1129- let lines: Vec<&str> = src.lines().collect();
1130- let indent = |l: &str| l.len() - l.trim_start().len();
1131- let mut found = 0usize;
1132- for (reason, alphabet) in chains {
1133- let refusal = lines
1134- .iter()
1135- .position(|l| l.contains(reason))
1136- .unwrap_or_else(|| panic!("{reason:?} is not in decode.rs"));
1137- // The branch that carries the refusal: the nearest `} else if`
1138- // above it. Its indentation is the chain's own.
1139- let head = (0..refusal)
1140- .rev()
1141- .find(|&i| lines[i].trim_start().starts_with("} else if "))
1142- .unwrap_or_else(|| panic!("{reason:?} is not inside an if/else chain"));
1143- let outer = indent(lines[head]);
1144- let var = lines[head].trim_start()["} else if ".len()..]
1145- .split_whitespace()
1146- .next()
1147- .unwrap_or("")
1148- .to_owned();
1149- assert!(
1150- !var.is_empty(),
1151- "the chain at decode.rs:{} tests nothing",
1152- head + 1
1153- );
1154-
1155- // Walk up collecting every branch head of this chain, each read to
1156- // the line that opens its body.
1157- let mut named = BTreeSet::new();
1158- let mut i = head + 1;
1159- let mut heads = 0usize;
1160- loop {
1161- i -= 1;
1162- let t = lines[i].trim_start();
1163- if indent(lines[i]) != outer
1164- || !(t.starts_with("} else if ") || t.starts_with("if "))
1165- {
1166- if i == 0 {
1167- break;
1168- }
1169- continue;
1170- }
1171- let mut cond = String::new();
1172- for l in &lines[i..] {
1173- cond.push(' ');
1174- cond.push_str(l.trim());
1175- if l.trim_end().ends_with('{') {
1176- break;
1177- }
1178- }
1179- assert!(
1180- cond.contains(&var),
1181- "the branch at decode.rs:{} sits in the chain that refuses {reason:?} but \
1182- does not test {var}",
1183- i + 1
1184- );
1185- assert!(
1186- !cond.contains("&&"),
1187- "the branch at decode.rs:{} handles its partition values only conditionally \
1188- ({cond:?}) -- the enumeration below would overstate what the chain covers",
1189- i + 1
1190- );
1191- named.extend(partition_values_named(&cond));
1192- heads += 1;
1193- if t.starts_with("if ") {
1194- break;
1195- }
1196- assert!(i > 0, "the chain that refuses {reason:?} has no start");
1197- }
1198- // The value the refusing branch excludes (`part16 != PARTITION_SPLIT`)
1199- // is handled by the chain's final `else`, so require one.
1200- let close = " ".repeat(outer) + "} else {";
1201- assert!(
1202- lines[refusal..].iter().any(|l| *l == close),
1203- "the chain that refuses {reason:?} has no final `else`, so the value its \
1204- refusing branch excludes is handled nowhere"
1205- );
1206- assert!(heads >= 2, "only {heads} branch(es) found for {reason:?}");
1207- found += 1;
1208- let missing: Vec<usize> = (0..alphabet).filter(|v| !named.contains(v)).collect();
1209- assert!(
1210- missing.is_empty(),
1211- "the chain at decode.rs:{} refuses {reason:?} but no branch names {:?} -- that \
1212- is a real gap in its {alphabet}-value alphabet, not a dead refusal",
1213- head + 1,
1214- missing
1215- .iter()
1216- .map(|v| PARTITION_NAMES[*v])
1217- .collect::<Vec<_>>()
1218- );
1219- }
1220- assert_eq!(found, chains.len());
1221- }
1222-
1223- /// Every `tx_type` symbol of every CDF width, mapped through the set that
1224- /// width names.
1225- ///
1226- /// The reader decodes `t` from a row of `n` slots, so `t` is in
1227- /// `0..n - 1`, and hands `(n, t)` to [`crate::decode::tx_type_from_symbol`]
1228- /// -- the readers' own mapping, called here rather than transcribed
1229- /// (class `shared-oracle-blindness`: a second copy of a table can be
1230- /// self-consistently wrong). The widths are read from `cdf_state.rs`'s
1231- /// `tx_type` field declarations, so a new table with a width the mapping
1232- /// does not name fails this test rather than reaching the refusal at
1233- /// runtime.
1234- ///
1235- /// Distinctness is part of the claim: a set of `n - 1` symbols must map to
1236- /// `n - 1` DIFFERENT transform types, or the mapping has lost a member of
1237- /// the spec's `Tx_Type_*_Inv_Set*` even while every symbol resolves.
1238- #[test]
1239- fn every_tx_type_symbol_of_every_cdf_width_maps_into_its_own_set() {
1240- let mut widths: BTreeSet<usize> = BTreeSet::new();
1241- for line in include_str!("cdf_state.rs").lines() {
1242- let t = line.trim();
1243- if !(t.starts_with("pub ") && t.contains("tx_type") && t.contains("[u16;")) {
1244- continue;
1245- }
1246- let tail = t.rsplit("[u16;").next().unwrap_or("");
1247- let n: usize = tail
1248- .split(']')
1249- .next()
1250- .unwrap_or("")
1251- .trim()
1252- .parse()
1253- .unwrap_or_else(|_| panic!("cannot read a CDF width out of {t:?}"));
1254- widths.insert(n);
1255- }
1256- assert!(
1257- widths.len() >= 4,
1258- "the cdf_state.rs scan found only {widths:?} -- it is broken, not the decoder"
1259- );
1260- for &n in &widths {
1261- let nsyms = n - 1;
1262- let mut set: Vec<crate::transform::TxType> = Vec::new();
1263- for t in 0..nsyms {
1264- let ty = crate::decode::tx_type_from_symbol(n, t).unwrap_or_else(|| {
1265- panic!(
1266- "a {n}-slot tx_type CDF codes symbol {t}, which maps to no transform \
1267- type -- the refusal \"a tx_type symbol outside its CDF's own set\" is \
1268- reachable, and that is a mapping-table gap to fix"
1269- )
1270- });
1271- assert!(
1272- !set.contains(&ty),
1273- "a {n}-slot tx_type CDF maps symbol {t} to {ty:?}, which another symbol of \
1274- the same set already names -- a member of the spec's inverse table is lost"
1275- );
1276- set.push(ty);
1277- }
1278- assert_eq!(set.len(), nsyms);
1279- }
1280- }
1281-
1282- /// The Golomb tail, enumerated over every value a conformant stream can
1283- /// carry.
1284- ///
1285- /// Spec 5.11.40 `read_golomb` counts its unary prefix and BREAKS at
1286- /// `length == 20`, then reads `length - 1` payload bits into an `x` whose
1287- /// top bit is implicit -- so no conformant stream carries a value above
1288- /// `(1 << 20) - 2`, and spec 5.11.39 agrees from the other side by masking
1289- /// the level it feeds with `0xFFFFF`. This walks both ends of every
1290- /// prefix length 1..=20 (plus the small values every real stream uses)
1291- /// through [`crate::tile::write_golomb`] and back through the decoder's own
1292- /// [`crate::decode::read_golomb`], so the refusal "a Golomb tail longer
1293- /// than this decoder reads" is proved to sit strictly OUTSIDE the value
1294- /// domain, not inside it.
1295- ///
1296- /// The residue is a bit pattern, not a value: the spec's break makes the
1297- /// 20th prefix bit a don't-care, so a stream whose 20th prefix bit is 0
1298- /// decodes to the same value there and is refused here. libaom refuses the
1299- /// same bit (`av1/decoder/decodetxb.c:30`, `AOM_CODEC_CORRUPT_FRAME` at
1300- /// `length > 20`), so this refusal is NOT a reader gap to widen: when it
1301- /// fires on a real stream it is an earlier desync's symptom -- see the
1302- /// comment on `read_golomb`.
1303- #[test]
1304- fn read_golomb_reads_every_value_a_conformant_stream_can_carry() {
1305- // lane-av1refusalspan: this gate is the PROOF for the refusal below, so
1306- // it names it and pins its guard site.
1307- const REFUSAL: &str = "a Golomb tail longer than this decoder reads";
1308- assert!(
1309- super::pins_refusal(crate::test_source::module_source("decode"), REFUSAL),
1310- "this gate proves {REFUSAL:?}, but that string is no longer in decode.rs"
1311- );
1312- let roundtrip = |value: u32| -> ec_core::Result<u32> {
1313- let mut enc = crate::msac::SymbolEncoder::new();
1314- crate::tile::write_golomb(&mut enc, value);
1315- let data = enc.finish();
1316- let mut dec = crate::msac::SymbolDecoder::new(&data);
1317- crate::decode::read_golomb(&mut dec)
1318- };
1319- let mut values: BTreeSet<u32> = (0..=64u32).collect();
1320- for length in 1..=20u32 {
1321- // `x` has `length` bits with its top bit set, and the value is
1322- // `x - 1`: the two ends of what this prefix length can express.
1323- values.insert((1u32 << (length - 1)) - 1);
1324- values.insert(((1u64 << length) - 2) as u32);
1325- }
1326- let max = *values.iter().max().unwrap();
1327- assert_eq!(
1328- max,
1329- (1u32 << 20) - 2,
1330- "the enumeration misses the spec's own ceiling"
1331- );
1332- // A coefficient is masked to 20 bits (spec 5.11.39), and the base and
1333- // base-range syntax contribute at most 15 of that before the tail, so
1334- // this is the largest tail a legal coefficient can need.
1335- assert!(
1336- max >= 0xF_FFFF - 15,
1337- "the ceiling is below the largest legal tail"
1338- );
1339- for value in values {
1340- match roundtrip(value) {
1341- Ok(read) => assert_eq!(read, value, "the Golomb tail {value} read back as {read}"),
1342- Err(e) => panic!(
1343- "the Golomb tail {value} is inside the domain spec 5.11.40 can write but \
1344- this decoder refuses it: {e}"
1345- ),
1346- }
1347- }
1348- // And the refusal still names something: 20 zero prefix bits.
1349- let mut enc = crate::msac::SymbolEncoder::new();
1350- for _ in 0..20 {
1351- enc.literal(0, 1);
1352- }
1353- for _ in 0..20 {
1354- enc.literal(1, 1);
1355- }
1356- let data = enc.finish();
1357- let mut dec = crate::msac::SymbolDecoder::new(&data);
1358- assert!(
1359- crate::decode::read_golomb(&mut dec).is_err(),
1360- "the Golomb refusal is dead code -- drop it from the inventory"
1361- );
1362- }
1363-
1364- /// The intra-mode alphabet, enumerated against the guard that refuses a
1365- /// symbol outside it.
1366- ///
1367- /// Three readers -- the rect-in-inter arm, the intra-in-inter square arm
1368- /// and the 8x8 leaf -- read a y_mode symbol and refuse `mode >= 13` with
1369- /// "an intra mode this decoder does not code (round 2)". A `y_mode` symbol
1370- /// comes from `Cdfs::y_mode[size_group]`, whose alphabet is
1371- /// `Y_MODE[g].len() - 1` (the last slot is the adaptation counter), and
1372- /// `SymbolDecoder::symbol` cannot return a value outside `0..nsyms` -- so
1373- /// the guard is unreachable exactly when every size group's alphabet is at
1374- /// most the threshold.
1375- ///
1376- /// Found by the refusal in the guard's own body rather than by line
1377- /// number, and the CDF the symbol was read from is checked too: a
1378- /// threshold of 13 over a 14-symbol table would be a live refusal, and a
1379- /// site reading a WIDER alphabet (`uv_mode` with CfL is 14) under the same
1380- /// guard would be one as well.
1381- #[test]
1382- fn every_intra_mode_symbol_of_the_y_mode_alphabet_is_coded() {
1383- const REFUSAL: &str = "an intra mode this decoder does not code (round 2)";
1384- // Both uv_mode alphabets are listed so the CfL-allowed one (14
1385- // symbols, `UV_MODE_CFL_ALLOWED`) cannot silently become the source of
1386- // a symbol tested against 13.
1387- let alphabets: [(&str, usize); 3] = [
1388- ("y_mode", crate::cdf::Y_MODE[0].len() - 1),
1389- ("uv_mode_no_cfl", crate::cdf::UV_MODE_NO_CFL[0].len() - 1),
1390- ("uv_mode_cfl", crate::cdf::UV_MODE_CFL[0].len() - 1),
1391- ];
1392- assert_eq!(alphabets[0].1, 13, "the y_mode alphabet changed size");
1393- for group in &crate::cdf::Y_MODE {
1394- assert_eq!(
1395- group.len() - 1,
1396- alphabets[0].1,
1397- "the y_mode rows disagree on width"
1398- );
1399- }
1400-
1401- let src = crate::test_source::module_source("decode");
1402- let lines: Vec<&str> = src.lines().collect();
1403- let mut sites = 0usize;
1404- for (i, line) in lines.iter().enumerate() {
1405- let t = line.trim();
1406- let Some(rest) = t.strip_prefix("if mode >= ") else {
1407- continue;
1408- };
1409- let Some(threshold) = rest.trim_end_matches(" {").parse::<usize>().ok() else {
1410- continue;
1411- };
1412- // Only the guards carrying THIS refusal.
1413- if !lines[i..(i + 4).min(lines.len())]
1414- .join("\n")
1415- .contains(REFUSAL)
1416- {
1417- continue;
1418- }
1419- sites += 1;
1420- // The symbol's own CDF: the nearest `dec.symbol(&mut cdfs.X[..])`
1421- // above the guard.
1422- let read = lines[i.saturating_sub(12)..i]
1423- .iter()
1424- .rev()
1425- .find(|l| l.contains("dec.symbol(&mut cdfs."))
1426- .unwrap_or_else(|| panic!("line {}: no symbol read above the guard", i + 1));
1427- let table = read
1428- .split("dec.symbol(&mut cdfs.")
1429- .nth(1)
1430- .unwrap()
1431- .split('[')
1432- .next()
1433- .unwrap();
1434- let (name, nsyms) = alphabets
1435- .iter()
1436- .find(|(n, _)| *n == table)
1437- .unwrap_or_else(|| panic!("line {}: unknown mode alphabet {table:?}", i + 1));
1438- assert!(
1439- *nsyms <= threshold,
1440- "line {}: the guard refuses mode >= {threshold} on a symbol read from a \
1441- {nsyms}-symbol {name} CDF -- symbol {threshold} is inside that alphabet, so \
1442- the refusal is live and this enumeration does not prove it",
1443- i + 1
1444- );
1445- }
1446- assert_eq!(
1447- sites, 3,
1448- "the intra-mode guard is at three sites, found {sites}"
1449- );
1450- }
1451-
1452- /// lane-t900 r31, ENUMERATION for "a HORZ/VERT intra strip in a
1453- /// screen-content frame (palette syntax is consumed for square blocks
1454- /// only)".
1455- ///
1456- /// That refusal guards the 128-root HORZ/VERT arm of the intra-in-inter
1457- /// path (`decode.rs`, the `bw.max(bh) == 128` branch): the body it calls,
1458- /// `decode_block_128rect`, reads no palette syntax, so a screen-content
1459- /// frame was assumed to code some there. It cannot. `av1_allow_palette`
1460- /// (spec 5.11.46 `read_palette_mode_info`: `bsize` between `BLOCK_8X8`
1461- /// and `BLOCK_64X64` by side) is what this decoder mirrors in
1462- /// `palette_bsize_ctx_wh`, whose bound is `bw > 64 || bh > 64 ||
1463- /// bw * bh < 64`. Every footprint with a 128-pixel side fails it, so the
1464- /// screen flag changes NOTHING a 128-root half codes -- the refusal's
1465- /// stated premise is false, and the string is a claim about the SYNTAX
1466- /// (provable, and disproved here) rather than about libaom.
1467- ///
1468- /// It is deliberately NOT registered in [`PROVEN`]: the guarded condition
1469- /// is still reachable (a screen frame CAN code a 128-root half), so this
1470- /// test proves the LIFT is safe, not that the case never happens. Lifting
1471- /// it is a `decode.rs` edit plus a witness stream, and no `--sb-size=128
1472- /// --tune-content=screen` encode found so far codes a 128-root half at all
1473- /// (lane-t900 r23's census).
1474- ///
1475- /// The bound is asserted against `decode.rs`'s own source rather than a
1476- /// copy of it here, so a change to the predicate breaks this test rather
1477- /// than silently invalidating it (class `table-and-reader-move-together`).
1478- #[test]
1479- fn no_block_footprint_with_a_128_pixel_side_can_carry_palette_syntax() {
1480- const BOUND: &str = "if bw > 64 || bh > 64 || bw * bh < 64 {";
1481- let src = crate::test_source::module_source("decode");
1482- assert!(
1483- src.contains("fn palette_bsize_ctx_wh(bw: usize, bh: usize) -> Option<usize> {"),
1484- "palette_bsize_ctx_wh is gone -- this enumeration no longer names the predicate \
1485- the decoder gates every palette read on"
1486- );
1487- assert_eq!(
1488- src.matches(BOUND).count(),
1489- 1,
1490- "av1_allow_palette's size bound is no longer spelled {BOUND:?} exactly once in \
1491- decode.rs -- re-derive this enumeration from the new spelling"
1492- );
1493- // `palette_bsize_ctx_wh`'s own bound, applied to every AV1 block
1494- // footprint (both sides a power of two from 4 to 128).
1495- let allows_palette = |bw: usize, bh: usize| !(bw > 64 || bh > 64 || bw * bh < 64);
1496- let (mut with_128, mut allowed_at_128) = (0u32, 0u32);
1497- for wl in 2..=7u32 {
1498- for hl in 2..=7u32 {
1499- let (bw, bh) = (1usize << wl, 1usize << hl);
1500- if bw.max(bh) != 128 {
1501- continue;
1502- }
1503- with_128 += 1;
1504- if allows_palette(bw, bh) {
1505- allowed_at_128 += 1;
1506- }
1507- }
1508- }
1509- assert!(
1510- with_128 > 0,
1511- "enumeration is vacuous -- no 128-sided footprint was tried"
1512- );
1513- assert_eq!(
1514- allowed_at_128, 0,
1515- "a footprint with a 128-pixel side passed av1_allow_palette's bound -- the \
1516- 128-root HORZ/VERT arm really would have to read palette syntax"
1517- );
1518- // And the guarded shapes specifically: the two 128-root HORZ/VERT
1519- // halves the refusal names.
1520- for (bw, bh) in [(128usize, 64usize), (64, 128)] {
1521- assert!(
1522- !allows_palette(bw, bh),
1523- "a {bw}x{bh} half can carry a palette after all"
1524- );
1525- }
1526- }
1527-
1528- /// lane-t900 r33, ENUMERATION for the two [`decode_rect_split`] refusals
1529- /// ("a coded HORZ/VERT strip whose chroma transform has no rect
1530- /// coefficient tables here" and "a split intra strip whose transform unit
1531- /// is {tx_w}x{tx_h}").
1532- ///
1533- /// Both guard shape lookups inside one function, so the proof is one
1534- /// enumeration: the footprints that function is CALLED with, walked
1535- /// through `depth_to_tx_wh` at every depth, against the two `match`
1536- /// tables read out of `decode.rs` itself (class
1537- /// `table-and-reader-move-together` -- a table edit invalidates this test
1538- /// rather than sneaking past it).
1539- ///
1540- /// The footprint domain is the five callers' own: `decode_block_rect`
1541- /// (32-level 2:1), `decode_block_rect4` (32-level 1:4), `decode_leaf_rect`
1542- /// (16-level 2:1), `decode_block_rect64` (64-level 2:1 and 1:4) and
1543- /// `decode_intra_rect_in_inter`, whose reachable shapes are the ten
1544- /// rectangular census shapes with `8 <= min` and `max <= 64` (already
1545- /// pinned by `every_intra_in_inter_shape_the_census_lists_has_a_size_group_row`).
1546- /// The two shape classes that would MISS a table -- a 128-sided half
1547- /// (chroma 64x32) and a sub-8 strip (16x4 -> chroma 8x2) -- are excluded
1548- /// structurally: their readers, `decode_block_128rect` and
1549- /// `decode_rect4_16_strip`, are not among the callers, which this test
1550- /// asserts by locating every `decode_rect_split(` call in its enclosing
1551- /// function.
1552- #[test]
1553- fn every_rect_strip_shape_the_split_path_codes_has_a_luma_and_chroma_table() {
1554- let src = crate::test_source::module_source("decode");
1555- // lane-av1refusalspan: this gate is the PROOF for both refusals below,
1556- // so it names both and pins both guard sites.
1557- for refusal in [
1558- "a coded HORZ/VERT strip whose chroma transform has no rect coefficient tables here",
1559- "a split intra strip whose transform unit is {tx_w}x{tx_h} (no luma coefficient tables for that shape here)",
1560- ] {
1561- assert!(
1562- super::pins_refusal(src, refusal),
1563- "this gate proves {refusal:?}, but that string is no longer in decode.rs"
1564- );
1565- }
1566-
1567- // (1) The caller set. Each call's enclosing function is the last
1568- // top-level `fn` before it.
1569- let fn_starts: Vec<(usize, String)> = src
1570- .match_indices("\nfn ")
1571- .map(|(i, _)| {
1572- let rest = &src[i + 4..];
1573- let name = rest[..rest.find('(').unwrap_or(0)].to_string();
1574- (i, name)
1575- })
1576- .collect();
1577- let mut callers: BTreeSet<String> = BTreeSet::new();
1578- for (at, _) in src.match_indices("decode_rect_split(") {
1579- let enclosing = fn_starts
1580- .iter().rfind(|(i, _)| *i < at)
1581- .expect("a decode_rect_split call outside any function");
1582- if enclosing.1 != "decode_rect_split" {
1583- callers.insert(enclosing.1.clone());
1584- }
1585- }
1586- let expected: BTreeSet<String> = [
1587- "decode_block_rect",
1588- "decode_block_rect4",
1589- "decode_block_rect64",
1590- "decode_intra_rect_in_inter",
1591- "decode_leaf_rect",
1592- ]
1593- .iter()
1594- .map(|s| s.to_string())
1595- .collect();
1596- assert_eq!(
1597- callers, expected,
1598- "the set of functions that call decode_rect_split changed -- re-derive the \
1599- footprint domain below from the new caller (a 128-sided or sub-8 caller makes \
1600- both refusals live)"
1601- );
1602-
1603- // (2) The walk, asserted against its own source before it is applied.
1604- const WALK: &str = " let (mut w, mut h) = (bw.min(64), bh.min(64));\n \
1605- for _ in 0..depth {\n match w.cmp(&h) {\n \
1606- std::cmp::Ordering::Greater => w /= 2,\n \
1607- std::cmp::Ordering::Less => h /= 2,\n \
1608- std::cmp::Ordering::Equal => {\n w /= 2;\n \
1609- h /= 2;\n }\n }\n }";
1610- assert_eq!(
1611- src.matches(WALK).count(),
1612- 1,
1613- "depth_to_tx_wh's walk is no longer spelled the way this enumeration mirrors it"
1614- );
1615- let depth_to_tx_wh = |bw: usize, bh: usize, depth: usize| {
1616- let (mut w, mut h) = (bw.min(64), bh.min(64));
1617- for _ in 0..depth {
1618- match w.cmp(&h) {
1619- std::cmp::Ordering::Greater => w /= 2,
1620- std::cmp::Ordering::Less => h /= 2,
1621- std::cmp::Ordering::Equal => {
1622- w /= 2;
1623- h /= 2;
1624- }
1625- }
1626- }
1627- (w, h)
1628- };
1629-
1630- // (3) The two tables, read out of decode_rect_split's own text: every
1631- // `(w, h) =>` / `(w, h) |` match arm head between the table's `let`
1632- // and the guard that follows it.
1633- let body_at = src
1634- .find("fn decode_rect_split(")
1635- .expect("decode_rect_split is gone");
1636- let body = &src[body_at..];
1637- let slice = |from: &str, to: &str| -> &str {
1638- let a = body
1639- .find(from)
1640- .unwrap_or_else(|| panic!("{from:?} is gone from decode_rect_split"));
1641- let b = body[a..]
1642- .find(to)
1643- .unwrap_or_else(|| panic!("{to:?} is gone from decode_rect_split"));
1644- &body[a..a + b]
1645- };
1646- let arm_shapes = |text: &str| -> BTreeSet<(usize, usize)> {
1647- let mut out = BTreeSet::new();
1648- let bytes = text.as_bytes();
1649- for (i, _) in text.match_indices('(') {
1650- let mut j = i + 1;
1651- let mut w = 0usize;
1652- while j < bytes.len() && bytes[j].is_ascii_digit() {
1653- w = w * 10 + usize::from(bytes[j] - b'0');
1654- j += 1;
1655- }
1656- if j == i + 1 || !text[j..].starts_with(", ") {
1657- continue;
1658- }
1659- j += 2;
1660- let mut h = 0usize;
1661- let start_h = j;
1662- while j < bytes.len() && bytes[j].is_ascii_digit() {
1663- h = h * 10 + usize::from(bytes[j] - b'0');
1664- j += 1;
1665- }
1666- if j == start_h || !text[j..].starts_with(')') {
1667- continue;
1668- }
1669- // Only an arm HEAD counts, never a `(32, 8)` inside prose.
1670- let after = text[j + 1..].trim_start();
1671- if after.starts_with("=>") || after.starts_with('|') {
1672- out.insert((w, h));
1673- }
1674- }
1675- out
1676- };
1677- let chroma = arm_shapes(slice("let chroma: Option<(TxbSet", "if !m.skip {"));
1678- let luma = arm_shapes(slice("let luma_rect: Option<(TxbSet", "no luma \\"));
1679- assert!(
1680- chroma.len() >= 6 && luma.len() >= 6,
1681- "the tables parsed to {} chroma / {} luma shapes -- the parse, not the decoder, \
1682- is what this would be measuring",
1683- chroma.len(),
1684- luma.len()
1685- );
1686-
1687- // (4) The enumeration itself.
1688- let mut checked = 0u32;
1689- for wl in 3..=6u32 {
1690- for hl in 3..=6u32 {
1691- let (bw, bh) = (1usize << wl, 1usize << hl);
1692- let ratio = bw.max(bh) / bw.min(bh);
1693- if ratio != 2 && ratio != 4 {
1694- continue;
1695- }
1696- assert!(
1697- chroma.contains(&(bw / 2, bh / 2)),
1698- "a {bw}x{bh} strip's {}x{} chroma transform has no rect table -- the \
1699- chroma refusal is LIVE for a shape a caller codes",
1700- bw / 2,
1701- bh / 2
1702- );
1703- // Every depth: once the walk reaches a square it stays square,
1704- // so this covers any tx_depth a header can code.
1705- for depth in 1..=4 {
1706- let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
1707- assert!(
1708- tx_w == tx_h || luma.contains(&(tx_w, tx_h)),
1709- "a {bw}x{bh} strip at depth {depth} resolves to a {tx_w}x{tx_h} \
1710- transform unit, which has no luma arm -- that refusal is LIVE"
1711- );
1712- checked += 1;
1713- }
1714- }
1715- }
1716- assert_eq!(
1717- checked, 40,
1718- "the strip domain is not the ten rect shapes x four depths"
1719- );
1720- }
1721-
1722- /// lane-av1rect8x16, ENUMERATION for "a rectangular chroma transform
1723- /// whose size has no coefficient table" --
1724- /// [`crate::decode::decode_block_rect`]'s `_` arm.
1725- ///
1726- /// This refusal had NO `PROVEN` row: the sibling sweep that found the
1727- /// gap (`every_rect_strip_shape_the_split_path_codes_has_a_luma_and_
1728- /// chroma_table`, which audits `decode_rect_split`'s tables, not this
1729- /// function's) asserted only the superblock-level 64x32/32x64
1730- /// footprints, so the 8x16 luma strip's 4x8 chroma was left unasked.
1731- ///
1732- /// The answer is that the shape is UNREACHABLE, and structurally so:
1733- /// every one of the function's call sites passes its `bw`/`bh` as
1734- /// integer LITERALS, and all of them are 32-level `PARTITION_HORZ` /
1735- /// `VERT` / `HORZ_A` / `HORZ_B` / `VERT_A` / `VERT_B` arms of
1736- /// `read_sb128_root`'s `match part32` -- i.e. 32x16 or 16x32, never
1737- /// 8x16. A 16-level 2:1 luma strip (16x8 / 8x16) is read by
1738- /// [`crate::decode::decode_leaf_rect`], which carries the matching
1739- /// `(4, 8)` / `(8, 4)` chroma rows (decode.rs:15409-15420,
1740- /// `TxbSet::ChromaRect8x4` + `SCAN_4X8` / `SCAN_8X4`).
1741- ///
1742- /// So the proof is the CALLER SHAPE SET, read out of the call sites'
1743- /// own argument lists, walked through `bw >> ss_x` / `bh >> ss_y` for
1744- /// every subsampling an AV1 `color_config` can carry, against the
1745- /// `match (chroma_w, chroma_h)` table read out of the function's own
1746- /// text (class `table-and-reader-move-together`: a table edit
1747- /// invalidates this test rather than sneaking past it).
1748- ///
1749- /// The subsampling domain is `{(0,0), (1,0), (1,1)}` and excludes
1750- /// `(0,1)`: `ec-av1-syntax`'s `color_config` only ever READS
1751- /// `subsampling_y` when `subsampling_x == 1` (sequence.rs:481), so
1752- /// `(0,1)` is uncodable. `(1,0)` is 4:2:2. It is walked because that is
1753- /// the codable domain, NOT because a guard stands in the way: as of
1754- /// lane-av1422lift the sequence header no longer refuses 4:2:2 at all, so
1755- /// the sentence this replaces ("refused at the sequence header by
1756- /// `a_non_420_subsampled_sequence_header_is_refused_by_name`") names a
1757- /// gate that no longer exists. The walk was already right; its stated
1758- /// reason was not.
1759- #[test]
1760- fn every_chroma_unit_decode_block_rect_can_present_has_a_coefficient_table() {
1761- let src = crate::test_source::module_source("decode");
1762-
1763- // (1) The caller shape set, read out of the call sites' own
1764- // argument lists. `decode_block_rect(dec, cdfs, neighbours, at, bw,
1765- // bh, ...)`, so args 4 and 5 (0-based, after the opening paren) are
1766- // `bw` and `bh`; the first three are the fixed `&mut` borrows.
1767- const LEAD: [&str; 3] = ["&mut dec", "&mut cdfs", "&mut neighbours"];
1768- let mut shapes: BTreeSet<(usize, usize)> = BTreeSet::new();
1769- let mut sites = 0usize;
1770- let at_def = src
1771- .find("fn decode_block_rect(")
1772- .expect("decode_block_rect is gone");
1773- for (i, _) in src.match_indices("decode_block_rect(") {
1774- // The definition's own parameter list carries the same text,
1775- // preceded by "fn " -- that is a declaration, not a call.
1776- if src[..i].ends_with("fn ") {
1777- continue;
1778- }
1779- // Split the argument list at top level (paren/bracket/angle
1780- // balanced), so the `(at32.0 + 1, at32.1)` origin argument --
1781- // which contains its own comma -- does not shift the indices.
1782- let open = i + "decode_block_rect(".len();
1783- let bytes = src.as_bytes();
1784- let mut args: Vec<String> = Vec::new();
1785- let mut depth = 0i32;
1786- let mut start = open;
1787- for j in open..bytes.len() {
1788- match bytes[j] {
1789- b'(' | b'[' => depth += 1,
1790- b')' | b']' => {
1791- if depth == 0 {
1792- args.push(src[start..j].to_string());
1793- break;
1794- }
1795- depth -= 1;
1796- }
1797- b',' if depth == 0 => {
1798- args.push(src[start..j].to_string());
1799- start = j + 1;
1800- }
1801- _ => {}
1802- }
1803- }
1804- assert!(
1805- args.len() >= 6,
1806- "a decode_block_rect call has only {} arguments -- the arg indices this \
1807- enumeration reads are off",
1808- args.len()
1809- );
1810- for k in 0..3 {
1811- assert_eq!(
1812- args[k].trim(),
1813- LEAD[k],
1814- "decode_block_rect's first three arguments changed -- re-derive the bw/bh \
1815- argument indices below"
1816- );
1817- }
1818- let lit = |a: &str| -> usize {
1819- a.trim().parse::<usize>().unwrap_or_else(|_| {
1820- panic!(
1821- "decode_block_rect is called with a non-literal strip size {:?} -- \
1822- this enumeration can no longer read the caller shape set",
1823- a.trim()
1824- )
1825- })
1826- };
1827- shapes.insert((lit(&args[4]), lit(&args[5])));
1828- sites += 1;
1829- }
1830- assert_eq!(
1831- sites, 8,
1832- "the number of decode_block_rect call sites changed"
1833- );
1834- let expected_shapes: BTreeSet<(usize, usize)> =
1835- [(32usize, 16usize), (16, 32)].into_iter().collect();
1836- assert_eq!(
1837- shapes, expected_shapes,
1838- "the set of strip sizes decode_block_rect is called with changed -- re-derive \
1839- the chroma domain below. An 8x16/16x8 caller makes this refusal LIVE (a \
1840- 4:2:0 8x16 luma strip's chroma is 4x8, which libaom codes as TX_4X8: \
1841- av1_ss_size_lookup[BLOCK_8X16][1][1] = BLOCK_4X8 in \
1842- av1/common/common_data.c:24, then max_txsize_rect_lookup[BLOCK_4X8] = TX_4X8 \
1843- in av1/common/common_data.h:130, via av1_get_max_uv_txsize, blockd.h:1372)"
1844- );
1845-
1846- // (2) The table, read out of the function's own text: every
1847- // `(w, h) =>` / `(w, h) |` arm head between the match and the guard.
1848- let body_at = at_def;
1849- let rest = &src[body_at..];
1850- let body = &rest[..rest.find("\nfn ").expect("unterminated fn")];
1851- let from = body
1852- .find("let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (chroma_w, chroma_h)")
1853- .expect("decode_block_rect's chroma match is gone");
1854- let to = body[from..]
1855- .find("a rectangular chroma transform whose size has no coefficient table")
1856- .expect("the refusal string is gone from decode_block_rect")
1857- + from;
1858- let table = &body[from..to];
1859- let mut arms: BTreeSet<(usize, usize)> = BTreeSet::new();
1860- let bytes = table.as_bytes();
1861- for (i, _) in table.match_indices('(') {
1862- let mut j = i + 1;
1863- let mut w = 0usize;
1864- while j < bytes.len() && bytes[j].is_ascii_digit() {
1865- w = w * 10 + usize::from(bytes[j] - b'0');
1866- j += 1;
1867- }
1868- if j == i + 1 || !table[j..].starts_with(", ") {
1869- continue;
1870- }
1871- j += 2;
1872- let mut h = 0usize;
1873- let start_h = j;
1874- while j < bytes.len() && bytes[j].is_ascii_digit() {
1875- h = h * 10 + usize::from(bytes[j] - b'0');
1876- j += 1;
1877- }
1878- if j == start_h || !table[j..].starts_with(')') {
1879- continue;
1880- }
1881- // Only an arm HEAD counts, never a `(32, 8)` inside prose.
1882- let after = table[j + 1..].trim_start();
1883- if after.starts_with("=>") || after.starts_with('|') {
1884- arms.insert((w, h));
1885- }
1886- }
1887- // (3) The enumeration itself -- run BEFORE the exact-table pin below
1888- // so a deleted arm fails HERE, naming the footprint, instead of
1889- // behind a vaguer "the table changed".
1890- let mut checked = 0u32;
1891- for &(bw, bh) in &shapes {
1892- for (ss_x, ss_y) in [(0usize, 0usize), (1, 0), (1, 1)] {
1893- let (cw, ch) = (bw >> ss_x, bh >> ss_y);
1894- assert!(
1895- arms.contains(&(cw, ch)),
1896- "a {bw}x{bh} strip at subsampling ({ss_x},{ss_y}) has a {cw}x{ch} chroma \
1897- transform with no coefficient table -- the chroma refusal is LIVE"
1898- );
1899- checked += 1;
1900- }
1901- }
1902- assert_eq!(
1903- checked, 6,
1904- "the chroma domain is not two shapes x three formats"
1905- );
1906-
1907- // (4) And the table is EXACTLY those six rows -- no row is a shape no
1908- // caller can present, which is what makes the `_` arm dead.
1909- assert_eq!(
1910- arms,
1911- [
1912- (8usize, 16usize),
1913- (8, 32),
1914- (16, 8),
1915- (16, 16),
1916- (16, 32),
1917- (32, 16)
1918- ]
1919- .into_iter()
1920- .collect::<BTreeSet<(usize, usize)>>(),
1921- "decode_block_rect's chroma table changed -- re-derive the walk above"
1922- );
1923-
1924- // (5) The residual, stated as an assertion so it cannot rot: the two
1925- // 4:2:0 rows an 8x16/16x8 luma strip would need are NOT in this
1926- // table, and (4,8)/(8,4) is not a shape any caller can produce. If a
1927- // future caller hands this function an 8x16, step (1) goes red
1928- // first, and the new row has to be added here with it.
1929- for residual in [(4usize, 8usize), (8, 4)] {
1930- assert!(
1931- !arms.contains(&residual),
1932- "decode_block_rect grew a {0}x{1} chroma row -- update the residual note",
1933- residual.0,
1934- residual.1
1935- );
1936- }
1937- let produces: BTreeSet<(usize, usize)> = shapes
1938- .iter()
1939- .flat_map(|&(bw, bh)| {
1940- [(0usize, 0usize), (1, 0), (1, 1)]
1941- .into_iter()
1942- .map(move |(sx, sy)| (bw >> sx, bh >> sy))
1943- })
1944- .collect();
1945- assert!(
1946- !produces.contains(&(4, 8)) && !produces.contains(&(8, 4)),
1947- "the caller set can now produce a 4x8/8x4 chroma shape but the table has no \
1948- such row -- the chroma refusal is LIVE"
1949- );
1950- }
1951-
1952- /// lane-av1txsizeaudit r2 -- the one value in `ec-av1` whose correct form
1953- /// is provable against libaom but whose *observable effect* is nil, so a
1954- /// pixel gate is impossible and this source scan is the only instrument
1955- /// that can catch a regression.
1956- ///
1957- /// `decode.rs`'s `suppress_internal_lf_edges` publishes the skipped 128
1958- /// root's own chroma extent into `uv_tx_grid`, so the deblocker's
1959- /// alignment gate (`x0 & (tx - 1)`) sees no internal transform edge. The
1960- /// correct extent is the block's own CHROMA footprint,
1961- /// `w_mi * MI >> ss_x` per axis -- `av1_setup_dst_planes`'s
1962- /// `get_plane_block_size(bsize, ss_x, ss_y)`, which at ss (0,0) is the
1963- /// block itself, so **128 and not 64** for a 128x128 root at 4:4:4. The
1964- /// site carried a hardcoded `w_mi * MI / 2`, which is right at 4:2:0 by
1965- /// the `>> 1 == / 2` identity and half the truth everywhere else; its
1966- /// sibling `fill_lf_grid_rect` had already been repaired to
1967- /// `(w_mi * MI) >> ss_x(fctx)`.
1968- ///
1969- /// **No pixel gate can exist for this, and that is measured, not assumed.**
1970- /// The widening defeats the alignment gate, but every edge it lets
1971- /// through then meets the SAME libaom rule applied at the correct place --
1972- /// `edge_params_body`'s spec-7.14.2 / `set_lpf_parameters` term
1973- /// `!pu_edge && cur_ref != 0 && pv_ref != 0 && skip_at && skip_at`, which
1974- /// holds for every internal edge because both cells are the same skipped
1975- /// block. Over 26 frames / 2 555 904 samples of five 4:4:4
1976- /// `--sb-size=128` streams that fire the arm 30 times, `64` and `128` both
1977- /// decode pixel-exact against `aomdec` and differ from each other in not
1978- /// one sample. The masking is TOTAL: the method is only ever called for a
1979- /// block that is itself skipped, so no input exists on which one side of
1980- /// an internal edge is not skipped. Hence: source scan, not pixels.
1981- ///
1982- /// This also pins the `fctx` threading, because `Neighbours` carries no
1983- /// subsampling of its own -- a sibling lane reached the same site and
1984- /// recorded it as unfixable for exactly that reason.
1985- #[test]
1986- fn the_skipped_128_root_chroma_suppression_publishes_the_blocks_own_per_axis_chroma_extent() {
1987- let src = crate::test_source::module_source("decode");
1988- let start = src
1989- .find("fn suppress_internal_lf_edges(")
1990- .expect("suppress_internal_lf_edges is gone");
1991- let body_start = start + src[start..].find('{').expect("no body");
1992- let body =
1993- &src[body_start..body_start + src[body_start..].find("\n }").expect("no end")];
1994-
1995- assert!(
1996- body.contains("((w_mi * MI) >> ss_x(fctx))")
1997- && body.contains("((h_mi * MI) >> ss_y(fctx))"),
1998- "suppress_internal_lf_edges must publish the block's own chroma extent per axis \
1999- -- `w_mi * MI >> ss_x(fctx)`, not a hardcoded `/2`"
2000- );
crates/ec-av1/src/stack_budget.rsmodified+0 -2
@@ -456,7 +456,6 @@ mod tests {
456 ("film_grain.rs", include_str!("film_grain.rs")),456 ("film_grain.rs", include_str!("film_grain.rs")),
457 ("filter_search.rs", include_str!("filter_search.rs")),457 ("filter_search.rs", include_str!("filter_search.rs")),
458 ("frame.rs", include_str!("frame.rs")),458 ("frame.rs", include_str!("frame.rs")),
459- ("gate_coverage.rs", include_str!("gate_coverage.rs")),
460 ("hits.rs", include_str!("hits.rs")),459 ("hits.rs", include_str!("hits.rs")),
461 ("intra.rs", include_str!("intra.rs")),460 ("intra.rs", include_str!("intra.rs")),
462 ("library_fixture.rs", include_str!("library_fixture.rs")),461 ("library_fixture.rs", include_str!("library_fixture.rs")),
@@ -471,7 +470,6 @@ mod tests {
471 ("probe.rs", include_str!("probe.rs")),470 ("probe.rs", include_str!("probe.rs")),
472 ("qm.rs", crate::test_source::module_source("qm")),471 ("qm.rs", crate::test_source::module_source("qm")),
473 ("quant.rs", include_str!("quant.rs")),472 ("quant.rs", include_str!("quant.rs")),
474- ("refusal_inventory.rs", include_str!("refusal_inventory.rs")),
475 ("restoration.rs", include_str!("restoration.rs")),473 ("restoration.rs", include_str!("restoration.rs")),
476 ("sequence.rs", include_str!("sequence.rs")),474 ("sequence.rs", include_str!("sequence.rs")),
477 ("speed.rs", include_str!("speed.rs")),475 ("speed.rs", include_str!("speed.rs")),
crates/ec-av1/src/stream/mod.rsmodified+0 -4
@@ -22,14 +22,10 @@ use ec_av1_syntax::{
22 // Census-only: read outside `mod tests` only in comments; the non-test lib22 // Census-only: read outside `mod tests` only in comments; the non-test lib
23 // target never touches them, so they ride in behind cfg(test) (via the test23 // target never touches them, so they ride in behind cfg(test) (via the test
24 // module's `use super::*`).24 // module's `use super::*`).
25-#[cfg(test)]
26-use ec_av1_syntax::{SEG_LVL_ALT_Q, SEG_LVL_MAX};
27 use ec_core::{Error, Result};25 use ec_core::{Error, Result};
28 26
29 use crate::cdf_state::Cdfs;27 use crate::cdf_state::Cdfs;
30 use crate::decode;28 use crate::decode;
31-#[cfg(test)]
32-use crate::decode::decode_key_frame_tile_lr;
33 use crate::decode::{decode_inter_frame_tile_with_cdfs, decode_key_frame_tile_with_cdfs, q_ctx_of};29 use crate::decode::{decode_inter_frame_tile_with_cdfs, decode_key_frame_tile_with_cdfs, q_ctx_of};
34 use crate::encode::Picture;30 use crate::encode::Picture;
35 31
crates/ec-av1/src/stream/tests/gates_a.rsdeleted+0 -2841

Diff too large; view file

@@ -1,2841 +0,0 @@
1-use super::*;
2-use super::support::*;
3-
4- /// Three-bucket gate summary (class [[gate-skips-on-its-own-failure]]):
5- /// every attempt lands in exactly one bucket -- decoded pixel-exact WITH
6- /// the feature counter moving, decoded pixel-exact WITHOUT it, or a named
7- /// refusal -- and the three sum to the attempts made.
8- pub(super) fn gate_buckets(name: &str, counted_exact: u32, uncounted_exact: u32, named_refusals: usize) {
9- eprintln!(
10- "{name}: buckets counted-exact={counted_exact} uncounted-exact={uncounted_exact} \
11- named-refusals={named_refusals} (attempts {})",
12- counted_exact as usize + uncounted_exact as usize + named_refusals
13- );
14- }
15-
16- pub(crate) fn lock_gate_counters() -> std::sync::MutexGuard<'static, ()> {
17- GATE_COUNTER_LOCK.lock().unwrap_or_else(|e| e.into_inner())
18- }
19-
20- /// The body every 4:4:4 lossy live gate runs: assert the oracle compare
21- /// CANNOT be skipped, assert the decode really is the cell it claims
22- /// (frame count, geometry, full-resolution chroma), assert the 4:4:4-only
23- /// own-extent route really ran, then compare every frame in decode order
24- /// against the oracle aomdec with the length asserted first.
25- ///
26- /// The aomdec arm is a HARD failure, not a skip: these three gates encode
27- /// LIVE, so reaching this point means the oracle aomenc resolved, and
28- /// aomenc and aomdec ship in the same build directory -- an aomdec that is
29- /// missing beside a present aomenc is a broken oracle, not a checkout
30- /// without one. (The older shape, `if aomdec_path().is_file()`, let the
31- /// compare vanish with no env escape at all; that is what
32- /// [`aomdec_available`] replaced for the pinned gates, and it cannot be
33- /// used here because these gates have no stream to compare without one.)
34- pub(super) fn gate_444_lossy_live_exact(name: &str, w: usize, h: usize) {
35- // The ONLY way out without measuring, and it has already printed a
36- // SKIP naming the env var that would turn it into a failure.
37- let Some(stream) = encode_444_lossy_live(name, w, h) else {
38- return;
39- };
40- assert!(
41- aomdec_path().is_file(),
42- "{name}: the oracle aomenc resolved to {} but no aomdec sits beside it at {} -- \
43- the pixel compare would silently skip, which this gate treats as a failure",
44- aomenc_path().display(),
45- aomdec_path().display()
46- );
47-
48- let _guard = lock_gate_counters();
49- crate::decode::reset_rect4_inter_own_chroma444_hits();
50- let frames = decode_stream(&stream).unwrap_or_else(|e| {
51- panic!("{name}: the live {w}x{h} 4:4:4 lossy stream was refused: {e}")
52- });
53- let own = crate::decode::rect4_inter_own_chroma444_hits();
54- assert!(
55- own > 0,
56- "{name}: no 4:4:4 1:4 inter strip read its chroma context over its own extent -- \
57- the route this cell is a witness for never ran (measured: 13 at 66x66, 12 at \
58- 130x122, 24 at 256x128)"
59- );
60- assert_eq!(
61- frames.len(),
62- 4,
63- "{name}: decoded {} frame(s), the recipe encodes 4 -- a short decode would make the \
64- oracle compare cover a prefix of the cell",
65- frames.len()
66- );
67- for (i, f) in frames.iter().enumerate() {
68- assert_eq!(
69- (f.width, f.height),
70- (w, h),
71- "{name}: frame {i} is {}x{}, the cell is {w}x{h}",
72- f.width,
73- f.height
74- );
75- // At 4:4:4 both chroma planes are full resolution. A decoder that
76- // kept a subsampled extent would hand quarter-size planes to the
77- // byte compare; say so here instead of letting the compare
78- // stand in for the shape claim.
79- assert_eq!(
80- f.u.len(),
81- w * h,
82- "{name}: frame {i} U plane is {} samples; at 4:4:4 it must be full resolution \
83- ({w}x{h})",
84- f.u.len()
85- );
86- assert_eq!(
87- f.v.len(),
88- w * h,
89- "{name}: frame {i} V plane is {} samples; at 4:4:4 it must be full resolution \
90- ({w}x{h})",
91- f.v.len()
92- );
93- assert_eq!(
94- f.y.len(),
95- w * h,
96- "{name}: frame {i} luma plane is {} samples, expected {w}x{h}",
97- f.y.len()
98- );
99- }
100- let (decoded, hidden) = decode_all_frames_vs_oracle(&stream, name);
101- assert_eq!(
102- decoded, 4,
103- "{name}: the oracle decoded {decoded} frame(s) in decode order, the recipe carries 4 \
104- (so far {hidden} hidden)"
105- );
106- eprintln!(
107- "{name}: {w}x{h} 4:4:4 lossy, {decoded} decode-order frame(s) byte-exact vs aomdec \
108- ({hidden} hidden), {own} own-extent 1:4 chroma gather(s)"
109- );
110- }
111-
112- /// lane-av1toolgates: the shared body of the two `enable-rect-tx`
113- /// coverage gates (8-bit and 10-bit).
114- ///
115- /// The aomenc ARGUMENT VECTOR is built by each gate and passed in, never
116- /// assembled here. That is not tidiness: `gate_coverage`'s `gate_bodies()`
117- /// splits `stream.rs` on `\n #[` and keeps a segment only if that
118- /// segment itself contains `--passes=1`, so a flag living in a helper is
119- /// invisible to the coverage derivation. A helper that owns the recipe
120- /// would leave this gate counted at whatever depth the helper's own text
121- /// implies -- which is the blind spot that kept `enable-rect-tx` on the
122- /// `NEVER_EXERCISED` lists after real streams had exercised it.
123- ///
124- /// WHAT THIS GATE IS AND IS NOT. `enable_rect_tx` has no sequence-header
125- /// bit in AV1 -- aom reads it only in `tx_search.c` (`search_tx_size`'s
126- /// `!enable_rect_tx && tx_size_wide != tx_size_high` skip and the
127- /// `tx_size_max_32_square` remap) -- so the flag never reaches a decoder.
128- /// Spelling `--enable-rect-tx=1` proves the ENCODER was ALLOWED the tool
129- /// and nothing more. It is CONTEXT here, not the witness: a gate that
130- /// stopped at the flag would be the `tool-disabled-in-every-gate` defect
131- /// `NEVER_EXERCISED` exists to prevent, in a new costume.
132- ///
133- /// The witness is the PARSED PARTITION SHAPE, the only thing in the
134- /// bitstream that can carry a rect transform:
135- /// [`decode::rect_partition_hits`] counts `PARTITION_HORZ`/`PARTITION_VERT`
136- /// symbols actually read, i.e. a rect partition in the tree this decoder
137- /// walked, and [`decode::rect_coeff_tu_hits`] counts the rectangular
138- /// transform units that then coded coefficients through `read_coeffs_rect`
139- /// (`all_zero == 0`) -- the rect coefficient TABLES being read, not a
140- /// header bit. Both are asserted above zero over the arms that decoded AND
141- /// compared, and every frame is pixel-compared against ffmpeg's own decode
142- /// of the identical bytes.
143- ///
144- /// LIMIT, stated because it bounds what this gate can claim: this
145- /// repository has no INDEPENDENT partition parser to list leaves from --
146- /// `ec-av1-syntax` parses OBU headers and the sequence header only -- and
147- /// `ec_av1::census`'s per-frame `blocks`/`tx` shape maps, the one true
148- /// leaf list, are armed by a process-global `OnceLock` on
149- /// `EC_AV1_BITCENSUS`, so arming them inside a lib test would switch the
150- /// accountant on for every other gate in the process. The partition walk is
151- /// therefore observed through the decoder's own counters, which is weaker
152- /// than a second opinion but is still a shape fact about the stream rather
153- /// than a fact about the flag.
154- ///
155- /// RED-BEFORE: the COUNTERS, one per assert, both measured.
156- /// `--enable-rect-tx=0` is deliberately NOT claimed as the mutation: it
157- /// does NOT zero these counters (39 rect coefficient TUs against 210 on
158- /// the cq20 arm, because `--enable-rect-partitions=1` already forces
159- /// non-square transform sizes regardless), and with every partition shape
160- /// off the flag yields no rect transform at either setting. `=0` does turn
161- /// the gate red, but through the ORACLE -- its `--enable-tx-size-search=0`
162- /// arm is a stream ffmpeg cannot decode past frame 6 of 15 -- so the
163- /// frame-count assert fires first and proves nothing about the tool.
164- pub(super) fn rect_tx_tool_gate(name: &str, ten_bit: bool, args: &[String]) -> (usize, usize) {
165- // A missing tool SKIPs, so the totals the caller sums stay 0 and the
166- // gate's own witness assert fails loudly instead of passing vacuously
167- // on a run that decoded nothing.
168- if !have_ffmpeg() {
169- eprintln!("SKIP {name}: no ffmpeg");
170- return (0, 0);
171- }
172- if !have_aomenc() {
173- eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
174- return (0, 0);
175- }
176- let (width, height) = (64usize, 64usize);
177- let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
178- .args([
179- "-v",
180- "error",
181- "-f",
182- "lavfi",
183- "-i",
184- "mandelbrot=size=64x64:rate=25",
185- "-pix_fmt",
186- if ten_bit { "yuv420p10le" } else { "yuv420p" },
187- // y4m calls 10-bit an unofficial pixel format (no-op at 8).
188- "-strict",
189- "-1",
190- "-t",
191- "0.60",
192- "-f",
193- "yuv4mpegpipe",
194- "-",
195- ])
196- .stdin(Stdio::null())
197- .stdout(Stdio::piped())
198- .stderr(Stdio::piped()), None, |c| c.output())
199- .expect("ffmpeg failed to run");
200- assert!(
201- y4m.status.success(),
202- "{name}: ffmpeg fixture: {}",
203- String::from_utf8_lossy(&y4m.stderr)
204- );
205- let out = run_with_stdin(Command::new(aomenc_path()).args(args), &y4m.stdout);
206- assert!(
207- out.status.success(),
208- "{name}: aomenc refused the fixture: {}",
209- String::from_utf8_lossy(&out.stderr)
210- );
211- let stream = out.stdout;
212- assert!(!stream.is_empty(), "{name}: aomenc wrote an empty stream");
213- if ten_bit {
214- assert_eq!(
215- parsed_bit_depth(&stream),
216- 10,
217- "{name}: aomenc did not write a 10-bit sequence header"
218- );
219- }
220- let parts_before = decode::rect_partition_hits();
221- let tus_before = decode::rect_coeff_tu_hits();
222- let decoded = match decode_stream(&stream) {
223- Ok(frames) => frames,
224- Err(e) => panic!("{name}: decode_stream refused: {e}"),
225- };
226- // Sampled after the decode, before the pixel compare, so a mismatch
227- // report can still say whether the arm fired.
228- let parts = decode::rect_partition_hits() - parts_before;
229- let tus = decode::rect_coeff_tu_hits() - tus_before;
230- // The ENCODE's frame count: the fixture renders `mandelbrot=size=64x64:rate=25`
231- // with `-t "0.60"` (10677-10691) -- 25 x 0.60 = 15 frames -- and the
232- // caller's `args` carry no `--limit` (10823-10853), so every arm's stream
233- // codes all 15. Asserted ABOVE the oracle call, which is the fix for the
234- // misattribution this gate's own doc comment records: the
235- // `--enable-tx-size-search=0` arm is a stream ffmpeg cannot decode past
236- // frame 6 of 15, and with the count taken from our decode the helper's
237- // byte-length assert fires FIRST and reads as an ffmpeg fault. Naming the
238- // 15 here makes the shortfall ours to explain.
239- const ENCODED_FRAMES: usize = 15;
240- assert_eq!(
241- decoded.len(),
242- ENCODED_FRAMES,
243- "{name}: the encode codes {ENCODED_FRAMES} frames, the decode showed {} (rect \
244- partitions {parts}, rect coefficient TUs {tus})",
245- decoded.len()
246- );
247- let reference = if ten_bit {
248- ffmpeg_decode_sequence_10bit(&stream, width, height, decoded.len())
249- } else {
250- ffmpeg_decode_sequence(&stream, width, height, decoded.len())
251- };
252- assert_eq!(
253- decoded.len(),
254- reference.len(),
255- "{name}: shown-frame count vs ffmpeg (rect partitions {parts}, rect coefficient \
256- TUs {tus})"
257- );
258- for (i, (ours, theirs)) in decoded.iter().zip(&reference).enumerate() {
259- for (plane, (a, b), w) in [
260- ("Y", (&ours.y, &theirs.y), width),
261- ("U", (&ours.u, &theirs.u), width / 2),
262- ("V", (&ours.v, &theirs.v), width / 2),
263- ] {
264- assert_eq!(a.len(), b.len(), "{name}: frame {i} {plane} plane length");
265- if a != b {
266- let pin = std::env::temp_dir().join(format!("{name}-mismatch.obu"));
267- crate::dumpio::pin("TEST_PIN", &pin, &stream);
268- let at = a
269- .iter()
270- .zip(b.iter())
271- .position(|(x, y)| x != y)
272- .unwrap_or(0);
273- panic!(
274- "{name}: frame {i} {plane} mismatch vs ffmpeg at row {}, col {}: {} vs \
275- {} (rect partitions {parts}, rect coefficient TUs {tus}; stream pinned \
276- at {})",
277- at / w,
278- at % w,
279- a[at],
280- b[at],
281- pin.display()
282- );
283- }
284- }
285- }
286- eprintln!(
287- "{name}: {} bit, pixel-exact vs ffmpeg; parsed rect partitions {parts}, rect \
288- coefficient TUs {tus}",
289- if ten_bit { "10" } else { "8" }
290- );
291- (parts, tus)
292- }
293-
294- /// lane-hbdgates r1: drive one 10-bit aomenc recipe over `seeds`, decode
295- /// every attempt and pixel-compare every SHOWN frame against ffmpeg's own
296- /// 10-bit decode of the identical bytes. Per-tool firing counters are
297- /// sampled PER ATTEMPT and summed only over attempts that decoded *and*
298- /// compared -- a stream that hit a named refusal contributes nothing
299- /// (class `counter-from-refused-stream`). Named refusals are tolerated
300- /// and reported; a pixel mismatch is a hard failure, never a SKIP.
301- pub(super) fn ten_bit_tool_gate(
302- name: &str,
303- width: usize,
304- height: usize,
305- frames: usize,
306- extra: &[&str],
307- seeds: &[u32],
308- counters: &[(&str, fn() -> usize)],
309- ) {
310- fn first_diff(ours: &[u16], theirs: &[u16], width: usize) -> Option<String> {
311- ours.iter()
312- .zip(theirs.iter())
313- .position(|(a, b)| a != b)
314- .map(|i| {
315- format!(
316- "first diff at index {i} (row {}, col {}): ours {} vs ffmpeg {}",
317- i / width,
318- i % width,
319- ours[i],
320- theirs[i]
321- )
322- })
323- }
324- let mut totals = vec![0usize; counters.len()];
325- let mut refusals: Vec<String> = Vec::new();
326- let mut compared = 0usize;
327- for &seed in seeds {
328- let stream = encode_10bit_gradients_seed(name, seed, width, height, frames, extra);
329- assert_eq!(
330- parsed_bit_depth(&stream),
331- 10,
332- "{name}: aomenc did not write a 10-bit sequence header (seed {seed})"
333- );
334- let before: Vec<usize> = counters.iter().map(|(_, f)| f()).collect();
335- let decoded = match decode_stream(&stream) {
336- Ok(frames) => frames,
337- Err(e) => {
338- refusals.push(format!("seed {seed}: {e}"));
339- continue;
340- }
341- };
342- // Deltas are read BEFORE the pixel compare so a mismatch report
343- // says whether the tool under test actually fired on the failing
344- // stream (a mismatch with a zero delta is some other defect).
345- let deltas: Vec<usize> = counters
346- .iter()
347- .zip(before.iter())
348- .map(|((_, f), b)| f() - b)
349- .collect();
350- let fired: Vec<String> = counters
351- .iter()
352- .zip(deltas.iter())
353- .map(|((label, _), d)| format!("{label}={d}"))
354- .collect();
355- let fired = fired.join(" ");
356- // The ENCODE's frame count, and it is this helper's `frames` PARAMETER
357- // (15446) -- not our decode's length. It is the same value handed to
358- // `encode_10bit_gradients_seed` (15469), which renders
359- // `frames / 25.0` seconds at `rate=25` (15928, 15940) and runs
360- // aomenc with no `--limit` of its own, so the stream codes exactly
361- // `frames` frames: 1 for the single-key-frame callers, 24 for the
362- // `--lag-in-frames=16` inter callers. Asserted ABOVE the oracle call,
363- // so a decode that showed fewer reds naming the encode rather than
364- // handing ffmpeg the same short count.
365- assert_eq!(
366- decoded.len(),
367- frames,
368- "{name}: seed {seed}: the encode codes {frames} frame(s), the decode showed {}",
369- decoded.len()
370- );
371- let reference = ffmpeg_decode_sequence_10bit(&stream, width, height, decoded.len());
372- assert_eq!(
373- decoded.len(),
374- reference.len(),
375- "{name}: seed {seed}: shown-frame count vs ffmpeg"
376- );
377- for (i, (ours, theirs)) in decoded.iter().zip(reference.iter()).enumerate() {
378- for (plane, (a, b), w) in [
379- ("Y", (&ours.y, &theirs.y), width),
380- ("U", (&ours.u, &theirs.u), width / 2),
381- ("V", (&ours.v, &theirs.v), width / 2),
382- ] {
383- if let Some(d) = first_diff(a, b, w) {
384- panic!("{name}: seed {seed} frame {i} plane {plane}: {d} [{fired}]");
385- }
386- assert_eq!(
387- a.len(),
388- b.len(),
389- "{name}: seed {seed} frame {i} plane {plane}: ours has {} samples, \
390- ffmpeg's has {} -- a short plane would zip-truncate the walk above \
391- and hide a chroma-span defect",
392- a.len(),
393- b.len()
394- );
395- }
396- }
397- compared += 1;
398- for (i, d) in deltas.iter().enumerate() {
399- totals[i] += d;
400- }
401- }
402- assert!(
403- compared > 0,
404- "{name}: every attempt hit a named refusal:\n{}",
405- refusals.join("\n")
406- );
407- for (i, (label, _)) in counters.iter().enumerate() {
408- assert!(
409- totals[i] > 0,
410- "{name}: {compared} attempt(s) decoded pixel-exact but {label} never fired -- \
411- the gate would prove nothing about that tool. refusals:\n{}",
412- refusals.join("\n")
413- );
414- }
415- let summary: Vec<String> = counters
416- .iter()
417- .zip(totals.iter())
418- .map(|((label, _), t)| format!("{label}={t}"))
419- .collect();
420- eprintln!(
421- "{name}: {compared}/{} attempts pixel-exact, {}",
422- seeds.len(),
423- summary.join(" ")
424- );
425- }
426-
427- pub(super) fn intra_rect_in_inter_gate(bit_depth: u32) {
428- const NAME: &str =
429- "a_real_aomenc_inter_sequence_with_an_intra_rect_strip_decodes_pixel_exact";
430- if !have_ffmpeg() {
431- eprintln!("SKIP {NAME}: no ffmpeg");
432- return;
433- }
434- if !have_aomenc() {
435- eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
436- return;
437- }
438- let (width, height, frame_count) = (96usize, 96usize, 8usize);
439- let mut refusals: Vec<String> = Vec::new();
440- let mut uncounted_exact = 0u32;
441- let mut compared = 0u32;
442- let mut shapes = [0usize; 3];
443- for attempt in 0..45u32 {
444- let seed = 42 + attempt;
445- // mandelbrot's fractal detail plus a HARD cut at frame 4: half
446- // the picture becomes a flat white box, which no motion vector
447- // can predict, so aomenc's RD codes those blocks INTRA inside an
448- // inter frame. The box's vertical edge at x=48 is what makes the
449- // partition search reach for HORZ/VERT strips there.
450- // A FAST ZOOM: `end_scale`/`end_pts` make mandelbrot rush
451- // through its own zoom, so consecutive frames share almost no
452- // content and aomenc's RD codes blocks INTRA inside INTER frames
453- // (`--kf-min-dist=1000` forbids a new key frame). That is the
454- // only way a real encoder reaches this decoder's intra-in-inter
455- // arm; a slowly-evolving source codes every rect strip inter.
456- let source = format!(
457- "mandelbrot=size={width}x{height}:start_scale={}:end_scale=0.004:end_pts=8:rate=25",
458- 5.0 - f64::from(attempt) * 0.06
459- );
460- let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
461- .args([
462- "-v",
463- "error",
464- "-f",
465- "lavfi",
466- "-i",
467- &source,
468- "-vf",
469- "hue=s=0",
470- "-pix_fmt",
471- if bit_depth == 10 {
472- "yuv420p10le"
473- } else {
474- "yuv420p"
475- },
476- "-strict",
477- "-1",
478- "-t",
479- "0.32",
480- "-f",
481- "yuv4mpegpipe",
482- "-strict",
483- "-1",
484- "-",
485- ])
486- .stdin(Stdio::null())
487- .stdout(Stdio::piped())
488- .stderr(Stdio::piped()), None, |c| c.output())
489- .expect("ffmpeg failed to run");
490- assert!(
491- y4m.status.success(),
492- "ffmpeg fixture: {}",
493- String::from_utf8_lossy(&y4m.stderr)
494- );
495- let depth_args: &[&str] = if bit_depth == 10 {
496- &["-b", "10", "--input-bit-depth=10"]
497- } else {
498- &[]
499- };
500- // MEASURED (r1): the speed preset gates the feature (class
501- // [[gate-preset-gates-the-feature]]) -- at `--cpu-used=4` this
502- // content produces no rect partition at all, at `--cpu-used=0`
503- // aomenc emits AB partitions the tile path refuses (it ignores
504- // `--enable-ab-partitions=0`, ledger). So the attempt sweep walks
505- // the preset as well as the seed.
506- let cpu = format!("--cpu-used={}", attempt % 5);
507- // The quantiser drives how finely the RD partitions: the sweep
508- // walks it too, so "no rect strip fired" cannot be an artefact of
509- // one cq.
510- let cq = format!("--cq-level={}", [30u32, 20, 12][(attempt / 5) as usize % 3]);
511- let out = run_with_stdin(
512- Command::new(aomenc_path())
513- .args(depth_args)
514- .arg(&cpu)
515- .arg(&cq)
516- .args([
517- // class [[aomenc-first-flag-wins]]: every flag is spelled
518- // exactly ONCE in this recipe, so there is no override to
519- // order. These four are what this gate is about.
520- "--enable-rect-partitions=1",
521- // MEASURED (r1): the charter's `--min-partition-size=8`
522- // makes 24/24 attempts stop at a sub-16 AB-partition
523- // refusal ("a HORZ_A/HORZ_B/VERT_A partition below 16x16",
524- // "a coded (non-skip) HORZ_B/VERT_B rect strip below
525- // 16x16") before any intra rect strip is reached -- those
526- // are other lanes' surfaces. 16 keeps the 16x8/8x16 shape
527- // reachable (a 16x16 block's own HORZ/VERT children).
528- "--min-partition-size=16",
529- "--max-partition-size=64",
530- // MEASURED (r1): with tx-size search ON, 24/24 attempts stop at
531- // the SQUARE intra-in-inter arm's own refusal ("an intra
532- // block in an inter frame whose tx_depth splits its luma
533- // transform (round 1)", read_block_tx_size) long before a
534- // rect strip is reached -- that arm is another lane's
535- // surface. OFF, no tx-depth symbol is coded at all and
536- // every rect strip here is the unsplit single-transform
537- // case. The SPLIT rect arm (`depth_to_tx_wh` +
538- // decode_rect_split's per-unit walk) is wired but stays
539- // UNGATED on this path until that square refusal lifts.
540- "--enable-tx-size-search=0",
541- "--codec=av1",
542- "--passes=1",
543- "--end-usage=q",
544- "--lag-in-frames=0",
545- "--auto-alt-ref=0",
546- // One key frame at the head: the frames after the cut must
547- // stay INTER frames carrying intra blocks, not become a
548- // new key frame.
549- "--kf-min-dist=1000",
550- "--kf-max-dist=1000",
551- "--threads=1",
552- "--row-mt=0",
553- "--enable-order-hint=0",
554- "--enable-warped-motion=0",
555- "--enable-obmc=0",
556- "--enable-masked-comp=0",
557- "--enable-interintra-comp=0",
558- "--enable-dist-wtd-comp=0",
559- "--enable-diff-wtd-comp=0",
560- "--enable-onesided-comp=0",
561- "--enable-interintra-wedge=0",
562- "--enable-smooth-interintra=0",
563- "--enable-ab-partitions=0",
564- "--enable-1to4-partitions=0",
565- // The intra-in-inter arm reads no `use_filter_intra`
566- // symbol (square OR rect) -- lane-fiinter owns that read.
567- "--enable-filter-intra=0",
568- "--enable-smooth-intra=0",
569- "--enable-paeth-intra=0",
570- "--enable-directional-intra=0",
571- "--enable-angle-delta=0",
572- "--enable-cdef=0",
573- "--enable-restoration=0",
574- "--enable-palette=0",
575- "--enable-intrabc=0",
576- "--enable-cfl-intra=0",
577- "--enable-ref-frame-mvs=0",
578- "--obu",
579- "-o",
580- "-",
581- "-",
582- ]),
583- &y4m.stdout,
584- );
585- assert!(
586- out.status.success(),
587- "aomenc refused the fixture: {}",
588- String::from_utf8_lossy(&out.stderr)
589- );
590- let stream = out.stdout;
591- let before = [
592- decode::intra_rect_strip_in_inter_hits(0),
593- decode::intra_rect_strip_in_inter_hits(1),
594- decode::intra_rect_strip_in_inter_hits(2),
595- ];
596- let kf_rect_before = decode::rect_partition_hits();
597- let frames = match decode_stream(&stream) {
598- Ok(frames) => frames,
599- Err(e) => {
600- let msg = e.to_string();
601- assert!(
602- msg.contains("unsupported"),
603- "intra-rect-in-inter decode failed outright (seed {seed}): {msg}"
604- );
605- refusals.push(format!("seed {seed} {cpu} {cq}: {msg}"));
606- continue;
607- }
608- };
609- let delta = [
610- decode::intra_rect_strip_in_inter_hits(0) - before[0],
611- decode::intra_rect_strip_in_inter_hits(1) - before[1],
612- decode::intra_rect_strip_in_inter_hits(2) - before[2],
613- ];
614- let ffmpeg_frames = if bit_depth == 10 {
615- ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
616- } else {
617- ffmpeg_decode_sequence(&stream, width, height, frame_count)
618- };
619- assert_eq!(frames.len(), frame_count);
620- eprintln!(
621- "intrarect gate {bit_depth}-bit seed={seed} {cpu} {cq}: intra rect strips in inter frames \
622- 64-level={} 32-level={} 16-level={}, key-frame rect strips this stream={}",
623- delta[0],
624- delta[1],
625- delta[2],
626- decode::rect_partition_hits() - kf_rect_before
627- );
628- for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
629- for (plane, (g, w)) in [
630- ("Y", (&got.y, &want.y)),
631- ("U", (&got.u, &want.u)),
632- ("V", (&got.v, &want.v)),
633- ] {
634- let stride = if plane == "Y" { width } else { width / 2 };
635- if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) {
636- eprintln!(
637- "intrarect gate {bit_depth}-bit seed={seed}: frame {i} {plane} first \
638- diff at ({}, {}) got {} want {} ({} samples differ)",
639- at % stride,
640- at / stride,
641- g[at],
642- w[at],
643- g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(),
644- );
645- // Magnitude separates a deblock/prediction difference
646- // (all |d| == 1) from an entropy desync (large,
647- // arbitrary): the first thing r2 needs to know.
648- let maxd = g
649- .iter()
650- .zip(w.iter())
651- .map(|(a, b)| i32::from(*a).abs_diff(i32::from(*b)))
652- .max()
653- .unwrap_or(0);
654- let rows: std::collections::BTreeSet<usize> = g
655- .iter()
656- .zip(w.iter())
657- .enumerate()
658- .filter(|(_, (a, b))| a != b)
659- .map(|(k, _)| k / stride)
660- .collect();
661- eprintln!(
662- "intrarect gate {bit_depth}-bit seed={seed}: frame {i} {plane} max \
663- |diff|={maxd}, rows {:?}..{:?}",
664- rows.iter().next(),
665- rows.iter().next_back()
666- );
667- }
668- assert_eq!(g, w, "{plane} vs ffmpeg (seed {seed}, frame {i})");
669- }
670- }
671- compared += 1;
672- if delta.iter().all(|d| *d == 0) {
673- uncounted_exact += 1;
674- refusals.push(format!(
675- "seed {seed} {cpu} {cq}: decoded and pixel-compared, but no intra rect strip on the \
676- inter path"
677- ));
678- }
679- for k in 0..3 {
680- shapes[k] += delta[k];
681- }
682- if shapes.iter().filter(|n| **n > 0).count() >= 2 {
683- break;
684- }
685- }
686- gate_buckets(
687- NAME,
688- compared - uncounted_exact,
689- uncounted_exact,
690- refusals.len() - uncounted_exact as usize,
691- );
692- eprintln!(
693- "{NAME} ({bit_depth}-bit): compared {compared} streams, intra rect strips in inter \
694- frames per shape: 64x32/32x64={} 32x16/16x32={} 16x8/8x16={}; refusals:\n{}",
695- shapes[0],
696- shapes[1],
697- shapes[2],
698- refusals.join("\n")
699- );
700- assert!(
701- compared > 0,
702- "{NAME} ({bit_depth}-bit): every attempt hit a named refusal -- nothing was \
703- pixel-compared:\n{}",
704- refusals.join("\n")
705- );
706- // MEASURED (r1, 90 attempts; r2 re-ran the 45-attempt sweep at both
707- // depths): only the 32x16/16x32 class is REACHABLE on this branch --
708- // the inter tile path refuses any SB-level partition other than
709- // NONE/SPLIT, so a 64x32/32x64 intra strip cannot be produced at all,
710- // and every 16x8/8x16 candidate stops at a sub-16 refusal owned by
711- // another lane. So the bar is that class, hard, not "two of three":
712- // a green run still cannot come from a stream that fired nothing.
713- assert!(
714- shapes[1] > 0,
715- "{NAME} ({bit_depth}-bit): no 32x16/16x32 intra rect strip fired over \
716- {compared} compared streams (64-level={} 32-level={} 16-level={})",
717- shapes[0],
718- shapes[1],
719- shapes[2]
720- );
721- }
722-
723- pub(super) fn tx_select_inter_gate(bit_depth: u32) {
724- if !have_ffmpeg() {
725- eprintln!(
726- "SKIP a_real_aomenc_inter_sequence_with_tx_select_decodes_pixel_exact: no ffmpeg"
727- );
728- return;
729- }
730- if !have_aomenc() {
731- eprintln!(
732- "SKIP a_real_aomenc_inter_sequence_with_tx_select_decodes_pixel_exact: no aomenc at {}",
733- aomenc_path().display()
734- );
735- return;
736- }
737- let (width, height, frame_count) = (64usize, 64usize, 4usize);
738- let mut refusals = Vec::new();
739- let mut uncounted_exact = 0u32;
740- for attempt in 0..40u32 {
741- let seed = 42 + attempt;
742- // Detail is what makes aomenc's RD prefer a split transform; a
743- // flat gradient resolves every `txfm_split` to 0. `mandelbrot`'s
744- // fractal boundary is the same source the sibling intra tx-select
745- // gate uses, at a different `start_scale` per attempt.
746- let source = format!(
747- "mandelbrot=size=64x64:start_scale={}:rate=25",
748- 5.0 - f64::from(attempt) * 0.06
749- );
750- let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
751- .args([
752- "-v",
753- "error",
754- "-f",
755- "lavfi",
756- "-i",
757- &source,
758- // Desaturated chroma: `uv_mode` stays DC_PRED, so the
759- // still-refused directional-chroma gap never fires and
760- // luma detail alone drives the transform split.
761- "-vf",
762- "hue=s=0",
763- "-pix_fmt",
764- if bit_depth == 10 {
765- "yuv420p10le"
766- } else {
767- "yuv420p"
768- },
769- // y4m carries no official 10-bit tag; ffmpeg writes one
770- // only under `-strict -1` (a no-op at 8 bit).
771- "-strict",
772- "-1",
773- "-t",
774- "0.16",
775- "-f",
776- "yuv4mpegpipe",
777- "-strict",
778- "-1",
779- "-",
780- ])
781- .stdin(Stdio::null())
782- .stdout(Stdio::piped())
783- .stderr(Stdio::piped()), None, |c| c.output())
784- .expect("ffmpeg failed to run");
785- assert!(
786- y4m.status.success(),
787- "ffmpeg fixture: {}",
788- String::from_utf8_lossy(&y4m.stderr)
789- );
790- let depth_args: &[&str] = if bit_depth == 10 {
791- &["-b", "10", "--input-bit-depth=10"]
792- } else {
793- &[]
794- };
795- let out = run_with_stdin(
796- Command::new(aomenc_path()).args(depth_args).args([
797- // lane-defon r1: explicit on-value (aomenc keeps the FIRST
798- // occurrence, so overrides go before the base list).
799- "--enable-tx-size-search=1",
800- "--codec=av1",
801- "--passes=1",
802- "--end-usage=q",
803- "--cq-level=55",
804- "--cpu-used=0",
805- "--lag-in-frames=0",
806- "--auto-alt-ref=0",
807- "--kf-max-dist=1000",
808- "--threads=1",
809- "--row-mt=0",
810- "--enable-order-hint=0",
811- "--enable-warped-motion=0",
812- "--enable-obmc=0",
813- "--enable-masked-comp=0",
814- "--enable-interintra-comp=0",
815- "--enable-dist-wtd-comp=0",
816- "--enable-diff-wtd-comp=0",
817- "--enable-onesided-comp=0",
818- "--enable-interintra-wedge=0",
819- "--enable-smooth-interintra=0",
820- "--enable-rect-partitions=0",
821- "--enable-ab-partitions=0",
822- "--enable-1to4-partitions=0",
823- "--enable-filter-intra=0",
824- "--enable-smooth-intra=0",
825- "--enable-paeth-intra=0",
826- "--enable-directional-intra=0",
827- "--enable-angle-delta=0",
828- // DELIBERATELY ABSENT: --enable-tx-size-search=0.
829- "--enable-cdef=0",
830- "--enable-restoration=0",
831- "--max-partition-size=32",
832- // Sub-16 inter partitions are a separate named refusal
833- // (this decoder codes no inter block below 16x16 through
834- // the square path this gate drives), and detailed content
835- // makes aomenc's RD reach for them on nearly every seed.
836- "--min-partition-size=16",
837- "--enable-palette=0",
838- "--enable-intrabc=0",
839- "--enable-cfl-intra=0",
840- "--enable-ref-frame-mvs=0",
841- "--obu",
842- "-o",
843- "-",
844- "-",
845- ]),
846- &y4m.stdout,
847- );
848- assert!(
849- out.status.success(),
850- "aomenc refused the fixture: {}",
851- String::from_utf8_lossy(&out.stderr)
852- );
853- let stream = out.stdout;
854- let (reads_before, hits_before) =
855- (decode::txfm_split_reads(), decode::txfm_split_hits());
856- let frames = match decode_stream(&stream) {
857- Ok(frames) => frames,
858- Err(e) => {
859- let msg = e.to_string();
860- assert!(
861- msg.contains("unsupported"),
862- "tx-select inter decode failed outright (seed {seed}): {msg}"
863- );
864- refusals.push(format!("seed {seed}: {msg}"));
865- continue;
866- }
867- };
868- let (reads, hits) = (
869- decode::txfm_split_reads() - reads_before,
870- decode::txfm_split_hits() - hits_before,
871- );
872- // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
873- // is ALWAYS pixel-compared below; the hit counter only decides whether
874- // the attempt counts toward the firing total.
875- let counted = hits != 0;
876- if !counted {
877- uncounted_exact += 1;
878- refusals.push(format!(
879- "seed {seed}: decoded and pixel-compared, but no block took a txfm_split \
880- ({reads} symbols read)"
881- ));
882- }
883- let ffmpeg_frames = if bit_depth == 10 {
884- ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
885- } else {
886- ffmpeg_decode_sequence(&stream, width, height, frame_count)
887- };
888- assert_eq!(frames.len(), frame_count);
889- eprintln!(
890- "txselect gate {bit_depth}-bit seed={seed}: txfm_split reads={reads} splits taken={hits}"
891- );
892- // Name the first differing sample before the assert fires: a
893- // 64x64 plane's `assert_eq!` output is 4096 numbers, useless for
894- // locating a desync.
895- for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
896- for (plane, (g, w)) in [
897- ("Y", (&got.y, &want.y)),
898- ("U", (&got.u, &want.u)),
899- ("V", (&got.v, &want.v)),
900- ] {
901- let stride = if plane == "Y" { width } else { width / 2 };
902- if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) {
903- eprintln!(
904- "txselect gate seed={seed}: frame {i} {plane} first diff at \
905- ({}, {}) got {} want {} ({} samples differ)",
906- at % stride,
907- at / stride,
908- g[at],
909- w[at],
910- g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(),
911- );
912- let coords: Vec<String> = g
913- .iter()
914- .zip(w.iter())
915- .enumerate()
916- .filter(|(_, (a, b))| a != b)
917- .take(12)
918- .map(|(k, (a, b))| format!("({},{})={a}/{b}", k % stride, k / stride))
919- .collect();
920- eprintln!("txselect gate seed={seed}: frame {i} {plane} diffs {coords:?}");
921- }
922- }
923- }
924- for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
925- assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
926- assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
927- assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
928- }
929- if counted {
930- gate_buckets(
931- &format!("tx_select_inter_gate({bit_depth})"),
932- 1,
933- uncounted_exact,
934- refusals.len() - uncounted_exact as usize,
935- );
936- return;
937- }
938- }
939- gate_buckets(
940- &format!("tx_select_inter_gate({bit_depth})"),
941- 0,
942- uncounted_exact,
943- refusals.len() - uncounted_exact as usize,
944- );
945- panic!(
946- "tx_select_inter_gate({bit_depth}) never observed a taken txfm_split:\n{}",
947- refusals.join("\n")
948- );
949- }
950-
951- pub(super) fn intra_in_inter_split_tx_gate(bit_depth: u32) {
952- let name = format!("intra_in_inter_split_tx_gate({bit_depth})");
953- if !have_ffmpeg() {
954- eprintln!("SKIP {name}: no ffmpeg");
955- return;
956- }
957- if !have_aomenc() {
958- eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
959- return;
960- }
961- let (width, height, frame_count) = (64usize, 64usize, 8usize);
962- let mut refusals = Vec::new();
963- let mut uncounted_exact = 0u32;
964- for attempt in 0..40u32 {
965- let seed = 42 + attempt;
966- // A zooming fractal: every frame moves (so the sequence is
967- // genuinely inter-coded) and keeps sharp new detail entering at
968- // the borders, which is what makes aomenc's RD choose an INTRA
969- // block inside an inter frame -- and then split its transform.
970- // A zooming fractal with a hard CUT halfway (`overlay` switching
971- // a second, unrelated fractal on at frame 4): after the cut every
972- // block is unpredictable from the reference, which is what makes
973- // aomenc code INTRA blocks inside an inter frame -- and at this
974- // cq the RD then splits their transforms.
975- let source = format!(
976- "mandelbrot=size=64x64:start_scale={}:rate=25[a];\
977- mandelbrot=size=64x64:start_scale={}:rate=25[b];\
978- [a][b]overlay=enable='gte(n,4)'",
979- 5.0 - f64::from(attempt) * 0.06,
980- 0.9 + f64::from(attempt) * 0.11
981- );
982- let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
983- .args([
984- "-v",
985- "error",
986- "-f",
987- "lavfi",
988- "-i",
989- &source,
990- // Desaturated chroma keeps `uv_mode` on DC_PRED, so the
991- // still-refused directional-chroma gaps never fire and
992- // luma detail alone drives the transform split.
993- "-vf",
994- "hue=s=0",
995- "-pix_fmt",
996- if bit_depth == 10 {
997- "yuv420p10le"
998- } else {
999- "yuv420p"
1000- },
1001- "-strict",
1002- "-1",
1003- "-t",
1004- "0.32",
1005- "-f",
1006- "yuv4mpegpipe",
1007- "-strict",
1008- "-1",
1009- "-",
1010- ])
1011- .stdin(Stdio::null())
1012- .stdout(Stdio::piped())
1013- .stderr(Stdio::piped()), None, |c| c.output())
1014- .expect("ffmpeg failed to run");
1015- assert!(
1016- y4m.status.success(),
1017- "ffmpeg fixture: {}",
1018- String::from_utf8_lossy(&y4m.stderr)
1019- );
1020- let depth_args: &[&str] = if bit_depth == 10 {
1021- &["-b", "10", "--input-bit-depth=10"]
1022- } else {
1023- &[]
1024- };
1025- let out = run_with_stdin(
1026- Command::new(aomenc_path()).args(depth_args).args([
1027- "--codec=av1",
1028- "--passes=1",
1029- "--end-usage=q",
1030- "--cq-level=30",
1031- "--cpu-used=0",
1032- "--lag-in-frames=0",
1033- "--auto-alt-ref=0",
1034- // One key frame only: every later frame is an inter frame,
1035- // which is where this gate's intra blocks must sit. The
1036- // MIN distance is what stops aomenc's scene-cut detector
1037- // from inserting a second key frame at the cut this gate's
1038- // source deliberately contains.
1039- "--kf-max-dist=1000",
1040- "--kf-min-dist=1000",
1041- "--threads=1",
1042- "--row-mt=0",
1043- "--enable-order-hint=0",
1044- "--enable-warped-motion=0",
1045- "--enable-obmc=0",
1046- "--enable-masked-comp=0",
1047- "--enable-interintra-comp=0",
1048- "--enable-dist-wtd-comp=0",
1049- "--enable-diff-wtd-comp=0",
1050- "--enable-onesided-comp=0",
1051- "--enable-interintra-wedge=0",
1052- "--enable-smooth-interintra=0",
1053- "--enable-ab-partitions=0",
1054- "--enable-1to4-partitions=0",
1055- "--enable-filter-intra=0",
1056- "--enable-smooth-intra=0",
1057- "--enable-paeth-intra=0",
1058- "--enable-directional-intra=0",
1059- "--enable-angle-delta=0",
1060- "--enable-cdef=0",
1061- "--enable-restoration=0",
1062- "--enable-palette=0",
1063- "--enable-intrabc=0",
1064- "--enable-cfl-intra=0",
1065- "--enable-ref-frame-mvs=0",
1066- // Per-arm overrides go LAST (aomenc keeps the last
1067- // occurrence of a repeated --enable-* flag): the intra
1068- // tx_depth symbol only exists under TX_MODE_SELECT, and
1069- // rect partitions are a separate named refusal.
1070- "--enable-tx-size-search=1",
1071- "--enable-rect-partitions=0",
1072- "--max-partition-size=32",
1073- // Sub-16 inter partitions are a separate named refusal,
1074- // as is the 8x8 intra leaf's own TX_4X4 split.
1075- "--min-partition-size=16",
1076- "--obu",
1077- "-o",
1078- "-",
1079- "-",
1080- ]),
1081- &y4m.stdout,
1082- );
1083- assert!(
1084- out.status.success(),
1085- "aomenc refused the fixture: {}",
1086- String::from_utf8_lossy(&out.stderr)
1087- );
1088- let stream = out.stdout;
1089- let before = decode::intra_in_inter_split_tx_hits();
1090- let frames = match decode_stream(&stream) {
1091- Ok(frames) => frames,
1092- Err(e) => {
1093- let msg = e.to_string();
1094- assert!(
1095- msg.contains("unsupported"),
1096- "{name} decode failed outright (seed {seed}): {msg}"
1097- );
1098- refusals.push(format!("seed {seed}: {msg}"));
1099- continue;
1100- }
1101- };
1102- let after = decode::intra_in_inter_split_tx_hits();
1103- let mut per_size = [0usize; 4];
1104- for i in 0..4 {
1105- per_size[i] = after[i] - before[i];
1106- }
1107- // class [[gate-skips-on-its-own-failure]]: a decode that
1108- // succeeded is ALWAYS pixel-compared below; the counter only
1109- // decides whether the attempt counts as firing.
1110- let counted = per_size.iter().sum::<usize>() != 0;
1111- if !counted {
1112- uncounted_exact += 1;
1113- refusals.push(format!(
1114- "seed {seed}: decoded and pixel-compared, but no intra block in an inter \
1115- frame split its transform"
1116- ));
1117- }
1118- let ffmpeg_frames = if bit_depth == 10 {
1119- ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
1120- } else {
1121- ffmpeg_decode_sequence(&stream, width, height, frame_count)
1122- };
1123- assert_eq!(frames.len(), frame_count);
1124- eprintln!(
1125- "{name} seed={seed}: split intra-in-inter blocks 8x8={} 16x16={} 32x32={} \
1126- 64x64={}",
1127- per_size[0], per_size[1], per_size[2], per_size[3]
1128- );
1129- for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
1130- for (plane, (g, w)) in [
1131- ("Y", (&got.y, &want.y)),
1132- ("U", (&got.u, &want.u)),
1133- ("V", (&got.v, &want.v)),
1134- ] {
1135- let stride = if plane == "Y" { width } else { width / 2 };
1136- if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) {
1137- eprintln!(
1138- "{name} seed={seed}: frame {i} {plane} first diff at ({}, {}) got {} \
1139- want {} ({} samples differ)",
1140- at % stride,
1141- at / stride,
1142- g[at],
1143- w[at],
1144- g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(),
1145- );
1146- }
1147- }
1148- }
1149- for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
1150- assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
1151- assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
1152- assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
1153- }
1154- if counted {
1155- gate_buckets(
1156- &name,
1157- 1,
1158- uncounted_exact,
1159- refusals.len() - uncounted_exact as usize,
1160- );
1161- return;
1162- }
1163- }
1164- gate_buckets(
1165- &name,
1166- 0,
1167- uncounted_exact,
1168- refusals.len() - uncounted_exact as usize,
1169- );
1170- panic!(
1171- "{name} never observed a split-transform intra block in an inter frame:\n{}",
1172- refusals.join("\n")
1173- );
1174- }
1175-
1176- pub(super) fn filter_intra_in_inter_gate(bit_depth: u32) {
1177- let name = format!("filter_intra_in_inter_gate({bit_depth})");
1178- if !have_ffmpeg() {
1179- eprintln!("SKIP {name}: no ffmpeg");
1180- return;
1181- }
1182- if !have_aomenc() {
1183- eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
1184- return;
1185- }
1186- let (width, height, frame_count) = (64usize, 64usize, 8usize);
1187- let mut refusals = Vec::new();
1188- let mut uncounted_exact = 0u32;
1189- for attempt in 0..40u32 {
1190- let seed = 42 + attempt;
1191- // A zooming fractal: every frame moves (so the sequence is
1192- // genuinely inter-coded) and keeps sharp new detail entering at
1193- // the borders, which is what makes aomenc's RD choose an INTRA
1194- // block inside an inter frame -- and then split its transform.
1195- // A zooming fractal with a hard CUT halfway (`overlay` switching
1196- // a second, unrelated fractal on at frame 4): after the cut every
1197- // block is unpredictable from the reference, which is what makes
1198- // aomenc code INTRA blocks inside an inter frame -- and at this
1199- // cq the RD then splits their transforms.
1200- let source = format!(
1201- "mandelbrot=size=64x64:start_scale={}:rate=25[a];\
1202- mandelbrot=size=64x64:start_scale={}:rate=25[b];\
1203- [a][b]overlay=enable='gte(n,4)'",
1204- 5.0 - f64::from(attempt) * 0.06,
1205- 0.9 + f64::from(attempt) * 0.11
1206- );
1207- let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1208- .args([
1209- "-v",
1210- "error",
1211- "-f",
1212- "lavfi",
1213- "-i",
1214- &source,
1215- // Desaturated chroma keeps `uv_mode` on DC_PRED, so the
1216- // still-refused directional-chroma gaps never fire and
1217- // luma detail alone drives the transform split.
1218- "-vf",
1219- "hue=s=0",
1220- "-pix_fmt",
1221- if bit_depth == 10 {
1222- "yuv420p10le"
1223- } else {
1224- "yuv420p"
1225- },
1226- "-strict",
1227- "-1",
1228- "-t",
1229- "0.32",
1230- "-f",
1231- "yuv4mpegpipe",
1232- "-strict",
1233- "-1",
1234- "-",
1235- ])
1236- .stdin(Stdio::null())
1237- .stdout(Stdio::piped())
1238- .stderr(Stdio::piped()), None, |c| c.output())
1239- .expect("ffmpeg failed to run");
1240- assert!(
1241- y4m.status.success(),
1242- "ffmpeg fixture: {}",
1243- String::from_utf8_lossy(&y4m.stderr)
1244- );
1245- let depth_args: &[&str] = if bit_depth == 10 {
1246- &["-b", "10", "--input-bit-depth=10"]
1247- } else {
1248- &[]
1249- };
1250- let out = run_with_stdin(
1251- Command::new(aomenc_path()).args(depth_args).args([
1252- "--codec=av1",
1253- "--passes=1",
1254- "--end-usage=q",
1255- "--cq-level=30",
1256- "--cpu-used=0",
1257- "--lag-in-frames=0",
1258- "--auto-alt-ref=0",
1259- // One key frame only: every later frame is an inter frame,
1260- // which is where this gate's intra blocks must sit. The
1261- // MIN distance is what stops aomenc's scene-cut detector
1262- // from inserting a second key frame at the cut this gate's
1263- // source deliberately contains.
1264- "--kf-max-dist=1000",
1265- "--kf-min-dist=1000",
1266- "--threads=1",
1267- "--row-mt=0",
1268- "--enable-order-hint=0",
1269- "--enable-warped-motion=0",
1270- "--enable-obmc=0",
1271- "--enable-masked-comp=0",
1272- "--enable-interintra-comp=0",
1273- "--enable-dist-wtd-comp=0",
1274- "--enable-diff-wtd-comp=0",
1275- "--enable-onesided-comp=0",
1276- "--enable-interintra-wedge=0",
1277- "--enable-smooth-interintra=0",
1278- "--enable-ab-partitions=0",
1279- "--enable-1to4-partitions=0",
1280- "--enable-smooth-intra=0",
1281- "--enable-paeth-intra=0",
1282- "--enable-directional-intra=0",
1283- "--enable-angle-delta=0",
1284- "--enable-cdef=0",
1285- "--enable-restoration=0",
1286- "--enable-palette=0",
1287- "--enable-intrabc=0",
1288- "--enable-cfl-intra=0",
1289- "--enable-ref-frame-mvs=0",
1290- // Per-arm overrides go LAST (aomenc keeps the last
1291- // occurrence of a repeated --enable-* flag): the intra
1292- // tx_depth symbol only exists under TX_MODE_SELECT, and
1293- // rect partitions are a separate named refusal.
1294- "--enable-filter-intra=1",
1295- "--enable-tx-size-search=1",
1296- "--enable-rect-partitions=0",
1297- "--max-partition-size=32",
1298- // Sub-16 inter partitions are a separate named refusal,
1299- // as is the 8x8 intra leaf's own TX_4X4 split.
1300- "--min-partition-size=16",
1301- "--obu",
1302- "-o",
1303- "-",
1304- "-",
1305- ]),
1306- &y4m.stdout,
1307- );
1308- assert!(
1309- out.status.success(),
1310- "aomenc refused the fixture: {}",
1311- String::from_utf8_lossy(&out.stderr)
1312- );
1313- let stream = out.stdout;
1314- let before = decode::intra_in_inter_filter_intra_hits();
1315- let frames = match decode_stream(&stream) {
1316- Ok(frames) => frames,
1317- Err(e) => {
1318- let msg = e.to_string();
1319- assert!(
1320- msg.contains("unsupported"),
1321- "{name} decode failed outright (seed {seed}): {msg}"
1322- );
1323- refusals.push(format!("seed {seed}: {msg}"));
1324- continue;
1325- }
1326- };
1327- let fired = decode::intra_in_inter_filter_intra_hits() - before;
1328- // class [[gate-skips-on-its-own-failure]]: a decode that
1329- // succeeded is ALWAYS pixel-compared below; the counter only
1330- // decides whether the attempt counts as firing.
1331- let counted = fired != 0;
1332- if !counted {
1333- uncounted_exact += 1;
1334- refusals.push(format!(
1335- "seed {seed}: decoded and pixel-compared, but no intra block in an inter \
1336- frame used filter intra"
1337- ));
1338- }
1339- let ffmpeg_frames = if bit_depth == 10 {
1340- ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
1341- } else {
1342- ffmpeg_decode_sequence(&stream, width, height, frame_count)
1343- };
1344- assert_eq!(frames.len(), frame_count);
1345- eprintln!("{name} seed={seed}: filter-intra blocks inside inter frames = {fired}");
1346- for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
1347- for (plane, (g, w)) in [
1348- ("Y", (&got.y, &want.y)),
1349- ("U", (&got.u, &want.u)),
1350- ("V", (&got.v, &want.v)),
1351- ] {
1352- let stride = if plane == "Y" { width } else { width / 2 };
1353- if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) {
1354- eprintln!(
1355- "{name} seed={seed}: frame {i} {plane} first diff at ({}, {}) got {} \
1356- want {} ({} samples differ)",
1357- at % stride,
1358- at / stride,
1359- g[at],
1360- w[at],
1361- g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(),
1362- );
1363- }
1364- }
1365- }
1366- for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
1367- assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
1368- assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
1369- assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
1370- }
1371- if counted {
1372- gate_buckets(
1373- &name,
1374- 1,
1375- uncounted_exact,
1376- refusals.len() - uncounted_exact as usize,
1377- );
1378- return;
1379- }
1380- }
1381- gate_buckets(
1382- &name,
1383- 0,
1384- uncounted_exact,
1385- refusals.len() - uncounted_exact as usize,
1386- );
1387- panic!(
1388- "{name} never observed a filter-intra intra block in an inter frame:\n{}",
1389- refusals.join("\n")
1390- );
1391- }
1392-
1393- pub(super) fn angle_delta_in_inter_gate(bit_depth: u32, min_partition: &str) {
1394- let name = format!("angle_delta_in_inter_gate({bit_depth}, min={min_partition})");
1395- let leaf8 = min_partition.ends_with('8');
1396- assert!(
1397- !leaf8,
1398- "the 8x8-leaf arm keeps its refusal; see the module note"
1399- );
1400- if !have_ffmpeg() {
1401- eprintln!("SKIP {name}: no ffmpeg");
1402- return;
1403- }
1404- if !have_aomenc() {
1405- eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
1406- return;
1407- }
1408- let (width, height, frame_count) = (64usize, 64usize, 8usize);
1409- let mut refusals = Vec::new();
1410- let mut uncounted_exact = 0u32;
1411- for attempt in 0..40u32 {
1412- let seed = 42 + attempt;
1413- // A zooming fractal: every frame moves (so the sequence is
1414- // genuinely inter-coded) and keeps sharp new detail entering at
1415- // the borders, which is what makes aomenc's RD choose an INTRA
1416- // block inside an inter frame -- and then split its transform.
1417- // A zooming fractal with a hard CUT halfway (`overlay` switching
1418- // a second, unrelated fractal on at frame 4): after the cut every
1419- // block is unpredictable from the reference, which is what makes
1420- // aomenc code INTRA blocks inside an inter frame -- and at this
1421- // cq the RD then splits their transforms.
1422- let source = format!(
1423- "mandelbrot=size={width}x{height}:start_scale={}:rate=25[a];\
1424- mandelbrot=size={width}x{height}:start_scale={}:rate=25[b];\
1425- [a][b]overlay=enable='gte(n,4)'",
1426- 5.0 - f64::from(attempt) * 0.06,
1427- 0.9 + f64::from(attempt) * 0.11
1428- );
1429- let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1430- .args([
1431- "-v",
1432- "error",
1433- "-f",
1434- "lavfi",
1435- "-i",
1436- &source,
1437- // Desaturated chroma keeps `uv_mode` on DC_PRED, so the
1438- // still-refused directional-chroma gaps never fire and
1439- // luma detail alone drives the transform split.
1440- "-vf",
1441- "hue=s=0",
1442- "-pix_fmt",
1443- if bit_depth == 10 {
1444- "yuv420p10le"
1445- } else {
1446- "yuv420p"
1447- },
1448- "-strict",
1449- "-1",
1450- "-t",
1451- "0.32",
1452- "-f",
1453- "yuv4mpegpipe",
1454- "-strict",
1455- "-1",
1456- "-",
1457- ])
1458- .stdin(Stdio::null())
1459- .stdout(Stdio::piped())
1460- .stderr(Stdio::piped()), None, |c| c.output())
1461- .expect("ffmpeg failed to run");
1462- assert!(
1463- y4m.status.success(),
1464- "ffmpeg fixture: {}",
1465- String::from_utf8_lossy(&y4m.stderr)
1466- );
1467- // The 8x8-leaf arm is fenced by three sibling refusals (non-DC
1468- // chroma on an 8x8 leaf, its TX_4X4 split, sub-16 rect inter
1469- // leaves), so it sweeps the quantiser as well as the source: a
1470- // coarser q is what pushes the RD to directional intra at 8x8.
1471- let cq = if leaf8 {
1472- format!("--cq-level={}", 20 + (attempt % 5) * 10)
1473- } else {
1474- "--cq-level=30".to_string()
1475- };
1476- let depth_args: &[&str] = if bit_depth == 10 {
1477- &["-b", "10", "--input-bit-depth=10"]
1478- } else {
1479- &[]
1480- };
1481- let out = run_with_stdin(
1482- Command::new(aomenc_path()).args(depth_args).args([
1483- "--codec=av1",
1484- "--passes=1",
1485- "--end-usage=q",
1486- &cq,
1487- "--cpu-used=0",
1488- "--lag-in-frames=0",
1489- "--auto-alt-ref=0",
1490- // One key frame only: every later frame is an inter frame,
1491- // which is where this gate's intra blocks must sit. The
1492- // MIN distance is what stops aomenc's scene-cut detector
1493- // from inserting a second key frame at the cut this gate's
1494- // source deliberately contains.
1495- "--kf-max-dist=1000",
1496- "--kf-min-dist=1000",
1497- "--threads=1",
1498- "--row-mt=0",
1499- "--enable-order-hint=0",
1500- "--enable-warped-motion=0",
1501- "--enable-obmc=0",
1502- "--enable-masked-comp=0",
1503- "--enable-interintra-comp=0",
1504- "--enable-dist-wtd-comp=0",
1505- "--enable-diff-wtd-comp=0",
1506- "--enable-onesided-comp=0",
1507- "--enable-interintra-wedge=0",
1508- "--enable-smooth-interintra=0",
1509- "--enable-ab-partitions=0",
1510- "--enable-1to4-partitions=0",
1511- "--enable-smooth-intra=0",
1512- "--enable-paeth-intra=0",
1513- "--enable-directional-intra=1",
1514- "--enable-angle-delta=1",
1515- "--enable-cdef=0",
1516- "--enable-restoration=0",
1517- "--enable-palette=0",
1518- "--enable-intrabc=0",
1519- "--enable-cfl-intra=0",
1520- "--enable-ref-frame-mvs=0",
1521- // Per-arm overrides go LAST (aomenc keeps the last
1522- // occurrence of a repeated --enable-* flag): the intra
1523- // tx_depth symbol only exists under TX_MODE_SELECT, and
1524- // rect partitions are a separate named refusal.
1525- "--enable-filter-intra=1",
1526- "--enable-tx-size-search=1",
1527- "--enable-rect-partitions=0",
1528- "--max-partition-size=32",
1529- // Sub-16 inter partitions are a separate named refusal,
1530- // as is the 8x8 intra leaf's own TX_4X4 split.
1531- min_partition,
1532- "--obu",
1533- "-o",
1534- "-",
1535- "-",
1536- ]),
1537- &y4m.stdout,
1538- );
1539- assert!(
1540- out.status.success(),
1541- "aomenc refused the fixture: {}",
1542- String::from_utf8_lossy(&out.stderr)
1543- );
1544- let stream = out.stdout;
1545- let before = decode::intra_in_inter_angle_delta_y_hits();
1546- let before_uv = decode::intra_in_inter_angle_delta_uv_hits();
1547- let frames = match decode_stream(&stream) {
1548- Ok(frames) => frames,
1549- Err(e) => {
1550- let msg = e.to_string();
1551- assert!(
1552- msg.contains("unsupported"),
1553- "{name} decode failed outright (seed {seed}): {msg}"
1554- );
1555- refusals.push(format!("seed {seed}: {msg}"));
1556- continue;
1557- }
1558- };
1559- let fired = decode::intra_in_inter_angle_delta_y_hits() - before;
1560- let fired_uv = decode::intra_in_inter_angle_delta_uv_hits() - before_uv;
1561- // class [[gate-skips-on-its-own-failure]]: a decode that
1562- // succeeded is ALWAYS pixel-compared below; the counter only
1563- // decides whether the attempt counts as firing.
1564- let counted = fired != 0;
1565- if !counted {
1566- uncounted_exact += 1;
1567- refusals.push(format!(
1568- "seed {seed}: decoded and pixel-compared, but no intra block in an inter \
1569- frame carried a nonzero angle_delta_y"
1570- ));
1571- }
1572- let ffmpeg_frames = if bit_depth == 10 {
1573- ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
1574- } else {
1575- ffmpeg_decode_sequence(&stream, width, height, frame_count)
1576- };
1577- assert_eq!(frames.len(), frame_count);
1578- eprintln!(
1579- "{name} seed={seed}: intra-in-inter blocks with a nonzero angle_delta_y = \
1580- {fired}, angle_delta_uv = {fired_uv}"
1581- );
1582- for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
1583- for (plane, (g, w)) in [
1584- ("Y", (&got.y, &want.y)),
1585- ("U", (&got.u, &want.u)),
1586- ("V", (&got.v, &want.v)),
1587- ] {
1588- let stride = if plane == "Y" { width } else { width / 2 };
1589- if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) {
1590- eprintln!(
1591- "{name} seed={seed}: frame {i} {plane} first diff at ({}, {}) got {} \
1592- want {} ({} samples differ)",
1593- at % stride,
1594- at / stride,
1595- g[at],
1596- w[at],
1597- g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(),
1598- );
1599- }
1600- }
1601- }
1602- for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
1603- assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
1604- assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
1605- assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
1606- }
1607- if counted {
1608- gate_buckets(
1609- &name,
1610- 1,
1611- uncounted_exact,
1612- refusals.len() - uncounted_exact as usize,
1613- );
1614- return;
1615- }
1616- }
1617- gate_buckets(
1618- &name,
1619- 0,
1620- uncounted_exact,
1621- refusals.len() - uncounted_exact as usize,
1622- );
1623- panic!(
1624- "{name} never observed a nonzero angle delta on an intra block in an inter \
1625- frame:\n{}",
1626- refusals.join("\n")
1627- );
1628- }
1629-
1630- pub(super) fn uv_mode_in_inter8_gate(bit_depth: u32, tile_columns: u32) {
1631- let name = format!("uv_mode_in_inter8_gate({bit_depth}, tiles={tile_columns})");
1632- if !have_ffmpeg() {
1633- eprintln!("SKIP {name}: no ffmpeg");
1634- return;
1635- }
1636- if !have_aomenc() {
1637- eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
1638- return;
1639- }
1640- let (width, height, frame_count) = (192usize, 128usize, 8usize);
1641- let mut refusals = Vec::new();
1642- let mut uncounted_exact = 0u32;
1643- let mut totals = (0usize, 0usize, 0usize);
1644- for attempt in 0..30u32 {
1645- let seed = 42 + attempt;
1646- // A zooming fractal with a hard CUT at frame 4 (`overlay`
1647- // switching a second, unrelated fractal on): after the cut a block
1648- // is unpredictable from the reference, which is what makes aomenc
1649- // code INTRA blocks inside an inter frame. Chroma is NOT
1650- // desaturated here (every sibling inter gate passes `hue=s=0`) --
1651- // real chroma detail is exactly what pushes the chroma RD off
1652- // DC_PRED. `noise` carries its own explicit seed (lavfi
1653- // `gradients` ignores its seed; class [[seeded-fixture-not-reproducible]]).
1654- let source = format!(
1655- "mandelbrot=size={width}x{height}:start_scale={}:rate=25[a];\
1656- mandelbrot=size={width}x{height}:start_scale={}:rate=25[b];\
1657- [a][b]overlay=enable='gte(n,4)',noise=alls=12:allf=t+u:all_seed={seed}",
1658- 5.0 - f64::from(attempt) * 0.06,
1659- 0.9 + f64::from(attempt) * 0.11
1660- );
1661- let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1662- .args([
1663- "-v",
1664- "error",
1665- "-f",
1666- "lavfi",
1667- "-i",
1668- &source,
1669- "-pix_fmt",
1670- if bit_depth == 10 {
1671- "yuv420p10le"
1672- } else {
1673- "yuv420p"
1674- },
1675- "-strict",
1676- "-1",
1677- "-t",
1678- "0.32",
1679- "-f",
1680- "yuv4mpegpipe",
1681- "-strict",
1682- "-1",
1683- "-",
1684- ])
1685- .stdin(Stdio::null())
1686- .stdout(Stdio::piped())
1687- .stderr(Stdio::piped()), None, |c| c.output())
1688- .expect("ffmpeg failed to run");
1689- assert!(
1690- y4m.status.success(),
1691- "ffmpeg fixture: {}",
1692- String::from_utf8_lossy(&y4m.stderr)
1693- );
1694- // A coarser quantiser is what pushes the chroma RD to a cheap
1695- // non-DC mode on a small block; sweep 12..40 (the low end is what
1696- // lane-cdef's cq12 arm needs).
1697- let cq = format!("--cq-level={}", 12 + (attempt % 5) * 7);
1698- let depth_args: &[&str] = if bit_depth == 10 {
1699- &["-b", "10", "--input-bit-depth=10"]
1700- } else {
1701- &[]
1702- };
1703- let tiles = format!("--tile-columns={}", tile_columns - 1);
1704- // The y4m goes through a FILE, not aomenc's stdin: this gate's
1705- // stream is ~100 KB, bigger than a pipe buffer, so an aomenc that
1706- // is still being fed on stdin blocks writing its stdout and the
1707- // test blocks writing its stdin -- a hard deadlock (measured
1708- // here, 3 min into attempt 0, class [[gate-loader-slurps-whole-file]]).
1709- // The path is PID-keyed (class [[pid-keyed-temp-path]]).
1710- let y4m_path = std::env::temp_dir().join(format!(
1711- "ec-av1-uv8-{}-{bit_depth}-{tile_columns}-{seed}.y4m",
1712- std::process::id()
1713- ));
1714- std::fs::write(&y4m_path, &y4m.stdout).expect("writing the y4m fixture");
1715- let child = Command::new(aomenc_path())
1716- .args(depth_args)
1717- .args([
1718- "--codec=av1",
1719- "--passes=1",
1720- "--end-usage=q",
1721- &cq,
1722- "--cpu-used=0",
1723- "--lag-in-frames=0",
1724- "--auto-alt-ref=0",
1725- "--kf-max-dist=9999",
1726- "--kf-min-dist=9999",
1727- "--threads=1",
1728- "--row-mt=0",
1729- &tiles,
1730- "--enable-order-hint=0",
1731- "--enable-warped-motion=0",
1732- "--enable-obmc=0",
1733- "--enable-masked-comp=0",
1734- "--enable-interintra-comp=0",
1735- "--enable-dist-wtd-comp=0",
1736- "--enable-diff-wtd-comp=0",
1737- "--enable-onesided-comp=0",
1738- "--enable-interintra-wedge=0",
1739- "--enable-smooth-interintra=0",
1740- "--enable-ab-partitions=0",
1741- "--enable-1to4-partitions=0",
1742- "--enable-cdef=0",
1743- "--enable-restoration=0",
1744- "--enable-palette=0",
1745- "--enable-intrabc=0",
1746- "--enable-ref-frame-mvs=0",
1747- // Per-arm overrides go LAST (aomenc keeps the LAST
1748- // occurrence of a repeated --enable-* flag). The three
1749- // chroma intra tools this gate is about, plus the fences
1750- // that keep the leaf's SIBLING refusals (its TX_4X4
1751- // split, a nonzero angle delta, sub-16 rect inter leaves)
1752- // out of the way.
1753- "--enable-cfl-intra=1",
1754- "--enable-smooth-intra=1",
1755- "--enable-paeth-intra=1",
1756- "--enable-directional-intra=1",
1757- "--enable-angle-delta=0",
1758- "--enable-tx-size-search=0",
1759- "--enable-rect-partitions=0",
1760- "--min-partition-size=8",
1761- "--max-partition-size=32",
1762- "--obu",
1763- "-o",
1764- "-",
1765- ])
1766- .arg(&y4m_path)
1767- .stdin(Stdio::null())
1768- .stdout(Stdio::piped())
1769- .stderr(Stdio::piped())
1770- .spawn()
1771- .expect("aomenc failed to start");
1772- let out = child.wait_with_output().expect("aomenc failed to run");
1773- let _ = std::fs::remove_file(&y4m_path);
1774- assert!(
1775- out.status.success(),
1776- "aomenc refused the fixture: {}",
1777- String::from_utf8_lossy(&out.stderr)
1778- );
1779- let stream = out.stdout;
1780- let before = decode::intra_in_inter8_uv_hits();
1781- let frames = match decode_stream(&stream) {
1782- Ok(frames) => frames,
1783- Err(e) => {
1784- let msg = e.to_string();
1785- assert!(
1786- msg.contains("unsupported"),
1787- "{name} decode failed outright (seed {seed}): {msg}"
1788- );
1789- refusals.push(format!("seed {seed}: {msg}"));
1790- continue;
1791- }
1792- };
1793- let now = decode::intra_in_inter8_uv_hits();
1794- // class [[counter-from-refused-stream]]: per-attempt deltas, and
1795- // only for an attempt that decoded to the end and is pixel-
1796- // compared below.
1797- let fired = (now.0 - before.0, now.1 - before.1, now.2 - before.2);
1798- totals = (totals.0 + fired.0, totals.1 + fired.1, totals.2 + fired.2);
1799- // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
1800- // is ALWAYS pixel-compared; the counter only decides whether the
1801- // attempt counts as firing.
1802- // lane-uv8 r3: every one of the three chroma classes this gate
1803- // exists for (directional, smooth/paeth, CfL) must fire on the
1804- // SAME pixel-compared attempt -- a sum-nonzero predicate would
1805- // pass on an attempt that only ever hit DC-adjacent CfL.
1806- let counted = fired.0 > 0 && fired.1 > 0 && fired.2 > 0;
1807- if !counted {
1808- uncounted_exact += 1;
1809- refusals.push(format!(
1810- "seed {seed}: decoded and pixel-compared, but no 8x8 intra leaf in an inter \
1811- frame carried a non-DC uv_mode"
1812- ));
1813- }
1814- let ffmpeg_frames = if bit_depth == 10 {
1815- ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
1816- } else {
1817- ffmpeg_decode_sequence(&stream, width, height, frame_count)
1818- };
1819- assert_eq!(frames.len(), frame_count);
1820- eprintln!(
1821- "{name} seed={seed} {cq}: 8x8 intra-in-inter leaves with a non-DC uv_mode -- \
1822- directional {}, smooth/paeth {}, CfL {}",
1823- fired.0, fired.1, fired.2
1824- );
1825- for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
1826- for (plane, (g, w)) in [
1827- ("Y", (&got.y, &want.y)),
1828- ("U", (&got.u, &want.u)),
1829- ("V", (&got.v, &want.v)),
1830- ] {
1831- let stride = if plane == "Y" { width } else { width / 2 };
1832- if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) {
1833- eprintln!(
1834- "{name} seed={seed}: frame {i} {plane} first diff at ({}, {}) got {} \
1835- want {} ({} samples differ)",
1836- at % stride,
1837- at / stride,
1838- g[at],
1839- w[at],
1840- g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(),
1841- );
1842- }
1843- }
1844- }
1845- for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
1846- assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
1847- assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
1848- assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
1849- }
1850- if counted {
1851- gate_buckets(
1852- &name,
1853- 1,
1854- uncounted_exact,
1855- refusals.len() - uncounted_exact as usize,
1856- );
1857- return;
1858- }
1859- }
1860- gate_buckets(
1861- &name,
1862- 0,
1863- uncounted_exact,
1864- refusals.len() - uncounted_exact as usize,
1865- );
1866- panic!(
1867- "{name} never observed a non-DC uv_mode on an 8x8 intra leaf in an inter frame \
1868- (totals dir/smooth/cfl {totals:?}):\n{}",
1869- refusals.join("\n")
1870- );
1871- }
1872-
1873- pub(super) fn tx_split_angle_in_inter8_gate(bit_depth: u32) {
1874- let name = format!("tx_split_angle_in_inter8_gate({bit_depth})");
1875- if !have_ffmpeg() {
1876- eprintln!("SKIP {name}: no ffmpeg");
1877- return;
1878- }
1879- if !have_aomenc() {
1880- eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
1881- return;
1882- }
1883- let (width, height, frame_count) = (192usize, 128usize, 6usize);
1884- let mut refusals = Vec::new();
1885- let mut uncounted_exact = 0u32;
1886- let mut counted_exact = 0u32;
1887- let mut totals = (0usize, 0usize);
1888- for attempt in 0..30u32 {
1889- let seed = 42 + attempt;
1890- // Same zoom + hard-cut fractal source the sibling uv_mode gate
1891- // uses (a cut is what makes aomenc code INTRA blocks inside an
1892- // inter frame); `noise` carries an explicit seed (class
1893- // [[seeded-fixture-not-reproducible]]).
1894- let source = format!(
1895- "mandelbrot=size={width}x{height}:start_scale={}:rate=25[a];\
1896- mandelbrot=size={width}x{height}:start_scale={}:rate=25[b];\
1897- [a][b]overlay=enable='gte(n,3)',noise=alls=12:allf=t+u:all_seed={seed}",
1898- 5.0 - f64::from(attempt) * 0.06,
1899- 0.9 + f64::from(attempt) * 0.11
1900- );
1901- let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1902- .args([
1903- "-v",
1904- "error",
1905- "-f",
1906- "lavfi",
1907- "-i",
1908- &source,
1909- "-pix_fmt",
1910- if bit_depth == 10 {
1911- "yuv420p10le"
1912- } else {
1913- "yuv420p"
1914- },
1915- "-strict",
1916- "-1",
1917- "-t",
1918- "0.24",
1919- "-f",
1920- "yuv4mpegpipe",
1921- "-strict",
1922- "-1",
1923- "-",
1924- ])
1925- .stdin(Stdio::null())
1926- .stdout(Stdio::piped())
1927- .stderr(Stdio::piped()), None, |c| c.output())
1928- .expect("ffmpeg failed to run");
1929- assert!(
1930- y4m.status.success(),
1931- "ffmpeg fixture: {}",
1932- String::from_utf8_lossy(&y4m.stderr)
1933- );
1934- let cq = format!("--cq-level={}", 12 + (attempt % 5) * 7);
1935- let depth_args: &[&str] = if bit_depth == 10 {
1936- &["-b", "10", "--input-bit-depth=10"]
1937- } else {
1938- &[]
1939- };
1940- // The y4m goes through a PID-keyed FILE, never aomenc's stdin
1941- // (pipe deadlock, class [[gate-loader-slurps-whole-file]]).
1942- let y4m_path = std::env::temp_dir().join(format!(
1943- "ec-av1-leaf8tx-{}-{bit_depth}-{seed}.y4m",
1944- std::process::id()
1945- ));
1946- std::fs::write(&y4m_path, &y4m.stdout).expect("writing the y4m fixture");
1947- let child = Command::new(aomenc_path())
1948- .args(depth_args)
1949- .args([
1950- "--codec=av1",
1951- "--passes=1",
1952- "--end-usage=q",
1953- &cq,
1954- "--cpu-used=0",
1955- "--lag-in-frames=0",
1956- "--auto-alt-ref=0",
1957- "--kf-max-dist=9999",
1958- "--kf-min-dist=9999",
1959- "--threads=1",
1960- "--row-mt=0",
1961- "--tile-columns=0",
1962- "--enable-order-hint=0",
1963- "--enable-warped-motion=0",
1964- "--enable-obmc=0",
1965- "--enable-masked-comp=0",
1966- "--enable-interintra-comp=0",
1967- "--enable-dist-wtd-comp=0",
1968- "--enable-diff-wtd-comp=0",
1969- "--enable-onesided-comp=0",
1970- "--enable-interintra-wedge=0",
1971- "--enable-smooth-interintra=0",
1972- "--enable-ab-partitions=0",
1973- "--enable-1to4-partitions=0",
1974- "--enable-cdef=0",
1975- "--enable-restoration=0",
1976- "--enable-palette=0",
1977- "--enable-intrabc=0",
1978- "--enable-ref-frame-mvs=0",
1979- // Per-arm overrides LAST (aomenc keeps the last
1980- // occurrence of a repeated --enable-* flag). Rect
1981- // partitions stay off so the leaf's unrelated sub-16 rect
1982- // inter refusal never fires.
1983- "--enable-rect-partitions=0",
1984- "--enable-tx-size-search=1",
1985- "--enable-angle-delta=1",
1986- "--enable-directional-intra=1",
1987- "--min-partition-size=8",
1988- "--max-partition-size=32",
1989- "--obu",
1990- "-o",
1991- "-",
1992- ])
1993- // r1 diagnostic: EC_LEAF8TX_CONTROL=1 turns THIS lane's two
1994- // tools back off (last occurrence of a repeated --enable-*
1995- // wins), so any mismatch that survives is not this lane's.
1996- .args(match std::env::var("EC_LEAF8TX_CONTROL").as_deref() {
1997- Ok("angle") => vec!["--enable-tx-size-search=0", "--enable-angle-delta=1"],
1998- Ok("tx") => vec!["--enable-tx-size-search=1", "--enable-angle-delta=0"],
1999- Ok("tx8") => vec![
2000- "--enable-tx-size-search=1",
crates/ec-av1/src/stream/tests/gates_b.rsdeleted+0 -2804

Diff too large; view file

@@ -1,2804 +0,0 @@
1-use super::*;
2-use super::support::*;
3-use super::gates_a::*;
4-
5- /// lane-cwarp r1: a real `--enable-global-motion=1 --enable-dist-wtd-comp=1`
6- /// stream over a rotating/zooming source, so a `GLOBAL_GLOBALMV` compound
7- /// block lands under a ROTZOOM/AFFINE model and each of its two references
8- /// is predicted through its OWN global warp
9- /// (`crate::warp::warp_affine_compound`, libaom `av1_warp_plane` with
10- /// `conv_params->is_compound`) rather than translationally. Before r1 that
11- /// path was SILENTLY WRONG -- no refusal named it, both taps went through
12- /// `mc::predict_compound_intermediate`. `compound_warp_hits() > 0` is a
13- /// hard assert: a run where the encoder never emitted one proves nothing.
14- /// A decode error or a pixel mismatch is a FAILURE, never a skip.
15- pub(super) fn run_compound_global_warp_gate(name: &str, bd: u32, min_part: u32, leaf8_assert: bool) {
16- let _gate_lock = lock_gate_counters();
17- assert!(have_ffmpeg(), "{name}: ffmpeg required");
18- assert!(
19- have_aomenc(),
20- "{name}: no aomenc at {}",
21- aomenc_path().display()
22- );
23- let (width, height, frame_count) = (64usize, 64usize, 24usize);
24- let before = crate::decode::compound_warp_hits();
25- let before8 = crate::decode::compound_warp_hits_8();
26- let mut matched = 0u32;
27- let mut named_refusals = 0u32;
28- let mut attempts = 0u32;
29- for cq in [32u32, 45, 55] {
30- for (i, rate) in [0.010f64, 0.022].iter().enumerate() {
31- attempts += 1;
32- let duration = frame_count as f64 / 25.0;
33- // A rotation about the frame centre plus a slow zoom is what
34- // aomenc's global-motion search fits a ROTZOOM/AFFINE model to;
35- // mandelbrot gives it real, non-flat texture to track.
36- let source = format!(
37- "mandelbrot=size={w}x{h}:rate=25:start_x={sx}:start_y=-0.4,\
38- rotate=a={rate}*n:ow={w}:oh={h}:c=black,scale={width}:{height}",
39- w = width * 2,
40- h = height * 2,
41- sx = -0.6 + 0.01 * (i as f64),
42- );
43- let pix_fmt = match bd {
44- 8 => "yuv420p",
45- 10 => "yuv420p10le",
46- _ => "yuv420p12le",
47- };
48- let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
49- .args([
50- "-v",
51- "error",
52- "-f",
53- "lavfi",
54- "-i",
55- &source,
56- "-t",
57- &duration.to_string(),
58- "-pix_fmt",
59- pix_fmt,
60- "-strict",
61- "-1",
62- "-f",
63- "yuv4mpegpipe",
64- "-",
65- ])
66- .stdin(Stdio::null())
67- .stdout(Stdio::piped())
68- .stderr(Stdio::piped()), None, |c| c.output())
69- .expect("ffmpeg failed to run");
70- assert!(
71- y4m.status.success(),
72- "ffmpeg fixture: {}",
73- String::from_utf8_lossy(&y4m.stderr)
74- );
75- let cq_arg = format!("--cq-level={cq}");
76- let (in_depth_arg, depth_arg) = (
77- format!("--input-bit-depth={bd}"),
78- format!("--bit-depth={bd}"),
79- );
80- let mut args: Vec<&str> = vec![
81- "--codec=av1",
82- "--passes=1",
83- "--end-usage=q",
84- &cq_arg,
85- "--cpu-used=0",
86- "--kf-max-dist=1000",
87- "--threads=1",
88- "--row-mt=0",
89- "--auto-alt-ref=1",
90- "--lag-in-frames=25",
91- "--enable-fwd-kf=0",
92- "--enable-order-hint=1",
93- // the two tools this gate exists for
94- "--enable-global-motion=1",
95- "--enable-dist-wtd-comp=1",
96- "--enable-warped-motion=1",
97- "--enable-obmc=1",
98- "--enable-masked-comp=1",
99- "--enable-onesided-comp=0",
100- "--enable-interintra-comp=1",
101- "--enable-interintra-wedge=0",
102- "--enable-smooth-interintra=1",
103- "--tune-content=default",
104- // partition/intra tools this decoder does not code yet --
105- // same exclusion list every compound gate carries.
106- "--enable-rect-partitions=0",
107- "--enable-ab-partitions=0",
108- "--enable-1to4-partitions=0",
109- "--enable-filter-intra=0",
110- "--enable-smooth-intra=0",
111- "--enable-paeth-intra=0",
112- "--enable-directional-intra=0",
113- "--enable-angle-delta=0",
114- "--enable-tx-size-search=0",
115- "--enable-cdef=0",
116- "--enable-restoration=0",
117- "--max-partition-size=32",
118- "--enable-palette=0",
119- "--enable-intrabc=0",
120- "--enable-cfl-intra=0",
121- "--enable-ref-frame-mvs=0",
122- ];
123- let min_part_arg = format!("--min-partition-size={min_part}");
124- args.push(min_part_arg.as_str());
125- if bd != 8 {
126- args.extend_from_slice(&[in_depth_arg.as_str(), depth_arg.as_str()]);
127- }
128- args.extend_from_slice(&["--obu", "-o", "-", "-"]);
129- let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
130- assert!(
131- out.status.success(),
132- "aomenc refused the fixture: {}",
133- String::from_utf8_lossy(&out.stderr)
134- );
135- let stream = out.stdout;
136- let frames = match decode_stream(&stream) {
137- Err(e) => {
138- let msg = e.to_string();
139- assert!(
140- msg.contains("unsupported"),
141- "{name} failed outright, not a named refusal (cq {cq}): {msg}"
142- );
143- assert!(
144- !msg.contains("warp"),
145- "{name} refused on warp (cq {cq}) -- warp decode is ported: {msg}"
146- );
147- named_refusals += 1;
148- eprintln!("{name} cq {cq} rate {rate} refusal: {msg}");
149- continue;
150- }
151- Ok(frames) => frames,
152- };
153- let want = match bd {
154- 8 => ffmpeg_decode_sequence(&stream, width, height, frame_count),
155- 10 => ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count),
156- _ => ffmpeg_decode_sequence_12bit(&stream, width, height, frame_count),
157- };
158- assert_eq!(frames.len(), frame_count);
159- if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP")
160- && frames
161- .iter()
162- .zip(&want)
163- .any(|(g, w)| g.y != w.y || g.u != w.u || g.v != w.v)
164- {
165- std::fs::write(&path, &stream).expect("writing pinned stream");
166- eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (cq {cq}) to {path}");
167- }
168- for (i, (got, want)) in frames.iter().zip(&want).enumerate() {
169- assert_eq!(got.y, want.y, "{name} frame {i} luma vs ffmpeg (cq {cq})");
170- assert_eq!(got.u, want.u, "{name} frame {i} U vs ffmpeg (cq {cq})");
171- assert_eq!(got.v, want.v, "{name} frame {i} V vs ffmpeg (cq {cq})");
172- }
173- matched += 1;
174- }
175- }
176- let hits = crate::decode::compound_warp_hits() - before;
177- let hits8 = crate::decode::compound_warp_hits_8() - before8;
178- eprintln!(
179- "{name}: {matched}/{attempts} pixel-exact, {named_refusals} named refusals, \
180- compound_warp_hits={hits} compound_warp_hits_8={hits8}"
181- );
182- if leaf8_assert {
183- assert!(
184- hits8 > 0,
185- "{name}: no 8x8 COMPOUND leaf was predicted through a per-ref global \
186- warp ({hits} bigger compound warp blocks, {matched} matches, \
187- {named_refusals} refusals of {attempts}) -- gate vacuous"
188- );
189- } else {
190- assert!(
191- hits > 0,
192- "{name}: no compound block was predicted through a per-ref global warp \
193- ({matched} matches, {named_refusals} refusals of {attempts}) -- gate vacuous"
194- );
195- }
196- assert!(
197- matched > 0,
198- "{name}: every attempt refused -- no pixel comparison ran"
199- );
200- }
201-
202- /// lane-fimv r1 (class `wrong-alphabet-same-value`): libaom
203- /// `motion_mode_allowed` (blockd.h ~1484) only returns `WARPED_CAUSAL`
204- /// when `!xd->cur_frame_force_integer_mv`, so on a frame whose header set
205- /// `force_integer_mv` an otherwise warp-eligible block reads the 2-symbol
206- /// `obmc_cdf`, not the 3-symbol `motion_mode_cdf`. This decoder read the
207- /// 3-symbol alphabet there (silent tile desync, no refusal named it).
208- ///
209- /// The fixture is screen content that is mostly static with only
210- /// whole-pixel motion, which is exactly what aomenc's own
211- /// `av1_is_integer_mv` (`encoder_utils.c:1357`, >=80% of blocks matching
212- /// their collocated block) needs to set `cur_frame_force_integer_mv`
213- /// under `--tune-content=screen` (seq `force_integer_mv == 2`, adaptive:
214- /// `encoder.c:4171`). Two hard asserts, both class
215- /// `gate-blind-to-feature`: at least one decoded frame header carried
216- /// `force_integer_mv = 1`, and at least one block took the 2-symbol
217- /// alphabet where `allow_warped_motion = 1` and `num_proj_ref >= 1` would
218- /// have picked the 3-symbol one. A decode error or a pixel mismatch is a
219- /// FAILURE, never a skip.
220- #[track_caller]
221- pub(super) fn run_fimv_motion_mode_gate(name: &str, ten_bit: bool) {
222- let _gate_lock = lock_gate_counters();
223- assert!(have_ffmpeg(), "{name}: ffmpeg required");
224- assert!(
225- have_aomenc(),
226- "{name}: no aomenc at {}",
227- aomenc_path().display()
228- );
229- let (width, height, frame_count) = (64usize, 64usize, 20usize);
230- let fimv_frames_before = crate::decode::fimv_frame_hits();
231- let alphabet_before = crate::decode::fimv_alphabet_hits();
232- let mut matched = 0u32;
233- let mut named_refusals = 0u32;
234- let mut attempts = 0u32;
235- let mut refusals = Vec::new();
236- for cq in [32u32, 45, 55] {
237- for step in [4u32, 8] {
238- attempts += 1;
239- // lane-fimv r1: per-attempt snapshots. The aggregate
240- // assertions below are satisfied by a single lucky cq/step
241- // cell; these prove EVERY attempt that decoded and
242- // pixel-compared really carried the header state and the
243- // forced alphabet under test (class gate-blind-to-feature).
244- let attempt_fimv_before = crate::decode::fimv_frame_hits();
245- let attempt_alphabet_before = crate::decode::fimv_alphabet_hits();
246- let duration = frame_count as f64 / 25.0;
247- // Flat screen-content tiles with hard edges, translating by a
248- // whole number of pixels per frame: static enough for
249- // `av1_is_integer_mv`, moving enough for a real inter block
250- // with overlappable neighbours.
251- let source = format!(
252- "color=c=black:s={width}x{height}:r=25,\
253- drawbox=x='8+{step}*mod(trunc(t*25)\\,3)':y=8:w=20:h=20:color=white:t=fill,\
254- drawbox=x=36:y='6+{step}*mod(trunc(t*25)+1\\,3)':w=16:h=16:color=0x808080:t=fill,\
255- drawbox=x=4:y=44:w=56:h=12:color=0xC0C0C0:t=fill"
256- );
257- let pix_fmt = if ten_bit { "yuv420p10le" } else { "yuv420p" };
258- let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
259- .args([
260- "-v",
261- "error",
262- "-f",
263- "lavfi",
264- "-i",
265- &source,
266- "-t",
267- &duration.to_string(),
268- "-pix_fmt",
269- pix_fmt,
270- "-strict",
271- "-1",
272- "-f",
273- "yuv4mpegpipe",
274- "-",
275- ])
276- .stdin(Stdio::null())
277- .stdout(Stdio::piped())
278- .stderr(Stdio::piped()), None, |c| c.output())
279- .expect("ffmpeg failed to run");
280- assert!(
281- y4m.status.success(),
282- "ffmpeg fixture: {}",
283- String::from_utf8_lossy(&y4m.stderr)
284- );
285- let cq_arg = format!("--cq-level={cq}");
286- let mut args: Vec<&str> = vec![
287- "--codec=av1",
288- "--passes=1",
289- "--end-usage=q",
290- &cq_arg,
291- "--cpu-used=0",
292- "--kf-max-dist=1000",
293- "--threads=1",
294- "--row-mt=0",
295- // single reference only: the 10-bit compound MC defect
296- // (see `a_real_compound_global_warp_10bit_stream_...`)
297- // is unrelated to this lane and would mask it.
298- "--auto-alt-ref=0",
299- "--lag-in-frames=0",
300- "--enable-fwd-kf=0",
301- "--enable-order-hint=1",
302- // the flag combination this gate exists for: warp allowed
303- // by the header, OBMC available, global motion off (so the
304- // GLOBALMV suppression is not what picks the alphabet).
305- "--tune-content=screen",
306- "--enable-warped-motion=1",
307- "--enable-obmc=1",
308- "--enable-global-motion=0",
309- "--enable-masked-comp=0",
310- "--enable-onesided-comp=0",
311- "--enable-interintra-comp=0",
312- "--enable-interintra-wedge=0",
313- "--enable-smooth-interintra=0",
314- "--enable-dist-wtd-comp=0",
315- // partition/intra tools this decoder does not code yet --
316- // the same exclusion list every inter gate here carries.
317- "--enable-rect-partitions=0",
318- "--enable-ab-partitions=0",
319- "--enable-1to4-partitions=0",
320- "--enable-filter-intra=0",
321- "--enable-smooth-intra=0",
322- "--enable-paeth-intra=0",
323- "--enable-directional-intra=0",
324- "--enable-angle-delta=0",
325- "--enable-tx-size-search=0",
326- "--enable-cdef=0",
327- "--enable-restoration=0",
328- "--max-partition-size=32",
329- "--min-partition-size=32",
330- "--enable-palette=0",
331- "--enable-intrabc=0",
332- "--enable-cfl-intra=0",
333- "--enable-ref-frame-mvs=0",
334- ];
335- if ten_bit {
336- args.extend_from_slice(&["--input-bit-depth=10", "--bit-depth=10"]);
337- }
338- args.extend_from_slice(&["--obu", "-o", "-", "-"]);
339- let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
340- assert!(
341- out.status.success(),
342- "aomenc refused the fixture: {}",
343- String::from_utf8_lossy(&out.stderr)
344- );
345- let stream = out.stdout;
346- let frames = match decode_stream(&stream) {
347- Err(e) => {
348- let msg = e.to_string();
349- assert!(
350- msg.contains("unsupported"),
351- "{name} failed outright (cq {cq} step {step}): {msg}"
352- );
353- named_refusals += 1;
354- refusals.push(format!("cq {cq} step {step}: {msg}"));
355- continue;
356- }
357- Ok(frames) => frames,
358- };
359- let want = if ten_bit {
360- ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
361- } else {
362- ffmpeg_decode_sequence(&stream, width, height, frame_count)
363- };
364- assert_eq!(frames.len(), frame_count);
365- if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP")
366- && frames
367- .iter()
368- .zip(&want)
369- .any(|(g, w)| g.y != w.y || g.u != w.u || g.v != w.v)
370- {
371- std::fs::write(&path, &stream).expect("writing pinned stream");
372- eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (cq {cq}) to {path}");
373- }
374- for (i, (got, want)) in frames.iter().zip(&want).enumerate() {
375- assert_eq!(
376- got.y, want.y,
377- "{name} frame {i} luma vs ffmpeg (cq {cq} step {step})"
378- );
379- assert_eq!(
380- got.u, want.u,
381- "{name} frame {i} U vs ffmpeg (cq {cq} step {step})"
382- );
383- assert_eq!(
384- got.v, want.v,
385- "{name} frame {i} V vs ffmpeg (cq {cq} step {step})"
386- );
387- }
388- assert!(
389- crate::decode::fimv_frame_hits() > attempt_fimv_before,
390- "{name} (cq {cq} step {step}): decoded and compared all \
391- frames but no frame header had force_integer_mv=1 -- \
392- this attempt is vacuous"
393- );
394- assert!(
395- crate::decode::fimv_alphabet_hits() > attempt_alphabet_before,
396- "{name} (cq {cq} step {step}): no block was forced onto the \
397- 2-symbol obmc alphabet by force_integer_mv while \
398- allow_warped_motion=1 and num_proj_ref>=1 -- this attempt \
399- is vacuous"
400- );
401- matched += 1;
402- }
403- }
404- let fimv_frames = crate::decode::fimv_frame_hits() - fimv_frames_before;
405- let alphabet = crate::decode::fimv_alphabet_hits() - alphabet_before;
406- eprintln!(
407- "{name}: {matched}/{attempts} pixel-exact, {named_refusals} named refusals, \
408- force_integer_mv frames={fimv_frames}, forced-2-symbol blocks={alphabet}\n{}",
409- refusals.join("\n")
410- );
411- assert!(
412- matched > 0,
413- "{name}: every attempt refused -- no pixel comparison ran"
414- );
415- assert!(
416- fimv_frames > 0,
417- "{name}: no decoded frame header had force_integer_mv=1 \
418- ({matched} matches of {attempts}) -- gate vacuous"
419- );
420- assert!(
421- alphabet > 0,
422- "{name}: no block read the 2-symbol obmc alphabet where \
423- allow_warped_motion=1 and num_proj_ref>=1 would have picked the \
424- 3-symbol motion_mode alphabet -- gate vacuous"
425- );
426- }
427-
428- /// lane-mcomp64 r1: at 64x64 `av1_is_wedge_used` is false
429- /// (`av1_wedge_params_lookup[BLOCK_64X64].wedge_types == 0`), so libaom's
430- /// `read_compound_type` codes NO `compound_type` symbol and INFERS
431- /// `COMPOUND_DIFFWTD`; only the 1-bit `mask_type` literal follows. This
432- /// decoder used to refuse such a block by name ("a masked compound 64x64
433- /// inter block..."), because reading the symbol would have desynced.
434- ///
435- /// The recipe pins every block to 64x64 (`--sb-size=64
436- /// --max-partition-size=64 --min-partition-size=64`) with masked compound
437- /// on and distance-weighted compound off, so the only way a
438- /// `comp_group_idx == 1` block can be coded is through the inferred arm.
439- /// `diffwtd_inferred_hits` is snapshotted PER ATTEMPT and only accumulated
440- /// for attempts that decoded AND pixel-compared (class
441- /// `counter-from-refused-stream`), and is hard-asserted at the end. A
442- /// decode error or a pixel mismatch is a FAILURE, never a skip.
443- #[track_caller]
444- pub(super) fn run_diffwtd_inferred_64x64_gate(name: &str, ten_bit: bool) {
445- let _gate_lock = lock_gate_counters();
446- assert!(have_ffmpeg(), "{name}: ffmpeg required");
447- assert!(
448- have_aomenc(),
449- "{name}: no aomenc at {}",
450- aomenc_path().display()
451- );
452- let (width, height, frame_count) = (128usize, 128usize, 16usize);
453- let mut matched = 0u32;
454- let mut named_refusals = 0u32;
455- let mut attempts = 0u32;
456- let mut fired = 0usize;
457- let mut refusals: Vec<String> = Vec::new();
458- for cq in [32u32, 45, 55] {
459- for (i, zoom) in [0.004f64, 0.010].iter().enumerate() {
460- attempts += 1;
461- let attempt_before = crate::decode::diffwtd_inferred_hits();
462- let duration = frame_count as f64 / 25.0;
463- // Hard-edged, moving content: a difference-weighted mask only
464- // wins where the two references genuinely disagree over part
465- // of a 64x64 block (a smooth `gradients` source measured
466- // diffwtd_hits == 0, memory `gate-blind-to-feature`).
467- let source = format!(
468- "mandelbrot=size={width}x{height}:rate=25:start_x={sx}:start_y=-0.4:\
469- end_scale=0.3:maxiter=200,\
470- noise=alls=6:allf=t+u:all_seed={seed}",
471- sx = -0.6 + zoom * (i as f64 + 1.0),
472- seed = 1000 + cq,
473- );
474- let pix_fmt = if ten_bit { "yuv420p10le" } else { "yuv420p" };
475- let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
476- .args([
477- "-v",
478- "error",
479- "-f",
480- "lavfi",
481- "-i",
482- &source,
483- "-t",
484- &duration.to_string(),
485- "-pix_fmt",
486- pix_fmt,
487- "-strict",
488- "-1",
489- "-f",
490- "yuv4mpegpipe",
491- "-",
492- ])
493- .stdin(Stdio::null())
494- .stdout(Stdio::piped())
495- .stderr(Stdio::piped()), None, |c| c.output())
496- .expect("ffmpeg failed to run");
497- assert!(
498- y4m.status.success(),
499- "ffmpeg fixture: {}",
500- String::from_utf8_lossy(&y4m.stderr)
501- );
502- let cq_arg = format!("--cq-level={cq}");
503- let mut args: Vec<&str> = vec![
504- "--codec=av1",
505- "--passes=1",
506- "--end-usage=q",
507- &cq_arg,
508- "--cpu-used=0",
509- "--kf-max-dist=1000",
510- "--threads=1",
511- "--row-mt=0",
512- "--auto-alt-ref=1",
513- "--lag-in-frames=16",
514- "--enable-fwd-kf=0",
515- "--enable-order-hint=1",
516- // the tools this gate exists for: masked compound on, the
517- // difference-weighted arm on, the distance-weighted
518- // competitor off so comp_group_idx==1 is the encoder's
519- // only masked choice at a size where wedge does not exist.
520- "--enable-masked-comp=1",
521- "--enable-diff-wtd-comp=1",
522- "--enable-dist-wtd-comp=0",
523- "--enable-onesided-comp=0",
524- "--enable-interintra-comp=0",
525- "--enable-global-motion=0",
526- "--enable-warped-motion=1",
527- "--enable-obmc=1",
528- "--tune-content=default",
529- // partition/intra tools this decoder does not code yet --
530- // same exclusion list every compound gate carries.
531- "--enable-rect-partitions=0",
532- "--enable-ab-partitions=0",
533- "--enable-1to4-partitions=0",
534- "--enable-filter-intra=0",
535- "--enable-smooth-intra=0",
536- "--enable-paeth-intra=0",
537- "--enable-directional-intra=0",
538- "--enable-angle-delta=0",
539- "--enable-tx-size-search=0",
540- "--enable-cdef=0",
541- "--enable-restoration=0",
542- "--enable-palette=0",
543- "--enable-intrabc=0",
544- "--enable-cfl-intra=0",
545- "--enable-ref-frame-mvs=0",
546- // every block is a whole 64x64 superblock: the ONLY size
547- // where compound_type is inferred rather than coded.
548- "--sb-size=64",
549- "--max-partition-size=64",
550- "--min-partition-size=64",
551- ];
552- if ten_bit {
553- args.extend_from_slice(&["--input-bit-depth=10", "--bit-depth=10"]);
554- }
555- args.extend_from_slice(&["--obu", "-o", "-", "-"]);
556- let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
557- assert!(
558- out.status.success(),
559- "aomenc refused the fixture: {}",
560- String::from_utf8_lossy(&out.stderr)
561- );
562- let stream = out.stdout;
563- let frames = match decode_stream(&stream) {
564- Err(e) => {
565- let msg = e.to_string();
566- assert!(
567- msg.contains("unsupported"),
568- "{name} failed outright, not a named refusal (cq {cq}): {msg}"
569- );
570- assert!(
571- !msg.contains("masked compound 64x64"),
572- "{name} refused the inferred-DIFFWTD 64x64 block (cq {cq}) -- \
573- that refusal is lifted, this is forbidden: {msg}"
574- );
575- named_refusals += 1;
576- refusals.push(msg.clone());
577- eprintln!("{name} cq {cq} variant {i} refusal: {msg}");
578- continue;
579- }
580- Ok(frames) => frames,
581- };
582- let want = if ten_bit {
583- ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
584- } else {
585- ffmpeg_decode_sequence(&stream, width, height, frame_count)
586- };
587- assert_eq!(frames.len(), frame_count);
588- if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP")
589- && frames
590- .iter()
591- .zip(&want)
592- .any(|(g, w)| g.y != w.y || g.u != w.u || g.v != w.v)
593- {
594- std::fs::write(&path, &stream).expect("writing pinned stream");
595- eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (cq {cq}) to {path}");
596- }
597- for (f, (got, want)) in frames.iter().zip(&want).enumerate() {
598- assert_eq!(got.y, want.y, "{name} frame {f} luma vs ffmpeg (cq {cq})");
599- assert_eq!(got.u, want.u, "{name} frame {f} U vs ffmpeg (cq {cq})");
600- assert_eq!(got.v, want.v, "{name} frame {f} V vs ffmpeg (cq {cq})");
601- }
602- // decoded AND compared: only now does this attempt's own
603- // inferred-DIFFWTD count mean anything.
604- fired += crate::decode::diffwtd_inferred_hits() - attempt_before;
605- matched += 1;
606- }
607- }
608- eprintln!(
609- "{name}: {matched}/{attempts} pixel-exact, {named_refusals} named refusals, \
610- diffwtd_inferred_hits (decoded+compared attempts only)={fired}"
611- );
612- assert!(
613- matched > 0,
614- "{name}: every attempt refused ({refusals:?}) -- no pixel compare ran"
615- );
616- assert!(
617- fired > 0,
618- "{name}: no inferred-DIFFWTD 64x64 block fired on a compared attempt \
619- ({matched} matches, {named_refusals} refusals of {attempts}) -- gate vacuous"
620- );
621- }
622-
623- pub(super) fn both_axes_cut_sweep(
624- name: &'static str,
625- (arm, frames, kf_arg, limit_arg): (&str, usize, &str, &str),
626- ) {
627- // Kept upper-case so every message string below reads the same as in
628- // the sibling gates.
629- #[allow(non_snake_case)]
630- let NAME = name;
631- let _gate_lock = lock_gate_counters();
632- if !have_ffmpeg() || !have_aomenc() {
633- eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
634- return;
635- }
636- let sizes: &[(usize, usize)] = &[(200, 72), (136, 104), (264, 136), (72, 200), (104, 136)];
637- let mut compared = 0u32;
638- let mut refusals: Vec<String> = Vec::new();
639- let mut totals = [0usize; 4];
640- for &(width, height) in sizes {
641- let mut size_compared = 0u32;
642- {
643- for bit_depth in [8u32, 10u32] {
644- // cq 58 is left out on purpose: measured r1, it is where
645- // libaom starts answering the frame-edge gathered symbol
646- // with a rect strip and other lanes' refusals fire first
647- // ("a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs
648- // rectangular residual coding").
649- for cq in [32u32, 45] {
650- let source = format!("mandelbrot=size={width}x{height}:rate=25");
651- // Feed exactly `frames` frames: --limit=1 makes
652- // aomenc stop reading after the first one and the
653- // y4m write then dies on a broken pipe.
654- let dur = format!("{}", frames as f64 / 25.0);
655- let pix_fmt = if bit_depth == 10 {
656- "yuv420p10le"
657- } else {
658- "yuv420p"
659- };
660- let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
661- .args([
662- "-v",
663- "error",
664- "-f",
665- "lavfi",
666- "-i",
667- &source,
668- "-t",
669- &dur,
670- "-pix_fmt",
671- pix_fmt,
672- "-strict",
673- "-1",
674- "-f",
675- "yuv4mpegpipe",
676- "-",
677- ])
678- .stdin(Stdio::null())
679- .stdout(Stdio::piped())
680- .stderr(Stdio::piped()), None, |c| c.output())
681- .expect("ffmpeg failed to run");
682- assert!(
683- y4m.status.success(),
684- "{NAME}: ffmpeg refused the {width}x{height} {bit_depth}-bit \
685- fixture: {}",
686- String::from_utf8_lossy(&y4m.stderr)
687- );
688- let depth_arg = format!("--bit-depth={bit_depth}");
689- let input_depth_arg = format!("--input-bit-depth={bit_depth}");
690- let cq_arg = format!("--cq-level={cq}");
691- let out = run_with_stdin(
692- Command::new(aomenc_path()).args([
693- "--codec=av1",
694- "--passes=1",
695- "--end-usage=q",
696- &cq_arg,
697- // cpu-used >= 1 keeps libaom on 64x64
698- // superblocks at these sizes
699- // (`av1_select_sb_size`).
700- "--cpu-used=4",
701- "--threads=1",
702- "--row-mt=0",
703- // --lag-in-frames=0: no hidden alt-ref, so
704- // decode order == display order and the
705- // compare below covers every frame the stream
706- // carries (class gate-blind-to-hidden-frames).
707- kf_arg,
708- limit_arg,
709- "--lag-in-frames=0",
710- &depth_arg,
711- &input_depth_arg,
712- // Other lanes' named refusals this recipe must
713- // not trip. The both-cut corner is FORCED down
714- // to 8x8 leaves, which is exactly where the
715- // 8x8-intra-leaf-in-an-inter-frame gaps live,
716- // so the intra tool set and tx-size search are
717- // pinned off: without them 30/30 inter
718- // attempts refused (measured r1) on "a nonzero
719- // angle delta on an 8x8 intra leaf in an inter
720- // frame", "a non-DC chroma mode on an 8x8
721- // inter-frame leaf" and "an 8x8 intra leaf in
722- // an inter frame whose tx_depth splits it into
723- // 4x4 transform units".
724- "--enable-rect-partitions=0",
725- "--enable-ab-partitions=0",
726- "--enable-1to4-partitions=0",
727- "--min-partition-size=8",
728- "--max-partition-size=64",
729- "--enable-palette=0",
730- "--enable-intrabc=0",
731- "--enable-warped-motion=0",
732- "--enable-obmc=0",
733- "--enable-masked-comp=0",
734- "--enable-interintra-comp=0",
735- "--enable-onesided-comp=0",
736- "--enable-interintra-wedge=0",
737- "--enable-smooth-interintra=0",
738- "--enable-ref-frame-mvs=0",
739- "--enable-angle-delta=0",
740- "--enable-cfl-intra=0",
741- "--enable-directional-intra=0",
742- "--enable-smooth-intra=0",
743- "--enable-paeth-intra=0",
744- "--enable-filter-intra=0",
745- "--enable-tx-size-search=0",
746- "--obu",
747- "-o",
748- "-",
749- "-",
750- ]),
751- &y4m.stdout,
752- );
753- assert!(
754- out.status.success(),
755- "aomenc refused: {}",
756- String::from_utf8_lossy(&out.stderr)
757- );
758- let stream = out.stdout;
759-
760- // Reset, never a delta across attempts: a refused
761- // attempt's hits must not count (class
762- // counter-from-refused-stream).
763- crate::decode::reset_edge_both_cut_hits();
764- let decoded = match decode_stream(&stream) {
765- Ok(f) => f,
766- Err(e) => {
767- let msg = e.to_string();
768- assert!(
769- msg.contains("unsupported"),
770- "{NAME}: {width}x{height} {arm} {bit_depth}-bit cq {cq} \
771- failed outright, not a named refusal: {msg}"
772- );
773- eprintln!(
774- " {NAME}: {width}x{height} {arm} {bit_depth}-bit cq {cq} \
775- REFUSED {msg}"
776- );
777- refusals.push(msg);
778- continue;
779- }
780- };
781- let hits = crate::decode::edge_both_cut_hits();
782- let reference = if bit_depth == 10 {
783- ffmpeg_decode_sequence_10bit(&stream, width, height, frames)
784- } else {
785- ffmpeg_decode_sequence(&stream, width, height, frames)
786- };
787- assert_eq!(
788- decoded.len(),
789- frames,
790- "{NAME}: {width}x{height} {arm} {bit_depth}-bit cq {cq} decoded {} \
791- frames, expected {frames}",
792- decoded.len()
793- );
794- assert_eq!(
795- reference.len(),
796- frames,
797- "{NAME}: {width}x{height} {arm} {bit_depth}-bit cq {cq} reference \
798- frame count"
799- );
800- for (i, (ours, theirs)) in decoded.iter().zip(&reference).enumerate() {
801- let nd = |a: &[u16], b: &[u16]| {
802- a.iter().zip(b).filter(|(x, y)| x != y).count()
803- };
804- // Where a mismatch lands is the whole diagnosis
805- // here (corner block vs elsewhere), so print the
806- // luma bounding box before the assert kills the run.
807- if nd(&ours.y, &theirs.y) > 0 {
808- let (mut r0, mut c0, mut r1, mut c1) =
809- (usize::MAX, usize::MAX, 0usize, 0usize);
810- for row in 0..height {
811- for col in 0..width {
812- if ours.y[row * width + col] != theirs.y[row * width + col]
813- {
814- r0 = r0.min(row);
815- c0 = c0.min(col);
816- r1 = r1.max(row);
817- c1 = c1.max(col);
818- }
819- }
820- }
821- eprintln!(
822- " {NAME}: {width}x{height} {arm} {bit_depth}-bit cq {cq} \
823- frame {i} luma diff bbox rows {r0}..={r1} cols {c0}..={c1}"
824- );
825- }
826- assert_eq!(
827- (
828- nd(&ours.y, &theirs.y),
829- nd(&ours.u, &theirs.u),
830- nd(&ours.v, &theirs.v)
831- ),
832- (0, 0, 0),
833- "{NAME}: {width}x{height} {arm} {bit_depth}-bit cq {cq} frame \
834- {i} differs from ffmpeg"
835- );
836- for (plane, a, b) in [
837- ("Y", &ours.y, &theirs.y),
838- ("U", &ours.u, &theirs.u),
839- ("V", &ours.v, &theirs.v),
840- ] {
841- assert_eq!(
842- a.len(),
843- b.len(),
844- "{NAME}: {width}x{height} {arm} {bit_depth}-bit cq {cq} \
845- frame {i} plane {plane}: ours has {} samples, ffmpeg's has \
846- {} -- a short plane would zip-truncate the diff count \
847- above and hide a chroma-span defect",
848- a.len(),
849- b.len()
850- );
851- }
852- }
853- // Every compared attempt must carry the case, so no
854- // compared attempt is out of scope and
855- // out_of_scope_mismatch is 0 by construction.
856- assert!(
857- hits[0] > 0,
858- "{NAME}: {width}x{height} {arm} {bit_depth}-bit cq {cq} decoded \
859- pixel-exact but no 16-level both-axes-cut block fired \
860- (hits={hits:?}) -- the recipe no longer reaches the lifted arm"
861- );
862- for l in 0..4 {
863- totals[l] += hits[l];
864- }
865- compared += 1;
866- size_compared += 1;
867- }
868- }
869- }
870- assert!(
871- size_compared > 0,
872- "{NAME}: every {width}x{height} attempt refused -- that size proved nothing"
873- );
874- }
875- assert!(
876- totals[1] > 0 && totals[2] > 0,
877- "{NAME}: no 32-level ({}) or 64-level ({}) both-axes-cut node fired -- 200x72 puts \
878- both in that state, so the sweep stopped reaching them",
879- totals[1],
880- totals[2]
881- );
882- eprintln!(
883- "{NAME}: {compared} attempts pixel-exact over {} sizes ({arm} arm), \
884- out_of_scope_mismatch=0, both_cut hits [16,32,64,128]={totals:?}, {} named refusals",
885- sizes.len(),
886- refusals.len()
887- );
888- }
889-
890- /// lane-av1tmvp: the temporal-MV gate -- unlike every `_single_ref_gate`
891- /// attempt above, this one leaves `--enable-ref-frame-mvs` at aomenc's
892- /// own default (on) instead of pinning it off, so `use_ref_frame_mvs`
893- /// actually fires and `decode::tmv_hits()` (this gate's own capability
894- /// proof, not just `non_last_ref_hits`) has to advance for the run to
895- /// count as a real pass rather than a `never_fired` skip.
896- pub(super) fn a_real_aomenc_temporal_mv_gate(seed_base: u32, attempts: u32) {
897- let gate_name = "a_real_aomenc_temporal_mv_gate";
898- let _gate_lock = lock_gate_counters();
899- if !have_ffmpeg() {
900- eprintln!("SKIP {gate_name}: no ffmpeg");
901- return;
902- }
903- if !have_aomenc() {
904- eprintln!("SKIP {gate_name}: no aomenc at {}", aomenc_path().display());
905- return;
906- }
907- let (width, height, frame_count) = (64usize, 64usize, 16usize);
908- let mut never_fired = 0u32;
909- let mut refusals = Vec::new();
910- for attempt in 0..attempts {
911- let seed = seed_base + attempt;
912- let duration = frame_count as f64 / 25.0;
913- let source =
914- gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
915- let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
916- .args([
917- "-v",
918- "error",
919- "-f",
920- "lavfi",
921- "-i",
922- &source,
923- "-pix_fmt",
924- "yuv420p",
925- "-f",
926- "yuv4mpegpipe",
927- "-",
928- ])
929- .stdin(Stdio::null())
930- .stdout(Stdio::piped())
931- .stderr(Stdio::piped()), None, |c| c.output())
932- .expect("ffmpeg failed to run");
933- assert!(
934- y4m.status.success(),
935- "ffmpeg fixture: {}",
936- String::from_utf8_lossy(&y4m.stderr)
937- );
938- // Same envelope as `a_real_aomenc_single_ref_gate`, minus its
939- // `--enable-ref-frame-mvs=0` pin -- everything else this decoder
940- // still cannot code stays refused the same way.
941- let args: Vec<&str> = vec![
942- "--codec=av1",
943- "--passes=1",
944- "--end-usage=q",
945- "--cq-level=55",
946- "--cpu-used=0",
947- "--kf-max-dist=1000",
948- "--threads=1",
949- "--row-mt=0",
950- "--auto-alt-ref=1",
951- "--lag-in-frames=16",
952- "--enable-fwd-kf=0",
953- "--enable-warped-motion=0",
954- "--enable-obmc=0",
955- "--enable-masked-comp=0",
956- "--enable-interintra-comp=0",
957- "--enable-dist-wtd-comp=0",
958- "--enable-diff-wtd-comp=0",
959- "--enable-onesided-comp=0",
960- "--enable-interintra-wedge=0",
961- "--enable-smooth-interintra=0",
962- "--enable-rect-partitions=0",
963- "--enable-ab-partitions=0",
964- "--enable-1to4-partitions=0",
965- "--enable-filter-intra=0",
966- "--enable-smooth-intra=0",
967- "--enable-paeth-intra=0",
968- "--enable-directional-intra=0",
969- "--enable-angle-delta=0",
970- "--enable-tx-size-search=0",
971- "--enable-cdef=0",
972- "--enable-restoration=0",
973- "--max-partition-size=32",
974- "--min-partition-size=32",
975- "--enable-palette=0",
976- "--enable-intrabc=0",
977- "--enable-cfl-intra=0",
978- "--obu",
979- "-o",
980- "-",
981- "-",
982- ];
983- let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
984- assert!(
985- out.status.success(),
986- "aomenc refused the fixture: {}",
987- String::from_utf8_lossy(&out.stderr)
988- );
989- let stream = out.stdout;
990- let before = decode::tmv_hits();
991- let frames = match decode_stream(&stream) {
992- Err(e) => {
993- let msg = e.to_string();
994- assert!(
995- msg.contains("unsupported"),
996- "{gate_name} failed outright (seed {seed}): {msg}"
997- );
998- refusals.push(format!("seed {seed}: {msg}"));
999- continue;
1000- }
1001- Ok(frames) => frames,
1002- };
1003- // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
1004- // is ALWAYS pixel-compared below; the hit counter only decides whether
1005- // the attempt counts toward the firing total.
1006- let counted = decode::tmv_hits() != before;
1007- if !counted {
1008- never_fired += 1;
1009- }
1010- let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
1011- assert_eq!(frames.len(), frame_count);
1012- if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
1013- let mismatched = frames
1014- .iter()
1015- .zip(&ffmpeg_frames)
1016- .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
1017- if mismatched {
1018- std::fs::write(&path, &stream).expect("writing pinned stream");
1019- eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
1020- }
1021- }
1022- for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
1023- assert_eq!(
1024- got.y, want.y,
1025- "{gate_name} frame {i} luma vs ffmpeg (seed {seed})"
1026- );
1027- assert_eq!(
1028- got.u, want.u,
1029- "{gate_name} frame {i} U vs ffmpeg (seed {seed})"
1030- );
1031- assert_eq!(
1032- got.v, want.v,
1033- "{gate_name} frame {i} V vs ffmpeg (seed {seed})"
1034- );
1035- }
1036- if counted {
1037- eprintln!(
1038- "{gate_name} FIRING seed {seed}: tmv_hits advanced by {}",
1039- decode::tmv_hits() - before
1040- );
1041- gate_buckets(gate_name, 1, never_fired, refusals.len());
1042- return;
1043- }
1044- }
1045- gate_buckets(gate_name, 0, never_fired, refusals.len());
1046- eprintln!(
1047- "SKIP {gate_name}: {never_fired} attempts decoded but never fired a temporal MV \
1048- candidate, and every other attempt hit a named refusal:\n{}",
1049- refusals.join("\n")
1050- );
1051- }
1052-
1053- /// lane-mvtwin r1: the COMPOUND MV-stack gate. Every other compound gate
1054- /// here pins `--enable-ref-frame-mvs=0`, so `find_mv_stack_compound`'s
1055- /// temporal half (the three `tpl_sample_pos` extension samples lane-sb128
1056- /// r3 found missing) and its extension pass have never been exercised by
1057- /// a real encoder. This arm turns ref-frame-mvs ON, gives the encoder a
1058- /// 25-frame lookahead plus alt-refs so `reference_select` really drives
1059- /// blocks to COMPOUND_REFERENCE, and sweeps global motion off/on so the
1060- /// combine step's `gm_mv_candidates` fill (r1 defect 1) is reachable.
1061- ///
1062- /// Firing proof, hard-asserted: `decode::comp_mode_hits` (a real
1063- /// compound block) AND `mvstack::tmv_hits` (a temporal candidate landed
1064- /// in some stack) must BOTH have advanced on an attempt that also
1065- /// decoded pixel-exact -- class [[gate-skips-on-its-own-failure]]: a
1066- /// decode that succeeds is ALWAYS compared, on every decode-order frame,
1067- /// and only the counters decide whether the attempt counts.
1068- // Signature mirrors the spec's per-call inputs; a parameter struct would only move them.
1069- #[allow(clippy::too_many_arguments)]
1070- pub(super) fn a_real_aomenc_compound_mv_stack_gate(
1071- gate_name: &str,
1072- seed_base: u32,
1073- attempts: u32,
1074- bit_depth: u32,
1075- sb_size: u32,
1076- global_motion: u32,
1077- width: usize,
1078- tile_columns: u32,
1079- ) {
1080- let _gate_lock = lock_gate_counters();
1081- if !have_ffmpeg() {
1082- eprintln!("SKIP {gate_name}: no ffmpeg");
1083- return;
1084- }
1085- if !have_aomenc() {
1086- eprintln!("SKIP {gate_name}: no aomenc at {}", aomenc_path().display());
1087- return;
1088- }
1089- let (height, frame_count) = (64usize, 16usize);
1090- let mut never_fired = 0u32;
1091- let mut refusals = Vec::new();
1092- for attempt in 0..attempts {
1093- let seed = seed_base + attempt;
1094- let duration = frame_count as f64 / 25.0;
1095- let source =
1096- gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
1097- let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1098- .args([
1099- "-v",
1100- "error",
1101- "-f",
1102- "lavfi",
1103- "-i",
1104- &source,
1105- "-pix_fmt",
1106- if bit_depth == 10 {
1107- "yuv420p10le"
1108- } else {
1109- "yuv420p"
1110- },
1111- "-strict",
1112- "-1",
1113- "-t",
1114- "0.64",
1115- "-f",
1116- "yuv4mpegpipe",
1117- "-strict",
1118- "-1",
1119- "-",
1120- ])
1121- .stdin(Stdio::null())
1122- .stdout(Stdio::piped())
1123- .stderr(Stdio::piped()), None, |c| c.output())
1124- .expect("ffmpeg failed to run");
1125- assert!(
1126- y4m.status.success(),
1127- "ffmpeg fixture: {}",
1128- String::from_utf8_lossy(&y4m.stderr)
1129- );
1130- let depth_args: &[&str] = if bit_depth == 10 {
1131- &["-b", "10", "--input-bit-depth=10"]
1132- } else {
1133- &[]
1134- };
1135- // The cq sweep: how finely RD partitions decides how often a
1136- // block's stack comes up short enough to reach the extension
1137- // pass at all.
1138- let cq = format!("--cq-level={}", [45u32, 55, 35][(attempt % 3) as usize]);
1139- let sb = format!("--sb-size={sb_size}");
1140- let gm = format!("--enable-global-motion={global_motion}");
1141- // `--tile-columns` is log2: 1 means two tile columns, which is
1142- // what makes every block in the right-hand tile carry a nonzero
1143- // `tile_col0` and so exercise r1 defect 3's reach clamp.
1144- let tiles = format!("--tile-columns={tile_columns}");
1145- // class [[aomenc-last-flag-wins]]: every flag appears exactly
1146- // once below, so there is no override to order.
1147- let out = run_with_stdin(
1148- Command::new(aomenc_path())
1149- .args(depth_args)
1150- .arg(&cq)
1151- .arg(&sb)
1152- .arg(&gm)
1153- .arg(&tiles)
1154- .args([
1155- "--codec=av1",
1156- "--passes=1",
1157- "--end-usage=q",
1158- "--cpu-used=0",
1159- "--kf-max-dist=1000",
1160- "--threads=1",
1161- "--row-mt=0",
1162- // What this gate is about: real compound references
1163- // with a real temporal MV field behind them.
1164- "--enable-ref-frame-mvs=1",
1165- "--enable-order-hint=1",
1166- "--auto-alt-ref=1",
1167- "--lag-in-frames=25",
1168- "--enable-fwd-kf=0",
1169- "--enable-warped-motion=0",
1170- "--enable-obmc=0",
1171- "--enable-masked-comp=0",
1172- "--enable-interintra-comp=0",
1173- "--enable-dist-wtd-comp=0",
1174- "--enable-diff-wtd-comp=0",
1175- "--enable-onesided-comp=0",
1176- "--enable-interintra-wedge=0",
1177- "--enable-smooth-interintra=0",
1178- "--enable-rect-partitions=0",
1179- "--enable-ab-partitions=0",
1180- "--enable-1to4-partitions=0",
1181- "--enable-filter-intra=0",
1182- "--enable-smooth-intra=0",
1183- "--enable-paeth-intra=0",
1184- "--enable-directional-intra=0",
1185- "--enable-angle-delta=0",
1186- "--enable-tx-size-search=0",
1187- "--enable-cdef=0",
1188- "--enable-restoration=0",
1189- "--max-partition-size=32",
1190- "--min-partition-size=32",
1191- "--enable-palette=0",
1192- "--enable-intrabc=0",
1193- "--enable-cfl-intra=0",
1194- "--obu",
1195- "-o",
1196- "-",
1197- "-",
1198- ]),
1199- &y4m.stdout,
1200- );
1201- assert!(
1202- out.status.success(),
1203- "aomenc refused the fixture: {}",
1204- String::from_utf8_lossy(&out.stderr)
1205- );
1206- let stream = out.stdout;
1207- let (before_comp, before_tmv) = (decode::comp_mode_hits(), decode::tmv_hits());
1208- let frames = match decode_stream(&stream) {
1209- Err(e) => {
1210- let msg = e.to_string();
1211- assert!(
1212- msg.contains("unsupported"),
1213- "{gate_name} failed outright (seed {seed}): {msg}"
1214- );
1215- refusals.push(format!("seed {seed}: {msg}"));
1216- continue;
1217- }
1218- Ok(frames) => frames,
1219- };
1220- let counted =
1221- decode::comp_mode_hits() != before_comp && decode::tmv_hits() != before_tmv;
1222- if !counted {
1223- never_fired += 1;
1224- }
1225- let ffmpeg_frames = if bit_depth == 10 {
1226- ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
1227- } else {
1228- ffmpeg_decode_sequence(&stream, width, height, frame_count)
1229- };
1230- assert_eq!(frames.len(), frame_count);
1231- // Every SHOWN/display frame `decode_stream` returned is compared --
1232- // that is decode_stream's whole output, and nothing else is.
1233- // HIDDEN frames are NOT covered here: they are never emitted as
1234- // pictures, so no ffmpeg picture corresponds to them (class
1235- // [[gate-blind-to-hidden-frames]]).
1236- for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
1237- assert_eq!(
1238- got.y, want.y,
1239- "{gate_name} frame {i} luma vs ffmpeg (seed {seed})"
1240- );
1241- assert_eq!(
1242- got.u, want.u,
1243- "{gate_name} frame {i} U vs ffmpeg (seed {seed})"
1244- );
1245- assert_eq!(
1246- got.v, want.v,
1247- "{gate_name} frame {i} V vs ffmpeg (seed {seed})"
1248- );
1249- }
1250- if counted {
1251- eprintln!(
1252- "{gate_name} FIRING seed {seed}: comp_mode_hits +{}, tmv_hits +{}, \
1253- comp_gm_fill_hits={}, stack_full_drops={}, tile_reach_clips={}",
1254- decode::comp_mode_hits() - before_comp,
1255- decode::tmv_hits() - before_tmv,
1256- crate::mvstack::comp_gm_fill_hits(),
1257- crate::mvstack::stack_full_drops(),
1258- crate::mvstack::tile_reach_clips(),
1259- );
1260- gate_buckets(gate_name, 1, never_fired, refusals.len());
1261- return;
1262- }
1263- }
1264- gate_buckets(gate_name, 0, never_fired, refusals.len());
1265- eprintln!(
1266- "SKIP {gate_name}: {never_fired} attempts decoded but never drove a compound block \
1267- with a temporal MV candidate, and every other attempt hit a named refusal:\n{}",
1268- refusals.join("\n")
1269- );
1270- }
1271-
1272- /// lane-seg: a real `aomenc` stream with SEGMENTATION genuinely active.
1273- /// `--aq-mode=1` (variance AQ) / `--aq-mode=2` (complexity AQ) are the two
1274- /// paths libaom uses to switch `segmentation_enabled` on by itself
1275- /// (`av1_vaq_frame_setup`/`av1_setup_in_frame_q_adj`, both of which only
1276- /// ever set `SEG_LVL_ALT_Q`); `--deltaq-mode=0` keeps the per-superblock
1277- /// delta-q reader out of the picture so a mismatch points at the segment
1278- /// map, not at `CurrentQIndex`. Mandelbrot's varying local contrast is
1279- /// what gives variance/complexity AQ different segments to assign --
1280- /// a flat gradient collapses every block onto one segment, which the
1281- /// `segment_ids_seen() >= 2` assert below would catch as a vacuous run.
1282- /// The rest of the recipe is the delta-q gate's own feature-disable
1283- /// envelope, so this gate isolates the segmentation reader.
1284- pub(super) fn run_segmentation_gate(
1285- name: &str,
1286- aq_mode: &str,
1287- bit_depth: usize,
1288- frame_count: usize,
1289- rate_args: &[&str],
1290- ) {
1291- let _gate_lock = lock_gate_counters();
1292- if !have_ffmpeg() {
1293- eprintln!("SKIP {name}: no ffmpeg");
1294- return;
1295- }
1296- if !have_aomenc() {
1297- eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
1298- return;
1299- }
1300- crate::decode::reset_segment_hits();
1301- let (width, height) = (128usize, 64usize);
1302- let mut named_refusals = 0u32;
1303- let mut matched = 0u32;
1304- let n_attempts: u32 = std::env::var("EC_SEG_GATE_ATTEMPTS")
1305- .ok()
1306- .and_then(|s| s.parse().ok())
1307- .unwrap_or(10);
1308- for attempt in 0..n_attempts {
1309- let seed = 42 + attempt;
1310- let duration = frame_count as f64 / 25.0;
1311- let source = format!(
1312- "mandelbrot=size={width}x{height}:rate=25:start_x={sx}:start_y={sy}",
1313- sx = -0.6 + 0.005 * (attempt as f64),
1314- sy = -0.4 + 0.005 * (attempt as f64)
1315- );
1316- let pix_fmt = if bit_depth == 10 {
1317- "yuv420p10le"
1318- } else {
1319- "yuv420p"
1320- };
1321- let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1322- .args([
1323- "-v",
1324- "error",
1325- "-f",
1326- "lavfi",
1327- "-i",
1328- &source,
1329- "-t",
1330- &duration.to_string(),
1331- "-pix_fmt",
1332- pix_fmt,
1333- "-strict",
1334- "-1",
1335- "-f",
1336- "yuv4mpegpipe",
1337- "-",
1338- ])
1339- .stdin(Stdio::null())
1340- .stdout(Stdio::piped())
1341- .stderr(Stdio::piped()), None, |c| c.output())
1342- .expect("ffmpeg failed to run");
1343- assert!(
1344- y4m.status.success(),
1345- "ffmpeg fixture: {}",
1346- String::from_utf8_lossy(&y4m.stderr)
1347- );
1348- let depth_args: Vec<String> = if bit_depth == 10 {
1349- vec![
1350- "--input-bit-depth=10".to_owned(),
1351- "--bit-depth=10".to_owned(),
1352- ]
1353- } else {
1354- Vec::new()
1355- };
1356- let aq = format!("--aq-mode={aq_mode}");
1357- let mut args: Vec<&str> = vec![
1358- "--codec=av1",
1359- "--passes=1",
1360- "--cpu-used=4",
1361- &aq,
1362- "--deltaq-mode=0",
1363- "--enable-cdef=0",
1364- "--kf-max-dist=1000",
1365- "--threads=1",
1366- "--row-mt=0",
1367- "--sb-size=64",
1368- "--auto-alt-ref=1",
1369- "--lag-in-frames=16",
1370- "--enable-fwd-kf=0",
1371- "--enable-order-hint=1",
1372- "--enable-warped-motion=1",
1373- "--enable-global-motion=0",
1374- "--enable-obmc=1",
1375- "--tune-content=default",
1376- "--enable-masked-comp=1",
1377- "--enable-dist-wtd-comp=0",
1378- "--enable-interintra-comp=1",
1379- "--enable-onesided-comp=0",
1380- "--enable-interintra-wedge=0",
1381- "--enable-smooth-interintra=1",
1382- "--enable-rect-partitions=0",
1383- "--enable-ab-partitions=0",
1384- "--enable-1to4-partitions=0",
1385- "--enable-filter-intra=0",
1386- "--enable-smooth-intra=0",
1387- "--enable-paeth-intra=0",
1388- "--enable-directional-intra=0",
1389- "--enable-angle-delta=0",
1390- "--enable-tx-size-search=0",
1391- "--enable-cdef=1",
1392- "--enable-restoration=0",
1393- "--max-partition-size=32",
1394- "--min-partition-size=32",
1395- "--enable-palette=0",
1396- "--enable-intrabc=0",
1397- "--enable-cfl-intra=0",
1398- "--enable-ref-frame-mvs=0",
1399- ];
1400- args.extend(rate_args.iter().copied());
1401- args.extend(depth_args.iter().map(String::as_str));
1402- args.extend(["--obu", "-o", "-", "-"]);
1403- let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
1404- assert!(
1405- out.status.success(),
1406- "aomenc refused the fixture: {}",
1407- String::from_utf8_lossy(&out.stderr)
1408- );
1409- let stream = out.stdout;
1410- // The stream must really carry `segmentation_enabled`, or the
1411- // gate proves nothing about the reader.
1412- let mut seg_frames = 0u32;
1413- {
1414- let mut probe = Av1Parser::new();
1415- let mut pos = 0usize;
1416- while pos < stream.len() {
1417- let obu = probe
1418- .parse_obu(&stream[pos..])
1419- .expect("parsing the gate stream");
1420- pos += obu.total_size;
1421- match &obu.kind {
1422- ObuKind::Frame(h, _) => {
1423- if h.segmentation.enabled {
1424- seg_frames += 1;
1425- }
1426- }
1427- ObuKind::FrameHeader(h)
1428- if h.segmentation.enabled => {
1429- seg_frames += 1;
1430- }
1431- _ => {}
1432- }
1433- }
1434- }
1435- if seg_frames == 0 {
1436- eprintln!(
1437- "seed {seed}: aomenc wrote no segmentation-enabled frame, skipping attempt"
1438- );
1439- continue;
1440- }
1441- let frames = match decode_stream(&stream) {
1442- Err(e) => {
1443- let msg = e.to_string();
1444- assert!(
1445- msg.contains("unsupported"),
1446- "{name} failed outright, not a named refusal (seed {seed}): {msg}"
1447- );
1448- assert!(
1449- !msg.contains("segment_id symbol"),
1450- "{name} refused on the segmentation reader itself (seed {seed}): {msg}"
1451- );
1452- named_refusals += 1;
1453- eprintln!("seed {seed} refusal: {msg}");
1454- continue;
1455- }
1456- Ok(frames) => frames,
1457- };
1458- let ffmpeg_frames = if bit_depth == 10 {
1459- ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
1460- } else {
1461- ffmpeg_decode_sequence(&stream, width, height, frame_count)
1462- };
1463- assert_eq!(frames.len(), frame_count);
1464- let mismatched = frames
1465- .iter()
1466- .zip(&ffmpeg_frames)
1467- .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
1468- if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
1469- std::fs::write(&path, &stream).expect("writing pinned stream");
1470- eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
1471- }
1472- for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
1473- assert_eq!(
1474- got.y, want.y,
1475- "{name} frame {i} luma vs ffmpeg (seed {seed})"
1476- );
1477- assert_eq!(got.u, want.u, "{name} frame {i} U vs ffmpeg (seed {seed})");
1478- assert_eq!(got.v, want.v, "{name} frame {i} V vs ffmpeg (seed {seed})");
1479- }
1480- matched += 1;
1481- }
1482- assert!(
1483- matched > 0,
1484- "{name}: every attempt refused on other capabilities ({named_refusals} refusals); \
1485- the gate never exercised segmentation"
1486- );
1487- assert!(
1488- crate::decode::segment_id_hits() > 0,
1489- "{name}: {matched} pixel-exact matches but zero segment_id symbols fired -- \
1490- the reader is unexercised"
1491- );
1492- assert!(
1493- crate::decode::segment_ids_seen() >= 2,
1494- "{name}: {matched} pixel-exact matches but only {} distinct segment id(s) -- \
1495- every block landed in one segment, so nothing was actually segmented",
1496- crate::decode::segment_ids_seen()
1497- );
1498- // An inter-frame run must also have exercised the TEMPORAL path
1499- // (`seg_id_predicted` against the primary reference's saved map);
1500- // the key-frame-only run has no previous map by construction.
1501- if frame_count > 1 {
1502- assert!(
1503- crate::decode::segment_pred_hits() > 0,
1504- "{name}: {matched} pixel-exact matches over {frame_count} frames but zero \
1505- seg_id_predicted symbols -- the temporal_update path is unexercised"
1506- );
1507- }
1508- eprintln!(
1509- "{name}: {named_refusals} other-capability refusals, {matched} pixel-exact matches \
1510- out of {n_attempts}, segment_id_hits={}, distinct segment ids={}, \
1511- seg_id_predicted symbols={}",
1512- crate::decode::segment_id_hits(),
1513- crate::decode::segment_ids_seen(),
1514- crate::decode::segment_pred_hits()
1515- );
1516- }
1517-
1518- pub(super) fn edge32_gate(name: &str, flat_band: bool) {
1519- let _gate_lock = lock_gate_counters();
1520- if !have_ffmpeg() {
1521- eprintln!("SKIP {name}: no ffmpeg");
1522- return;
1523- }
1524- if !have_aomenc() {
1525- eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
1526- return;
1527- }
1528- // (width, height, frames, ten_bit, tile_columns_log2)
1529- let mut arms: Vec<(usize, usize, usize, bool, u32)> = Vec::new();
1530- for &(w, h) in &[(192usize, 80usize), (80usize, 192usize)] {
1531- arms.push((w, h, 1, false, 0));
1532- arms.push((w, h, 1, true, 0));
1533- }
1534- // The inter arm: >= 4 frames so the 32-level edge path in the INTER
1535- // tile walk is exercised too.
1536- arms.push((192, 80, 5, false, 0));
1537- // lane-golomb r9: the straddling-band arms, only under the ignored
1538- // `a_frame_edge_straddling_band_decodes_pixel_exact` name (they are
1539- // RED -- see that test's own comment for the stage bisection). Naming
1540- // them here rather than in a second copy of this gate keeps the
1541- // recipe, the counters and the refusal handling identical.
1542- if name == "a_frame_edge_straddling_band_decodes_pixel_exact" {
1543- arms.clear();
1544- for &tile_cols in &[0u32, 1] {
1545- arms.push((192, 68, 5, false, tile_cols));
1546- arms.push((192, 68, 5, true, tile_cols));
1547- arms.push((68, 192, 5, false, tile_cols));
1548- arms.push((68, 192, 5, true, tile_cols));
1549- }
1550- }
1551- // lane-golomb r8 MEASURED, arm STILL NOT added (every cq level is
1552- // vacuous, panicking or red -- each measured this round with
1553- // `arms.push((192, 68, 5, false))`, log
1554- // `$HOME/.cache/golomb-gate-r8{b,e,f,g}.log`):
1555- // * the r7 blocker IS fixed -- no attempt refuses "a reference
1556- // picture whose height does not match this frame's own true
1557- // size" any more (`decode.rs`'s comparison now uses the header's
1558- // frame height, per libaom's crop-dimension reference test).
1559- // * cq35 now refuses LATER, by another lane's name: "an inter
1560- // SB-level AB partition (HORZ_A/HORZ_B/VERT_A/VERT_B)" -- so the
1561- // arm compares nothing (class `counter-from-refused-stream`).
1562- // * cq40 PANICS in `decode_inter_block8`
1563- // (`from_switchable_symbol` handed a 4th symbol, `mc.rs:203`) =
1564- // lane-sub8's own open below-8x8 desync; a panic cannot be
1565- // tolerated as a named refusal.
1566- // * cq59 8-bit is RED: `frame 1 plane Y: 217 pixels differ, first
1567- // at row 60 col 170 (ours 172 vs ffmpeg 173)`, and the cq35
1568- // 10-bit twin is RED at `row 56 col 48 (ours 530 vs ffmpeg
1569- // 531)`. Both are +-1 bands in rows 56..63, i.e. the deblock/CDEF
1570- // bleed ABOVE the 4-px straddling row band (64..67) -- the same
1571- // shape as the `(68, 192, 5, false)` column defect below, so the
1572- // two are very likely ONE straddling-band reconstruction defect.
1573- // lane-golomb r7 MEASURED, arm NOT added (it would be vacuous or red):
1574- // a 68-px axis leaves the last superblock straddling by 4 px, the
1575- // shape `read_var_tx_size`'s `blk_row >= max_h_mi || blk_col >=
1576- // max_w_mi` early return exists for. With
1577- // `arms.push((192, 68, 5, false))` all EIGHT cq attempts refuse by
1578- // name -- "a reference picture whose height does not match this
1579- // frame's own true size" -- so the arm compares nothing (class
1580- // `counter-from-refused-stream`). With
1581- // `arms.push((68, 192, 5, false))` the gate goes RED on a real,
1582- // separate defect: `68x192 cq35 frames=5 10bit=false frame 1 plane Y:
1583- // 141 pixels differ, first at row 0 col 64 (ours 167 vs ffmpeg 166)
1584- // [edge32=[0,34,0,0,1,17,0,1]]` -- LUMA, inside the 4-px straddling
1585- // COLUMN. Both are unrelated to this round's chroma tx_type fix.
1586- let cqs: [u32; 8] = [35, 40, 45, 50, 55, 57, 59, 61];
1587- let mut totals = [0usize; 8];
1588- let mut compared = 0usize;
1589- // lane-t900 r15 (class `counter-from-refused-stream`): the aggregate
1590- // `compared` counter is carried by the single-tile arms alone, so the
1591- // `--tile-columns=1` twins were free to refuse every attempt and keep
1592- // the gate green. Counted separately and asserted below.
1593- let mut compared_multi_tile = 0usize;
1594- let mut refusals: Vec<String> = Vec::new();
1595- let straddle = name == "a_frame_edge_straddling_band_decodes_pixel_exact";
1596- let mut straddle_units = 0usize;
1597- for &(width, height, frame_count, ten_bit, tile_cols) in &arms {
1598- for &cq in &cqs {
1599- let duration = frame_count as f64 / 25.0;
1600- // `noise` (explicit seed) both defeats aomenc's
1601- // screen-content detection -- which otherwise refuses every
1602- // attempt at "a HORZ/VERT intra strip in a screen-content
1603- // frame" -- and keeps the RD search off flat NONE blocks.
1604- // Natural content over the whole superblock-aligned area,
1605- // with the 16-px straddling band left FLAT (`pad`): with
1606- // detail in that band aomenc always answers the edge bit with
1607- // SPLIT (measured: 178 edge bits, 178 of them SPLIT, over a
1608- // cq 35..61 sweep), so the HORZ/VERT arm this round guards
1609- // never fired. `noise` on top keeps screen-content detection
1610- // (and its palette-strip refusal) off.
1611- let (cw, ch) = (
1612- if flat_band && width % 64 != 0 {
1613- width - 16
1614- } else {
1615- width
1616- },
1617- if flat_band && height % 64 != 0 {
1618- height - 16
1619- } else {
1620- height
1621- },
1622- );
1623- let pad = if flat_band {
1624- format!("pad={width}:{height}:0:0:gray,")
1625- } else {
1626- String::new()
1627- };
1628- let source = format!(
1629- "testsrc2=size={cw}x{ch}:duration={duration}:rate=25,\
1630- {pad}noise=alls=6:allf=t+u:all_seed={cq}"
1631- );
1632- let pix = if ten_bit { "yuv420p10le" } else { "yuv420p" };
1633- let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1634- .args([
1635- "-v",
1636- "error",
1637- "-f",
1638- "lavfi",
1639- "-i",
1640- &source,
1641- "-pix_fmt",
1642- pix,
1643- "-strict",
1644- "-1",
1645- "-t",
1646- &format!("{duration}"),
1647- "-f",
1648- "yuv4mpegpipe",
1649- "-",
1650- ])
1651- .stdin(Stdio::null())
1652- .stdout(Stdio::piped())
1653- .stderr(Stdio::piped()), None, |c| c.output())
1654- .expect("ffmpeg failed to run");
1655- assert!(
1656- y4m.status.success(),
1657- "{name}: ffmpeg fixture: {}",
1658- String::from_utf8_lossy(&y4m.stderr)
1659- );
1660- let cq_arg = format!("--cq-level={cq}");
1661- let mut args: Vec<&str> = vec![
1662- "--codec=av1",
1663- "--passes=1",
1664- "--end-usage=q",
1665- &cq_arg,
1666- "--cpu-used=0",
1667- "--threads=1",
1668- "--row-mt=0",
1669- "--sb-size=64",
1670- "--enable-restoration=0",
1671- "--enable-palette=0",
1672- "--deltaq-mode=0",
1673- "--enable-intrabc=0",
1674- // Per-arm overrides go LAST (aomenc keeps the last
1675- // occurrence of a repeated --enable-* flag).
1676- "--enable-rect-partitions=1",
1677- "--enable-ab-partitions=0",
1678- "--enable-1to4-partitions=0",
1679- // 32, not the charter's 8: at 8 the sub-16 AB and
1680- // split-transform strip arms (still refused by name here)
1681- // fire before the 32-level edge is reached and EVERY
1682- // attempt refuses (measured). At 32 the edge block cannot
1683- // split, so aomenc is forced onto the gathered edge bit's
1684- // HORZ/VERT -- exactly the arm this round guards.
1685- "--min-partition-size=32",
1686- "--tune-content=film",
1687- "--max-partition-size=64",
1688- ];
1689- if ten_bit {
1690- args.extend_from_slice(&["--input-bit-depth=10", "--bit-depth=10"]);
1691- }
1692- let tile_arg = format!("--tile-columns={tile_cols}");
1693- if tile_cols > 0 {
1694- args.push(&tile_arg);
1695- }
1696- args.extend_from_slice(&["--obu", "-o", "-", "-"]);
1697- let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
1698- assert!(
1699- out.status.success(),
1700- "{name}: aomenc refused the fixture: {}",
1701- String::from_utf8_lossy(&out.stderr)
1702- );
1703- let stream = out.stdout;
1704- if ten_bit {
1705- assert_eq!(
1706- parsed_bit_depth(&stream),
1707- 10,
1708- "{name}: aomenc did not write a 10-bit sequence header"
1709- );
1710- }
1711- let tag = format!(
1712- "{width}x{height} cq{cq} frames={frame_count} 10bit={ten_bit} \
1713- tile_cols={tile_cols}"
1714- );
1715- let before = crate::decode::edge32_hits();
1716- let straddle_before = crate::decode::cdef_straddle_units();
1717- // lane-golomb r8: name the attempt BEFORE decoding it -- a
1718- // desync surfaces as a panic deep in mc.rs with no arm in the
1719- // message, and r8 spent a run bisecting arms by hand.
1720- if std::env::var_os("EC_GATE_VERBOSE").is_some() {
1721- eprintln!("{name}: attempting {tag}");
1722- }
1723- let decoded = match decode_stream(&stream) {
1724- Ok(frames) => frames,
1725- Err(e) => {
1726- let msg = e.to_string();
1727- assert!(
1728- msg.contains("unsupported"),
1729- "{name} failed outright, not a named refusal ({tag}): {msg}"
1730- );
1731- refusals.push(format!("{tag}: {msg}"));
1732- continue;
1733- }
1734- };
1735- let after = crate::decode::edge32_hits();
1736- let delta: Vec<usize> = (0..8).map(|i| after[i] - before[i]).collect();
1737- // The ENCODE's frame count, and it is PER ARM: the arm tuple's
1738- // `frame_count` field is what the y4m is built from
1739- // (`duration = frame_count / 25.0`, 38085, rendered with
1740- // `-t {duration}` at 38131) and this gate's aomenc carries no
1741- // `--limit` and no `--lag-in-frames`, so the stream codes exactly
1742- // `frame_count` frames (1 for the intra arms, 5 for the
1743- // inter/straddling ones). Asserted ABOVE the oracle call, so a
1744- // decode that dropped one reds naming the encode.
1745- assert_eq!(
1746- decoded.len(),
1747- frame_count,
1748- "{name}: {tag}: the encode codes {frame_count} frame(s), the decode showed {}",
1749- decoded.len()
1750- );
1751- let reference = if ten_bit {
1752- ffmpeg_decode_sequence_10bit(&stream, width, height, decoded.len())
1753- } else {
1754- ffmpeg_decode_sequence(&stream, width, height, decoded.len())
1755- };
1756- assert_eq!(
1757- decoded.len(),
1758- reference.len(),
1759- "{name}: {tag}: shown-frame count vs ffmpeg"
1760- );
1761- for (i, (ours, theirs)) in decoded.iter().zip(reference.iter()).enumerate() {
1762- for (plane, a, b, w) in [
1763- ("Y", &ours.y, &theirs.y, width),
1764- ("U", &ours.u, &theirs.u, width / 2),
1765- ("V", &ours.v, &theirs.v, width / 2),
1766- ] {
1767- if let Some(d) = a.iter().zip(b.iter()).position(|(x, y)| x != y) {
1768- let n = a.iter().zip(b.iter()).filter(|(x, y)| x != y).count();
1769- if std::env::var_os("EC_EDGE32_ROWS").is_some() {
1770- let mut per_row: std::collections::BTreeMap<usize, usize> =
1771- Default::default();
1772- for (k, (x, y)) in a.iter().zip(b.iter()).enumerate() {
1773- if x != y {
1774- *per_row.entry(k / w).or_default() += 1;
1775- }
1776- }
1777- eprintln!("{name}: {tag} plane {plane} diffs per row: {per_row:?}");
1778- }
1779- panic!(
1780- "{name}: {tag} frame {i} plane {plane}: {n} pixels differ, first \
1781- at row {} col {} (ours {} vs ffmpeg {}) [edge32={delta:?}]",
1782- d / w,
1783- d % w,
1784- a[d],
1785- b[d]
1786- );
1787- }
1788- assert_eq!(
1789- a.len(),
1790- b.len(),
1791- "{name}: {tag} frame {i} plane {plane}: ours has {} samples, \
1792- ffmpeg's has {} -- a short plane would zip-truncate the walk above \
1793- and hide a chroma-span defect",
1794- a.len(),
1795- b.len()
1796- );
1797- }
1798- }
1799- compared += 1;
1800- if tile_cols > 0 {
1801- compared_multi_tile += 1;
1802- }
1803- straddle_units += crate::decode::cdef_straddle_units() - straddle_before;
1804- for i in 0..8 {
1805- totals[i] += delta[i];
1806- }
1807- }
1808- }
1809- assert!(
1810- compared > 0,
1811- "{name}: every attempt hit a named refusal:\n{}",
1812- refusals.join("\n")
1813- );
1814- assert!(
1815- !straddle || compared_multi_tile > 0,
1816- "{name}: every `--tile-columns=1` attempt hit a named refusal -- the \
1817- multi-tile twins compared nothing:\n{}",
1818- refusals.join("\n")
1819- );
1820- assert!(
1821- !straddle || straddle_units > 0,
1822- "{name}: no FILTERED 8x8 CDEF unit crossed the cropped frame edge over \
1823- {compared} compared attempts -- the straddling arms proved nothing"
1824- );
1825- assert!(
1826- totals[0] + totals[1] + totals[4] + totals[5] > 0,
1827- "{name}: no frame-edge partition bit was read at all over \
1828- {compared} compared attempts -- the gate proved nothing"
1829- );
1830- // lane-golomb r3: the flat-band arm's ASSERT moved one level up. Until
1831- // r3 the last superblock row was reached through a 32-level edge bit
1832- // only because our own out-of-frame transform units had desynced the
1833- // stream; with that fixed, real aomenc answers a bottom-edge
1834- // superblock with the 64-level `PARTITION_HORZ` (and a right-edge one
1835- // with `PARTITION_VERT`) and the 32-level slots stay 0 on this
1836- // content. Slots 6/7 are the strips actually decoded at the edge.
1837- assert!(
1838- !flat_band || totals[6] > 0,
1839- "{name}: no 64x32 bottom-edge HORZ strip was decoded \
1840- (edge32={totals:?}, {compared} compared attempts)"
1841- );
1842- assert!(
1843- !flat_band || totals[7] > 0,
1844- "{name}: no 32x64 right-edge VERT strip was decoded \
1845- (edge32={totals:?}, {compared} compared attempts)"
1846- );
1847- eprintln!(
1848- "{name}: {compared} pixel-exact attempts, 32-level edge bits \
1849- [horz_or_vert={} split={}] bottom-HORZ={} right-VERT={}, 64-level edge bits \
1850- [horz_or_vert={} split={}] bottom-HORZ={} right-VERT={}, \
1851- {straddle_units} straddling CDEF units, {} named refusals",
1852- totals[0],
1853- totals[1],
1854- totals[2],
1855- totals[3],
1856- totals[4],
1857- totals[5],
1858- totals[6],
1859- totals[7],
1860- refusals.len()
1861- );
1862- for r in &refusals {
1863- eprintln!("{name} refusal: {r}");
1864- }
1865- }
1866-
1867- /// lane-tiles r11: every tile gate before this one turns the coding tools
1868- /// OFF (rect/ab partitions, tx-size search, cdef, restoration all `=0`)
1869- /// to isolate the per-tile loop, which is exactly the
1870- /// [[tool-disabled-in-every-gate]] shape -- a tile-edge defect in any of
1871- /// those tools is invisible to all of them. This one runs the BROAD tool
1872- /// set (rect + ab partitions, default tx search, cdef and loop
1873- /// restoration both on, deblocking left at its default so it filters
1874- /// across tile boundaries as the spec requires) over a real 2D tile grid,
1875- /// through `decode_stream` rather than the tile entry point, so it is the
1876- /// same path a caller decoding a file takes.
1877- ///
1878- /// 256x128 is four 64x64 superblocks wide and two tall, so
1879- /// `--tile-columns=1 --tile-rows=1` really yields a 2x2 grid and
1880- /// `--tile-columns=2` really yields 4 columns; both are asserted from the
1881- /// parsed `tile_info` rather than assumed, and the decoded-tile counter
1882- /// (`tile_hits`) is asserted at >= 4 per decoded frame so a stream whose
1883- /// header claims 4 tiles but whose decode only walked one cannot pass.
1884- // `#[track_caller]` so a failing assert names the calling arm's line, and
1885- // so `gate_coverage`'s body split (on `\n #[`) treats this helper's
1886- // recipe as its own gate rather than gluing it onto the preceding one.
1887- #[track_caller]
1888- // Signature mirrors the spec's per-call inputs; a parameter struct would only move them.
1889- #[allow(clippy::too_many_arguments)]
1890- pub(super) fn run_multi_tile_gate(
1891- name: &str,
1892- tile_cols_log2: u32,
1893- tile_rows_log2: u32,
1894- bit_depth: usize,
1895- frame_count: usize,
1896- extra: &[&str],
1897- // lane-tiles r12: the palette arm's own override proof. `true` asserts,
1898- // per attempt, that the arm's `--tune-content=screen --enable-palette=1`
1899- // really reached the encoder (frame header `allow_screen_content_tools`)
1900- // AND that a palette block fired at a TILE's left column -- the exact
1901- // block whose colour cache must not see the previous tile's colours.
1902- require_tile_left_palette: bool,
1903- // `None` = the shared `gradients_source`. The palette arm overrides it
1904- // with `smptebars`, the flat few-colour source the existing palette
1905- // gates use -- gradients never make aomenc pick a palette block.
1906- source_override: Option<&str>,
1907- ) {
1908- let _gate_lock = lock_gate_counters();
1909- if !have_ffmpeg() {
1910- eprintln!("SKIP {name}: no ffmpeg");
1911- return;
1912- }
1913- if !have_aomenc() {
1914- eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
1915- return;
1916- }
1917- let (width, height) = (256usize, 128usize);
1918- let expected_tiles = (1usize << tile_cols_log2) * (1usize << tile_rows_log2);
1919- let mut matched = 0u32;
1920- let mut named_refusals = 0u32;
1921- let mut uv_edge_suppressed = 0usize;
1922- let n_attempts: u32 = std::env::var("EC_TILES_GATE_ATTEMPTS")
1923- .ok()
1924- .and_then(|s| s.parse().ok())
1925- .unwrap_or(6);
1926- for attempt in 0..n_attempts {
1927- let seed = 42 + attempt;
1928- let duration = frame_count as f64 / 25.0;
1929- let source = match source_override {
1930- Some(src) => format!("{src}=size={width}x{height}:duration={duration}:rate=25"),
1931- None => {
1932- gradients_source(seed, width, height, &format!("duration={duration}:rate=25"))
1933- }
1934- };
1935- let pix_fmt = if bit_depth == 10 {
1936- "yuv420p10le"
1937- } else {
1938- "yuv420p"
1939- };
1940- let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1941- .args([
1942- "-v",
1943- "error",
1944- "-f",
1945- "lavfi",
1946- "-i",
1947- &source,
1948- "-pix_fmt",
1949- pix_fmt,
1950- "-strict",
1951- "-1",
1952- "-f",
1953- "yuv4mpegpipe",
1954- "-",
1955- ])
1956- .stdin(Stdio::null())
1957- .stdout(Stdio::piped())
1958- .stderr(Stdio::piped()), None, |c| c.output())
1959- .expect("ffmpeg failed to run");
1960- assert!(
1961- y4m.status.success(),
1962- "ffmpeg fixture: {}",
1963- String::from_utf8_lossy(&y4m.stderr)
1964- );
1965- let cols = format!("--tile-columns={tile_cols_log2}");
1966- let rows = format!("--tile-rows={tile_rows_log2}");
1967- let limit = format!("--limit={frame_count}");
1968- let depth_args: Vec<String> = if bit_depth == 10 {
1969- vec![
1970- "--input-bit-depth=10".to_owned(),
1971- "--bit-depth=10".to_owned(),
1972- ]
1973- } else {
1974- Vec::new()
1975- };
1976- let mut args: Vec<&str> = vec![
1977- "--codec=av1",
1978- "--passes=1",
1979- "--end-usage=q",
1980- "--cq-level=40",
1981- "--cpu-used=4",
1982- &limit,
1983- "--kf-max-dist=1000",
1984- "--threads=1",
1985- "--row-mt=0",
1986- // This decoder is 64x64-superblock only, and `--tile-columns`
1987- // splits on superblock boundaries, so 128x128 superblocks
1988- // would leave 256px only two tiles' worth of columns.
1989- "--sb-size=64",
1990- &cols,
1991- &rows,
1992- // The point of this gate: tools ON across tile edges.
1993- "--enable-rect-partitions=1",
1994- "--enable-ab-partitions=1",
1995- "--enable-cdef=1",
1996- "--enable-restoration=1",
1997- // Still off: capabilities this decoder refuses outright, which
1998- // would turn every attempt into a refusal and make the gate
1999- // vacuous rather than proving anything about tiles.
2000- "--enable-1to4-partitions=0",
crates/ec-av1/src/stream/tests/mod.rsmodified+1 -17
@@ -1,22 +1,6 @@
1 use super::*;1 use super::*;
2-use crate::encode::{Picture as Pic, encode_sequence_with_ctx};2+use crate::encode::Picture as Pic;
3-use crate::probe::run_with_stdin;
4-use std::process::{Command, Stdio};
5 3
6-mod gates_a;
7-mod gates_b;
8 mod layers;4 mod layers;
9 mod streaming;5 mod streaming;
10-mod support;
11-mod t01;
12-mod t02;
13-mod t03;
14-mod t04;
15-mod t05;
16-mod t06;
17-mod t07;
18-mod t08;
19-mod t09;
20-mod t10;
21 6
22-pub(crate) use gates_a::lock_gate_counters;
crates/ec-av1/src/stream/tests/support.rsdeleted+0 -4172

Diff too large; view file

@@ -1,4172 +0,0 @@
1-use super::*;
2-use super::gates_a::*;
3-
4- pub(super) fn test_card(width: usize, height: usize) -> Pic {
5- let mut picture = Pic::grey(width, height);
6- for row in 0..height {
7- for col in 0..width {
8- picture.y[row * width + col] = ((row * 7 + col * 11) % 251) as u16;
9- }
10- }
11- for row in 0..height / 2 {
12- for col in 0..width / 2 {
13- let i = row * width / 2 + col;
14- picture.u[i] = (100 + (col * 60 / (width / 2).max(1))) as u16;
15- picture.v[i] = (200 - (row * 80 / (height / 2).max(1))) as u16;
16- }
17- }
18- picture
19- }
20-
21- pub(super) fn panned_test_card(width: usize, height: usize, shift: i64) -> Pic {
22- let mut picture = Pic::grey(width, height);
23- for y in 0..height {
24- for x in 0..width {
25- let sx = (x as i64 - shift).rem_euclid(width as i64) as f64;
26- let gradient = sx * 200.0 / width as f64;
27- picture.y[y * width + x] = (20.0 + gradient).clamp(0.0, 255.0) as u16;
28- }
29- }
30- for y in 0..height / 2 {
31- for x in 0..width / 2 {
32- let sx = (x as i64 - shift / 2).rem_euclid((width / 2) as i64) as usize;
33- let i = y * width / 2 + x;
34- picture.u[i] = (100 + (sx * 60 / (width / 2))) as u16;
35- picture.v[i] = (200 - (y * 80 / (height / 2))) as u16;
36- }
37- }
38- picture
39- }
40-
41- /// One census attempt: encode `frames` frames of `source` with real
42- /// aomenc plus `extra` args, decode with THIS decoder, and return the
43- /// stream's byte length with either the picture count or the refusal (any
44- /// decode error) it produced. A census is about what the encoder emits,
45- /// so a refusal is data here, not a failure.
46- pub(super) fn census_attempt(
47- source: &str,
48- width: usize,
49- height: usize,
50- frames: usize,
51- extra: &[&str],
52- ) -> (usize, std::result::Result<usize, String>) {
53- let duration = format!("{}", frames as f64 / 25.0);
54- let src = format!("{source}=size={width}x{height}:rate=25");
55- let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
56- .args([
57- "-v",
58- "error",
59- "-f",
60- "lavfi",
61- "-i",
62- &src,
63- "-t",
64- &duration,
65- "-pix_fmt",
66- "yuv420p",
67- "-strict",
68- "-1",
69- "-f",
70- "yuv4mpegpipe",
71- "-",
72- ])
73- .stdin(Stdio::null())
74- .stdout(Stdio::piped())
75- .stderr(Stdio::piped()), None, |c| c.output())
76- .expect("ffmpeg failed to run");
77- assert!(
78- y4m.status.success(),
79- "ffmpeg refused the {width}x{height} fixture"
80- );
81- let limit = format!("--limit={frames}");
82- let mut args: Vec<String> = [
83- "--codec=av1",
84- "--passes=1",
85- "--end-usage=q",
86- "--threads=1",
87- "--row-mt=0",
88- "--kf-max-dist=9999",
89- "--lag-in-frames=0",
90- ]
91- .iter()
92- .map(|s| (*s).to_owned())
93- .collect();
94- args.push(limit);
95- args.extend(extra.iter().map(|s| (*s).to_owned()));
96- args.extend([
97- "--obu".to_owned(),
98- "-o".to_owned(),
99- "-".to_owned(),
100- "-".to_owned(),
101- ]);
102- let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
103- assert!(
104- out.status.success(),
105- "aomenc refused {args:?}: {}",
106- String::from_utf8_lossy(&out.stderr)
107- );
108- let stream = out.stdout;
109- let result = match decode_stream(&stream) {
110- Ok(pictures) => Ok(pictures.len()),
111- Err(e) => Err(e.to_string()),
112- };
113- (stream.len(), result)
114- }
115-
116- /// lane-av1seglvl: encode `frames` frames of `source` with real aomenc
117- /// plus `extra` args and return the raw `.obu` bytes -- the census's
118- /// half-sibling of [`census_attempt`] that keeps the STREAM instead of
119- /// only its decode verdict, so the caller can parse the frame headers'
120- /// segmentation tables themselves.
121- pub(super) fn encode_aomenc_stream(
122- source: &str,
123- width: usize,
124- height: usize,
125- frames: usize,
126- extra: &[&str],
127- ) -> Vec<u8> {
128- let duration = format!("{}", frames as f64 / 25.0);
129- let src = format!("{source}=size={width}x{height}:rate=25");
130- let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
131- .args([
132- "-v",
133- "error",
134- "-f",
135- "lavfi",
136- "-i",
137- &src,
138- "-t",
139- &duration,
140- "-pix_fmt",
141- "yuv420p",
142- "-strict",
143- "-1",
144- "-f",
145- "yuv4mpegpipe",
146- "-",
147- ])
148- .stdin(Stdio::null())
149- .stdout(Stdio::piped())
150- .stderr(Stdio::piped()), None, |c| c.output())
151- .expect("ffmpeg failed to run");
152- assert!(
153- y4m.status.success(),
154- "ffmpeg refused the {width}x{height} fixture"
155- );
156- let limit = format!("--limit={frames}");
157- let mut args: Vec<String> = [
158- "--codec=av1",
159- "--passes=1",
160- "--end-usage=q",
161- "--threads=1",
162- "--row-mt=0",
163- "--kf-max-dist=9999",
164- "--lag-in-frames=0",
165- ]
166- .iter()
167- .map(|s| (*s).to_owned())
168- .collect();
169- args.push(limit);
170- args.extend(extra.iter().map(|s| (*s).to_owned()));
171- args.extend([
172- "--obu".to_owned(),
173- "-o".to_owned(),
174- "-".to_owned(),
175- "-".to_owned(),
176- ]);
177- let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
178- assert!(
179- out.status.success(),
180- "aomenc refused {args:?}: {}",
181- String::from_utf8_lossy(&out.stderr)
182- );
183- out.stdout
184- }
185-
186- /// lane-av1seglvl: encode `frames` frames with a real TWO-PASS aomenc
187- /// (pass 1 writes the stats file into the session temp dir, pass 2
188- /// consumes it) and return the `.obu` bytes. This is the only shape that
189- /// reaches libaom's `is_stat_consumption_stage_twopass` segmentation
190- /// setup (`configure_static_seg_features`), so the census is not proven
191- /// over the encoder's whole reachable surface without it.
192- pub(super) fn encode_aomenc_stream_twopass(
193- source: &str,
194- width: usize,
195- height: usize,
196- frames: usize,
197- extra: &[&str],
198- ) -> Vec<u8> {
199- let duration = format!("{}", frames as f64 / 25.0);
200- let src = format!("{source}=size={width}x{height}:rate=25");
201- let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
202- .args([
203- "-v",
204- "error",
205- "-f",
206- "lavfi",
207- "-i",
208- &src,
209- "-t",
210- &duration,
211- "-pix_fmt",
212- "yuv420p",
213- "-strict",
214- "-1",
215- "-f",
216- "yuv4mpegpipe",
217- "-",
218- ])
219- .stdin(Stdio::null())
220- .stdout(Stdio::piped())
221- .stderr(Stdio::piped()), None, |c| c.output())
222- .expect("ffmpeg failed to run");
223- assert!(
224- y4m.status.success(),
225- "ffmpeg refused the {width}x{height} fixture"
226- );
227- let limit = format!("--limit={frames}");
228- let fpf =
229- std::env::temp_dir().join(format!("ec-av1-segldapass-{}.fpf", std::process::id()));
230- let mut base: Vec<String> = [
231- "--codec=av1",
232- "--passes=2",
233- "--end-usage=q",
234- "--threads=1",
235- "--row-mt=0",
236- "--kf-max-dist=9999",
237- "--lag-in-frames=0",
238- ]
239- .iter()
240- .map(|s| (*s).to_owned())
241- .collect();
242- base.push(limit);
243- base.extend(extra.iter().map(|s| (*s).to_owned()));
244- let mut pass1 = base.clone();
245- pass1.extend(["--pass=1".to_owned(), format!("--fpf={}", fpf.display())]);
246- pass1.extend([
247- "--obu".to_owned(),
248- "-o".to_owned(),
249- "/dev/null".to_owned(),
250- "-".to_owned(),
251- ]);
252- let out1 = run_with_stdin(Command::new(aomenc_path()).args(&pass1), &y4m.stdout);
253- assert!(
254- out1.status.success(),
255- "aomenc pass 1 refused {pass1:?}: {}",
256- String::from_utf8_lossy(&out1.stderr)
257- );
258- let mut pass2 = base;
259- pass2.extend(["--pass=2".to_owned(), format!("--fpf={}", fpf.display())]);
260- pass2.extend([
261- "--obu".to_owned(),
262- "-o".to_owned(),
263- "-".to_owned(),
264- "-".to_owned(),
265- ]);
266- let out2 = run_with_stdin(Command::new(aomenc_path()).args(&pass2), &y4m.stdout);
267- let _ = std::fs::remove_file(&fpf);
268- assert!(
269- out2.status.success(),
270- "aomenc pass 2 refused {pass2:?}: {}",
271- String::from_utf8_lossy(&out2.stderr)
272- );
273- out2.stdout
274- }
275-
276- /// lane-av1seglvl: walk every frame OBU of `stream` and tally which
277- /// `SEG_LVL` features the frame headers actually ENABLE, plus the shape
278- /// counters a census premise is asserted against: frames with
279- /// segmentation on, of which `update_map == 1` (the map is coded) and
280- /// `update_map == 0` (every block's id is INHERITED), and frames whose
281- /// table carries a real `SEG_LVL_ALT_Q` delta.
282- /// The last vector counts per SEGMENT-FEATURE INSTANCE (a frame with
283- /// ALT_Q on all 8 segments contributes 8), which is all the verdict
284- /// needs: only index `SEG_LVL_ALT_Q` may be non-zero.
285- /// Returns `(enabled_frames, update_map_frames, inherited_frames,
286- /// alt_q_frames, feature_instances: [usize; SEG_LVL_MAX])`.
287- #[allow(clippy::type_complexity)]
288- pub(super) fn segmentation_feature_census(
289- stream: &[u8],
290- ) -> (usize, usize, usize, usize, [usize; SEG_LVL_MAX]) {
291- let mut parser = Av1Parser::new();
292- let obus = parser
293- .parse_temporal_unit(stream)
294- .unwrap_or_else(|e| panic!("the census stream does not even parse: {e}"));
295- let mut enabled = 0usize;
296- let mut update_map = 0usize;
297- let mut inherited = 0usize;
298- let mut alt_q = 0usize;
299- let mut feature_frames = [0usize; SEG_LVL_MAX];
300- for obu in &obus {
301- if let ObuKind::Frame(header, _) = &obu.kind {
302- let seg = &header.segmentation;
303- if !seg.enabled {
304- continue;
305- }
306- enabled += 1;
307- if seg.update_map {
308- update_map += 1;
309- } else {
310- inherited += 1;
311- }
312- let mut any_q = false;
313- for segment in 0..MAX_SEGMENTS {
314- // Index loop mirrors the spec's per-position form over several offsets; an iterator would obscure it.
315- #[allow(clippy::needless_range_loop)]
316- for feature in 0..SEG_LVL_MAX {
317- if seg.feature_enabled[segment][feature] {
318- feature_frames[feature] += 1;
319- if feature == SEG_LVL_ALT_Q {
320- any_q = true;
321- }
322- }
323- }
324- }
325- if any_q {
326- alt_q += 1;
327- }
328- }
329- }
330- (enabled, update_map, inherited, alt_q, feature_frames)
331- }
332-
333- /// lane-interedge r1: one attempt of the inter frame-edge half-strip gate --
334- /// encode `width x height` with real aomenc (rect partitions ON, every other
335- /// lane's open tool pinned off), decode it, and return
336- /// `(inter_edge_strip hits, frames whose LUMA differs, frames whose CHROMA
337- /// differs)` against ffmpeg. A refusal or a decode error is a hard failure:
338- /// this recipe reached every size without one (measured r1).
339- pub(super) fn inter_edge_strip_attempt(
340- name: &str,
341- width: usize,
342- height: usize,
343- bit_depth: u32,
344- cq: u32,
345- frames: usize,
346- ) -> ([usize; 6], usize, usize) {
347- let duration = format!("{}", frames as f64 / 25.0);
348- let source = format!("mandelbrot=size={width}x{height}:rate=25");
349- let pix_fmt = if bit_depth == 10 {
350- "yuv420p10le"
351- } else {
352- "yuv420p"
353- };
354- let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
355- .args([
356- "-v",
357- "error",
358- "-f",
359- "lavfi",
360- "-i",
361- &source,
362- "-t",
363- &duration,
364- "-pix_fmt",
365- pix_fmt,
366- "-strict",
367- "-1",
368- "-f",
369- "yuv4mpegpipe",
370- "-",
371- ])
372- .stdin(Stdio::null())
373- .stdout(Stdio::piped())
374- .stderr(Stdio::piped()), None, |c| c.output())
375- .expect("ffmpeg failed to run");
376- assert!(
377- y4m.status.success(),
378- "{name}: ffmpeg refused the {width}x{height} {bit_depth}-bit fixture: {}",
379- String::from_utf8_lossy(&y4m.stderr)
380- );
381- let depth_arg = format!("--bit-depth={bit_depth}");
382- let input_depth_arg = format!("--input-bit-depth={bit_depth}");
383- let cq_arg = format!("--cq-level={cq}");
384- let limit_arg = format!("--limit={frames}");
385- let out = run_with_stdin(
386- Command::new(aomenc_path()).args([
387- "--codec=av1",
388- "--passes=1",
389- "--end-usage=q",
390- &cq_arg,
391- // cpu-used >= 1 keeps libaom on 64x64 superblocks at these
392- // sizes (`av1_select_sb_size`).
393- "--cpu-used=4",
394- "--threads=1",
395- "--row-mt=0",
396- "--kf-max-dist=9999",
397- &limit_arg,
398- // decode order == display order, so the compare below covers
399- // every frame the stream carries (class gate-blind-to-hidden-frames).
400- "--lag-in-frames=0",
401- &depth_arg,
402- &input_depth_arg,
403- // Rect partitions stay ON: the frame-edge strip is a FORCED
404- // (gathered) HORZ/VERT, but with rect coding off the encoder
405- // answers that gathered symbol SPLIT every time and no edge
406- // strip ever fires (lane-oddh r2's finding, re-measured r1).
407- "--enable-rect-partitions=1",
408- "--enable-ab-partitions=0",
409- "--enable-1to4-partitions=0",
410- "--min-partition-size=8",
411- "--max-partition-size=64",
412- // Other lanes' open gaps this recipe must not trip.
413- "--enable-palette=0",
414- "--enable-intrabc=0",
415- "--enable-warped-motion=0",
416- "--enable-obmc=0",
417- "--enable-masked-comp=0",
418- "--enable-interintra-comp=0",
419- "--enable-onesided-comp=0",
420- "--enable-interintra-wedge=0",
421- "--enable-smooth-interintra=0",
422- "--enable-ref-frame-mvs=0",
423- "--enable-angle-delta=0",
424- "--enable-cfl-intra=0",
425- "--enable-directional-intra=0",
426- "--enable-smooth-intra=0",
427- "--enable-paeth-intra=0",
428- "--enable-filter-intra=0",
429- "--enable-tx-size-search=0",
430- "--obu",
431- "-o",
432- "-",
433- "-",
434- ]),
435- &y4m.stdout,
436- );
437- assert!(
438- out.status.success(),
439- "aomenc refused: {}",
440- String::from_utf8_lossy(&out.stderr)
441- );
442- let stream = out.stdout;
443-
444- // Reset, never a delta: a refused attempt's hits must not leak into the
445- // next one (class counter-from-refused-stream).
446- crate::decode::reset_inter_edge_strip_hits();
447- let decoded = decode_stream(&stream).unwrap_or_else(|e| {
448- panic!("{name}: {width}x{height} {bit_depth}-bit cq {cq} did not decode: {e}")
449- });
450- let hits = crate::decode::inter_edge_strip_hits();
451- let reference = if bit_depth == 10 {
452- ffmpeg_decode_sequence_10bit(&stream, width, height, frames)
453- } else {
454- ffmpeg_decode_sequence(&stream, width, height, frames)
455- };
456- assert_eq!(
457- decoded.len(),
458- reference.len(),
459- "{name}: {width}x{height} {bit_depth}-bit cq {cq} frame count"
460- );
461- assert!(
462- decoded.len() >= frames,
463- "{name}: {width}x{height} {bit_depth}-bit cq {cq} decoded only {} frames",
464- decoded.len()
465- );
466- let (mut luma_bad, mut chroma_bad) = (0usize, 0usize);
467- for (ours, theirs) in decoded.iter().zip(&reference) {
468- if ours.y != theirs.y {
469- luma_bad += 1;
470- }
471- if ours.u != theirs.u || ours.v != theirs.v {
472- chroma_bad += 1;
473- }
474- }
475- (hits, luma_bad, chroma_bad)
476- }
477-
478- /// A GOP (key frame plus panned inter frames, so blocks actually take
479- /// motion) decodes bit-exact through `decode_stream` alone, threading its
480- /// own DPB rather than a test-supplied reference.
481- pub(super) fn gop_round_trips(width: usize, height: usize, fctx: &crate::decode::FrameCtx) {
482- let pictures: Vec<_> = (0..4)
483- .map(|i| panned_test_card(width, height, i * 3))
484- .collect();
485- let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
486- let decoded = decode_stream(&encoded.stream).unwrap();
487- assert_eq!(decoded.len(), encoded.frames.len());
488- for (i, (got, frame)) in decoded.iter().zip(&encoded.frames).enumerate() {
489- assert_eq!(
490- got.y, frame.reconstruction.y,
491- "{width}x{height} frame {i} luma"
492- );
493- assert_eq!(
494- got.u, frame.reconstruction.u,
495- "{width}x{height} frame {i} U"
496- );
497- assert_eq!(
498- got.v, frame.reconstruction.v,
499- "{width}x{height} frame {i} V"
500- );
501- }
502- }
503-
504- /// Firing-detection gates (single-ref envelope, temporal-MV, `comp_mode`,
505- /// `skip_mode`/compound) all read a process-global atomic counter delta
506- /// (`decode::ref_hits`/`tmv_hits`/`comp_mode_hits`/`skip_mode_hits`) to
507- /// prove a real block picked the feature under test, not just that a
508- /// header bit was set. Under `cargo test`'s default parallel run, a
509- /// SIBLING test's own decode bumps the same global counter mid-gate --
510- /// a false "fired" reading pixel-compares an attempt the gate would
511- /// otherwise `continue` past, on top of genuine defects that path may
512- /// still have. Serialising every counter-delta gate behind this one
513- /// mutex makes firing detection honest again (matches the existing
514- /// cdf-forwarding-gate flake shape, ledger `omp-liveness-pgrep-self-match`).
515- pub(super) static GATE_COUNTER_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
516-
517- /// lane-cdfflake: a cheap, dependency-free (FNV-1a, not cryptographic --
518- /// this is a load-bearing-identity fingerprint for flake triage, not a
519- /// security digest, so no `sha2` dep is pulled in) fixture fingerprint
520- /// for the cdf-forwarding gate's instrumentation below.
521- /// Reads a pinned fixture, asserting its length and FNV first, so a
522- /// swapped or truncated pin fails loudly instead of silently changing
523- /// what the gate measures.
524- pub(super) fn read_pin(path: &std::path::Path, len: usize, fnv: u64, name: &str) -> Vec<u8> {
525- let bytes = std::fs::read(path).unwrap_or_else(|e| {
526- panic!(
527- "{name}: pinned fixture {} is missing ({e}) -- the gate cannot run, \
528- which is a failure, not a skip",
529- path.display()
530- )
531- });
532- assert_eq!(bytes.len(), len, "{name}: fixture length moved");
533- assert_eq!(fnv1a64(&bytes), fnv, "{name}: fixture bytes moved");
534- bytes
535- }
536-
537- /// The bit depth the stream's OWN sequence header declares, read from
538- /// the bytes rather than taken from the gate's name or recipe (class
539- /// `helper-packs-u16-for-an-8-bit-stream`: aomdec's `--rawvideo`
540- /// writes 8 bits per sample for an 8-bit stream and 16 bits LE for a
541- /// high-bitdepth one, so a u16 packer turns every 8-bit compare into a
542- /// raw-SIZE failure that never looks at a sample).
543- pub(super) fn stream_bit_depth(stream: &[u8], name: &str) -> u8 {
544- let mut probe = Av1Parser::new();
545- let mut pos = 0usize;
546- while pos < stream.len() && probe.sequence_header().is_none() {
547- let obu = probe
548- .parse_obu(&stream[pos..])
549- .unwrap_or_else(|e| panic!("{name}: OBU at byte {pos} does not parse: {e:?}"));
550- pos += obu.total_size;
551- }
552- probe
553- .sequence_header()
554- .unwrap_or_else(|| panic!("{name}: the stream carries no sequence header OBU"))
555- .color_config
556- .bit_depth
557- }
558-
559- /// The stream's OWN `color_config.subsampling_x/y` (spec 5.5.2), read
560- /// from its bytes the same way [`stream_bit_depth`] reads the depth.
561- pub(super) fn stream_subsampling(stream: &[u8], name: &str) -> (u8, u8) {
562- let mut probe = Av1Parser::new();
563- let mut pos = 0usize;
564- while pos < stream.len() && probe.sequence_header().is_none() {
565- let obu = probe
566- .parse_obu(&stream[pos..])
567- .unwrap_or_else(|e| panic!("{name}: OBU at byte {pos} does not parse: {e:?}"));
568- pos += obu.total_size;
569- }
570- let cc = &probe
571- .sequence_header()
572- .unwrap_or_else(|| panic!("{name}: the stream carries no sequence header OBU"))
573- .color_config;
574- (cc.subsampling_x, cc.subsampling_y)
575- }
576-
577- /// The chroma shape a `(subsampling_x, subsampling_y)` pair means.
578- pub(super) fn chroma_shape(sx: u8, sy: u8) -> &'static str {
579- match (sx, sy) {
580- (1, 1) => "4:2:0",
581- (1, 0) => "4:2:2",
582- (0, 0) => "4:4:4",
583- (0, 1) => "4:4:0",
584- _ => "an unassigned subsampling",
585- }
586- }
587-
588- /// lane-av1oracleguard: HARD REFUSAL for the 4:2:0 ffmpeg oracle helpers.
589- ///
590- /// `ffmpeg_decode_sequence`, `ffmpeg_decode_sequence_10bit` and
591- /// `ffmpeg_decode_sequence_12bit` ask ffmpeg for `-pix_fmt yuv420p*` and
592- /// size chroma at `width * height / 4`. Those are the 4:2:0 numbers, so
593- /// for a stream that is NOT (1,1) ffmpeg does not fail -- it CONVERTS,
594- /// and the helper then slices a 4:2:0-shaped picture out of it. A 4:2:2
595- /// gate built on one of them compares the wrong planes and passes green:
596- /// the exact failure `lanes/av1subsizesweep.report.md` names. The correct
597- /// siblings (`ffmpeg_decode_sequence_422` / `_422_depth` /
598- /// `ffmpeg_decode_sequence_444`) exist and take the same bytes, so the
599- /// refusal points at them by name rather than leaving the caller to
600- /// rediscover the shape.
601- ///
602- /// Refused by SUBSAMPLING read from the stream's own sequence header, not
603- /// from the caller's `width`/`height` (class
604- /// `helper-assumes-the-shape-the-gate-name-implies`).
605- pub(super) fn assert_420_oracle_stream(stream: &[u8], helper: &str, sibling: &str) {
606- let (sx, sy) = stream_subsampling(stream, helper);
607- assert!(
608- (sx, sy) == (1, 1),
609- "{helper} REFUSED a ({sx},{sy}) stream: this helper asks ffmpeg for a 4:2:0 \
610- pix_fmt, which CONVERTS the stream's real {} chroma down to 4:2:0 instead of \
611- failing, then sizes chroma at `width * height / 4` rather than the {} shape. A \
612- gate built on it would compare converted planes against real ones and pass green. \
613- Use `{sibling}` for a ({sx},{sy}) stream.",
614- chroma_shape(sx, sy),
615- chroma_shape(sx, sy),
616- );
617- }
618-
619- /// lane-av1oracleguard: run `f`, return the panic MESSAGE it raised (or
620- /// `None` if it did not panic). The panic hook is silenced so a refusal
621- /// that PASSES its gate prints nothing -- the assertion is the return.
622- pub(super) fn panic_message<F: FnOnce()>(f: F) -> Option<String> {
623- let hook = std::panic::take_hook();
624- std::panic::set_hook(Box::new(|_| {}));
625- let caught = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f));
626- std::panic::set_hook(hook);
627- match caught {
628- Ok(()) => None,
629- Err(payload) => Some(
630- payload
631- .downcast_ref::<String>()
632- .cloned()
633- .or_else(|| payload.downcast_ref::<&str>().map(|s| (*s).to_string()))
634- .unwrap_or_else(|| "<non-string panic payload>".to_string()),
635- ),
636- }
637- }
638-
639- /// Packs decoded planes the way `aomdec --rawvideo` writes them for
640- /// `bit_depth`: 1 byte per sample at 8-bit, 2 bytes little-endian at
641- /// 10/12-bit. Plane order is Y, U, V at the frame's own subsampled
642- /// shape, which is exactly what rawvideo emits.
643- pub(super) fn pack_rawvideo(decoded: &[Pic], bit_depth: u8, name: &str) -> Vec<u8> {
644- let mut ours: Vec<u8> = Vec::new();
645- for (fi, f) in decoded.iter().enumerate() {
646- for p in [&f.y, &f.u, &f.v] {
647- if bit_depth == 8 {
648- for &s in p {
649- assert!(
650- s <= 0xff,
651- "{name}: decode-order frame {fi} carries the sample {s}, which an \
652- 8-bit stream cannot hold -- the stream is not the one this gate thinks \
653- it is"
654- );
655- ours.push(s as u8);
656- }
657- } else {
658- for &s in p {
659- ours.extend_from_slice(&s.to_le_bytes());
660- }
661- }
662- }
663- }
664- ours
665- }
666-
667- /// Decodes `stream` and the oracle's `aomdec --rawvideo` output and
668- /// requires every sample of every frame to agree, in decode order.
669- ///
670- /// `bit_depth` is the depth the CALLER believes the stream has; it is
671- /// asserted against the stream's own sequence header, so a gate that
672- /// hands this an 8-bit stream under a 10-bit label fails here by name
673- /// instead of dying on a raw-size mismatch that reads like a pixel bug.
674- pub(super) fn assert_rawvideo_matches(
675- obu: &std::path::Path,
676- stream: &[u8],
677- name: &str,
678- frames: usize,
679- bit_depth: u8,
680- ) {
681- let actual_depth = stream_bit_depth(stream, name);
682- assert_eq!(
683- actual_depth, bit_depth,
684- "{name}: the stream's sequence header says {actual_depth}-bit, the gate passed \
685- {bit_depth}-bit -- aomdec's --rawvideo writes {actual_depth} bits per sample for it, \
686- so packing for {bit_depth} compares nothing"
687- );
688- let dir = std::env::temp_dir().join(format!("ec-av1-{name}-{}", std::process::id()));
689- let _ = std::fs::remove_dir_all(&dir);
690- std::fs::create_dir_all(&dir).expect("scratch dir");
691- let raw = dir.join("aomdec.raw");
692- let out = crate::tool_cache::cached_output_io(Command::new(aomdec_path())
693- .args(["--codec=av1", "--rawvideo", "-o"])
694- .arg(&raw)
695- .arg(obu)
696- .stdin(Stdio::null())
697- .stdout(Stdio::piped())
698- .stderr(Stdio::piped()), None, |c| c.output())
699- .expect("aomdec failed to run");
700- assert!(
701- out.status.success(),
702- "{name}: the oracle aomdec refused the stream: {}",
703- String::from_utf8_lossy(&out.stderr)
704- );
705- let ref_raw = std::fs::read(&raw).expect("aomdec rawvideo output");
706- let _ = std::fs::remove_dir_all(&dir);
707- let decoded = decode_stream(stream).expect("decode for comparison");
708- let ours = pack_rawvideo(&decoded, bit_depth, name);
709- assert_eq!(
710- ours.len(),
711- ref_raw.len(),
712- "{name}: {bit_depth}-bit raw sizes differ -- ours packs {} bytes ({} samples at \
713- {} bit/sample), aomdec wrote {}",
714- ours.len(),
715- decoded
716- .iter()
717- .map(|f| f.y.len() + f.u.len() + f.v.len())
718- .sum::<usize>(),
719- bit_depth,
720- ref_raw.len()
721- );
722- assert_eq!(decoded.len(), frames, "{name}: frame count");
723- let first = ours
724- .iter()
725- .zip(&ref_raw)
726- .position(|(a, b)| a != b)
727- .unwrap_or(ours.len());
728- assert_eq!(
729- first,
730- ours.len(),
731- "{name}: {} bytes of decoded output differ from aomdec (first at {})",
732- ours.iter().zip(&ref_raw).filter(|(a, b)| a != b).count(),
733- first
734- );
735- }
736-
737- pub(super) fn fnv1a64(bytes: &[u8]) -> u64 {
738- let mut hash = 0xcbf29ce484222325u64;
739- for &b in bytes {
740- hash ^= b as u64;
741- hash = hash.wrapping_mul(0x100000001b3);
742- }
743- hash
744- }
745-
746- /// Whether ffmpeg is on PATH. Absence normally SKIPs, but
747- /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every
748- /// aomenc gate decodes its stream through ffmpeg and is meaningless
749- /// without it -- turns it into a hard failure. Without this the require
750- /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first
751- /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg
752- /// printed SKIP and reported green (class gate-skips-on-its-own-failure).
753- pub(super) fn have_ffmpeg() -> bool {
754- let present = Command::new("ffmpeg")
755- .arg("-version")
756- .stdout(Stdio::null())
757- .stderr(Stdio::null())
758- .status()
759- .is_ok_and(|s| s.success());
760- assert!(
761- present
762- || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none()
763- && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()),
764- "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH"
765- );
766- present
767- }
768-
769- /// Decodes `frames` concatenated 4:2:0 frames out of one AV1 OBU stream.
770- /// The frame-count diagnostic shared by the three `ffmpeg_decode_sequence*`
771- /// helpers (lane-av1pins5 r6).
772- ///
773- /// Before this, a caller that passed its OWN decode's length as the expected
774- /// count got `expected N 4:2:0 frames, ffmpeg said: ` -- with an EMPTY tail,
775- /// because ffmpeg ran at `-v error` and succeeded. The message named ffmpeg,
776- /// said nothing about where `N` came from, and sent the next reader hunting
777- /// ffmpeg for a count ffmpeg never chose.
778- ///
779- /// The class is MISATTRIBUTED RED, not silent pass: the helper's
780- /// `out.stdout.len() == frame_bytes * frames` assert fires unconditionally, so
781- /// a wrong count cannot pass -- it just fails while blaming the wrong
782- /// component. (Measured: `ffmpeg_decode_sequence(&s, 192, 128, 0)` panics
783- /// here, not silently.) Naming the real cause is the whole fix; no caller has
784- /// to change to benefit.
785- pub(super) fn frame_count_diagnosis(
786- format: &str,
787- frames: usize,
788- width: usize,
789- height: usize,
790- frame_bytes: usize,
791- got: usize,
792- stderr: &[u8],
793- ) -> String {
794- let actual = got.checked_div(frame_bytes).unwrap_or(0);
795- let leftover = if frame_bytes == 0 {
796- got
797- } else {
798- got % frame_bytes
799- };
800- format!(
801- "FRAME COUNT MISMATCH ({format} {width}x{height}): the caller passed \
802- `frames={frames}`, ffmpeg produced {actual} frame(s) ({got} bytes, \
803- {leftover} byte(s) not a whole frame, at {frame_bytes} B/frame).\n\
804- `frames` is the EXPECTED count the CALLER asserted -- it is NOT measured \
805- from ffmpeg, so it never had ffmpeg's agreement. If it came from our own \
806- decode_stream(), this is OUR decoder disagreeing with ffmpeg about how many \
807- frames the stream holds, and the fix is on OUR side, not ffmpeg's. ffmpeg \
808- itself exited cleanly{}.",
809- if stderr.is_empty() {
810- " with no diagnostics (`-v error`)"
811- } else {
812- ""
813- }
814- )
815- }
816-
817- pub(super) fn ffmpeg_decode_sequence(
818- stream: &[u8],
819- width: usize,
820- height: usize,
821- frames: usize,
822- ) -> Vec<Pic> {
823- // lane-av1oracleguard: this helper's numbers are 4:2:0's. A (1,0) or
824- // (0,0) stream would be CONVERTED by ffmpeg rather than refused.
825- assert_420_oracle_stream(
826- stream,
827- "ffmpeg_decode_sequence",
828- "ffmpeg_decode_sequence_422 (4:2:2) or ffmpeg_decode_sequence_444 (4:4:4)",
829- );
830- let out = run_with_stdin(
831- Command::new(ffmpeg_path()).args([
832- "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
833- ]),
834- stream,
835- );
836- assert!(
837- out.status.success(),
838- "ffmpeg refused the stream: {}",
839- String::from_utf8_lossy(&out.stderr)
840- );
841- let (luma, chroma) = (width * height, width * height / 4);
842- let frame_bytes = luma + 2 * chroma;
843- assert_eq!(
844- out.stdout.len(),
845- frame_bytes * frames,
846- "{}",
847- frame_count_diagnosis(
848- "4:2:0",
849- frames,
850- width,
851- height,
852- frame_bytes,
853- out.stdout.len(),
854- &out.stderr
855- )
856- );
857- (0..frames)
858- .map(|i| {
859- let base = i * frame_bytes;
860- Pic {
861- width,
862- height,
863- y: out.stdout[base..base + luma]
864- .iter()
865- .map(|&v| u16::from(v))
866- .collect(),
867- u: out.stdout[base + luma..base + luma + chroma]
868- .iter()
869- .map(|&v| u16::from(v))
870- .collect(),
871- v: out.stdout[base + luma + chroma..base + frame_bytes]
872- .iter()
873- .map(|&v| u16::from(v))
874- .collect(),
875- }
876- })
877- .collect()
878- }
879-
880- /// As [`ffmpeg_decode_sequence`], for a MONOCHROME stream: one 8-bit luma
881- /// plane per frame, exactly what `ffmpeg -pix_fmt gray -f rawvideo` writes
882- /// (lane-av1mono). Fed through [`run_with_stdin`] for the reason its doc
883- /// records.
884- pub(super) fn ffmpeg_decode_gray_sequence(
885- stream: &[u8],
886- width: usize,
887- height: usize,
888- frames: usize,
889- ) -> Vec<u8> {
890- let out = run_with_stdin(
891- Command::new(ffmpeg_path()).args([
892- "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "gray", "-",
893- ]),
894- stream,
895- );
896- assert!(
897- out.status.success(),
898- "ffmpeg refused the monochrome stream: {}",
899- String::from_utf8_lossy(&out.stderr)
900- );
901- assert_eq!(
902- out.stdout.len(),
903- width * height * frames,
904- "expected {frames} monochrome frames, ffmpeg said: {}",
905- String::from_utf8_lossy(&out.stderr)
906- );
907- out.stdout
908- }
909-
910- /// As [`ffmpeg_decode_sequence`], but for a `yuv420p10le` stream: samples
911- /// are 2-byte little-endian, one full 16-bit range regardless of the
912- /// stream's real 10-bit depth (ffmpeg's rawvideo muxer never packs to the
913- /// bit depth). The 8-bit helper above stays untouched -- every existing
914- /// gate depends on it.
915- ///
916- /// lane-av1oracledepth: the stream's OWN sequence header must parse
917- /// 10-bit, the same way `assert_12bit_sequence_header` covers the 12-bit
918- /// gates. A wrong-depth stream handed here would otherwise CONVERT
919- /// silently -- ffmpeg re-scales 8-bit samples into the 16-bit container
920- /// and sizes no plane differently -- so a gate could compare ffmpeg's
921- /// rescaled 8-bit planes against our 10-bit decode and read exact (class
922- /// `helper-assumes-the-shape-the-gate-name-implies`, the depth axis).
923- pub(super) fn ffmpeg_decode_sequence_10bit(
924- stream: &[u8],
925- width: usize,
926- height: usize,
927- frames: usize,
928- ) -> Vec<Pic> {
929- assert_420_oracle_stream(
930- stream,
931- "ffmpeg_decode_sequence_10bit",
932- "ffmpeg_decode_sequence_422_depth(.., 10, \"yuv422p10le\") (4:2:2); \
933- ffmpeg_decode_sequence_444_depth(.., 10, \"yuv444p10le\") (4:4:4)",
934- );
935- assert_eq!(
936- stream_bit_depth(stream, "ffmpeg_decode_sequence_10bit"),
937- 10,
938- "ffmpeg_decode_sequence_10bit REFUSED a stream whose own sequence header is not \
939- 10-bit -- ffmpeg converts it to yuv420p10le instead of failing, and the comparison \
940- would read a converted reference"
941- );
942- let out = run_with_stdin(
943- Command::new(ffmpeg_path()).args([
944- "-v",
945- "error",
946- "-f",
947- "obu",
948- "-i",
949- "-",
950- "-f",
951- "rawvideo",
952- "-pix_fmt",
953- "yuv420p10le",
954- "-",
955- ]),
956- stream,
957- );
958- assert!(
959- out.status.success(),
960- "ffmpeg refused the stream: {}",
961- String::from_utf8_lossy(&out.stderr)
962- );
963- let (luma, chroma) = (width * height, width * height / 4);
964- let frame_samples = luma + 2 * chroma;
965- let frame_bytes = frame_samples * 2;
966- assert_eq!(
967- out.stdout.len(),
968- frame_bytes * frames,
969- "{}",
970- frame_count_diagnosis(
971- "4:2:0 10-bit",
972- frames,
973- width,
974- height,
975- frame_bytes,
976- out.stdout.len(),
977- &out.stderr
978- )
979- );
980- fn le16(bytes: &[u8]) -> Vec<u16> {
981- bytes
982- .as_chunks::<2>().0.iter()
983- .map(|c| u16::from_le_bytes([c[0], c[1]]))
984- .collect()
985- }
986- (0..frames)
987- .map(|i| {
988- let base = i * frame_bytes;
989- Pic {
990- width,
991- height,
992- y: le16(&out.stdout[base..base + luma * 2]),
993- u: le16(&out.stdout[base + luma * 2..base + luma * 2 + chroma * 2]),
994- v: le16(&out.stdout[base + luma * 2 + chroma * 2..base + frame_bytes]),
995- }
996- })
997- .collect()
998- }
999-
1000- /// Builds a `gradients` lavfi source string with colours derived from
1001- /// `seed`, not left to the filter's own default.
1002- ///
1003- /// Measured (lane-fixdet r1): ffmpeg's `gradients` source IGNORES its
1004- /// `seed=` parameter for colour selection -- five encodes of an
1005- /// identical command line (same `seed=`, same everything) produced five
1006- /// different fixtures, because the unset `c0..c9` stops are randomized
1007- /// from something other than that seed. Every one of this file's ~20
1008- /// gate fixtures built a `gradients` source this way, so none of them
1009- /// had a reproducible input: a pin captured from one run could not be
1010- /// regenerated, and "attempt N failed" was as likely to be a different
1011- /// fixture as a different decode outcome.
1012- ///
1013- /// Freezing the colours outright (as the earliest four gates below do,
1014- /// hand-picking `c0=red:c1=blue:c2=green`) fixes reproducibility but
1015- /// throws away the per-attempt content variety the sweep gates need to
1016- /// make features (OBMC, warp, wedge, ...) fire at all -- this repo's own
1017- /// `sampler-decorrelated-gate` class. So: derive `c0..c3` deterministically
1018- /// FROM the seed with a plain integer hash, and keep passing `seed=`
1019- /// itself too, so a future ffmpeg that actually honours it only adds
1020- /// more variety, never removes the determinism this buys.
1021- pub(super) fn gradients_source(seed: u32, width: usize, height: usize, tail: &str) -> String {
1022- fn hash_color(seed: u32, salt: u32) -> String {
1023- let h = seed
1024- .wrapping_mul(2_654_435_761)
1025- .wrapping_add(salt.wrapping_mul(0x9E37_79B9))
1026- ^ (seed.rotate_left(13));
1027- format!("0x{:06x}", h & 0x00ff_ffff)
1028- }
1029- let (c0, c1, c2, c3) = (
1030- hash_color(seed, 0),
1031- hash_color(seed, 1),
1032- hash_color(seed, 2),
1033- hash_color(seed, 3),
1034- );
1035- format!(
1036- "gradients=size={width}x{height}:c0={c0}:c1={c1}:c2={c2}:c3={c3}:seed={seed}:{tail}"
1037- )
1038- }
1039-
1040- /// Encodes a real libaom-av1 stream (via ffmpeg's own encoder, not this
1041- /// crate's) with the same reduced-partition flags lane-av1adst's r6
1042- /// probe found still select `ADST_ADST`/`ADST_DCT`/`DCT_ADST` on
1043- /// gradient content (TX_SET_INTRA_2), and decodes it with
1044- /// [`decode_stream`] -- lifting the round-2 refusal is only real if it
1045- /// gets past an encoder this crate never wrote a byte of.
1046- pub(super) fn libaom_encode(lavfi: &str, width: usize, height: usize, crf: u32) -> Option<Vec<u8>> {
1047- libaom_encode_with(lavfi, width, height, crf, &[])
1048- }
1049-
1050- /// As [`libaom_encode`], with extra encoder args appended -- used to pin
1051- /// a deterministic stream (`-threads 1` etc., since libaom's `cpu-used 8`
1052- /// RD search is not otherwise stable run-to-run on this box, and lavfi
1053- /// `gradients` needs its own `seed=` for the same reason) and to gate
1054- /// individual feature flags (`-enable-cdef 0`) a given fixture needs off.
1055- pub(super) fn libaom_encode_with(
1056- lavfi: &str,
1057- width: usize,
1058- height: usize,
1059- crf: u32,
1060- extra: &[&str],
1061- ) -> Option<Vec<u8>> {
1062- let mut args = vec![
1063- "-v",
1064- "error",
1065- "-f",
1066- "lavfi",
1067- "-i",
1068- lavfi,
1069- "-frames:v",
1070- "1",
1071- "-pix_fmt",
1072- "yuv420p",
1073- "-c:v",
1074- "libaom-av1",
1075- ];
1076- let crf_str = crf.to_string();
1077- args.extend(["-crf", &crf_str]);
1078- args.extend([
1079- "-cpu-used",
1080- "8",
1081- "-enable-rect-partitions",
1082- "0",
1083- "-enable-ab-partitions",
1084- "0",
1085- "-enable-1to4-partitions",
1086- "0",
1087- "-enable-angle-delta",
1088- "0",
1089- "-enable-cfl-intra",
1090- "0",
1091- ]);
1092- args.extend(extra.iter().copied());
1093- args.extend(["-f", "obu", "-"]);
1094- let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1095- .args(&args)
1096- .stdin(Stdio::null())
1097- .stdout(Stdio::piped())
1098- .stderr(Stdio::piped()), None, |c| c.output())
1099- .expect("ffmpeg failed to run");
1100- if !out.status.success() {
1101- eprintln!(
1102- "ffmpeg refused to encode {lavfi} at {width}x{height}: {}",
1103- String::from_utf8_lossy(&out.stderr)
1104- );
1105- return None;
1106- }
1107- Some(out.stdout)
1108- }
1109-
1110- /// As [`ffmpeg_decode_sequence`], for a 4:4:4 stream: chroma planes are
1111- /// FULL resolution (`yuv444p` rawvideo), the shape lane-av1-llinter's
1112- /// lossless profile-1 fixture codes.
1113- pub(super) fn ffmpeg_decode_sequence_444(
1114- stream: &[u8],
1115- width: usize,
1116- height: usize,
1117- frames: usize,
1118- ) -> Vec<Pic> {
1119- ffmpeg_decode_sequence_444_depth(stream, width, height, frames, 8, "yuv444p")
1120- }
1121-
1122- /// lane-av1oracledepth: the depth-generic 4:4:4 oracle comparator -- the
1123- /// [`ffmpeg_decode_sequence_422_depth`] twin for full-resolution chroma.
1124- /// `yuv444p`, `yuv444p10le` or `yuv444p12le`, with the container width
1125- /// taken from `depth` itself (8 -> one byte per sample; 10/12 -> a 16-bit
1126- /// LE container on BOTH sides, so ours and ffmpeg's are directly
1127- /// comparable sample for sample and nothing narrows). Until this helper
1128- /// existed a 10/12-bit 4:4:4 gate had to fall back to the 8-bit
1129- /// `ffmpeg_decode_sequence_444`, which ffmpeg converts at `yuv444p`
1130- /// instead of refusing, or to a raw hand-rolled spawn (class
1131- /// `helper-assumes-the-shape-the-gate-name-implies`, the depth axis).
1132- ///
1133- /// Refused by SHAPE read from the stream's own sequence header, like its
1134- /// 4:2:0 siblings: `(0,0)` only, so a 4:2:2 or 4:2:0 stream handed here
1135- /// cannot have ffmpeg silently convert it.
1136- pub(super) fn ffmpeg_decode_sequence_444_depth(
1137- stream: &[u8],
1138- width: usize,
1139- height: usize,
1140- frames: usize,
1141- depth: u8,
1142- pix_fmt: &str,
1143- ) -> Vec<Pic> {
1144- assert!(
1145- matches!(depth, 8 | 10 | 12),
1146- "lane-av1oracledepth: ffmpeg_decode_sequence_444_depth takes 8, 10 or 12, got {depth}"
1147- );
1148- let (sx, sy) = stream_subsampling(stream, "ffmpeg_decode_sequence_444_depth");
1149- assert!(
1150- (sx, sy) == (0, 0),
1151- "ffmpeg_decode_sequence_444_depth REFUSED a ({sx},{sy}) stream: this helper asks \
1152- ffmpeg for a 4:4:4 pix_fmt, which CONVERTS the stream's real {} chroma instead of \
1153- failing, then slices full-resolution planes from converted bytes. \
1154- ffmpeg_decode_sequence_422_depth handles (1,0); ffmpeg_decode_sequence handles \
1155- (1,1).",
1156- chroma_shape(sx, sy)
1157- );
1158- assert_eq!(
1159- stream_bit_depth(stream, "ffmpeg_decode_sequence_444_depth"),
1160- depth,
1161- "ffmpeg_decode_sequence_444_depth REFUSED a stream whose own sequence header is \
1162- not {depth}-bit -- ffmpeg would convert it to {pix_fmt} instead of failing"
1163- );
1164- let out = run_with_stdin(
1165- Command::new(ffmpeg_path()).args([
1166- "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", pix_fmt, "-",
1167- ]),
1168- stream,
1169- );
1170- assert!(
1171- out.status.success(),
1172- "ffmpeg refused the 4:4:4 stream ({pix_fmt}): {}",
1173- String::from_utf8_lossy(&out.stderr)
1174- );
1175- let plane = width * height;
1176- let bps = if depth == 8 { 1 } else { 2 };
1177- let frame_bytes = 3 * plane * bps;
1178- assert_eq!(
1179- out.stdout.len(),
1180- frame_bytes * frames,
1181- "{}",
1182- frame_count_diagnosis(
1183- if depth == 8 {
1184- "4:4:4"
1185- } else {
1186- "4:4:4 high depth"
1187- },
1188- frames,
1189- width,
1190- height,
1191- frame_bytes,
1192- out.stdout.len(),
1193- &out.stderr
1194- )
1195- );
1196- (0..frames)
1197- .map(|i| {
1198- let base = i * frame_bytes;
1199- let samples = |off: usize| -> Vec<u16> {
1200- let slice = &out.stdout[base + off..base + off + plane * bps];
1201- if bps == 1 {
1202- slice.iter().map(|&v| u16::from(v)).collect()
1203- } else {
1204- slice
1205- .as_chunks::<2>().0.iter()
1206- .map(|c| u16::from_le_bytes([c[0], c[1]]))
1207- .collect()
1208- }
1209- };
1210- Pic {
1211- width,
1212- height,
1213- y: samples(0),
1214- u: samples(plane * bps),
1215- v: samples(2 * plane * bps),
1216- }
1217- })
1218- .collect()
1219- }
1220-
1221- /// lane-av1422lift: as [`ffmpeg_decode_sequence`] (4:2:0 8-bit) and
1222- /// [`ffmpeg_decode_sequence_444`], for a 4:2:2 stream: `yuv422p`
1223- /// rawvideo, whose chroma planes are HALF WIDTH and FULL HEIGHT -- the
1224- /// `w/2 * h` shape the whole per-axis port exists to produce. A helper
1225- /// that computed the chroma span 4:2:0-style would make every 4:2:2
1226- /// gate compare half the oracle's bytes and pass, so the span is
1227- /// asserted against the byte count below, not assumed.
1228- pub(super) fn ffmpeg_decode_sequence_422(
1229- stream: &[u8],
1230- width: usize,
1231- height: usize,
1232- frames: usize,
1233- ) -> Vec<Pic> {
1234- ffmpeg_decode_sequence_422_depth(stream, width, height, frames, 8, "yuv422p")
1235- }
1236-
1237- /// lane-av1422lift: the depth-generic 4:2:2 oracle comparator --
1238- /// `yuv422p`, `yuv422p10le` or `yuv422p12le`, with the container width
1239- /// taken from `depth` itself (8 -> one byte per sample; 10/12 -> a
1240- /// 16-bit LE container on BOTH sides, so ours and ffmpeg's are directly
1241- /// comparable sample for sample and nothing narrows).
1242- pub(super) fn ffmpeg_decode_sequence_422_depth(
1243- stream: &[u8],
1244- width: usize,
1245- height: usize,
1246- frames: usize,
1247- depth: u8,
1248- pix_fmt: &str,
1249- ) -> Vec<Pic> {
1250- assert!(
1251- matches!(depth, 8 | 10 | 12),
1252- "lane-av1422lift: ffmpeg_decode_sequence_422_depth takes 8, 10 or 12, got {depth}"
1253- );
1254- let out = run_with_stdin(
1255- Command::new("ffmpeg").args([
1256- "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", pix_fmt, "-",
1257- ]),
1258- stream,
1259- );
1260- assert!(
1261- out.status.success(),
1262- "ffmpeg refused the 4:2:2 stream ({pix_fmt}): {}",
1263- String::from_utf8_lossy(&out.stderr)
1264- );
1265- let (luma, chroma) = (width * height, width.div_ceil(2) * height);
1266- let bps = if depth == 8 { 1 } else { 2 };
1267- let frame_bytes = (luma + 2 * chroma) * bps;
1268- assert_eq!(
1269- out.stdout.len(),
1270- frame_bytes * frames,
1271- "{}",
1272- frame_count_diagnosis(
1273- "4:2:2",
1274- frames,
1275- width,
1276- height,
1277- frame_bytes,
1278- out.stdout.len(),
1279- &out.stderr
1280- )
1281- );
1282- (0..frames)
1283- .map(|i| {
1284- let base = i * frame_bytes;
1285- let samples = |off: usize, n: usize| -> Vec<u16> {
1286- let slice = &out.stdout[base + off..base + off + n * bps];
1287- if bps == 1 {
1288- slice.iter().map(|&v| u16::from(v)).collect()
1289- } else {
1290- slice
1291- .as_chunks::<2>().0.iter()
1292- .map(|c| u16::from_le_bytes([c[0], c[1]]))
1293- .collect()
1294- }
1295- };
1296- Pic {
1297- width,
1298- height,
1299- y: samples(0, luma),
1300- u: samples(luma * bps, chroma),
1301- v: samples((luma + chroma) * bps, chroma),
1302- }
1303- })
1304- .collect()
1305- }
1306-
1307- /// lane-av1422lift: the shared body of every 4:2:2 exactness gate this
1308- /// lane adds, and the answer to "a byte-exact 4:2:2 gate can still be
1309- /// vacuous".
1310- ///
1311- /// Before lane-av1422census422 the per-plane coefficient-unit census was
1312- /// armed at `ss_x == 0 && ss_y == 0` only, so on a 4:2:2 stream
1313- /// `census_nonsub_units()` read `[0, 0, 0]` BY CONSTRUCTION -- a gate
1314- /// could have been green while the decode walked nothing at all. The
1315- /// census is now armed for `(ss_x == 0 || ss_y == 0)`, so the delta
1316- /// asserted here is a real measurement of the walk this stream caused:
1317- /// every plane must show a non-zero number of transform units AND of
1318- /// units that coded at least one coefficient.
1319- ///
1320- /// Four things are asserted per frame, in this order:
1321- ///
1322- /// 1. the decoded frame's dimensions, and that its chroma planes are
1323- /// `round_ss(w, 1) * round_ss(h, 0)` -- half width, FULL height. A
1324- /// decoder that kept 4:2:0 plane allocation while walking 4:2:2
1325- /// entropy would pass a per-sample compare against a 4:2:0-sized
1326- /// oracle; this is the shape assertion that closes that hole, and it
1327- /// is asserted against the DECODED frame, never against the gate's
1328- /// own name.
1329- /// 2. the depth, read out of the stream's own sequence header.
1330- /// 3. per-plane, per-frame byte-exactness against ffmpeg's rawvideo of
1331- /// the same bytes at the depth-correct pixel format. Frame N of ours
1332- /// against frame N of ffmpeg's: `decode_stream` returns DISPLAY order
1333- /// and so does ffmpeg's rawvideo muxer, so a hidden alt-ref does not
1334- /// shift the pairing (the decode-order-vs-display-order trap the
1335- /// out-of-process corpus comparator has to solve separately).
1336- /// 4. the census delta, asserted once for the whole stream rather than
1337- /// per frame, because the counters are cumulative per thread.
1338- ///
1339- /// `require_coded` is false ONLY for a cell whose identity IS that it
1340- /// codes nothing -- `422_allskip_2f.obu`, whose whole point is that
1341- /// the inter frame reads no residual and the pre-port decoder read
1342- /// PHANTOM units there. Demanding coded units on it would be
1343- /// demanding the defect; its caller asserts the all-skip property
1344- /// directly instead.
1345- pub(super) fn assert_422_stream_pixel_exact(
1346- name: &str,
1347- stream: &[u8],
1348- width: usize,
1349- height: usize,
1350- frames: usize,
1351- depth: u8,
1352- require_coded: bool,
1353- ) -> ([usize; 3], [usize; 3]) {
1354- let _gate_lock = lock_gate_counters();
1355- assert_eq!(
1356- stream_bit_depth(stream, name),
1357- depth,
1358- "{name}: the stream's OWN sequence header does not say {depth} bit"
1359- );
1360- let before = crate::decode::census_nonsub_units();
1361- let before_coded = crate::decode::census_nonsub_coded();
1362- let ours = decode_stream(stream)
1363- .unwrap_or_else(|e| panic!("{name}: decode_stream refused a real 4:2:2 stream: {e}"));
1364- assert_eq!(ours.len(), frames, "{name}: decoded frame count");
1365- for (i, f) in ours.iter().enumerate() {
1366- assert_eq!(
1367- (f.width, f.height),
1368- (width, height),
1369- "{name}: frame {i} dimensions"
1370- );
1371- assert_eq!(
1372- (f.u.len(), f.v.len()),
1373- (width.div_ceil(2) * height, width.div_ceil(2) * height),
1374- "{name}: frame {i} chroma planes are {}/{} samples -- 4:2:2 is HALF WIDTH and \
1375- FULL HEIGHT ({width}/2 x {height}); a quarter-height plane means the decode kept \
1376- a 4:2:0 allocation",
1377- f.u.len(),
1378- f.v.len()
1379- );
1380- }
1381- let pix_fmt = match depth {
1382- 8 => "yuv422p",
1383- 10 => "yuv422p10le",
1384- 12 => "yuv422p12le",
1385- other => panic!("{name}: no ffmpeg pixel format mapped for depth {other}"),
1386- };
1387- let theirs =
1388- ffmpeg_decode_sequence_422_depth(stream, width, height, frames, depth, pix_fmt);
1389- for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
1390- for (plane, ours_plane, theirs_plane) in
1391- [("Y", &a.y, &b.y), ("U", &a.u, &b.u), ("V", &a.v, &b.v)]
1392- {
1393- assert_eq!(
1394- ours_plane.len(),
1395- theirs_plane.len(),
1396- "{name}: {plane} plane {i} is {} samples against ffmpeg's {} -- the 4:2:2 chroma \
1397- span is wrong on one of the two sides",
1398- ours_plane.len(),
1399- theirs_plane.len()
1400- );
1401- if let Some(bad) = ours_plane
1402- .iter()
1403- .zip(theirs_plane)
1404- .position(|(x, y)| x != y)
1405- {
1406- panic!(
1407- "{name}: {plane} differs from ffmpeg at frame {i} sample {bad} ({} vs {}; \
1408- {} of {} samples differ)",
1409- ours_plane[bad],
1410- theirs_plane[bad],
1411- ours_plane
1412- .iter()
1413- .zip(theirs_plane)
1414- .filter(|(x, y)| x != y)
1415- .count(),
1416- ours_plane.len()
1417- );
1418- }
1419- }
1420- }
1421- let units = crate::decode::census_nonsub_units();
1422- let coded = crate::decode::census_nonsub_coded();
1423- let delta: [usize; 3] = std::array::from_fn(|p| units[p] - before[p]);
1424- let coded_delta: [usize; 3] = std::array::from_fn(|p| coded[p] - before_coded[p]);
1425- for (p, plane) in ["luma", "U", "V"].into_iter().enumerate() {
1426- assert!(
1427- delta[p] > 0,
1428- "{name}: the {plane} plane read ZERO coefficient units across the whole stream -- \
1429- this byte-exact compare is vacuous with respect to 4:2:2 (class \
1430- gate-blind-to-feature)"
1431- );
1432- if require_coded {
1433- assert!(
1434- coded_delta[p] > 0,
1435- "{name}: the {plane} plane coded ZERO coefficient units across the whole \
1436- stream -- every unit took the all-zero early return, so no coefficient path \
1437- was exercised"
1438- );
1439- }
1440- }
1441- eprintln!(
1442- "{name}: byte-exact vs ffmpeg ({pix_fmt}, {frames} frames); census delta \
1443- units=[{}, {}, {}] coded=[{}, {}, {}]",
1444- delta[0], delta[1], delta[2], coded_delta[0], coded_delta[1], coded_delta[2]
1445- );
1446- (delta, coded_delta)
1447- }
1448-
1449- /// `(subsampling_x, subsampling_y, bit_depth)` out of the stream's OWN
1450- /// sequence header. A gate that claims to exercise a subsampling-specific
1451- /// path must assert this from the parsed header, not from the recipe that
1452- /// produced the fixture: the recipe can drift (or a wrong `--pix_fmt`
1453- /// argument can silently produce a different subsampling) and every other
1454- /// assertion would then pass vacuously.
1455- pub(super) fn subsampled_header_shape(stream: &[u8], name: &str) -> (u8, u8, usize) {
1456- let mut parser = Av1Parser::new();
1457- let mut pos = 0usize;
1458- let mut shape = None;
1459- while pos < stream.len() {
1460- let obu = parser
1461- .parse_obu(&stream[pos..])
1462- .unwrap_or_else(|e| panic!("{name}: OBU does not parse: {e:?}"));
1463- if obu.total_size == 0 {
1464- break;
1465- }
1466- pos += obu.total_size;
1467- if let ObuKind::SequenceHeader(seq) = obu.kind {
1468- shape = Some((
1469- seq.color_config.subsampling_x,
1470- seq.color_config.subsampling_y,
1471- seq.color_config.bit_depth as usize,
1472- ));
1473- }
1474- }
1475- shape.unwrap_or_else(|| panic!("{name}: no sequence header parsed"))
1476- }
1477-
1478- /// lane-av1gates444: the live 4:4:4 LOSSY cell the chroma-format sweep
1479- /// measured EXACT 4/4 and left unpinned. The recipe is the sweep's own
1480- /// §6.2 encode, reproduced LIVE against the oracle `aomenc` rather than
1481- /// from a pin, because the claim these three gates carry is a property
1482- /// of the *decoder* at a geometry, not of a blob:
1483- /// ```text
1484- /// ffmpeg -f lavfi -i "testsrc2=size=<W>x<H>:rate=25" -frames:v 4 \
1485- /// -pix_fmt yuv444p -f yuv4mpegpipe - | \
1486- /// aomenc --codec=av1 --profile=1 --passes=1 --end-usage=q --cq-level=20 \
1487- /// --cpu-used=2 --threads=1 --row-mt=0 --lag-in-frames=0 \
1488- /// --kf-max-dist=100 --limit=4 --obu -o - -
1489- /// ```
1490- /// `rate=25` is load-bearing (testsrc2's pattern is time-parameterised)
1491- /// and `--limit=4` is the sweep's frame count: at `--limit=6` the same
1492- /// recipe emits 7674 / 11465 / 19121 bytes instead of the sweep's
1493- /// 5938 / 8945 / 15239, i.e. a different stream than the one measured.
1494- /// `--profile=1` is what makes the source 4:4:4 at all.
1495- ///
1496- /// Every assertion here is a non-vacuity assertion first and a pixel
1497- /// compare second. The frame count, the per-frame geometry and the
1498- /// FULL-RESOLUTION chroma plane length are asserted because a truncated
1499- /// or 4:2:0-shaped decode can pass a lenient compare; the
1500- /// `rect4_inter_own_chroma444_hits()` reach assert is there because the
1501- /// class these cells belong to is the 4:4:4-only own-chroma-extent route
1502- /// in [`decode_inter_block`]'s `around_c` (a 4:2:0 stream of the same
1503- /// content leaves it at 0), and a counter at 0 would mean the gate
1504- /// measured a different route than it names.
1505- /// The guard is [`have_aomenc`], which probes first and asserts LAST with
1506- /// the env escape: with `EC_AV1_REQUIRE_AOMENC` set, a missing oracle is
1507- /// a hard failure naming the path it looked for, and a batch run cannot
1508- /// report green off three skipped gates. With it unset the `None` below is
1509- /// a developer-only convenience for a checkout without an oracle -- it is
1510- /// the ONLY way this gate can return without measuring, and it announces
1511- /// itself on stderr naming the env var that would make it a failure.
1512- /// (It used to return an empty `Vec` that the caller turned into a silent
1513- /// early `return`: the same green, reached through a second exit nobody
1514- /// was reading.)
1515- pub(super) fn encode_444_lossy_live(name: &str, w: usize, h: usize) -> Option<Vec<u8>> {
1516- if !have_aomenc() {
1517- eprintln!(
1518- "SKIP {name}: no aomenc oracle at {} -- set EC_AV1_REQUIRE_AOMENC=1 to make this \
1519- a failure, or run scripts/build-aom-oracle.sh",
1520- aomenc_path().display()
1521- );
1522- return None;
1523- }
1524- let source = format!("testsrc2=size={w}x{h}:rate=25");
1525- let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1526- .args([
1527- "-v",
1528- "error",
1529- "-f",
1530- "lavfi",
1531- "-i",
1532- &source,
1533- "-frames:v",
1534- "4",
1535- "-pix_fmt",
1536- "yuv444p",
1537- "-f",
1538- "yuv4mpegpipe",
1539- "-",
1540- ])
1541- .stdin(Stdio::null())
1542- .stdout(Stdio::piped())
1543- .stderr(Stdio::piped()), None, |c| c.output())
1544- .expect("ffmpeg failed to run");
1545- assert!(
1546- y4m.status.success(),
1547- "{name}: ffmpeg refused the {w}x{h} 4:4:4 source: {}",
1548- String::from_utf8_lossy(&y4m.stderr)
1549- );
1550- let out = run_with_stdin(
1551- Command::new(aomenc_path()).args([
1552- "--codec=av1",
1553- "--profile=1",
1554- "--passes=1",
1555- "--end-usage=q",
1556- "--cq-level=20",
1557- "--cpu-used=2",
1558- "--threads=1",
1559- "--row-mt=0",
1560- "--lag-in-frames=0",
1561- "--kf-max-dist=100",
1562- "--limit=4",
1563- "--obu",
1564- "-o",
1565- "-",
1566- "-",
1567- ]),
1568- &y4m.stdout,
1569- );
1570- assert!(
1571- out.status.success(),
1572- "{name}: aomenc refused the {w}x{h} 4:4:4 lossy recipe: {}",
1573- String::from_utf8_lossy(&out.stderr)
1574- );
1575- assert!(
1576- !out.stdout.is_empty(),
1577- "{name}: aomenc produced no OBU for {w}x{h} -- a zero-length stream would \
1578- decode to nothing and the compare below would compare nothing"
1579- );
1580- Some(out.stdout)
1581- }
1582-
1583- /// lane-av1-loss64: the generator for the two gates below -- a deterministic
1584- /// 1-frame lossless superblock-128 aomenc stream of `testsrc2`. `extra`
1585- /// flags land last (aomenc keeps the LAST occurrence of a repeated flag).
1586- /// The recipe is the one lanes/av1rect14.report.md section 2 measured
1587- /// (`--lossless=1 --sb-size=128 --enable-1to4-partitions=1`); the
1588- /// `--min-partition-size` override is what steers the bottom superblock
1589- /// row's RD into overhanging 64x64 `NONE` blocks (the shape the first fix
1590- /// clips) or, at 8, keeps sub-8x8 partitions out of the second gate's
1591- /// stream so the whole frame is decodable.
1592- pub(super) fn lossless_sb128_testsrc2(width: usize, height: usize, extra: &[&str]) -> Vec<u8> {
1593- let mut ff = Command::new("ffmpeg");
1594- let out = crate::tool_cache::cached_output_io(ff
1595- .args(["-v", "error", "-f", "lavfi", "-i"])
1596- .arg(format!("testsrc2=s={width}x{height}:r=25"))
1597- .args([
1598- "-frames:v",
1599- "1",
1600- "-pix_fmt",
1601- "yuv420p",
1602- "-strict",
1603- "-1",
1604- "-f",
1605- "yuv4mpegpipe",
1606- "-",
1607- ])
1608- .stdin(Stdio::null())
1609- .stdout(Stdio::piped())
1610- .stderr(Stdio::piped()), None, |c| c.output())
1611- .expect("ffmpeg failed to run");
1612- assert!(
1613- out.status.success(),
1614- "ffmpeg failed for testsrc2 {width}x{height}"
1615- );
1616- let y4m = out.stdout;
1617- let out = run_with_stdin(
1618- Command::new(aomenc_path())
1619- .args(["--codec=av1", "--bit-depth=8", "--input-bit-depth=8"])
1620- .args([
1621- "--passes=1",
1622- "--cpu-used=0",
1623- "--lag-in-frames=0",
1624- "--kf-max-dist=1",
1625- "--limit=1",
1626- "--threads=1",
1627- "--tile-columns=0",
1628- "--lossless=1",
1629- "--sb-size=128",
1630- "--enable-1to4-partitions=1",
1631- ])
1632- .args(extra)
1633- .args(["--obu", "-o", "-", "-"]),
1634- &y4m,
1635- );
1636- assert!(
1637- out.status.success(),
1638- "aomenc failed: {}",
1639- String::from_utf8_lossy(&out.stderr)
1640- );
1641- out.stdout
1642- }
1643-
1644- /// Path to a real `aomenc` build carrying the reference options this
1645- /// fixture needs (`--max-partition-size`, `--enable-tx-size-search`,
1646- /// `--loopfilter-control`) -- this box's `ffmpeg` links a libaom too old
1647- /// to expose `enable-tx-size-search`/`loopfilter-control` through its
1648- /// own `-aom-params` passthrough (probed live: "Cannot find aom
1649- /// option"), so [`a_real_aomenc_filter_intra_stream_decodes_pixel_exact`]
1650- /// shells out to the standalone binary instead of ffmpeg's libaom-av1
1651- /// wrapper every other test here uses. `EC_AV1_AOMENC` overrides the
1652- /// default dev-build path; the test skips (not fails) when neither this
1653- /// nor `ffmpeg` is present.
1654- pub(super) fn aomenc_path() -> std::path::PathBuf {
1655- if let Some(p) = std::env::var_os("EC_AV1_AOMENC") {
1656- return std::path::PathBuf::from(p);
1657- }
1658- // The oracle used to live only under `/tmp`, which this box's tmpfs
1659- // guard reclaims -- when it did, all 20 aomenc gates below went
1660- // silently vacuous (SKIP, suite still green). The durable location
1661- // is provisioned by `scripts/build-aom-oracle.sh`; the `/tmp` path
1662- // stays last as a legacy fallback.
1663- let mut candidates = Vec::new();
1664- if let Some(home) = std::env::var_os("HOME") {
1665- candidates.push(std::path::PathBuf::from(&home).join(".cache/aom-oracle/build/aomenc"));
1666- }
1667- candidates.push("/tmp/libaom-src/build/encoder/aomenc".into());
1668- candidates
1669- .iter()
1670- .find(|p| p.is_file())
1671- .cloned()
1672- .unwrap_or_else(|| candidates.remove(0))
1673- }
1674-
1675- /// Whether the aomenc oracle is present. Absence normally SKIPs (a
1676- /// checkout without the oracle should still run the rest of the suite),
1677- /// but `EC_AV1_REQUIRE_AOMENC=1` turns it into a hard failure so a batch
1678- /// run cannot report green off 20 skipped gates.
1679- /// Where a pinned stream lives. `fixtures/` is a symlink to a durable
1680- /// directory outside the repo, so a pin captured in one session is still
1681- /// there in the next; a session scratchpad is not (tmpfs reaps it, and
1682- /// four pins were silently dead because of that).
1683- pub(super) fn pin_dir() -> std::path::PathBuf {
1684- if let Some(p) = std::env::var_os("EC_AV1_PIN_DIR") {
1685- return std::path::PathBuf::from(p);
1686- }
1687- std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1688- .join("../../fixtures")
1689- .canonicalize()
1690- .unwrap_or_else(|_| std::path::PathBuf::from("fixtures"))
1691- }
1692-
1693- /// A COMMITTED pin: `crates/ec-av1/fixtures/<name>`, which travels in the
1694- /// tarball and is therefore present on every runner. `pin_dir()` resolves
1695- /// to the gitignored root `fixtures/`, so a pin written there is lost when
1696- /// the machine's scratchpad is reaped -- three gates sat at `rc=0` having
1697- /// tested nothing for exactly that reason (lane-av1pins). Falls back to
1698- /// `pin_dir()` so a locally re-captured stream still overrides.
1699- /// Read a pin that a gate cannot proceed without. A missing pin is a
1700- /// HARD failure naming the path and the generator, never a raw io panic
1701- /// and never a silent skip: `EC_AV1_GATE_DUMP_PIN` points the gate at a
1702- /// freshly captured stream, and a runner without the committed copy must
1703- /// say so instead of reporting green having tested nothing.
1704- pub(super) fn require_pin(path: &std::path::Path, name: &str) -> Vec<u8> {
1705- std::fs::read(path).unwrap_or_else(|e| {
1706- panic!(
1707- "no pinned bytes at {} ({e}) -- set EC_AV1_GATE_DUMP_PIN to a freshly \
1708- captured stream, or restore the committed copy at \
1709- crates/ec-av1/fixtures/{name}",
1710- path.display()
1711- )
1712- })
1713- }
1714-
1715- pub(super) fn crate_pin(name: &str) -> std::path::PathBuf {
1716- let in_crate = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1717- .join("fixtures")
1718- .join(name);
1719- if in_crate.is_file() {
1720- in_crate
1721- } else {
1722- pin_dir().join(name)
1723- }
1724- }
1725-
1726- pub(super) fn have_aomenc() -> bool {
1727- let present = aomenc_path().is_file();
1728- assert!(
1729- present || std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none(),
1730- "EC_AV1_REQUIRE_AOMENC is set but no aomenc at {} -- run scripts/build-aom-oracle.sh",
1731- aomenc_path().display()
1732- );
1733- present
1734- }
1735-
1736- /// lane-av1oracleskip: the probe for the ORACLE COMPARER, in the same
1737- /// shape as [`have_ffmpeg`] -- probe first, then `assert!` LAST, with the
1738- /// env escape -- and it prints its own SKIP so a caller cannot skip the
1739- /// compare silently.
1740- ///
1741- /// Why this exists: thirteen gates wrapped their oracle arm in a bare
1742- /// `if aomdec_path().is_file()`, and that shape had NO env escape at all.
1743- /// An oracle build with `aomenc` but no `aomdec` beside it (or an
1744- /// `EC_AV1_AOMDEC` override pointing at a moved path) made the gate
1745- /// encode, decode, assert its geometry and its counters, and then quietly
1746- /// never compare -- green having measured nothing, with no line in the
1747- /// output to notice. Nine of the thirteen printed a SKIP in an `else` and
1748- /// four printed nothing at all; both are the same defect, and both are
1749- /// closed by one probe.
1750- ///
1751- /// With `EC_AV1_REQUIRE_AOMENC` (or the aomdec-specific
1752- /// `EC_AV1_REQUIRE_AOMDEC`) set, the absence is a HARD failure naming the
1753- /// path that was looked for -- that is the batch-run guarantee, and it is
1754- /// what the bare `is_file()` could not give. With it unset the SKIP below
1755- /// is printed and the gate still passes: that remains a developer-only
1756- /// convenience for a checkout without an oracle, never evidence.
1757- pub(super) fn aomdec_available(name: &str) -> bool {
1758- let present = aomdec_path().is_file();
1759- let require = std::env::var_os("EC_AV1_REQUIRE_AOMDEC").is_some()
1760- || std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_some();
1761- assert!(
1762- present || !require,
1763- "{name}: no oracle aomdec at {} -- the pixel compare this gate exists for would be \
1764- skipped, and EC_AV1_REQUIRE_AOMDEC/EC_AV1_REQUIRE_AOMENC is set. Build the oracle \
1765- with scripts/build-aom-oracle.sh, or point EC_AV1_AOMDEC at a real aomdec.",
1766- aomdec_path().display()
1767- );
1768- if !present {
1769- eprintln!(
1770- "SKIP {name}: no oracle aomdec at {} -- the pixel compare is NOT running (set \
1771- EC_AV1_REQUIRE_AOMDEC=1 to make this a failure)",
1772- aomdec_path().display()
1773- );
1774- }
1775- present
1776- }
1777-
1778- // lane-av1cmpaudit2: this thread's oracle override, set by
1779- // `set_oracle_path` and consulted by `aomdec_path` ahead of the env var.
1780- //
1781- // It is thread-local for the same reason `FINAL_DUMP_PREFIX` is: the
1782- // control test `every_oracle_comparator_reds_on_a_one_byte_wrong_oracle`
1783- // has to hand the helpers a DELIBERATELY WRONG oracle, and a
1784- // process-global `std::env::set_var` could not do that safely -- the
1785- // crate forbids `unsafe_code`, and even where it did not, one test's
1786- // tampered oracle would leak into every sibling test's comparison
1787- // running on another thread. A thread-local override confines the wrong
1788- // oracle to the one thread that asked for it.
1789- thread_local! {
1790- static ORACLE_PATH: std::cell::RefCell<Option<std::path::PathBuf>> =
1791- const { std::cell::RefCell::new(None) };
1792- }
1793-
1794- /// Points this thread's oracle helpers at `path`. `None` restores the
1795- /// real `aomdec`.
1796- pub(super) fn set_oracle_path(path: Option<std::path::PathBuf>) {
1797- ORACLE_PATH.with(|c| *c.borrow_mut() = path);
1798- }
1799-
1800- // lane-film10fix: this thread's ffmpeg override, set by
1801- // `set_ffmpeg_path` and consulted by `ffmpeg_path` ahead of the bare
1802- // name. Same shape and same reason as `ORACLE_PATH` above: the control
1803- // test `every_ffmpeg_comparator_reds_on_a_one_sample_wrong_ffmpeg` has
1804- // to hand the `ffmpeg_decode_sequence*` helpers a DELIBERATELY WRONG
1805- // reference, and a process-global PATH edit would leak that wrong
1806- // reference into every sibling test decoding on another thread. The
1807- // crate forbids `unsafe_code`, so `std::env::set_var` is not available
1808- // either; a thread-local confines the tamper to the one thread.
1809- thread_local! {
1810- static FFMPEG_PATH: std::cell::RefCell<Option<std::path::PathBuf>> =
1811- const { std::cell::RefCell::new(None) };
1812- }
1813-
1814- /// Points this thread's `ffmpeg_decode_sequence*` helpers at `path`.
1815- /// `None` restores the real `ffmpeg` on PATH.
1816- pub(super) fn set_ffmpeg_path(path: Option<std::path::PathBuf>) {
1817- FFMPEG_PATH.with(|c| *c.borrow_mut() = path);
1818- }
1819-
1820- /// The `ffmpeg` every reference helper in this module spawns.
1821- pub(super) fn ffmpeg_path() -> std::path::PathBuf {
1822- if let Some(p) = FFMPEG_PATH.with(|c| c.borrow().clone()) {
1823- return p;
1824- }
1825- std::path::PathBuf::from("ffmpeg")
1826- }
1827-
1828- /// The instrumented `aomdec` beside the `aomenc` oracle
1829- /// (`scripts/build-aom-oracle.sh` + `scripts/instrument-aom-oracle.sh`).
1830- pub(super) fn aomdec_path() -> std::path::PathBuf {
1831- if let Some(p) = ORACLE_PATH.with(|c| c.borrow().clone()) {
1832- return p;
1833- }
1834- if let Some(p) = std::env::var_os("EC_AV1_AOMDEC") {
1835- return std::path::PathBuf::from(p);
1836- }
1837- aomenc_path().with_file_name("aomdec")
1838- }
1839-
1840- /// Decodes `stream` with both this decoder and the instrumented oracle
1841- /// `aomdec`, and compares EVERY decoded frame in DECODE order --
1842- /// including the hidden (`show_frame == 0`) alt-ref frames no other gate
1843- /// in this repo can see, because `decode_stream` only pushes shown
1844- /// frames and `ffmpeg -f obu ... rawvideo` only emits shown frames
1845- /// (class gate-blind-to-hidden-frames: a hidden frame's defect surfaces
1846- /// only as drift on some later shown frame, if at all).
1847- ///
1848- /// Both sides write the final, post-deblock/CDEF/LR/superres frame as it
1849- /// is stored into the reference buffer (`EC_AV1_FINAL_DUMP`, ours in
1850- /// `decode_stream`, the oracle's in rung 12 of
1851- /// `scripts/instrument-aom-oracle.sh`), 8-bit as u8 / high bitdepth as
1852- /// u16 LE. Returns `(frames_decoded, hidden_frames)`.
1853- pub(super) fn decode_all_frames_vs_oracle(stream: &[u8], name: &str) -> (usize, usize) {
1854- let dir = std::env::temp_dir().join(format!("ec-av1-{name}-{}", std::process::id()));
1855- let _ = std::fs::remove_dir_all(&dir);
1856- std::fs::create_dir_all(&dir).expect("scratch dir");
1857- let obu = dir.join("in.obu");
1858- std::fs::write(&obu, stream).expect("writing the stream");
1859- let aom_prefix = dir.join("aom");
1860- let out = crate::tool_cache::cached_output_io(Command::new(aomdec_path())
1861- .args(["--codec=av1", "-o"])
1862- .arg(dir.join("out.y4m"))
1863- .arg(&obu)
1864- .env("EC_AV1_FINAL_DUMP", &aom_prefix)
1865- .stdin(Stdio::null())
1866- .stdout(Stdio::piped())
1867- .stderr(Stdio::piped()), None, |c| c.output())
1868- .expect("aomdec failed to run");
1869- assert!(
1870- out.status.success(),
1871- "{name}: the oracle aomdec refused the stream: {}",
1872- String::from_utf8_lossy(&out.stderr)
1873- );
1874- let count_dumps = |prefix: &std::path::Path| -> usize {
1875- let mut n = 0usize;
1876- while std::path::PathBuf::from(format!("{}.f{n}", prefix.display())).is_file() {
1877- n += 1;
1878- }
1879- n
1880- };
1881- let oracle_frames = count_dumps(&aom_prefix);
1882- assert!(
1883- oracle_frames > 0,
1884- "{name}: the oracle wrote no EC_AV1_FINAL_DUMP frames -- rung 12 of \
1885- scripts/instrument-aom-oracle.sh is missing from {}",
1886- aomdec_path().display()
1887- );
1888- let ours_prefix = dir.join("ours");
1889- set_final_dump_prefix(Some(ours_prefix.display().to_string()));
1890- let decoded = decode_stream(stream);
1891- set_final_dump_prefix(None);
1892- let shown = decoded
1893- .unwrap_or_else(|e| panic!("{name}: this decoder refused the stream: {e}"))
1894- .len();
1895- let our_frames = count_dumps(&ours_prefix);
1896- assert_eq!(
1897- our_frames, oracle_frames,
1898- "{name}: decoded {our_frames} frames in decode order, the oracle decoded \
1899- {oracle_frames}"
1900- );
1901- for i in 0..oracle_frames {
1902- let want =
1903- std::fs::read(format!("{}.f{i}", aom_prefix.display())).expect("oracle dump");
1904- let got = std::fs::read(format!("{}.f{i}", ours_prefix.display())).expect("our dump");
1905- assert_eq!(
1906- got.len(),
1907- want.len(),
1908- "{name}: decode-order frame {i} is {} bytes, the oracle's is {}",
1909- got.len(),
1910- want.len()
1911- );
1912- if let Some(at) = got.iter().zip(&want).position(|(a, b)| a != b) {
1913- let differing = got.iter().zip(&want).filter(|(a, b)| a != b).count();
1914- panic!(
1915- "{name}: decode-order frame {i} of {oracle_frames} ({shown} shown, {} \
1916- hidden) differs from the oracle at byte {at} (ours {} vs {}), {differing} \
1917- bytes differ -- stream pinned at {}",
1918- oracle_frames - shown,
1919- got[at],
1920- want[at],
1921- obu.display()
1922- );
1923- }
1924- }
1925- let hidden = oracle_frames - shown;
1926- let _ = std::fs::remove_dir_all(&dir);
1927- (oracle_frames, hidden)
1928- }
1929-
1930- /// lane-av1422anom: a COUNTING oracle comparison.
1931- ///
1932- /// [`assert_rawvideo_matches`] is the right tool for "these must be equal"
1933- /// and the wrong tool for a lane that has to classify many cells: it
1934- /// panics on the first differing byte, so it answers one cell per process
1935- /// and cannot report a magnitude. This returns the count instead.
1936- ///
1937- /// It exists because the previous lane's per-cell counter was tautological:
1938- /// it packed our own decoded samples into `ours` and then compared `ours`
1939- /// against the same samples, never touching the oracle's bytes, so it
1940- /// reported "0 wrong" on every cell including one that differs from
1941- /// `aomdec` in 1612 samples. [`the_counting_oracle_diff_reports_a_real_difference`]
1942- /// below is the test that keeps that mistake from recurring.
1943- ///
1944- /// Returns `(wrong_y, wrong_u, wrong_v, frames_total, frames_exact)`, or
1945- /// `None` when the two sides are not byte-comparable at all (a size
1946- /// mismatch, which is a different failure and must not read as "exact").
1947- /// `flip` flips ONE bit of the ORACLE's own bytes before comparing, so
1948- /// [`the_counting_oracle_diff_detects_one_flipped_oracle_byte`] can prove
1949- /// the comparison still reads the oracle on a stream that is now exact.
1950- pub(super) fn count_rawvideo_diffs(
1951- stream: &[u8],
1952- name: &str,
1953- flip: Option<usize>,
1954- ) -> Option<(usize, usize, usize, usize, usize)> {
1955- let dir = std::env::temp_dir().join(format!("ec-av1-{name}-{}", std::process::id()));
1956- let _ = std::fs::remove_dir_all(&dir);
1957- std::fs::create_dir_all(&dir).expect("scratch dir");
1958- let obu = dir.join("in.obu");
1959- std::fs::write(&obu, stream).expect("writing the stream");
1960- let raw = dir.join("aomdec.raw");
1961- let out = crate::tool_cache::cached_output_io(Command::new(aomdec_path())
1962- .args(["--codec=av1", "--rawvideo", "-o"])
1963- .arg(&raw)
1964- .arg(&obu)
1965- .stdin(Stdio::null())
1966- .stdout(Stdio::piped())
1967- .stderr(Stdio::piped()), None, |c| c.output())
1968- .expect("aomdec failed to run");
1969- assert!(
1970- out.status.success(),
1971- "{name}: the oracle aomdec refused the stream: {}",
1972- String::from_utf8_lossy(&out.stderr)
1973- );
1974- let mut want = std::fs::read(&raw).expect("aomdec rawvideo output");
1975- if let Some(i) = flip {
1976- assert!(
1977- i < want.len(),
1978- "{name}: flip index {i} is past the oracle's {} bytes",
1979- want.len()
1980- );
1981- want[i] ^= 0x01;
1982- }
1983- let _ = std::fs::remove_dir_all(&dir);
1984- let bit_depth = stream_bit_depth(stream, name);
1985- let decoded = decode_stream(stream).expect("decode for comparison");
1986- let ours = pack_rawvideo(&decoded, bit_depth, name);
1987- if ours.len() != want.len() {
1988- return None;
1989- }
1990- let bpp = if bit_depth == 8 { 1 } else { 2 };
1991- // lane-av1cmpframe: the plane split is PER FRAME and comes from each
1992- // decoded frame's OWN plane lengths -- never from a formula, and
1993- // never from the first picture.
1994- //
1995- // The first-picture form was wrong on every multi-frame stream: it
1996- // compared a byte index against frame 0's thresholds forever, so
1997- // every sample after frame 0's luma was attributed to the LAST
1998- // plane. On `420_oddheight_320x236` (16 frames of 320x236
1999- // 4:2:0, whose frame is 113 280 bytes and whose V plane therefore
2000- // holds 302 080 bytes in total) it reported `wrong_v = 330 673` --
crates/ec-av1/src/stream/tests/t01.rsdeleted+0 -4538

Diff too large; view file

@@ -1,4538 +0,0 @@
1-use super::*;
2-use super::support::*;
3-use super::gates_a::*;
4-use crate::encode::{Picture as Pic, encode_key_frame_with_ctx, encode_sequence_with_ctx};
5-use crate::probe::run_with_stdin;
6-use std::process::{Command, Stdio};
7-
8- /// lane-av1422lift: THE 4:2:2 LIFT, in two pins. This test is the renamed,
9- /// inverted replacement for `a_non_420_subsampled_sequence_header_is_
10- /// refused_by_name`, and the two fixtures replace that gate's fixture --
11- /// a hand-built profile-2 header bolted onto a 4:2:0 TILE from this
12- /// crate's own encoder, which could never be inverted into an exactness
13- /// claim no matter how the assert was flipped (class `refusal-lifted-
14- /// without-a-gate`, and the risk study's R6).
15- ///
16- /// Both pins are REAL 4:2:2 streams from libaom's own writer over a
17- /// y4m whose header line is `C422`, so every chroma symbol in them is a
18- /// 4:2:2 chroma symbol. Provenance (both, verbatim, no other encoder):
19- ///
20- /// ```text
21- /// aomenc --codec=av1 --profile=2 \
22- /// --input-chroma-subsampling-x=1 --input-chroma-subsampling-y=0 \
23- /// --passes=1 --end-usage=q --cq-level=24 --cpu-used=0 \
24- /// --threads=1 --row-mt=0 --obu -o <pin> <source.y4m>
25- /// ```
26- ///
27- /// * `422_key_64x64.obu` -- 755 bytes, sha256
28- /// `3c9396c9e42701d720419ec2cb5577387e305482df0cb150f7f0b965edeaaffc`,
29- /// fnv1a64 `0x87fc569cf53bcbc6`. A single 64x64 8-bit KEY frame
30- /// (`--limit=1 --kf-min-dist=0 --kf-max-dist=0`) over a
31- /// hand-generated two-frame integer `C422` card source, the second
32- /// source frame unused by the `--limit=1`. The smallest thing that can
33- /// say "4:2:2 intra reconstructs".
34- /// * `422_inter_160x128_3f.obu` -- 6522 bytes, sha256
35- /// `7b54834c18f5fdc0e8606a6dc5bf4ff368402417d87fcfc2ab9758e4e9164902`,
36- /// fnv1a64 `0xf87eba3bf4fc2bb8`. Three 160x128 8-bit frames with a
37- /// panning square
38- /// (`--limit=3 --kf-min-dist=3 --kf-max-dist=3`, so frames 1 and 2 are
39- /// INTER), over a three-frame integer `C422` card source whose square
40- /// moves (6,4) -> (9,6) -> (12,8). This is what exercises the
41- /// inter-predicted 4:2:2 chroma reference: a decoder that walked the
42- /// key frame correctly and then predicted chroma from a 4:2:0-shaped
43- /// reference passes the first pin and reds here.
44- ///
45- /// Both are asserted BYTE-EXACT against ffmpeg 8.1.3's own rawvideo of
46- /// the same bytes at `yuv422p`, per plane and per frame, with the
47- /// per-plane coefficient-unit census as the non-vacuity arm (see
48- /// [`assert_422_stream_pixel_exact`]). A gate whose only assertion was
49- /// `err.contains(REFUSAL)` would have passed unchanged on a tree where
50- /// 4:2:2 decode was completely broken; that is what this replaces.
51- #[test]
52- fn a_real_422_key_frame_and_inter_sequence_decode_pixel_exact() {
53- const NAME: &str = "a_real_422_key_frame_and_inter_sequence_decode_pixel_exact";
54- if !have_ffmpeg() {
55- eprintln!("SKIP {NAME}: no ffmpeg");
56- return;
57- }
58- let key = crate_pin("422_key_64x64.obu");
59- let key_stream = read_pin(&key, 755, 0x87fc569cf53bcbc6, NAME);
60- let (units, _) = assert_422_stream_pixel_exact(NAME, &key_stream, 64, 64, 1, 8, true);
61- let (l, u, v) = (units[0], units[1], units[2]);
62- assert!(
63- l > 0 && u > 0 && v > 0,
64- "{NAME}: the key-frame pin walked no 4:2:2 chroma units [{l}, {u}, {v}]"
65- );
66-
67- let inter = crate_pin("422_inter_160x128_3f.obu");
68- let inter_stream = read_pin(&inter, 6522, 0xf87eba3bf4fc2bb8, NAME);
69- let (units, _) = assert_422_stream_pixel_exact(NAME, &inter_stream, 160, 128, 3, 8, true);
70- let (l, u, v) = (units[0], units[1], units[2]);
71- assert!(
72- u > 0 && v > 0,
73- "{NAME}: the inter pin walked no 4:2:2 chroma units [{l}, {u}, {v}] -- the inter \
74- chroma reference path was never reached"
75- );
76- }
77-
78- /// lane-av1422lift: 4:2:2 at 12 bits, and 4:2:2 with superres, are the two
79- /// cells the corpus had no coverage for at all (the risk study's R3 and
80- /// R9: the sweep recipe passed no 12-bit depth and no `--superres-mode`,
81- /// so every 4:2:2 measurement in the tree was 8- or 10-bit, none
82- /// superres). Both are pinned and both are byte-exact here.
83- ///
84- /// `s422_12bit_160x128.obu` -- 9214 bytes, sha256
85- /// `eacc70f75c82ad7d795efbd0242aa4ee33db917b8c1a3570ebce2570ee8bc245`,
86- /// fnv1a64 `0xa62b8e3fe6f60ae5`. 160x128, 12-bit, 3 frames,
87- /// `yuv422p12le` per ffprobe, profile 2 ("Professional").
88- ///
89- /// **Provenance is ffmpeg's libaom-av1 wrapper, not aomenc, and the
90- /// reason is measured, not preferred.** aomenc's own 12-bit y4m path
91- /// issues `AV1E_SET_CHROMA_SUBSAMPLING_X` (apps/aomenc.c:2272-2278,
92- /// reached whenever the input is not 4:2:0 and the bit depth is 12)
93- /// BEFORE `aom_codec_enc_config_set`, and on this libaom that control
94- /// returns `AOM_CODEC_INTERNAL_ERROR` for any non-4:2:0 shape -- measured
95- /// on four independently built trees
96- /// (`~/.cache/aom-oracle`, `aom-affine`, `aom-oracle2`, `aom-oracle3`):
97- /// `C422p12` and `C444p12` both die with "Failed to set chroma
98- /// subsampling x", while `C420p12` and the 8-bit `C422`/`C444` both
99- /// encode. It is not a 4:2:2-specific gap (12-bit 4:4:4 fails too) and
100- /// not a 4:2:0 gap (12-bit 4:2:0 encodes). The same control succeeds at
101- /// 8 bits, so the failure is the 12-bit configuration order, and the
102- /// workaround is a wrapper that sets the codec config first. ffmpeg's
103- /// libaom-av1 does exactly that:
104- ///
105- /// ```text
106- /// ffmpeg -f lavfi -i "testsrc2=size=160x128:rate=1:duration=3" \
107- /// -pix_fmt yuv422p12le -c:v libaom-av1 -profile:v 2 -b:v 0 -crf 30 \
108- /// -cpu-used 8 -auto-alt-ref 0 -lag-in-frames 0 \
109- /// -strict experimental -f obu s422_12bit_160x128.obu
110- /// ```
111- ///
112- /// That is libaom's encoder either way -- ffmpeg links it and calls
113- /// `aom_codec_encode` -- and the oracle side is ffmpeg's own
114- /// `yuv422p12le` rawvideo decode of the same bytes, so the pin and the
115- /// oracle come from the same library, which is the property that makes
116- /// byte-exactness a claim about OUR decoder rather than about a
117- /// disagreement between two encoders.
118- ///
119- /// `s422_superres_160x128.obu` -- 5304 bytes, sha256
120- /// `5852ff2c273cb773c4886762c6a6f2cce6e12065a690eb3a5ca2119c0b6f2957`,
121- /// fnv1a64 `0x0789d1b2851b94ae`. 160x128, 8-bit, 3 frames, `--superres-
122- /// mode=1` (fixed) over a `C422` testsrc2 source, encoded by the
123- /// aomenc recipe above plus `--superres-mode=1`. Superres is the one
124- /// 4:2:2 path whose output crop is `(round_ss(w,1) x round_ss(h,0))` at
125- /// the UPSCALED size, and it had no 4:2:2 cell anywhere.
126- #[test]
127- fn a_real_422_12bit_and_superres_stream_decode_pixel_exact() {
128- const NAME: &str = "a_real_422_12bit_and_superres_stream_decode_pixel_exact";
129- if !have_ffmpeg() {
130- eprintln!("SKIP {NAME}: no ffmpeg");
131- return;
132- }
133- let hbd = crate_pin("s422_12bit_160x128.obu");
134- let hbd_stream = read_pin(&hbd, 9214, 0xa62b8e3fe6f60ae5, NAME);
135- assert_422_stream_pixel_exact(NAME, &hbd_stream, 160, 128, 3, 12, true);
136-
137- let sr = crate_pin("s422_superres_160x128.obu");
138- let sr_stream = read_pin(&sr, 5304, 0x0789d1b2851b94ae, NAME);
139- assert_422_stream_pixel_exact(NAME, &sr_stream, 160, 128, 3, 8, true);
140- }
141-
142- /// lane-av1lr422: a libaom-recipe 10-bit 4:2:2 stream with loop
143- /// restoration ON, `s422_lr_10bit_200x120.obu` (129409 bytes, sha256
144- /// `5d6bc195934709390191c9ea8af167d385552c5b1330e8abd38f76a4416ba751`,
145- /// fnv1a64 `0xc5d5489355fdc2df`), 200x120, 8 frames. It was REFUSED by
146- /// the sub-8x8 plane-block check before the fix: the refusal was a
147- /// parse desync, not a wrong check. The 32x8 / 8x32 rect4 general arm
148- /// gathered the chroma dc-sign votes per mi instead of per 4-px chroma
149- /// column, which desynced the coefficient contexts. Decodes byte-exact
150- /// against ffmpeg libdav1d rawvideo.
151- #[test]
152- fn a_422_10bit_lr_stream_decodes_pixel_exact() {
153- const NAME: &str = "a_422_10bit_lr_stream_decodes_pixel_exact";
154- if !have_ffmpeg() {
155- eprintln!("SKIP {NAME}: no ffmpeg");
156- return;
157- }
158- let p = crate_pin("s422_lr_10bit_200x120.obu");
159- let stream = read_pin(&p, 129409, 0xc5d5489355fdc2df, NAME);
160- assert_422_stream_pixel_exact(NAME, &stream, 200, 120, 8, 10, true);
161- }
162-
163- /// lane-av1odd440, CELL 1 of 2: `4:2:0 with an ODD luma dimension`, the
164- /// cell `lanes/av1formatsweep.report.md` left as declared debt because
165- /// "aomenc rounds a 4:2:0 frame's coded size DOWN to even, so no stream
166- /// this recipe can produce codes an odd luma dimension".
167- ///
168- /// The pin, `420_odd65x65_key.obu` (2305 bytes,
169- /// sha256 `66986019a561f81130f407f426c4379b25e6e80c2cd9ce47d517b3216e9a03cf`),
170- /// is that missing stream, built offline by
171- /// `examples/gen_coverage_cells.rs`: a 96x96 card padded to the block
172- /// grid, coded by `encode::encode_key_frame_at_size` with a 65x65 frame
173- /// header. Provenance: that example, `cargo run -p ec-av1 --example
174- /// gen_coverage_cells -- crates/ec-av1/fixtures`; no encoder, no ffmpeg,
175- /// no lavfi.
176- ///
177- /// WHY THE CELL IS NOT A RUBBER STAMP -- the chroma extent is where a
178- /// floor shows. A 65-wide 4:2:0 frame has
179- /// `ROUND_POWER_OF_TWO(65, 1) = 33` chroma columns (libaom
180- /// `av1_common_plane_width`, `av1/common/av1_common_int.h`), not 32, so
181- /// the decoded frame's own plane sizes, the rawvideo sample count and
182- /// the oracle compare all move if `decode::round_ss` is floored. The
183- /// mutation was run: flooring `round_ss` (`decode.rs:697`) turns the
184- /// `round_ss` assert below red at 32 chroma columns and the oracle arm
185- /// red at a 6273-byte raw against the oracle's 6403. The gate is
186- /// therefore not green on a floored decoder, which is the whole content
187- /// of this cell.
188- ///
189- /// The stream decodes PIXEL-EXACT against the instrumented `aomdec`
190- /// (6403 raw bytes = 65*65 + 2*33*33, byte-identical), so the cell is a
191- /// `y` and not a `–`.
192- #[test]
193- fn an_odd_luma_420_key_frame_decodes_pixel_exact() {
194- const NAME: &str = "an_odd_luma_420_key_frame_decodes_pixel_exact";
195- let _gate_lock = lock_gate_counters();
196- let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
197- .join("fixtures")
198- .join("420_odd65x65_key.obu");
199- let stream = read_pin(&path, 2305, 0xf55645c4b139e8f7, NAME);
200-
201- // The stream's OWN header, read from its own bytes: an odd luma size
202- // at 4:2:0, which is the cell. (Taken from the pin, not from the
203- // gate's name -- class `helper-packs-u16-for-an-8-bit-stream`.)
204- let mut probe = Av1Parser::new();
205- let mut pos = 0usize;
206- while pos < stream.len() && probe.sequence_header().is_none() {
207- let obu = probe
208- .parse_obu(&stream[pos..])
209- .unwrap_or_else(|e| panic!("{NAME}: OBU at byte {pos} does not parse: {e:?}"));
210- pos += obu.total_size;
211- }
212- let seq = probe
213- .sequence_header()
214- .unwrap_or_else(|| panic!("{NAME}: the pin carries no sequence header"));
215- assert_eq!(
216- (seq.max_frame_width, seq.max_frame_height),
217- (65, 65),
218- "{NAME}: the pin must declare an ODD luma size, it declares {}x{}",
219- seq.max_frame_width,
220- seq.max_frame_height
221- );
222- assert_eq!(
223- (
224- seq.color_config.subsampling_x,
225- seq.color_config.subsampling_y
226- ),
227- (1, 1),
228- "{NAME}: this cell is an odd luma SIZE at 4:2:0, not another chroma shape"
229- );
230-
231- // The decoded frame's own extents. This arm needs no oracle, and it
232- // is the one a floored `round_ss` turns red.
233- let frames = decode_stream(&stream).expect("the odd-luma 4:2:0 pin must decode");
234- assert_eq!(frames.len(), 1, "{NAME}: frame count");
235- let frame = &frames[0];
236- assert_eq!(
237- (frame.width, frame.height),
238- (65, 65),
239- "{NAME}: decoded luma extent"
240- );
241- assert_eq!(frame.y.len(), 65 * 65, "{NAME}: decoded luma sample count");
242- assert_eq!(
243- (frame.u.len(), frame.v.len()),
244- (33 * 33, 33 * 33),
245- "{NAME}: a 65x65 4:2:0 frame has ROUND_POWER_OF_TWO(65,1) = 33 chroma \
246- columns and rows -- 32 means the extent was floored"
247- );
248-
249- if !aomdec_available(NAME) {
250- return;
251- }
252- assert_rawvideo_matches(&path, &stream, NAME, 1, 8);
253- }
254-
255- /// lane-av1odd440, CELL 2 of 2: the `4:4:0 (ss 0,1)` row, which the same
256- /// report called "unmeasured and unproducible by recipe". It is neither
257- /// unmeasured nor unproducible: it is NOT A CELL AT ALL.
258- ///
259- /// `subsampling_y` is coded only when `subsampling_x` is 1 (spec 5.5.2
260- /// `color_config`), so a sequence header can carry exactly three chroma
261- /// shapes -- 4:2:0 `(1,1)`, 4:2:2 `(1,0)`, 4:4:4 `(0,0)` -- and never
262- /// `(0,1)`. libaom says so in both directions: the reader leaves
263- /// `subsampling_y = 0` when `subsampling_x` is 0
264- /// (`av1_read_color_config`, `av1/decoder/decodeframe.c:4171-4175`) and
265- /// the writer ASSERTS it -- `assert(seq_params->subsampling_y == 0 &&
266- /// "4:4:0 subsampling not allowed in AV1")`, `av1/encoder/bitstream.c:
267- /// 2463-2465`. So there is no stream to decode, no fixture to pin that
268- /// a decoder could be handed, and no oracle to compare against: a
269- /// 4:4:0 row in a coverage matrix is a matrix bug, not a decoder gap.
270- ///
271- /// What is pinned, then, is the claim itself, in three arms that a
272- /// mutation turns red:
273- ///
274- /// 1. WRITER: every `(profile, bit_depth, mono, colour description,
275- /// requested subsampling)` combination a `color_config` can carry is
276- /// written by this crate's own writer and read back by this crate's
277- /// own reader. The reachable set is asserted to be EXACTLY
278- /// `{(1,1), (1,0), (0,0)}` -- each legal shape present, `(0,1)`
279- /// absent -- and, on the BYTES rather than on the round trip, the two
280- /// requests that differ only in `subsampling_y` must write identical
281- /// headers whenever `subsampling_x` is 0. A sweep that silently wrote
282- /// nothing would pass, so the count of combinations actually written
283- /// and read is asserted too.
284- /// 2. READER: the one byte that carries `subsampling_x` is found by
285- /// diffing an `(0,0)` header against an `(1,0)` one, and then all 256
286- /// values of that byte are fed back through the reader. Not one of the
287- /// headers that parse reads back `(0,1)`, because the reader never
288- /// reads a `subsampling_y` bit in that position. A reader that always
289- /// read a second bit would produce `(0,1)` at the one value that sets
290- /// both bits.
291- /// 3. THE PIN: `440_request_is_422.obu` (2014 bytes, sha256
292- /// `4afaa5470c4e010d9d970086ef514680adfe801a579e4deeec582f52d13c5e7c`,
293- /// fnv1a64 `0x98a1378df976253d`) is what this crate's writer produces
294- /// when it is handed `subsampling (0,1)` at profile 2 -- profile 2
295- /// below 12 bits is 4:2:2 and codes no subsampling bit at all, so the
296- /// request lands on `(1,0)`. The pin is asserted to read back `(1,0)`,
297- /// NOT `(0,1)`. Its frame OBU is a 4:2:0 key frame's, so the pin is a
298- /// HEADER witness, not a decodable 4:2:2 stream -- nothing here claims
299- /// pixels for it. Provenance: `examples/gen_coverage_cells.rs`, `cargo
300- /// run -p ec-av1 --example gen_coverage_cells -- crates/ec-av1/fixtures`.
301- ///
302- /// lane-av1422lift: this arm used to end "and the decoder is asserted
303- /// to refuse it by name, which is the honest outcome for the shape a
304- /// 4:4:0 request actually yields". That was honest only because the
305- /// decoder refused EVERY (1,0) header -- the assertion was about the
306- /// guard, not about these bytes. With 4:2:2 admitted, refusing these
307- /// bytes would be wrong and accepting them without comment would be
308- /// worse, so the arm now asserts the one thing that IS true of them:
309- /// the SEQUENCE HEADER, not the tile, fixes the decode's chroma
310- /// geometry. The pixel claim moved to genuinely 4:2:2 pins.
311- #[test]
312- fn the_440_cell_is_not_a_codable_chroma_shape() {
313- const NAME: &str = "the_440_cell_is_not_a_codable_chroma_shape";
314- let _gate_lock = lock_gate_counters();
315- let header_obu = |profile: u8, color: ec_av1_syntax::ColorConfig| -> Vec<u8> {
316- let (mut seq, _header) = crate::encode::key_frame_headers_colour(64, 64, 100, color)
317- .expect("the header builders accept a colour config");
318- seq.seq_profile = profile;
319- crate::sequence::sequence_header_obu(&seq).expect("writing the sequence header")
320- };
321- let shape_of = |obu: &[u8]| -> Option<(u8, u8)> {
322- let mut parser = Av1Parser::new();
323- let parsed = parser.parse_obu(obu).ok()?;
324- if !matches!(parsed.kind, ec_av1_syntax::ObuKind::SequenceHeader(_)) {
325- return None;
326- }
327- let seq = parser.sequence_header()?;
328- Some((
329- seq.color_config.subsampling_x,
330- seq.color_config.subsampling_y,
331- ))
332- };
333-
334- // ---- arm 1: the writer's whole reachable space --------------------
335- let mut reachable: std::collections::BTreeSet<(u8, u8)> = Default::default();
336- let mut asked = 0usize;
337- for profile in [0u8, 1, 2] {
338- for bit_depth in [8u8, 10, 12] {
339- for mono_chrome in [false, true] {
340- // Profile 1 is 4:4:4 and codes no mono bit; asking for
341- // monochrome there is refused by the writer, which is
342- // not a chroma shape and not this gate's subject.
343- if mono_chrome && profile == 1 {
344- continue;
345- }
346- for (label, (cp, tc, mc)) in [
347- ("unspecified", (2u8, 2u8, 2u8)),
348- ("bt709", (1u8, 1u8, 1u8)),
349- ("srgb", (1u8, 13u8, 0u8)),
350- ] {
351- for sx in [0u8, 1] {
352- for sy in [0u8, 1] {
353- let color = ec_av1_syntax::ColorConfig {
354- bit_depth,
355- mono_chrome,
356- num_planes: if mono_chrome { 1 } else { 3 },
357- color_primaries: cp,
358- transfer_characteristics: tc,
359- matrix_coefficients: mc,
360- color_range: false,
361- subsampling_x: sx,
362- subsampling_y: sy,
363- chroma_sample_position:
364- ec_av1_syntax::ChromaSamplePosition::Unknown,
365- separate_uv_delta_q: false,
366- };
367- asked += 1;
368- let obu = header_obu(profile, color);
369- // The WRITER half of the claim, measured on the
370- // bytes rather than on a round trip: with
371- // `subsampling_x == 0` the spec codes no
372- // `subsampling_y` bit at all, so the two
373- // requests that differ ONLY in `subsampling_y`
374- // must produce byte-identical headers. A
375- // writer that emitted the bit anyway (the
376- // mutation libaom's own `assert` exists to
377- // catch, av1/encoder/bitstream.c:2467-2468) fails
378- // here -- and note it does NOT fail the
379- // round trip, because the reader then absorbs
380- // the extra bit as `separate_uv_delta_q`.
381- if sx == 0 {
382- let mut other = color;
383- other.subsampling_y = 1;
384- assert_eq!(
385- obu,
386- header_obu(profile, other),
387- "{NAME}: a (0,0) and a (0,1) request wrote DIFFERENT \
388- bytes at profile {profile}, {bit_depth}-bit, mono \
389- {mono_chrome}, {label} -- `subsampling_y` must not be \
390- coded at all when `subsampling_x` is 0"
391- );
392- }
393- if let Some(got) = shape_of(&obu) {
394- assert_ne!(
395- got,
396- (0, 1),
397- "{NAME}: a 4:4:0 shape came back out of the writer at \
398- profile {profile}, {bit_depth}-bit, mono {mono_chrome}, \
399- {label}, asked for ({sx},{sy}) -- libaom forbids this \
400- shape outright (av1/encoder/bitstream.c:2467-2468)"
401- );
402- reachable.insert(got);
403- }
404- }
405- }
406- }
407- }
408- }
409- }
410- assert!(
411- asked >= 100 && reachable.len() == 3,
412- "{NAME}: the sweep asked {asked} combinations and reached {} shapes -- it must reach \
413- all three legal ones, or it is not measuring the space",
414- reachable.len()
415- );
416- assert_eq!(
417- reachable,
418- std::collections::BTreeSet::from([(0u8, 0u8), (1u8, 0u8), (1u8, 1u8)]),
419- "{NAME}: the chroma shapes a `color_config` can code are exactly 4:4:4 (0,0), 4:2:2 \
420- (1,0) and 4:2:0 (1,1)"
421- );
422-
423- // ---- arm 2: the reader's bit at that position ----------------------
424- // Profile 2 at 12 bits is the only place BOTH subsampling bits are
425- // coded, so it is where a hand-built header could try to smuggle a
426- // `subsampling_y`. Find the byte that carries `subsampling_x` by
427- // diffing the two shapes, then read back all eight of its values.
428- let at_444 = |sx: u8| {
429- let color = ec_av1_syntax::ColorConfig {
430- bit_depth: 12,
431- subsampling_x: sx,
432- subsampling_y: 0,
433- chroma_sample_position: ec_av1_syntax::ChromaSamplePosition::Unknown,
434- ..ec_av1_syntax::ColorConfig::default()
435- };
436- let (mut seq, _h) =
437- crate::encode::key_frame_headers_colour(64, 64, 100, color).unwrap();
438- seq.seq_profile = 2;
439- let obu = crate::sequence::sequence_header_obu(&seq).unwrap();
440- let mut parser = Av1Parser::new();
441- parser.parse_obu(&obu).expect("the profile-2 header parses");
442- let seq = parser.sequence_header().expect("sequence header");
443- (
444- seq.color_config.subsampling_x,
445- seq.color_config.subsampling_y,
446- )
447- };
448- assert_eq!(at_444(0), (0, 0), "{NAME}: the sx=0 header is 4:4:4");
449- assert_eq!(at_444(1), (1, 0), "{NAME}: the sx=1 header is 4:2:2");
450- let base = {
451- let color = ec_av1_syntax::ColorConfig {
452- bit_depth: 12,
453- subsampling_x: 0,
454- subsampling_y: 0,
455- chroma_sample_position: ec_av1_syntax::ChromaSamplePosition::Unknown,
456- ..ec_av1_syntax::ColorConfig::default()
457- };
458- let (mut seq, _h) =
459- crate::encode::key_frame_headers_colour(64, 64, 100, color).unwrap();
460- seq.seq_profile = 2;
461- crate::sequence::sequence_header_obu(&seq).unwrap()
462- };
463- let other = {
464- let color = ec_av1_syntax::ColorConfig {
465- bit_depth: 12,
466- subsampling_x: 1,
467- subsampling_y: 0,
468- chroma_sample_position: ec_av1_syntax::ChromaSamplePosition::Unknown,
469- ..ec_av1_syntax::ColorConfig::default()
470- };
471- let (mut seq, _h) =
472- crate::encode::key_frame_headers_colour(64, 64, 100, color).unwrap();
473- seq.seq_profile = 2;
474- crate::sequence::sequence_header_obu(&seq).unwrap()
475- };
476- assert_eq!(
477- base.len(),
478- other.len(),
479- "{NAME}: the two headers must differ in place"
480- );
481- let byte_at = base
482- .iter()
483- .zip(&other)
484- .position(|(a, b)| a != b)
485- .expect("the two shapes must differ somewhere");
486- // Every value of that byte is fed back through the reader -- it is the
487- // LAST payload byte, so the bits a smuggled `subsampling_y` would come
488- // from are in it too (spec 5.5.2 always codes `separate_uv_delta_q`
489- // after the subsampling pair, and the payload is padded out to the
490- // byte with `trailing_bits`). A header that stops parsing is not a
491- // 4:4:0 shape and cannot be counted as one; the sweep asserts how
492- // many DID parse, so a sweep that quietly parsed nothing is not
493- // evidence of anything.
494- let mut parsed_headers = 0usize;
495- for value in 0..256u16 {
496- let mut poked = base.clone();
497- poked[byte_at] = value as u8;
498- let mut parser = Av1Parser::new();
499- let Ok(parsed) = parser.parse_obu(&poked) else {
500- continue;
501- };
502- if !matches!(parsed.kind, ec_av1_syntax::ObuKind::SequenceHeader(_)) {
503- continue;
504- }
505- let seq = parser.sequence_header().expect("sequence header");
506- parsed_headers += 1;
507- assert_ne!(
508- (
509- seq.color_config.subsampling_x,
510- seq.color_config.subsampling_y
511- ),
512- (0, 1),
513- "{NAME}: payload byte {byte_at} = {value:#04x} read back as 4:4:0 -- the reader \
514- took a `subsampling_y` bit that spec 5.5.2 does not code when `subsampling_x` \
515- is 0"
516- );
517- }
518- assert!(
519- parsed_headers > 100,
520- "{NAME}: only {parsed_headers} of the 256 poked headers parsed -- the sweep is not \
521- measuring the reader"
522- );
523-
524- // ---- arm 3: the pinned bytes a 4:4:0 request produces --------------
525- let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
526- .join("fixtures")
527- .join("440_request_is_422.obu");
528- let pinned = read_pin(&path, 2014, 0x98a1378df976253d, NAME);
529- let mut parser = Av1Parser::new();
530- let obu = parser
531- .parse_obu(&pinned)
532- .unwrap_or_else(|e| panic!("{NAME}: the pin's first OBU does not parse: {e:?}"));
533- assert!(
534- matches!(obu.kind, ec_av1_syntax::ObuKind::SequenceHeader(_)),
535- "{NAME}: the pin must start with its sequence header"
536- );
537- let seq = parser.sequence_header().expect("the pin's sequence header");
538- assert_eq!(
539- (
540- seq.color_config.subsampling_x,
541- seq.color_config.subsampling_y
542- ),
543- (1, 0),
544- "{NAME}: the pin is what a 4:4:0 request at profile 2 produces -- 4:2:2 (1,0). If this \
545- ever reads (0,1), a 4:4:0 cell became codable and this whole gate is wrong about the \
546- format."
547- );
548- // lane-av1unwritten: lane-av1422lift replaced the old 4:2:2 header
549- // refusal with "it decodes, and the decoded chroma planes are 32x64".
550- // That was the wrong contract for THIS pin: its frame OBU is a 4:2:0
551- // key frame's, so at 4:2:2 its partition symbols name subsizes with no
552- // chroma plane block, which libaom rejects as a corrupt frame
553- // ("Block size 8x16 invalid with this subsampling mode",
554- // decodeframe.c:1456) and `aomdec` does. The replacement is the
555- // REFUSAL, by that rule.
556- //
557- // The pin's remaining job is unchanged and still worth saying: it
558- // proves a 4:4:0 REQUEST at profile 2 lands on 4:2:2 (1,0), i.e. that
559- // `the_440_cell_is_not_a_codable_chroma_shape`'s claim is still true.
560- let err = decode_stream(&pinned).err().unwrap_or_else(|| {
561- panic!(
562- "{NAME}: the pin is a 4:2:2 header over a 4:2:0 tile -- libaom refuses it \
563- (aomdec: \"Block size 8x16 invalid with this subsampling mode\"), and so \
564- must we"
565- )
566- });
567- assert!(
568- err.to_string()
569- .contains("invalid with this subsampling mode"),
570- "{NAME}: the refusal must name libaom's rule, got: {err}"
571- );
572- // The pixels this pin never had: the sibling gate
573- // `a_422_header_over_a_420_tile_refuses_the_subsize_libaom_calls_corrupt`
574- // pins the refusal plus a genuine 4:2:2 positive control, and every
575- // real 4:2:2 exactness claim lives on genuinely 4:2:2 pins in this
576- // file.
577- }
578-
579- /// lane-av1unwritten: this pin is a MISSING REFUSAL, not a pixel defect.
580- ///
581- /// `440_request_is_422.obu` is a 4:2:2 sequence header wrapped around a
582- /// 4:2:0 key frame's tile, so the tile's partition symbols make subsizes
583- /// (8x16 among them) that have NO chroma plane block at ss (1,0). libaom
584- /// refuses exactly that, before descending into the subsize:
585- ///
586- /// ```text
587- /// $ aomdec --rawvideo -o /dev/null fixtures/440_request_is_422.obu
588- /// Warning: Failed to decode frame 1: Corrupt frame detected
589- /// Warning: Additional information: Block size 8x16 invalid with this subsampling mode
590- /// ```
591- ///
592- /// (`av1/decoder/decodeframe.c:1449-1458`,
593- /// `get_plane_block_size(subsize, ss_x, ss_y) == BLOCK_INVALID` ->
594- /// `AOM_CODEC_CORRUPT_FRAME`.) We walked those subsizes instead, and the
595- /// first version of this lane misread the downstream symptom -- a chroma
596- /// plane block covered by a square unit, whole 4x4 blocks left unwritten,
597- /// and a `EC_AV1_FINAL_DUMP` hash that CHANGED RUN TO RUN because the
598- /// unwritten samples were uninitialised plane memory.
599- ///
600- /// The contract pinned here is the one libaom has: the pin REFUSES, by a
601- /// named error that says which shape and which subsampling mode. The
602- /// positive control is a genuinely 4:2:2 pin, which must still decode --
603- /// so this gate cannot pass by refusing everything.
604- #[test]
605- fn a_422_header_over_a_420_tile_refuses_the_subsize_libaom_calls_corrupt() {
606- const NAME: &str = "a_422_header_over_a_420_tile_refuses_the_subsize_libaom_calls_corrupt";
607- let _gate_lock = lock_gate_counters();
608- let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
609- .join("fixtures")
610- .join("440_request_is_422.obu");
611- let pinned = read_pin(&path, 2014, 0x98a1378df976253d, NAME);
612- // The refusal this gate PROVES, quoted whole -- the anchor the PROVEN
613- // row in `refusal_inventory.rs` is checked against inside this body's
614- // own bounds. The assertion below used to match only the libaom
615- // citation *inside* the string, so a reworded guard kept passing for
616- // as long as it kept citing `decodeframe.c:1456`: the half that names
617- // OUR shapes (4x8 / 8x16 / 16x4, and 8x4 at 4:4:0) was never pinned.
618- const REFUSAL: &str = "a block size 4x8, 8x16 or 16x4 (or 8x4 at 4:4:0) has no chroma \
619- plane block at this frame's subsampling mode (libaom: \"Block \
620- size %dx%d invalid with this subsampling mode\", \
621- av1/decoder/decodeframe.c:1456, refusing by the same rule)";
622- let err = decode_stream(&pinned)
623- .err()
624- .unwrap_or_else(|| panic!("{NAME}: the pin must be REFUSED, not decoded"));
625- let msg = err.to_string();
626- assert!(
627- msg.contains("invalid with this subsampling mode"),
628- "{NAME}: the refusal must name the rule it refuses by (libaom's own wording), got: \
629- {msg}"
630- );
631- assert!(
632- msg.contains(REFUSAL),
633- "{NAME}: the refusal must be this decoder's OWN string, whole -- the guard's wording \
634- drifted, so the PROVEN row no longer names what fires, got: {msg}"
635- );
636- // Positive control: a real 4:2:2 stream must still decode, so the gate
637- // cannot pass by refusing everything.
638- let ok_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
639- .join("fixtures")
640- .join("422_key_64x64.obu");
641- let ok = decode_stream(&std::fs::read(&ok_path).expect("the 4:2:2 control fixture"))
642- .unwrap_or_else(|e| panic!("{NAME}: a genuine 4:2:2 pin must still decode: {e}"));
643- assert!(
644- !ok.is_empty(),
645- "{NAME}: the 4:2:2 control decoded no frames"
646- );
647- }
648-
649- /// lane-av1subsizesweep: the FRAME-EDGE walk of a BLOCK_INVALID subsize,
650- /// pinned. This is the one install site the partition-symbol guards missed,
651- /// and the sibling pin above cannot see it -- that pin's 8x16 comes from a
652- /// 16x16-level `PARTITION_VERT_B` (an interior AB strip, refused at
653- /// decode.rs:36472), while this pin's comes from the key-frame 16-level
654- /// FRAME-EDGE arm, which is not a `dec.symbol(` site at all: it reads one
655- /// gathered bit with `dec.symbol_fixed(&gather(..))` and dispatches
656- /// `decode_leaf_rect` straight off it.
657- ///
658- /// `422_header_edge16_walk.obu` (128 bytes, sha256
659- /// `e8ab2bb229896f796cdec4d2cb383b41f057ef8d364da30f160a3f55a452657f`,
660- /// fnv1a64 `0xcfa2394ebe1f7764`) is a 4:2:2 sequence header over a 4:2:0
661- /// key frame's tile, at 88x64. Width 88 is 8 mod 16, so the last 16x16
662- /// column block is COLUMN-short and the frame-edge arm fires; height 64 is
663- /// 16-aligned, so the ROW is not short and the both-cut arm is not taken.
664- /// The gathered bit names `PARTITION_VERT`, so the strip is `BLOCK_8X16`.
665- ///
666- /// libaom's own verdict, which is the rule this pin pins:
667- ///
668- /// ```text
669- /// $ aomdec --rawvideo -o /dev/null fixtures/422_header_edge16_walk.obu
670- /// Warning: Failed to decode frame 1: Corrupt frame detected
671- /// Warning: Additional information: Block size 8x16 invalid with this subsampling mode
672- /// ```
673- ///
674- /// What makes this pin different from every other refusal gate in this file
675- /// is that the 8x16 is the ONLY offending subsize in the stream. Measured
676- /// over a 260-candidate sweep (4 card textures x 5 quantizers x 13 declared
677- /// widths), this is the one candidate whose decode with the guard removed
678- /// SUCCEEDS: with the `refuse_invalid_subsize` at decode.rs:37098 deleted,
679- /// this decoder returned a full 88x64 picture where libaom refuses the
680- /// frame. So the guard is not a redundant second refusal here -- it is the
681- /// only thing between a corrupt frame and a plausible-looking decode.
682- #[test]
683- fn a_422_header_whose_only_invalid_subsize_is_the_16_level_frame_edge_walk_is_refused() {
684- const NAME: &str =
685- "a_422_header_whose_only_invalid_subsize_is_the_16_level_frame_edge_walk_is_refused";
686- let _gate_lock = lock_gate_counters();
687- let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
688- .join("fixtures")
689- .join("422_header_edge16_walk.obu");
690- let pinned = read_pin(&path, 128, 0xcfa2394ebe1f7764, NAME);
691- // The shape must be the one this lane's arm carries: if the pin ever
692- // stops being an 8x16 strip the refusal is coming from somewhere else
693- // and this gate is measuring the wrong thing.
694- assert!(
695- !crate::decode::chroma_plane_block_codable(8, 16, 1, 0),
696- "{NAME}: BLOCK_8X16 must be BLOCK_INVALID at 4:2:2 -- this gate's whole \
697- subject is `av1_ss_size_lookup[BLOCK_8X16][1][0] == BLOCK_INVALID`"
698- );
699- assert!(
700- crate::decode::chroma_plane_block_codable(16, 8, 1, 0),
701- "{NAME}: the 16x8 mirror MUST stay legal at 4:2:2 (BLOCK_8X8) -- it is what \
702- keeps the new guard from refusing the sibling arm's strip"
703- );
704- let err = decode_stream(&pinned)
705- .err()
706- .unwrap_or_else(|| panic!("{NAME}: the pin must be REFUSED, not decoded"));
707- let msg = err.to_string();
708- assert!(
709- msg.contains("invalid with this subsampling mode"),
710- "{NAME}: the refusal must name libaom's rule (its own wording), got: {msg}"
711- );
712- // Positive control: a genuine 4:2:2 stream must still decode, so this
713- // gate cannot pass by refusing everything.
714- let ok_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
715- .join("fixtures")
716- .join("422_key_64x64.obu");
717- let ok = decode_stream(&std::fs::read(&ok_path).expect("the 4:2:2 control fixture"))
718- .unwrap_or_else(|e| panic!("{NAME}: a genuine 4:2:2 pin must still decode: {e}"));
719- assert!(
720- !ok.is_empty(),
721- "{NAME}: the 4:2:2 control decoded no frames"
722- );
723- }
724-
725- /// lane-av1-422bigblock: the two witnessed 4:2:2 big-block defects, pinned
726- /// as fixtures (`git add -f`; `fixtures/` is gitignored).
727- ///
728- /// `422_allskip_2f.obu` (62 bytes) is a 128x128 profile-2 key frame plus
729- /// its all-skip first inter frame: the pre-port decoder read phantom
730- /// coefficient units in the inter frame and then panicked in
731- /// `reconstruct_mc_rect` on a full-height 4:2:2 chroma rect. At this
732- /// lane's HEAD the block-half port's per-axis plane-block model already
733- /// has it entropy-locked (all 20 key-frame coefficient units pair
734- /// rng-for-rng with the instrumented oracle, the inter frame reads
735- /// zero, matching the oracle) and pixel-exact vs aomdec.
736- ///
737- /// `422_sb128_3f.obu` (12543 bytes) carries the f2 128x128
738- /// `PARTITION_NONE` non-skip inter block: the mu-chunk chroma walk cut
739- /// each chunk's 32x64 chroma into a `chroma_side`-square 64x64 (twice
740- /// the units the oracle codes), indexed the prediction buffer at the
741- /// square `chroma_side` instead of `chroma_stride` (the empty-slice
742- /// panic at `push_mc_rect_tx`'s densify), and the reference plane
743- /// resolution guessed every non-4:4:4 picture quarter-height, so the
744- /// bottom mu-chunk row predicted from a clamped row-63 edge. All fixed;
745- /// both witnesses decode pixel-exact vs aomdec on the lane's local
746- /// `EC_AV1_ALLOW_422_PROBE` patch-run-restore build (recipe and measured
747- /// numbers in `lanes/av1422bigblock.report.md`).
748- ///
749- /// lane-av1422lift: `decode_stream` no longer refuses 4:2:2 at the
750- /// sequence header, so this gate stops being a refusal contract and
751- /// becomes the one it should have been: BOTH pins, byte-pinned AND
752- /// byte-exact against ffmpeg, with the per-plane coefficient-unit census
753- /// as the non-vacuity arm. The pins are unchanged and still load-bearing
754- /// (size + fnv1a64); only the assertion moved.
755- #[test]
756- fn the_pinned_422_bigblock_witnesses_decode_pixel_exact() {
757- const NAME: &str = "the_pinned_422_bigblock_witnesses_decode_pixel_exact";
758- if !have_ffmpeg() {
759- eprintln!("SKIP {NAME}: no ffmpeg");
760- return;
761- }
762- for (file, bytes, fp, frames, require_coded) in [
763- (
764- "422_allskip_2f.obu",
765- 62usize,
766- 0x7e4d69d3c728c55f_u64,
767- 2usize,
768- false,
769- ),
770- ("422_sb128_3f.obu", 12543, 0x5171e0aab8000da7, 3, true),
771- ] {
772- let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
773- .join("fixtures")
774- .join(file);
775- let data = std::fs::read(&path).unwrap_or_else(|e| {
776- panic!(
777- "{NAME}: pinned witness {} is missing ({e}) -- the gate cannot run",
778- path.display()
779- )
780- });
781- assert_eq!(data.len(), bytes, "{NAME}: {file} size drifted");
782- assert_eq!(fnv1a64(&data), fp, "{NAME}: {file} bytes drifted");
783- let (_units, coded_delta) =
784- assert_422_stream_pixel_exact(NAME, &data, 128, 128, frames, 8, require_coded);
785- if !require_coded {
786- // `422_allskip_2f.obu` is named for what it does NOT code, and
787- // the pre-port defect was exactly that: the decoder read
788- // PHANTOM coefficient units in the all-skip inter frame and
789- // then panicked in `reconstruct_mc_rect` on a full-height
790- // 4:2:2 chroma rect. So the cell's non-vacuity is a NEGATIVE
791- // measurement on the CHROMA planes, asserted here rather than
792- // inherited: the walk ran (units > 0, which the shared body
793- // checks) and coded nothing on U or V.
794- assert_eq!(
795- (coded_delta[1], coded_delta[2]),
796- (0, 0),
797- "{NAME}: {file} CODED a chroma coefficient -- this is the all-skip inter-frame \
798- cell and a phantom residual read is exactly the defect it witnesses"
799- );
800- }
801- }
802- }
803-
804- /// lane-av1muchroma: the `chroma_side * chroma_side` mu-chroma site
805- /// census, over the whole committed 4:2:2 corpus, as a per-site
806- /// REACHABILITY measurement with a non-vacuity arm.
807- ///
808- /// `lanes/av1subsizesweep.report.md` named "mu-chroma sites using
809- /// `chroma_side * chroma_side`" as unprobed residue. This lane's sweep
810- /// (env-gated probe at each of the 12 sites, run over every pinned 4:2:2
811- /// gate) measured them:
812- ///
813- /// - sites 4, 7, 10 are guarded `ss_x == 0 && ss_y == 0`, i.e. 4:4:4
814- /// ONLY -- structurally unreachable at 4:2:2, not merely unwitnessed.
815- /// - sites 2, 8 (`side > 64` mu-chunk walks) were not reached by any
816- /// committed 4:2:2 fixture; their single-reference twin, site 5, is
817- /// (side 128, plane 64x128), and its square allocation is the ENCLOSING
818- /// square, so it is 2x oversized, never short.
819- /// - sites 1, 3, 5, 6, 9, 11, 12 ARE reached. For 3/5/6/9/11/12
820- /// `chroma_side` is `max(side >> ss_x, side >> ss_y)` (decode.rs), the
821- /// ENCLOSING square of the plane rect, so at 4:2:2 the square is 2x
822- /// the per-axis extent: oversized, never short.
823- /// - site 1 alone still used `side >> ss_x` and was therefore sized at
824- /// HALF the plane block at 4:2:2. Fixed per-axis; this gate pins it.
825- ///
826- /// Non-vacuity: [`crate::decode::skip_arm_chroma_plane_block_hits`]
827- /// fires only where the per-axis and square forms differ, so a green run
828- /// that never reached the site would be vacuous and this asserts > 0.
829- #[test]
830- fn the_422_skip_arm_chroma_grid_is_sized_per_axis_not_square() {
831- const NAME: &str = "the_422_skip_arm_chroma_grid_is_sized_per_axis_not_square";
832- const FILE: &str = "s422_322x240.obu";
833- const BYTES: usize = 21096;
834- const FP: u64 = 0x9a96dda2a19d47a6;
835- const W: usize = 322;
836- const H: usize = 240;
837- const FRAMES: usize = 16;
838- let _gate_lock = lock_gate_counters();
839- let data = std::fs::read(crate_pin(FILE)).unwrap_or_else(|e| {
840- panic!("{NAME}: the committed pin {FILE} is missing ({e}) -- a failure, not a skip")
841- });
842- assert_eq!(data.len(), BYTES, "{NAME}: {FILE} size drifted");
843- assert_eq!(fnv1a64(&data), FP, "{NAME}: {FILE} bytes drifted");
844- let rect_before = crate::decode::skip_arm_chroma_rect_shapes();
845- let short_before = crate::decode::skip_arm_chroma_short_samples();
846- let ours = decode_stream(&data)
847- .unwrap_or_else(|e| panic!("{NAME}: decode_stream refused a real 4:2:2 stream: {e}"));
848- assert_eq!(ours.len(), FRAMES, "{NAME}: decoded frame count");
849- for (i, f) in ours.iter().enumerate() {
850- assert_eq!((f.width, f.height), (W, H), "{NAME}: frame {i} dimensions");
851- assert_eq!(
852- (f.u.len(), f.v.len()),
853- (W.div_ceil(2) * H, W.div_ceil(2) * H),
854- "{NAME}: frame {i} chroma planes are {}/{} samples -- 4:2:2 is HALF WIDTH and \
855- FULL HEIGHT; a quarter-height plane means the decode kept a 4:2:0 allocation",
856- f.u.len(),
857- f.v.len()
858- );
859- }
860- let rect_after = crate::decode::skip_arm_chroma_rect_shapes();
861- assert!(
862- rect_after > rect_before,
863- "{NAME}: no skipped block decoded at a rect chroma shape ({rect_before} -> \
864- {rect_after}) -- this gate is then VACUOUS: per-axis and square sizing are the \
865- same number at 4:2:0 and 4:4:4, so it proves nothing about the site it claims"
866- );
867- let short_after = crate::decode::skip_arm_chroma_short_samples();
868- assert_eq!(
869- short_after, short_before,
870- "{NAME}: decode_block's SKIP arm chroma grids fell {short_after} samples SHORT of \
871- their own plane block -- the square `side >> ss_x` form this lane removed allocates \
872- exactly half the plane block at 4:2:2 (ss (1,0))"
873- );
874- }
875-
876- /// lane-av1floorshift: the two FRAME chroma plane allocators
877- /// (`decode_key_frame_tile_with_cdfs`, `decode_inter_tile`) size U and V as
878- /// `(width >> ss_x) x (height >> ss_y)`. `lanes/av1subsizesweep.report.md`
879- /// named them "floor-`>>` chroma plane allocators -- shape assumption at
880- /// frame edges; not probed" and left them open. This is the probe.
881- ///
882- /// **The verdict is ALREADY CORRECT, and it is structural, not
883- /// corpus-luck.** `width`/`height` are `block_grid(mi_cols, mi_rows) *
884- /// BLOCK` (`BLOCK == 32`) and the allocator is handed those, not the frame's
885- /// own `true_width`/`true_height`: both axes are multiples of 32, and
886- /// `ss_x`/`ss_y` are the sequence header's single-bit subsampling fields,
887- /// so `ss <= 1` on every stream that exists. `32k >> ss == round_ss(32k, ss)`
888- /// for every `k` and every `ss <= 1` -- the `>>` can never floor one sample
889- /// short of libaom's own chroma crop, at a frame edge or anywhere else. The
890- /// static half of the gate below proves that exhaustively over every
891- /// `mi_cols`/`mi_rows` this decoder admits.
892- ///
893- /// The corpus half keeps the instrument honest: it decodes one frame per
894- /// selectable subsampling cell and asserts the allocators were REACHED
895- /// (`frame_chroma_alloc_calls` moved), so a green run cannot be the census
896- /// having been wired to nothing.
897- ///
898- /// Witnesses, all byte-pinned (`size`, `fnv1a64`), chosen to cover all
899- /// three selectable cells and both allocators:
900- ///
901- /// | file | cell | frame | covers |
902- /// |---|---|---|---|
903- /// | `420_odd65x65_key.obu` | 4:2:0, **odd** 65x65 | key | key allocator, the odd-dimension cell where a floor WOULD show |
904- /// | `422_key_64x64.obu` | 4:2:2 (1,0) | key | key allocator, half-width/full-height |
905- /// | `444_intrabc_rect4_witness.obu` | 4:4:4 (0,0) | key | key allocator, the `ss == 0` cell where `>> ss` is the identity |
906- ///
907- /// 4:4:0 (`0,1`) is excluded and cannot be added: libaom's
908- /// `av1_read_color_config` asserts `subsampling_y == 0` when
909- /// `subsampling_x == 0`, and no of 256 header bytes reads back `(0,1)` --
910- /// the reader census at `the_reader_never_produces_440` names it.
911- #[test]
912- fn the_frame_chroma_planes_are_allocated_on_the_per_axis_floor_that_never_rounds() {
913- const NAME: &str =
914- "the_frame_chroma_planes_are_allocated_on_the_per_axis_floor_that_never_rounds";
915- let _gate_lock = lock_gate_counters();
916- for (file, bytes, fp, cell, ss) in [
917- (
918- "420_odd65x65_key.obu",
919- 2305usize,
920- 0xf55645c4b139e8f7u64,
921- "4:2:0",
922- (1usize, 1usize),
923- ),
924- (
925- "422_key_64x64.obu",
926- 755,
927- 0x87fc569cf53bcbc6,
928- "4:2:2",
929- (1, 0),
930- ),
931- (
932- "444_intrabc_rect4_witness.obu",
933- 1016,
934- 0x27c2fad540472994,
935- "4:4:4",
936- (0, 0),
937- ),
938- ] {
939- let data = std::fs::read(crate_pin(file))
940- .unwrap_or_else(|e| panic!("{NAME}: the committed pin {file} is missing ({e})"));
941- assert_eq!(data.len(), bytes, "{NAME}: {file} size drifted");
942- assert_eq!(fnv1a64(&data), fp, "{NAME}: {file} bytes drifted");
943- let calls_before = crate::decode::frame_chroma_alloc_calls();
944- let short_before = crate::decode::frame_chroma_alloc_short_samples();
945- let crop_before = crate::decode::frame_chroma_alloc_crop_shapes();
946- let frames = decode_stream(&data)
947- .unwrap_or_else(|e| panic!("{NAME}: {file} ({cell}) refused: {e}"));
948- let calls = crate::decode::frame_chroma_alloc_calls() - calls_before;
949- assert!(
950- calls >= frames.len(),
951- "{NAME}: {file} ({cell}) decoded {} frames but the chroma plane allocator ran \
952- {calls} times -- the instrument is not on the path this gate claims to cover",
953- frames.len()
954- );
955- // The shape the allocator owes the tile, and the shape the output
956- // crop owes the caller: libaom's chroma CROP of the frame's own
957- // dimensions (`av1_round_shift`), which is what
958- // `decode_key_frame_tile_with_cdfs`'s `Picture` crop uses. At the
959- // odd 65x65 4:2:0 cell this is 33x33 -- 1089 samples, NOT the
960- // floor 32x32 an `>>` short of the true extent would have left.
961- for (i, f) in frames.iter().enumerate() {
962- let (cw, ch) = (
963- crate::decode::round_ss(f.width, ss.0),
964- crate::decode::round_ss(f.height, ss.1),
965- );
966- assert_eq!(
967- (f.u.len(), f.v.len()),
968- (cw * ch, cw * ch),
969- "{NAME}: {file} ({cell}) frame {i} is {}x{} and its chroma planes are {} / {} \
970- samples; {cell} is a {cw}x{ch} = {} crop",
971- f.width,
972- f.height,
973- f.u.len(),
974- f.v.len(),
975- cw * ch
976- );
977- }
978- let short = crate::decode::frame_chroma_alloc_short_samples() - short_before;
979- assert_eq!(
980- short, 0,
981- "{NAME}: {file} ({cell}) allocated {short} chroma samples SHORT of the `round_ss` \
982- extent the tile's chroma walks may address -- the frame chroma planes are sized \
983- by a FLOOR `>> ss` that does not round"
984- );
985- let crop = crate::decode::frame_chroma_alloc_crop_shapes() - crop_before;
986- assert_eq!(
987- crop, 0,
988- "{NAME}: {file} ({cell}) reached a frame shape on which `>> ss` and `round_ss` \
989- disagree ({crop} frames) -- the allocators are handed a MULTIPLE OF 32 \
990- (block_grid * BLOCK) and `ss <= 1`, so this can only mean the allocator's own \
991- argument changed, and the shortfall assertion above is then vacuous on this file"
992- );
993- }
994- }
995-
996- /// lane-av1floorshift: the STATIC half of the same claim, and the part that
997- /// does not need a corpus. The frame chroma allocators' shift argument is
998- /// `block_grid(mi_cols, mi_rows) * BLOCK` with `BLOCK == 32`, so for every
999- /// `mi_cols`/`mi_rows` this decoder can admit and every subsampling the
1000- /// header can carry (`ss in {0, 1}` per axis), `>> ss` and `round_ss` are
1001- /// the same number. Exhaustively checked here over a range wider than any
1002- /// frame a header can declare; the two counters above are zero for a
1003- /// reason, and this is the reason.
1004- #[test]
1005- fn the_frame_chroma_alloc_shift_argument_cannot_floor_below_round_ss() {
1006- const NAME: &str = "the_frame_chroma_alloc_shift_argument_cannot_floor_below_round_ss";
1007- const BLOCK: usize = 32;
1008- // `block_grid(mi) = mi.div_ceil(BLOCK_MI)` with `BLOCK_MI == 8`
1009- // (`tile.rs`), so the allocator's width is `(mi.div_ceil(8)) * 32`.
1010- for mi in 1..=512usize {
1011- let coded = mi.div_ceil(8) * BLOCK;
1012- for ss in 0..=1usize {
1013- assert_eq!(
1014- coded >> ss,
1015- crate::decode::round_ss(coded, ss),
1016- "{NAME}: coded {coded} (mi {mi}) at ss {ss}: the floor and the crop differ -- \
1017- the frame chroma plane would be allocated short"
1018- );
1019- // The TRUE extent is `mi * 4`; it is what the allocator
1020- // derives `true_width` from and what every chroma walk is
1021- // clamped against, so it earns the same check.
1022- let truth = mi * 4;
1023- assert_eq!(
1024- truth >> ss,
1025- crate::decode::round_ss(truth, ss),
1026- "{NAME}: true {truth} (mi {mi}) at ss {ss}: the floor and the crop differ"
1027- );
1028- }
1029- }
1030- // And the 4:4:0 cell libaom refuses, spelled out rather than left as
1031- // an assumption: at `ss (0,1)` the shift is exact too, so the site
1032- // would be correct even if the cell were ever admitted.
1033- for mi in 1..=64usize {
1034- assert_eq!((mi * 4) >> 1, crate::decode::round_ss(mi * 4, 1));
1035- assert_eq!(mi * 4, crate::decode::round_ss(mi * 4, 0));
1036- }
1037- }
1038-
1039- /// lane-av1422tailskip: the WITNESS cell for the 4:2:2 intra-in-inter
1040- /// PALETTE chroma per-unit window, and its byte pin.
1041- ///
1042- /// `422_palette_intra_in_inter_384x240_17f.obu` (19344 B, sha256
1043- /// `bf1c658e9bfdc13ec1ed51e59049d2b81201941b6ef4571f8382f356ea4b815b`) is
1044- /// the one 4:2:2 cell of the 384x240 census sweep: 384x240, ss (1,0),
1045- /// 8-bit, **17 decode frames, 16 shown** (decode 1 is the hidden altref).
1046- /// Its decode-frame-1 block at mi(32,0) is a 64x64 INTRA block with a
1047- /// PALETTE -- `aomdec`'s `EC_PIB` prints `use_palette=1` there, and the
1048- /// oracle's own prediction rungs print nothing for the block because
1049- /// `av1_predict_intra_block` returns at its palette branch before them
1050- /// (`reconintra.c:1735`).
1051- ///
1052- /// At 4:2:2 that block's chroma plane block is 32x64, but
1053- /// `av1_get_max_uv_txsize` adjusts `max_tx_size_rect_lookup[BLOCK_32X64]`
1054- /// down to TX_32X32, so it codes TWO STACKED SQUARE units per plane.
1055- /// `decode_inter_block`'s `side == 64` walk armed the ONE block-sized
1056- /// 2048-entry chroma palette prediction before the loop: the first unit
1057- /// consumed all of it and the second found none pending, so it silently
1058- /// fell back to the edge DC prediction -- a flat 90/240 box where the
1059- /// oracle carries its palette (U/V rows 170..189, cols 23..31, 180 wrong
1060- /// samples per plane at the pre-filter stage). Each unit now takes its own
1061- /// `palette_window` of that buffer (`decode.rs`) -- the same helper the
1062- /// split-transform chroma paths already used.
1063- ///
1064- /// **The committed assertion follows the family's standing rule** (same
1065- /// shape as
1066- /// [`the_pinned_422_bigblock_witnesses_are_present_and_refuse_by_name`]):
1067- /// the byte pin plus this decoder's disposition of those bytes.
1068- /// lane-av1422lift: `decode_stream` no longer refuses 4:2:2 at the sequence
1069- /// header, so the OK arm is the live one -- the gate decodes the pin and
1070- /// asserts 17 decode-order frames byte-exact against aomdec with
1071- /// `palette_422_unit_window_hits()` fired. lane-av1oracledepth: the stale
1072- /// `Err` arm (it matched the pre-lift refusal string
1073- /// `"a chroma format of 4:2:2"` the decoder no longer returns, and could
1074- /// have swallowed a future decode error as green) is deleted; a refusal
1075- /// now fails this gate loudly.
1076- #[test]
1077- fn the_pinned_422_palette_intra_in_inter_cell_window_is_byte_exact() {
1078- const NAME: &str = "the_pinned_422_palette_intra_in_inter_cell_window_is_byte_exact";
1079- const FILE: &str = "422_palette_intra_in_inter_384x240_17f.obu";
1080- const BYTES: usize = 19344;
1081- const FP: u64 = 0x923ccabfcb933e90;
1082- let _gate_lock = lock_gate_counters();
1083- let data = std::fs::read(crate_pin(FILE)).unwrap_or_else(|e| {
1084- panic!("{NAME}: the committed pin {FILE} is missing ({e}) -- a failure, not a skip")
1085- });
1086- assert_eq!(data.len(), BYTES, "{NAME}: {FILE} size drifted");
1087- assert_eq!(fnv1a64(&data), FP, "{NAME}: {FILE} bytes drifted");
1088- let before = crate::decode::palette_422_unit_window_hits();
1089- // lane-av1oracledepth: the OK arm is MEASURED to be the live one (the
1090- // pinned bytes decode, 17 decode-order frames byte-exact vs aomdec,
1091- // 16 windowed units) and the old `Err` arm matching the pre-lift
1092- // refusal string "a chroma format of 4:2:2" is deleted: committed
1093- // code no longer returns that string, so the arm could only ever
1094- // swallow a FUTURE decode error that happened to contain it and read
1095- // green off a stream that decoded nothing. A refusal today now fails
1096- // this gate loudly, as it should.
1097- match decode_stream(&data) {
1098- Err(e) => {
1099- panic!(
1100- "{NAME}: {FILE} was refused by the current decoder: {e}. 4:2:2 is a \
1101- DECODED format; a refusal here is a regression, not the old sequence-\
1102- header gate"
1103- )
1104- }
1105- Ok(_) => {
1106- let windows = crate::decode::palette_422_unit_window_hits() - before;
1107- assert!(
1108- windows > 0,
1109- "{NAME}: {FILE} decoded, but no 4:2:2 intra-in-inter chroma unit took \
1110- the per-unit palette window ({windows} did) -- this cell does not \
1111- exercise the arm at all (class gate-blind-to-feature)"
1112- );
1113- let (decoded, hidden) = decode_all_frames_vs_oracle(&data, FILE);
1114- assert_eq!(
1115- decoded, 17,
1116- "{NAME}: the oracle decoded {decoded} frames in DECODE order, not 17"
1117- );
1118- assert_eq!(hidden, 1, "{NAME}: expected exactly the one hidden altref");
1119- eprintln!(
1120- "{NAME}: {decoded} decode-order frame(s) byte-exact against aomdec \
1121- ({hidden} hidden), {windows} chroma palette unit window(s)"
1122- );
1123- }
1124- }
1125- }
1126-
1127- /// lane-av1-ibc128chunk: the WITNESS for the 128-root intrabc strip's
1128- /// de-square-cut mu-chunk chroma walk, and the byte pin for it.
1129- ///
1130- /// `decode_intrabc_128rect` cut each mu chunk's chroma plane block with
1131- /// `chunk_chroma = cside * 64 / side` -- a `chroma_side`-SQUARE chunk,
1132- /// i.e. the 4:2:0 count on BOTH axes (the same defect lane-av1-422bigblock
1133- /// fixed, and witnessed, in `decode_inter_block` and
1134- /// `decode_block_128rect`; this copy was deferred there as unwitnessed).
1135- /// At 4:2:2 a 64x64 mu chunk's chroma plane block is 32x64, so it holds
1136- /// TWO STACKED TX_32X32 units per plane: the square-cut walk read one per
1137- /// plane per chunk, left the chunk's lower 32 chroma rows with no
1138- /// residual at all, and stamped each unit's entropy context over a
1139- /// 16x16-mi luma span instead of 16x8.
1140- ///
1141- /// Measured red-before on the pinned witness (parent `a7d22aec`, via the
1142- /// local `EC_AV1_ALLOW_422_PROBE` patch-run-restore build): 8 chroma
1143- /// units stamped over the stream's two reached blocks and frames 0 and 3
1144- /// diverge from `aomdec` (45135 / 44540 of 245760 samples each), the
1145- /// first difference at Y sample 98368 -- frame 0, row 256, col 64, the
1146- /// top-left corner of the first 128x64 intrabc block at mi(64,0). The
1147- /// red build then lost 4 of the stream's 6 intrabc blocks to the desync.
1148- /// Green-after, same fixture: 48 chroma units stamped, all 6 blocks
1149- /// decoded, and ALL FIVE frames byte-identical to `aomdec --rawvideo`.
1150- ///
1151- /// lane-av1422lift: committed code no longer refuses 4:2:2 at the
1152- /// sequence header, so the red/green evidence above is no longer
1153- /// probe-only: this gate is the one that asserts it. Both pins are
1154- /// byte-pinned AND byte-exact against ffmpeg's `yuv422p` rawvideo of the
1155- /// same bytes, per plane and per frame, with the per-plane
1156- /// coefficient-unit census as the non-vacuity arm -- the census is what
1157- /// makes "48 chroma units stamped" a committed, reproducible number here
1158- /// instead of a sentence in a lane report. The source-scan arm below
1159- /// keeps its own claim (the per-axis SPELLING) and does not overlap.
1160- #[test]
1161- fn the_pinned_422_intrabc_sb128_strip_witnesses_decode_pixel_exact() {
1162- const NAME: &str = "the_pinned_422_intrabc_sb128_strip_witnesses_decode_pixel_exact";
1163- if !have_ffmpeg() {
1164- eprintln!("SKIP {NAME}: no ffmpeg");
1165- return;
1166- }
1167- for (file, bytes, fp) in [
1168- (
1169- "422_intrabc_sb128_strip.obu",
1170- 1672usize,
1171- 0x50f5cfc576e4cd00_u64,
1172- ),
1173- (
1174- "422_intrabc_sb128_strip_notxsearch.obu",
1175- 1675,
1176- 0xd4936f252ff8cff0,
1177- ),
1178- ] {
1179- let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1180- .join("fixtures")
1181- .join(file);
1182- let data = std::fs::read(&path).unwrap_or_else(|e| {
1183- panic!(
1184- "{NAME}: pinned witness {} is missing ({e}) -- the gate cannot run",
1185- path.display()
1186- )
1187- });
1188- assert_eq!(data.len(), bytes, "{NAME}: {file} size drifted");
1189- assert_eq!(fnv1a64(&data), fp, "{NAME}: {file} bytes drifted");
1190- assert_422_stream_pixel_exact(NAME, &data, 384, 320, 5, 8, true);
1191- }
1192- }
1193-
1194- /// lane-av1422a2a4: the firing gate for `decode_block`'s var-tx EITHER/OR
1195- /// tail at 4:2:2 -- an INTRABC block whose var-tx tree resolved MIXED
1196- /// leaves, where the old blanket `set_txfm_ctxs` + `fill_lf_grid` publishes
1197- /// clobbered the per-leaf TXFM_CONTEXT bands libaom keeps.
1198- ///
1199- /// Provenance: aomenc profile 2, `testsrc2=size=128x112:rate=25` tiled 2x2
1200- /// to 256x224, cq 30, 3 frames (`lanes/av1422ibcrect.report.md` §2, stream
1201- /// A4). The oracle decodes it to completion; the pre-fix tree refused it
1202- /// mid-tile with the documented `decodeframe.c:1456` subsize string -- the
1203- /// E6/E7 desync-symptom class, NOT an invalid shape.
1204- ///
1205- /// Measured on the pinned bytes: the 32x32 intrabc block at mi(32,8)
1206- /// resolves leaves (0,0)+((0,4) 8x8, (4,0)+(4,4) 16x16, so
1207- /// `left_txfm[32..35]` must read 16 when the NEXT tree's sub-unit at
1208- /// (32,16) row0col0 reads its `txfm_partition` context (oracle operands
1209- /// `above=16 left=16`, ctx 9). The blanket publishes reset those cells to
1210- /// 8 -> ctx 10 -> a wrong `is_split` -> the first divergent read, and the
1211- /// refusal surfaced ~30 partition symbols later.
1212- #[test]
1213- fn the_pinned_422_intrabc_vartx_mixedtree_witnesses_decode_pixel_exact() {
1214- const NAME: &str = "the_pinned_422_intrabc_vartx_mixedtree_witnesses_decode_pixel_exact";
1215- if !have_ffmpeg() {
1216- eprintln!("SKIP {NAME}: no ffmpeg");
1217- return;
1218- }
1219- let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1220- .join("fixtures")
1221- .join("422_intrabc_vartx_mixedtree_a4.obu");
1222- let data = std::fs::read(&path).unwrap_or_else(|e| {
1223- panic!(
1224- "{NAME}: pinned witness {} is missing ({e}) -- the gate cannot run",
1225- path.display()
1226- )
1227- });
1228- assert_eq!(data.len(), 30937, "{NAME}: pinned witness size drifted");
1229- assert_eq!(
1230- fnv1a64(&data),
1231- 0x6f0fc77c2217910a_u64,
1232- "{NAME}: pinned witness bytes drifted"
1233- );
1234- assert_422_stream_pixel_exact(NAME, &data, 256, 224, 3, 8, true);
1235- }
1236-
1237- /// lane-av1422ibctxsel: the firing gate for `decode_intrabc_owned_rect`'s
1238- /// NON-SPLIT chroma coefficient context at 4:2:2.
1239- ///
1240- /// `lanes/av1422gathercensus.report.md` closed its ss (1, 0) class sweep
1241- /// with this one gather at STOP -- unwitnessed: `around_mi_rect` over the
1242- /// block's LUMA span feeds the CHROMA `dc_sign_ctx`, and at ss (1, 0) a
1243- /// chroma 4-px cell spans TWO luma mi columns, so the per-mi sum counts
1244- /// every chroma column twice (`around_mi_422_chroma`'s every-second
1245- /// sampling is libaom's one-vote-per-cell sum). `lane-av1422ibcrect`
1246- /// found a stream that ENTERS the gather (24 entries) but whose two
1247- /// gathers agree on every entry, so the class stayed harmless-ON-THAT-
1248- /// STREAM, not proven.
1249- ///
1250- /// This fixture is the discriminating witness: aomenc profile 2, 384x288
1251- /// 4:2:2, 4 key frames, `--sb-size=64` with the last superblock row half
1252- /// outside the frame (so the 64-root partition is a single gathered bit
1253- /// and the strips are 64x32 HORZ intra-BC strips), `--enable-tx-size-
1254- /// search=1` plus a high-frequency patch that keeps the frame's `tx_mode`
1255- /// at `TX_MODE_SELECT` (`txb_split_count > 0`; without it encodeframe.c
1256- /// :2690 downgrades every frame to `TX_MODE_LARGEST`), and a chroma band
1257- /// above the strips so a full-weight above context meets a full-weight
1258- /// left one of the opposite sign.
1259- ///
1260- /// Measured on the pinned bytes: 24 non-split chroma gathers entered (6
1261- /// strips x 4 frames; 48 plane reads), and FIVE of them -- plane 2, strips
1262- /// mi (64,16)..(64,80) of frame 0 -- read `dc_sign_ctx` 1 through the
1263- /// luma-span gather against libaom's 0 through the pair rule (`full = 2A +
1264- /// L = -8`, `pair = A + L = 0`: the double-counted above vote crosses
1265- /// zero, and the context is a sign).
1266- ///
1267- /// Red-before (the route reverted, same fixture bytes): the wrong sign
1268- /// context changes the decoded dc-sign CDF and desyncs the tile -- the
1269- /// decoder refuses the stream mid-frame with "a block size 4x8, 8x16 or
1270- /// 16x4 ... has no chroma plane block at this frame's subsampling mode",
1271- /// so NO frame decodes at all. That refusal is also the proof it is a
1272- /// desync symptom and not a real sub-8x8 shape: both oracles decode the
1273- /// pinned bytes fully. Green-after: 4/4 frames byte-exact against
1274- /// ffmpeg's `yuv422p` rawvideo, with the per-plane coefficient-unit
1275- /// census (the helper's) and the pair-rule route counter as the
1276- /// non-vacuity arms. The 4:4:4 arm below pins the guard's other side:
1277- /// the same function at ss (0, 0) keeps the verbatim luma-span gather and
1278- /// must NOT fire the route.
1279- #[test]
1280- fn a_422_intrabc_owned_rect_nonsplit_chroma_context_uses_the_pair_rule() {
1281- const NAME: &str = "a_422_intrabc_owned_rect_nonsplit_chroma_context_uses_the_pair_rule";
1282- const FILE: &str = "ibc422_nonsplit_ctx.obu";
1283- const LEN: usize = 2170;
1284- /// sha256 `4f82d5da8b4c3d6553953fc373001a1c7a729c9b189214b65503af1e04eb6b68`,
1285- /// fnv1a64 `0x92e2c4e45ca27e34`.
1286- const FNV: u64 = 0x92e2c4e45ca27e34;
1287- if !have_ffmpeg() {
1288- eprintln!("SKIP {NAME}: no ffmpeg");
1289- return;
1290- }
1291- let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1292- .join("fixtures")
1293- .join(FILE);
1294- let data = std::fs::read(&path).unwrap_or_else(|e| {
1295- panic!(
1296- "{NAME}: pinned witness {} is missing ({e}) -- the gate cannot run",
1297- path.display()
1298- )
1299- });
1300- assert_eq!(data.len(), LEN, "{NAME}: {FILE} size drifted");
1301- assert_eq!(fnv1a64(&data), FNV, "{NAME}: {FILE} bytes drifted");
1302- // No `lock_gate_counters()` here: the bumps are thread-local, and
1303- // `assert_422_stream_pixel_exact` takes that same (non-reentrant)
1304- // mutex itself -- holding it across this call self-deadlocks.
1305- crate::decode::reset_ibc_owned_rect_422_pair_hits();
1306- assert_422_stream_pixel_exact(NAME, &data, 384, 288, 4, 8, true);
1307- let hits = crate::decode::ibc_owned_rect_422_pair_hits();
1308- assert_eq!(
1309- hits, 24,
1310- "{NAME}: the pair-rule route fired {hits} times, not 24 (6 non-split chroma gathers \
1311- x 4 frames) -- the witness stopped exercising the arm, or the guard's extent moved"
1312- );
1313- // The guard's other arm: the 4:4:4 owner-rect stream (`r512.obu`,
1314- // pinned by the gate below) reaches this same function at ss (0, 0),
1315- // where the verbatim luma-span gather is correct -- the route counter
1316- // must stay put.
1317- let r512 = std::fs::read(
1318- std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("fixtures/r512.obu"),
1319- )
1320- .expect("r512.obu must exist");
1321- crate::decode::reset_ibc_owned_rect_422_pair_hits();
1322- let _ = decode_stream(&r512).expect("the 4:4:4 owner-rect witness decodes");
1323- assert_eq!(
1324- crate::decode::ibc_owned_rect_422_pair_hits(),
1325- 0,
1326- "{NAME}: the 4:2:2 pair-rule route fired on a 4:4:4 stream -- the ss (1, 0) guard \
1327- leaks (class gate-blind-to-feature)"
1328- );
1329- }
1330-
1331- /// lane-av1-ibc128chunk: the SOURCE-SCAN arm of the witness gate above.
1332- ///
1333- /// The decode-level half of the red/green evidence now runs in committed
1334- /// code too -- the witness gate above,
1335- /// `the_pinned_422_intrabc_sb128_strip_witnesses_decode_pixel_exact`,
1336- /// decodes both pins byte-exact against ffmpeg (lane-av1422lift lifted the
1337- /// sequence-header refusal). This arm complements it by pinning the thing
1338- /// that would silently bring the defect back: the square-cut
1339- /// `chunk_chroma = cside * 64 / side` expression, and the per-axis
1340- /// replacements that replaced it at BOTH sites in
1341- /// [`decode_intrabc_128rect`] -- the mu-chunk read walk and the
1342- /// `mu_chroma` per-unit context replay. It also pins the per-axis
1343- /// counters' accessors so the arms stay reachable, and the walk's own
1344- /// per-axis extent, derived here from the same `64 >> ss` form the
1345- /// witnesses measured (4:2:0 = one TX_32X32 per plane per chunk,
1346- /// 4:2:2 = two stacked, 4:4:4 = four).
1347- #[test]
1348- fn the_intrabc_128rect_chroma_chunk_walk_stays_per_axis() {
1349- const NAME: &str = "the_intrabc_128rect_chroma_chunk_walk_stays_per_axis";
1350- let src = crate::test_source::module_source("decode");
1351- let body = src
1352- .split_once("fn decode_intrabc_128rect(")
1353- .expect("decode_intrabc_128rect must exist")
1354- .1
1355- .split_once("\nfn ")
1356- .expect("decode_intrabc_128rect must be a top-level fn")
1357- .0;
1358- // Scan CODE only: the fix's own comments quote the old expression to
1359- // say what it was, and a prose mention must not read as a
1360- // reintroduction (nor mask one).
1361- let stripped: Vec<&str> = body
1362- .lines()
1363- .map(|l| l.split_once("//").map_or(l, |(c, _)| c))
1364- .collect();
1365- let code = stripped.join("\n");
1366- let body = code.as_str();
1367- assert_eq!(
1368- body.matches("cside * 64 / side").count(),
1369- 0,
1370- "{NAME}: the square-cut `cside * 64 / side` chunk extent is BACK in \
1371- decode_intrabc_128rect -- that expression is the 4:2:2 defect this \
1372- gate exists for (a 64x64 mu chunk's chroma plane block is \
1373- (64 >> ss_x) x (64 >> ss_y), not `chroma_side` square)"
1374- );
1375- // The per-axis chunk extent, declared once at the mu-chunk read walk
1376- // and once at the `mu_chroma` replay -- the two de-square-cut sites.
1377- //
1378- // The replay must ALSO enumerate every unit inside a chunk, not just
1379- // its first: counting mu CHUNKS in `rows`/`cols` and then stepping the
1380- // mi origin and reading the grid per UNIT only agrees when a chunk
1381- // holds exactly one unit (4:2:0). At 4:2:2 and 4:4:4 a chunk holds two
1382- // or four, so the per-unit body alone left the rest of the chunk with
1383- // the composed-grid smearing the replay exists to undo.
1384- for name in [
1385- "let chunk_chroma_w = (64usize) >> ss_x(fctx);",
1386- "let chunk_chroma_h = (64usize) >> ss_y(fctx);",
1387- ] {
1388- assert_eq!(
1389- body.matches(name).count(),
1390- 2,
1391- "{NAME}: `{name}` must appear at BOTH de-square-cut sites in \
1392- decode_intrabc_128rect (the mu-chunk read walk and the mu_chroma \
1393- context replay), found {}",
1394- body.matches(name).count()
1395- );
1396- }
1397- for name in [
1398- "let (ur, uc) = (chunk_chroma_h / cu, chunk_chroma_w / cu);",
1399- "for kr in 0..ur {",
1400- "for kc in 0..uc {",
1401- ] {
1402- assert_eq!(
1403- body.matches(name).count(),
1404- 1,
1405- "{NAME}: `{name}` must appear exactly once in \
1406- decode_intrabc_128rect -- the mu_chroma replay must walk chunk \
1407- THEN unit (decode_inter_block's `mu_chroma_units` shape), found {}",
1408- body.matches(name).count()
1409- );
1410- }
1411- for name in [
1412- "let unit_luma_w = cu_tx << ss_x(fctx);",
1413- "let unit_luma_h = cu_tx << ss_y(fctx);",
1414- "let (cw, ch) = (bw >> ss_x(fctx), bh >> ss_y(fctx));",
1415- "let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));",
1416- "neighbours.around_mi_rect(unit_mi, unit_luma_w, unit_luma_h)",
1417- ] {
1418- assert_eq!(
1419- body.matches(name).count(),
1420- 1,
1421- "{NAME}: `{name}` must appear exactly once in \
1422- decode_intrabc_128rect, found {}",
1423- body.matches(name).count()
1424- );
1425- }
1426- // lane-av1muchunk422sym: the CHROMA gather of that same walk must take
1427- // the 4:2:2 pair rule, exactly as `decode_inter_block`'s mu-chunk walk
1428- // does (one chroma column per pair of luma mi cells; the plain rect
1429- // gather doubles the above dc vote and flips `dc_sign_ctx` wherever
1430- // above and left cancel). Reachability is measured: the walk fires at
1431- // ss (1, 0) on `422_intrabc_sb128_strip.obu` (`EC_IBC128_BANDS`
1432- // prints); that fixture's own votes do not cancel, so THIS gate -- not
1433- // a pixel compare -- is what stops the routing being reverted.
1434- for name in [
1435- "let cu_around = if ss_x(fctx) == 1 && ss_y(fctx) == 0 {",
1436- "neighbours.around_mi_422_chroma(",
1437- ] {
1438- assert_eq!(
1439- body.matches(name).count(),
1440- 1,
1441- "{NAME}: `{name}` must appear exactly once in \
1442- decode_intrabc_128rect's chroma chunk walk, found {} -- the \
1443- gather has fallen back to the square per-mi rule",
1444- body.matches(name).count()
1445- );
1446- }
1447- // The replay's own unit luma span is the lossless/lossy `cu << ss` form
1448- // (site 2 spells it separately from the read walk's `cu_tx << ss`).
1449- for name in [
1450- "let unit_luma_w = cu << ss_x(fctx);",
1451- "let unit_luma_h = cu << ss_y(fctx);",
1452- ] {
1453- assert_eq!(
1454- body.matches(name).count(),
1455- 1,
1456- "{NAME}: `{name}` must appear exactly once in \
1457- decode_intrabc_128rect, found {}",
1458- body.matches(name).count()
1459- );
1460- }
1461- // The per-axis chunk extent the geometry demands, spelled out here so
1462- // the scan and the witnesses cannot disagree about it.
1463- let per_axis_units = |ss_x: u32, ss_y: u32| (64 >> ss_x) / 32 * (64 >> ss_y) / 32;
1464- assert_eq!(per_axis_units(1, 1), 1, "{NAME}: 4:2:0 must stay one unit");
1465- assert_eq!(per_axis_units(1, 0), 2, "{NAME}: 4:2:2 must be two units");
1466- assert_eq!(per_axis_units(0, 0), 4, "{NAME}: 4:4:4 must be four units");
1467- // The counters the probe arms read must stay exported.
1468- for name in [
1469- "pub fn intrabc_128rect_chroma_chunk_hits()",
1470- "pub fn intrabc_128rect_chunk_shape()",
1471- ] {
1472- assert!(
1473- src.contains(name),
1474- "{NAME}: the accessor `{name}` must stay in decode.rs"
1475- );
1476- }
1477- }
1478-
1479- /// lane-av1422gather3: `decode_block_128rect`'s per-chunk CHROMA unit
1480- /// walk gathered its coefficient context with the plain square-cut
1481- /// `around_mi_rect`, so at ss (1,0) its above dc vote summed 16 LUMA mi
1482- /// cells where libaom's `get_txb_ctx_general` reads `txb_w_unit` =
1483- /// `chroma_tx / 4` = 8 CHROMA cells (one chroma column per PAIR of luma
1484- /// mi columns; both luma cells of a column carry the covering unit's
1485- /// whole-unit dc sign). That is the same pair rule the mu-chunk walks
1486- /// take (`around_mi_422_chroma`), and the gather now routes through it
1487- /// under the ss guard -- verbatim `around_mi_rect` at every other shape.
1488- ///
1489- /// Reachability is MEASURED, not assumed: the walk fires at ss (1,0) on
1490- /// both pinned `422_intrabc_sb128_strip*.obu` cells, 72 chroma unit
1491- /// gathers each (`sb128rect_chroma_replay_hits().0`, the same walk's own
1492- /// replay counter). No committed cell DISCRIMINATES the change: with the
1493- /// pair rule in place all 21 committed 4:2:2 cells are byte-exact
1494- /// against ffmpeg, exactly as the pre-change tree was (the gathered
1495- /// votes cancel at every reached unit), so THIS gate -- not a pixel
1496- /// compare -- is what stops the routing being reverted.
1497- ///
1498- /// lane-av1422mismatch9: the same decode loop now also asserts the
1499- /// `SB128RECT_REPLAY_SPAN_MISMATCH_HITS` count (NINE per pin) and states
1500- /// why it is not a pixel miss -- the counter's predicate is a span
1501- /// DIFFERENCE, true by construction at ss (1,0); the replay re-stamps the
1502- /// identical context cells with the same per-axis pair the read walk used;
1503- /// and `record_mi_chroma` writes no pixel sample. See the assert's message.
1504- #[test]
1505- fn the_422_block_128rect_chroma_chunk_gather_stays_per_axis() {
1506- const NAME: &str = "the_422_block_128rect_chroma_chunk_gather_stays_per_axis";
1507- let src = crate::test_source::module_source("decode");
1508- let body = src
1509- .split_once("fn decode_block_128rect(")
1510- .expect("decode_block_128rect must exist")
1511- .1
1512- .split_once("\nfn ")
1513- .expect("decode_block_128rect must be a top-level fn")
1514- .0;
1515- // Scan CODE only: the fix's own comment quotes the guard form, and a
1516- // prose mention must not read as a reintroduction (nor mask one).
1517- let stripped: Vec<&str> = body
1518- .lines()
1519- .map(|l| l.split_once("//").map_or(l, |(c, _)| c))
1520- .collect();
1521- let code = stripped.join("\n");
1522- let body = code.as_str();
1523- assert_eq!(
1524- body.matches("if ss_x(fctx) == 1 && ss_y(fctx) == 0 {")
1525- .count(),
1526- 1,
1527- "{NAME}: the ss (1, 0) guard over the per-chunk chroma gather must \
1528- appear exactly once in decode_block_128rect, found {}",
1529- body.matches("if ss_x(fctx) == 1 && ss_y(fctx) == 0 {")
1530- .count()
1531- );
1532- for name in [
1533- "neighbours.around_mi_422_chroma(cu_mi, luma_span, luma_span_h)",
1534- "neighbours.around_mi_rect(cu_mi, luma_span, luma_span_h)",
1535- ] {
1536- assert_eq!(
1537- body.matches(name).count(),
1538- 1,
1539- "{NAME}: `{name}` must appear exactly once in \
1540- decode_block_128rect's per-chunk chroma gather, found {} -- one \
1541- arm has been dropped, so the gather has fallen back to the \
1542- square per-mi rule at ss (1, 0)",
1543- body.matches(name).count()
1544- );
1545- }
1546- // Reachability arm: the walk must actually RUN at ss (1, 0) on the
1547- // pinned strips, or the routing above is a no-op the gate cannot see.
1548- // A stream that stopped coding 128-axis intra blocks reads 0 and this
1549- // assert fails instead of passing over a decode that never reached
1550- // the fixed gather (class gate-blind-to-feature).
1551- for (file, bytes, fp) in [
1552- (
1553- "422_intrabc_sb128_strip.obu",
1554- 1672usize,
1555- 0x50f5cfc576e4cd00_u64,
1556- ),
1557- (
1558- "422_intrabc_sb128_strip_notxsearch.obu",
1559- 1675,
1560- 0xd4936f252ff8cff0,
1561- ),
1562- ] {
1563- let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1564- .join("fixtures")
1565- .join(file);
1566- let data = std::fs::read(&path).unwrap_or_else(|e| {
1567- panic!(
1568- "{NAME}: pinned witness {} is missing ({e}) -- the gate cannot run",
1569- path.display()
1570- )
1571- });
1572- assert_eq!(data.len(), bytes, "{NAME}: {file} size drifted");
1573- assert_eq!(fnv1a64(&data), fp, "{NAME}: {file} bytes drifted");
1574- let _guard = lock_gate_counters();
1575- let before = crate::decode::sb128rect_chroma_replay_hits();
1576- let frames = decode_stream(&data)
1577- .unwrap_or_else(|e| panic!("{NAME}: {file} no longer decodes cleanly: {e}"));
1578- let after = crate::decode::sb128rect_chroma_replay_hits();
1579- assert_eq!(
1580- after.0 - before.0,
1581- 72,
1582- "{NAME}: {file} gathered {} chroma unit context(s) in \
1583- decode_block_128rect's per-chunk walk; 72 were measured at ss (1, 0) -- \
1584- a lower number means the gather is no longer REACHED here \
1585- (class gate-blind-to-feature)",
1586- after.0 - before.0
1587- );
1588- // lane-av1422mismatch9: `SB128RECT_REPLAY_SPAN_MISMATCH_HITS` reads
1589- // NINE on each of these two pins, and this is the only place that
1590- // number is asserted. It is NOT a pixel miss, and the three facts
1591- // below are why -- the assert encodes the measurement, not a wish:
1592- //
1593- // 1. The predicate (`decode.rs`, end of `decode_block_128rect`) is
1594- // `luma_span != luma_span_h` -- `chroma_tx << ss_x` vs
1595- // `chroma_tx << ss_y`. At ss (1, 0) the two DIFFER BY
1596- // CONSTRUCTION for every 128-root rect block, so the counter is
1597- // a shape test ("this is the 4:2:2 span shape"), not a
1598- // divergence test. Nine is the number of such blocks the five
1599- // frames code.
1600- // 2. The replay re-stamps with the SAME per-axis pair the in-loop
1601- // walk stamped with (`record_mi_chroma(cu_mi, luma_span,
1602- // luma_span_h, ...)` at both the read walk and the replay), so
1603- // it rewrites the identical context cells -- this is exactly
1604- // the `record_mi_chroma(cu_mi, luma_span, luma_span_h)` pairing
1605- // the source-scan arm above pins. The pre-lane-av1-128rectspan
1606- // defect (width passed on both axes) is caught by that
1607- // spelling arm, not by this counter.
1608- // 3. `record_mi_chroma` writes only `Neighbours::left`/`above`
1609- // (entropy-context arrays); it touches ZERO pixel samples. So
1610- // the 9 events cannot write a sample the oracle lacks. The
1611- // pixel proof is the same file's
1612- // `the_pinned_422_intrabc_sb128_strip_witnesses_decode_pixel_
1613- // exact`, which pins all five frames byte-exact against
1614- // ffmpeg's `yuv422p` rawvideo.
1615- //
1616- // Change this expected count ONLY with a new measurement; a 4:2:2
1617- // stream coding more 128-root rect blocks legitimately changes it.
1618- assert_eq!(
1619- after.1 - before.1,
1620- 9,
1621- "{NAME}: {file} fired the 4:2:2 span-shape arm {} time(s); NINE were \
1622- measured and are NOT a pixel miss (the predicate is `luma_span != \
1623- luma_span_h`, true by construction at ss (1,0); the replay re-stamps the \
1624- identical context cells with the same per-axis pair; `record_mi_chroma` \
1625- writes no pixel) -- see the report above",
1626- after.1 - before.1
1627- );
1628- assert_eq!(frames.len(), 5, "{NAME}: {file} frame count");
1629- }
1630- }
1631-
1632- /// lane-av1422lpf: the three 4:2:2 LOSSLESS INTER witness fixtures,
1633- /// PINNED. As of lane-av1422lift they are asserted to DECODE pixel-exact
1634- /// against ffmpeg (the lane-av1422lift paragraph at the end of this doc);
1635- /// before the lift this gate asserted the SEQUENCE-HEADER refusal instead.
1636- ///
1637- /// W/X/Y (`W_intrabc.obu`, `X_intrabc_tiled.obu`, `Y_intrabc_10b.obu`) are
1638- /// the streams on which lane-av1422lpf found the seven-site chroma-extent
1639- /// PANIC family -- each site indexed a block's chroma PLANE BLOCK with
1640- /// the ENCLOSING SQUARE `max(side >> ss_x, side >> ss_y)` instead of the
1641- /// PER-AXIS `(bw >> ss_x, bh >> ss_y)` -- so the pins keep the bytes that
1642- /// witnessed it from silently changing under the gate.
1643- ///
1644- /// WHAT THIS GATE DID NOT COVER BEFORE THE LIFT, measured rather than
1645- /// argued: the refusal it asserted was the HEADER refusal, which fired
1646- /// BEFORE any of the seven sites is reachable, and it fired IDENTICALLY on
1647- /// the pre-fix tree (commit `aef4fa67` prints the same string, built and
1648- /// run for this correction). As a refusal contract the gate was therefore
1649- /// VACUOUS with respect to the seven-site fix -- it passed before and
1650- /// after the fix, and its only real content was the three pins.
1651- ///
1652- /// That refusal is GONE (lane-av1422lift lifted the sequence-header
1653- /// refusal), so the decode-level half of the evidence now runs in
1654- /// committed code: this gate's own byte-exact arm below decodes all three
1655- /// fixtures against ffmpeg. `EC_AV1_ALLOW_422_PROBE` was only ever the
1656- /// patch-run-restore bypass for the manual measurement in
1657- /// `lanes/av1422lpf.report.md`; it is still deliberately not committed.
1658- /// The source-scan arm
1659- /// `the_422_lossless_inter_chroma_walk_sites_stay_per_axis` remains the
1660- /// per-axis SPELLING proof; the pixel proof is now the committed decode.
1661- ///
1662- /// CORRECTED by lane-av1422llintra: the name said `..._panics_refuse_
1663- /// by_name`, and lane-av1422lpf's report claimed W and X now REFUSE with
1664- /// `a Golomb tail longer than this decoder reads` at frame 2. That
1665- /// refusal DOES NOT REPRODUCE on this tip: with the bypass applied, all
1666- /// three cells DECODE 16/16 -- no panic and no second refusal.
1667- ///
1668- /// lane-av1422lift: the three pins are asserted BYTE-EXACT against
1669- /// ffmpeg's rawvideo of the same bytes, per plane and per frame, with the
1670- /// per-plane coefficient-unit census as the non-vacuity arm -- so the
1671- /// three DECODE 16/16 fact the paragraph above records from a bypassed
1672- /// probe build is now a committed assertion. `Y` is the 10-bit member
1673- /// and carries the depth-correct HBD compare (`yuv422p10le`, 16-bit
1674- /// containers on both sides) rather than an 8-bit narrowing of a
1675- /// high-bit-depth cell.
1676- #[test]
1677- fn the_pinned_422_lossless_inter_witnesses_decode_pixel_exact() {
1678- const NAME: &str = "the_pinned_422_lossless_inter_witnesses_decode_pixel_exact";
1679- if !have_ffmpeg() {
1680- eprintln!("SKIP {NAME}: no ffmpeg");
1681- return;
1682- }
1683- for (file, bytes, fp, depth) in [
1684- ("W_intrabc.obu", 130_320usize, 0xb6d5c4653a32567a_u64, 8u8),
1685- ("X_intrabc_tiled.obu", 131_696, 0xb6e04621d2116ef7, 8),
1686- ("Y_intrabc_10b.obu", 202_281, 0x2ecf03435a14dbf, 10),
1687- ] {
1688- let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1689- .join("fixtures")
1690- .join(file);
1691- let data = std::fs::read(&path).unwrap_or_else(|e| {
1692- panic!("{NAME}: pinned witness {file} is missing ({e}) -- the gate cannot run")
1693- });
1694- assert_eq!(data.len(), bytes, "{NAME}: {file} size drifted");
1695- assert_eq!(fnv1a64(&data), fp, "{NAME}: {file} bytes drifted");
1696- assert_422_stream_pixel_exact(NAME, &data, 320, 240, 16, depth, true);
1697- }
1698- }
1699-
1700- /// lane-av1422lpf: the SOURCE-SCAN arm of the witness gate above -- one
1701- /// assertion per site, so a mutation at any single site reds exactly that
1702- /// site and leaves the other six alone.
1703- ///
1704- /// Every assertion has a NEGATIVE twin (`forbidden`) and a POSITIVE twin
1705- /// (`required`), so neither an unreverted site nor a matcher that has
1706- /// stopped matching can pass: the forbidden string is absent AND the
1707- /// required string is present in the same function body. The `required`
1708- /// half is what makes this gate non-vacuous in the
1709- /// `dead-matcher-positive-control` sense -- a scan that matched nothing
1710- /// would fail it rather than pass silently.
1711- ///
1712- /// WHAT IT DOES NOT COVER: this arm is a SPELLING scan. It cannot observe
1713- /// a decode, so it cannot prove any cell decodes and cannot prove any
1714- /// pixel -- the same limit as the witness gate above it, and stated here
1715- /// because "one assertion per site, each with a mutation proof" reads
1716- /// like more coverage than it is.
1717- ///
1718- /// `strip_code` is the same comment-stripping the arms above use: the
1719- /// fixes quote their own old expression to say what it was, and a prose
1720- /// mention must neither read as a reintroduction nor mask one.
1721- #[test]
1722- fn the_422_lossless_inter_chroma_walk_sites_stay_per_axis() {
1723- const NAME: &str = "the_422_lossless_inter_chroma_walk_sites_stay_per_axis";
1724- let src = crate::test_source::module_source("decode");
1725- let strip_code = |body: &str| -> String {
1726- body.lines()
1727- .map(|l| l.split_once("//").map_or(l, |(c, _)| c))
1728- .collect::<Vec<_>>()
1729- .join("\n")
1730- };
1731- // A SECOND form with the same comment stripping but every run of
1732- // whitespace collapsed to one space, so a matcher can span an argument
1733- // list that a line-anchored fix's own comment sits inside. Without it
1734- // the site-5 and site-6 matchers are DEAD: the mutation that reverts
1735- // them still passes, because the literal being searched for never
1736- // matched even when the fix was in place. Measured, not assumed --
1737- // `verifier-dead-matcher-positive-control`.
1738- let flatten = |body: &str| -> String {
1739- strip_code(body)
1740- .split_whitespace()
1741- .collect::<Vec<_>>()
1742- .join(" ")
1743- };
1744- let body_of = |fn_name: &str| -> String {
1745- let after = src
1746- .split_once(&format!("\nfn {fn_name}("))
1747- .unwrap_or_else(|| panic!("{NAME}: `{fn_name}` must exist in decode.rs"));
1748- let end = after.1.find("\nfn ").unwrap_or(after.1.len());
1749- strip_code(&after.1[..end])
1750- };
1751- let flat_of = |fn_name: &str| -> String {
1752- let after = src
1753- .split_once(&format!("\nfn {fn_name}("))
1754- .unwrap_or_else(|| panic!("{NAME}: `{fn_name}` must exist in decode.rs"));
1755- let end = after.1.find("\nfn ").unwrap_or(after.1.len());
1756- flatten(&after.1[..end])
1757- };
1758- // (label, enclosing fn, forbidden square-cut spelling, required
1759- // per-axis spelling, required count in that fn)
1760- let sites: [(&str, &str, &str, &str, usize); 4] = [
1761- (
1762- "site 1 -- read_inter_chroma_lossless's composed-grid extent",
1763- "read_inter_chroma_lossless",
1764- "stride * stride,\n );",
1765- "stride * blk_h,",
1766- 1,
1767- ),
1768- (
1769- "site 7 -- read_intra_chroma_lossless's composed-grid extent",
1770- "read_intra_chroma_lossless",
1771- "stride * stride,\n );",
1772- "stride * blk_h,",
1773- 1,
1774- ),
1775- (
1776- "site 4 -- the strip chroma rect's VERT arm at ss (1,0)",
1777- "decode_inter_block",
1778- "} else if s.horz {\n (8, 4)\n } else {\n (4, 8)\n }",
1779- "} else if ss_y(fctx) == 0 {\n (4, 16)\n } else {\n (4, 8)\n }",
1780- 1,
1781- ),
1782- (
1783- "site 5 -- the mu-chunk lossless walk's prediction stride",
1784- "decode_inter_block",
1785- "(write_chroma_w, write_chroma_h), chroma_side, mode_for_tx,",
1786- "(write_chroma_w, write_chroma_h), chroma_stride, mode_for_tx,",
1787- 2,
1788- ),
1789- ];
1790- for (label, fn_name, forbidden, required, count) in sites {
1791- // The last table row is written in the flattened form (it spans a
1792- // comment the fix itself wrote); the others are line-anchored.
1793- let flattened = required.contains(" mode_for_tx,");
1794- let body = if flattened {
1795- flat_of(fn_name)
1796- } else {
1797- body_of(fn_name)
1798- };
1799- assert_eq!(
1800- body.matches(forbidden).count(),
1801- 0,
1802- "{NAME}: {label} is BACK -- the square-cut expression \
1803- `{forbidden}` is what this gate exists for"
1804- );
1805- assert!(
1806- body.matches(required).count() >= count,
1807- "{NAME}: {label}: the per-axis expression `{required}` must appear \
1808- at least {count} time(s) in `{fn_name}` -- found {}",
1809- body.matches(required).count()
1810- );
1811- }
1812- // Sites 2, 5 and 6 are the `chroma_side`-vs-`chroma_stride` and
1813- // `chroma_side`-vs-`chroma_buf_h` argument choices, which are
1814- // single-token differences on otherwise identical lines. Counting the
1815- // remaining `chroma_side` uses per arm is the only way to see them, so
1816- // they get their own exact-count assertions instead of a substring.
1817- let dib = body_of("decode_inter_block");
1818- // Site 2: the lossless TX_4x4 unit replay indexes the composed grid.
1819- assert_eq!(
1820- dib.matches("let start = (cr * cu + rr) * chroma_stride + cc * cu;")
1821- .count(),
1822- 1,
1823- "{NAME}: site 2 -- the lossless TX_4x4 replay must index the \
1824- composed plane grid at `chroma_stride` (the plane block's own \
1825- width), not `chroma_side`"
1826- );
1827- assert_eq!(
1828- dib.matches("let start = (cr * cu + rr) * chroma_side + cc * cu;")
1829- .count(),
1830- 0,
1831- "{NAME}: site 2 is BACK -- the lossless TX_4x4 replay indexes the \
1832- composed grid at the enclosing square again"
1833- );
1834- // Sites 5 and 6. The two mu-chunk walks (the single-reference and the
1835- // compound twin) take the block's `(write_chroma_w, write_chroma_h)`
1836- // and the stride SEPARATELY; the two intra-in-inter walks take both
1837- // the block shape and the region as `(chroma_stride, chroma_buf_h)`.
1838- // Every one of the four must be per-axis; the pre-fix spelling was
1839- // the enclosing square `chroma_side` for the stride, and
1840- // `(chroma_side, chroma_side)` for the intra block shape.
1841- let dibf = format!(
1842- "{}{}",
1843- flat_of("decode_inter_block"),
1844- flat_of("decode_inter_block_intra_arm"),
1845- ); // the intra arm was split out of decode_inter_block (av1split D8a)
1846- assert_eq!(
1847- dibf.matches("(chroma_stride, chroma_buf_h),").count(),
1848- 3,
1849- "{NAME}: site 6 -- the two intra-in-inter walks pass the plane block \
1850- as `(chroma_stride, chroma_buf_h)` at all THREE argument positions \
1851- it occupies -- the mu-chunk walk's blk shape, and the whole-block walk's blk shape and region -- found {}",
1852- dibf.matches("(chroma_stride, chroma_buf_h),").count()
1853- );
1854- assert_eq!(
1855- dibf.matches("(chroma_side, chroma_side),").count(),
1856- 0,
1857- "{NAME}: site 6 is BACK -- an intra-in-inter walk still hands the \
1858- plane block the enclosing square `chroma_side`"
1859- );
1860- // The geometry the scan cannot see, derived from the same `>> ss`
1861- // forms the fixes use, so the scan and the fix cannot disagree about
1862- // what per-axis means at each chroma format. A 16x16 luma block:
1863- // (side >> ss_x, side >> ss_y) is the plane block and
1864- // max(side >> ss_x, side >> ss_y) is the enclosing square.
1865- let plane_block = |side: usize, ss_x: u32, ss_y: u32| (side >> ss_x, side >> ss_y);
1866- let enclosing = |side: usize, ss_x: u32, ss_y: u32| {
1867- (
1868- (side >> ss_x).max(side >> ss_y),
1869- (side >> ss_x).max(side >> ss_y),
1870- )
1871- };
1872- for (label, side, ss_x, ss_y, block, square) in [
1873- ("4:2:0", 16usize, 1u32, 1u32, (8, 8), (8, 8)),
1874- ("4:2:2", 16, 1, 0, (8, 16), (16, 16)),
1875- ("4:4:4", 16, 0, 0, (16, 16), (16, 16)),
1876- ] {
1877- assert_eq!(
1878- plane_block(side, ss_x, ss_y),
1879- block,
1880- "{NAME}: the {label} chroma plane block of a {side}x{side} luma block"
1881- );
1882- assert_eq!(
1883- enclosing(side, ss_x, ss_y),
1884- square,
1885- "{NAME}: the {label} enclosing chroma square of a {side}x{side} \
1886- luma block"
1887- );
1888- }
1889- // The load-bearing claim of "unchanged at 4:2:0 and 4:4:4": the two
1890- // are the same number exactly when `ss_x == ss_y`, and DIFFERENT at
1891- // 4:2:2 -- which is what makes every site above inert there and
1892- // active at 4:2:2. If this ever held at 4:2:2 the fixes would be
1893- // untested rather than inert.
1894- assert_eq!(plane_block(16, 1, 1), enclosing(16, 1, 1));
1895- assert_eq!(plane_block(16, 0, 0), enclosing(16, 0, 0));
1896- assert_ne!(
1897- plane_block(16, 1, 0),
1898- enclosing(16, 1, 0),
1899- "{NAME}: 4:2:2 must NOT be square -- if the plane block equalled \
1900- the enclosing square at ss (1,0), none of these sites could ever \
1901- be wrong and the gates above would be measuring nothing"
1902- );
1903- // Site 4's own geometry: a PARTITION_VERT_4 strip is 4x16 luma and
1904- // pairs on COLUMNS while `ss_x == 1`, so the pair is 8x16 and its
1905- // plane block is (8 >> ss_x, 16 >> ss_y).
1906- for (label, ss_x, _ss_y, want) in [
1907- ("4:2:0", 1u32, 1u32, (4usize, 8usize)),
1908- ("4:2:2", 1, 0, (4, 16)),
1909- ("4:4:4", 0, 0, (8, 16)),
1910- ] {
1911- assert_eq!(
1912- plane_block(8, ss_x, 0).0,
1913- want.0,
1914- "{NAME}: site 4 -- the {label} VERT strip pair's chroma width"
1915- );
1916- }
1917- // ...and the HORZ arm of the same match needs NO third shape at
1918- // 4:2:2: a HORZ_4 strip pairs on ROWS only while `ss_y == 1`, and
1919- // 4:2:2 has `ss_y == 0`, so each 16x4 strip is its own chroma
1920- // reference and its own (8 >> ss_x, 4 >> 0) plane block -- which is
1921- // the (8, 4) the existing arm already returns.
1922- assert_eq!(
1923- (plane_block(16, 1, 0).0, plane_block(4, 1, 0).1),
1924- (8usize, 4usize),
1925- "{NAME}: site 4 -- the 4:2:2 HORZ strip's own plane block is already \
1926- the (8, 4) the unsplit arm returns, which is why only the VERT arm \
1927- gained a shape"
1928- );
1929- }
1930-
1931- /// lane-av1422warp: the SECOND 4:2:2 coverage witness -- the one
1932- /// `422_sb128_3f.obu` could not be, because that stream's inter content
1933- /// is skip-heavy (see `lanes/av1422stripwrite.report.md`, which named a
1934- /// second fixture with real residuals, compound and warped motion above
1935- /// the vertical midpoint as the thing that would justify lifting the
1936- /// refusal). This is that fixture.
1937- ///
1938- /// `422_residual_compound_warp_16f.obu` (38845 bytes), sha256
1939- /// `d78e2afb43ce311d3d82335a945c6f80f62db4537966d881c1349a68b3aecb95`:
1940- ///
1941- /// ```text
1942- /// ffmpeg -f lavfi -i "mandelbrot=size=256x288:rate=24:maxiter=220:start_scale=3:end_scale=0.35:end_pts=300,rotate=a=0.10*t:c=none:ow=256:oh=288" \
1943- /// -frames:v 24 -pix_fmt yuv422p -f yuv4mpegpipe src422.y4m
1944- /// aomenc --codec=av1 --profile=2 --input-bit-depth=8 --limit=16
1945- /// --width=256 --height=288 --lag-in-frames=25 --auto-alt-ref=1
1946- /// --enable-global-motion=1 --pass=1
1947- /// --cq-level=24 --cpu-used=0
1948- /// --threads=4 --kf-min-dist=0 --kf-max-dist=999999 \
1949- /// src422.y4m -o a1.webm
1950- /// ffmpeg -i a1.webm -c copy -f obu -y a1.obu
1951- /// ```
1952- ///
1953- /// CORRECTED by lane-av1422lrless (reviewer P2). This doc previously
1954- /// carried a different ffmpeg filter (`rotate=a=0.10`, no `*t`, no
1955- /// `:c=none:ow/oh`) and a `-n ffp --pass=2 --fpf=...` two-pass line.
1956- /// **Neither produced these bytes.** Re-encoding from the recorded
1957- /// source `src422.y4m` (sha256
1958- /// `4d35eaf65d1a5541b3177e1183644c163b3868d8f141bed0ce9fdf833280ba9f`)
1959- /// was measured three ways: the two-pass form gives 38774 bytes
1960- /// (`e93c4ed7...`), and only adding `--pass=1` reproduces these 38845
1961- /// bytes byte for byte (`d78e2afb...`). `aomenc` DEFAULTS to two-pass,
1962- /// so the flag has to be stated to get back the pinned stream. The
1963- /// recipe above is the one that was actually run.
1964- ///
1965- /// Measured on a patch-run-restore build (the `EC_AV1_ALLOW_422_PROBE`
1966- /// bypass applied for the run, reverted after -- it is deliberately NOT
1967- /// committed). This block is the bypassed measurement; the committed
1968- /// assertion is now the byte-exact compare in the lane-av1422lift
1969- /// paragraph below:
1970- ///
1971- /// - all 16 frames pixel-exact against `aomdec --rawvideo`, 2359296
1972- /// bytes each, sha256 `4bfc2395e5ca6ea178f606e6b1ced773e26fc2d85b
1973- /// c3a6cdb63a402939aeb203` on both sides;
1974- /// - the entropy stream pairs bit-for-bit against the instrumented
1975- /// oracle -- 246735 symbol reads each, no divergence anywhere in the
1976- /// stream, not merely at the window this lane spent nine rounds
1977- /// narrowing;
1978- /// - the arms this fixture exists to cover really fire ABOVE the
1979- /// vertical midpoint: 3 upper-half blocks on a non-`TRANSLATION`
1980- /// global-motion model (`top_half_warp_hits`, gated on libaom's
1981- /// `is_global_mv_block` per slot) and 3 upper-half
1982- /// `GLOBAL_GLOBALMV` compound blocks (`top_half_compound_hits`),
1983- /// alongside 25 compound-warp, 18 compound-warp-8x8-leaf, 84
1984- /// rotzoom global-warp, 22 Wiener and 10 SGRPROJ loop-restoration
1985- /// units frame-globally.
1986- ///
1987- /// The loop-restoration numbers are load-bearing twice over: decoding
1988- /// this stream is what exposed the per-axis `read_lr` corner bug
1989- /// (`restoration.rs`, `av1_loop_restoration_corners_in_sb`), whose fix
1990- /// is what made the whole sequence pair. 4:2:0 and 4:4:4 are unchanged
1991- /// by it -- byte-identical to their pre-lane decodes, with the LR gate
1992- /// family green.
1993- ///
1994- /// lane-av1422lift: the committed assertion is now the byte pin AND
1995- /// byte-exactness against ffmpeg's `yuv422p` rawvideo of the same bytes,
1996- /// per plane and per frame, with the per-plane coefficient-unit census
1997- /// as the non-vacuity arm. The paragraph above's coverage counts (25
1998- /// compound-warp, 84 rotzoom global-warp, 22 Wiener, 10 SGRPROJ, CDEF
1999- /// 39) are what make the row non-vacuous: without them a byte-exact
2000- /// compare could be green over a stream that never entered a warp arm.
crates/ec-av1/src/stream/tests/t02.rsdeleted+0 -4341

Diff too large; view file

@@ -1,4341 +0,0 @@
1-use super::*;
2-use super::support::*;
3-use super::gates_a::*;
4-use crate::encode::{Picture as Pic, encode_key_frame_with_ctx, encode_sequence_with_ctx};
5-use crate::probe::run_with_stdin;
6-use std::process::{Command, Stdio};
7-
8- /// lane-av1oracledepth: the depth-generic 4:4:4 oracle comparator, armed
9- /// on the same pinned 10-bit 4:4:4 cell
10- /// `a_444_lossy_palette_chroma_unit_window_is_byte_exact_at_352x242_10bit`
11- /// gates (fixture sha256
12- /// `84df2f37cc7982f9a572443d85dfcc13bf366a64f3fb567391dcd5acd58a0ad2`):
13- /// every plane of every SHOWN frame must come back byte-exact against
14- /// ffmpeg's `yuv444p10le` rawvideo of the same bytes, with the depth read
15- /// from the stream's own sequence header, never assumed.
16- ///
17- /// The flip control is the crate's own comparator-liveness shape (the
18- /// same one
19- /// [`every_ffmpeg_comparator_reds_on_a_one_sample_wrong_ffmpeg`] runs for
20- /// the other helpers): with a thread-local ffmpeg shim that rotates ONE
21- /// byte of the oracle's own rawvideo stdout, the compare must move from
22- /// 0 to EXACTLY 1 differing sample in the tampered plane and stay at 0 in
23- /// the other two -- a comparator that cannot see a one-sample difference
24- /// would make every "byte-exact" claim above vacuous.
25- #[test]
26- fn the_444_depth_helper_is_byte_exact_on_a_pinned_10bit_444_cell() {
27- const NAME: &str = "the_444_depth_helper_is_byte_exact_on_a_pinned_10bit_444_cell";
28- if !have_ffmpeg() {
29- eprintln!("SKIP {NAME}: no ffmpeg");
30- return;
31- }
32- let _gate_lock = lock_gate_counters();
33- let path = crate_pin("444_lossy_palette_chroma_352x242_10b.obu");
34- let stream = read_pin(&path, 24875, 0x7fda_dbb4_3bbf_9af3, NAME);
35- // The fixture is 16 SHOWN frames; ffmpeg's rawvideo muxer emits shown
36- // frames only, and so does decode_stream's return.
37- const W: usize = 352;
38- const H: usize = 242;
39- const FRAMES: usize = 16;
40- assert_eq!(stream_bit_depth(&stream, NAME), 10, "{NAME}: pin depth");
41- let ours = decode_stream(&stream)
42- .unwrap_or_else(|e| panic!("{NAME}: the pinned 10-bit 4:4:4 cell was refused: {e}"));
43- assert_eq!(ours.len(), FRAMES, "{NAME}: decoded frame count");
44- let theirs = ffmpeg_decode_sequence_444_depth(&stream, W, H, FRAMES, 10, "yuv444p10le");
45- for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
46- for (plane, x, y) in [("Y", &a.y, &b.y), ("U", &a.u, &b.u), ("V", &a.v, &b.v)] {
47- if let Some(at) = x.iter().zip(y).position(|(p, q)| p != q) {
48- panic!(
49- "{NAME}: {plane} differs from ffmpeg's yuv444p10le at frame {i} sample \
50- {at} (ours {} vs {}); {n} of {m} samples differ",
51- x[at],
52- y[at],
53- n = x.iter().zip(y).filter(|(p, q)| p != q).count(),
54- m = x.len()
55- );
56- }
57- }
58- }
59- eprintln!(
60- "{NAME}: {FRAMES} shown frames byte-exact vs ffmpeg yuv444p10le on the pinned \
61- 10-bit 4:4:4 cell"
62- );
63-
64- // ---- the flip control: one wrong oracle sample must move the count
65- // 0 -> 1 in exactly the tampered plane -------------------------
66- let dir = std::env::temp_dir().join(format!("ec-av1-{NAME}-{}", std::process::id()));
67- let _ = std::fs::remove_dir_all(&dir);
68- std::fs::create_dir_all(&dir).expect("scratch dir");
69- let real = if let Some(p) = std::env::var_os("EC_AV1_FFMPEG") {
70- std::path::PathBuf::from(p)
71- } else {
72- let found = Command::new("ffmpeg")
73- .arg("-version")
74- .stdout(Stdio::null())
75- .stderr(Stdio::null())
76- .status()
77- .is_ok_and(|s| s.success());
78- assert!(found, "{NAME}: no working ffmpeg on PATH to wrap");
79- let path_env = std::env::var_os("PATH").unwrap_or_default();
80- std::env::split_paths(&path_env)
81- .map(|d| d.join("ffmpeg"))
82- .find(|p| p.is_file())
83- .expect("{NAME}: ffmpeg is on PATH but not resolvable to a file")
84- };
85- std::fs::write(dir.join("real-ffmpeg"), real.as_os_str().as_encoded_bytes())
86- .expect("recording the real ffmpeg's path for the shim");
87- let script = r#"#!/bin/sh
88-REAL=$(cat "$(dirname "$0")/real-ffmpeg")
89-OUT=$(mktemp)
90-"$REAL" "$@" > "$OUT" || exit $?
91-while read -r o; do
92- [ -n "$o" ] || continue
93- b=$(od -An -tu1 -j "$o" -N 1 "$OUT" 2>/dev/null | tr -d ' \n')
94- [ -n "$b" ] || continue
95- esc=$(printf '\\%03o' $(( (b + 128) % 256 )))
96- printf "$esc" | dd of="$OUT" bs=1 seek="$o" count=1 conv=notrunc 2>/dev/null
97-done < "$(dirname "$0")/offsets"
98-cat "$OUT"
99-rm -f "$OUT"
100-exit 0
101-"#;
102- let shim = dir.join("one-sample-wrong-ffmpeg.sh");
103- std::fs::write(&shim, script).expect("writing the ffmpeg shim");
104- #[cfg(unix)]
105- {
106- use std::os::unix::fs::PermissionsExt;
107- std::fs::set_permissions(&shim, std::fs::Permissions::from_mode(0o755))
108- .expect("the ffmpeg shim must be executable");
109- }
110- let set_offsets = |bytes: &[usize]| {
111- let body: String = bytes
112- .iter()
113- .map(|b| format!("{b}\n"))
114- .collect::<Vec<_>>()
115- .concat();
116- std::fs::write(dir.join("offsets"), body).expect("writing the offsets file");
117- };
118- let count = |theirs_t: &[Pic]| -> [usize; 3] {
119- let mut wrong = [0usize; 3];
120- for (a, b) in ours.iter().zip(theirs_t) {
121- for (plane, (x, y)) in
122- [(0usize, (&a.y, &b.y)), (1, (&a.u, &b.u)), (2, (&a.v, &b.v))]
123- {
124- wrong[plane] += x.iter().zip(y).filter(|(p, q)| p != q).count();
125- }
126- }
127- wrong
128- };
129- // Frame bytes are 3 planes x W*H samples x 2 bytes (10-bit container).
130- let plane_bytes = W * H * 2;
131- let mut blind: Vec<String> = Vec::new();
132- set_ffmpeg_path(Some(shim.clone()));
133- for (plane, base) in [("Y", 0usize), ("U", plane_bytes), ("V", 2 * plane_bytes)] {
134- // Byte 2000 of the named plane: sample 1000, still frame 0 on
135- // every plane at this geometry.
136- set_offsets(&[base + 2000]);
137- let theirs_t =
138- ffmpeg_decode_sequence_444_depth(&stream, W, H, FRAMES, 10, "yuv444p10le");
139- let got = count(&theirs_t);
140- let mut expected = [0usize, 0, 0];
141- expected[match plane {
142- "Y" => 0,
143- "U" => 1,
144- _ => 2,
145- }] = 1;
146- if got != expected {
147- blind.push(format!(
148- "{plane} arm: counted {got:?}, expected {expected:?} (exactly the one \
149- tampered sample)"
150- ));
151- }
152- }
153- set_ffmpeg_path(None);
154- let _ = std::fs::remove_dir_all(&dir);
155- assert!(
156- blind.is_empty(),
157- "{NAME}: {} of 3 flip arms stayed GREEN against an ffmpeg that is wrong by exactly \
158- one sample -- {blind:#?} -- the comparator cannot see a difference, so its \
159- byte-exact verdict proves nothing (class comparator-that-never-reads-the-oracle)",
160- blind.len()
161- );
162- eprintln!(
163- "{NAME}: flip control bites on Y, U and V separately (0 -> 1 per tampered plane)"
164- );
165- }
166-
167- /// lane-av1oracledepth: `ffmpeg_decode_sequence_10bit` must REFUSE a
168- /// wrong-depth stream by the stream's OWN sequence header, the way the
169- /// 12-bit gates read `assert_12bit_sequence_header`. An 8-bit 4:2:0
170- /// stream handed to the 10-bit helper is the wrong-depth shape: ffmpeg
171- /// converts it to `yuv420p10le` and sizes no plane differently, so
172- /// without the depth assert a gate could compare a converted 8-bit
173- /// reference against our 10-bit decode and read exact.
174- #[test]
175- fn the_10bit_oracle_helper_refuses_a_wrong_depth_stream() {
176- const NAME: &str = "the_10bit_oracle_helper_refuses_a_wrong_depth_stream";
177- let _gate_lock = lock_gate_counters();
178- let path = crate_pin("mix176_offtile_chroma_clip.obu");
179- let stream = read_pin(&path, 4581, 0x5e31be5efc9c3c1d, NAME);
180- assert_eq!(
181- stream_bit_depth(&stream, NAME),
182- 8,
183- "{NAME}: the control pin must really be 8-bit, or this proves nothing"
184- );
185- assert_eq!(
186- stream_subsampling(&stream, NAME),
187- (1, 1),
188- "{NAME}: the control pin must really be 4:2:0, or the refusal below could be the \
189- shape guard instead of the depth guard"
190- );
191- let msg = panic_message(|| {
192- ffmpeg_decode_sequence_10bit(&stream, 176, 144, 1);
193- })
194- .unwrap_or_else(|| {
195- panic!(
196- "{NAME}: ffmpeg_decode_sequence_10bit ACCEPTED an 8-bit stream -- ffmpeg \
197- converted it to yuv420p10le and the helper returned a comparison that could \
198- pass green"
199- )
200- });
201- assert!(
202- msg.contains("not 10-bit"),
203- "{NAME}: the refusal must name the depth guard (\"not 10-bit\"); it said: {msg}"
204- );
205- eprintln!("{NAME}: refused -> {msg}");
206- }
207-
208- /// lane-av1rawhelper: `assert_rawvideo_matches` used to pack our samples
209- /// as `u16` for EVERY stream, while `aomdec --rawvideo` writes 8 bits
210- /// per sample for an 8-bit stream. An 8-bit caller therefore died on a
211- /// raw-SIZE assertion (2359296 vs 1179648) without comparing a single
212- /// sample, and a high-bitdepth caller was the only one that could work.
213- ///
214- /// Two arms, both on a real `aomenc` 8-bit stream:
215- ///
216- /// 1. the correct label compares real samples -- the byte counts it
217- /// walks equal the oracle's, so every `u8` in the 8-bit pack is
218- /// zipped against a real oracle byte;
219- /// 2. a WRONG label fails by name, quoting both depths and the fact that
220- /// the pack would compare nothing, rather than by size. Arm 2 is what
221- /// keeps arm 1 from being a green that a reverted check would also
222- /// give.
223- #[test]
224- fn the_rawvideo_helper_compares_real_samples_at_the_streams_own_bit_depth() {
225- const NAME: &str = "the_rawvideo_helper_compares_real_samples_at_the_streams_own_bit_depth";
226- let _gate_lock = lock_gate_counters();
227- if !have_aomenc() || !have_ffmpeg() {
228- eprintln!("SKIP {NAME}: no aomenc/aomdec oracle or no ffmpeg");
229- return;
230- }
231- let (w, h) = (192usize, 128usize);
232- let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
233- .args([
234- "-v",
235- "error",
236- "-f",
237- "lavfi",
238- "-i",
239- &gradients_source(7, w, h, "duration=0.24:rate=25"),
240- "-pix_fmt",
241- "yuv420p",
242- "-t",
243- "0.24",
244- "-f",
245- "yuv4mpegpipe",
246- "-",
247- ])
248- .stdin(Stdio::null())
249- .stdout(Stdio::piped())
250- .stderr(Stdio::piped()), None, |c| c.output())
251- .expect("ffmpeg failed to run");
252- assert!(
253- y4m.status.success(),
254- "{NAME}: ffmpeg fixture: {}",
255- String::from_utf8_lossy(&y4m.stderr)
256- );
257- let args: Vec<&str> = vec![
258- "--codec=av1",
259- "--passes=1",
260- "--end-usage=q",
261- "--cq-level=40",
262- "--cpu-used=2",
263- "--threads=1",
264- "--row-mt=0",
265- "--limit=6",
266- "--obu",
267- "-o",
268- "-",
269- "-",
270- ];
271- let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
272- assert!(
273- out.status.success(),
274- "{NAME}: aomenc refused the fixture: {}",
275- String::from_utf8_lossy(&out.stderr)
276- );
277- let stream = out.stdout;
278- assert_eq!(
279- stream_bit_depth(&stream, NAME),
280- 8,
281- "{NAME}: the fixture must really be 8-bit, or this gate measures nothing"
282- );
283- let dir = std::env::temp_dir().join(format!("ec-av1-{NAME}-raw8-{}", std::process::id()));
284- let _ = std::fs::remove_dir_all(&dir);
285- std::fs::create_dir_all(&dir).expect("scratch dir");
286- let obu = dir.join("in.obu");
287- std::fs::write(&obu, &stream).expect("writing the stream");
288- let frames = decode_stream(&stream)
289- .unwrap_or_else(|e| panic!("{NAME}: the 8-bit stream no longer decodes: {e}"))
290- .len();
291- assert!(frames > 0, "{NAME}: nothing decoded");
292-
293- // ARM 2 first: the wrong label must be refused BY NAME. A helper that
294- // packed u16 unconditionally got this far and then failed on size.
295- let wrong = std::panic::catch_unwind(|| {
296- assert_rawvideo_matches(&obu, &stream, NAME, frames, 10);
297- });
298- let boom = wrong
299- .err()
300- .map(|e| e.downcast_ref::<String>().cloned().unwrap_or_default())
301- .unwrap_or_default();
302- assert!(
303- boom.contains("sequence header says 8-bit") && boom.contains("compares nothing"),
304- "{NAME}: a 10-bit label on an 8-bit stream must be refused by the depth check \
305- naming both depths; the panic read: {boom}"
306- );
307-
308- // ARM 1: the correct label compares real samples. The pre-fix helper
309- // reached a size mismatch here (ours 2x the oracle); reaching the
310- // sample compare is what this arm proves.
311- assert_rawvideo_matches(&obu, &stream, NAME, frames, 8);
312- let _ = std::fs::remove_dir_all(&dir);
313- eprintln!("{NAME}: {frames} 8-bit frame(s) byte-identical to aomdec --rawvideo");
314- }
315-
316- /// lane-svtinter: an SVT-AV1 screen stream whose frame height is not a
317- /// multiple of the superblock size codes PALETTE blocks in the bottom
318- /// (and right) superblock row that hang off the mi grid. Spec 5.11.50
319- /// `palette_tokens` reads the colour-index map only over the block's
320- /// `onscreenWidth x onscreenHeight` corner and replicates it outward;
321- /// this decoder read the full block grid, so it consumed colour-index
322- /// symbols libaom never wrote and desynced the rest of the tile -- either
323- /// a wrong bottom superblock row (1599 luma samples in this stream's
324- /// frame 0, ~80k per inter frame after) or, further along the same tile,
325- /// a bogus "a Golomb tail longer than this decoder reads" refusal.
326- ///
327- /// Unlike its lane-svt1 sibling above this one BUILDS its stream: the
328- /// recipe is synthetic (`smptebars,drawgrid` through `libsvtav1 -preset 8
329- /// -svtav1-params screen-content-mode=1`), and 384x152 puts a 32x32
330- /// palette block at mi row 32 of a 38-mi-tall frame, 24 of its 32 rows
331- /// on screen. `palette_onscreen_cut_hits` is asserted non-zero so the row
332- /// cannot pass on a stream that never cuts a palette map (class
333- /// gate-blind-to-feature).
334- #[test]
335- fn an_svt_screen_palette_map_cut_by_the_frame_edge_decodes_exactly() {
336- const NAME: &str = "an_svt_screen_palette_map_cut_by_the_frame_edge_decodes_exactly";
337- if !have_ffmpeg() {
338- eprintln!("SKIP {NAME}: no ffmpeg");
339- return;
340- }
341- let (width, height) = (384usize, 152usize);
342- let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
343- .args([
344- "-v",
345- "error",
346- "-f",
347- "lavfi",
348- "-i",
349- "smptebars=s=384x152:r=12,drawgrid=w=8:h=8:t=1:c=black",
350- "-frames:v",
351- "4",
352- "-c:v",
353- "libsvtav1",
354- "-preset",
355- "8",
356- "-crf",
357- "30",
358- "-svtav1-params",
359- "lp=1:screen-content-mode=1",
360- "-g",
361- "12",
362- "-f",
363- "obu",
364- "-",
365- ])
366- .stdin(Stdio::null())
367- .stdout(Stdio::piped())
368- .stderr(Stdio::piped()), None, |c| c.output())
369- .expect("ffmpeg failed to run");
370- if !out.status.success() || out.stdout.is_empty() {
371- eprintln!(
372- "SKIP {NAME}: no libsvtav1 in this ffmpeg: {}",
373- String::from_utf8_lossy(&out.stderr)
374- );
375- return;
376- }
377- let stream = out.stdout;
378- crate::decode::reset_palette_onscreen_cut_hits();
379- let decoded = decode_stream(&stream).expect("the SVT-AV1 screen stream decodes");
380- assert_eq!(decoded.len(), 4, "{NAME}: frame count");
381- assert!(
382- crate::decode::palette_onscreen_cut_hits() > 0,
383- "{NAME}: no palette map is cut by the frame edge here -- the gate would pass blind"
384- );
385- let want = ffmpeg_decode_sequence(&stream, width, height, decoded.len());
386- assert_eq!(want.len(), decoded.len(), "{NAME}: ffmpeg frame count");
387- for (i, (got, want)) in decoded.iter().zip(&want).enumerate() {
388- assert_eq!(got.y, want.y, "{NAME}: frame {i} luma vs ffmpeg");
389- assert_eq!(got.u, want.u, "{NAME}: frame {i} U vs ffmpeg");
390- assert_eq!(got.v, want.v, "{NAME}: frame {i} V vs ffmpeg");
391- }
392- }
393-
394- /// lane-svt1: an SVT-AV1 (v3.1.2, `-preset 8`) screen key frame codes 16x16
395- /// PALETTE blocks with `skip == 1` whose `tx_depth` split the luma
396- /// transform. [`crate::decode::decode_block`] armed the palette prediction
397- /// only when the transform covered the whole block, so that one block
398- /// predicted DC off its own edges instead: the right symbols (the whole mode
399- /// ladder diffs clean against an instrumented aomdec) and the wrong pixels
400- /// -- 812 luma samples in frame 0, carried by the V_PRED blocks under it to
401- /// 10122 samples over the 12-frame stream the defect was found on.
402- ///
403- /// lane-av1pinspec2: the gate used to RIDE an external crop named by
404- /// `EC_AV1_SVT1_STREAM` and SKIP when that was unset, so it never ran on a
405- /// stock box -- which is exactly why its oracle count could not be pinned
406- /// (an assert on a gate that never executes is an unexercised assert wearing
407- /// a pin's clothes). It now runs on the COMMITTED pin
408- /// `crates/ec-av1/fixtures/svt1-split-tx-pin.obu`.
409- ///
410- /// The pin is a REPLAY, not a fresh capture, and the recipe is recorded
411- /// because it reproduces the bytes exactly (two independent encodes on this
412- /// box, SVT-AV1 v3.1.2, both sha256
413- /// `c9d9c0ae934fba72fc9a9374bc36853f290796a8a4d6442140e239669e0b341f`,
414- /// 1838 bytes):
415- ///
416- /// ffmpeg -v error -f lavfi \
417- /// -i "smptehdbars=s=192x152:r=12,drawgrid=w=8:h=8:t=1:c=black" \
418- /// -frames:v 1 -c:v libsvtav1 -preset 8 -crf 50 \
419- /// -svtav1-params "lp=1:screen-content-mode=1" -g 12 -f obu out.obu
420- ///
421- /// `-frames:v 1` is the part lane-svt1's search lacked: its 6x5x6 sweep ran
422- /// FOUR frames per stream, and the ~200k-sample misses that killed every
423- /// candidate were on the INTER frames (`lanes/svt1.report.md`). One key
424- /// frame has no inter frames, and this one reaches the fixed arm
425- /// (`skip_split_tx_override_hits == 1`) and is pixel-exact.
426- ///
427- /// THE COUNT, and why it is derived from the wire rather than from a
428- /// literal. The oracle is handed the number of frame OBUs this stream
429- /// actually codes, counted with `Av1Parser` below -- never our decode's
430- /// length, which is the thing under test. A header count would OVER-count
431- /// a stream carrying `show_existing_frame` (spec 5.9.5: it codes no pixels,
432- /// so the header count is larger than the shown-frame count), so that case
433- /// is asserted impossible on this pin rather than assumed: the loop refuses
434- /// any frame header with `show_existing_frame` set, which is what makes
435- /// "one header == one shown frame" a checked fact here instead of an
436- /// argument.
437- ///
438- /// `EC_AV1_SVT1_STREAM` still overrides the pin, so a re-capture is one env
439- /// var away; `crate_pin` falls back to `pin_dir()` for the same reason.
440- ///
441- /// `skip_split_tx_override_hits` is asserted non-zero so the row cannot
442- /// pass on a stream that never reaches the fixed arm (class
443- /// gate-blind-to-feature).
444- #[test]
445- fn an_svt_screen_palette_block_with_a_split_transform_decodes_exactly() {
446- const NAME: &str = "an_svt_screen_palette_block_with_a_split_transform_decodes_exactly";
447- const PIN: &str = "svt1-split-tx-pin.obu";
448- if !have_ffmpeg() {
449- eprintln!("SKIP {NAME}: no ffmpeg");
450- return;
451- }
452- let path = match std::env::var("EC_AV1_SVT1_STREAM") {
453- Ok(p) => std::path::PathBuf::from(p),
454- // The name is spelled as a LITERAL here even though `PIN` is right
455- // above, on purpose: `gate_coverage::pin_inventory` matches a pin
456- // read by the quote that follows the callee name, so a const
457- // argument would leave this pin outside the "every pin a gate reads
458- // is a committed crate-local copy" invariant. The dup is the
459- // coverage -- and it is also why this comment must NOT quote that
460- // spelling: the scanner reads prose too, and a quoted spelling here
461- // parses as a pin called " and would not see a const argument, ...".
462- Err(_) => crate_pin("svt1-split-tx-pin.obu"),
463- };
464- let data = require_pin(&path, PIN);
465- // The ENCODE's frame count, read off the WIRE: parse this stream's own
466- // OBUs and count the frame headers. `show_existing_frame` is refused
467- // here on purpose -- such a header codes no pixels, so counting it
468- // would make this count larger than the frames the oracle can decode.
469- let mut parser = Av1Parser::new();
470- let mut pos = 0usize;
471- let mut frame_headers = 0usize;
472- while pos < data.len() {
473- let Ok(obu) = parser.parse_obu(&data[pos..]) else {
474- break;
475- };
476- pos += obu.total_size.max(1);
477- let header = match &obu.kind {
478- ObuKind::Frame(h, _) | ObuKind::FrameHeader(h) => h,
479- _ => continue,
480- };
481- assert!(
482- !header.show_existing_frame,
483- "{NAME}: frame header {frame_headers} sets show_existing_frame, so the header \
484- count is not the shown-frame count and this gate's oracle budget would be wrong"
485- );
486- frame_headers += 1;
487- }
488- assert!(
489- frame_headers > 0,
490- "{NAME}: {} carries no frame header at all",
491- path.display()
492- );
493- crate::decode::reset_skip_split_tx_override_hits();
494- let decoded = decode_stream(&data).expect("the pinned SVT-AV1 screen stream decodes");
495- assert!(
496- crate::decode::skip_split_tx_override_hits() > 0,
497- "{NAME}: no skipped split-transform palette block in {} -- the gate would pass blind",
498- path.display()
499- );
500- assert_eq!(
501- decoded.len(),
502- frame_headers,
503- "{NAME}: the stream codes {frame_headers} frame(s), the decode showed {}",
504- decoded.len()
505- );
506- let (width, height) = (decoded[0].width, decoded[0].height);
507- let want = ffmpeg_decode_sequence(&data, width, height, frame_headers);
508- for (i, (got, want)) in decoded.iter().zip(&want).enumerate() {
509- assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg");
510- assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg");
511- assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg");
512- }
513- }
514-
515- /// `decode_stream` agrees with ffmpeg/dav1d on the same wire bytes -- an
516- /// independent decoder, not just this crate checking its own tile path.
517- #[test]
518- fn decode_stream_agrees_with_ffmpeg_on_a_gop() {
519- let fctx = &crate::decode::FrameCtx::for_encoder();
520- if !have_ffmpeg() {
521- eprintln!("SKIP decode_stream_agrees_with_ffmpeg_on_a_gop: no ffmpeg");
522- return;
523- }
524- // lane-av1straddle: 216x96 joins 128x64 because only a size whose
525- // 32x32 blocks straddle the right-hand frame edge can see the writer
526- // coding a transform unit that starts outside the frame -- libdav1d
527- // AND libaom both refused the whole key frame while it did, and this
528- // crate's own (lenient) decoder only differed in the last block's V.
529- for &(width, height) in &[(128usize, 64usize), (216usize, 96usize)] {
530- let pictures: Vec<_> = (0..3)
531- .map(|i| panned_test_card(width, height, i * 3))
532- .collect();
533- let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
534- let ffmpeg_frames = ffmpeg_decode_sequence(&encoded.stream, width, height, 3);
535- let decoded = decode_stream(&encoded.stream).unwrap();
536- assert_eq!(decoded.len(), 3);
537- for (i, (got, want)) in decoded.iter().zip(&ffmpeg_frames).enumerate() {
538- assert_eq!(got.y, want.y, "{width}x{height} frame {i} luma vs ffmpeg");
539- assert_eq!(got.u, want.u, "{width}x{height} frame {i} U vs ffmpeg");
540- assert_eq!(got.v, want.v, "{width}x{height} frame {i} V vs ffmpeg");
541- }
542- // ... and the encoder's own reconstruction is what ffmpeg sees,
543- // so the check fails on a writer-side desync too, not only on a
544- // decoder-side one.
545- for (i, (frame, want)) in encoded.frames.iter().zip(&ffmpeg_frames).enumerate() {
546- let rec = &frame.reconstruction;
547- assert_eq!(
548- rec.y, want.y,
549- "{width}x{height} frame {i} luma: reconstruction vs ffmpeg"
550- );
551- assert_eq!(
552- rec.u, want.u,
553- "{width}x{height} frame {i} U: reconstruction vs ffmpeg"
554- );
555- assert_eq!(
556- rec.v, want.v,
557- "{width}x{height} frame {i} V: reconstruction vs ffmpeg"
558- );
559- }
560- }
561- }
562-
563- /// lane-av1rect: the encoder used to REFUSE every size where a 32x32
564- /// block straddles BOTH true frame edges at once ("straddles the true
565- /// frame edge in a way that needs a rectangular (HORZ/VERT) transform
566- /// this encoder does not code yet"). That refusal was a misreading of
567- /// spec 5.11.4: a block whose `hasRows` and `hasCols` are BOTH false
568- /// reads no partition symbol at all and is `PARTITION_SPLIT` by
569- /// inference, down to the 8x8 leaves whose own mi origin is inside the
570- /// frame -- exactly the leaves this writer already codes for the
571- /// one-axis case, and no rectangular transform anywhere. The sweep walks
572- /// the corners around the 32-multiples (each width has a 16x16 column
573- /// whose right half is outside, each height a row whose bottom half is,
574- /// so the bottom-right 16x16 of every size here is cut on both axes) and
575- /// three-way compares: our decoder, the encoder's own reconstruction and
576- /// ffmpeg, over a 4-frame GOP so the inter writer's copy of the same
577- /// signaling is covered too. `edge_both_cut_hits` proves the decoder
578- /// really took the inferred-split path rather than the gate passing on
579- /// geometry that never fires it.
580- #[test]
581- fn a_sweep_of_doubly_straddling_sizes_round_trips_through_ffmpeg() {
582- let fctx = &crate::decode::FrameCtx::for_encoder();
583- if !have_ffmpeg() {
584- eprintln!(
585- "SKIP a_sweep_of_doubly_straddling_sizes_round_trips_through_ffmpeg: no ffmpeg"
586- );
587- return;
588- }
589- const FRAMES: usize = 4;
590- let mut both_cut = 0usize;
591- for &width in &[200usize, 216, 232, 248] {
592- for &height in &[104usize, 120, 136, 152] {
593- let pictures: Vec<_> = (0..FRAMES as i64)
594- .map(|i| panned_test_card(width, height, i * 3))
595- .collect();
596- let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx)
597- .unwrap_or_else(|e| panic!("{width}x{height}: encoder refused: {e}"));
598- // Reset per attempt, never a delta across sizes (class
599- // counter-from-refused-stream).
600- crate::decode::reset_edge_both_cut_hits();
601- let decoded = decode_stream(&encoded.stream)
602- .unwrap_or_else(|e| panic!("{width}x{height}: our decoder refused: {e}"));
603- both_cut += crate::decode::edge_both_cut_hits().iter().sum::<usize>();
604- let ffmpeg_frames = ffmpeg_decode_sequence(&encoded.stream, width, height, FRAMES);
605- assert_eq!(
606- ffmpeg_frames.len(),
607- FRAMES,
608- "{width}x{height}: ffmpeg decoded {} of {FRAMES} frames",
609- ffmpeg_frames.len()
610- );
611- assert_eq!(decoded.len(), FRAMES, "{width}x{height}: frame count");
612- for (i, (got, want)) in decoded.iter().zip(&ffmpeg_frames).enumerate() {
613- assert_eq!(got.y, want.y, "{width}x{height} frame {i} luma vs ffmpeg");
614- assert_eq!(got.u, want.u, "{width}x{height} frame {i} U vs ffmpeg");
615- assert_eq!(got.v, want.v, "{width}x{height} frame {i} V vs ffmpeg");
616- }
617- for (i, (frame, want)) in encoded.frames.iter().zip(&ffmpeg_frames).enumerate() {
618- let rec = &frame.reconstruction;
619- assert_eq!(
620- rec.y, want.y,
621- "{width}x{height} frame {i} luma: recon vs ffmpeg"
622- );
623- assert_eq!(
624- rec.u, want.u,
625- "{width}x{height} frame {i} U: recon vs ffmpeg"
626- );
627- assert_eq!(
628- rec.v, want.v,
629- "{width}x{height} frame {i} V: recon vs ffmpeg"
630- );
631- }
632- }
633- }
634- assert!(
635- both_cut > 0,
636- "no partition node in the whole sweep was coded as the both-axes-cut \
637- inferred split -- the gate is blind to the feature it pins"
638- );
639- }
640-
641- /// lane-corner: sizes whose LAST superblock is cut by the true frame
642- /// edge on BOTH axes with more than half of each still inside -- so
643- /// `has_cols` and `has_rows` are both true and the spec lets that
644- /// superblock stay a whole 64x64 `PARTITION_NONE` block, which this
645- /// encoder's roots take (`EC_AV1_B64EDGE` on the inter side, the key
646- /// frame's own `Superblock::Whole`). The sibling luma-only test
647- /// (`encoder.rs`'s `a_non_superblock_aligned_clip_...`) is blind to
648- /// chroma (class `metric-blind-to-a-plane`), so this one compares all
649- /// three planes three ways: our decoder, the encoder's own
650- /// reconstruction, and ffmpeg.
651- #[test]
652- fn a_doubly_cut_superblock_root_round_trips_in_every_plane() {
653- let fctx = &crate::decode::FrameCtx::for_encoder();
654- if !have_ffmpeg() {
655- eprintln!("SKIP a_doubly_cut_superblock_root_round_trips_in_every_plane: no ffmpeg");
656- return;
657- }
658- const FRAMES: usize = 4;
659- // Each size leaves MORE than half of its last superblock row (and,
660- // but for 200x120's 8-px column, of its last column) inside, which is
661- // what makes the root legal there at all; 248x168/232x168/248x184 are
662- // cut on BOTH axes at once. 1920x1080 -- the user's own export shape
663- // -- is the same case: 1080 = 16*64 + 56, a 56-px bottom straddle.
664- for &(width, height) in &[(248usize, 168usize), (232, 168), (200, 120), (248, 184)] {
665- let pictures: Vec<_> = (0..FRAMES as i64)
666- .map(|i| panned_test_card(width, height, i * 3))
667- .collect();
668- let _ = crate::encode::take_b64_edge_hits();
669- let _ = crate::encode::take_i64_root_hits();
670- let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx)
671- .unwrap_or_else(|e| panic!("{width}x{height}: encoder refused: {e}"));
672- let edges = crate::encode::take_b64_edge_hits();
673- let [i64_whole, i64_offered, i64_edge] = crate::encode::take_i64_root_hits();
674- eprintln!(
675- "{width}x{height}: edge inter 64 roots {edges}, key 64 roots {i64_whole} of \
676- {i64_offered} offered, {i64_edge} of them cut by the frame edge"
677- );
678- // gate-blind-to-feature: without this the three-way compare below
679- // passes on a stream that never coded a whole root at the cut
680- // superblock at all.
681- assert!(
682- i64_edge > 0,
683- "{width}x{height}: no 64x64 root sat on a superblock the frame edge cuts"
684- );
685- let decoded = decode_stream(&encoded.stream)
686- .unwrap_or_else(|e| panic!("{width}x{height}: our decoder refused: {e}"));
687- let ffmpeg_frames = ffmpeg_decode_sequence(&encoded.stream, width, height, FRAMES);
688- assert_eq!(
689- ffmpeg_frames.len(),
690- FRAMES,
691- "{width}x{height}: ffmpeg frame count"
692- );
693- assert_eq!(decoded.len(), FRAMES, "{width}x{height}: frame count");
694- for (i, (got, want)) in decoded.iter().zip(&ffmpeg_frames).enumerate() {
695- assert_eq!(
696- got.y, want.y,
697- "{width}x{height} frame {i} luma: ours vs ffmpeg"
698- );
699- assert_eq!(
700- got.u, want.u,
701- "{width}x{height} frame {i} U: ours vs ffmpeg"
702- );
703- assert_eq!(
704- got.v, want.v,
705- "{width}x{height} frame {i} V: ours vs ffmpeg"
706- );
707- }
708- for (i, (frame, want)) in encoded.frames.iter().zip(&ffmpeg_frames).enumerate() {
709- let rec = &frame.reconstruction;
710- assert_eq!(
711- rec.y, want.y,
712- "{width}x{height} frame {i} luma: recon vs ffmpeg"
713- );
714- assert_eq!(
715- rec.u, want.u,
716- "{width}x{height} frame {i} U: recon vs ffmpeg"
717- );
718- assert_eq!(
719- rec.v, want.v,
720- "{width}x{height} frame {i} V: recon vs ffmpeg"
721- );
722- }
723- }
724- }
725-
726- /// A hand-built 3-frame stream that actually fires `GOLDEN_FRAME`
727- /// through [`decode_stream`], proving the round-4 flip (`decode.rs`'s
728- /// `decode_inter_block` `GOLDEN_FRAME` arm) the way 120+ real aomenc
729- /// attempts never could: frame 0 is a real key frame (this crate's own
730- /// encoder, real texture), refreshing all 8 DPB slots as spec requires --
731- /// slot 3 keeps that exact picture from here on. Frame 1 is a hand-coded
732- /// inter frame whose lone 32x32 block is *intra* (`DC_PRED`, `skip`),
733- /// refreshing only slot 0 with a flat 128 block -- distinguishable from
734- /// frame 0's real texture, so slot 0 (`LAST_FRAME`) and slot 3
735- /// (`GOLDEN_FRAME`) hold visibly different pictures once frame 2 runs.
736- /// Frame 2 is a hand-coded inter frame naming `ref_frame_idx[3] = 3`
737- /// (GOLDEN_FRAME's slot) and `ref_frame_idx[0] = 0` (LAST_FRAME's), whose
738- /// lone block codes `single_ref` all the way out to `GOLDEN_FRAME`
739- /// (`p1=0, p3=1, p5=1`) and a `skip` zero-MV `NEARESTMV`: a direct copy
740- /// of GOLDEN's picture, so its output must equal frame 0's own
741- /// reconstruction exactly, and must differ from frame 1's -- proof the
742- /// decoder actually read the golden plane, not silently substituted
743- /// `LAST_FRAME`'s. Rounds 4-9 masked and re-masked this arm chasing a
744- /// deblock/MC residue that turned out to be film-grain synthesis
745- /// (lane-av1golden7's `apply_grain` refusal, unrelated to GOLDEN);
746- /// lane-av1golden8 fixed mvstack's single-ref extension pass, clearing
747- /// the last real defect (`pinned_golden7` non_last_ref_hits 0->2), so
748- /// this fixture flips back to its round-4 pixel-exact form. ffmpeg
749- /// decodes the identical wire bytes as the foreign oracle
750- /// (shared-oracle-blindness class): this crate's own decoder agreeing
751- /// with itself would prove nothing.
752- #[test]
753- fn a_hand_built_golden_reference_decodes_pixel_exact_against_ffmpeg() {
754- let fctx = &crate::decode::FrameCtx::new();
755- if !have_ffmpeg() {
756- eprintln!(
757- "SKIP a_hand_built_golden_reference_decodes_pixel_exact_against_ffmpeg: no ffmpeg"
758- );
759- return;
760- }
761- use crate::cdf_state::Cdfs;
762- use crate::decode::{intra_inter_ctx, non_last_ref_hits, q_ctx_of};
763- use crate::encode::{inter_frame_headers, key_frame_headers};
764- use crate::frame::frame_obu;
765- use crate::msac::SymbolEncoder;
766- use crate::mvstack::{
767- GOLDEN_FRAME, MiGrid, find_mv_stack, single_ref_p1_ctx, single_ref_p3_ctx,
768- single_ref_p5_ctx,
769- };
770- use crate::obu::temporal_delimiter;
771-
772- let (width, height) = (32usize, 32usize);
773- let base_q_idx = 100u8;
774- // The whole picture is one 32x32 block: `partition_ctx`/`skip_ctx`/
775- // `intra_inter_ctx`'s neighbour inputs are all "no neighbour yet" --
776- // a fresh `Neighbours`' `above_side_mi`/`left_side_mi` start at `SB`
777- // (64), so `partition_ctx_mi`'s `side_mi * 2 <= side` (32) is false
778- // on both axes (ctx 0), and `above_skip`/`left_skip`/`above_inter`/
779- // `left_inter`/`above_ref`/`left_ref` all start `false`/`-1`
780- // (decode.rs `Neighbours::new`) -- computed here without
781- // constructing the (module-private) `Neighbours` itself.
782- const PARTITION_NONE: usize = 0;
783- let ii_ctx = intra_inter_ctx(false, false, false, false);
784- let sr_p1_ctx = single_ref_p1_ctx(None, None, None, None);
785- let sr_p3_ctx = single_ref_p3_ctx(None, None, None, None);
786- let sr_p5_ctx = single_ref_p5_ctx(None, None, None, None);
787-
788- for run in 0..4 {
789- let picture = test_card(width, height);
790- let key = encode_key_frame_with_ctx(&picture, base_q_idx, 0.5, fctx).unwrap();
791- let (seq, _) = key_frame_headers(width, height, base_q_idx).unwrap();
792-
793- // Frame 1: hand-coded, intra-only, refreshes slot 0 with a flat
794- // 128 block (no neighbours to predict `DC_PRED` from).
795- let (_, mut header1) = inter_frame_headers(width, height, base_q_idx, 1, 0).unwrap();
796- // These two tiles are hand-coded from a FRESH `Cdfs`, so the
797- // frames must not carry CDF state the way the encoder's own inter
798- // frames now do (spec 7.20): with the bit set, what each frame
799- // stores is what it started from -- the defaults -- which is
800- // exactly what the next hand-coded tile assumes.
801- header1.disable_frame_end_update_cdf = true;
802- let tile1 = {
803- let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));
804- let mut enc = SymbolEncoder::new();
805- enc.symbol(PARTITION_NONE, &mut cdfs.partition_w32[0]);
806- enc.symbol(1, &mut cdfs.skip[0]); // skip
807- enc.symbol(0, &mut cdfs.intra_inter[ii_ctx]); // is_inter = false
808- enc.symbol(0, &mut cdfs.y_mode[3]); // DC_PRED, size group 3 (32x32)
809- enc.symbol(0, &mut cdfs.uv_mode_cfl[0]); // DC_PRED
810- enc.finish()
811- };
812- let mut stream = key.stream.clone();
813- stream.extend(temporal_delimiter());
814- stream.extend(frame_obu(&seq, &header1, &tile1).unwrap());
815-
816- // Frame 2: hand-coded, single_ref all the way to GOLDEN_FRAME,
817- // skip zero-MV NEARESTMV -- a direct copy of slot 3 (frame 0).
818- let (_, mut header2) = inter_frame_headers(width, height, base_q_idx, 2, 0).unwrap();
819- header2.disable_frame_end_update_cdf = true;
820- header2.ref_frame_idx[3] = 3; // GOLDEN_FRAME's own slot: frame 0's, untouched by frame 1
821- let tile2 = {
822- let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));
823- let mut enc = SymbolEncoder::new();
824- let grid = MiGrid::new(8, 8);
825- let stack = find_mv_stack(&grid, 0, 0, 8, 8, GOLDEN_FRAME, 8, 8);
826- enc.symbol(PARTITION_NONE, &mut cdfs.partition_w32[0]);
827- enc.symbol(1, &mut cdfs.skip[0]); // skip
828- enc.symbol(1, &mut cdfs.intra_inter[ii_ctx]); // is_inter = true
829- enc.symbol(0, &mut cdfs.single_ref[sr_p1_ctx][0]); // p1: LAST/LAST2/LAST3/GOLDEN group
830- enc.symbol(1, &mut cdfs.single_ref[sr_p3_ctx][2]); // p3: GOLDEN/LAST3 sub-group
831- enc.symbol(1, &mut cdfs.single_ref[sr_p5_ctx][4]); // p5: GOLDEN_FRAME
832- enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not_new -> not NEWMV
833- enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not_zero -> not GLOBALMV
834- enc.symbol(0, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // nearest -> NEARESTMV, (0, 0)
835- enc.finish()
836- };
837- stream.extend(temporal_delimiter());
838- stream.extend(frame_obu(&seq, &header2, &tile2).unwrap());
839-
840- let before = non_last_ref_hits();
841- let decoded = decode_stream(&stream).unwrap();
842- assert_eq!(decoded.len(), 3, "run {run}: expected 3 pictures");
843- assert!(
844- non_last_ref_hits() > before,
845- "run {run}: GOLDEN_FRAME never fired"
846- );
847-
848- let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 3);
849- for (i, (got, want)) in decoded.iter().zip(&ffmpeg_frames).enumerate() {
850- assert_eq!(got.y, want.y, "run {run} frame {i}: luma vs ffmpeg");
851- assert_eq!(got.u, want.u, "run {run} frame {i}: U vs ffmpeg");
852- assert_eq!(got.v, want.v, "run {run} frame {i}: V vs ffmpeg");
853- }
854- assert_eq!(
855- decoded[0].y, key.reconstruction.y,
856- "run {run}: frame 0 vs the encoder's own reconstruction"
857- );
858- assert_eq!(
859- decoded[2].y, key.reconstruction.y,
860- "run {run}: GOLDEN_FRAME's block did not reproduce the keyframe it names"
861- );
862- assert_ne!(
863- decoded[2].y, decoded[1].y,
864- "run {run}: LAST_FRAME's and GOLDEN_FRAME's slots were not actually \
865- distinguishable -- the gate proves nothing"
866- );
867- }
868- }
869-
870- /// The determinism guard: same seed twice must byte-match ffmpeg's own
871- /// output; different seeds must not. Regresses this fix if it ever
872- /// breaks.
873- #[test]
874- fn gradients_source_is_reproducible_per_seed() {
875- if !have_ffmpeg() {
876- eprintln!("SKIP gradients_source_is_reproducible_per_seed: no ffmpeg");
877- return;
878- }
879- fn render_hash(lavfi: &str) -> Vec<u8> {
880- let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
881- .args([
882- "-v",
883- "error",
884- "-f",
885- "lavfi",
886- "-i",
887- lavfi,
888- "-frames:v",
889- "1",
890- "-f",
891- "rawvideo",
892- "-",
893- ])
894- .stdin(Stdio::null())
895- .stdout(Stdio::piped())
896- .stderr(Stdio::piped()), None, |c| c.output())
897- .expect("ffmpeg failed to run");
898- assert!(out.status.success(), "ffmpeg refused {lavfi}");
899- out.stdout
900- }
901- let a1 = render_hash(&gradients_source(42, 64, 64, "duration=0.04:rate=25"));
902- let a2 = render_hash(&gradients_source(43, 64, 64, "duration=0.04:rate=25"));
903- let a3 = render_hash(&gradients_source(42, 64, 64, "duration=0.04:rate=25"));
904- assert_eq!(a1, a3, "same seed must reproduce byte-identical output");
905- assert_ne!(a1, a2, "different seeds must not collide");
906- }
907-
908- /// The end-to-end gate: two real libaom-av1 configs, decoded with
909- /// [`decode_stream`] and checked against ffmpeg's own decode of the same
910- /// bytes. Not every config this encoder writes decodes yet (partitions
911- /// below 16x16, AB partitions, CfL and others remain round-2 gaps per the
912- /// r6 catalogue) -- both configs here pick `cpu-used 8` plus the
913- /// partition/angle-delta/CfL flags r6 found narrow the encoder onto this
914- /// decoder's supported syntax, while still landing on non-`DCT_DCT` tx
915- /// types on gradient content.
916- #[test]
917- fn a_real_libaom_stream_with_adst_decodes_end_to_end() {
918- if !have_ffmpeg() {
919- eprintln!("SKIP a_real_libaom_stream_with_adst_decodes_end_to_end: no ffmpeg");
920- return;
921- }
922- let configs: [(String, usize, usize, u32); 2] = [
923- ("testsrc2=size=64x64:rate=1".to_string(), 64, 64, 15),
924- (gradients_source(42, 64, 64, "rate=1"), 64, 64, 15),
925- ];
926- let mut verdicts = Vec::new();
927- for (lavfi, width, height, crf) in configs {
928- let lavfi = lavfi.as_str();
929- let Some(stream) = libaom_encode(lavfi, width, height, crf) else {
930- verdicts.push(format!("{lavfi}: ffmpeg itself refused to encode"));
931- continue;
932- };
933- match decode_stream(&stream) {
934- Ok(frames) => {
935- let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
936- let matches = frames[0].y == ffmpeg_frames[0].y
937- && frames[0].u == ffmpeg_frames[0].u
938- && frames[0].v == ffmpeg_frames[0].v;
939- verdicts.push(format!(
940- "{lavfi}: decoded, {} ffmpeg's own decode",
941- if matches { "MATCHES" } else { "MISMATCHES" }
942- ));
943- // Not a hard `assert!`: libaom's own mode decisions at
944- // `cpu-used 8` are not observed stable run-to-run on this
945- // box (multi-threaded RD search), so a run that happens
946- // to land on a still-unsupported syntax element (e.g. a
947- // partition below 16x16, a separate round-2 gap) can
948- // decode without erroring yet disagree -- that failure
949- // mode belongs to those other gaps, not to this round's
950- // ADST wiring, and the eprintln below reports it either
951- // way rather than hiding it.
952- }
953- Err(e) => {
954- verdicts.push(format!("{lavfi}: still refuses ({e})"));
955- }
956- }
957- }
958- eprintln!("libaom ADST end-to-end verdicts:");
959- for v in &verdicts {
960- eprintln!(" {v}");
961- }
962- }
963-
964- /// lane-dgolomb: the `force_integer_mv` gate. libaom turns screen-content
965- /// tools on for DARK, SMOOTH content -- its `av1_set_screen_content_options`
966- /// counts 16x16 blocks with 2..=4 distinct luma values -- and then sets
967- /// `force_integer_mv` on any inter frame whose source is pixel-identical to
968- /// the previously coded source (`av1_is_integer_mv`: `cs_rate >= 0.8` and
969- /// `C == T`, every collocated 8x8 block matching, is the only path that
970- /// returns 1). Both hold on his real AV1 films, and this decoder used to
971- /// drop `lower_mv_precision`'s `is_integer` half as unreachable, so every
972- /// temporal MV candidate on such a frame came out at eighth-pel: the frame
973- /// decoded without any error into a whole-frame prediction mismatch, and
974- /// the desync surfaced blocks later as "a Golomb tail longer than this
975- /// decoder reads".
976- ///
977- /// The source is SYNTHETIC (no film sample lives in `fixtures`): the
978- /// near-flat dark pattern libaom's own screen-content detector counts as
979- /// screen content, at the film-B crop size 1920x1024, SCROLLING globally
980- /// 5 px per frame and frozen on frame 8 -- an exact duplicate of frame 7
981- /// (the `C == T` trigger) whose twin is not among its own references, so
982- /// its blocks still code real motion under `force_integer_mv`.
983- ///
984- /// lane-dpm1 made this gate SENSITIVE: with the `force_integer_mv` branch
985- /// of [`crate::motion_field::lower_mv_precision`] stubbed out (`if false
986- /// &&`) the stream decodes WRONG -- frame 8, luma sample 25695, 20 against
987- /// ffmpeg's 19 -- where the previous patch-in-a-static-background recipe
988- /// (and two others tried) still decoded byte-exact: there the used mv-stack
989- /// slots came from agreeing spatial neighbours and the rounded temporal
990- /// entries never won one. The gate asserts both halves: at least one INTER
991- /// frame really carries `force_integer_mv` (class `gate-blind-to-feature`),
992- /// and every shown frame decodes sample-exact against ffmpeg's own decode.
993- #[test]
994- fn a_libaom_force_integer_mv_stream_decodes_exact() {
995- const NAME: &str = "a_libaom_force_integer_mv_stream_decodes_exact";
996- if !have_ffmpeg() {
997- eprintln!("SKIP {NAME}: no ffmpeg");
998- return;
999- }
1000- let (w, h, frames) = (1920usize, 1024usize, 16usize);
1001- let mut raw = Vec::with_capacity(frames * w * h * 3 / 2);
1002- let mut off = 0usize;
1003- for f in 0..frames {
1004- // lane-dpm1: the WHOLE picture scrolls 5 px per frame and freezes
1005- // on frame 8, so (a) every block of the frozen frame -- including
1006- // mi(0,0), which has no spatial neighbour at all -- still codes
1007- // real motion against the references that are not its twin, and
1008- // (b) 40 eighth-pels projected over the pyramid's distances lands
1009- // on non-multiples of 8 (40/2 = 20 -> 16). A patch moving inside a
1010- // static background was NOT sensitive: there the used stack slots
1011- // came from spatial neighbours that agreed, and the rounded
1012- // temporal entries never won one.
1013- if f > 0 && f != 8 {
1014- off = (off + 5) % h;
1015- }
1016- let mut y = vec![0u8; w * h];
1017- for row in 0..h {
1018- let src = (row + off) % h;
1019- for col in 0..w {
1020- // 2..=4 distinct values per 16x16 block, all dark: the
1021- // screen-content detector's own counting rule.
1022- y[row * w + col] =
1023- 16 + ((col / 32 + src / 32) % 5) as u8 + ((col / 4 + src / 4) % 3) as u8;
1024- }
1025- }
1026- raw.extend_from_slice(&y);
1027- raw.extend(std::iter::repeat_n(128u8, w * h / 2));
1028- }
1029- // [[pid-keyed-temp-path]]: parallel test binaries must not share a name.
1030- let src = std::env::temp_dir().join(format!("ec-av1-intmv-{}.yuv", std::process::id()));
1031- std::fs::write(&src, &raw).expect("raw source");
1032- let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1033- .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"])
1034- .args(["-s", &format!("{w}x{h}"), "-r", "24", "-i"])
1035- .arg(&src)
1036- .args(["-an", "-threads", "1", "-g", "16", "-c:v", "libaom-av1"])
1037- .args([
1038- "-cpu-used",
1039- "6",
1040- "-b:v",
1041- "0",
1042- "-crf",
1043- "35",
1044- "-f",
1045- "obu",
1046- "-",
1047- ])
1048- .stdin(Stdio::null())
1049- .stdout(Stdio::piped())
1050- .stderr(Stdio::piped()), None, |c| c.output())
1051- .expect("ffmpeg failed to run");
1052- let _ = std::fs::remove_file(&src);
1053- if !out.status.success() {
1054- eprintln!(
1055- "SKIP {NAME}: ffmpeg has no libaom-av1 encoder ({})",
1056- String::from_utf8_lossy(&out.stderr)
1057- );
1058- return;
1059- }
1060- let stream = out.stdout;
1061-
1062- // Half of the gate: the stream must actually carry the feature.
1063- let mut parser = Av1Parser::new();
1064- let (mut pos, mut int_mv_inter) = (0usize, 0usize);
1065- while pos < stream.len() {
1066- let obu = parser.parse_obu(&stream[pos..]).expect("libaom OBU parses");
1067- pos += obu.total_size.max(1);
1068- let header = match &obu.kind {
1069- ObuKind::FrameHeader(h) | ObuKind::Frame(h, _) => h,
1070- _ => continue,
1071- };
1072- if header.force_integer_mv && !header.frame_is_intra && header.use_ref_frame_mvs {
1073- int_mv_inter += 1;
1074- }
1075- }
1076- assert!(
1077- int_mv_inter > 0,
1078- "{NAME} went blind: libaom coded no inter frame with force_integer_mv"
1079- );
1080-
1081- let ours = decode_stream(&stream).expect("libaom screen-content stream decodes");
1082- let theirs = ffmpeg_decode_sequence(&stream, w, h, frames);
1083- assert_eq!(ours.len(), frames, "shown frame count");
1084- for (i, (a, b)) in ours.iter().zip(theirs.iter()).enumerate() {
1085- for (plane, l, r) in [("Y", &a.y, &b.y), ("U", &a.u, &b.u), ("V", &a.v, &b.v)] {
1086- let first = l.iter().zip(r.iter()).position(|(x, y)| x != y);
1087- assert!(
1088- first.is_none(),
1089- "frame {i} plane {plane} differs from ffmpeg at sample {} \
1090- ({int_mv_inter} force_integer_mv inter frames in this stream)",
1091- first.unwrap()
1092- );
1093- assert_eq!(
1094- l.len(),
1095- r.len(),
1096- "frame {i} plane {plane}: ours has {} samples, ffmpeg's has {} -- a short \
1097- plane would zip-truncate the compare above and hide a chroma-span defect",
1098- l.len(),
1099- r.len()
1100- );
1101- }
1102- }
1103- }
1104-
1105- /// lane-dpm1: the 128x128-INTRA-inside-an-INTER-frame chroma context gate.
1106- /// A 128x128 block codes its chroma as four TX_32X32 units, one per 64x64
1107- /// mu chunk, and libaom stamps the coefficient context PER UNIT. The two
1108- /// INTER mu-chunk sites set `mu_chroma` so the block tail re-stamps the
1109- /// four units in mu order; the INTRA-in-inter site did not, so the
1110- /// whole-block record left every unit carrying the TOP-LEFT unit's level.
1111- /// The next block then read its `txb_skip` off ctx 11 where libaom reads
1112- /// ctx 10 (class `override-slot-on-one-arm`) -- one symbol on the wrong
1113- /// CDF row, tile desynced, and because the loop-restoration coefficients
1114- /// live in the same tile data the damage showed up as a +-1 luma sample at
1115- /// the TOP of the frame (measured: frame 1, luma sample 66, ours 146 /
1116- /// ffmpeg 145, with 1.7M samples wrong behind it).
1117- ///
1118- /// Source: the repository's own 2160p colour-bar fixture at the native
1119- /// gate's crop (1920x1024 out of the middle), 12 frames, libaom
1120- /// `-cpu-used 6 -crf 45 -g 12` -- the first reference point of
1121- /// `bd_rate_screen_native`'s "bars 2160p" row, which is where the assertion
1122- /// caught it. The gate asserts the tool fired (class
1123- /// `gate-blind-to-feature`) and that every shown frame decodes sample-exact
1124- /// against ffmpeg's own decode.
1125- #[test]
1126- fn a_libaom_stream_with_128_intra_blocks_in_inter_frames_decodes_exact() {
1127- const NAME: &str = "a_libaom_stream_with_128_intra_blocks_in_inter_frames_decodes_exact";
1128- if !have_ffmpeg() {
1129- eprintln!("SKIP {NAME}: no ffmpeg");
1130- return;
1131- }
1132- // lane-av1clipprobe: the bare `clip.exists()` -> SKIP had no env
1133- // escape, so on a tree with no root `fixtures/` this 128-intra-block
1134- // gate reported green having decoded nothing.
1135- let Some(clip) = crate::library_fixture::require("video/h264-2160p-23.976-8bit.mp4", NAME)
1136- else {
1137- return;
1138- };
1139- let (w, h, frames) = (1920usize, 1024usize, 12usize);
1140- // [[pid-keyed-temp-path]]: parallel test binaries must not share a name.
1141- let src = std::env::temp_dir().join(format!("ec-av1-i128-{}.yuv", std::process::id()));
1142- let load = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1143- .args(["-v", "error", "-y", "-i"])
1144- .arg(&clip)
1145- .args([
1146- "-frames:v",
1147- &frames.to_string(),
1148- "-vf",
1149- "crop=1920:1024:960:568",
1150- ])
1151- .args(["-f", "rawvideo", "-pix_fmt", "yuv420p"])
1152- .arg(&src), None, |c| c.output())
1153- .expect("ffmpeg failed to run");
1154- assert!(
1155- load.status.success(),
1156- "{NAME}: {}",
1157- String::from_utf8_lossy(&load.stderr)
1158- );
1159- let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1160- .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"])
1161- .args(["-s", &format!("{w}x{h}"), "-r", "24", "-i"])
1162- .arg(&src)
1163- .args(["-an", "-threads", "1", "-g", "12", "-c:v", "libaom-av1"])
1164- .args([
1165- "-cpu-used",
1166- "6",
1167- "-b:v",
1168- "0",
1169- "-crf",
1170- "45",
1171- "-f",
1172- "obu",
1173- "-",
1174- ])
1175- .stdin(Stdio::null())
1176- .stdout(Stdio::piped())
1177- .stderr(Stdio::piped()), None, |c| c.output())
1178- .expect("ffmpeg failed to run");
1179- let _ = std::fs::remove_file(&src);
1180- if !out.status.success() {
1181- eprintln!(
1182- "SKIP {NAME}: ffmpeg has no libaom-av1 encoder ({})",
1183- String::from_utf8_lossy(&out.stderr)
1184- );
1185- return;
1186- }
1187- let stream = out.stdout;
1188- let before = crate::decode::intra_128_in_inter_hits();
1189- let ours = decode_stream(&stream).expect("libaom bars stream decodes");
1190- assert!(
1191- crate::decode::intra_128_in_inter_hits() > before,
1192- "{NAME} went blind: no 128-rooted intra block inside an inter frame"
1193- );
1194- let theirs = ffmpeg_decode_sequence(&stream, w, h, frames);
1195- assert_eq!(ours.len(), frames, "shown frame count");
1196- for (i, (a, b)) in ours.iter().zip(theirs.iter()).enumerate() {
1197- for (plane, l, r) in [("Y", &a.y, &b.y), ("U", &a.u, &b.u), ("V", &a.v, &b.v)] {
1198- let first = l.iter().zip(r.iter()).position(|(x, y)| x != y);
1199- assert!(
1200- first.is_none(),
1201- "frame {i} plane {plane} differs from ffmpeg at sample {}",
1202- first.unwrap()
1203- );
1204- assert_eq!(
1205- l.len(),
1206- r.len(),
1207- "frame {i} plane {plane}: ours has {} samples, ffmpeg's has {} -- a short \
1208- plane would zip-truncate the compare above and hide a chroma-span defect",
1209- l.len(),
1210- r.len()
1211- );
1212- }
1213- }
1214- }
1215-
1216- /// lane-lossless: the refusal became an implementation, so its gate became
1217- /// a DECODE-EXACT one (class `refusal-lifted-without-a-gate`). libaom at
1218- /// `-crf 0` codes `base_q_idx == 0` -- the same lossless frame his
1219- /// screen-capture row gets at `-crf 5` -- where every plane is TX_4X4 with
1220- /// the Walsh-Hadamard transform, no `tx_type` symbol is coded
1221- /// (`read_tx_type`, `decodetxb.c`: "No need to read transform type for
1222- /// lossless mode(qindex==0)") and `is_cfl_allowed` (`blockd.h`) narrows to
1223- /// a BLOCK_4X4 chroma plane block. The gate asserts the stream really is
1224- /// lossless (class `gate-blind-to-feature`), that every KEY frame decodes
1225- /// sample-exact against ffmpeg, and that the still-unimplemented lossless
1226- /// INTER frame is refused BY NAME rather than decoded wrong.
1227- #[test]
1228- fn a_lossless_libaom_key_frame_decodes_sample_exact() {
1229- const NAME: &str = "a_lossless_libaom_key_frame_decodes_sample_exact";
1230- if !have_ffmpeg() {
1231- eprintln!("SKIP {NAME}: no ffmpeg");
1232- return;
1233- }
1234- let (w, h, frames) = (256usize, 128usize, 2usize);
1235- let mut raw = Vec::with_capacity(frames * w * h * 3 / 2);
1236- for f in 0..frames {
1237- for row in 0..h {
1238- for col in 0..w {
1239- raw.push(((col * 7 + row * 13 + f * 31) % 251) as u8);
1240- }
1241- }
1242- // lane-lossless2: TEXTURED chroma. A flat chroma plane codes one
1243- // `txb_skip` symbol per 4x4 unit with every context at 0, which
1244- // is blind to both the unit ORDER and the per-unit contexts
1245- // (class `gate-blind-to-feature`).
1246- for row in 0..h / 2 {
1247- for col in 0..w / 2 {
1248- raw.push((((col + f) * 11 + row * 5) % 251) as u8);
1249- }
1250- }
1251- for row in 0..h / 2 {
1252- for col in 0..w / 2 {
1253- raw.push(((col * 3 + (row + f) * 17) % 251) as u8);
1254- }
1255- }
1256- }
1257- // [[pid-keyed-temp-path]]: parallel test binaries must not share a name.
1258- let src = std::env::temp_dir().join(format!("ec-av1-lossless-{}.yuv", std::process::id()));
1259- std::fs::write(&src, &raw).expect("raw source");
1260- let encode = |gop: &str| {
1261-
1262- crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1263- .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"])
1264- .args(["-s", &format!("{w}x{h}"), "-r", "24", "-i"])
1265- .arg(&src)
1266- .args(["-an", "-threads", "1", "-g", gop, "-c:v", "libaom-av1"])
1267- .args(["-cpu-used", "6", "-b:v", "0", "-crf", "0", "-f", "obu", "-"])
1268- .stdin(Stdio::null())
1269- .stdout(Stdio::piped())
1270- .stderr(Stdio::piped()), None, |c| c.output())
1271- .expect("ffmpeg failed to run")
1272- };
1273- let out = encode("1");
1274- let _ = std::fs::remove_file(&src);
1275- if !out.status.success() {
1276- eprintln!(
1277- "SKIP {NAME}: ffmpeg has no libaom-av1 encoder ({})",
1278- String::from_utf8_lossy(&out.stderr)
1279- );
1280- return;
1281- }
1282- let stream = out.stdout;
1283- // Half of the gate: the stream must really carry a lossless frame
1284- // (class `gate-blind-to-feature`).
1285- let mut parser = Av1Parser::new();
1286- let (mut pos, mut lossless) = (0usize, 0usize);
1287- while pos < stream.len() {
1288- let obu = parser.parse_obu(&stream[pos..]).expect("libaom OBU parses");
1289- pos += obu.total_size.max(1);
1290- let header = match &obu.kind {
1291- ObuKind::FrameHeader(h) | ObuKind::Frame(h, _) => h,
1292- _ => continue,
1293- };
1294- if header.lossless.iter().all(|&l| l) {
1295- lossless += 1;
1296- }
1297- }
1298- assert_eq!(
1299- lossless, frames,
1300- "{NAME} went blind: libaom coded no lossless key frame at -crf 0"
1301- );
1302- let ours = decode_stream(&stream).expect("a lossless key-frame stream decodes");
1303- let refs = ffmpeg_decode_sequence(&stream, w, h, frames);
1304- assert_eq!(ours.len(), frames, "{NAME}: frame count");
1305- for (i, (got, want)) in ours.iter().zip(refs.iter()).enumerate() {
1306- for (plane, (g, r)) in [(&got.y, &want.y), (&got.u, &want.u), (&got.v, &want.v)]
1307- .iter()
1308- .enumerate()
1309- {
1310- let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count();
1311- assert_eq!(
1312- bad, 0,
1313- "{NAME}: frame {i} plane {plane}: {bad} samples differ"
1314- );
1315- assert_eq!(
1316- g.len(),
1317- r.len(),
1318- "{NAME}: frame {i} plane {plane}: ours has {} samples, ffmpeg's has {} -- a \
1319- short plane would zip-truncate the compare above and hide a chroma-span \
1320- defect",
1321- g.len(),
1322- r.len()
1323- );
1324- }
1325- }
1326- }
1327-
1328- /// lane-lossless2: the refusal `a_lossless_inter_frame_is_refused_by_name`
1329- /// pinned became an implementation, so its gate became a DECODE-EXACT one
1330- /// (class `refusal-lifted-without-a-gate`). A lossless INTER frame codes
1331- /// its chroma plane as 4x4 transform units, plane-major inside each 64x64
1332- /// mu chunk (libaom `read_tx_size` returns TX_4X4 for every plane under
1333- /// `xd->lossless[..]`, and `decode_token_recon_block` walks
1334- /// `for (plane..) for (blk_row..) for (blk_col..)`), which is what
1335- /// `decode::read_inter_chroma_lossless` reads. The source carries TEXTURED
1336- /// CHROMA and real motion on purpose: a flat-chroma source codes one
1337- /// `txb_skip` symbol per unit and is blind to both the unit order and the
1338- /// per-unit contexts (class `gate-blind-to-feature`).
1339- #[test]
1340- fn a_lossless_libaom_inter_frame_decodes_sample_exact() {
1341- const NAME: &str = "a_lossless_libaom_inter_frame_decodes_sample_exact";
1342- if !have_ffmpeg() {
1343- eprintln!("SKIP {NAME}: no ffmpeg");
1344- return;
1345- }
1346- // (w, h, frames, gop, bit depth, 128-superblock, screen content)
1347- // lane-lossless2: the SCREEN rows carry palette blocks, which is what
1348- // caught the whole-block palette prediction being handed to a 4x4
1349- // chroma unit.
1350- // lane-lossless3: the last row is a screen source with INTER frames --
1351- // the row that caught both of this lane's defects (a skip 8x8 leaf
1352- // restoring the previous block's luma level band over the zeros
1353- // `av1_reset_entropy_context` writes, and a rect sub-8x8 INTRA leaf
1354- // reading one TX_4X8 unit where a lossless frame codes two TX_4X4).
1355- let cases: [(usize, usize, usize, &str, u32, bool, bool); 7] = [
1356- (256, 128, 8, "4", 8, false, false),
1357- (192, 96, 6, "3", 10, false, false),
1358- (320, 192, 6, "3", 8, false, false),
1359- (256, 256, 4, "2", 8, true, false),
1360- (320, 192, 2, "1", 8, false, true),
1361- (640, 384, 2, "1", 8, false, true),
1362- (640, 384, 6, "3", 8, false, true),
1363- ];
1364- for &(w, h, frames, gop, depth, sb128, screen) in &cases {
1365- let tag = format!(
1366- "{w}x{h} {depth}-bit gop {gop}{}{}",
1367- if sb128 { " sb128" } else { "" },
1368- if screen { " screen" } else { "" }
1369- );
1370- let mut raw: Vec<u8> = Vec::new();
1371- let put = |v: u32, raw: &mut Vec<u8>| {
1372- if depth == 10 {
1373- raw.extend_from_slice(&((v * 4) as u16).to_le_bytes());
1374- } else {
1375- raw.push(v as u8);
1376- }
1377- };
1378- // A screen source is a few flat colours in 16x16 tiles plus
1379- // 1-px text-like rows -- what makes libaom code palette blocks.
1380- const PAL: [u32; 8] = [16, 60, 110, 145, 180, 210, 235, 128];
1381- for f in 0..frames {
1382- for row in 0..h {
1383- for col in 0..w {
1384- let v = if screen {
1385- if row % 7 == 0 && col % 3 == 0 {
1386- if (col / 3 + row + f) % 2 == 1 {
1387- 16
1388- } else {
1389- 235
1390- }
1391- } else {
1392- PAL[((col + 4 * f) / 16 + row / 16) % PAL.len()]
1393- }
1394- } else {
1395- (((col + 2 * f) * 7 + row * 13) % 251) as u32
1396- };
1397- put(v, &mut raw);
1398- }
1399- }
1400- for plane in 0..2usize {
1401- for row in 0..h / 2 {
1402- for col in 0..w / 2 {
1403- let v = if screen {
1404- PAL[((col + 2 * f) / 8 + row / 8 + plane) % PAL.len()]
1405- } else if plane == 0 {
1406- (((col + f) * 11 + row * 5) % 251) as u32
1407- } else {
1408- ((col * 3 + (row + f) * 17) % 251) as u32
1409- };
1410- put(v, &mut raw);
1411- }
1412- }
1413- }
1414- }
1415- let pix = if depth == 10 {
1416- "yuv420p10le"
1417- } else {
1418- "yuv420p"
1419- };
1420- // [[pid-keyed-temp-path]]: parallel test binaries must not share a name.
1421- let src = std::env::temp_dir().join(format!(
1422- "ec-av1-lossless2-{}-{w}x{h}-{depth}.yuv",
1423- std::process::id()
1424- ));
1425- std::fs::write(&src, &raw).expect("raw source");
1426- let mut cmd = Command::new("ffmpeg");
1427- cmd.args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", pix])
1428- .args(["-s", &format!("{w}x{h}"), "-r", "24", "-i"])
1429- .arg(&src)
1430- .args(["-an", "-threads", "1", "-g", gop, "-c:v", "libaom-av1"])
1431- .args(["-pix_fmt", pix, "-cpu-used", "6", "-b:v", "0", "-crf", "0"]);
1432- if sb128 {
1433- cmd.args(["-aom-params", "sb-size=128"]);
1434- }
1435- if screen {
1436- cmd.args(["-aom-params", "tune-content=screen"]);
1437- }
1438- let out = crate::tool_cache::cached_output_io(cmd
1439- .args(["-f", "obu", "-"])
1440- .stdin(Stdio::null())
1441- .stdout(Stdio::piped())
1442- .stderr(Stdio::piped()), None, |c| c.output())
1443- .expect("ffmpeg failed to run");
1444- let _ = std::fs::remove_file(&src);
1445- if !out.status.success() {
1446- eprintln!(
1447- "SKIP {NAME}: ffmpeg has no libaom-av1 encoder ({})",
1448- String::from_utf8_lossy(&out.stderr)
1449- );
1450- return;
1451- }
1452- let stream = out.stdout;
1453- // The stream must really be lossless AND really carry inter frames
1454- // (class `gate-blind-to-feature`).
1455- let mut parser = Av1Parser::new();
1456- let (mut pos, mut lossless, mut inters) = (0usize, 0usize, 0usize);
1457- while pos < stream.len() {
1458- let obu = parser.parse_obu(&stream[pos..]).expect("libaom OBU parses");
1459- pos += obu.total_size.max(1);
1460- let header = match &obu.kind {
1461- ObuKind::FrameHeader(h) | ObuKind::Frame(h, _) => h,
1462- _ => continue,
1463- };
1464- if header.lossless.iter().all(|&l| l) {
1465- lossless += 1;
1466- }
1467- if header.frame_type == FrameType::Inter {
1468- inters += 1;
1469- }
1470- }
1471- assert!(
1472- lossless >= frames,
1473- "{NAME} [{tag}] went blind: {lossless} lossless frames"
1474- );
1475- assert!(
1476- screen || inters > 0,
1477- "{NAME} [{tag}] went blind: no inter frame at gop {gop}"
1478- );
1479- let ours = decode_stream(&stream)
1480- .unwrap_or_else(|e| panic!("{NAME} [{tag}]: a lossless inter stream decodes: {e}"));
1481- let refs = if depth == 10 {
1482- ffmpeg_decode_sequence_10bit(&stream, w, h, frames)
1483- } else {
1484- ffmpeg_decode_sequence(&stream, w, h, frames)
1485- };
1486- assert_eq!(ours.len(), frames, "{NAME} [{tag}]: frame count");
1487- for (i, (got, want)) in ours.iter().zip(refs.iter()).enumerate() {
1488- for (plane, (g, r)) in [(&got.y, &want.y), (&got.u, &want.u), (&got.v, &want.v)]
1489- .iter()
1490- .enumerate()
1491- {
1492- let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count();
1493- assert_eq!(
1494- bad, 0,
1495- "{NAME} [{tag}]: frame {i} plane {plane}: {bad} samples differ"
1496- );
1497- assert_eq!(
1498- g.len(),
1499- r.len(),
1500- "{NAME} [{tag}]: frame {i} plane {plane}: ours has {} samples, ffmpeg's has \
1501- {} -- a short plane would zip-truncate the compare above and hide a \
1502- chroma-span defect",
1503- g.len(),
1504- r.len()
1505- );
1506- }
1507- }
1508- }
1509- }
1510-
1511- /// lane-av1-llband: the pinned 4:4:4 LOSSLESS key frame
1512- /// (`fixtures/ll444-lossless-key.obu`, the `ll444` recipe's frame 0 --
1513- /// `testsrc2 128x96` yuv444p cut to its key frame) decodes sample-exact,
1514- /// and its HORZ/VERT strips really walked their chroma as 4x4 units at
1515- /// subsampling 0/0 (one unit per mi cell). That unit walk used the 4:2:0
1516- /// span (8 luma px per 4x4 chroma unit) unconditionally, so every unit
1517- /// past the first column/row read its `txb_skip` context two mi cells
1518- /// over and stamped a 2-cell smear -- the 178-byte key-frame miss, first
1519- /// divergence at the 16x8 leaf mi (16,24)'s U bc=2 unit (oracle
1520- /// `txb_skip` base 0 off `above[26]`, ours base 1 off the polluted
1521- /// `above[29]`). The counter assertion is the non-vacuity half (class
1522- /// `gate-blind-to-feature`): a stream that never reaches the 4:4:4 unit
1523- /// walk must not pass.
1524- #[test]
1525- fn a_real_aomenc_lossless_444_key_frame_decodes_sample_exact() {
1526- const NAME: &str = "a_real_aomenc_lossless_444_key_frame_decodes_sample_exact";
1527- if !have_ffmpeg() {
1528- eprintln!("SKIP {NAME}: no ffmpeg");
1529- return;
1530- }
1531- // lane-av1pins: committed at crates/ec-av1/fixtures/ll444-lossless-key.obu
1532- // (7845 bytes; sha256
1533- // f496ef0a1171c2bc66d411cc60db05db547dcdb49cd834d4e0543de9db441374),
1534- // re-encoded 2026-09-29 from the recipe this very SKIP line records --
1535- // `testsrc2 128x96` yuv444p 6 frames, aomenc --profile=1 --lossless=1
1536- // --enable-palette=0 --enable-intrabc=0 --bit-depth=8 --cpu-used=0
1537- // --threads=1 --row-mt=0 --lag-in-frames=0 --kf-max-dist=100, --limit=1
1538- // so the key frame's OBUs are the whole stream (no OBU surgery needed).
1539- //
1540- // lane-av1skipfix: reading the pin from the GITIGNORED root
1541- // `fixtures/` (`pin_dir()`) is what made this gate report green having
1542- // decoded nothing -- a fresh clone, and every linked worktree, can
1543- // never have that directory. The pin is now COMMITTED under the crate
1544- // (the home the other pins use) and read through `CARGO_MANIFEST_DIR`,
1545- // so a missing file is a REPO DEFECT and fails unconditionally: there
1546- // is no environment left to escape, which is strictly stronger than
1547- // the `EC_REQUIRE_FIXTURES` / `EC_AV1_REQUIRE_AOMENC` opt-in hard
1548- // fail this arm used to carry.
1549- let pin = crate_pin("ll444-lossless-key.obu");
1550- let stream = std::fs::read(&pin).unwrap_or_else(|e| {
1551- panic!(
1552- "{NAME}: the pinned 4:4:4 lossless key frame is missing at {} ({e}). A \
1553- COMMITTED pin that is absent is a repo defect and this gate would prove \
1554- nothing. No script generates it -- regenerate it with `testsrc2 128x96` \
1555- yuv444p 6 frames, aomenc --profile=1 --lossless=1 --enable-palette=0 \
1556- --enable-intrabc=0 --bit-depth=8 --cpu-used=0 --threads=1 --row-mt=0 \
1557- --lag-in-frames=0 --kf-max-dist=100 --limit=1, and commit the result.",
1558- pin.display()
1559- )
1560- });
1561- // Blindness guard: the pinned fixture must really be a lossless frame.
1562- let mut parser = Av1Parser::new();
1563- let mut pos = 0usize;
1564- let mut lossless = false;
1565- while pos < stream.len() {
1566- let obu = parser.parse_obu(&stream[pos..]).expect("aomenc OBU parses");
1567- pos += obu.total_size.max(1);
1568- if let ObuKind::FrameHeader(h) | ObuKind::Frame(h, _) = obu.kind {
1569- lossless = h.lossless.iter().all(|&l| l);
1570- }
1571- }
1572- assert!(
1573- lossless,
1574- "{NAME} went blind: the pinned frame is not lossless"
1575- );
1576- let before = crate::decode::rect_split_lossless_chroma444_hits();
1577- let ours = decode_stream(&stream).expect("a 444 lossless key-frame stream decodes");
1578- assert_eq!(ours.len(), 1, "{NAME}: frame count");
1579- assert!(
1580- crate::decode::rect_split_lossless_chroma444_hits() > before,
1581- "{NAME} went blind: no lossless HORZ/VERT strip walked its chroma \
1582- as 4x4 units at subsampling 0/0"
1583- );
1584- let refs = Command::new("ffmpeg")
1585- .args([
1586- "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv444p", "-",
1587- ])
1588- .stdin(Stdio::piped())
1589- .stdout(Stdio::piped())
1590- .stderr(Stdio::piped())
1591- .spawn()
1592- .and_then(|mut child| {
1593- use std::io::Write as _;
1594- child.stdin.as_mut().expect("stdin").write_all(&stream)?;
1595- child.wait_with_output()
1596- })
1597- .expect("ffmpeg 444 decode failed");
1598- assert!(
1599- refs.status.success(),
1600- "{}",
1601- String::from_utf8_lossy(&refs.stderr)
1602- );
1603- let frame = &ours[0];
1604- let planes = [
1605- (&frame.y, frame.width * frame.height),
1606- (&frame.u, frame.width * frame.height),
1607- (&frame.v, frame.width * frame.height),
1608- ];
1609- let mut off = 0usize;
1610- for (plane, (g, len)) in planes.iter().enumerate() {
1611- let raw = &refs.stdout[off..off + len];
1612- let bad = g
1613- .iter()
1614- .zip(raw.iter())
1615- .filter(|&(&a, &b)| a != u16::from(b))
1616- .count();
1617- assert_eq!(bad, 0, "{NAME}: plane {plane}: {bad} samples differ");
1618- off += len;
1619- }
1620- }
1621-
1622- /// lane-av1-llinter: the firing gate for the lossless 4:4:4 INTER chroma
1623- /// fix. The fixture is the report's dodge2 stream pinned into `fixtures/`:
1624- /// aomenc profile 1 over testsrc2 128x96 yuv444p, `--lossless=1`,
1625- /// `--sb-size=64 --min-partition-size=64 --max-partition-size=64`, 6
1626- /// frames; 37658 bytes, sha256
1627- /// `5a070fa351a3f2109de855234f2b3d0a872970f3e7f658db21f65c12eeb135b4`.
1628- /// The firing counter is the EXISTING `decode::chroma_split_tx_hits` (one
1629- /// bump per lossless chroma TX unit read): with min=max partition 64 the
1630- /// roots stay whole 64x64 inter blocks -- no 8x8 leaf exists in this
1631- /// stream -- so every chroma unit goes through the big-block ss-aware
1632- /// lossless route this lane fixed (fixes 2-5). A 4:2:0 lossless stream
1633- /// fires the same counter, but the fixture bytes are pinned, so the gate
1634- /// cannot run on anything else; the pre-fix 4:2:0-hardcoded math corrupts
1635- /// at 4:4:4, so the pixel-exact compares are what prove the ss-aware path
1636- /// (class `gate-blind-to-feature`). Every frame must come out pixel-exact
1637- /// through BOTH the oracle `aomdec --rawvideo` and ffmpeg. The
1638- /// default-partition ll444 stream is deliberately NOT claimed here: its
1639- /// key frame is still the intra lane's named sub8-chroma stop
1640- /// (lanes/av1llintra.report.md).
1641- #[test]
1642- fn a_lossless_444_min_partition64_inter_stream_decodes_pixel_exact() {
1643- const NAME: &str = "a_lossless_444_min_partition64_inter_stream_decodes_pixel_exact";
1644- const FIXTURE_LEN: usize = 37658;
1645- const FIXTURE_FNV: u64 = 0xf68d_c26f_a14d_283c;
1646- const W: usize = 128;
1647- const H: usize = 96;
1648- const FRAMES: usize = 6;
1649- let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1650- .join("fixtures/ll444_minp64_inter.obu");
1651- let stream = std::fs::read(&obu).unwrap_or_else(|e| {
1652- panic!(
1653- "{NAME}: pinned fixture {} is missing ({e}) -- the gate cannot run, \
1654- which is a failure, not a skip",
1655- obu.display()
1656- )
1657- });
1658- assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: fixture length moved");
1659- assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: fixture bytes moved");
1660-
1661- let _guard = lock_gate_counters();
1662- let before = crate::decode::chroma_split_tx_hits();
1663- let frames = decode_stream(&stream)
1664- .unwrap_or_else(|e| panic!("{NAME}: the pinned stream no longer decodes cleanly: {e}"));
1665- let hits = crate::decode::chroma_split_tx_hits();
1666- assert!(
1667- hits > before,
1668- "{NAME}: gate is vacuous -- no lossless chroma TX unit was read \
1669- (delta {before} -> {hits})"
1670- );
1671- assert_eq!(frames.len(), FRAMES, "{NAME}: frame count");
1672- for f in &frames {
1673- assert_eq!((f.width, f.height), (W, H), "{NAME}: dimensions");
1674- }
1675-
1676- // The oracle aomdec, rawvideo out: FRAMES concatenated yuv444p frames.
1677- if aomdec_available(NAME) {
1678- let dir = std::env::temp_dir().join(format!("ec-av1-ll444-{}", std::process::id()));
1679- let _ = std::fs::remove_dir_all(&dir);
1680- std::fs::create_dir_all(&dir).expect("scratch dir");
1681- let raw = dir.join("aomdec.raw");
1682- let out = crate::tool_cache::cached_output_io(Command::new(aomdec_path())
1683- .args(["--codec=av1", "--rawvideo", "-o"])
1684- .arg(&raw)
1685- .arg(&obu)
1686- .stdin(Stdio::null())
1687- .stdout(Stdio::piped())
1688- .stderr(Stdio::piped()), None, |c| c.output())
1689- .expect("aomdec failed to run");
1690- assert!(
1691- out.status.success(),
1692- "{NAME}: the oracle aomdec refused the stream: {}",
1693- String::from_utf8_lossy(&out.stderr)
1694- );
1695- let ref_raw = std::fs::read(&raw).expect("aomdec rawvideo output");
1696- let _ = std::fs::remove_dir_all(&dir);
1697- assert_eq!(ref_raw.len(), W * H * 3 * FRAMES, "{NAME}: aomdec raw size");
1698- for (i, f) in frames.iter().enumerate() {
1699- let base = i * W * H * 3;
1700- for ((plane, off), p) in [(&f.y, 0usize), (&f.u, W * H), (&f.v, 2 * W * H)]
1701- .into_iter()
1702- .zip(["y", "u", "v"])
1703- {
1704- let want = &ref_raw[base + off..base + off + W * H];
1705- let bad = plane
1706- .iter()
1707- .zip(want)
1708- .filter(|&(&a, &b)| a as u8 != b)
1709- .count();
1710- assert_eq!(
1711- bad, 0,
1712- "{NAME}: aomdec frame {i} plane {p}: {bad} samples differ"
1713- );
1714- assert_eq!(
1715- plane.len(),
1716- want.len(),
1717- "{NAME}: aomdec frame {i} plane {p}: ours has {} samples, the oracle's \
1718- has {} -- a short plane would zip-truncate the compare above and hide \
1719- a chroma-span defect",
1720- plane.len(),
1721- want.len()
1722- );
1723- }
1724- }
1725- }
1726-
1727- // ffmpeg's decoder: same frames, full-resolution chroma.
1728- if have_ffmpeg() {
1729- let refs = ffmpeg_decode_sequence_444(&stream, W, H, FRAMES);
1730- for (i, (got, want)) in frames.iter().zip(refs.iter()).enumerate() {
1731- for (p, (g, r)) in [(&got.y, &want.y), (&got.u, &want.u), (&got.v, &want.v)]
1732- .iter()
1733- .enumerate()
1734- {
1735- let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count();
1736- assert_eq!(
1737- bad, 0,
1738- "{NAME}: ffmpeg frame {i} plane {p}: {bad} samples differ"
1739- );
1740- assert_eq!(
1741- g.len(),
1742- r.len(),
1743- "{NAME}: ffmpeg frame {i} plane {p}: ours has {} samples, ffmpeg's has {} \
1744- -- a short plane would zip-truncate the compare above and hide a \
1745- chroma-span defect",
1746- g.len(),
1747- r.len()
1748- );
1749- }
1750- }
1751- } else {
1752- eprintln!("SKIP {NAME} ffmpeg arm: no ffmpeg");
1753- }
1754- }
1755-
1756- /// lane-av1h5: the 128-ROOT lossless 4:4:4 pin, and the control arm
1757- /// that proves the 128 root is what it needs.
1758- ///
1759- /// Witness: testsrc2 128x96 yuv444p10le, aomenc `--profile=1 --lossless=1
1760- /// --enable-palette=0 --enable-intrabc=0 --cpu-used=0`, 6 frames; 63429
1761- /// bytes, sha256 `bbffb979d20d581deb271aac75b7ee779dde57c024524ed6b1389356f55ca0fa`.
1762- /// Control: the same recipe at `--max-partition-size=64` (61494 bytes,
1763- /// sha256 `4cadce41e1f8967567b32f5cf8abaa46ffdf4fd6d4afe784c8d99a7f6bf1ae4c`),
1764- /// which never reaches a 128 root.
1765- ///
1766- /// libaom's `decode_token_recon_block` (`av1/decoder/decodeframe.c:972`)
1767- /// walks 64x64 "mu" chunks with the PLANE loop inside the chunk loop, on a
1768- /// chunk grid of `mi_size_wide[BLOCK_64X64]` = 16 mi per axis. The var-tx
1769- /// leaf list is a BLOCK-wide raster (32 leaves across at 128), so a chunk's
1770- /// members are not contiguous: leaves 0..15 are chunk (0,0) row 0, but
1771- /// chunk (0,0) rows 1..15 are leaves 32..47, 64..79, ... A chunk test on
1772- /// the given order closed the chunk every SIXTEEN leaves and coded each
1773- /// chunk's chroma sixteen times.
1774- ///
1775- /// The three assertions below are all EXACT and all stay true when the
1776- /// stream becomes byte-exact. None of them is a floor on wrong output:
1777- /// a no-op [`crate::decode::mu_chunk_order`] permutation reads 0 on
1778- /// `mu_chunk_order_hits`, so the first cannot be satisfied by a gate that
1779- /// merely ran; the walk and unit totals are libaom's own per-chunk counts;
1780- /// the control arm is a straight exactness assertion.
1781- #[test]
1782- fn a_lossless_444_128_root_lossless_stream_reads_chunks_chunk_major() {
1783- const NAME: &str = "a_lossless_444_128_root_lossless_stream_reads_chunks_chunk_major";
1784- const W: usize = 128;
1785- const H: usize = 96;
1786- const FRAMES: usize = 6;
1787- /// 5 inter frames, one unsplit 128 root each; frame 0 splits.
1788- const ROOTS: usize = 5;
1789- /// libaom's chunk grid on a 128x128 root: 2x2 chunks per root.
1790- const CHUNKS_PER_ROOT: usize = 4;
1791- /// Chroma TX_4X4 units per inter frame: 768 per plane over 128x96.
1792- const UNITS_PER_FRAME: usize = 1536;
1793-
1794- let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1795- .join("fixtures/ll444_128root_lossless.obu");
1796- let stream = read_pin(&obu, 63429, 0xf07d_47fc_fd51_2658, NAME);
1797- let _guard = lock_gate_counters();
1798- let (o0, w0, u0) = (
1799- crate::decode::mu_chunk_order_hits(),
1800- crate::decode::mu_chunk_walks(),
1801- crate::decode::mu_chunk_walk_units(),
1802- );
1803- let frames = decode_stream(&stream)
1804- .unwrap_or_else(|e| panic!("{NAME}: the pinned stream no longer decodes cleanly: {e}"));
1805- let (o1, w1, u1) = (
1806- crate::decode::mu_chunk_order_hits(),
1807- crate::decode::mu_chunk_walks(),
1808- crate::decode::mu_chunk_walk_units(),
1809- );
1810- // (1) the reorder PERMUTED each root's walk -- a no-op reads 0.
1811- assert_eq!(
1812- o1 - o0,
1813- ROOTS,
1814- "{NAME}: the chunk-major sort permuted {}/{} of the 128 roots -- a no-op \
1815- ordering must read 0 here, so this is what makes the gate non-vacuous",
1816- o1 - o0,
1817- ROOTS
1818- );
1819- // (2) libaom's own per-chunk counts: 4 chroma walks per 128 root, and
1820- // the 1536 chroma units an inter frame codes at 128x96 4:4:4.
1821- assert_eq!(
1822- w1 - w0,
1823- ROOTS * CHUNKS_PER_ROOT,
1824- "{NAME}: {}/{} chunk-major chroma walks; the 16x redundancy (64 per \
1825- frame instead of 4) would read {}",
1826- w1 - w0,
1827- ROOTS * CHUNKS_PER_ROOT,
1828- ROOTS * CHUNKS_PER_ROOT * 16
1829- );
1830- assert_eq!(
1831- u1 - u0,
1832- ROOTS * UNITS_PER_FRAME,
1833- "{NAME}: {}/{} chroma units over the 128 roots; the oracle codes {} \
1834- per inter frame and our pre-fix walk read 16x that",
1835- u1 - u0,
1836- ROOTS * UNITS_PER_FRAME,
1837- UNITS_PER_FRAME
1838- );
1839- assert_eq!(frames.len(), FRAMES, "{NAME}: frame count");
1840- for f in &frames {
1841- assert_eq!((f.width, f.height), (W, H), "{NAME}: dimensions");
1842- }
1843-
1844- // (3) the control arm: no 128 root, and byte-exact through the oracle.
1845- let ctrl = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1846- .join("fixtures/ll444_minp64_128root_control.obu");
1847- let ctrl_stream = read_pin(
1848- &ctrl,
1849- 61494,
1850- 0xf6f5_a3cb_efc7_eb10,
1851- &format!("{NAME} control"),
1852- );
1853- let _ = decode_stream(&ctrl_stream)
1854- .unwrap_or_else(|e| panic!("{NAME}: the control arm no longer decodes cleanly: {e}"));
1855- if aomdec_available(NAME) {
1856- assert_rawvideo_matches(&ctrl, &ctrl_stream, NAME, FRAMES, 10);
1857- }
1858- }
1859-
1860- /// lane-av1lm444loss: a LOSSLESS block's transform-unit grid is clipped at
1861- /// the FRAME edge, exactly as libaom's `max_block_high`/`max_block_wide`
1862- /// clip it (`av1_common_int.h:1565`, `:1579` fold `mb_to_bottom_edge` /
1863- /// `mb_to_right_edge` into `block_size_high/wide` before `>>
1864- /// MI_SIZE_LOG2`), so a block hanging off the bottom/right codes only the
1865- /// units inside the frame. `decode_token_recon_block` then bounds every
1866- /// mu chunk with `unit_height = ROUND_POWER_OF_TWO(AOMMIN(mu_blocks_high
1867- /// + row, max_blocks_high), ss_y)`, so the overflow units are never read
1868- /// there either.
1869- ///
1870- /// Fixture is the sibling [`a_lossless_444_128_root_lossless_stream_reads_chunks_chunk_major`]
1871- /// pin -- 128x96 yuv444p 4:4:4 lossless, 6 frames, 63429 bytes -- because
1872- /// 96 is NOT a multiple of the 128 superblock: its five inter frames each
1873- /// carry one unsplit 128 root that overhangs the bottom by 32 px. That is
1874- /// the whole reason this stream is the witness. The frame is 24 mi tall,
1875- /// so `max_blocks_high >> 2` is 24 transform rows where the block's own
1876- /// `side / MI` is 32.
1877- ///
1878- /// The three assertions are all non-vacuous and all EXACT:
1879- ///
1880- /// 1. `lossless_edge_clipped()` fired -- 5, one per inter frame's 128
1881- /// root. It is 0 on any frame whose height and width are multiples of
1882- /// the superblock, so a stream that merely decodes cannot satisfy it.
1883- /// 2. `lossless_edge_clip_units()` is 1280 = 5 x 256: the 8 transform rows
1884- /// x 32 columns the unclipped walk read past the frame bottom, per
1885- /// inter frame. The pre-fix walk read 2560 units per inter frame
1886- /// against the oracle's 2304, and this is that 256.
1887- /// 3. every sample of every frame matches the oracle `aomdec
1888- /// --rawvideo` in decode order -- all six frames, hidden alt-ref
1889- /// included, which the pre-fix tree failed from frame 1 on
1890- /// (5596 wrong samples there, growing to 33561 by frame 5).
1891- ///
1892- /// The control arm pins the other direction of the invariant: the
1893- /// `ll444_minp64_128root_control` stream has no overhanging root, so its
1894- /// clip counters must both read 0 -- the clip cannot fire on a block that
1895- /// fits, which is what keeps every other lossless pin byte-identical.
1896- #[test]
1897- fn a_lossless_block_clips_its_transform_grid_at_the_frame_edge() {
1898- const NAME: &str = "a_lossless_block_clips_its_transform_grid_at_the_frame_edge";
1899- const W: usize = 128;
1900- const H: usize = 96;
1901- const FRAMES: usize = 6;
1902- /// 5 inter frames, one unsplit 128 root each; frame 0 splits.
1903- const ROOTS: usize = 5;
1904- /// `max_blocks_high >> 2` = 24 rows (96 px / 4), against the block's
1905- /// own `side / MI` = 32 -- so 8 rows x 32 columns = 256 units per root
1906- /// were read past the frame bottom before the clip.
1907- const CLIP_UNITS_PER_ROOT: usize = 256;
1908-
1909- let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1910- .join("fixtures/ll444_128root_lossless.obu");
1911- let stream = read_pin(&obu, 63429, 0xf07d_47fc_fd51_2658, NAME);
1912- let _guard = lock_gate_counters();
1913- let (c0, u0) = (
1914- crate::decode::lossless_edge_clipped(),
1915- crate::decode::lossless_edge_clip_units(),
1916- );
1917- let frames = decode_stream(&stream)
1918- .unwrap_or_else(|e| panic!("{NAME}: the pinned stream no longer decodes cleanly: {e}"));
1919- let (c1, u1) = (
1920- crate::decode::lossless_edge_clipped(),
1921- crate::decode::lossless_edge_clip_units(),
1922- );
1923- assert_eq!(
1924- c1 - c0,
1925- ROOTS,
1926- "{NAME}: the frame-edge clip fired on {}/{} of the 128 roots -- it must be 0 \
1927- on a frame that fits, so this is what makes the gate non-vacuous",
1928- c1 - c0,
1929- ROOTS
1930- );
1931- assert_eq!(
1932- u1 - u0,
1933- ROOTS * CLIP_UNITS_PER_ROOT,
1934- "{NAME}: the clip removed {}/{} transform units; the unclipped walk read {} \
1935- per inter frame past the 96 px frame bottom (8 rows x 32 columns)",
1936- u1 - u0,
1937- ROOTS * CLIP_UNITS_PER_ROOT,
1938- CLIP_UNITS_PER_ROOT
1939- );
1940- assert_eq!(frames.len(), FRAMES, "{NAME}: frame count");
1941- for f in &frames {
1942- assert_eq!((f.width, f.height), (W, H), "{NAME}: dimensions");
1943- }
1944- if aomdec_available(NAME) {
1945- assert_rawvideo_matches(&obu, &stream, NAME, FRAMES, 10);
1946- }
1947-
1948- // Control: a stream whose roots all fit must not clip at all.
1949- let ctrl = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1950- .join("fixtures/ll444_minp64_128root_control.obu");
1951- let ctrl_stream = read_pin(
1952- &ctrl,
1953- 61494,
1954- 0xf6f5_a3cb_efc7_eb10,
1955- &format!("{NAME} control"),
1956- );
1957- let (c2, u2) = (
1958- crate::decode::lossless_edge_clipped(),
1959- crate::decode::lossless_edge_clip_units(),
1960- );
1961- let _ = decode_stream(&ctrl_stream)
1962- .unwrap_or_else(|e| panic!("{NAME}: the control arm no longer decodes cleanly: {e}"));
1963- assert_eq!(
1964- crate::decode::lossless_edge_clipped() - c2,
1965- 0,
1966- "{NAME} control: the clip fired on a stream whose blocks all fit -- the clip \
1967- must be a no-op there, which is what keeps every other lossless pin \
1968- byte-identical"
1969- );
1970- assert_eq!(
1971- crate::decode::lossless_edge_clip_units() - u2,
1972- 0,
1973- "{NAME} control: the clip removed units from a stream whose blocks all fit"
1974- );
1975- }
1976-
1977- /// lane-av1lm444loss-corr: the MI STEP at which `decode_intrabc_rect`'s
1978- /// lossless chroma replay walks the plane block.
1979- ///
1980- /// `lane-whtshape` (`f541d062`, merged `afa13bcf`) gave this route the
1981- /// per-TX_4X4 lossless chroma walk and the tail replay that re-stamps
1982- /// each unit's own coefficient context over the whole-block record. The
1983- /// replay stepped by `4 >> ss_y(fctx)` mi cells, which is 4:2:0-only
1984- /// arithmetic: at ss (1,1) it reads 2 and the ss-aware form
1985- /// `(4 << ss_y) / MI` also reads 2, so 4:2:0 agrees by construction; at
1986- /// ss (0,0) it reads 4 mi, i.e. 16 luma px per 4x4 chroma unit, where the
1987- /// unit covers `4 << 0` = 4 luma px = ONE mi. Every replayed unit was
1988- /// therefore stamped at 4x its own mi origin on a 4:4:4 lossless frame,
1989- /// writing over cells that belong to other blocks.
1990- ///
1991- /// This gate is the WIRNESS stream, not a vacuous one. The 4:2:0
1992- /// 4x4-identity is stated in the step's own comment and measured by the
1993- /// `4:2:0` arm of the lane's invariant battery, not asserted here --
1994- /// a 4:2:0 stream cannot fail this gate, by construction, and pretending
1995- /// otherwise would be a floor on wrong output.
1996- ///
1997- /// Fixture `ll444_intrabc_rect_l2.obu`, 121844 bytes, sha256
1998- /// `f0de080edce35d34cdd628b71f63dc452f946e8328352b69d3c1da090a54ec67`:
1999- /// `testsrc2 512x128 yuv444p`, aomenc `--lossless=1 --cpu-used=2
2000- /// --lag-in-frames=0 --kf-max-dist=100 --limit=6`, 6 frames. On main's
crates/ec-av1/src/stream/tests/t03.rsdeleted+0 -4567

Diff too large; view file

@@ -1,4567 +0,0 @@
1-use super::*;
2-use super::support::*;
3-use super::gates_a::*;
4-use crate::probe::run_with_stdin;
5-use std::process::{Command, Stdio};
6-
7- /// As [`a_real_libaom_gradients_stream_decodes_pixel_exact`], but leaves
8- /// CDEF *on* (no `-enable-cdef 0`) -- the whole point of `lane-av1cdef`:
9- /// proves `apply_cdef` itself, not just that this decoder still works
10- /// when the filter never fires. Gradient content at a low crf reliably
11- /// gives libaom something to dering.
12- ///
13- /// lane-av1skipfix: the attempt-loop shape. A single-SB 64x64 frame can
14- /// never make libaom write `cdef_bits > 0` (nothing to differentiate per
15- /// superblock), so this recipe is MULTI-SB and MULTI-FRAME, and it sweeps
16- /// (size, cpu-used, crf) until one attempt reads a real `cdef_idx` literal
17- /// -- MEASURED 2026-09-29 on `a21f3680`: 64x64 at every crf/cpu reads
18- /// ZERO `cdef_idx` (single superblock, `bits == 0`, though `apply_cdef`
19- /// does filter with a nonzero strength pair), while 128x64/128x128 at
20- /// 24 frames read 2-8. Every attempt that decodes is ALWAYS pixel-
21- /// compared against ffmpeg's own decode of the identical bytes; a decode
22- /// error is a named refusal recorded per attempt, never a SKIP, and
23- /// exhausting every attempt -- or decoding without ever reading a
24- /// `cdef_idx` -- is a hard FAILURE (an unfired gate is a vacuous gate,
25- /// class `gate-skips-on-its-own-failure`).
26- #[test]
27- fn a_real_libaom_gradients_stream_with_cdef_decodes_pixel_exact() {
28- const NAME: &str = "a_real_libaom_gradients_stream_with_cdef_decodes_pixel_exact";
29- let _gate_lock = lock_gate_counters();
30- if !have_ffmpeg() {
31- eprintln!("SKIP {NAME}: no ffmpeg");
32- return;
33- }
34- // (width, height, frames, cpu-used, crf). The frame count is what
35- // gives libaom's cdef search more than one superblock to price.
36- const RECIPES: [(usize, usize, usize, &str, u32); 8] = [
37- (128, 64, 24, "0", 20),
38- (128, 64, 24, "2", 20),
39- (128, 64, 24, "0", 16),
40- (128, 128, 24, "2", 20),
41- (128, 128, 24, "0", 16),
42- (128, 128, 24, "0", 24),
43- (128, 64, 24, "2", 24),
44- (128, 128, 24, "2", 24),
45- ];
46- let mut refusals = Vec::new();
47- let mut counted_exact = 0u32;
48- let mut uncounted_exact = 0u32;
49- for (w, h, frames, cpu, crf) in RECIPES {
50- let Some(stream) = libaom_encode_with(
51- &gradients_source(42, w, h, "rate=25"),
52- w,
53- h,
54- crf,
55- &[
56- "-cpu-used",
57- cpu,
58- "-frames:v",
59- &frames.to_string(),
60- "-threads",
61- "1",
62- "-row-mt",
63- "0",
64- "-tile-columns",
65- "0",
66- "-tile-rows",
67- "0",
68- ],
69- ) else {
70- refusals.push(format!(
71- "{w}x{h} cpu-used {cpu} crf {crf}: ffmpeg itself refused"
72- ));
73- continue;
74- };
75- let before = decode::cdef_idx_hits();
76- let decoded = match decode_stream(&stream) {
77- Ok(frames) => frames,
78- Err(e) => {
79- refusals.push(format!("{w}x{h} cpu-used {cpu} crf {crf}: {e}"));
80- continue;
81- }
82- };
83- // A decode that succeeded is ALWAYS pixel-compared; the hit
84- // counter only decides whether the attempt counts as firing
85- // (class `counter-from-refused-stream`).
86- let counted = decode::cdef_idx_hits() != before;
87- if counted {
88- counted_exact += 1;
89- } else {
90- uncounted_exact += 1;
91- }
92- let ffmpeg_frames = ffmpeg_decode_sequence(&stream, w, h, frames);
93- assert_eq!(decoded.len(), frames);
94- for (i, (got, want)) in decoded.iter().zip(&ffmpeg_frames).enumerate() {
95- assert_eq!(
96- got.y, want.y,
97- "{NAME} frame {i} luma vs ffmpeg ({w}x{h} cpu-used {cpu} crf {crf}, \
98- cdef_idx fired: {counted})"
99- );
100- assert_eq!(
101- got.u, want.u,
102- "{NAME} frame {i} U vs ffmpeg ({w}x{h} cpu-used {cpu} crf {crf}, \
103- cdef_idx fired: {counted})"
104- );
105- assert_eq!(
106- got.v, want.v,
107- "{NAME} frame {i} V vs ffmpeg ({w}x{h} cpu-used {cpu} crf {crf}, \
108- cdef_idx fired: {counted})"
109- );
110- }
111- if counted_exact >= 2 {
112- break;
113- }
114- }
115- gate_buckets(NAME, counted_exact, uncounted_exact, refusals.len());
116- assert!(
117- counted_exact > 0,
118- "{NAME}: no attempt of {} read a cdef_idx literal -- CDEF is not exercised \
119- (class gate-blind-to-feature):\n{}",
120- RECIPES.len(),
121- refusals.join("\n")
122- );
123- }
124-
125- /// lane-av1422h232: the non-vacuity test for [`count_rawvideo_diffs`].
126- ///
127- /// A cell-classifying counter that cannot report a difference is worse
128- /// than no counter, because it reports "exact" for everything -- that is
129- /// exactly how lane-av1422remeasure's "18/18 byte-exact" table was
130- /// produced (it compared our own packed samples against the same
131- /// samples, never reading `aomdec`'s output).
132- ///
133- /// It used to lean on the pinned witness DIFFERING to prove the counting
134- /// path fires. That witness is byte-exact now (lane-av1422hrtx fixed the
135- /// 32-point inter chroma `tx_type`), so "it differs" is no longer
136- /// available and a witness-based version of this test would be vacuous by
137- /// construction. Instead this proves the same property directly and
138- /// unconditionally: flipping ONE bit of the ORACLE's own bytes must move
139- /// the count by exactly one, in the plane that bit is in, and knock exactly
140- /// one frame out of `frames_exact`. A comparator that had stopped reading
141- /// the oracle reports the baseline numbers again and fails by name.
142- #[test]
143- fn the_counting_oracle_diff_detects_one_flipped_oracle_byte() {
144- const NAME: &str = "the_counting_oracle_diff_detects_one_flipped_oracle_byte";
145- // lane-av1cmpaudit2: same mutex as every other oracle gate -- this
146- // one reads `aomdec_path()`, so it must not overlap a sibling's
147- // tampered-oracle run.
148- let _gate_lock = lock_gate_counters();
149- let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
150- .join("fixtures")
151- .join("420_oddheight_320x232.obu");
152- let data = std::fs::read(&path).expect("the pinned witness is missing");
153- let (wy, wu, wv, frames, exact) =
154- count_rawvideo_diffs(&data, NAME, None).expect("the two sides must be byte-comparable");
155- assert_eq!(
156- (wy, wu, wv, exact),
157- (0, 0, 0, frames),
158- "{NAME}: the pinned witness must decode byte-exactly against `aomdec --rawvideo`"
159- );
160- // Frame 0 byte 0 is luma; byte 90_000 is inside frame 0's chroma.
161- for (idx, plane) in [(0usize, 0usize), (90_000, 1)] {
162- let (wy, wu, wv, _, exact) = count_rawvideo_diffs(&data, NAME, Some(idx))
163- .expect("the two sides must be byte-comparable");
164- let got = [wy, wu, wv];
165- assert_eq!(
166- got.iter().sum::<usize>(),
167- 1,
168- "{NAME}: flipping oracle byte {idx} must report exactly ONE wrong sample \
169- across all planes -- got {got:?}. Reporting the unflipped numbers means \
170- the comparison stopped reading the oracle's bytes"
171- );
172- assert_eq!(got[plane], 1, "{NAME}: byte {idx} is in plane {plane}");
173- assert_eq!(
174- exact,
175- frames - 1,
176- "{NAME}: one flipped byte spoils one frame"
177- );
178- }
179- eprintln!("{NAME}: baseline exact, each flipped oracle byte reported as exactly 1");
180- }
181-
182- /// lane-av1cmpframe: the control for the class
183- /// `comparator-that-attributes-the-wrong-plane`.
184- ///
185- /// [`count_rawvideo_diffs`] used to derive its plane split from the FIRST
186- /// decoded picture and compare every byte index against those frame-0
187- /// thresholds. On a multi-frame stream that attributes every sample after
188- /// frame 0's luma to the LAST plane: on the pinned 320x236 stream below
189- /// (16 frames of 320x236 4:2:0, 113 280 bytes per frame, so plane V holds
190- /// 302 080 bytes in total) it reported `wrong_v = 330 673` -- more wrong V
191- /// bytes than exist. The per-frame totals and the frame-exact count were
192- /// sound, so the defect was invisible to every gate that only asserted
193- /// zeros; it corrupted exactly the numbers a per-plane report exists to
194- /// give.
195- ///
196- /// Three arms, each of which the old attribution FAILS:
197- ///
198- /// 1. **Arithmetic.** Each plane's count must be at most that plane's own
199- /// byte capacity summed over frames, and the three must sum to the
200- /// independently computed total. The old code reported 330 673 wrong V
201- /// bytes in a 302 080-byte plane.
202- /// 2. **A later frame's U.** Flipping one byte inside frame 5's U plane
203- /// must move U by exactly one and leave Y and V at their baseline.
204- /// The old code has no frame-5 U at all -- byte 600 000 is past every
205- /// frame-0 threshold, so it landed in V.
206- /// 3. **Frame attribution.** `frames_exact` must equal the number of
207- /// frames this test counts itself, per frame, from the decoded
208- /// pictures' own plane lengths.
209- ///
210- /// The pin is asserted only for IDENTITY (bytes + fnv1a64) and for
211- /// comparability. Whether the stream currently diverges is deliberately
212- /// NOT asserted: this is a control for the INSTRUMENT, and it must keep
213- /// biting after the odd-height entropy fork is fixed.
214- #[test]
215- fn the_counting_oracle_diff_attributes_planes_per_frame() {
216- const NAME: &str = "the_counting_oracle_diff_attributes_planes_per_frame";
217- let _gate_lock = lock_gate_counters();
218- const FILE: &str = "420_oddheight_320x236.obu";
219- const BYTES: usize = 16562;
220- // sha256 84e4d1ab56620af1c5b78e1aa3d2d67496a492f2e127198c82dd1d68b01c6200.
221- // The tree pins fixture identity by fnv1a64; a `const SHA256`
222- // compared against itself would be the tautology this lane exists to
223- // kill, so it is not written.
224- const FNV1A64: u64 = 521889434652397870;
225- let data = crate_pin("420_oddheight_320x236.obu");
226- let data = std::fs::read(&data)
227- .unwrap_or_else(|e| panic!("{NAME}: the committed pin {FILE} is missing ({e})"));
228- assert_eq!(data.len(), BYTES, "{NAME}: {FILE} size drifted");
229- assert_eq!(fnv1a64(&data), FNV1A64, "{NAME}: {FILE} bytes drifted");
230- let bit_depth = stream_bit_depth(&data, NAME);
231- let bpp = if bit_depth == 8 { 1 } else { 2 };
232-
233- // ---- this test's own reading of the oracle, from scratch ---------
234- let dir = std::env::temp_dir().join(format!("ec-av1-{NAME}-{}", std::process::id()));
235- let _ = std::fs::remove_dir_all(&dir);
236- std::fs::create_dir_all(&dir).expect("scratch dir");
237- let obu = dir.join("in.obu");
238- std::fs::write(&obu, &data).expect("writing the stream");
239- let raw = dir.join("aomdec.raw");
240- let out = crate::tool_cache::cached_output_io(Command::new(aomdec_path())
241- .args(["--codec=av1", "--rawvideo", "-o"])
242- .arg(&raw)
243- .arg(&obu)
244- .stdin(Stdio::null())
245- .stdout(Stdio::piped())
246- .stderr(Stdio::piped()), None, |c| c.output())
247- .expect("aomdec failed to run");
248- assert!(
249- out.status.success(),
250- "{NAME}: the oracle aomdec refused the stream: {}",
251- String::from_utf8_lossy(&out.stderr)
252- );
253- let want = std::fs::read(&raw).expect("aomdec rawvideo output");
254- let _ = std::fs::remove_dir_all(&dir);
255- let decoded = decode_stream(&data).expect("the pinned stream decodes");
256- let ours = pack_rawvideo(&decoded, bit_depth, NAME);
257- assert_eq!(
258- ours.len(),
259- want.len(),
260- "{NAME}: the two sides differ in size"
261- );
262-
263- // The per-frame plane table, built from each decoded picture's OWN
264- // plane lengths -- the same source `pack_rawvideo` lays the bytes out
265- // from, and never a formula.
266- let mut spans: Vec<[usize; 4]> = Vec::with_capacity(decoded.len());
267- let mut capacity = [0usize; 3];
268- let mut off = 0usize;
269- for f in &decoded {
270- let (y, u, v) = (f.y.len() * bpp, f.u.len() * bpp, f.v.len() * bpp);
271- spans.push([off, off + y, off + y + u, off + y + u + v]);
272- capacity[0] += y;
273- capacity[1] += u;
274- capacity[2] += v;
275- off += y + u + v;
276- }
277- assert_eq!(off, ours.len(), "{NAME}: the plane table covers the buffer");
278-
279- // The truth, counted here with no help from the helper under test.
280- let mut truth = [0usize; 3];
281- let mut truth_exact = 0usize;
282- for s in &spans {
283- let mut frame_exact = true;
284- for (p, a, b) in [(0usize, s[0], s[1]), (1, s[1], s[2]), (2, s[2], s[3])] {
285- let n = ours[a..b]
286- .iter()
287- .zip(&want[a..b])
288- .filter(|(x, y)| x != y)
289- .count();
290- truth[p] += n;
291- frame_exact &= n == 0;
292- }
293- truth_exact += usize::from(frame_exact);
294- }
295-
296- let (wy, wu, wv, frames, exact) =
297- count_rawvideo_diffs(&data, NAME, None).expect("the two sides must be byte-comparable");
298- eprintln!(
299- "{NAME}: pinned {FILE} as wrongY={wy} wrongU={wu} wrongV={wv} over {frames} frames, \
300- {exact} exact; this test's own count {truth:?} with {truth_exact} exact frames; \
301- plane capacities {capacity:?}"
302- );
303- assert_eq!(frames, decoded.len(), "{NAME}: frame count");
304- assert_eq!(
305- [wy, wu, wv],
306- truth,
307- "{NAME}: the helper's per-plane split must equal an independent per-frame count"
308- );
309- assert_eq!(exact, truth_exact, "{NAME}: frames_exact");
310- for p in 0..3 {
311- assert!(
312- truth[p] <= capacity[p],
313- "{NAME}: plane {p} counts {} wrong bytes but holds only {}",
314- truth[p],
315- capacity[p]
316- );
317- }
318-
319- // ---- arm 2: a byte inside a LATER frame's U plane. --------------
320- // Frame 5's U plane's first byte. The old first-picture attribution
321- // has no frame-5 U at all: that byte is past every frame-0 threshold,
322- // so it landed in V.
323- let u5 = spans[5][1];
324- let (fy, fu, fv, fframes, fexact) = count_rawvideo_diffs(&data, NAME, Some(u5))
325- .expect("the two sides must be byte-comparable");
326- let flipped = [fy, fu, fv];
327- assert_eq!(fframes, frames, "{NAME}: frame count under the flip");
328- assert_eq!(
329- flipped.iter().sum::<usize>(),
330- truth.iter().sum::<usize>() + 1,
331- "{NAME}: flipping one byte inside frame 5's U plane must add exactly one wrong \
332- byte -- got {flipped:?} against this test's own count {truth:?}"
333- );
334- assert_eq!(
335- flipped[1],
336- truth[1] + 1,
337- "{NAME}: byte {u5} is inside frame 5's U plane"
338- );
339- assert_eq!(flipped[0], truth[0], "{NAME}: byte {u5} is not in luma");
340- assert_eq!(
341- flipped[2], truth[2],
342- "{NAME}: byte {u5} must NOT be attributed to V -- the first-picture attribution \
343- puts every byte past frame 0's luma in V"
344- );
345- let want_exact = if truth_exact < frames {
346- truth_exact
347- } else {
348- frames - 1
349- };
350- assert_eq!(
351- fexact, want_exact,
352- "{NAME}: one flipped byte inside frame 5 leaves frames_exact at {want_exact}"
353- );
354- }
355-
356- /// lane-av1cmpaudit2: the permanent CONTROL for the class
357- /// `comparator-that-never-reads-the-oracle`.
358- ///
359- /// The retracted predecessor lane's per-cell counter reported "0 wrong"
360- /// on 18/18 cells -- including cells that differ from `aomdec
361- /// --rawvideo` in 17658 samples -- because it packed OUR decoded samples
362- /// into a buffer and compared that buffer against the same samples.
363- /// `aomdec`'s output was written, length-checked, and never read.
364- /// Nothing about that mistake is visible from the outside: the helper's
365- /// signature, its panic text and its return type are all exactly what a
366- /// working comparator has, and no amount of reading the source of a
367- /// healthy-looking helper proves the next one is healthy.
368- ///
369- /// So the class is pinned here from the other direction.
370- /// `EC_AV1_AOMDEC` is already the crate's oracle override, so this test
371- /// points every oracle helper at a shim that runs the REAL `aomdec` and
372- /// then corrupts exactly ONE byte of whatever it wrote -- the
373- /// `--rawvideo` output and the `EC_AV1_FINAL_DUMP` frame 0 -- leaving
374- /// every other sample a genuine decode. On a pin that IS byte-exact
375- /// against the real oracle:
376- ///
377- /// 1. **arm 1, real oracle: every helper is GREEN.** Without this arm,
378- /// arm 2's red could just be a stream that was never exact.
379- /// 2. **arm 2, one-byte-wrong oracle: every helper is RED.** A helper
380- /// that stays green here is the retracted defect itself: it cannot
381- /// fail, so its green is worth nothing.
382- ///
383- /// One test, five helpers, and it goes red for the exact mistake that
384- /// was retracted. Measured over this file: the other 62 tests that
385- /// reach an oracle helper all take `lock_gate_counters()` before their
386- /// first oracle call, which is what makes the process-global
387- /// `EC_AV1_AOMDEC` safe to flip here.
388- #[test]
389- fn every_oracle_comparator_reds_on_a_one_byte_wrong_oracle() {
390- const NAME: &str = "every_oracle_comparator_reds_on_a_one_byte_wrong_oracle";
391- let _gate_lock = lock_gate_counters();
392- if !aomdec_available(NAME) {
393- return;
394- }
395- let pin = crate_pin("420_odd65x65_key.obu");
396- let stream = std::fs::read(&pin).unwrap_or_else(|e| {
397- panic!(
398- "{NAME}: the control's pin {} is missing ({e}) -- restore the committed copy",
399- pin.display()
400- )
401- });
402- assert_eq!(
403- stream_bit_depth(&stream, NAME),
404- 8,
405- "{NAME}: the control's pin must be the 8-bit cell the shim corrupts"
406- );
407- let plane_samples = {
408- let frames = decode_stream(&stream).expect("the control's pin must decode");
409- let f = &frames[0];
410- [f.y.len(), f.u.len(), f.v.len()]
411- };
412-
413- // ---- arm 1: the real oracle, every comparator green ------------
414- {
415- let obu = std::env::temp_dir().join(format!("{NAME}-arm1.obu"));
416- std::fs::write(&obu, &stream).expect("writing the pin for arm 1");
417- assert_rawvideo_matches(&obu, &stream, "oracle-control-arm1-rawvideo", 1, 8);
418- let _ = std::fs::remove_file(&obu);
419- let (frames, hidden) =
420- decode_all_frames_vs_oracle(&stream, "oracle-control-arm1-alldumps");
421- assert_eq!(
422- (frames, hidden),
423- (1, 0),
424- "{NAME}: arm 1 expects one decode-order frame and no hidden frames"
425- );
426- let (wy, wu, wv, n, exact) =
427- count_rawvideo_diffs(&stream, "oracle-control-arm1-count", None)
428- .expect("arm 1: the two sides must be byte-comparable");
429- assert_eq!(
430- (wy, wu, wv),
431- (0, 0, 0),
432- "{NAME}: arm 1 runs against the REAL oracle, so every plane must be zero"
433- );
434- assert_eq!(
435- (n, exact),
436- (1, 1),
437- "{NAME}: arm 1 expects one shown frame that is byte-identical"
438- );
439- let (differing, first) = key_frame_diffs(&stream, "oracle-control-arm1-kf");
440- assert_eq!(
441- (differing, first),
442- (0, None),
443- "{NAME}: arm 1's key frame must be byte-identical to the oracle's"
444- );
445- let [y, u, v] =
446- oracle_plane_diffs(&stream, "oracle-control-arm1-planes", plane_samples);
447- assert_eq!(
448- [y, u, v],
449- [0, 0, 0],
450- "{NAME}: arm 1 must be zero on every plane against the real oracle"
451- );
452- }
453-
454- // ---- the one-byte-wrong oracle ---------------------------------
455- let dir = std::env::temp_dir().join(format!("ec-av1-{NAME}-{}", std::process::id()));
456- let _ = std::fs::remove_dir_all(&dir);
457- std::fs::create_dir_all(&dir).expect("scratch dir");
458- let shim = dir.join("one-byte-wrong-aomdec.sh");
459- // The real oracle's path rides in a sibling file rather than inside
460- // the script, so a path with a quote or a space cannot mangle it and
461- // the script body needs no `format!` escaping at all.
462- std::fs::write(
463- dir.join("real-aomdec"),
464- aomdec_path().as_os_str().as_encoded_bytes(),
465- )
466- .expect("recording the real oracle's path for the shim");
467- // Byte 7 of both the `--rawvideo` output and the `EC_AV1_FINAL_DUMP`
468- // frame 0 is inside the Y plane, and its value is rotated by 128 so
469- // the write always changes it. Nothing else is touched: the stream,
470- // the geometry, the frame count and every other sample are a genuine
471- // `aomdec` decode.
472- let script = r#"#!/bin/sh
473-REAL=$(cat "$(dirname "$0")/real-aomdec")
474-rawvideo=0
475-out=""
476-prev=""
477-for a in "$@"; do
478- if [ "$a" = "--rawvideo" ]; then rawvideo=1; fi
479- if [ "$prev" = "-o" ]; then out="$a"; fi
480- prev="$a"
481-done
482-"$REAL" "$@" || exit $?
483-flip() {
484- [ -s "$1" ] || return 0
485- b=$(od -An -tu1 -j 7 -N 1 "$1" 2>/dev/null | tr -d ' \n')
486- [ -n "$b" ] || return 0
487- esc=$(printf '\\%03o' $(( (b + 128) % 256 )))
488- printf "$esc" | dd of="$1" bs=1 seek=7 count=1 conv=notrunc 2>/dev/null
489- return 0
490-}
491-[ "$rawvideo" = 1 ] && flip "$out"
492-[ -n "$EC_AV1_FINAL_DUMP" ] && flip "$EC_AV1_FINAL_DUMP.f0"
493-exit 0
494-"#;
495- std::fs::write(&shim, script).expect("writing the oracle shim");
496- #[cfg(unix)]
497- {
498- use std::os::unix::fs::PermissionsExt;
499- std::fs::set_permissions(&shim, std::fs::Permissions::from_mode(0o755))
500- .expect("the oracle shim must be executable");
501- }
502-
503- // ---- arm 2: same pin, oracle off by ONE byte -------------------
504- // The override is THREAD-LOCAL, so the tampered oracle is confined
505- // to this thread and no sibling test can see it; it is still cleared
506- // before any result is asserted, so a red arm cannot leave this
507- // test's own later work reading a wrong oracle.
508- let reds: [bool; 5];
509- {
510- set_oracle_path(Some(shim.clone()));
511- let panicked =
512- |f: &dyn Fn()| std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).is_err();
513- let rawvideo_red = panicked(&|| {
514- let obu = std::env::temp_dir().join(format!("{NAME}-arm2.obu"));
515- std::fs::write(&obu, &stream).expect("writing the pin for arm 2");
516- assert_rawvideo_matches(&obu, &stream, "oracle-control-arm2-rawvideo", 1, 8);
517- });
518- let _ = std::fs::remove_file(std::env::temp_dir().join(format!("{NAME}-arm2.obu")));
519- let dumps_red = panicked(&|| {
520- decode_all_frames_vs_oracle(&stream, "oracle-control-arm2-alldumps");
521- });
522- let count_red = {
523- let counted = count_rawvideo_diffs(&stream, "oracle-control-arm2-count", None)
524- .unwrap_or_else(|| {
525- panic!(
526- "{NAME}: a single flipped oracle byte must NOT change the buffer \
527- LENGTH -- returning None means the shim corrupted more than the \
528- comparison"
529- )
530- });
531- counted.0 + counted.1 + counted.2 > 0 && counted.4 < counted.3
532- };
533- let kf_red = {
534- let (differing, first) = key_frame_diffs(&stream, "oracle-control-arm2-kf");
535- differing > 0 && first.is_some()
536- };
537- let planes_red = {
538- let [y, u, v] =
539- oracle_plane_diffs(&stream, "oracle-control-arm2-planes", plane_samples);
540- y + u + v > 0
541- };
542- set_oracle_path(None);
543- let _ = std::fs::remove_dir_all(&dir);
544- reds = [rawvideo_red, dumps_red, count_red, kf_red, planes_red];
545- }
546- // One assert, naming EVERY comparator that stayed green: a partial
547- // run would report the first and hide whether the other four are
548- // covered.
549- let blind: Vec<&str> = [
550- ("assert_rawvideo_matches", reds[0]),
551- ("decode_all_frames_vs_oracle", reds[1]),
552- ("count_rawvideo_diffs", reds[2]),
553- ("key_frame_diffs", reds[3]),
554- ("oracle_plane_diffs", reds[4]),
555- ]
556- .into_iter()
557- .filter(|(_, red)| !red)
558- .map(|(what, _)| what)
559- .collect();
560- assert!(
561- blind.is_empty(),
562- "{NAME}: {} of 5 oracle comparators stayed GREEN against an oracle that is wrong \
563- by exactly one byte -- {blind:?} -- they cannot fail, so their green proves \
564- nothing (class `comparator-that-never-reads-the-oracle`)",
565- blind.len()
566- );
567- eprintln!("{NAME}: all five oracle comparators red on a one-byte-wrong oracle");
568- }
569-
570- /// lane-film10fix: the permanent CONTROL for the ffmpeg half of the class
571- /// `comparator-that-never-reads-the-oracle`.
572- ///
573- /// Its sibling above covers the five `aomdec` comparators. The `ffmpeg`
574- /// half had no such control, and it is the half the two 10-bit FILM gates
575- /// rest on: `a_10bit_128sb_film_frames_with_warp_cdef_and_interintra_...`
576- /// and `a_10bit_film_frames_with_small_side_globalmv_and_rect_warp_...`
577- /// both declare "pixel-exact" purely as
578- /// `assert_eq!(ours.<plane>, ffmpeg_decode_sequence_10bit(...).<plane>)`
579- /// over 15 and 33 shown frames. If `ffmpeg_decode_sequence_10bit` ever
580- /// stopped reading ffmpeg's stdout -- packed our own samples into the
581- /// buffer it returns, say -- both gates would report exact on a decoder
582- /// that could be arbitrarily wrong, and nothing in the crate would go
583- /// red. Reading the helper's source proves it is live TODAY; only a
584- /// deliberately wrong reference proves it can FAIL.
585- ///
586- /// So this is the same two-arm shape, pointed at ffmpeg. The shim runs the
587- /// REAL ffmpeg and then rotates ONE byte of its rawvideo stdout per
588- /// offset in a sibling file, leaving the stream, the geometry, the frame
589- /// count and every other sample a genuine decode. On a pin that IS
590- /// byte-exact against real ffmpeg:
591- ///
592- /// 1. **arm 1, real ffmpeg: every helper is GREEN.** Without this arm,
593- /// arm 2's red could just be a stream that was never exact.
594- /// 2. **arm 2, one-sample-wrong ffmpeg, PER PLANE: every helper is RED
595- /// and the red names the plane that was tampered with.** Three arms,
596- /// one per plane, because a helper that only ever compared luma would
597- /// pass the Y arm and fail U and V -- and a 10-bit film gate that
598- /// reported "exact" while ignoring chroma entirely would be exactly
599- /// the class this controls.
600- ///
601- /// The three helpers are the whole reference surface in this module:
602- /// `ffmpeg_decode_sequence` (4:2:0 8-bit), `ffmpeg_decode_gray_sequence`
603- /// (monochrome, one plane) and `ffmpeg_decode_sequence_10bit` (the
604- /// `yuv420p10le` family both film gates use). Each is driven on a pin it
605- /// is known to be exact against: the 8-bit `420_odd65x65_key.obu` for the
606- /// first, the same stream for the third's shape arithmetic, and the
607- /// monochrome recipe the mono gate already builds for the second. The
608- /// override is thread-local, so a red arm cannot leave a tampered ffmpeg
609- /// behind for a sibling test on another thread.
610- #[test]
611- fn every_ffmpeg_comparator_reds_on_a_one_sample_wrong_ffmpeg() {
612- const NAME: &str = "every_ffmpeg_comparator_reds_on_a_one_sample_wrong_ffmpeg";
613- if !have_ffmpeg() {
614- eprintln!("SKIP {NAME}: no ffmpeg");
615- return;
616- }
617- // Same mutex the oracle control takes: this test's shim is
618- // thread-local, but the SCREAM it produces must not interleave with a
619- // sibling's decode in the captured log.
620- let _gate_lock = lock_gate_counters();
621-
622- // The 4:2:0 8-bit arm. It BUILDS its stream with the same
623- // `libaom-av1` lavfi recipe the mono gate below uses rather than
624- // pinning one: `ffmpeg_decode_sequence` derives its frame size as
625- // `w*h + 2*(w*h/4)`, which is only right for EVEN dimensions -- on a
626- // 65x65 stream 4:2:0 chroma is ceil(65/2)^2 = 1089, not 4225/4 =
627- // 1056, and the helper's length assert fires (loudly, by design --
628- // see `frame_count_diagnosis`). 320x240 keeps the offsets below
629- // exact: luma 76800 samples, chroma 160x120 = 19200 each.
630- let (w, h) = (320usize, 240usize);
631- let (ys, cs) = (w * h, (w / 2) * (h / 2));
632- assert_eq!(
633- (ys, cs),
634- (76800, 19200),
635- "{NAME}: the byte offsets in this test are computed from this geometry"
636- );
637- let build_8bit = {
638- let out = crate::tool_cache::cached_output_io(Command::new(ffmpeg_path())
639- .args([
640- "-v",
641- "error",
642- "-f",
643- "lavfi",
644- "-i",
645- "testsrc2=size=320x240:rate=30:duration=1",
646- "-pix_fmt",
647- "yuv420p",
648- "-c:v",
649- "libaom-av1",
650- "-cpu-used",
651- "8",
652- "-b:v",
653- "300k",
654- "-f",
655- "obu",
656- "-",
657- ])
658- .stdin(Stdio::null())
659- .stdout(Stdio::piped())
660- .stderr(Stdio::piped()), None, |c| c.output())
661- .expect("ffmpeg failed to build the 4:2:0 8-bit arm");
662- assert!(
663- out.status.success(),
664- "{NAME}: ffmpeg could not build the 8-bit arm: {}",
665- String::from_utf8_lossy(&out.stderr)
666- );
667- out.stdout
668- };
669- assert_eq!(
670- stream_bit_depth(&build_8bit, NAME),
671- 8,
672- "{NAME}: this arm is the 8-bit cell the byte offsets below are computed for"
673- );
674- let our_8bit =
675- decode_stream(&build_8bit).expect("the 8-bit arm must decode -- arm 1 needs it exact");
676- assert!(
677- !our_8bit.is_empty(),
678- "{NAME}: the 8-bit arm decoded nothing"
679- );
680- let frames_8bit = our_8bit.len();
681-
682- // The monochrome recipe, byte-identical to the one
683- // `a_real_libaom_monochrome_key_frame_decodes_pixel_exact` builds, so
684- // the gray helper is driven on a stream that gate already proves
685- // exact. A MONOCHROME stream is also this test's 4:2:0 4:2:0-free
686- // arm: `ffmpeg_decode_gray_sequence` returns a flat luma buffer, so
687- // the one flipped offset must be attributed to Y and to nothing else.
688- let gray_stream = {
689- let out = crate::tool_cache::cached_output_io(Command::new(ffmpeg_path())
690- .args([
691- "-v",
692- "error",
693- "-f",
694- "lavfi",
695- "-i",
696- "testsrc2=size=64x64:rate=30:duration=1",
697- "-pix_fmt",
698- "gray",
699- "-c:v",
700- "libaom-av1",
701- "-cpu-used",
702- "8",
703- "-b:v",
704- "100k",
705- "-f",
706- "obu",
707- "-",
708- ])
709- .stdin(Stdio::null())
710- .stdout(Stdio::piped())
711- .stderr(Stdio::piped()), None, |c| c.output())
712- .expect("ffmpeg failed to build the monochrome arm");
713- assert!(
714- out.status.success(),
715- "{NAME}: ffmpeg could not build the monochrome arm: {}",
716- String::from_utf8_lossy(&out.stderr)
717- );
718- out.stdout
719- };
720- let our_gray = decode_stream(&gray_stream).expect("the monochrome arm must decode");
721- assert!(
722- !our_gray.is_empty(),
723- "{NAME}: the monochrome arm decoded nothing"
724- );
725- let frames_gray = our_gray.len();
726-
727- // ---- the one-sample-wrong ffmpeg shim ---------------------------
728- let dir = std::env::temp_dir().join(format!("ec-av1-{NAME}-{}", std::process::id()));
729- let _ = std::fs::remove_dir_all(&dir);
730- std::fs::create_dir_all(&dir).expect("scratch dir");
731- // The real ffmpeg's path rides in a sibling file rather than inside
732- // the script, so a path with a space or a quote cannot mangle it and
733- // the script body needs no `format!` escaping.
734- let real = if let Some(p) = std::env::var_os("EC_AV1_FFMPEG") {
735- std::path::PathBuf::from(p)
736- } else {
737- let found = Command::new("ffmpeg")
738- .arg("-version")
739- .stdout(Stdio::null())
740- .stderr(Stdio::null())
741- .status()
742- .is_ok_and(|s| s.success());
743- assert!(found, "{NAME}: no working ffmpeg on PATH to wrap");
744- // Resolve the bare name through PATH so the shim does not depend
745- // on inheriting whatever PATH the test runner had.
746- let path = std::env::var_os("PATH").unwrap_or_default();
747- std::env::split_paths(&path)
748- .map(|d| d.join("ffmpeg"))
749- .find(|p| p.is_file())
750- .expect("{NAME}: ffmpeg is on PATH but not resolvable to a file")
751- };
752- std::fs::write(dir.join("real-ffmpeg"), real.as_os_str().as_encoded_bytes())
753- .expect("recording the real ffmpeg's path for the shim");
754- // Each line of `offsets` is one byte of the rawvideo stdout to rotate
755- // by 128, so the write always changes it. Everything else -- the
756- // stream, the geometry, the frame count, every other sample -- is a
757- // genuine ffmpeg decode. stdin is inherited so the shim is a drop-in
758- // for the helpers' `run_with_stdin` call.
759- let script = r#"#!/bin/sh
760-REAL=$(cat "$(dirname "$0")/real-ffmpeg")
761-OUT=$(mktemp)
762-"$REAL" "$@" > "$OUT" || exit $?
763-while read -r o; do
764- [ -n "$o" ] || continue
765- b=$(od -An -tu1 -j "$o" -N 1 "$OUT" 2>/dev/null | tr -d ' \n')
766- [ -n "$b" ] || continue
767- esc=$(printf '\\%03o' $(( (b + 128) % 256 )))
768- printf "$esc" | dd of="$OUT" bs=1 seek="$o" count=1 conv=notrunc 2>/dev/null
769-done < "$(dirname "$0")/offsets"
770-cat "$OUT"
771-rm -f "$OUT"
772-exit 0
773-"#;
774- let shim = dir.join("one-sample-wrong-ffmpeg.sh");
775- std::fs::write(&shim, script).expect("writing the ffmpeg shim");
776- #[cfg(unix)]
777- {
778- use std::os::unix::fs::PermissionsExt;
779- std::fs::set_permissions(&shim, std::fs::Permissions::from_mode(0o755))
780- .expect("the ffmpeg shim must be executable");
781- }
782- let set_offsets = |bytes: &[usize]| {
783- let body: String = bytes
784- .iter()
785- .map(|b| format!("{b}\n"))
786- .collect::<Vec<_>>()
787- .concat();
788- std::fs::write(dir.join("offsets"), body).expect("writing the offsets file");
789- };
790- // A comparator that cannot report a difference is worse than none, so
791- // each arm is scored as a COUNT of differing samples, not as a panic.
792- let count8 = |theirs: &[Pic]| -> [usize; 3] {
793- let mut wrong = [0usize; 3];
794- for (plane, (x, y)) in [
795- (0usize, (&our_8bit[0].y, &theirs[0].y)),
796- (1, (&our_8bit[0].u, &theirs[0].u)),
797- (2, (&our_8bit[0].v, &theirs[0].v)),
798- ] {
799- wrong[plane] = x.iter().zip(y).filter(|(a, b)| a != b).count();
800- }
801- wrong
802- };
803-
804- // The 10-bit FILM pin, and the comparator both charter-named film
805- // gates rest on. Driven on the real stream rather than a synthetic
806- // one: `ffmpeg_decode_sequence_10bit` is the only reference helper
807- // with a per-plane split, so it is the one that could silently lose a
808- // plane. 1920x792 at 10 bits: luma 1920*792*2 bytes per frame, chroma
809- // 960*396*2.
810- let film = std::fs::read(crate_pin("reelc_sb128_inter_witness.obu")).unwrap_or_else(|e| {
811- panic!(
812- "{NAME}: the 10-bit film pin reelc_sb128_inter_witness.obu is missing ({e}) -- \
813- restore the committed copy"
814- )
815- });
816- assert_eq!(
817- stream_bit_depth(&film, NAME),
818- 10,
819- "{NAME}: this arm is the 10-bit cell the byte offsets below are computed for"
820- );
821- let our_10bit =
822- decode_stream(&film).expect("the 10-bit film pin must decode -- arm 1 needs it exact");
823- let (fw, fh) = (1920usize, 792usize);
824- let film_frames = our_10bit.len();
825- let (fys, fcs) = (fw * fh * 2, (fw / 2) * (fh / 2) * 2);
826- let count10 = |theirs: &[Pic]| -> [usize; 3] {
827- let mut wrong = [0usize; 3];
828- for (a, b) in our_10bit.iter().zip(theirs) {
829- for (plane, (x, y)) in
830- [(0usize, (&a.y, &b.y)), (1, (&a.u, &b.u)), (2, (&a.v, &b.v))]
831- {
832- wrong[plane] += x.iter().zip(y).filter(|(p, q)| p != q).count();
833- }
834- }
835- wrong
836- };
837- let count_gray = |theirs: &[u8]| -> usize {
838- our_gray[0]
839- .y
840- .iter()
841- .zip(theirs)
842- .filter(|(a, b)| **a != u16::from(**b))
843- .count()
844- };
845-
846- // ---- arm 1: the real ffmpeg, every comparator GREEN ------------
847- {
848- set_offsets(&[]);
849- set_ffmpeg_path(None);
850- let theirs = ffmpeg_decode_sequence(&build_8bit, w, h, frames_8bit);
851- assert_eq!(
852- count8(&theirs),
853- [0, 0, 0],
854- "{NAME}: arm 1 runs against the REAL ffmpeg, so every plane must be zero -- if \
855- this is red the stream is not the byte-exact pin this control needs"
856- );
857- let their_gray = ffmpeg_decode_gray_sequence(&gray_stream, 64, 64, frames_gray);
858- assert_eq!(
859- count_gray(&their_gray),
860- 0,
861- "{NAME}: arm 1's monochrome plane must be zero against the real ffmpeg"
862- );
863- // arm 1's 10-bit half: the film pin is byte-exact against real
864- // ffmpeg on every plane of every shown frame -- that is exactly
865- // what `a_10bit_128sb_film_frames_with_warp_cdef_and_interintra_...`
866- // asserts -- so this is the cell the two charter-named film gates
867- // claim.
868- let their_10bit = ffmpeg_decode_sequence_10bit(&film, fw, fh, film_frames);
869- assert_eq!(
870- count10(&their_10bit),
871- [0, 0, 0],
872- "{NAME}: arm 1's 10-bit film pin must be zero on every plane against the real \
873- ffmpeg -- if this is red the control's pin is not the byte-exact stream it needs"
874- );
875- }
876-
877- // ---- arm 2: one sample wrong, PER PLANE -------------------------
878- // The shim is thread-local, so the tampered reference is confined to
879- // this thread; it is cleared before anything is asserted, so a red arm
880- // cannot leave this test's own later work reading a wrong ffmpeg.
881- let mut blind: Vec<String> = Vec::new();
882- {
883- set_ffmpeg_path(Some(shim.clone()));
884- for (plane, (_name, base)) in [("Y", 0usize), ("U", ys), ("V", ys + cs)]
885- .into_iter()
886- .enumerate()
887- {
888- // Byte 1000 of the named plane: inside the 4:2:0 8-bit pin's
889- // luma (4225), inside its chroma (1024), or past both.
890- set_offsets(&[base + 1000]);
891- let theirs = ffmpeg_decode_sequence(&build_8bit, w, h, frames_8bit);
892- let got = count8(&theirs);
893- let want = [0usize, 0, 0];
894- let mut expected = want;
895- expected[plane] = 1;
896- if got != expected {
897- blind.push(format!(
898- "ffmpeg_decode_sequence {plane} arm: counted {got:?}, expected \
899- {expected:?} (exactly the one tampered sample)"
900- ));
901- }
902- }
903- // The 10-bit helper, per plane, on the 10-bit FILM pin. This is the
904- // arm that matters for the charter: both
905- // `a_10bit_128sb_film_frames_with_warp_cdef_and_interintra_...`
906- // and
907- // `a_10bit_film_frames_with_small_side_globalmv_and_rect_warp_...`
908- // declare "pixel-exact on every plane" using nothing but this
909- // helper's output. A helper that dropped U or V would leave both
910- // gates green while chroma went unchecked for 15 and 33 frames.
911- for (plane, (_name, base)) in [("Y", 0usize), ("U", fys), ("V", fys + fcs)]
912- .into_iter()
913- .enumerate()
914- {
915- // Sample 1000 of the named plane, two bytes per sample.
916- set_offsets(&[base + 2000]);
917- let theirs = ffmpeg_decode_sequence_10bit(&film, fw, fh, film_frames);
918- let got = count10(&theirs);
919- let mut expected = [0usize, 0, 0];
920- expected[plane] = 1;
921- if got != expected {
922- blind.push(format!(
923- "ffmpeg_decode_sequence_10bit {plane} arm: counted {got:?}, expected \
924- {expected:?} (exactly the one tampered sample)"
925- ));
926- }
927- }
928- // The monochrome helper: one plane, so the single flipped offset
929- // must show up as luma and nothing else can absorb it.
930- set_offsets(&[1000]);
931- let their_gray = ffmpeg_decode_gray_sequence(&gray_stream, 64, 64, frames_gray);
932- if count_gray(&their_gray) != 1 {
933- blind.push(format!(
934- "ffmpeg_decode_gray_sequence arm: counted {} differing luma samples, expected \
935- exactly 1",
936- count_gray(&their_gray)
937- ));
938- }
939- set_ffmpeg_path(None);
940- }
941- let _ = std::fs::remove_dir_all(&dir);
942- // One assert, naming EVERY helper that failed to notice: a partial run
943- // would report the first and hide whether the others are covered.
944- assert!(
945- blind.is_empty(),
946- "{NAME}: {} of 7 ffmpeg comparator arms stayed GREEN against an ffmpeg that is wrong \
947- by exactly one sample -- {blind:#?} -- they cannot fail, so their green proves \
948- nothing (class `comparator-that-never-reads-the-oracle`)",
949- blind.len()
950- );
951- eprintln!(
952- "{NAME}: ffmpeg_decode_sequence red on a one-sample-wrong Y, U and V separately; \
953- ffmpeg_decode_gray_sequence red on one wrong luma sample; \
954- ffmpeg_decode_sequence_10bit red on a one-sample-wrong Y, U and V of the 10-bit \
955- film pin"
956- );
957- }
958-
959- /// lane-av1422chrtx: the odd-frame-HEIGHT 4:2:0 witness, pinned and now
960- /// EXACT (lane-av1422anom had pinned it as a ratchet on its own defect).
961- ///
962- /// This is NOT a 4:2:2 cell and needs no bypass -- it is ordinary 4:2:0,
963- /// reachable by any user. lane-av1422anom pinned it as a RATCHET asserting
964- /// its own measured defect `(0, 200, 17658)`, and said whoever fixed it
965- /// must flip that to exactness. That is done, and the flip is the
966- /// deliverable:
967- ///
968- /// the defect was a chroma `tx_type`, not a geometry. libaom's
969- /// `av1_get_ext_tx_set_type` (`blockd.h`) resolves a **32-point** chroma
970- /// unit to `EXT_TX_SET_DCT_IDTX` when the block `is_inter` -- so an
971- /// Intra-Block-Copy block whose luma coded `IDTX` runs the identity
972- /// transform on its chroma. `read_plane`'s `side >= 32` clamp forced
973- /// `DCT_DCT` there (its `DCT_DCT` cap is really libaom's
974- /// `txsize_sqr_up_map[tx_size] > TX_32X32`, i.e. 64 and up), so the
975- /// residual was a 32-point IDCT where libaom's was a plain copy of the
976- /// dequantized coefficients `>>2`. The wrong samples sat in one 64x64
977- /// IBC block's 32x32 chroma unit at chroma (128,96) on frame 0, and
978- /// propagated from there through the inter frames.
979- ///
980- /// `the_counting_oracle_diff_detects_one_flipped_oracle_byte` is the
981- /// non-vacuity control that keeps the `0` above worth anything.
982- #[test]
983- fn the_pinned_420_oddheight_witness_is_pinned_and_decodes_byte_exact() {
984- const NAME: &str = "the_pinned_420_oddheight_witness_is_pinned_and_decodes_byte_exact";
985- // lane-av1cmpaudit2: same mutex as every other oracle gate.
986- let _gate_lock = lock_gate_counters();
987- const FILE: &str = "420_oddheight_320x232.obu";
988- const BYTES: usize = 15773;
989- // sha256 6832c3cd867f5fc491b45fd67f77c38453db0ca6d461e7d225e6276f4d0784c8,
990- // recorded in `lanes/av1422anom.report.md`. The tree pins fixture
991- // identity by fnv1a64, asserted below. A `const SHA256` compared
992- // against itself would be a tautology -- the exact bug this lane
993- // exists to kill -- so it is not written.
994- const FNV1A64: u64 = 0x37877f15307c3b;
995- let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
996- .join("fixtures")
997- .join(FILE);
998- let data = std::fs::read(&path)
999- .unwrap_or_else(|e| panic!("{NAME}: pinned witness {FILE} is missing ({e})"));
1000- assert_eq!(data.len(), BYTES, "{NAME}: {FILE} size drifted");
1001- assert_eq!(fnv1a64(&data), FNV1A64, "{NAME}: {FILE} bytes drifted");
1002- let (wy, wu, wv, frames, exact) =
1003- count_rawvideo_diffs(&data, NAME, None).expect("the two sides must be byte-comparable");
1004- assert_eq!(
1005- (wy, wu, wv),
1006- (0, 0, 0),
1007- "{NAME}: the pinned 320x232 witness must decode byte-exactly against \
1008- `aomdec --rawvideo` on every plane. It was a RATCHET asserting its own \
1009- measured defect (0, 200, 17658); lane-av1422chrtx flipped it to exactness \
1010- when the 32-point INTER chroma `tx_type` (EXT_TX_SET_DCT_IDTX, not \
1011- EXT_TX_SET_DCTONLY) was fixed. Any non-zero value here is a regression -- \
1012- name it in the report."
1013- );
1014- assert_eq!(frames, 16, "{NAME}: shown frame count");
1015- assert_eq!(
1016- exact, frames,
1017- "{NAME}: every shown frame must be byte-exact"
1018- );
1019- }
1020-
1021- /// lane-av1oddheightfork3: the 320x236 cell this lane CLOSED, as a
1022- /// permanent BYTE-EXACTNESS gate against the live oracle -- not a route
1023- /// counter, not a source scan. It compares our decoded samples with
1024- /// `aomdec --rawvideo`'s own bytes plane by plane, and asserts every
1025- /// frame is byte-exact.
1026- ///
1027- /// **The defect it pins.** Before the fix this cell measured
1028- /// `Y 234349 / U 56957 / V 52981, 0 of 16 frames exact` -- reproduced on
1029- /// this lane's own tree by reverting the fix, matching
1030- /// `lanes/av1oddluma.report.md` and `lanes/av1cmpframe.report.md` digit
1031- /// for digit. The first divergent read is the `txfm_partition` symbol of
1032- /// the INTRABC 8x16 block at mi(44,60): our `TXFM_CONTEXT` grid held the
1033- /// BLOCK's own `16` in `left_txfm[44]` where libaom holds the split
1034- /// leaf's `8` (the operand pair is printed by the oracle rung
1035- /// `EC_VARTXCTX`, `scripts/instrument-aom-oracle.sh`), so `ctx` was 12
1036- /// against libaom's 13 and `is_split` 0 against 1.
1037- ///
1038- /// **Non-vacuity.** `the_counting_oracle_diff_detects_one_flipped_oracle_byte`
1039- /// is the comparator control and does not depend on any witness
1040- /// diverging; the mutation proof that this gate BITES the defect it
1041- /// names is in `lanes/av1oddheightfork3.report.md` (revert the
1042- /// `fill_lf_grid_rect_after_vartx` call sites -> this test reds BY NAME
1043- /// with the numbers above).
1044- #[test]
1045- fn the_pinned_420_oddheight_320x236_witness_decodes_byte_exact() {
1046- const NAME: &str = "the_pinned_420_oddheight_320x236_witness_decodes_byte_exact";
1047- let _gate_lock = lock_gate_counters();
1048- const FILE: &str = "420_oddheight_320x236.obu";
1049- const BYTES: usize = 16562;
1050- // sha256 84e4d1ab56620af1c5b78e1aa3d2d67496a492f2e127198c82dd1d68b01c6200.
1051- // Identity is pinned by fnv1a64 (the same value
1052- // `the_counting_oracle_diff_attributes_planes_per_frame` asserts) --
1053- // a `const SHA256` compared against itself would be the tautology
1054- // this lane exists to kill.
1055- const FNV1A64: u64 = 521889434652397870;
1056- let data = crate_pin("420_oddheight_320x236.obu");
1057- let data = std::fs::read(&data)
1058- .unwrap_or_else(|e| panic!("{NAME}: the committed pin {FILE} is missing ({e})"));
1059- assert_eq!(data.len(), BYTES, "{NAME}: {FILE} size drifted");
1060- assert_eq!(fnv1a64(&data), FNV1A64, "{NAME}: {FILE} bytes drifted");
1061- let (wy, wu, wv, frames, exact) =
1062- count_rawvideo_diffs(&data, NAME, None).expect("the two sides must be byte-comparable");
1063- assert_eq!(
1064- (wy, wu, wv),
1065- (0, 0, 0),
1066- "{NAME}: the pinned 320x236 cell must decode byte-exactly against \
1067- `aomdec --rawvideo` on every plane. It measured \
1068- (234349, 56957, 52981) with 0 of 16 frames exact until \
1069- lane-av1oddheightfork3 fixed the TXFM_CONTEXT whole-block \
1070- publish that overwrote a var-tx tree's per-leaf sizes. Any \
1071- non-zero value here is a regression -- name it in the report."
1072- );
1073- assert_eq!(frames, 16, "{NAME}: shown frame count");
1074- assert_eq!(
1075- exact, frames,
1076- "{NAME}: every shown frame must be byte-exact"
1077- );
1078- }
1079-
1080- /// The repo's first hidden-frame pixel gate. Every other aomenc gate
1081- /// here compares `decode_stream`'s output against `ffmpeg -f obu`, and
1082- /// both sides emit SHOWN frames only -- so an alt-ref frame that is
1083- /// decoded, stored into a reference slot and never displayed was, until
1084- /// this gate, never compared to anything (class
1085- /// gate-blind-to-hidden-frames). His films are aomenc-encoded with the
1086- /// default `--lag-in-frames`, so they are full of exactly these frames.
1087- ///
1088- /// `--auto-alt-ref=1 --lag-in-frames=25` on moving content makes aomenc
1089- /// build alt-refs; `--arnr-maxframes=0` is load-bearing -- with libaom's
1090- /// temporal filter on, this fixture's alt-ref candidates get filtered
1091- /// away and the encoder emits ZERO hidden frames (measured: 0 hidden
1092- /// with the filter on, 3 with it off), which would have made the gate
1093- /// vacuous. The `hidden >= 2` assertion is hard, on both bit depths, so
1094- /// a recipe that stops producing hidden frames fails rather than skips.
1095- #[test]
1096- fn a_real_aomenc_altref_sequence_hidden_frames_decode_pixel_exact() {
1097- const NAME: &str = "a_real_aomenc_altref_sequence_hidden_frames_decode_pixel_exact";
1098- let _gate_lock = lock_gate_counters();
1099- if !have_ffmpeg() {
1100- eprintln!("SKIP {NAME}: no ffmpeg");
1101- return;
1102- }
1103- if !have_aomenc() {
1104- eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
1105- return;
1106- }
1107- for bit_depth in [8u32, 10u32] {
1108- let (width, height, frames) = (64usize, 64usize, 40usize);
1109- let duration = frames as f64 / 25.0;
1110- let source = format!("testsrc2=size={width}x{height}:duration={duration}:rate=25");
1111- let pix_fmt = if bit_depth == 10 {
1112- "yuv420p10le"
1113- } else {
1114- "yuv420p"
1115- };
1116- let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1117- .args([
1118- "-v",
1119- "error",
1120- "-f",
1121- "lavfi",
1122- "-i",
1123- &source,
1124- "-t",
1125- &duration.to_string(),
1126- "-pix_fmt",
1127- pix_fmt,
1128- "-strict",
1129- "-1",
1130- "-f",
1131- "yuv4mpegpipe",
1132- "-",
1133- ])
1134- .stdin(Stdio::null())
1135- .stdout(Stdio::piped())
1136- .stderr(Stdio::piped()), None, |c| c.output())
1137- .expect("ffmpeg failed to run");
1138- assert!(
1139- y4m.status.success(),
1140- "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
1141- String::from_utf8_lossy(&y4m.stderr)
1142- );
1143- let depth_arg = format!("--bit-depth={bit_depth}");
1144- let input_depth_arg = format!("--input-bit-depth={bit_depth}");
1145- let out = run_with_stdin(
1146- Command::new(aomenc_path()).args([
1147- // lane-defon r1: the repo's only gate that decodes hidden
1148- // frames is also the only place a FORWARD KEYFRAME can be
1149- // proven -- a KEY frame with `show_frame == 0`, which is
1150- // exactly the shape this gate already compares in decode
1151- // order. On-values go before the base list (aomenc keeps
1152- // the FIRST occurrence of a repeated flag).
1153- "--enable-fwd-kf=1",
1154- "--fwd-kf-dist=8",
1155- "--codec=av1",
1156- "--passes=1",
1157- "--end-usage=q",
1158- "--cq-level=45",
1159- "--cpu-used=0",
1160- "--threads=1",
1161- "--row-mt=0",
1162- "--kf-max-dist=1000",
1163- "--enable-order-hint=1",
1164- "--auto-alt-ref=1",
1165- "--lag-in-frames=25",
1166- "--arnr-maxframes=0",
1167- &depth_arg,
1168- &input_depth_arg,
1169- // The same tool set every sibling inter gate pins -- the
1170- // open capability gaps (rect/AB partitions, warped/OBMC,
1171- // masked compound, palette, ...) are other lanes' work;
1172- // this gate is about hidden frames, not about them.
1173- "--enable-warped-motion=0",
1174- // OBMC stays off HERE (this gate is about hidden frames);
1175- // the tool's own coverage is the `obmc*` gates and, on a
1176- // 16x8/8x16 leaf, the `--enable-obmc=1` arm of
1177- // `..._with_a_16_level_rect_leaf_...` (lane-inter4 r4).
1178- "--enable-obmc=0",
1179- "--enable-masked-comp=0",
1180- "--enable-interintra-comp=0",
1181- "--enable-onesided-comp=0",
1182- "--enable-interintra-wedge=0",
1183- "--enable-smooth-interintra=0",
1184- "--enable-rect-partitions=0",
1185- "--enable-ab-partitions=0",
1186- "--enable-1to4-partitions=0",
1187- "--enable-filter-intra=0",
1188- "--enable-smooth-intra=0",
1189- "--enable-paeth-intra=0",
1190- "--enable-directional-intra=0",
1191- "--enable-angle-delta=0",
1192- "--enable-tx-size-search=0",
1193- "--enable-cdef=0",
1194- "--enable-restoration=0",
1195- "--max-partition-size=32",
1196- "--min-partition-size=32",
1197- "--enable-palette=0",
1198- "--enable-intrabc=0",
1199- "--enable-cfl-intra=0",
1200- "--enable-ref-frame-mvs=0",
1201- "--obu",
1202- "-o",
1203- "-",
1204- "-",
1205- ]),
1206- &y4m.stdout,
1207- );
1208- assert!(
1209- out.status.success(),
1210- "{NAME}: aomenc refused the {bit_depth}-bit fixture: {}",
1211- String::from_utf8_lossy(&out.stderr)
1212- );
1213- let stream = out.stdout;
1214- let fwd_kf_before = crate::decode::fwd_kf_hits();
1215- let (total, hidden) =
1216- decode_all_frames_vs_oracle(&stream, &format!("altref-hidden-{bit_depth}bit"));
1217- let fwd_kf = crate::decode::fwd_kf_hits() - fwd_kf_before;
1218- assert!(
1219- hidden >= 2,
1220- "{NAME}: the {bit_depth}-bit recipe produced only {hidden} hidden frame(s) of \
1221- {total} decoded -- the gate would be vacuous (class \
1222- gate-blind-to-hidden-frames)"
1223- );
1224- // lane-defon r1: `--enable-fwd-kf=1` is spelled on this recipe, so
1225- // a KEY frame with `show_frame == 0` must actually have been
1226- // decoded -- otherwise the on-value proves nothing.
1227- assert!(
1228- fwd_kf > 0,
1229- "{NAME}: the {bit_depth}-bit recipe decoded {total} frames ({hidden} hidden) but \
1230- zero forward keyframes -- --enable-fwd-kf=1 --fwd-kf-dist=8 never reached the \
1231- bitstream"
1232- );
1233- eprintln!(
1234- "{NAME} {bit_depth}-bit: {total} frames decoded, {hidden} hidden, {fwd_kf} \
1235- forward keyframes, all pixel-exact vs the oracle in decode order"
1236- );
1237- }
1238- }
1239-
1240- /// A real `aomenc` filter-intra fixture: every other intra mode disabled
1241- /// (smooth/paeth/directional/angle-delta) and
1242- /// `--max-partition-size=32` (past which `av1_filter_intra_allowed_bsize`'s
1243- /// <=32x32 bound means `use_filter_intra` never reads at all, spec
1244- /// 5.11.14), so the only way this frame codes is `DC_PRED` with filter
1245- /// intra on top -- `--loopfilter-control=0` is required too: this
1246- /// decoder has no in-loop deblocking filter at all, and libaom's default
1247- /// (on) smooths every block-boundary column, which first looked like a
1248- /// filter-intra math bug (mismatches straddling the 32-pixel block
1249- /// seam) until the recipe without it round-tripped byte-exact.
1250- ///
1251- /// lane-av1skipfix: the attempt-loop shape this gate's single recipe
1252- /// lacked. It sweeps (seed, cq) and REQUIRES at least one attempt to both
1253- /// decode and read `use_filter_intra`: a decode error on EVERY attempt is
1254- /// a hard failure carrying the refusal texts, not a printed SKIP, and an
1255- /// attempt that decodes without the symbol firing is still pixel-compared
1256- /// (class `gate-skips-on-its-own-failure`). MEASURED 2026-09-29 on
1257- /// `a21f3680`: seed 42 cq 40 and seed 43 cq 40 read the symbol 3x each,
1258- /// pixel-exact, while seed 44 cq 45 and seed 45 cq 30 decode WITHOUT it --
1259- /// so the one fixed recipe really did carry the whole gate.
1260- ///
1261- /// The per-attempt decode error the old single recipe SKIPped on is
1262- /// `screen_content_tools_determination` (libaom `encoder_utils.c`): a real
1263- /// internal trial-encode/PSNR comparison, not a flag this CLI exposes a
1264- /// knob for -- on this flat gradient fixture it lands on
1265- /// `allow_screen_content_tools=0` most runs but occasionally trips over
1266- /// its 0.9 dB threshold the other way even with palette/intrabc both
1267- /// disabled. That is a genuine separate gap (`decode_stream` never reads
1268- /// `intrabc`/`palette_mode_info`), so it is a NAMED REFUSAL counted per
1269- /// attempt, never a silent skip and never a pass.
1270- #[test]
1271- fn a_real_aomenc_filter_intra_stream_decodes_pixel_exact() {
1272- const NAME: &str = "a_real_aomenc_filter_intra_stream_decodes_pixel_exact";
1273- let _gate_lock = lock_gate_counters();
1274- if !have_ffmpeg() {
1275- eprintln!("SKIP {NAME}: no ffmpeg");
1276- return;
1277- }
1278- if !have_aomenc() {
1279- eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
1280- return;
1281- }
1282- let (width, height) = (64usize, 64usize);
1283- // Recipe-search hooks: with the encoder pinned to one thread the stream
1284- // is a deterministic function of (seed, cq), so a firing recipe can be
1285- // searched for without a rebuild. These pin attempt 0 for a bisect; the
1286- // sweep walks the same axes regardless.
1287- let fi_seed: u32 = std::env::var("EC_FI_SEED")
1288- .ok()
1289- .and_then(|v| v.parse().ok())
1290- .unwrap_or(42);
1291- let fi_cq: u32 = std::env::var("EC_FI_CQ")
1292- .ok()
1293- .and_then(|v| v.parse().ok())
1294- .unwrap_or(40);
1295- // Two seeds x three quantisers, so "every attempt refused" and "no
1296- // attempt ever read `use_filter_intra`" are distinguishable failures
1297- // rather than one unlucky recipe.
1298- const CQS: [u32; 3] = [40, 35, 30];
1299- let mut refusals = Vec::new();
1300- let mut counted_exact = 0u32;
1301- let mut uncounted_exact = 0u32;
1302- 'attempts: for round in 0..2u32 {
1303- for (i, &walked) in CQS.iter().enumerate() {
1304- let seed = fi_seed + round;
1305- let cq = if round == 0 && i == 0 { fi_cq } else { walked };
1306- let source = gradients_source(seed, width, height, "duration=0.04:rate=25");
1307- let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1308- .args([
1309- "-v",
1310- "error",
1311- "-f",
1312- "lavfi",
1313- "-i",
1314- &source,
1315- "-pix_fmt",
1316- "yuv420p",
1317- "-f",
1318- "yuv4mpegpipe",
1319- "-",
1320- ])
1321- .stdin(Stdio::null())
1322- .stdout(Stdio::piped())
1323- .stderr(Stdio::piped()), None, |c| c.output())
1324- .expect("ffmpeg failed to run");
1325- assert!(
1326- y4m.status.success(),
1327- "ffmpeg refused to generate the y4m fixture: {}",
1328- String::from_utf8_lossy(&y4m.stderr)
1329- );
1330- let cq_arg = format!("--cq-level={cq}");
1331- let out = run_with_stdin(
1332- Command::new(aomenc_path()).args([
1333- "--codec=av1",
1334- "--passes=1",
1335- "--end-usage=q",
1336- &cq_arg,
1337- "--cpu-used=0",
1338- // Every sibling gate pins these; this one did not, and a
1339- // multi-threaded aomenc is not deterministic, so each run
1340- // encoded a slightly different stream and the gate flaked
1341- // against whichever features that run happened to pick.
1342- // Pinning them makes seed 42 mean one stream (class
1343- // `parallel-flake-is-attempt-selection`).
1344- "--threads=1",
1345- "--row-mt=0",
1346- "--enable-filter-intra=1",
1347- "--enable-smooth-intra=0",
1348- "--enable-paeth-intra=0",
1349- "--enable-directional-intra=0",
1350- "--enable-angle-delta=0",
1351- "--enable-tx-size-search=0",
1352- "--enable-cdef=0",
1353- "--max-partition-size=32",
1354- "--loopfilter-control=0",
1355- "--enable-palette=0",
1356- "--enable-intrabc=0",
1357- "--obu",
1358- "-o",
1359- "-",
1360- "-",
1361- ]),
1362- &y4m.stdout,
1363- );
1364- assert!(
1365- out.status.success(),
1366- "{NAME}: aomenc refused the seed {seed} cq {cq} fixture: {}",
1367- String::from_utf8_lossy(&out.stderr)
1368- );
1369- let stream = out.stdout;
1370- let before = decode::filter_intra_hits();
1371- let frames = match decode_stream(&stream) {
1372- Ok(frames) => frames,
1373- Err(e) => {
1374- refusals.push(format!("seed {seed} cq {cq}: {e}"));
1375- continue;
1376- }
1377- };
1378- // A decode that succeeded is ALWAYS pixel-compared; the hit
1379- // counter only decides whether the attempt counts as firing
1380- // (class `counter-from-refused-stream`).
1381- let counted = decode::filter_intra_hits() != before;
1382- if counted {
1383- counted_exact += 1;
1384- } else {
1385- uncounted_exact += 1;
1386- }
1387- let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
1388- assert_eq!(
1389- frames[0].y, ffmpeg_frames[0].y,
1390- "luma vs ffmpeg (seed {seed} cq {cq}, use_filter_intra fired: {counted})"
1391- );
1392- assert_eq!(
1393- frames[0].u, ffmpeg_frames[0].u,
1394- "U vs ffmpeg (seed {seed} cq {cq}, use_filter_intra fired: {counted})"
1395- );
1396- assert_eq!(
1397- frames[0].v, ffmpeg_frames[0].v,
1398- "V vs ffmpeg (seed {seed} cq {cq}, use_filter_intra fired: {counted})"
1399- );
1400- if counted_exact >= 2 {
1401- break 'attempts;
1402- }
1403- }
1404- }
1405- gate_buckets(NAME, counted_exact, uncounted_exact, refusals.len());
1406- assert!(
1407- counted_exact > 0,
1408- "{NAME}: none of {} attempts decoded a stream that read use_filter_intra -- the \
1409- gate would prove nothing (class gate-blind-to-feature):\n{}",
1410- CQS.len() * 2,
1411- refusals.join("\n")
1412- );
1413- }
1414-
1415- /// A real `aomenc` palette-Y fixture (lane-palette r3): `smptebars`
1416- /// (SMPTE colour bars -- a handful of large flat luma regions, exactly
1417- /// the "flat, few-colour, repetitive" content `av1_choose_palette_map`'s
1418- /// RD trial rewards) with `hue=s=0` to flatten chroma to one constant
1419- /// value, so `DC_PRED` already nails every chroma block with zero
1420- /// residual and the encoder's own RD never has a reason to spend bits on
1421- /// a *UV* palette too (a real symbol this decoder still refuses --
1422- /// lane-palette r3's own scope is Y only). `smptebars` has no seed to
1423- /// vary, so the fixture is deterministic by construction; hashed twice
1424- /// below to prove it rather than assert it. `--enable-rect-partitions=0`
1425- /// / `-ab-` / `-1to4-` keep every intra block square, sidestepping the
1426- /// rect-strip screen-content refusal at `read_intra_mode_rect`
1427- /// (decode.rs ~2226) -- that refusal is this lane's own next milestone,
1428- /// not this gate's. `--sb-size=64` and `--threads=1 --row-mt=0` are the
1429- /// sibling-lane facts this charter paid for: a single 64x64 frame is one
1430- /// superblock either way, but pinning them keeps the recipe identical to
1431- /// every other gate in this file. HARD-asserts
1432- /// [`decode::palette_hits`] moved -- a stream that never reads a real
1433- /// palette block would refuse (or not) by construction without proving
1434- /// this milestone at all.
1435- ///
1436- /// lane-palette r4/r6/r7: r3/r4 found that this fixture's reconstructed
1437- /// pixels did not match ffmpeg's decode of the same bytes even though
1438- /// every symbol read by `decode_color_index_map` checked line-for-line
1439- /// against the oracle and matched. r6's range trace (`compare-range-not-tell`)
1440- /// pinned the real cause: `decode_color_index_map` was called from the
1441- /// wrong syntax position -- inline right after the Y colours, instead of
1442- /// after the whole mode-info read (UV palette mode_info + `filter_intra`,
1443- /// `av1_visit_palette`'s real call order). r7 ported the UV palette
1444- /// mode_info read and moved the colour-index-map decode after
1445- /// `filter_intra`; this gate now asserts a real pixel match instead of
1446- /// the old named refusal.
1447- #[test]
1448- fn a_real_aomenc_stream_with_palette_y_decodes_pixel_exact() {
1449- const NAME: &str = "a_real_aomenc_stream_with_palette_y_decodes_pixel_exact";
1450- if !have_ffmpeg() {
1451- eprintln!("SKIP {NAME}: no ffmpeg");
1452- return;
1453- }
1454- if !have_aomenc() {
1455- eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
1456- return;
1457- }
1458- let source = "smptebars=size=64x64:rate=25";
1459- fn render(source: &str) -> Vec<u8> {
1460- crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1461- .args([
1462- "-v",
1463- "error",
1464- "-f",
1465- "lavfi",
1466- "-i",
1467- source,
1468- "-vf",
1469- "hue=s=0",
1470- "-pix_fmt",
1471- "yuv420p",
1472- "-t",
1473- "0.04",
1474- "-f",
1475- "yuv4mpegpipe",
1476- "-",
1477- ])
1478- .stdin(Stdio::null())
1479- .stdout(Stdio::piped())
1480- .stderr(Stdio::piped()), None, |c| c.output())
1481- .expect("ffmpeg failed to run")
1482- .stdout
1483- }
1484- let y4m_a = render(source);
1485- let y4m_b = render(source);
1486- assert_eq!(
1487- y4m_a, y4m_b,
1488- "smptebars must render byte-identical across two runs"
1489- );
1490- let y4m = y4m_a;
1491- let out = run_with_stdin(
1492- Command::new(aomenc_path()).args([
1493- "--codec=av1",
1494- "--passes=1",
1495- "--end-usage=q",
1496- "--cq-level=30",
1497- "--cpu-used=0",
1498- "--threads=1",
1499- "--row-mt=0",
1500- "--sb-size=64",
1501- "--tune-content=screen",
1502- "--enable-palette=1",
1503- "--enable-intrabc=0",
1504- "--enable-rect-partitions=0",
1505- "--enable-ab-partitions=0",
1506- "--enable-1to4-partitions=0",
1507- "--min-partition-size=32",
1508- "--max-partition-size=32",
1509- "--enable-filter-intra=0",
1510- "--enable-smooth-intra=0",
1511- "--enable-paeth-intra=0",
1512- "--enable-directional-intra=0",
1513- "--enable-angle-delta=0",
1514- "--enable-cfl-intra=0",
1515- "--enable-cdef=0",
1516- "--enable-restoration=0",
1517- "--enable-tx-size-search=0",
1518- "--loopfilter-control=0",
1519- "--obu",
1520- "-o",
1521- "-",
1522- "-",
1523- ]),
1524- &y4m,
1525- );
1526- assert!(
1527- out.status.success(),
1528- "aomenc refused the fixture: {}",
1529- String::from_utf8_lossy(&out.stderr)
1530- );
1531- let stream = out.stdout;
1532- let before = decode::palette_hits();
1533- let frames = match decode_stream(&stream) {
1534- Ok(frames) => frames,
1535- Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
1536- };
1537- assert!(
1538- decode::palette_hits() > before,
1539- "palette_y_mode never fired decoding this stream -- gate is vacuous"
1540- );
1541- let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 64, 64, 1);
1542- assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg");
1543- assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg");
1544- assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg");
1545- }
1546-
1547- /// lane-kf900 r3: the palette colour reader at BOTH bit depths.
1548- ///
1549- /// `read_palette_colors_y`/`_uv` (decode.rs, mirroring `decodemv.c:478`
1550- /// and `:509`) size every raw literal they read by the sequence's
1551- /// `bit_depth`: the first colour is `bit_depth` bits, `min_bits` is
1552- /// `bit_depth - 3` (Y/U) or `bit_depth - 4` (V), `range` starts at
1553- /// `1 << bit_depth`, and the clamp/wrap bound is `(1 << bit_depth) - 1`.
1554- /// Ours hardcoded 8, so every 10-bit palette block read TWO BITS TOO FEW
1555- /// per transmitted colour and silently decoded the rest of the tile from
1556- /// the wrong bit position.
1557- ///
1558- /// It was silent because raw literals are EQUIPROBABLE: at the ranges
1559- /// this content reaches an equiprobable read maps the msac range onto
1560- /// itself (62728 -> 31364 -> renormalised 62728), so a cross-decoder
1561- /// RANGE ladder stays bit-identical straight through the miscount and
1562- /// only the decoded VALUE moves. Pinned on a 256x192 10-bit
1563- /// `--cq-level=59` stream whose first block is a 32x16 palette: aomdec's
1564- /// `EC_PAL` ladder and ours agreed on every range and disagreed on the
1565- /// very first colour index (0 vs 1); after the fix all 1024 `EC_PAL`
1566- /// lines of that block match aomdec line for line.
1567- ///
1568- /// The recipe is the 8-bit `..._with_palette_y_...` gate's, with the
1569- /// depth as the only variable, so a failure here is the depth and
1570- /// nothing else. HARD-asserts [`decode::palette_hits`] moved on each arm
1571- /// (a stream with no real palette block would prove nothing) and
1572- /// compares all three planes against ffmpeg's decode of the same bytes.
1573- #[test]
1574- fn a_real_aomenc_palette_stream_decodes_pixel_exact_at_8_and_10_bit() {
1575- const NAME: &str = "a_real_aomenc_palette_stream_decodes_pixel_exact_at_8_and_10_bit";
1576- if !have_ffmpeg() {
1577- eprintln!("SKIP {NAME}: no ffmpeg");
1578- return;
1579- }
1580- if !have_aomenc() {
1581- eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
1582- return;
1583- }
1584- let (width, height) = (64usize, 64usize);
1585- for depth in [8usize, 10] {
1586- let pix_fmt = if depth == 10 {
1587- "yuv420p10le"
1588- } else {
1589- "yuv420p"
1590- };
1591- let render = || {
1592- crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1593- .args([
1594- "-v",
1595- "error",
1596- "-f",
1597- "lavfi",
1598- "-i",
1599- "smptebars=size=64x64:rate=25",
1600- "-vf",
1601- "hue=s=0",
1602- "-pix_fmt",
1603- pix_fmt,
1604- "-strict",
1605- "-1",
1606- "-t",
1607- "0.04",
1608- "-f",
1609- "yuv4mpegpipe",
1610- "-",
1611- ])
1612- .stdin(Stdio::null())
1613- .stdout(Stdio::piped())
1614- .stderr(Stdio::piped()), None, |c| c.output())
1615- .expect("ffmpeg failed to run")
1616- .stdout
1617- };
1618- let y4m_a = render();
1619- let y4m_b = render();
1620- assert_eq!(
1621- y4m_a, y4m_b,
1622- "{NAME}: smptebars must render byte-identical across two runs at {depth}-bit"
1623- );
1624- let y4m = y4m_a;
1625- let depth_arg = format!("--bit-depth={depth}");
1626- let input_depth_arg = format!("--input-bit-depth={depth}");
1627- let out = run_with_stdin(
1628- Command::new(aomenc_path())
1629- .args([
1630- "--codec=av1",
1631- "--passes=1",
1632- "--end-usage=q",
1633- "--cq-level=30",
1634- "--cpu-used=0",
1635- "--threads=1",
1636- "--row-mt=0",
1637- "--sb-size=64",
1638- "--tune-content=screen",
1639- "--enable-palette=1",
1640- "--enable-intrabc=0",
1641- "--enable-rect-partitions=0",
1642- "--enable-ab-partitions=0",
1643- "--enable-1to4-partitions=0",
1644- "--min-partition-size=32",
1645- "--max-partition-size=32",
1646- "--enable-filter-intra=0",
1647- "--enable-smooth-intra=0",
1648- "--enable-paeth-intra=0",
1649- "--enable-directional-intra=0",
1650- "--enable-angle-delta=0",
1651- "--enable-cfl-intra=0",
1652- "--enable-cdef=0",
1653- "--enable-restoration=0",
1654- "--enable-tx-size-search=0",
1655- "--loopfilter-control=0",
1656- "--limit=1",
1657- ])
1658- // Per-arm overrides go AFTER the base recipe: aomenc keeps the
1659- // LAST occurrence of a repeated flag.
1660- .args([&depth_arg, &input_depth_arg])
1661- .args(["--obu", "-o", "-", "-"]),
1662- &y4m,
1663- );
1664- assert!(
1665- out.status.success(),
1666- "{NAME}: aomenc refused the {depth}-bit fixture: {}",
1667- String::from_utf8_lossy(&out.stderr)
1668- );
1669- let stream = out.stdout;
1670- let before = decode::palette_hits();
1671- let frames = match decode_stream(&stream) {
1672- Ok(frames) => frames,
1673- Err(e) => panic!("{NAME}: decode_stream refused the {depth}-bit stream: {e}"),
1674- };
1675- assert!(
1676- decode::palette_hits() > before,
1677- "{NAME}: no real palette block at {depth}-bit -- gate is vacuous"
1678- );
1679- let ffmpeg_frames = if depth == 10 {
1680- ffmpeg_decode_sequence_10bit(&stream, width, height, 1)
1681- } else {
1682- ffmpeg_decode_sequence(&stream, width, height, 1)
1683- };
1684- assert_eq!(
1685- frames[0].y, ffmpeg_frames[0].y,
1686- "{NAME}: luma at {depth}-bit"
1687- );
1688- assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U at {depth}-bit");
1689- assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V at {depth}-bit");
1690- }
1691- }
1692-
1693- /// lane-pal8 r1, the gate for a palette on a SQUARE 8x8 LEAF.
1694- ///
1695- /// `read_palette_mode_info` (decodemv.c:567) reads `palette_y_mode` for
1696- /// every `DC_PRED` block whose `av1_get_palette_bsize_ctx`
1697- /// (`num_pels_log2 - num_pels_log2[BLOCK_8X8]`, 0 at 8x8) exists, and
1698- /// `av1_decode_palette_tokens` (decodeframe.c:1135, `av1_visit_palette`)
1699- /// reads the colour-index map after the WHOLE mode-info read. Ours passed
1700- /// `None`/`&[]` from [`decode::decode_leaf8`], reading the mode symbol off
1701- /// CDF row 0 and refusing "a block that actually uses a palette (Y) --
1702- /// reconstruction is out of scope" the moment it fired -- and at 8 bit
1703- /// aomenc palettes SQUARE blocks, so with `--min-partition-size=8` every
1704- /// 8-bit screen-content stream stopped there (lane-kf900 r4's measurement).
1705- ///
1706- /// Sweeps both bit depths x cq 30/40/55 x `--enable-tx-size-search` 0/1 x
1707- /// two lavfi sources (+ a `--tile-columns=1` arm, per the neighbour-map
1708- /// rule: the palette bands are per-mi and tile-guarded). Key frame only
1709- /// (`--limit=1`): the inter frames of these recipes stop on OTHER lanes'
1710- /// open refusals (8x8 inter leaf chroma mode, inter 1:4 partitions).
1711- /// HARD-asserts the 8x8-leaf palette counter moved on the compared arms
1712- /// and that no arm mismatched, in or out of scope.
1713- #[test]
1714- fn a_real_aomenc_palette_stream_with_8x8_leaves_decodes_pixel_exact() {
1715- const NAME: &str = "a_real_aomenc_palette_stream_with_8x8_leaves_decodes_pixel_exact";
1716- if !have_ffmpeg() {
1717- eprintln!("SKIP {NAME}: no ffmpeg");
1718- return;
1719- }
1720- if !have_aomenc() {
1721- eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
1722- return;
1723- }
1724- let (width, height) = (128usize, 128usize);
1725- let (mut leaf8_total, mut fired_arms, mut compared, mut frames_compared) =
1726- (0usize, 0u32, 0u32, 0usize);
1727- let (mut out_of_scope, mut out_of_scope_mismatch, mut refusals) = (0u32, 0u32, 0u32);
1728- let (mut sb_strip_total, mut sb_strip_arms) = (0usize, 0u32);
1729- // lane-t900 r34 LIFTED this shape; the counter stays so the gate
1730- // fails loudly if the refusal ever comes back.
1731- let mut sb_strip_refusals = 0u32;
1732- for src in ["testsrc2", "smptebars"] {
1733- for depth in [8usize, 10usize] {
1734- for cq in [30usize, 40, 55] {
1735- for txs in [0usize, 1] {
1736- for tiles in [0usize, 1] {
1737- let arm = format!("{src}-{depth}bit-cq{cq}-txs{txs}-tc{tiles}");
1738- let pix_fmt = if depth == 10 {
1739- "yuv420p10le"
1740- } else {
1741- "yuv420p"
1742- };
1743- let size = format!("{src}=size={width}x{height}:rate=25");
1744- let render = || {
1745- let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1746- .args([
1747- "-v",
1748- "error",
1749- "-f",
1750- "lavfi",
1751- "-i",
1752- &size,
1753- "-t",
1754- "0.04",
1755- "-pix_fmt",
1756- pix_fmt,
1757- "-strict",
1758- "-1",
1759- "-f",
1760- "yuv4mpegpipe",
1761- "-",
1762- ])
1763- .stdin(Stdio::null())
1764- .stdout(Stdio::piped())
1765- .stderr(Stdio::piped()), None, |c| c.output())
1766- .expect("ffmpeg failed to run");
1767- assert!(out.status.success(), "{NAME}: ffmpeg failed for {arm}");
1768- out.stdout
1769- };
1770- let y4m_a = render();
1771- let y4m_b = render();
1772- assert_eq!(
1773- y4m_a, y4m_b,
1774- "{NAME}: {arm} must render byte-identical across two runs"
1775- );
1776- let y4m = y4m_a;
1777- let depth_arg = format!("--bit-depth={depth}");
1778- let input_depth_arg = format!("--input-bit-depth={depth}");
1779- let cq_arg = format!("--cq-level={cq}");
1780- let txs_arg = format!("--enable-tx-size-search={txs}");
1781- let tiles_arg = format!("--tile-columns={tiles}");
1782- let out = run_with_stdin(
1783- Command::new(aomenc_path())
1784- .args([
1785- "--codec=av1",
1786- "--passes=1",
1787- "--end-usage=q",
1788- "--cpu-used=0",
1789- "--threads=1",
1790- "--row-mt=0",
1791- "--lag-in-frames=0",
1792- "--limit=1",
1793- "--sb-size=64",
1794- "--tune-content=screen",
1795- "--enable-palette=1",
1796- "--enable-intrabc=0",
1797- "--min-partition-size=8",
1798- "--enable-cdef=0",
1799- "--enable-restoration=0",
1800- "--loopfilter-control=0",
1801- ])
1802- // aomenc keeps the LAST occurrence of a repeated flag,
1803- // so per-arm overrides go after the base recipe.
1804- .args([
1805- &depth_arg,
1806- &input_depth_arg,
1807- &cq_arg,
1808- &txs_arg,
1809- &tiles_arg,
1810- ])
1811- .args(["--obu", "-o", "-", "-"]),
1812- &y4m,
1813- );
1814- assert!(
1815- out.status.success(),
1816- "{NAME}: aomenc refused {arm}: {}",
1817- String::from_utf8_lossy(&out.stderr)
1818- );
1819- let stream = out.stdout;
1820- decode::reset_palette_leaf8_hits();
1821- decode::reset_palette_sb_strip_hits();
1822- let decoded = decode_stream(&stream);
1823- let leaf8 = decode::palette_leaf8_hits();
1824- let sb_strip = decode::palette_sb_strip_hits();
1825- leaf8_total += leaf8;
1826- sb_strip_total += sb_strip;
1827- match decoded {
1828- Ok(frames) => {
1829- assert!(!frames.is_empty(), "{NAME}: {arm} decoded no frame");
1830- // The ENCODE's frame count: the per-arm
1831- // render (10417) builds
1832- // `{src}=size=128x128:rate=25` with `-t 0.04`
1833- // (10427) -- one frame -- and the aomenc args
1834- // carry `--limit=1` (10467), so every
1835- // (src, depth, cq, txs, tiles) arm codes
1836- // exactly 1 frame. Asserted ABOVE the oracle
1837- // call.
1838- assert_eq!(frames.len(), 1, "{NAME}: {arm} key frame");
1839- let theirs = if depth == 10 {
1840- ffmpeg_decode_sequence_10bit(
1841- &stream,
1842- width,
1843- height,
1844- frames.len(),
1845- )
1846- } else {
1847- ffmpeg_decode_sequence(&stream, width, height, frames.len())
1848- };
1849- assert_eq!(
1850- frames.len(),
1851- theirs.len(),
1852- "{NAME}: {arm} frame count"
1853- );
1854- let mut same = true;
1855- for (i, (ours, ref_f)) in
1856- frames.iter().zip(theirs.iter()).enumerate()
1857- {
1858- let ok = ours.y == ref_f.y
1859- && ours.u == ref_f.u
1860- && ours.v == ref_f.v;
1861- if !ok {
1862- eprintln!("{NAME}: {arm} MISMATCH at frame {i}");
1863- }
1864- same &= ok;
1865- frames_compared += 1;
1866- }
1867- compared += 1;
1868- if sb_strip > 0 {
1869- sb_strip_arms += 1;
1870- assert!(
1871- same,
1872- "{NAME}: {arm} decoded {sb_strip} non-skip palette \
1873- block(s) on a superblock-level strip and did not \
1874- match ffmpeg"
1875- );
1876- }
1877- if leaf8 > 0 || sb_strip > 0 {
1878- fired_arms += 1;
1879- assert!(
1880- same,
1881- "{NAME}: {arm} decoded {leaf8} 8x8-leaf palette \
1882- block(s) and did not match ffmpeg"
1883- );
1884- } else {
1885- out_of_scope += 1;
1886- if !same {
1887- out_of_scope_mismatch += 1;
1888- }
1889- }
1890- eprintln!(
1891- "{NAME}: {arm} {} frame(s), {leaf8} 8x8-leaf palette \
1892- block(s), {sb_strip} superblock-strip palette \
1893- block(s), exact={same}",
1894- frames.len()
1895- );
1896- }
1897- Err(e) => {
1898- let msg = e.to_string();
1899- assert!(
1900- msg.contains("unsupported"),
1901- "{NAME}: {arm} decode failed: {e}"
1902- );
1903- // Named, counted, never turned into a skip.
1904- if msg.contains("superblock-level HORZ/VERT strip") {
1905- sb_strip_refusals += 1;
1906- }
1907- eprintln!("{NAME}: {arm} REFUSED: {e}");
1908- refusals += 1;
1909- }
1910- }
1911- }
1912- }
1913- }
1914- }
1915- }
1916- eprintln!(
1917- "{NAME}: {leaf8_total} 8x8-leaf palette block(s) across {fired_arms} arm(s), \
1918- {compared} arms compared ({frames_compared} frames), {sb_strip_total} \
1919- superblock-strip palette block(s) across {sb_strip_arms} arm(s), \
1920- {out_of_scope} out of scope ({out_of_scope_mismatch} mismatched), \
1921- {refusals} refused ({sb_strip_refusals} superblock-strip palette)"
1922- );
1923- assert!(
1924- leaf8_total > 0 && fired_arms > 0,
1925- "{NAME}: gate is vacuous -- no compared arm decoded an 8x8-leaf palette block"
1926- );
1927- assert_eq!(
1928- sb_strip_refusals, 0,
1929- "{NAME}: the superblock-strip palette refusal is back (lane-t900 r34 lifted it)"
1930- );
1931- assert!(
1932- sb_strip_arms > 0 && sb_strip_total > 0,
1933- "{NAME}: no arm decoded a non-skip palette block on a superblock-level strip -- \
1934- the shape r34 lifted is no longer exercised"
1935- );
1936- assert_eq!(
1937- out_of_scope_mismatch, 0,
1938- "{NAME}: an out-of-scope arm mismatched ffmpeg -- a defect, never a skip"
1939- );
1940- assert!(
1941- frames_compared > 0,
1942- "{NAME}: no frame was compared pixel-exact"
1943- );
1944- }
1945-
1946- /// lane-av1toolgates: `enable-rect-tx` at 8 BITS. See
1947- /// [`rect_tx_tool_gate`] for what the flag does and does not prove, and
1948- /// why the recipe is spelled here rather than in the helper.
1949- ///
1950- /// The whole recipe is inline: `--passes=1` has to be findable in this
1951- /// segment for the coverage derivation to count the gate at all, and
1952- /// `--enable-rect-tx=1` has to be findable here for it to count the
1953- /// TOOL. The quantiser and the tx-size-search setting are swept as two
1954- /// arms so the witness cannot rest on one RD interaction.
1955- #[test]
1956- fn a_real_aomenc_8bit_stream_with_a_rect_transform_decodes_pixel_exact() {
1957- let mut totals = (0usize, 0usize);
1958- for (cq, tx_search) in [("20", "1"), ("40", "0")] {
1959- let args: Vec<String> = [
1960- "--codec=av1",
1961- "--passes=1",
1962- "--end-usage=q",
1963- "--cpu-used=0",
1964- "--threads=1",
1965- "--row-mt=0",
1966- "--lag-in-frames=0",
1967- "--auto-alt-ref=0",
1968- "--kf-max-dist=1000",
1969- "--error-resilient=1",
1970- "--sb-size=64",
1971- // The tool under test, spelled explicitly. CONTEXT, per
1972- // `rect_tx_tool_gate`: aomenc was ALLOWED rect tx sizes.
1973- "--enable-rect-tx=1",
1974- "--enable-rect-partitions=1",
1975- "--enable-ab-partitions=0",
1976- "--enable-1to4-partitions=0",
1977- "--enable-restoration=0",
1978- "--enable-palette=0",
1979- "--enable-cdef=0",
1980- "--enable-cfl-intra=0",
1981- "--enable-intrabc=0",
1982- "--enable-order-hint=0",
1983- "--min-partition-size=8",
1984- "--max-partition-size=32",
1985- ]
1986- .map(String::from)
1987- .into_iter()
1988- .chain([
1989- format!("--cq-level={cq}"),
1990- format!("--enable-tx-size-search={tx_search}"),
1991- ])
1992- // The output tail comes LAST: aomenc stops reading flags at the
1993- // first bare argument, so a sweep flag appended after `-o - -` is
1994- // silently dropped and the arm encodes a different recipe than the
1995- // one this gate claims to have run.
1996- .chain(["--obu", "-o", "-", "-"].map(String::from))
1997- .collect();
1998- let name = format!(
1999- "a_real_aomenc_8bit_stream_with_a_rect_transform_decodes_pixel_exact[cq{cq}/tx{tx_search}]"
2000- );
crates/ec-av1/src/stream/tests/t04.rsdeleted+0 -4516

Diff too large; view file

@@ -1,4516 +0,0 @@
1-use super::*;
2-use super::support::*;
3-use super::gates_a::*;
4-use crate::probe::run_with_stdin;
5-use std::process::{Command, Stdio};
6-
7- /// The 12-bit WARP witness (lane-av112bitw): the same source and recipe
8- /// with the warp tools ON -- aomenc picks warp models on this content
9- /// (measured pre-lift: the warp model fires at the third frame, and the
10- /// decode refused by name at exactly that block) -- now decodes
11- /// BYTE-EXACT against ffmpeg. The warp filter's shifts are the bumped
12- /// `conv_params->round_0` (`warp::warp_round_0`, 5 at 12 bits, feeding
13- /// `reduce_bits_horiz`, the derived non-compound
14- /// `reduce_bits_vert = 2*FILTER_BITS - round_0` and both `offset_bits`),
15- /// the whole libaom `get_conv_params_no_round` 12-bit bump.
16- ///
17- /// Non-vacuous: the same recipe refused by name before the lift, the
18- /// gate hard-asserts a warp predictor was really resolved (a warpless
19- /// stream would pass the pixel compare and prove nothing), and every
20- /// plane of every frame compares against ffmpeg's decode.
21- #[test]
22- fn a_12bit_warped_motion_stream_decodes_pixel_exact() {
23- const NAME: &str = "a_12bit_warped_motion_stream_decodes_pixel_exact";
24- let _gate_lock = lock_gate_counters();
25- if !have_ffmpeg() {
26- eprintln!("SKIP {NAME}: no ffmpeg");
27- return;
28- }
29- if !have_aomenc() {
30- eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
31- return;
32- }
33- let y4m = y4m_12bit_subpel_source(6);
34- // Exactly the recipe measured to refuse at warp pre-lift: warp ON,
35- // global motion NOT spelled (spelling it ON drives a GLOBAL_GLOBALMV
36- // compound block into the compound-warp arm -- see the compound gate
37- // below), six frames -- the warp model fires at the third frame.
38- let stream = encode_12bit(&y4m, 6, &["--enable-warped-motion=1"]);
39- assert_12bit_sequence_header(&stream, NAME);
40- let (before_selected, before_warp8, before_affine) = (
41- decode::warp_selected_hits(),
42- decode::warp_hits_8(),
43- decode::affine_gm_hits(),
44- );
45- let frames = decode_stream(&stream).unwrap_or_else(|e| {
46- panic!("{NAME}: decode_stream refused a real 12-bit warp stream: {e}")
47- });
48- assert_eq!(frames.len(), 6);
49- let (delta_selected, delta_warp8, delta_affine) = (
50- decode::warp_selected_hits() - before_selected,
51- decode::warp_hits_8() - before_warp8,
52- decode::affine_gm_hits() - before_affine,
53- );
54- eprintln!(
55- "{NAME}: warp_engagement selected(16x16+ symbol)={delta_selected} \
56- warped8(usable 8x8 model)={delta_warp8} affine_gm(6-param model)={delta_affine}"
57- );
58- assert!(
59- delta_selected + delta_warp8 + delta_affine > 0,
60- "{NAME}: no warp predictor was resolved -- the stream carries no \
61- warp model and the pixel compare would prove nothing"
62- );
63- let ffmpeg_frames = ffmpeg_decode_sequence_12bit(&stream, 160, 128, 6);
64- for (i, (ours, reference)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
65- assert_eq!(
66- ours.y, reference.y,
67- "frame {i} luma vs ffmpeg (12-bit warp)"
68- );
69- assert_eq!(ours.u, reference.u, "frame {i} U vs ffmpeg (12-bit warp)");
70- assert_eq!(ours.v, reference.v, "frame {i} V vs ffmpeg (12-bit warp)");
71- }
72- }
73-
74- /// The 12-bit COMPOUND witness (lane-av112bitc): the parent's source
75- /// and recipe with warp pinned OFF -- with six frames LAST diverges
76- /// from GOLDEN from frame 2 on and aomenc codes compound inter blocks
77- /// (pre-lift measurement: the decode refused at the compound mode
78- /// read). Two arms: the default recipe (dist-weighted average
79- /// combines live) and `--enable-dist-wtd-comp=0` (pushes compound AND
80- /// the masked choice harder: 6 diffwtd blends). Both byte-exact
81- /// against ffmpeg; each hard-asserts compound mode symbols and
82- /// masked-diffwtd blends really ran, so the parameterised combine
83- /// rounds (`INTER_POST_ROUND - delta`, diffwtd `+ (bd-8) - delta` at
84- /// 12 bits) and the ffmpeg-pinned pixel path genuinely executed.
85- #[test]
86- fn a_real_aomenc_12bit_compound_inter_sequence_decodes_pixel_exact() {
87- const NAME: &str = "a_real_aomenc_12bit_compound_inter_sequence_decodes_pixel_exact";
88- let _gate_lock = lock_gate_counters();
89- if !have_ffmpeg() {
90- eprintln!("SKIP {NAME}: no ffmpeg");
91- return;
92- }
93- if !have_aomenc() {
94- eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
95- return;
96- }
97- let y4m = y4m_12bit_subpel_source(6);
98- for (arm, extra) in [
99- ("dist-wtd", &["--enable-warped-motion=0"][..]),
100- (
101- "plain-masked",
102- &["--enable-warped-motion=0", "--enable-dist-wtd-comp=0"][..],
103- ),
104- ] {
105- let stream = encode_12bit(&y4m, 6, extra);
106- assert_12bit_sequence_header(&stream, NAME);
107- let before_compound = decode::compound_mode_hits();
108- let before_masked = decode::masked_compound_hits();
109- let before_diffwtd = decode::diffwtd_hits();
110- let before_wedge = decode::wedge_hits();
111- let frames = decode_stream(&stream).unwrap_or_else(|e| {
112- panic!("{NAME} [{arm}]: decode_stream refused a real 12-bit compound stream: {e}")
113- });
114- assert_eq!(frames.len(), 6, "{NAME} [{arm}]: frame count");
115- let (comp, masked, diffwtd, wedge) = (
116- decode::compound_mode_hits() - before_compound,
117- decode::masked_compound_hits() - before_masked,
118- decode::diffwtd_hits() - before_diffwtd,
119- decode::wedge_hits() - before_wedge,
120- );
121- eprintln!(
122- "{NAME} [{arm}]: compound blocks={comp} masked={masked} diffwtd={diffwtd} wedge={wedge}"
123- );
124- assert!(
125- comp > 0,
126- "{NAME} [{arm}]: no compound mode symbol was read -- the compound path is unexercised"
127- );
128- assert!(
129- masked > 0,
130- "{NAME} [{arm}]: no masked compound block ran -- the masked combine is unexercised"
131- );
132- assert!(
133- diffwtd > 0,
134- "{NAME} [{arm}]: no diffwtd blend ran -- the diffwtd combine is unexercised"
135- );
136- let ffmpeg_frames = ffmpeg_decode_sequence_12bit(&stream, 160, 128, 6);
137- for (i, (ours, reference)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
138- assert_eq!(
139- ours.y, reference.y,
140- "{NAME} [{arm}] frame {i} luma vs ffmpeg"
141- );
142- assert_eq!(ours.u, reference.u, "{NAME} [{arm}] frame {i} U vs ffmpeg");
143- assert_eq!(ours.v, reference.v, "{NAME} [{arm}] frame {i} V vs ffmpeg");
144- }
145- }
146- }
147-
148- /// lane-av112bitg: the 12-bit film grain witness. A real
149- /// `aomenc --bit-depth=12 --profile=2 --film-grain-test=5` stream -- grain
150- /// params present AND applied (2 luma + 9 cb + 9 cr scaling points,
151- /// overlap blending on, clip-to-restricted-range on; the second frame is
152- /// an INTER frame that inherits the params via `update_grain = 0`) --
153- /// decoded byte-exact against ffmpeg's own 12-bit decode of the identical
154- /// bytes (ffmpeg synthesizes grain by default; no grain-disable flag is
155- /// passed anywhere in this file). Proves the bit-depth-generic grain path
156- /// at 12 bits: `grain_range`'s ±(128 << 4) AR clamp and overlap-blend
157- /// clamp, the `gauss_sec_shift = 12 - bd` Gaussian shift, the 4096-entry
158- /// expanded scaling-LUT interpolation, and the `<< (bit_depth - 8)`
159- /// chroma offsets and legal-range clamps. HARD-asserts the parsed headers
160- /// really carry that coverage and `film_grain::grain_hits()` fired, so
161- /// neither a params-without-apply stream nor a silently-skipped synthesis
162- /// can pass vacuously.
163- #[test]
164- fn a_real_aomenc_12bit_film_grain_stream_decodes_pixel_exact() {
165- const NAME: &str = "a_real_aomenc_12bit_film_grain_stream_decodes_pixel_exact";
166- let _gate_lock = lock_gate_counters();
167- if !have_ffmpeg() {
168- eprintln!("SKIP {NAME}: no ffmpeg");
169- return;
170- }
171- if !have_aomenc() {
172- eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
173- return;
174- }
175- let y4m = y4m_12bit_subpel_source(2);
176- // Warp stays refused at 12 bits (lane-av112bitg lifts GRAIN only), so
177- // the arm pins both motion tools off exactly once each -- aomenc
178- // otherwise picks warped motion on this fixture's sub-pel motion.
179- let stream = encode_12bit(
180- &y4m,
181- 2,
182- &[
183- "--film-grain-test=5",
184- "--enable-warped-motion=0",
185- "--enable-global-motion=0",
186- ],
187- );
188- assert_12bit_sequence_header(&stream, NAME);
189- // The arm is only honest if the stream itself carries the coverage:
190- // grain applied on every frame, scaling points on all three planes,
191- // overlap blending and restricted-range clipping on.
192- let mut probe = Av1Parser::new();
193- let mut pos = 0usize;
194- let mut grain_frames = 0usize;
195- while pos < stream.len() {
196- let obu = probe.parse_obu(&stream[pos..]).unwrap();
197- pos += obu.total_size;
198- if let ObuKind::Frame(header, _) = obu.kind {
199- let fg = &header.film_grain;
200- assert!(
201- fg.apply_grain,
202- "{NAME}: frame without apply_grain -- aomenc emitted params it does not apply"
203- );
204- assert!(
205- fg.num_y_points > 0 && fg.num_cb_points > 0 && fg.num_cr_points > 0,
206- "{NAME}: grain without all three planes' scaling points -- the bit-depth \
207- LUT math would not be exercised"
208- );
209- assert!(
210- fg.overlap_flag,
211- "{NAME}: overlap off -- the grain_min/grain_max blend clamp is not exercised"
212- );
213- assert!(
214- fg.clip_to_restricted_range,
215- "{NAME}: clip_to_restricted_range off -- the << (bd - 8) legal-range clamps \
216- are not exercised"
217- );
218- grain_frames += 1;
219- }
220- }
221- assert_eq!(grain_frames, 2, "{NAME}: expected grain on both frames");
222- let before = crate::film_grain::grain_hits();
223- let frames = decode_stream(&stream).unwrap_or_else(|e| {
224- panic!("{NAME}: decode_stream refused a real 12-bit grain stream: {e}")
225- });
226- assert_eq!(frames.len(), 2);
227- assert!(
228- crate::film_grain::grain_hits() > before,
229- "{NAME}: matched but zero grain_hits -- grain synthesis never ran"
230- );
231- let ffmpeg_frames = ffmpeg_decode_sequence_12bit(&stream, 160, 128, 2);
232- for (i, (ours, theirs)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
233- assert_eq!(
234- ours.y, theirs.y,
235- "{NAME}: luma vs ffmpeg (12-bit grain, frame {i})"
236- );
237- assert_eq!(
238- ours.u, theirs.u,
239- "{NAME}: U vs ffmpeg (12-bit grain, frame {i})"
240- );
241- assert_eq!(
242- ours.v, theirs.v,
243- "{NAME}: V vs ffmpeg (12-bit grain, frame {i})"
244- );
245- }
246- eprintln!(
247- "{NAME}: byte-exact, grain_hits={}",
248- crate::film_grain::grain_hits()
249- );
250- }
251-
252- /// lane-av1screen12: a 12-bit PALETTE screen-content stream, palette on
253- /// and palette-UV on, `allow_intrabc` off.
254- ///
255- /// Recipe: `ffmpeg -f lavfi -i testsrc2=s=160x128:r=25 -pix_fmt
256- /// yuv420p12le -strict -1` (2 frames, 160x128 4:2:0) piped to
257- /// [`encode_12bit`] with `--tune-content=screen --enable-palette=1
258- /// `--enable-intrabc=1`; pin `screen12_palette.obu` (3616 bytes, sha256
259- /// `adfe26c67c08a7e986db2743b914ecc3e214c56dd2abbdfd17ebf99f06de64c8`).
260- ///
261- /// What it replaces: this is the arm the blanket refusal "a 12-bit frame
262- /// with screen content tools" blocked while decoding exactly.
263- #[test]
264- fn a_real_aomenc_12bit_screen_content_palette_stream_decodes_pixel_exact() {
265- const NAME: &str = "a_real_aomenc_12bit_screen_content_palette_stream_decodes_pixel_exact";
266- const PIN: &str = "screen12_palette.obu";
267- let _gate_lock = lock_gate_counters();
268- if !have_ffmpeg() {
269- eprintln!("SKIP {NAME}: no ffmpeg");
270- return;
271- }
272- let y4m = y4m_12bit_screen_source("testsrc2=s=160x128:r=25", false);
273- let live = if have_aomenc() {
274- encode_12bit(
275- &y4m,
276- 2,
277- &[
278- "--tune-content=screen",
279- "--enable-palette=1",
280- "--enable-intrabc=1",
281- ],
282- )
283- } else {
284- Vec::new()
285- };
286- assert_12bit_screen_content_arm(
287- NAME,
288- PIN,
289- live,
290- PIN_LEN_PALETTE,
291- PIN_FNV_PALETTE,
292- 2,
293- 160,
294- 128,
295- false,
296- );
297- }
298-
299- /// lane-av1screen12: a 12-bit screen-content stream whose KEY frame sets
300- /// `allow_intrabc = 1` and really codes `use_intrabc` blocks.
301- ///
302- /// Recipe: [`screen_intrabc_stream_at_depth`] at depth 12 -- the same
303- /// shape the 8/10-bit intrabc census and the sb128 intrabc witness use:
304- /// `-vf tile=2x2` over `smptebars=size=128x96:rate=25` (256x192),
305- /// `--tune-content=screen --enable-intrabc=1 --enable-palette=1
306- /// --cq-level=30 --enable-tx-size-search=0 --min-partition-size=8
307- /// --max-partition-size=32 --sb-size=64 --kf-max-dist=1 --limit=1`, so
308- /// ONE 12-bit key frame; pin `screen12_intrabc.obu` (482 bytes, sha256
309- /// `a3b6b94cabdd09a12057c4688990d55495826b87a14332c386d319629070382e`).
310- ///
311- /// This arm is the one the old refusal's "nor intrabc" half named, and it
312- /// is why the refusal could be LIFTED rather than narrowed: it decodes
313- /// byte-exact at 12 bits and `intrabc_hits()` proves the blocks really
314- /// reconstructed from the current frame.
315- #[test]
316- fn a_real_aomenc_12bit_intrabc_screen_stream_decodes_pixel_exact() {
317- const NAME: &str = "a_real_aomenc_12bit_intrabc_screen_stream_decodes_pixel_exact";
318- const PIN: &str = "screen12_intrabc.obu";
319- let _gate_lock = lock_gate_counters();
320- if !have_ffmpeg() {
321- eprintln!("SKIP {NAME}: no ffmpeg");
322- return;
323- }
324- let live = if have_aomenc() {
325- // `--enable-palette=1` LAST (aomenc keeps the last occurrence), so
326- // this 12-bit arm carries BOTH screen-content syntaxes rather than
327- // intra-block copy alone.
328- screen_intrabc_stream_at_depth(
329- "smptebars=size=128x96:rate=25",
330- "30",
331- "0",
332- true,
333- false,
334- 12,
335- &["--enable-palette=1"],
336- )
337- } else {
338- Vec::new()
339- };
340- assert_12bit_screen_content_arm(
341- NAME,
342- PIN,
343- live,
344- PIN_LEN_INTRABC,
345- PIN_FNV_INTRABC,
346- 1,
347- 256,
348- 192,
349- true,
350- );
351- }
352-
353- /// lane-av1screen12: a 12-bit LOSSLESS screen-content stream with
354- /// palette and palette-UV on.
355- ///
356- /// Recipe: the palette arm's source and flags plus `--lossless=1`, so the
357- /// frame is `CodedLossless` (base_q_idx 0, WHT on every plane) AND
358- /// screen-content -- two 12-bit tile-syntax interactions in one frame;
359- /// pin `screen12_lossless_palette.obu` (11698 bytes, sha256
360- /// `ec7942c96763593e6d8e4b3fb23c03930bba3bb743102d0cf552fe73ae11c203`).
361- #[test]
362- fn a_real_aomenc_12bit_lossless_screen_content_stream_decodes_pixel_exact() {
363- const NAME: &str = "a_real_aomenc_12bit_lossless_screen_content_stream_decodes_pixel_exact";
364- const PIN: &str = "screen12_lossless_palette.obu";
365- let _gate_lock = lock_gate_counters();
366- if !have_ffmpeg() {
367- eprintln!("SKIP {NAME}: no ffmpeg");
368- return;
369- }
370- let y4m = y4m_12bit_screen_source("testsrc2=s=160x128:r=25", false);
371- let live = if have_aomenc() {
372- encode_12bit(
373- &y4m,
374- 2,
375- &[
376- "--tune-content=screen",
377- "--enable-palette=1",
378- "--enable-intrabc=1",
379- "--lossless=1",
380- ],
381- )
382- } else {
383- Vec::new()
384- };
385- assert_12bit_screen_content_arm(
386- NAME,
387- PIN,
388- live,
389- PIN_LEN_LOSSLESS,
390- PIN_FNV_LOSSLESS,
391- 2,
392- 160,
393- 128,
394- false,
395- );
396- }
397-
398- #[test]
399- fn a_real_aomenc_10bit_stream_decodes_pixel_exact() {
400- const NAME: &str = "a_real_aomenc_10bit_stream_decodes_pixel_exact";
401- if !have_ffmpeg() {
402- eprintln!("SKIP {NAME}: no ffmpeg");
403- return;
404- }
405- if !have_aomenc() {
406- eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
407- return;
408- }
409- let (width, height) = (64usize, 64usize);
410- let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
411- .args([
412- "-v",
413- "error",
414- "-f",
415- "lavfi",
416- "-i",
417- &gradients_source(42, width, height, "duration=0.04:rate=25"),
418- "-pix_fmt",
419- "yuv420p10le",
420- "-strict",
421- "-1",
422- "-t",
423- "0.04",
424- "-f",
425- "yuv4mpegpipe",
426- "-",
427- ])
428- .stdin(Stdio::null())
429- .stdout(Stdio::piped())
430- .stderr(Stdio::piped()), None, |c| c.output())
431- .expect("ffmpeg failed to run");
432- assert!(
433- y4m.status.success(),
434- "ffmpeg failed to render the 10-bit fixture: {}",
435- String::from_utf8_lossy(&y4m.stderr)
436- );
437- let out = run_with_stdin(
438- Command::new(aomenc_path()).args([
439- "--codec=av1",
440- "--passes=1",
441- "--end-usage=q",
442- "--cq-level=30",
443- "--cpu-used=0",
444- "--threads=1",
445- "--row-mt=0",
446- "--sb-size=64",
447- "--input-bit-depth=10",
448- "--bit-depth=10",
449- "--limit=1",
450- "--obu",
451- "-o",
452- "-",
453- "-",
454- ]),
455- &y4m.stdout,
456- );
457- assert!(
458- out.status.success(),
459- "aomenc refused the 10-bit fixture: {}",
460- String::from_utf8_lossy(&out.stderr)
461- );
462- let stream = out.stdout;
463- // Confirm the sequence header this stream actually parses to before
464- // trusting any pixel comparison below.
465- let mut probe = Av1Parser::new();
466- let mut pos = 0usize;
467- while pos < stream.len() && probe.sequence_header().is_none() {
468- let obu = probe.parse_obu(&stream[pos..]).unwrap();
469- pos += obu.total_size;
470- }
471- let seq = probe
472- .sequence_header()
473- .expect("stream has a sequence header OBU");
474- assert_eq!(
475- seq.color_config.bit_depth, 10,
476- "{NAME}: aomenc did not actually write a 10-bit sequence header"
477- );
478- let frames = match decode_stream(&stream) {
479- Ok(frames) => frames,
480- Err(e) => panic!("{NAME}: decode_stream refused a real 10-bit stream: {e}"),
481- };
482- let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
483- assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg (10-bit)");
484- assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (10-bit)");
485- assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (10-bit)");
486- }
487-
488- /// The 10-bit *inter* counterpart of the gate above: a real `aomenc`
489- /// `yuv420p10le` sequence whose non-key frames are plain forward
490- /// single-`LAST_FRAME` P frames (same `--lag-in-frames=0
491- /// --auto-alt-ref=0 --error-resilient=1` shape as the 8-bit inter gate),
492- /// decoded pixel-exact on every frame. 10-bit intra was proven exact by
493- /// lane-hbd; inter reconstruction at `bit_depth == 10` was never gated.
494- #[test]
495- fn a_real_aomenc_10bit_inter_sequence_decodes_pixel_exact() {
496- const NAME: &str = "a_real_aomenc_10bit_inter_sequence_decodes_pixel_exact";
497- let _gate_lock = lock_gate_counters();
498- if !have_ffmpeg() {
499- eprintln!("SKIP {NAME}: no ffmpeg");
500- return;
501- }
502- if !have_aomenc() {
503- eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
504- return;
505- }
506- let (width, height, frame_count) = (128usize, 64usize, 16usize);
507- let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
508- .args([
509- "-v",
510- "error",
511- "-f",
512- "lavfi",
513- "-i",
514- &gradients_source(42, width, height, "duration=0.64:rate=25"),
515- "-pix_fmt",
516- "yuv420p10le",
517- "-strict",
518- "-1",
519- "-t",
520- "0.64",
521- "-f",
522- "yuv4mpegpipe",
523- "-",
524- ])
525- .stdin(Stdio::null())
526- .stdout(Stdio::piped())
527- .stderr(Stdio::piped()), None, |c| c.output())
528- .expect("ffmpeg failed to run");
529- assert!(
530- y4m.status.success(),
531- "ffmpeg failed to render the 10-bit fixture: {}",
532- String::from_utf8_lossy(&y4m.stderr)
533- );
534- let out = run_with_stdin(
535- Command::new(aomenc_path()).args([
536- // lane-defon r1: explicit on-value (aomenc keeps the FIRST
537- // occurrence, so overrides go before the base list).
538- "--loopfilter-control=1",
539- "--codec=av1",
540- "--passes=1",
541- "--end-usage=q",
542- "--cq-level=15",
543- "--cpu-used=0",
544- "--threads=1",
545- "--row-mt=0",
546- "--sb-size=64",
547- "--input-bit-depth=10",
548- "--bit-depth=10",
549- "--lag-in-frames=0",
550- "--auto-alt-ref=0",
551- "--kf-max-dist=1000",
552- "--error-resilient=1",
553- "--aq-mode=0",
554- "--deltaq-mode=0",
555- "--enable-cdef=0",
556- "--enable-rect-partitions=0",
557- "--enable-ab-partitions=0",
558- "--enable-1to4-partitions=0",
559- "--enable-filter-intra=0",
560- "--enable-smooth-intra=0",
561- "--enable-paeth-intra=0",
562- "--enable-directional-intra=0",
563- "--enable-angle-delta=0",
564- "--enable-tx-size-search=0",
565- "--enable-cdef=1",
566- "--enable-restoration=1",
567- "--min-partition-size=16",
568- "--max-partition-size=32",
569- "--enable-palette=0",
570- "--enable-intrabc=0",
571- "--enable-cfl-intra=0",
572- "--enable-ref-frame-mvs=0",
573- "--obu",
574- "-o",
575- "-",
576- "-",
577- ]),
578- &y4m.stdout,
579- );
580- assert!(
581- out.status.success(),
582- "aomenc refused the 10-bit fixture: {}",
583- String::from_utf8_lossy(&out.stderr)
584- );
585- let stream = out.stdout;
586- if let Ok(dump) = std::env::var("EC_AV1_GATE_DUMP") {
587- std::fs::write(dump, &stream).expect("dump stream");
588- }
589- let mut probe = Av1Parser::new();
590- let mut pos = 0usize;
591- while pos < stream.len() && probe.sequence_header().is_none() {
592- let obu = probe.parse_obu(&stream[pos..]).unwrap();
593- pos += obu.total_size;
594- }
595- assert_eq!(
596- probe
597- .sequence_header()
598- .expect("stream has a sequence header OBU")
599- .color_config
600- .bit_depth,
601- 10,
602- "{NAME}: aomenc did not actually write a 10-bit sequence header"
603- );
604- let before_deblock = decode::deblock_hits();
605- let before_inter = decode::inter_pred_hits();
606- let before_lr = crate::restoration::wiener_hits()
607- + crate::restoration::sgrproj_hits()
608- + crate::restoration::switchable_hits();
609- let frames = match decode_stream(&stream) {
610- Ok(frames) => frames,
611- Err(e) => panic!("{NAME}: decode_stream refused a real 10-bit inter stream: {e}"),
612- };
613- assert!(
614- decode::inter_pred_hits() > before_inter,
615- "{NAME}: no inter-predicted block decoded -- the gate proves nothing"
616- );
617- assert!(
618- decode::deblock_hits() > before_deblock,
619- "{NAME}: no deblocking edge fired -- raise cq-level"
620- );
621- // Loop restoration is where the 10-bit inter/intra defect lived
622- // (lane-hbdinter r1: the self-guided box sums were never brought back
623- // to the 8-bit scale, `restoration.c:660`); a recipe whose RD happened
624- // to pick RESTORE_NONE would pass while proving nothing.
625- assert!(
626- crate::restoration::wiener_hits()
627- + crate::restoration::sgrproj_hits()
628- + crate::restoration::switchable_hits()
629- > before_lr,
630- "{NAME}: no loop-restoration unit decoded a real filter -- lower cq-level"
631- );
632- eprintln!(
633- "{NAME}: inter_pred {} deblock {} cdef_idx {} wiener {} sgrproj {}",
634- decode::inter_pred_hits() - before_inter,
635- decode::deblock_hits() - before_deblock,
636- decode::cdef_idx_hits(),
637- crate::restoration::wiener_hits(),
638- crate::restoration::sgrproj_hits(),
639- );
640- assert_eq!(frames.len(), frame_count);
641- let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count);
642- for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
643- if got.y != want.y || got.u != want.u || got.v != want.v {
644- let pin = std::env::temp_dir().join("ec-av1-10bit-inter-gate-fail.obu");
645- crate::dumpio::pin("TEST_PIN", &pin, &stream);
646- let first = |a: &Vec<u16>, b: &Vec<u16>| {
647- a.iter()
648- .zip(b)
649- .enumerate()
650- .find(|(_, (x, y))| x != y)
651- .map(|(k, (x, y))| (k, *x, *y))
652- };
653- panic!(
654- "{NAME}: frame {i} mismatch vs ffmpeg -- Y {:?} U {:?} V {:?}; stream pinned at {}",
655- first(&got.y, &want.y),
656- first(&got.u, &want.u),
657- first(&got.v, &want.v),
658- pin.display()
659- );
660- }
661- }
662- }
663-
664- /// lane-hbd10 r1: a real `aomenc --bit-depth=10 --film-grain-test=1`
665- /// stream, decoded pixel-exact against ffmpeg's own 10-bit decode of the
666- /// identical bytes (ffmpeg synthesizes grain by default -- no
667- /// grain-disable flag is passed anywhere in this file). Proves the
668- /// bit-depth-generic grain path (`film_grain.rs`'s `grain_range`,
669- /// `scale_lut`, the `<< (bit_depth - 8)` offsets/legal ranges) rather
670- /// than the old `bit_depth != 8` refusal. HARD-asserts both the parsed
671- /// `bit_depth == 10` and `film_grain::grain_hits() > 0`, so neither a
672- /// silent 8-bit fallback nor a stream aomenc emitted without
673- /// `apply_grain` can make it pass vacuously.
674- #[test]
675- fn a_real_aomenc_10bit_film_grain_stream_decodes_pixel_exact() {
676- const NAME: &str = "a_real_aomenc_10bit_film_grain_stream_decodes_pixel_exact";
677- if !have_ffmpeg() {
678- eprintln!("SKIP {NAME}: no ffmpeg");
679- return;
680- }
681- if !have_aomenc() {
682- eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
683- return;
684- }
685- let (width, height) = (64usize, 64usize);
686- let stream = encode_10bit_gradients(
687- NAME,
688- width,
689- height,
690- 1,
691- &["--film-grain-test=1", "--limit=1"],
692- );
693- assert_eq!(
694- parsed_bit_depth(&stream),
695- 10,
696- "{NAME}: aomenc did not actually write a 10-bit sequence header"
697- );
698- let mut probe = Av1Parser::new();
699- let mut pos = 0usize;
700- let mut saw_grain = false;
701- while pos < stream.len() {
702- let obu = probe.parse_obu(&stream[pos..]).unwrap();
703- pos += obu.total_size;
704- if let ObuKind::Frame(header, _) = obu.kind
705- && header.film_grain.apply_grain
706- {
707- // A grain block whose scaling LUT is empty would blend a
708- // zero delta into every pixel and let this gate pass without
709- // the bit-depth math mattering at all.
710- assert!(
711- header.film_grain.num_y_points > 0,
712- "{NAME}: apply_grain with no luma scaling points -- grain would be a no-op"
713- );
714- saw_grain = true;
715- }
716- }
717- assert!(saw_grain, "{NAME}: aomenc did not turn on apply_grain");
718- let before = crate::film_grain::grain_hits();
719- let frames = match decode_stream(&stream) {
720- Ok(frames) => frames,
721- Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
722- };
723- assert!(
724- crate::film_grain::grain_hits() > before,
725- "{NAME}: matched but zero grain_hits -- grain synthesis never ran"
726- );
727- let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
728- assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
729- assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg");
730- assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg");
731- eprintln!(
732- "{NAME}: pixel-exact, grain_hits={}",
733- crate::film_grain::grain_hits()
734- );
735- }
736-
737- /// lane-t900 r29: `fixtures/superres_kf_cdef_lr_64x64.obu` is a real
738- /// aomenc key frame (64x64 upscaled from a coded 43x64,
739- /// `--superres-mode=1 --superres-denominator=12 --cpu-used=0 --sb-size=64
740- /// --enable-cdef=1 --enable-restoration=1 --cq-level=32`) -- the first
741- /// stream in this repo that runs BOTH in-loop filters under superres.
742- ///
743- /// The defect it pins: spec 7.16's upscale runs between CDEF and loop
744- /// restoration (libaom `superres_post_decode`, `decodeframe.c`, called
745- /// between `av1_cdef_frame` and `av1_loop_restoration_filter_frame`),
746- /// but this decoder ran the whole filter chain on the DOWNSCALED frame
747- /// and upscaled last, in `stream.rs`. Loop restoration therefore filtered
748- /// downscaled pixels with a unit grid sized from the downscaled width
749- /// (1873 wrong samples, max 7, on this very stream). Class
750- /// `wrong-stage-width`: every plane width in the filter chain is either
751- /// the downscaled one (deblock, CDEF, and the mi grid all three walk) or
752- /// the upscaled one (loop restoration's `av1_get_upsampled_plane_size`
753- /// unit grid, `av1_loop_restoration_corners_in_sb`'s `mi_to_num_x`
754- /// superres arm, and the pixel filters themselves); the sweep is every
755- /// caller of `apply_deblock`/`apply_cdef`/`apply_loop_restoration` plus
756- /// `RestorationGrid::new` and `read_lr`.
757- #[test]
758- fn a_superres_key_frame_with_cdef_and_loop_restoration_decodes_pixel_exact() {
759- const NAME: &str =
760- "a_superres_key_frame_with_cdef_and_loop_restoration_decodes_pixel_exact";
761- let _gate_lock = lock_gate_counters();
762- if !have_ffmpeg() {
763- eprintln!("SKIP {NAME}: no ffmpeg");
764- return;
765- }
766- let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
767- .join("fixtures/superres_kf_cdef_lr_64x64.obu");
768- let stream = std::fs::read(&path)
769- .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
770- let (width, height) = (64usize, 64usize);
771- let before_lr = crate::restoration::wiener_hits() + crate::restoration::sgrproj_hits();
772- let frames = match decode_stream(&stream) {
773- Ok(frames) => frames,
774- Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
775- };
776- assert_eq!(frames.len(), 1, "{NAME}: one key frame");
777- assert_eq!((frames[0].width, frames[0].height), (width, height));
778- // class `gate-blind-to-feature`: the stream must actually upscale and
779- // actually run a real restoration filter, or this gate proves nothing.
780- assert!(
781- crate::superres::superres_hits() > 0,
782- "{NAME}: zero superres_hits -- the frame was never upscaled"
783- );
784- assert!(
785- crate::restoration::wiener_hits() + crate::restoration::sgrproj_hits() > before_lr,
786- "{NAME}: zero restoration units fired -- LR never ran under superres"
787- );
788- let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
789- assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
790- assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg");
791- assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg");
792- }
793-
794- /// lane-av1superhbd (1): 4:4:4 superres at **10 bits**, `--superres-mode=1
795- /// --superres-denominator=12` on all four frames -- coded 171x128 upscaled
796- /// to 256x128 at `denom = 12`.
797- ///
798- /// **What it closes.** Every superres fixture the crate carried parsed
799- /// `bit_depth = 8` (4:2:0 `superres_kf_cdef_lr_64x64.obu`) or was 4:2:0
800- /// (`superres_alltools_sb128_320x180.obu`), and the 4:4:4 superres cells
801- /// were 8-bit. The chroma-format sweep's not-measured list kept "4:4:4
802- /// superres at 10/12 bits" open on that basis. This arm is the 10-bit
803- /// measurement: a 4:4:4 chroma plane upscaled at FULL resolution, where
804- /// the upscaler and the scaled inter predictor both run with a
805- /// 10-bit sample width and the 4:4:4 chroma gather has no subsampling
806- /// halving to hide behind.
807- ///
808- /// **The recipe** (sha256
809- /// `95b49d7aa81843399ee3aa64bdadfec8f4037bcc3f861923c9b2da3bc868b223`,
810- /// 15803 bytes, 4 frames, `testsrc2 256x128 rate=25` yuv444p10le):
811- /// ```text
812- /// ffmpeg -f lavfi -i "testsrc2=size=256x128:rate=25" -frames:v 4 \
813- /// -pix_fmt yuv444p10le -strict -1 -f yuv4mpegpipe - | \
814- /// aomenc --codec=av1 --profile=1 --bit-depth=10 --input-bit-depth=10 \
815- /// --passes=1 --end-usage=q --cq-level=20 --cpu-used=2 --threads=1 \
816- /// --row-mt=0 --lag-in-frames=0 --kf-max-dist=100 --limit=4 \
817- /// --superres-mode=1 --superres-denominator=12 \
818- /// --superres-kf-denominator=12 --obu -o - -
819- /// ```
820- /// `-strict -1` is load-bearing: without it ffmpeg refuses to write
821- /// `yuv444p10le` into a y4m pipe at all (zero bytes out).
822- #[test]
823- fn a_444_lossy_superres_10bit_d12_stream_decodes_pixel_exact() {
824- a_444_hbd_superres_arm(
825- "a_444_lossy_superres_10bit_d12_stream_decodes_pixel_exact",
826- "fixtures/444_lossy_superres_256x128_d12_10bit.obu",
827- 15803,
828- 0x9fad_3227_6e91_792c,
829- "95b49d7aa81843399ee3aa64bdadfec8f4037bcc3f861923c9b2da3bc868b223",
830- 10,
831- (256, 128),
832- &[(12, 171); 4],
833- );
834- }
835-
836- /// lane-av1superhbd (2): 4:4:4 superres at **12 bits**,
837- /// `--superres-mode=1 --superres-denominator=12`, coded 171x128 upscaled
838- /// to 256x128.
839- ///
840- /// **Why the source is `mandelbrot` and not `testsrc2`.** The 12-bit
841- /// frame gate refuses a frame carrying `allow_screen_content_tools = 1`
842- /// by name (palette and intrabc have no 12-bit witness). libaom sets
843- /// that bit from its own content detection
844- /// (`av1_set_screen_content_options` -> `encoder_utils.c:1153`, keyed on
845- /// the palette-pixel ratio of the FIRST pass), and `testsrc2` -- flat
846- /// colour bars and hard edges -- trips it at 12 bits while the very same
847- /// recipe at 10 bits does not. `--enable-palette=0 --enable-intrabc=0`
848- /// and `--tune-content=film` do NOT suppress it (measured: all four
849- /// still parse `allow_screen_content_tools = true`), because the
850- /// detection is a property of the CONTENT, not of those flags. A
851- /// photographic source (`mandelbrot`, same geometry and frame count)
852- /// parses `allow_screen_content_tools = false` and decodes. This is a
853- /// source choice, stated so the next lane does not re-derive it.
854- ///
855- /// **The recipe** (sha256
856- /// `973bf374c0185c4e6301509ce834cef01318e6cdb9488fd258118d7ec89bdd04`,
857- /// 11023 bytes, 4 frames, `mandelbrot 256x128 rate=25` yuv444p12le):
858- /// ```text
859- /// ffmpeg -f lavfi -i "mandelbrot=size=256x128:rate=25" -frames:v 4 \
860- /// -pix_fmt yuv444p12le -strict -1 -f yuv4mpegpipe - | \
861- /// aomenc --codec=av1 --profile=1 --bit-depth=12 --input-bit-depth=12 \
862- /// --passes=1 --end-usage=q --cq-level=20 --cpu-used=2 --threads=1 \
863- /// --row-mt=0 --lag-in-frames=0 --kf-max-dist=100 --limit=4 \
864- /// --superres-mode=1 --superres-denominator=12 \
865- /// --superres-kf-denominator=12 --obu -o - -
866- /// ```
867- /// Byte-reproducible: two independent encodes produced the same 11023
868- /// bytes.
869- #[test]
870- fn a_444_lossy_superres_12bit_d12_stream_decodes_pixel_exact() {
871- a_444_hbd_superres_arm(
872- "a_444_lossy_superres_12bit_d12_stream_decodes_pixel_exact",
873- "fixtures/444_lossy_superres_256x128_d12_12bit.obu",
874- 11023,
875- 0xd6cf_bb83_2b42_8e2d,
876- "973bf374c0185c4e6301509ce834cef01318e6cdb9488fd258118d7ec89bdd04",
877- 12,
878- (256, 128),
879- &[(12, 171); 4],
880- );
881- }
882-
883- /// lane-av1superhbd (3): 4:4:4 superres at **12 bits** at the WIDEST
884- /// denominator this geometry allows, `--superres-denominator=9` -- coded
885- /// 228x128 upscaled to 256x128, so 28 of the 256 columns are the frame's
886- /// right-edge upscale margin, against 12's 85.
887- ///
888- /// It is a separate gate from the den=12 arm because the margin is
889- /// where a round-trip is most likely to read past the coded picture: a
890- /// decoder that sized the upscale source from `UpscaledWidth` instead of
891- /// `FrameWidth` is exact at den=12 on this content and wrong here. Its
892- /// recipe is the 12-bit one above with `--superres-denominator=9
893- /// --superres-kf-denominator=9` (sha256
894- /// `898c775108495b998cb5ec9b08e194d4656ed0140aa8e7e7236892d468bbad99`,
895- /// 13015 bytes).
896- #[test]
897- fn a_444_lossy_superres_12bit_d9_stream_decodes_pixel_exact() {
898- a_444_hbd_superres_arm(
899- "a_444_lossy_superres_12bit_d9_stream_decodes_pixel_exact",
900- "fixtures/444_lossy_superres_256x128_d9_12bit.obu",
901- 13015,
902- 0x4110_ce7b_cd85_901b,
903- "898c775108495b998cb5ec9b08e194d4656ed0140aa8e7e7236892d468bbad99",
904- 12,
905- (256, 128),
906- &[(9, 228); 4],
907- );
908- }
909-
910- /// lane-av1superhbd (4): 4:4:4 superres at **10 bits** under
911- /// `--superres-mode=2` -- the random-denominator arm, where libaom picks
912- /// a DIFFERENT denominator for every frame and IGNORES
913- /// `--superres-denominator` entirely.
914- ///
915- /// This is what keeps the high-bit-depth superres cell from silently
916- /// degenerating into a single-denominator cell: the per-frame parsed
917- /// denominators are 11, 14, 15, 9 -- three of them values no flag on the
918- /// command line ever named -- so a gate that read the flag instead of
919- /// the header would be wrong on three of four frames. The assertion
920- /// below makes that structural rather than incidental, and it is the
921- /// assertion that fails if a future libaom starts honouring the flag
922- /// under mode 2.
923- ///
924- /// **The recipe** (sha256
925- /// `699398aba58fb53b80e05d3d214eb746a3c91945e01da6b47488513f20b55668`,
926- /// 17776 bytes, 4 frames, `testsrc2 256x128 rate=25` yuv444p10le):
927- /// ```text
928- /// ffmpeg -f lavfi -i "testsrc2=size=256x128:rate=25" -frames:v 4 \
929- /// -pix_fmt yuv444p10le -strict -1 -f yuv4mpegpipe - | \
930- /// aomenc --codec=av1 --profile=1 --bit-depth=10 --input-bit-depth=10 \
931- /// --passes=1 --end-usage=q --cq-level=20 --cpu-used=2 --threads=1 \
932- /// --row-mt=0 --lag-in-frames=0 --kf-max-dist=100 --limit=4 \
933- /// --superres-mode=2 --obu -o - -
934- /// ```
935- #[test]
936- fn a_444_lossy_superres_10bit_mode2_random_denom_stream_decodes_pixel_exact() {
937- const NAME: &str =
938- "a_444_lossy_superres_10bit_mode2_random_denom_stream_decodes_pixel_exact";
939- let heads = a_444_hbd_superres_arm(
940- NAME,
941- "fixtures/444_lossy_superres_mode2_256x128_10bit.obu",
942- 17776,
943- 0x164f_4099_7576_7ae4,
944- "699398aba58fb53b80e05d3d214eb746a3c91945e01da6b47488513f20b55668",
945- 10,
946- (256, 128),
947- &[(11, 186), (14, 146), (15, 137), (9, 228)],
948- );
949- // Distinct-denominator assert: the cell must stay a MULTI-denominator
950- // one. A libaom that collapsed mode 2 onto a single denominator (or
951- // stopped scaling) would still decode, and the gate above would still
952- // hold only because the literals would have been re-pinned with it --
953- // so the property is asserted from the parsed headers directly.
954- let denoms: Vec<u8> = heads.iter().map(|h| h.superres_denom).collect();
955- let mut distinct = denoms.clone();
956- distinct.sort_unstable();
957- distinct.dedup();
958- assert!(
959- distinct.len() >= 3,
960- "{NAME}: the stream carries denominators {denoms:?} -- fewer than three distinct \
961- values, so this is no longer the per-frame-denominator cell and the pin has to be \
962- re-derived from the stream"
963- );
964- let flagged = [9u8, 12, 16];
965- assert!(
966- denoms.iter().any(|d| !flagged.contains(d)),
967- "{NAME}: every parsed denominator is one of the flag values {flagged:?} -- mode 2 now \
968- appears to honour --superres-denominator, and this cell stops being the \
969- flag-ignoring one"
970- );
971- }
972-
973- /// lane-av1superhbd (5): 4:4:4 superres at **12 bits** under
974- /// `--superres-mode=2` -- the high-bit-depth random-denominator arm, the
975- /// 12-bit twin of the arm above (sha256
976- /// `18aa8b3124ab10672f22577a8eea81e44141a3d0bb506104aee2f950254a2e9f`,
977- /// 14656 bytes, same `mandelbrot` source as the 12-bit fixed-denominator
978- /// arms). Its parsed denominators are again 11/14/15/9 at coded widths
979- /// 186/146/137/228, so the upscaler is handed FOUR coded-to-upscaled
980- /// ratios in one 12-bit decode -- the case a single-denominator gate
981- /// cannot reach at any bit depth.
982- #[test]
983- fn a_444_lossy_superres_12bit_mode2_random_denom_stream_decodes_pixel_exact() {
984- const NAME: &str =
985- "a_444_lossy_superres_12bit_mode2_random_denom_stream_decodes_pixel_exact";
986- let heads = a_444_hbd_superres_arm(
987- NAME,
988- "fixtures/444_lossy_superres_mode2_256x128_12bit.obu",
989- 14656,
990- 0xef38_3fb7_b284_2166,
991- "18aa8b3124ab10672f22577a8eea81e44141a3d0bb506104aee2f950254a2e9f",
992- 12,
993- (256, 128),
994- &[(11, 186), (14, 146), (15, 137), (9, 228)],
995- );
996- let denoms: Vec<u8> = heads.iter().map(|h| h.superres_denom).collect();
997- let mut distinct = denoms.clone();
998- distinct.sort_unstable();
999- distinct.dedup();
1000- assert!(
1001- distinct.len() >= 3,
1002- "{NAME}: the stream carries denominators {denoms:?} -- fewer than three distinct \
1003- values, so this is no longer the per-frame-denominator cell and the pin has to be \
1004- re-derived from the stream"
1005- );
1006- let flagged = [9u8, 12, 16];
1007- assert!(
1008- denoms.iter().any(|d| !flagged.contains(d)),
1009- "{NAME}: every parsed denominator is one of the flag values {flagged:?} -- mode 2 now \
1010- appears to honour --superres-denominator, and this cell stops being the \
1011- flag-ignoring one"
1012- );
1013- }
1014-
1015- /// lane-wave1 step (ii): the superblock-row wavefront
1016- /// (`EC_AV1_RECON_THREADS`) reconstructs every output frame byte for
1017- /// byte as the inline path does, on a hidden-ARF 10-bit stream (no-show
1018- /// frames, CfL, 128 superblocks) and on the two screen-content streams
1019- /// whose palette/intrabc blocks READ the current frame's pixels while
1020- /// parsing -- the sites that make the workers barrier.
1021- #[test]
1022- fn a_real_stream_reconstructs_identically_with_one_and_four_recon_threads() {
1023- const NAME: &str = "a_real_stream_reconstructs_identically_with_one_and_four_recon_threads";
1024- let _gate_lock = lock_gate_counters();
1025- for fixture in [
1026- "reelb_arf_witness.obu",
1027- "palette_screen_witness.obu",
1028- "palette_screen_witness_10bit.obu",
1029- // lane-av1wavefront: the 4:4:4 inter witness. The wavefront's
1030- // replay-side chroma (`mv_to_q4(.., ss_x(fctx))` in the deferred
1031- // builds, `exec_intra`'s CfL AC) used to read the worker's fresh
1032- // `FrameCtx` 4:2:0 DEFAULT instead of the frame's subsampling --
1033- // invisible on the three 4:2:0 streams above, chroma-only loss on
1034- // this one (f1 U 17504 / V 3, f2 U 25472 / V 1472 at PREFILT).
1035- "444_sb128rect_lr_witness.obu",
1036- ] {
1037- let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1038- .join("fixtures")
1039- .join(fixture);
1040- let stream = std::fs::read(&path)
1041- .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
1042- crate::par::set_recon_threads(1);
1043- let one = match decode_stream(&stream) {
1044- Ok(frames) => frames,
1045- Err(e) => panic!("{NAME}: {fixture} refused at 1 recon thread: {e}"),
1046- };
1047- crate::par::set_recon_threads(4);
1048- let four = match decode_stream(&stream) {
1049- Ok(frames) => frames,
1050- Err(e) => {
1051- crate::par::set_recon_threads(1);
1052- panic!("{NAME}: {fixture} refused at 4 recon threads: {e}")
1053- }
1054- };
1055- crate::par::set_recon_threads(1);
1056- assert!(!one.is_empty(), "{NAME}: {fixture} decoded nothing");
1057- assert_eq!(one.len(), four.len(), "{NAME}: {fixture} frame count");
1058- for (i, (a, b)) in one.iter().zip(four.iter()).enumerate() {
1059- assert_eq!(
1060- a.y, b.y,
1061- "{NAME}: {fixture} frame {i} luma differs at 4 recon threads"
1062- );
1063- assert_eq!(
1064- a.u, b.u,
1065- "{NAME}: {fixture} frame {i} U differs at 4 recon threads"
1066- );
1067- assert_eq!(
1068- a.v, b.v,
1069- "{NAME}: {fixture} frame {i} V differs at 4 recon threads"
1070- );
1071- }
1072- }
1073- }
1074-
1075- /// lane-filt1: `EC_AV1_FILTER_THREADS` splits every in-frame filter stage
1076- /// -- deblock (row bands for the vertical-edge pass, column bands for the
1077- /// horizontal one), CDEF (mi row bands), loop restoration (RU row bands)
1078- /// and film grain (32-pixel block rows) -- across scoped worker threads.
1079- /// A split is only legal if it is BYTE-EXACT, so this gate decodes two
1080- /// real aomenc streams at 1 and at 4 filter threads and compares every
1081- /// output frame's three planes.
1082- ///
1083- /// Between them the fixtures fire all four stages, and the firing
1084- /// counters are asserted rather than assumed (class `gate-blind-to-feature`):
1085- /// `superres_alltools_sb128_320x180.obu` is the 10-bit CDEF + loop
1086- /// restoration stream, `grain_cdef_lr_128x128.obu` a 128x128
1087- /// `--denoise-noise-level=25` stream whose frames carry film grain
1088- /// parameters (small enough that 4 bands is one block row each, which is
1089- /// what exercises the grain band's one-row `prelude` replay).
1090- #[test]
1091- fn a_real_stream_filters_identically_with_one_and_four_filter_threads() {
1092- const NAME: &str = "a_real_stream_filters_identically_with_one_and_four_filter_threads";
1093- let _gate_lock = lock_gate_counters();
1094- for (fixture, wants_lr, wants_grain) in [
1095- ("superres_alltools_sb128_320x180.obu", true, false),
1096- ("grain_cdef_lr_128x128.obu", false, true),
1097- ] {
1098- let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1099- .join("fixtures")
1100- .join(fixture);
1101- let stream = std::fs::read(&path)
1102- .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
1103- let before = (
1104- crate::decode::deblock_hits(),
1105- crate::restoration::wiener_hits() + crate::restoration::sgrproj_hits(),
1106- crate::film_grain::grain_hits(),
1107- );
1108- crate::par::set_filter_threads(1);
1109- let one = match decode_stream(&stream) {
1110- Ok(frames) => frames,
1111- Err(e) => panic!("{NAME}: {fixture} refused at 1 filter thread: {e}"),
1112- };
1113- let after = (
1114- crate::decode::deblock_hits(),
1115- crate::restoration::wiener_hits() + crate::restoration::sgrproj_hits(),
1116- crate::film_grain::grain_hits(),
1117- );
1118- crate::par::set_filter_threads(4);
1119- let four = match decode_stream(&stream) {
1120- Ok(frames) => frames,
1121- Err(e) => {
1122- crate::par::set_filter_threads(1);
1123- panic!("{NAME}: {fixture} refused at 4 filter threads: {e}")
1124- }
1125- };
1126- crate::par::set_filter_threads(1);
1127- assert!(
1128- after.0 > before.0,
1129- "{NAME}: {fixture} deblocked no edge at all"
1130- );
1131- if wants_lr {
1132- assert!(
1133- after.1 > before.1,
1134- "{NAME}: {fixture} ran no restoration unit"
1135- );
1136- }
1137- if wants_grain {
1138- assert!(
1139- after.2 > before.2,
1140- "{NAME}: {fixture} applied no film grain"
1141- );
1142- }
1143- assert_eq!(one.len(), four.len(), "{NAME}: {fixture} frame count");
1144- assert!(!one.is_empty(), "{NAME}: {fixture} decoded nothing");
1145- for (i, (a, b)) in one.iter().zip(four.iter()).enumerate() {
1146- assert_eq!(
1147- a.y, b.y,
1148- "{NAME}: {fixture} frame {i} luma differs at 4 filter threads"
1149- );
1150- assert_eq!(
1151- a.u, b.u,
1152- "{NAME}: {fixture} frame {i} U differs at 4 filter threads"
1153- );
1154- assert_eq!(
1155- a.v, b.v,
1156- "{NAME}: {fixture} frame {i} V differs at 4 filter threads"
1157- );
1158- }
1159- }
1160- }
1161-
1162- /// lane-t900 r30b: `fixtures/superres_alltools_sb128_320x180.obu` is 10
1163- /// frames of `--cpu-used=4 --sb-size=128 --superres-mode=1
1164- /// --superres-denominator=12 --cq-level=32` with every tool aomenc turns
1165- /// on by default (CDEF, loop restoration, OBMC, compound, warp) -- the
1166- /// first stream here that deblocks CHROMA across a group of 4x4 luma
1167- /// blocks.
1168- ///
1169- /// The defect it pins (fixed at this commit, `decode.rs`'s
1170- /// `plane_to_mi`/`edge_params`): `set_lpf_parameters`
1171- /// (`av1_loopfilter.c:245`) indexes the mi grid for a CHROMA edge at
1172- /// `scale | ((coord << scale) >> MI_SIZE_LOG2)` -- the BOTTOM/RIGHT mi of
1173- /// the co-located 8x8 luma group, the same cell that donates the group's
1174- /// chroma prediction. This decoder dropped that `| 1` and read the
1175- /// group's top-left mi, stepped to the previous cell by one mi instead of
1176- /// `1 << ss`, and priced `pu_edge` by comparing mi origins rather than
1177- /// the edge coordinate against the block size in the FILTERED plane's own
1178- /// pixels (chroma bottoms out at 4). All three are invisible while every
1179- /// block is 8x8 or larger (all four mi of a group carry the same tx size,
1180- /// ref frame, skip flag and delta_lf) and wrong the moment cpu-used=4
1181- /// splits a group into 4x4 blocks: on this stream one U sample of frame 2
1182- /// took a filter level of 12 where libaom's neighbouring 4x4 block gives
1183- /// 8, and the error compounded through the reference chain to 280 U + 331
1184- /// V samples (max 9) by frame 9. Class `context-read-from-one-cell`.
1185- ///
1186- /// Post-deblock, this stream is now byte-exact against the instrumented
1187- /// libaom (`EC_AV1_POSTDEBLOCK_DUMP`) in all 10 frames, and the final
1188- /// output matches ffmpeg's.
1189- #[test]
1190- fn a_superres_all_tools_sb128_stream_decodes_pixel_exact() {
1191- const NAME: &str = "a_superres_all_tools_sb128_stream_decodes_pixel_exact";
1192- let _gate_lock = lock_gate_counters();
1193- if !have_ffmpeg() {
1194- eprintln!("SKIP {NAME}: no ffmpeg");
1195- return;
1196- }
1197- let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1198- .join("fixtures/superres_alltools_sb128_320x180.obu");
1199- let stream = std::fs::read(&path)
1200- .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
1201- let (width, height, count) = (320usize, 180usize, 10usize);
1202- let frames = match decode_stream(&stream) {
1203- Ok(frames) => frames,
1204- Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
1205- };
1206- assert_eq!(frames.len(), count, "{NAME}: frame count");
1207- let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, count);
1208- for (i, (ours, theirs)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
1209- assert_eq!(ours.y, theirs.y, "{NAME}: frame {i} luma vs ffmpeg");
1210- assert_eq!(ours.u, theirs.u, "{NAME}: frame {i} U vs ffmpeg");
1211- assert_eq!(ours.v, theirs.v, "{NAME}: frame {i} V vs ffmpeg");
1212- }
1213- }
1214-
1215- /// lane-golomb r1: THE FILM ITSELF. `crates/ec-av1/fixtures/reelb_head_key_frame.obu`
1216- /// is the first frame of the user's ReelB AV1 release (3840x1608
1217- /// yuv420p10le, `ffmpeg -i <mkv> -c copy -frames:v 1 -f obu`, 147 bytes) --
1218- /// a real 10-bit key frame whose height is NOT a multiple of the 64-pixel
1219- /// superblock, so its last superblock row (mi_row=400 of 402) carries the
1220- /// edge partition symbol this lane fixed: libaom's `ec_read_partition_impl`
1221- /// returns `PARTITION_HORZ` when the gathered `split_or_horz` bit is 0, and
1222- /// this decoder used to READ that bit and throw it away, forcing SPLIT
1223- /// (class `parsed-then-discarded`). The desync surfaced two rows later as
1224- /// "a Golomb tail longer than this decoder reads" -- a refusal naming the
1225- /// symptom, never the cause.
1226- #[test]
1227- fn the_reelb_head_key_frame_decodes_pixel_exact() {
1228- const NAME: &str = "the_reelb_head_key_frame_decodes_pixel_exact";
1229- if !have_ffmpeg() {
1230- eprintln!("SKIP {NAME}: no ffmpeg");
1231- return;
1232- }
1233- let path =
1234- std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures/reelb_head_key_frame.obu");
1235- let stream = std::fs::read(&path)
1236- .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
1237- let (width, height) = (3840usize, 1608usize);
1238- let frames = match decode_stream(&stream) {
1239- Ok(frames) => frames,
1240- Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
1241- };
1242- assert_eq!(frames.len(), 1, "{NAME}: one key frame");
1243- assert_eq!((frames[0].width, frames[0].height), (width, height));
1244- let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
1245- assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
1246- assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg");
1247- assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg");
1248- }
1249-
1250- /// lane-reelckf r2: `crates/ec-av1/fixtures/reelc_kf2700.obu` is a 1920x792
1251- /// 10-bit AV1 key frame taken out of one of the user's own films
1252- /// (`ffmpeg -ss 2700 -c:v copy -f obu`, then truncated to its first temporal
1253- /// unit, 36 kB) -- the ONLY stream in this repo that contains a SKIPPED
1254- /// `UV_CFL_PRED` block. 30 aomenc recipes (r1's 20 plus r2's chroma-correlated
1255- /// `geq` sweep, cq 40..63, cpu-used 0..2, min/max-partition 4..64, 8 and
1256- /// 10 bit) never made the encoder pick one, so the counter can only be
1257- /// hard-asserted against a real film frame. The instrumented oracle agrees:
1258- /// `EC_TRACE_MODE=1 aomdec` prints 5 `EC_IMODE_VAL ... uv_mode=13 skip=1`
1259- /// lines for this frame.
1260- ///
1261- /// The defect it pins (fixed at 29cd53f, `decode.rs:7719`/`:10528`/`:10891`):
1262- /// a skipped intra block must still PREDICT with CfL -- libaom's
1263- /// `predict_and_reconstruct_intra_block` predicts every plane and guards only
1264- /// the residual on `skip_txfm`. Before the fix this frame had 499 wrong
1265- /// chroma samples (U rows 48..79 cols 464..492); after it, zero.
1266- ///
1267- /// The ffmpeg reference is `ffmpeg -f obu -i <fixture> -f rawvideo
1268- /// -pix_fmt yuv420p10le -` (what `ffmpeg_decode_sequence_10bit` runs).
1269- #[test]
1270- fn a_real_film_key_frame_with_a_skipped_cfl_block_decodes_pixel_exact() {
1271- const NAME: &str = "a_real_film_key_frame_with_a_skipped_cfl_block_decodes_pixel_exact";
1272- let path =
1273- std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures/reelc_kf2700.obu");
1274- let stream = std::fs::read(&path)
1275- .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
1276- let (width, height) = (1920usize, 792usize);
1277- let before = crate::decode::reelc_chroma_counters();
1278- let frames = match decode_stream(&stream) {
1279- Ok(frames) => frames,
1280- Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
1281- };
1282- let after = crate::decode::reelc_chroma_counters();
1283- let skip_cfl = after.0 - before.0;
1284- assert_eq!(frames.len(), 1, "{NAME}: one key frame");
1285- assert_eq!((frames[0].width, frames[0].height), (width, height));
1286- // Asserted before the ffmpeg compare so an absent ffmpeg cannot make the
1287- // gate vacuous: the skipped-CfL path is exercised on every run.
1288- assert!(
1289- skip_cfl > 0,
1290- "{NAME}: zero skipped-CfL blocks -- the fixture no longer exercises defect 1"
1291- );
1292- if !have_ffmpeg() {
1293- eprintln!("SKIP {NAME} pixel compare: no ffmpeg (skipped_cfl={skip_cfl})");
1294- return;
1295- }
1296- let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
1297- assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
1298- assert_eq!(
1299- frames[0].u, ffmpeg_frames[0].u,
1300- "{NAME}: U vs ffmpeg ({skip_cfl} skipped-CfL blocks)"
1301- );
1302- assert_eq!(
1303- frames[0].v, ffmpeg_frames[0].v,
1304- "{NAME}: V vs ffmpeg ({skip_cfl} skipped-CfL blocks)"
1305- );
1306- eprintln!("{NAME}: pixel-exact, skipped_cfl={skip_cfl}");
1307- }
1308-
1309- /// lane-kf1200 r2: the same film's `-ss 300` key frame, pinned because no
1310- /// aomenc recipe reaches its shape -- a SKIPPED sub-8x8 chroma block whose
1311- /// `uv_mode` is `UV_CFL_PRED`. (lane-reelckf r1 burned 20 recipes across cq
1312- /// 40..63 and nine lavfi sources hunting exactly this block and never got
1313- /// one; ledger dead-end "never produced a SKIPPED 1:4 or sub-8x8 CfL
1314- /// block".) Before the fix the two sub-8x8 skip arms passed `None` for the
1315- /// CfL argument, so the block reconstructed as flat DC and 463 bytes of
1316- /// this frame's chroma were wrong. HARD-asserts `skip_cfl_hits` moved, so
1317- /// the fixture cannot silently stop exercising the arm.
1318- #[test]
1319- fn the_reelb_ss300_key_frame_skipped_cfl_decodes_pixel_exact() {
1320- const NAME: &str = "the_reelb_ss300_key_frame_skipped_cfl_decodes_pixel_exact";
1321- if !have_ffmpeg() {
1322- eprintln!("SKIP {NAME}: no ffmpeg");
1323- return;
1324- }
1325- let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1326- .join("fixtures/reelb_ss300_key_frame.obu");
1327- let stream = std::fs::read(&path)
1328- .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
1329- let (width, height) = (3840usize, 1608usize);
1330- let before = crate::decode::skip_cfl_hits();
1331- let frames = match decode_stream(&stream) {
1332- Ok(frames) => frames,
1333- Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
1334- };
1335- let skipped_cfl = crate::decode::skip_cfl_hits() - before;
1336- assert!(
1337- skipped_cfl > 0,
1338- "{NAME}: zero skipped sub-8x8 CfL blocks -- the fixture no longer \
1339- exercises the arm this test exists for"
1340- );
1341- assert_eq!(frames.len(), 1, "{NAME}: one key frame");
1342- assert_eq!((frames[0].width, frames[0].height), (width, height));
1343- let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
1344- assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
1345- assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg");
1346- assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg");
1347- eprintln!("{NAME}: {skipped_cfl} skipped sub-8x8 CfL chroma blocks, frame pixel-exact");
1348- }
1349-
1350- /// lane-kf900 r2: the film's key frame at -ss 900, one frame
1351- /// (`crates/ec-av1/fixtures/reelb_kf900.obu`, 484640 bytes, sha256
1352- /// `a273ae99328388be14a1ff8fa1c5a6d391a9948159eaef120e1b50e02015eb83`,
1353- /// extracted twice from independent
1354- /// `ffmpeg -ss 900 -t 2 -i <2160p AV1 HDR10 mkv> -c:v copy -f obu` runs and
1355- /// truncated to the first frame; both extracts hashed identically).
1356- ///
1357- /// This is the ONLY stream that reaches the r1 defect: a SKIPPED 8x8 intra
1358- /// leaf whose `tx_depth` symbol resolved to `TX_4X4` still publishes 4 --
1359- /// not its 8-pixel block side -- to the next block's `get_tx_size_context`
1360- /// (`set_txfm_ctxs(mbmi->tx_size, bw, bh, skip_txfm && is_inter_block(...))`,
1361- /// `decodemv.c`; the skip term is 0 for intra). It fires 15 times here and
1362- /// zero times across 108 measured aomenc recipes, so the counter is
1363- /// asserted against the film rather than against a synthesised stream.
1364- ///
1365- /// LUMA only. U/V still differ (open residue, lane-kf900 r2: 221 U and
1366- /// 47912 V samples, max |d| 23/2, first at chroma (195, 640) -- chroma
1367- /// RESIDUAL, the prediction there is bit-exact against aomdec's
1368- /// `EC_PREDOUT`), so this gate pins what is proven and no more.
1369- #[test]
1370- fn a_10bit_key_frame_with_skipped_8x8_intra_leaves_that_split_their_transform_decodes_luma_exact()
1371- {
1372- const NAME: &str = "a_10bit_key_frame_with_skipped_8x8_intra_leaves_that_split_their_transform_decodes_luma_exact";
1373- if !have_ffmpeg() {
1374- eprintln!("SKIP {NAME}: no ffmpeg");
1375- return;
1376- }
1377- let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures/reelb_kf900.obu");
1378- let stream = std::fs::read(&path)
1379- .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
1380- let (width, height) = (3840usize, 1608usize);
1381- crate::decode::reset_skip_split_tx_hits();
1382- let frames = match decode_stream(&stream) {
1383- Ok(frames) => frames,
1384- Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
1385- };
1386- assert_eq!(frames.len(), 1, "{NAME}: one key frame");
1387- assert_eq!((frames[0].width, frames[0].height), (width, height));
1388- assert!(
1389- crate::decode::skip_split_tx_hits() >= 15,
1390- "{NAME}: skip_split_tx_hits() == {} -- the stream that carries the tx-context \
1391- defect stopped carrying it, so this gate proves nothing",
1392- crate::decode::skip_split_tx_hits()
1393- );
1394- let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
1395- assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
1396- }
1397-
1398- /// lane-kf1200 r3: the same film's `-ss 600` key frame (3840x1608, one
1399- /// 8-px partial bottom superblock row), pinned because no aomenc recipe
1400- /// reaches its shape -- a SKIPPED 8x8 intra leaf whose `tx_depth` resolved
1401- /// to TX_4X4. (80 recipes swept this round: 4 frame shapes x 2 sources x
1402- /// cq 32..63 x cpu-used 0/3 x 8/10-bit, all with
1403- /// `--enable-tx-size-search=1 --enable-filter-intra=1`; every one came
1404- /// back with `skip_split_tx_hits == 0`, `lanes/kf1200-r3.report.md`.)
1405- /// An intra block reads `tx_depth` whether or not it is skipped, so the
1406- /// leaf must record its resolved 4 -- not its 8x8 side -- in the txfm
1407- /// context; recording 8 gave the NEXT block's `tx_depth` symbol the wrong
1408- /// `tx_size_cdf` row (ctx 2 where libaom reads 1) and desynced the
1409- /// entropy stream at mi (400,46). HARD-asserts `skip_split_tx_hits` moved.
1410- #[test]
1411- fn the_reelb_ss600_key_frame_skipped_split_tx_decodes_pixel_exact() {
1412- const NAME: &str = "the_reelb_ss600_key_frame_skipped_split_tx_decodes_pixel_exact";
1413- if !have_ffmpeg() {
1414- eprintln!("SKIP {NAME}: no ffmpeg");
1415- return;
1416- }
1417- let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1418- .join("fixtures/reelb_ss600_key_frame.obu");
1419- let stream = std::fs::read(&path)
1420- .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
1421- let (width, height) = (3840usize, 1608usize);
1422- crate::decode::reset_skip_split_tx_hits();
1423- let frames = match decode_stream(&stream) {
1424- Ok(frames) => frames,
1425- Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
1426- };
1427- let skipped_split_tx = crate::decode::skip_split_tx_hits();
1428- assert!(
1429- skipped_split_tx > 0,
1430- "{NAME}: zero skipped 8x8 leaves with a split transform -- the fixture no longer \
1431- exercises the arm this test exists for"
1432- );
1433- assert_eq!(frames.len(), 1, "{NAME}: one key frame");
1434- assert_eq!((frames[0].width, frames[0].height), (width, height));
1435- let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
1436- assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
1437- assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg");
1438- assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg");
1439- eprintln!("{NAME}: {skipped_split_tx} skipped 8x8 TX_4X4 leaves, frame pixel-exact");
1440- }
1441-
1442- /// lane-hbd10 r1: a real `aomenc --bit-depth=10 --superres-mode=1
1443- /// --superres-denominator=12` key frame, decoded pixel-exact against
1444- /// ffmpeg's own 10-bit decode. Proves `superres::upscale_row`'s
1445- /// `clip_pixel_highbd` clamp (`(1 << bit_depth) - 1`) on real 10-bit
1446- /// planes rather than the old `bit_depth != 8` refusal. HARD-asserts
1447- /// `bit_depth == 10` and `superres_hits > 0`.
1448- #[test]
1449- fn a_real_aomenc_10bit_superres_stream_decodes_pixel_exact() {
1450- const NAME: &str = "a_real_aomenc_10bit_superres_stream_decodes_pixel_exact";
1451- if !have_ffmpeg() {
1452- eprintln!("SKIP {NAME}: no ffmpeg");
1453- return;
1454- }
1455- if !have_aomenc() {
1456- eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
1457- return;
1458- }
1459- let (width, height) = (64usize, 64usize);
1460- let stream = encode_10bit_gradients(
1461- NAME,
1462- width,
1463- height,
1464- 1,
1465- &[
1466- "--limit=1",
1467- "--kf-max-dist=0",
1468- "--superres-mode=1",
1469- "--superres-denominator=12",
1470- "--superres-kf-denominator=12",
1471- "--enable-rect-partitions=0",
1472- "--enable-ab-partitions=0",
1473- "--enable-1to4-partitions=0",
1474- "--enable-filter-intra=0",
1475- "--enable-smooth-intra=0",
1476- "--enable-paeth-intra=0",
1477- "--enable-directional-intra=0",
1478- "--enable-angle-delta=0",
1479- "--enable-tx-size-search=0",
1480- "--enable-cdef=0",
1481- "--enable-restoration=0",
1482- "--max-partition-size=32",
1483- "--min-partition-size=32",
1484- "--enable-palette=0",
1485- "--enable-intrabc=0",
1486- "--enable-cfl-intra=0",
1487- ],
1488- );
1489- assert_eq!(
1490- parsed_bit_depth(&stream),
1491- 10,
1492- "{NAME}: aomenc did not actually write a 10-bit sequence header"
1493- );
1494- let before = crate::superres::superres_hits();
1495- let frames = match decode_stream(&stream) {
1496- Ok(frames) => frames,
1497- Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
1498- };
1499- assert!(
1500- crate::superres::superres_hits() > before,
1501- "{NAME}: matched but zero superres_hits -- the upscaler never ran"
1502- );
1503- let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
1504- assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
1505- assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg");
1506- assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg");
1507- eprintln!(
1508- "{NAME}: pixel-exact, superres_hits={}",
1509- crate::superres::superres_hits()
1510- );
1511- }
1512-
1513- /// lane-hbdgates r1: the four intra tools that had an 8-bit gate and no
1514- /// 10-bit one (`filter-intra`, `smooth-intra`, `paeth-intra`,
1515- /// `intra-edge-filter`) on ONE real 10-bit `aomenc` key frame, each with
1516- /// its own hard-asserted counter. His two films are yuv420p10le, so an
1517- /// 8-bit-only gate for these tools proves nothing about the streams that
1518- /// matter (lane-covbd r1).
1519- #[test]
1520- fn a_real_aomenc_10bit_intra_tools_stream_decodes_pixel_exact() {
1521- const NAME: &str = "a_real_aomenc_10bit_intra_tools_stream_decodes_pixel_exact";
1522- if !have_ffmpeg() {
1523- eprintln!("SKIP {NAME}: no ffmpeg");
1524- return;
1525- }
1526- if !have_aomenc() {
1527- eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
1528- return;
1529- }
1530- ten_bit_tool_gate(
1531- NAME,
1532- 64,
1533- 64,
1534- 1,
1535- &[
1536- "--limit=1",
1537- "--kf-max-dist=0",
1538- "--enable-filter-intra=1",
1539- "--enable-smooth-intra=1",
1540- "--enable-paeth-intra=1",
1541- "--enable-intra-edge-filter=1",
1542- "--enable-directional-intra=1",
1543- "--enable-angle-delta=0",
1544- "--enable-rect-partitions=0",
1545- "--enable-ab-partitions=0",
1546- "--enable-1to4-partitions=0",
1547- "--enable-tx-size-search=0",
1548- "--enable-cdef=0",
1549- "--enable-restoration=0",
1550- "--max-partition-size=32",
1551- "--min-partition-size=16",
1552- "--enable-palette=0",
1553- "--enable-intrabc=0",
1554- "--enable-cfl-intra=0",
1555- "--enable-ref-frame-mvs=0",
1556- ],
1557- &[42, 7, 11, 23, 31, 57],
1558- &[
1559- ("filter_intra_hits", decode::filter_intra_hits),
1560- ("smooth_pred_hits", crate::intra::smooth_pred_hits),
1561- ("paeth_pred_hits", crate::intra::paeth_pred_hits),
1562- (
1563- "intra_edge_filter_hits",
1564- crate::intra::intra_edge_filter_hits,
1565- ),
1566- ],
1567- );
1568- }
1569-
1570- /// lane-hbdgates r1: `--enable-restoration=1` at 10 bits. Every earlier
1571- /// bit-depth gate ran `--enable-restoration=0`, which is exactly why two
1572- /// high-bit-depth loop-restoration defects survived to 2026-09-01
1573- /// (SGR box sums unscaled, Wiener clamp at the 8-bit bound). Same recipe
1574- /// as the 8-bit LR gate, at 10 bits.
1575- // Written `#[ignore]`d on lane-hbdgates (the branch lacked lane-hbdinter's
1576- // 10-bit LR fix and failed at seed 42, frame 0, Y index 122: ours 351 vs
1577- // ffmpeg 350). Un-ignored on the merge into main 2026-09-01, where the
1578- // SGR box-sum scaling and the Wiener clamp are fixed: 16/16 attempts
1579- // pixel-exact, lr_hits=28.
1580- #[test]
1581- fn a_real_aomenc_10bit_restoration_stream_decodes_pixel_exact() {
1582- const NAME: &str = "a_real_aomenc_10bit_restoration_stream_decodes_pixel_exact";
1583- if !have_ffmpeg() {
1584- eprintln!("SKIP {NAME}: no ffmpeg");
1585- return;
1586- }
1587- if !have_aomenc() {
1588- eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
1589- return;
1590- }
1591- // 192x128 = 3x2 superblocks, so `read_lr` is re-entered per SB
1592- // (the 8-bit LR gate's own trap warning); cq-level=15 because
1593- // aomenc's RD only picks a non-RESTORE_NONE frame type at low cq.
1594- ten_bit_tool_gate(
1595- NAME,
1596- 192,
1597- 128,
1598- 1,
1599- &[
1600- "--limit=1",
1601- "--kf-max-dist=0",
1602- "--cq-level=15",
1603- "--enable-restoration=1",
1604- "--enable-cdef=0",
1605- "--enable-rect-partitions=0",
1606- "--enable-ab-partitions=0",
1607- "--enable-1to4-partitions=0",
1608- "--enable-filter-intra=0",
1609- "--enable-smooth-intra=0",
1610- "--enable-paeth-intra=0",
1611- "--enable-tx-size-search=0",
1612- "--max-partition-size=32",
1613- "--min-partition-size=16",
1614- "--enable-palette=0",
1615- "--enable-intrabc=0",
1616- "--enable-cfl-intra=0",
1617- "--enable-ref-frame-mvs=0",
1618- ],
1619- &LR_SEEDS,
1620- &[("lr_hits", ten_bit_lr_hits)],
1621- );
1622- }
1623-
1624- /// lane-reelckf2 r1: loop restoration on frame sizes whose LAST stripe is
1625- /// partial, with 128-sample superblocks -- the two stripe shapes whose
1626- /// boundary substitution is special (`filter_restoration_unit`: the first
1627- /// stripe is 8 rows short and takes its above boundary from the frame's
1628- /// own top rows, the last one is truncated and takes its below boundary
1629- /// from the frame's own bottom row) had no gate at all: every earlier LR
1630- /// size (192x128, 160x96) is a whole multiple of 64 rows and ran at
1631- /// `--sb-size=64`. 152 = 2*64+24 and 216 = 3*64+24 both leave a 32-row
1632- /// tail stripe, mirroring the 792-row 10-bit film that made this lane.
1633- /// `lr_stripe0_hits`/`lr_last_stripe_hits` are hard-asserted per attempt
1634- /// by [`ten_bit_tool_gate`], so an RD that picked RESTORE_NONE on either
1635- /// stripe cannot pass.
1636- #[test]
1637- fn a_real_aomenc_10bit_partial_bottom_stripe_restoration_decodes_pixel_exact() {
1638- const NAME: &str =
1639- "a_real_aomenc_10bit_partial_bottom_stripe_restoration_decodes_pixel_exact";
1640- if !have_ffmpeg() {
1641- eprintln!("SKIP {NAME}: no ffmpeg");
1642- return;
1643- }
1644- if !have_aomenc() {
1645- eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
1646- return;
1647- }
1648- // `--sb-size=128` goes in `extra`, which the helper appends AFTER its
1649- // own `--sb-size=64` (aomenc keeps the LAST occurrence of a repeated
1650- // flag, measured 2026-09-02); `--max-partition-size=32` keeps the 128
1651- // root on SPLIT, the only 128-root partition decoded today.
1652- for (width, height, cq) in [
1653- (256usize, 152usize, "15"),
1654- (384, 216, "15"),
1655- (256, 152, "25"),
1656- ] {
1657- ten_bit_tool_gate(
1658- &format!("{NAME} {width}x{height} cq{cq}"),
1659- width,
1660- height,
1661- 1,
1662- &[
1663- "--limit=1",
1664- "--kf-max-dist=0",
1665- &format!("--cq-level={cq}"),
1666- "--sb-size=128",
1667- "--enable-restoration=1",
1668- "--enable-cdef=0",
1669- "--enable-rect-partitions=0",
1670- "--enable-ab-partitions=0",
1671- "--enable-1to4-partitions=0",
1672- "--enable-filter-intra=0",
1673- "--enable-smooth-intra=0",
1674- "--enable-paeth-intra=0",
1675- "--enable-tx-size-search=0",
1676- "--max-partition-size=32",
1677- "--min-partition-size=16",
1678- "--enable-palette=0",
1679- "--enable-intrabc=0",
1680- "--enable-cfl-intra=0",
1681- "--enable-ref-frame-mvs=0",
1682- ],
1683- &LR_SEEDS,
1684- &[
1685- ("lr_hits", ten_bit_lr_hits),
1686- ("lr_stripe0_hits", crate::restoration::lr_stripe0_hits),
1687- (
1688- "lr_last_stripe_hits",
1689- crate::restoration::lr_last_stripe_hits,
1690- ),
1691- ],
1692- );
1693- }
1694- }
1695-
1696- /// lane-hbdgates r1: `--enable-rect-partitions=1 --enable-ab-partitions=1`
1697- /// at 10 bits, one intra stream, one counter per tool
1698- /// (`rect_partition_hits`, `partab_hits`) so a stream that only fired the
1699- /// rect arms cannot stand in for AB.
1700- #[test]
1701- fn a_real_aomenc_10bit_rect_and_ab_partitions_decode_pixel_exact() {
1702- const NAME: &str = "a_real_aomenc_10bit_rect_and_ab_partitions_decode_pixel_exact";
1703- if !have_ffmpeg() {
1704- eprintln!("SKIP {NAME}: no ffmpeg");
1705- return;
1706- }
1707- if !have_aomenc() {
1708- eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
1709- return;
1710- }
1711- // The 8-bit free-partition/AB recipe, verbatim, at 10 bits: AB
1712- // splits are an INTER dispatch here (intra-frame AB is still a named
1713- // refusal), so the stream needs alt-refs and 24 frames, not one key
1714- // frame.
1715- ten_bit_tool_gate(
1716- NAME,
1717- 64,
1718- 64,
1719- 24,
1720- &[
1721- "--cq-level=45",
1722- "--kf-max-dist=1000",
1723- "--auto-alt-ref=1",
1724- "--lag-in-frames=16",
1725- "--enable-fwd-kf=0",
1726- "--enable-order-hint=1",
1727- "--enable-warped-motion=1",
1728- "--enable-obmc=1",
1729- "--tune-content=default",
1730- "--enable-masked-comp=0",
1731- "--enable-interintra-comp=0",
1732- "--enable-onesided-comp=0",
1733- "--enable-interintra-wedge=0",
1734- "--enable-smooth-interintra=0",
1735- "--enable-rect-partitions=1",
1736- "--enable-ab-partitions=1",
1737- "--enable-1to4-partitions=0",
1738- "--enable-filter-intra=0",
1739- "--enable-smooth-intra=0",
1740- "--enable-paeth-intra=0",
1741- "--enable-directional-intra=0",
1742- "--enable-angle-delta=0",
1743- "--enable-tx-size-search=0",
1744- "--enable-cdef=0",
1745- "--enable-restoration=0",
1746- "--max-partition-size=32",
1747- "--min-partition-size=16",
1748- "--enable-palette=0",
1749- "--enable-intrabc=0",
1750- "--enable-cfl-intra=0",
1751- "--enable-ref-frame-mvs=0",
1752- ],
1753- &LR_SEEDS,
1754- &[
1755- ("rect_partition_hits", decode::rect_partition_hits),
1756- ("partab_hits", decode::partab_hits),
1757- ],
1758- );
1759- }
1760-
1761- /// lane-obmcrec r1: OBMC whose above/left neighbour is a 4-wide/4-tall
1762- /// 1:4-partition strip -- the shape the three 1080p 10-bit film cuts
1763- /// refused on ("an OBMC neighbour whose switchable interp filter was never
1764- /// recorded"). `overlappable_above`/`_left` snap such a neighbour to the
1765- /// chroma pair's SECOND mi but used to read its interp filter from the
1766- /// FIRST one, a different block whose filter record is the intra
1767- /// `[3, 3]` sentinel whenever that half is intra. `obmc_pair_filter_hits`
1768- /// counts exactly that neighbour shape, so a stream without 1:4 strips
1769- /// next to an OBMC block cannot stand in for it.
1770- #[test]
1771- fn a_real_aomenc_10bit_obmc_over_1to4_strip_neighbours_decodes_pixel_exact() {
1772- const NAME: &str =
1773- "a_real_aomenc_10bit_obmc_over_1to4_strip_neighbours_decodes_pixel_exact";
1774- if !have_ffmpeg() {
1775- eprintln!("SKIP {NAME}: no ffmpeg");
1776- return;
1777- }
1778- if !have_aomenc() {
1779- eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
1780- return;
1781- }
1782- ten_bit_tool_gate(
1783- NAME,
1784- 128,
1785- 128,
1786- 24,
1787- &[
1788- "--ec-fixture-noise",
1789- "--cq-level=45",
1790- "--kf-max-dist=1000",
1791- "--auto-alt-ref=1",
1792- "--lag-in-frames=16",
1793- "--enable-fwd-kf=0",
1794- "--enable-order-hint=1",
1795- "--enable-warped-motion=0",
1796- "--enable-obmc=1",
1797- "--tune-content=default",
1798- "--enable-masked-comp=0",
1799- "--enable-interintra-comp=0",
1800- "--enable-onesided-comp=0",
1801- "--enable-interintra-wedge=0",
1802- "--enable-smooth-interintra=0",
1803- "--enable-rect-partitions=1",
1804- "--enable-ab-partitions=0",
1805- "--enable-1to4-partitions=1",
1806- "--enable-filter-intra=0",
1807- "--enable-smooth-intra=0",
1808- "--enable-paeth-intra=0",
1809- "--enable-directional-intra=0",
1810- "--enable-angle-delta=0",
1811- "--enable-tx-size-search=0",
1812- "--enable-cdef=0",
1813- "--enable-restoration=0",
1814- "--max-partition-size=32",
1815- "--min-partition-size=4",
1816- "--enable-palette=0",
1817- "--enable-intrabc=0",
1818- "--enable-cfl-intra=0",
1819- "--enable-ref-frame-mvs=0",
1820- ],
1821- &OBMC_PAIR_SEEDS,
1822- &[("obmc_pair_filter_hits", decode::obmc_pair_filter_hits)],
1823- );
1824- }
1825-
1826- /// A real `aomenc` palette-**UV** fixture (lane-palette2 r2): `testsrc2`
1827- /// (the multicoloured AV1 test pattern -- flat, few-colour, repetitive
1828- /// per-region colour *and* chroma, unlike `smptebars=hue=s=0` above,
1829- /// which flattened chroma to a single value specifically to avoid
1830- /// exercising this path). Same square-only recipe as the palette-Y gate
1831- /// (`--enable-rect-partitions=0`/`-ab-`/`-1to4-`, fixed 32x32 partition)
1832- /// so a UV palette block never lands inside the still-refused HORZ/VERT
1833- /// screen-content strip. HARD-asserts [`decode::palette_uv_hits`] moved
1834- /// -- a stream that never reads a real UV palette block would decode (or
1835- /// not) by construction without proving this milestone at all
1836- /// ([[gate-blind-to-feature]]).
1837- #[test]
1838- fn a_real_aomenc_stream_with_palette_uv_decodes_pixel_exact() {
1839- const NAME: &str = "a_real_aomenc_stream_with_palette_uv_decodes_pixel_exact";
1840- if !have_ffmpeg() {
1841- eprintln!("SKIP {NAME}: no ffmpeg");
1842- return;
1843- }
1844- if !have_aomenc() {
1845- eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
1846- return;
1847- }
1848- let source = "testsrc2=size=64x64:rate=25";
1849- fn render(source: &str) -> Vec<u8> {
1850- crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1851- .args([
1852- "-v",
1853- "error",
1854- "-f",
1855- "lavfi",
1856- "-i",
1857- source,
1858- "-pix_fmt",
1859- "yuv420p",
1860- "-t",
1861- "0.16",
1862- "-f",
1863- "yuv4mpegpipe",
1864- "-",
1865- ])
1866- .stdin(Stdio::null())
1867- .stdout(Stdio::piped())
1868- .stderr(Stdio::piped()), None, |c| c.output())
1869- .expect("ffmpeg failed to run")
1870- .stdout
1871- }
1872- let y4m_a = render(source);
1873- let y4m_b = render(source);
1874- assert_eq!(
1875- y4m_a, y4m_b,
1876- "testsrc2 must render byte-identical across two runs"
1877- );
1878- let y4m = y4m_a;
1879- let out = run_with_stdin(
1880- Command::new(aomenc_path()).args([
1881- "--codec=av1",
1882- "--passes=1",
1883- "--end-usage=q",
1884- "--cq-level=30",
1885- "--cpu-used=0",
1886- "--threads=1",
1887- "--row-mt=0",
1888- "--sb-size=64",
1889- "--tune-content=screen",
1890- "--enable-palette=1",
1891- "--enable-intrabc=0",
1892- "--enable-rect-partitions=0",
1893- "--enable-ab-partitions=0",
1894- "--enable-1to4-partitions=0",
1895- "--min-partition-size=32",
1896- "--max-partition-size=32",
1897- "--enable-filter-intra=0",
1898- "--enable-cdef=0",
1899- "--enable-restoration=0",
1900- "--enable-tx-size-search=0",
1901- "--loopfilter-control=0",
1902- "--obu",
1903- "-o",
1904- "-",
1905- "-",
1906- ]),
1907- &y4m,
1908- );
1909- assert!(
1910- out.status.success(),
1911- "aomenc refused the fixture: {}",
1912- String::from_utf8_lossy(&out.stderr)
1913- );
1914- let stream = out.stdout;
1915- let before = decode::palette_uv_hits();
1916- let frames = match decode_stream(&stream) {
1917- Ok(frames) => frames,
1918- Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
1919- };
1920- assert!(
1921- decode::palette_uv_hits() > before,
1922- "palette_uv_mode never fired decoding this stream -- gate is vacuous"
1923- );
1924- let frame_count = frames.len();
1925- let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 64, 64, frame_count);
1926- for i in 0..frame_count {
1927- assert_eq!(frames[i].y, ffmpeg_frames[i].y, "luma vs ffmpeg, frame {i}");
1928- assert_eq!(frames[i].u, ffmpeg_frames[i].u, "U vs ffmpeg, frame {i}");
1929- assert_eq!(frames[i].v, ffmpeg_frames[i].v, "V vs ffmpeg, frame {i}");
1930- }
1931- }
1932-
1933- /// A real `aomenc` fixture that lands palette syntax on a HORZ/VERT
1934- /// intra strip (lane-palette2 r5, gating r4's `read_intra_mode_rect`
1935- /// wiring). `smptebars`/`rgbtestsrc` at plain default settings both hit a
1936- /// SQUARE palette refusal or an unrelated 32x32 `HORZ_A`/`VERT_A`/etc
1937- /// partition FIRST on every size/cq combo probed -- `--enable-ab-
1938- /// partitions=0` measurably does not stop aomenc choosing one at this
1939- /// screen-content tune (byte-identical output with `=0` vs `=1`, same
1940- /// aomenc quirk as `[[lane-sbpart-r2]]`'s SB-level AB). Forcing
1941- /// `--min/max-partition-size=64` sidesteps that whole 32x32-level code
1942- /// path: the only choices left at the (single, key-frame) superblock are
1943- /// NONE/SPLIT/HORZ/VERT/AB/1to4 straight from [`decode_block_rect64`],
1944- /// and a size/cq sweep (measured live this round) reliably lands
1945- /// PARTITION_HORZ/VERT with a real (non-split-tx) palette block on both
1946- /// sources. Drives `decode_stream` directly (below any refusal) and
1947- /// HARD-asserts [`decode::palette_rect_hits`] moved on every attempt that
1948- /// didn't refuse, before comparing pixels ([[gate-blind-to-feature]]) --
1949- /// a decode that never lands a rect palette block is not a match.
1950- #[test]
1951- fn a_real_aomenc_stream_with_rect_palette_decodes_pixel_exact() {
1952- const NAME: &str = "a_real_aomenc_stream_with_rect_palette_decodes_pixel_exact";
1953- let _gate_lock = lock_gate_counters();
1954- if !have_ffmpeg() {
1955- eprintln!("SKIP {NAME}: no ffmpeg");
1956- return;
1957- }
1958- if !have_aomenc() {
1959- eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
1960- return;
1961- }
1962- let mut matched = 0u32;
1963- let mut uncounted_exact = 0u32;
1964- let mut named_refusals = 0u32;
1965- let mut attempts = 0u32;
1966- let sizes = [(64, 128), (128, 64), (128, 128), (128, 192), (192, 192)];
1967- let cqs = [5u32, 15, 25, 35, 45, 55, 63];
1968- for src_name in ["smptebars", "rgbtestsrc"] {
1969- for (width, height) in sizes {
1970- for cq in cqs {
1971- attempts += 1;
1972- let source = format!("{src_name}=size={width}x{height}:rate=25");
1973- let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1974- .args([
1975- "-v",
1976- "error",
1977- "-f",
1978- "lavfi",
1979- "-i",
1980- &source,
1981- "-pix_fmt",
1982- "yuv420p",
1983- "-t",
1984- "0.04",
1985- "-f",
1986- "yuv4mpegpipe",
1987- "-",
1988- ])
1989- .stdin(Stdio::null())
1990- .stdout(Stdio::piped())
1991- .stderr(Stdio::piped()), None, |c| c.output())
1992- .expect("ffmpeg failed to run");
1993- assert!(
1994- y4m.status.success(),
1995- "ffmpeg fixture: {}",
1996- String::from_utf8_lossy(&y4m.stderr)
1997- );
1998- let cq_arg = format!("--cq-level={cq}");
1999- let out = run_with_stdin(
2000- Command::new(aomenc_path()).args([
crates/ec-av1/src/stream/tests/t05.rsdeleted+0 -4488

Diff too large; view file

@@ -1,4488 +0,0 @@
1-use super::*;
2-use super::support::*;
3-use super::gates_a::*;
4-use crate::probe::run_with_stdin;
5-use std::process::{Command, Stdio};
6-
7- /// lane-sqdrift r2: the SQUARE-ONLY twin of the no-CFL `uv_mode` gate
8- /// above. With `--enable-rect-partitions=0` the encoder codes only
9- /// `PARTITION_NONE` and `PARTITION_SPLIT`, and on detailed content the RD
10- /// eventually hands one whole 64x64 superblock of an INTER frame to an
11- /// INTRA block -- `bsize == sb_size`, the one shape whose `uv_mode` must
12- /// come off the 13-symbol `uv_mode_no_cfl` alphabet because libaom's
13- /// `is_cfl_allowed` (`blockd.h`: `wide <= 32 && high <= 32`) excludes it.
14- ///
15- /// Before the fix this decoder read the 14-symbol CFL alphabet there: the
16- /// same `DC_PRED` value, a different interval, and the tile desynced from
17- /// that block on. r1 measured the damage on the pinned 192x128 stream
18- /// (sha256 `c6af4fb4...`): decode-order frames 0-3 pre-filter byte-exact,
19- /// frame 4 luma 3540 samples wrong over exactly the last superblock
20- /// (x 128..191, y 64..127), then 24k wrong by frame 7 -- and the decoder
21- /// did not even report a mismatch, it reported an intra-rect-strip refusal
22- /// read out of the already-desynced stream (class `refusal-from-own-desync`;
23- /// aomdec's own partition histogram over that stream is rect-free).
24- /// After the fix the same stream is byte-exact on all 8 frames.
25- ///
26- /// Distinct from the sibling gate: rect partitions OFF (so the 64x64 NONE
27- /// really is a whole superblock), `--min-partition-size=16`, natural
28- /// mandelbrot detail instead of a synthetic half-noise ramp, and 8 frames
29- /// of drift so a desync that survives one frame still fails here. Every
30- /// decode-order frame of every attempt is compared against ffmpeg, so a
31- /// mismatch of ANY shape fails; the gate never turns one into a SKIP.
32- #[test]
33- fn a_real_aomenc_square_only_inter_sequence_with_a_64x64_intra_superblock_decodes_pixel_exact()
34- {
35- const NAME: &str = "a_real_aomenc_square_only_inter_sequence_with_a_64x64_intra_superblock_decodes_pixel_exact";
36- let _gate_lock = lock_gate_counters();
37- if !have_ffmpeg() {
38- eprintln!("SKIP {NAME}: no ffmpeg");
39- return;
40- }
41- if !have_aomenc() {
42- eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
43- return;
44- }
45- let (width, height, frame_count) = (192usize, 128usize, 8usize);
46- for bit_depth in [8u32, 10u32] {
47- let (mut named_refusals, mut matched, mut carried_none) = (0u32, 0u32, 0u32);
48- let mut total_hits = 0usize;
49- for attempt in 0..4u32 {
50- // r1's pinned recipe is (start_scale 4.76, cq 55); the other
51- // three points move the detail level and the quantiser, which
52- // is what moves WHICH superblock the RD codes intra.
53- let start_scale = ["4.76", "3.20"][(attempt % 2) as usize];
54- let cq = [55, 45][(attempt / 2) as usize];
55- let duration = frame_count as f64 / 25.0;
56- let source = format!(
57- "mandelbrot=size={width}x{height}:start_scale={start_scale}:\
58- end_scale=0.004:end_pts=8:rate=25"
59- );
60- let pix_fmt = if bit_depth == 10 {
61- "yuv420p10le"
62- } else {
63- "yuv420p"
64- };
65- let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
66- .args([
67- "-v",
68- "error",
69- "-f",
70- "lavfi",
71- "-i",
72- &source,
73- "-vf",
74- "hue=s=0",
75- "-t",
76- &duration.to_string(),
77- "-pix_fmt",
78- pix_fmt,
79- "-strict",
80- "-1",
81- "-f",
82- "yuv4mpegpipe",
83- "-strict",
84- "-1",
85- "-",
86- ])
87- .stdin(Stdio::null())
88- .stdout(Stdio::piped())
89- .stderr(Stdio::piped()), None, |c| c.output())
90- .expect("ffmpeg failed to run");
91- assert!(
92- y4m.status.success(),
93- "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
94- String::from_utf8_lossy(&y4m.stderr)
95- );
96- let cq_arg = format!("--cq-level={cq}");
97- let depth_arg = format!("--bit-depth={bit_depth}");
98- let input_depth_arg = format!("--input-bit-depth={bit_depth}");
99- let args: Vec<&str> = vec![
100- "--codec=av1",
101- "--passes=1",
102- "--end-usage=q",
103- &cq_arg,
104- "--cpu-used=1",
105- "--threads=1",
106- "--row-mt=0",
107- "--sb-size=64",
108- &depth_arg,
109- &input_depth_arg,
110- "--lag-in-frames=0",
111- "--auto-alt-ref=0",
112- "--kf-min-dist=1000",
113- "--kf-max-dist=1000",
114- "--enable-rect-partitions=0",
115- "--enable-ab-partitions=0",
116- "--enable-1to4-partitions=0",
117- "--min-partition-size=16",
118- "--max-partition-size=64",
119- "--enable-tx-size-search=0",
120- "--enable-order-hint=0",
121- "--enable-warped-motion=0",
122- "--enable-obmc=0",
123- "--enable-masked-comp=0",
124- "--enable-interintra-comp=0",
125- "--enable-dist-wtd-comp=0",
126- "--enable-diff-wtd-comp=0",
127- "--enable-onesided-comp=0",
128- "--enable-interintra-wedge=0",
129- "--enable-smooth-interintra=0",
130- "--enable-filter-intra=0",
131- "--enable-smooth-intra=0",
132- "--enable-paeth-intra=0",
133- "--enable-directional-intra=0",
134- "--enable-angle-delta=0",
135- "--enable-cdef=0",
136- "--enable-restoration=0",
137- "--enable-palette=0",
138- "--enable-intrabc=0",
139- "--enable-cfl-intra=0",
140- "--enable-ref-frame-mvs=0",
141- "--obu",
142- "-o",
143- "-",
144- "-",
145- ];
146- let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
147- assert!(
148- out.status.success(),
149- "aomenc refused the fixture: {}",
150- String::from_utf8_lossy(&out.stderr)
151- );
152- let stream = out.stdout;
153- let before = crate::decode::nocfl_uv_mode_hits();
154- let frames = match decode_stream(&stream) {
155- Err(e) => {
156- let msg = e.to_string();
157- assert!(
158- msg.contains("unsupported"),
159- "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
160- attempt {attempt}): {msg}"
161- );
162- named_refusals += 1;
163- eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
164- continue;
165- }
166- Ok(frames) => frames,
167- };
168- let hits = crate::decode::nocfl_uv_mode_hits() - before;
169- let ffmpeg_frames = if bit_depth == 10 {
170- ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
171- } else {
172- ffmpeg_decode_sequence(&stream, width, height, frame_count)
173- };
174- assert_eq!(frames.len(), frame_count);
175- if hits == 0 {
176- carried_none += 1;
177- }
178- for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
179- assert_eq!(
180- got.y, want.y,
181- "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit, hits={hits})"
182- );
183- assert_eq!(
184- got.u, want.u,
185- "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit, hits={hits})"
186- );
187- assert_eq!(
188- got.v, want.v,
189- "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit, hits={hits})"
190- );
191- }
192- if hits > 0 {
193- matched += 1;
194- total_hits += hits;
195- }
196- }
197- eprintln!(
198- "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \
199- attempts carrying a 64x64 intra superblock ({total_hits} no-CFL uv_mode reads), \
200- {carried_none} attempts carried none"
201- );
202- assert!(
203- matched > 0 && total_hits > 0,
204- "{NAME} ({bit_depth}-bit): no square-only attempt decoded a 64x64 intra block \
205- inside an inter frame, so the no-CFL uv_mode alphabet was never exercised -- \
206- gate proved nothing ({named_refusals} refusals, {carried_none} carried none)"
207- );
208- }
209- }
210-
211- /// lane-mc64 r2: the RECT-ON twin of the square-only gate above, pinned
212- /// as a stream fixture because its aomenc recipe is not reproducible
213- /// (the r2 recipe re-encoded to a different file, measured md5
214- /// `278be00...` vs the fixture's `add55f6...`; class
215- /// `seeded-fixture-not-reproducible`).
216- ///
217- /// `crates/ec-av1/fixtures/av1_192x128_8bit_intra64_in_inter.obu`
218- /// (sha256 `e4cff46cb1700527c68efc866db27a2835705e949d646f73f0c9df577d594bd6`)
219- /// carries a 64x64 `PARTITION_NONE` INTRA block inside an INTER frame at
220- /// decode-order frame 2, mi(16,32), in a stream whose OTHER superblocks
221- /// are rect-partitioned -- so the 64-axis `is_cfl_allowed` narrowing
222- /// (`blockd.h`: `wide <= 32 && high <= 32`) has to hold on the intra
223- /// arm that the rect recipe reaches, not only on the whole-superblock
224- /// one. Before lane-sbrect10's fix this frame reconstructed with 3720
225- /// wrong luma samples (delta -12..+9, chroma bit-exact) and the decode
226- /// then died at frame 3 on a phantom refusal of its own desync (class
227- /// `refusal-from-own-desync`); all 6 decode-order frames are byte-exact
228- /// against the oracle now.
229- #[test]
230- fn a_pinned_rect_stream_with_a_64x64_intra_block_in_an_inter_frame_decodes_pixel_exact() {
231- const NAME: &str =
232- "a_pinned_rect_stream_with_a_64x64_intra_block_in_an_inter_frame_decodes_pixel_exact";
233- let _gate_lock = lock_gate_counters();
234- if !have_aomenc() {
235- eprintln!(
236- "SKIP {NAME}: no aomenc/aomdec oracle at {}",
237- aomenc_path().display()
238- );
239- return;
240- }
241- let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
242- .join("fixtures/av1_192x128_8bit_intra64_in_inter.obu");
243- let stream = std::fs::read(&path)
244- .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
245- let before = crate::decode::nocfl_uv_mode_hits();
246- let (frames, hidden) = decode_all_frames_vs_oracle(&stream, NAME);
247- let hits = crate::decode::nocfl_uv_mode_hits() - before;
248- assert_eq!(
249- frames, 6,
250- "{NAME}: expected 6 decode-order frames ({hidden} hidden)"
251- );
252- assert!(
253- hits > 0,
254- "{NAME}: no 64-axis intra block read the no-CFL uv_mode alphabet -- the fixture no \
255- longer carries the shape this test gates"
256- );
257- }
258-
259- /// lane-av1444chr: a 4:4:4 INTER chroma unit inherits the `tx_type` of
260- /// the luma leaf covering its OWN quadrant, not the block-level (top-left
261- /// leaf) one. `av1_get_tx_type` (`blockd.h:1287-1297`) reads
262- /// `xd->tx_type_map` at the chroma unit's own position scaled back to
263- /// luma, and `read_coeffs`' `all_zero` arm stamps `DCT_DCT` into that
264- /// leaf's cell (`decodetxb.c:199-203`) -- so a chroma unit sitting over a
265- /// luma leaf that coded NOTHING must reconstruct as DCT_DCT even when the
266- /// block's top-left leaf is `IDTX`.
267- ///
268- /// The fixture is the report's witness pinned into `fixtures/`:
269- /// `testsrc2 128x128` yuv444p 4 frames, aomenc `--profile=1 --cq-level=20
270- /// --cpu-used=2 --sb-size=64 --min-partition-size=64
271- /// --max-partition-size=64 --passes=1 --end-usage=q --threads=1 --row-mt=0
272- /// --lag-in-frames=0 --kf-max-dist=100 --limit=4 --obu`; 27933 bytes,
273- /// sha256 `a06c9f7a0862252f6ab7ebdcec340d0602e730e38089365f14747db37f8e78d5`.
274- /// Every inter block is a whole 64x64 (min=max partition 64) whose luma
275- /// var-tx tree is four TX_32X32 leaves, so each block's chroma plane is
276- /// four TX_32X32 units -- one per leaf.
277- ///
278- /// Pre-fix, decode-order frames 1/2/3 differ from the oracle in 777/640/554
279- /// V samples (luma and U exact) and the per-unit type census disagrees at
280- /// exactly the units over the skipped leaf: V(0,32) of block mi(0,0) in
281- /// frame 1, V(64,96) of block mi(16,16) in every inter frame. Post-fix all
282- /// 136 non-empty inter units agree with the oracle's `EC_DQCOEFF` type and
283- /// every frame is byte-exact.
284- ///
285- /// The non-vacuity bar is the DIFFERS counter, not the route counter: a
286- /// route counter fires on every four-unit chroma read (96 of them here)
287- /// and stayed green through a no-op fix that changed zero pixels, because
288- /// on a block whose four leaves agree the per-quadrant resolve and the
289- /// block-level value are the same answer. The number that says the resolve
290- /// CHANGED something is 8 on this stream -- the four skipped-leaf quadrants
291- /// (two of them in decode-order frame 1), each resolved once per chroma
292- /// plane -- and it must be 0 on the 4:2:0 control below, since the arm is
293- /// unreachable at 4:2:0.
294- #[test]
295- fn a_pinned_444_inter_stream_chroma_units_inherit_their_own_quadrants_tx_type() {
296- const NAME: &str =
297- "a_pinned_444_inter_stream_chroma_units_inherit_their_own_quadrants_tx_type";
298- const FIXTURE_LEN: usize = 27933;
299- const FIXTURE_FNV: u64 = 0x85fa_830b_8800_90df;
300- let _gate_lock = lock_gate_counters();
301- if !have_aomenc() {
302- eprintln!(
303- "SKIP {NAME}: no aomenc/aomdec oracle at {}",
304- aomenc_path().display()
305- );
306- return;
307- }
308- let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
309- .join("fixtures/444_quad_leaf_tx_type.obu");
310- let stream = std::fs::read(&path)
311- .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
312- assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: fixture length moved");
313- assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: fixture bytes moved");
314-
315- let quad0 = crate::decode::chroma_quad_leaf_tx_hits();
316- let diff0 = crate::decode::chroma_quad_leaf_tx_diff_hits();
317- let (frames, hidden) = decode_all_frames_vs_oracle(&stream, NAME);
318- let quad = crate::decode::chroma_quad_leaf_tx_hits() - quad0;
319- let diff = crate::decode::chroma_quad_leaf_tx_diff_hits() - diff0;
320- assert_eq!(
321- frames, 4,
322- "{NAME}: expected 4 decode-order frames ({hidden} hidden)"
323- );
324- assert!(
325- quad >= 2 * diff && quad > 0,
326- "{NAME}: no chroma unit took its type from the covering luma leaf \
327- (quad {quad}, differs {diff}) -- the corrected route never ran"
328- );
329- assert!(
330- diff >= 2,
331- "{NAME}: the per-quadrant resolve never CHANGED an answer (diff {diff}; measured 4 \
332- on this stream, 2 of them in decode-order frame 1). A route counter alone is not a \
333- witness: it fires on every four-unit chroma read, including the \
334- blocks whose four leaves all agree -- the exact shape a no-op fix looked green on."
335- );
336- eprintln!("{NAME}: quad-resolved chroma units {quad}, of which {diff} differed");
337-
338- // 4:2:0 control: the same decode, same counters, zero differences --
339- // the four-unit arm is the 4:4:4 (`ss 0/0`) route only.
340- let control = std::fs::read(
341- std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
342- .join("fixtures/av1_192x128_8bit_intra64_in_inter.obu"),
343- )
344- .unwrap_or_else(|e| panic!("{NAME}: reading the 4:2:0 control: {e}"));
345- let c_quad0 = crate::decode::chroma_quad_leaf_tx_hits();
346- let c_diff0 = crate::decode::chroma_quad_leaf_tx_diff_hits();
347- let c_frames = decode_stream(&control)
348- .unwrap_or_else(|e| panic!("{NAME}: the 4:2:0 control no longer decodes: {e}"))
349- .len();
350- let c_quad = crate::decode::chroma_quad_leaf_tx_hits() - c_quad0;
351- let c_diff = crate::decode::chroma_quad_leaf_tx_diff_hits() - c_diff0;
352- assert!(c_frames > 0, "{NAME}: the 4:2:0 control decoded no frames");
353- assert_eq!(
354- (c_quad, c_diff),
355- (0, 0),
356- "{NAME}: the 4:2:0 control fired the 4:4:4 four-unit route ({c_quad} units, {c_diff} \
357- differing) -- the counter is not specific to the route it claims to witness"
358- );
359- }
360-
361- /// lane-av1f9singleland: `decode_inter_block` has TWO textually parallel
362- /// copies of the 4:4:4 four-unit chroma arm -- the compound prediction
363- /// arm (the `build` closure) and the single-reference arm. Both resolve
364- /// each unit's `tx_type` through `covering_leaf_tx_type` over a
365- /// `leaf_tx_types` list collected at EVERY size, both bumped the same
366- /// `CHROMA_QUAD_LEAF_TX_HITS` / `..._DIFF_HITS` pair, and the gate above
367- /// asserts only that pair. So that gate cannot say which arm its witness
368- /// came from, and the two arms can be reverted independently.
369- ///
370- /// Measured on the gate's own witness `fixtures/444_quad_leaf_tx_type.obu`
371- /// (the census is the point of this test, so it is quoted rather than
372- /// assumed): 96 chroma units resolve through their covering luma leaf, of
373- /// which 88 are the single-reference arm's and 8 the compound arm's; of
374- /// the 8 units whose resolved type DIFFERS from the block-level one --
375- /// the non-vacuity bar, since a block whose four leaves agree makes the
376- /// per-quadrant resolve a no-op -- ALL 8 are the single-reference arm's.
377- /// The shared counters' non-vacuity number is therefore 100%
378- /// single-reference, and the compound arm contributes 8 of 96 route hits
379- /// and none of the 8 that change an answer.
380- ///
381- /// The other 27 pinned 4:4:4 fixtures in this tree reach the arm zero
382- /// times (`444_intrabc_rect4_witness`, `444_leaf8_oob`,
383- /// `444_lossy_rect4_*`, `444_lossy_superres_*`, `444_sb128rect_lr_witness`,
384- /// and every `ll444_*`), so this one witness is the only thing pinning
385- /// the single-reference copy of the arm at all.
386- ///
387- /// Non-vacuity, per the mutation recorded in
388- /// `lanes/av1f9singleland.report.md`: reverting ONLY this arm's
389- /// `Some(cu_tx_type)` to `Some(luma_tx_type)` turns this gate red on
390- /// decode-order frame 1 with 777 bytes differing; gating ONLY this arm's
391- /// leaf push back behind `if side > 64` (the pre-`6c33f204` state) turns
392- /// it red with the same 777 bytes.
393- #[test]
394- fn the_pinned_444_quadrant_witness_is_the_single_reference_arms_and_not_only_the_compound_arms()
395- {
396- const NAME: &str = "the_pinned_444_quadrant_witness_is_the_single_reference_arms_and_not_only_the_compound_arms";
397- const FIXTURE_LEN: usize = 27933;
398- const FIXTURE_FNV: u64 = 0x85fa_830b_8800_90df;
399- let _gate_lock = lock_gate_counters();
400- let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
401- .join("fixtures/444_quad_leaf_tx_type.obu");
402- let stream = std::fs::read(&path)
403- .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
404- assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: fixture length moved");
405- assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: fixture bytes moved");
406-
407- let q0 = crate::decode::chroma_quad_leaf_tx_hits();
408- let s0 = crate::decode::chroma_quad_leaf_tx_singleref_hits();
409- let sd0 = crate::decode::chroma_quad_leaf_tx_singleref_diff_hits();
410- let frames = decode_stream(&stream)
411- .unwrap_or_else(|e| panic!("{NAME}: the witness no longer decodes: {e}"))
412- .len();
413- assert_eq!(frames, 4, "{NAME}: expected 4 shown frames");
414- let quad = crate::decode::chroma_quad_leaf_tx_hits() - q0;
415- let singleref = crate::decode::chroma_quad_leaf_tx_singleref_hits() - s0;
416- let sr_diff = crate::decode::chroma_quad_leaf_tx_singleref_diff_hits() - sd0;
417-
418- assert!(
419- singleref > quad / 2,
420- "{NAME}: the single-reference arm resolved {singleref} of {quad} covering-leaf chroma \
421- units -- the shared counter is no longer dominated by the arm this gate witnesses, so \
422- a revert of the single-reference copy would leave the shared total comfortably non-zero"
423- );
424- assert!(
425- sr_diff >= 2,
426- "{NAME}: the single-reference arm's per-quadrant resolve never CHANGED an answer \
427- (differing {sr_diff}). A route count alone is not a witness: it fires on every \
428- four-unit chroma read, including the blocks whose four luma leaves all agree -- the \
429- exact shape a no-op resolve looks green on."
430- );
431- eprintln!(
432- "{NAME}: {singleref} of {quad} covering-leaf units are the single-reference arm's, \
433- {sr_diff} of which changed an answer"
434- );
435-
436- // 4:2:0 control, as in the gate above: the four-unit arm is the 4:4:4
437- // (`ss 0/0`) route only, so the single-reference arm's own counters
438- // must stay at exactly 0 there too.
439- let control = std::fs::read(
440- std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
441- .join("fixtures/av1_192x128_8bit_intra64_in_inter.obu"),
442- )
443- .unwrap_or_else(|e| panic!("{NAME}: reading the 4:2:0 control: {e}"));
444- let c_s0 = crate::decode::chroma_quad_leaf_tx_singleref_hits();
445- let c_sd0 = crate::decode::chroma_quad_leaf_tx_singleref_diff_hits();
446- let c_frames = decode_stream(&control)
447- .unwrap_or_else(|e| panic!("{NAME}: the 4:2:0 control no longer decodes: {e}"))
448- .len();
449- assert!(c_frames > 0, "{NAME}: the 4:2:0 control decoded no frames");
450- assert_eq!(
451- (
452- crate::decode::chroma_quad_leaf_tx_singleref_hits() - c_s0,
453- crate::decode::chroma_quad_leaf_tx_singleref_diff_hits() - c_sd0,
454- ),
455- (0, 0),
456- "{NAME}: the 4:2:0 control fired the single-reference arm's four-unit route -- the \
457- counter is not specific to the route it claims to witness"
458- );
459- }
460-
461- /// lane-av1chrtx: the SIBLING of lane-av1444chr's four-unit arm -- a RECT
462- /// inter block's chroma plane, read by `read_inter_rect_chroma`. That
463- /// helper was left handing every unit the block-level `luma_tx_type`
464- /// (the top-left leaf's type) after the four-unit arms were pointed at
465- /// `covering_leaf_tx_type`, so a rect block whose chroma plane splits
466- /// (`nx*ny > 1`) over MIXED var-tx leaves read the wrong type per unit.
467- ///
468- /// The witness is pinned into `fixtures/`: `testsrc2 256x256` yuv444p 3
469- /// frames, aomenc `--profile=1 --cq-level=30 --cpu-used=0 --sb-size=64
470- /// --min-partition-size=32 --max-partition-size=64 --enable-tx-size-search=1
471- /// --passes=1 --end-usage=q --threads=1 --row-mt=0 --lag-in-frames=0
472- /// --kf-max-dist=100 --limit=3 --obu`; 26839 bytes, sha256
473- /// `06174a66e92aaeb751a8e86db59711fcb1f18d74bde2d77e1ef1be7983eb7c80`.
474- /// Its one qualifying block is the 32x64 inter strip at mi(32,48): a
475- /// 4:4:4 chroma plane of (32,64) = TWO TX_32X32 units, over a luma tree
476- /// of five leaves -- `Idtx` (32x32) on top, then `VDct`/`DctDct`/`HDct`/
477- /// `VDct` 16x16 leaves. The lower chroma unit therefore inherits `VDct`
478- /// where the block-level value is `Idtx`.
479- ///
480- /// Getting a witness at all took a bounded hunt (200+ encodes): `multi`
481- /// is false by construction at 4:2:0 (a `side <= 64` block's chroma plane
482- /// is at most 32x32 = one unit), so the arm needs 4:4:4 AND a rect block
483- /// that keeps a 64-px axis, AND `--cpu-used=0` with `--min-partition-size=32`
484- /// to make aomenc actually pick the 32x64 strip.
485- ///
486- /// The non-vacuity bar is the DIFFERS counter, not the route counter: the
487- /// control below is a committed 4:4:4 rect stream where the route fires
488- /// and still changes nothing, because that block's leaves agree.
489- #[test]
490- fn a_pinned_444_rect_inter_stream_resolves_each_chroma_unit_from_its_own_luma_leaf() {
491- const NAME: &str =
492- "a_pinned_444_rect_inter_stream_resolves_each_chroma_unit_from_its_own_luma_leaf";
493- const FIXTURE_LEN: usize = 26839;
494- const FIXTURE_FNV: u64 = 0xc77f_310c_036d_ff73;
495- let _gate_lock = lock_gate_counters();
496- if !have_aomenc() {
497- eprintln!(
498- "SKIP {NAME}: no aomenc/aomdec oracle at {}",
499- aomenc_path().display()
500- );
501- return;
502- }
503- let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
504- .join("fixtures/444_rect_strip_leaf_tx_type.obu");
505- let stream = std::fs::read(&path)
506- .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
507- assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: fixture length moved");
508- assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: fixture bytes moved");
509-
510- let hits0 = crate::decode::chroma_rect_leaf_tx_hits();
511- let diff0 = crate::decode::chroma_rect_leaf_tx_diff_hits();
512- let (frames, hidden) = decode_all_frames_vs_oracle(&stream, NAME);
513- let hits = crate::decode::chroma_rect_leaf_tx_hits() - hits0;
514- let diff = crate::decode::chroma_rect_leaf_tx_diff_hits() - diff0;
515- assert_eq!(
516- frames, 3,
517- "{NAME}: expected 3 decode-order frames ({hidden} hidden)"
518- );
519- assert!(
520- hits >= 2 * diff && hits > 0,
521- "{NAME}: no rect chroma unit took its type from the covering luma leaf (hits {hits}, \
522- differs {diff}) -- the corrected route never ran"
523- );
524- assert!(
525- diff >= 2,
526- "{NAME}: the per-unit resolve never CHANGED an answer (diff {diff}; measured 2 on this \
527- stream, one per chroma plane). A route counter alone is not a witness: the control \
528- below fires it and changes nothing."
529- );
530- eprintln!(
531- "{NAME}: rect chroma units resolved from their own leaf {hits}, of which {diff} differed"
532- );
533-
534- // Control: a committed 4:4:4 rect stream where the SAME route fires
535- // and every resolved type equals the block-level one -- the shape a
536- // no-op fix would also be green on.
537- let control = std::fs::read(
538- std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
539- .join("fixtures/444_sb128rect_lr_witness.obu"),
540- )
541- .unwrap_or_else(|e| panic!("{NAME}: reading the rect-strip control: {e}"));
542- let c_hits0 = crate::decode::chroma_rect_leaf_tx_hits();
543- let c_diff0 = crate::decode::chroma_rect_leaf_tx_diff_hits();
544- let c_frames = decode_stream(&control)
545- .unwrap_or_else(|e| panic!("{NAME}: the rect-strip control no longer decodes: {e}"))
546- .len();
547- let c_hits = crate::decode::chroma_rect_leaf_tx_hits() - c_hits0;
548- let c_diff = crate::decode::chroma_rect_leaf_tx_diff_hits() - c_diff0;
549- assert!(
550- c_frames > 0,
551- "{NAME}: the rect-strip control decoded no frames"
552- );
553- assert!(
554- c_hits > 0 && c_diff == 0,
555- "{NAME}: the rect-strip control fired the route {c_hits} times with {c_diff} differing \
556- types -- expected the single-unit/same-type shape (route fires, nothing changes)"
557- );
558- }
559-
560- /// lane-av1ichromatx: the LAST site in `decode_inter_block` that can hand a
561- /// chroma unit the BLOCK-level `luma_tx_type` instead of the unit's own
562- /// `tx_type_map` cell is [`read_inter_rect_chroma`]'s fallback: the branch
563- /// taken when `covering_leaf_tx_type` finds no luma leaf covering the
564- /// unit's own MI cell. The decode closes it with an assertion (a
565- /// multi-unit chroma plane may only reach the fallback when the block
566- /// coded a SINGLE luma transform, whose stamp covers the whole plane and
567- /// makes `luma_tx_type` that unit's own cell).
568- ///
569- /// This gate is the measurement behind that assertion, on the witness that
570- /// reaches it: `fixtures/444_rect_strip_leaf_tx_type.obu` (26839 bytes,
571- /// sha256 `06174a66e92aaeb751a8e86db59711fcb1f18d74bde2d77e1ef1be7983eb7c80`).
572- /// Measured there: the rect arm is called twice, BOTH on a multi-unit
573- /// chroma plane (`nx*ny > 1`), and 4 of its 8 units take the block-level
574- /// fallback -- every one of them with an EMPTY leaf list, i.e. the
575- /// single-luma-unit shape the assertion allows. So `multi_fallback >= 2`
576- /// here is the number that says the guarded shape is REACHED (a fallback
577- /// count of 0 would leave the assertion vacuous), and the decoded frames
578- /// stay byte-exact against instrumented aomdec, which is what says the
579- /// fallback still hands the right value on that shape.
580- ///
581- /// Non-vacuity, by mutation: forcing the covering-leaf resolve to miss on a
582- /// multi-unit plane (`…unit_rel_mi).filter(|_| !multi)`) turns the
583- /// assertion RED on this same witness --
584- /// `a multi-unit rect chroma plane fell back to the block-level tx_type
585- /// while 5 luma leaves were coded` -- so the closure is not a comment.
586- #[test]
587- fn a_multi_unit_rect_chroma_plane_only_falls_back_to_the_block_type_on_a_single_luma_unit() {
588- const NAME: &str = "a_multi_unit_rect_chroma_plane_only_falls_back_to_the_block_type_on_a_single_luma_unit";
589- const FIXTURE_LEN: usize = 26839;
590- const FIXTURE_FNV: u64 = 0xc77f_310c_036d_ff73;
591- let _gate_lock = lock_gate_counters();
592- let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
593- .join("fixtures/444_rect_strip_leaf_tx_type.obu");
594- let stream = std::fs::read(&path)
595- .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
596- assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: fixture length moved");
597- assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: fixture bytes moved");
598-
599- let fb0 = crate::decode::chroma_rect_block_tx_fallback();
600- let fbm0 = crate::decode::chroma_rect_block_tx_fallback_multi();
601- let frames = decode_stream(&stream)
602- .unwrap_or_else(|e| panic!("{NAME}: the witness no longer decodes: {e}"))
603- .len();
604- let fb = crate::decode::chroma_rect_block_tx_fallback() - fb0;
605- let fbm = crate::decode::chroma_rect_block_tx_fallback_multi() - fbm0;
606- assert_eq!(frames, 3, "{NAME}: expected 3 shown frames");
607- assert!(
608- fbm >= 2,
609- "{NAME}: only {fbm} block-level fallbacks landed on a MULTI-unit chroma plane \
610- ({fb} in total) -- the shape the decode's assertion guards is no longer reached, so \
611- that assertion is vacuous on this witness"
612- );
613- eprintln!("{NAME}: {fb} block-level chroma fallbacks, {fbm} of them on a multi-unit plane");
614- }
615-
616- /// lane-av1readcensus: the 4:4:4 coefficient-UNIT census, pinned.
617- ///
618- /// The lane report `av1444rect` round 4 left an unexplained signal: 636
619- /// square chroma reads against the oracle's 1086, and 2052 luma reads
620- /// against its 1309, recorded as "most likely a counting-shape difference"
621- /// with no evidence either way. This gate is that evidence.
622- ///
623- /// Measured on this arm (`ll444_minp8_inter`, pixel-exact against aomdec
624- /// on every plane of every frame -- see
625- /// `a_lossless_444_min_partition8_inter_stream_decodes_sample_exact`),
626- /// pairing each of our 11292 walked units with the oracle's
627- /// `av1_read_coeffs_txb` call BY `post_rng` (the msac state after the
628- /// unit) rather than by plane label or walk position: EVERY unit pairs,
629- /// and no unit's plane, shape, eob or all-zero flag differs. The per-plane
630- /// split is equal too -- 3764 units per plane on both sides, of which
631- /// 975 / 1793 / 1859 coded coefficients. So on a pixel-exact arm there is
632- /// no asymmetry to explain at all; the round-4 numbers came from
633- /// `444_intrabc_rect4_witness`, an arm that DIVERGES (390380 of 921600
634- /// samples wrong), where our surplus is the divergence itself.
635- ///
636- /// What this gate pins is the walk's OBJECT SHAPE on the pixel-exact arm:
637- /// a change to the number or plane split of coefficient units this decoder
638- /// walks shows up here as an intentional diff, not as the next lane's
639- /// mystery signal. The 4:2:0 control asserts the census is inert there.
640- #[test]
641- fn a_pixel_exact_444_stream_walks_the_same_coefficient_units_the_oracle_does() {
642- const NAME: &str =
643- "a_pixel_exact_444_stream_walks_the_same_coefficient_units_the_oracle_does";
644- const FIXTURE_LEN: usize = 34037;
645- const FIXTURE_FNV: u64 = 0x2c8f_4a2c_c025_52da;
646- let _gate_lock = lock_gate_counters();
647- if !have_aomenc() {
648- eprintln!(
649- "SKIP {NAME}: no aomenc/aomdec oracle at {}",
650- aomenc_path().display()
651- );
652- return;
653- }
654- let path =
655- std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures/ll444_minp8_inter.obu");
656- let stream = std::fs::read(&path)
657- .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
658- assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: fixture length moved");
659- assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: fixture bytes moved");
660- let delta = |now: [usize; 3], before: [usize; 3]| {
661- [now[0] - before[0], now[1] - before[1], now[2] - before[2]]
662- };
663-
664- let u0 = crate::decode::census_nonsub_units();
665- let c0 = crate::decode::census_nonsub_coded();
666- let (frames, hidden) = decode_all_frames_vs_oracle(&stream, NAME);
667- assert_eq!(
668- frames + hidden,
669- 8,
670- "{NAME}: expected 8 decode-order frames (6 shown + 2 hidden)"
671- );
672- let walked = delta(crate::decode::census_nonsub_units(), u0);
673- let coded = delta(crate::decode::census_nonsub_coded(), c0);
674-
675- // The oracle's own census on the same stream, paired by post_rng:
676- // 3764 units per plane, 975 / 1793 / 1859 of them coded.
677- assert_eq!(
678- walked,
679- [3764, 3764, 3764],
680- "{NAME}: the 4:4:4 unit walk changed -- {walked:?} against the oracle's \
681- [3764, 3764, 3764] (measured by post_rng pairing, every unit matching). A change \
682- here is a WALK-SHAPE change: re-measure against aomdec before assuming it is a bug"
683- );
684- assert_eq!(
685- coded,
686- [975, 1793, 1859],
687- "{NAME}: the coded-unit split changed -- {coded:?} against the oracle's [975, 1793, 1859]"
688- );
689- assert!(
690- walked.iter().all(|&v| v > 0) && coded.iter().all(|&v| v > 0),
691- "{NAME}: an all-zero plane split means the census did not run, not that the walk is empty"
692- );
693-
694- // A SECOND pixel-exact arm, with a MIXED unit-shape mix -- the pinned
695- // lossless stream above is all TX_4X4 (min-partition-8), so on its own
696- // it would not notice a var-tx walk that started folding 8x8/4x8
697- // leaves. This one walks 4x4/8x8/8x4/4x8/4x16/16x4/8x16/16x16, and
698- // the oracle's census on it pairs unit-for-unit by post_rng with no
699- // shape, plane, eob or all-zero difference: 1373 units, 629 luma and
700- // 372 per chroma plane, of which 130 / 253 / 278 coded.
701- let path2 = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
702- .join("fixtures/444_lossy_rect4_inter_witness.obu");
703- let stream2 = std::fs::read(&path2)
704- .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path2.display()));
705- let m0 = crate::decode::census_nonsub_units();
706- let mc0 = crate::decode::census_nonsub_coded();
707- let (frames2, hidden2) = decode_all_frames_vs_oracle(&stream2, NAME);
708- assert!(
709- frames2 + hidden2 > 0,
710- "{NAME}: the mixed-shape 4:4:4 arm decoded no frames"
711- );
712- let walked2 = delta(crate::decode::census_nonsub_units(), m0);
713- let coded2 = delta(crate::decode::census_nonsub_coded(), mc0);
714- assert_eq!(
715- walked2,
716- [629, 372, 372],
717- "{NAME}: the mixed-shape 4:4:4 walk changed -- {walked2:?} against the oracle's \
718- [629, 372, 372]. The all-4x4 arm above cannot see a var-tx fold; this one can"
719- );
720- assert_eq!(
721- coded2,
722- [130, 253, 278],
723- "{NAME}: the mixed-shape coded-unit split changed -- {coded2:?} against the oracle's \
724- [130, 253, 278]"
725- );
726-
727- // 4:2:0 control: the census is a 4:4:4 question and must not fire.
728- let control = std::fs::read(
729- std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
730- .join("fixtures/av1_192x128_8bit_intra64_in_inter.obu"),
731- )
732- .unwrap_or_else(|e| panic!("{NAME}: reading the 4:2:0 control: {e}"));
733- let k0 = crate::decode::census_nonsub_units();
734- let kc0 = crate::decode::census_nonsub_coded();
735- let k_frames = decode_stream(&control)
736- .unwrap_or_else(|e| panic!("{NAME}: the 4:2:0 control no longer decodes: {e}"))
737- .len();
738- assert!(k_frames > 0, "{NAME}: the 4:2:0 control decoded no frames");
739- assert_eq!(
740- delta(crate::decode::census_nonsub_units(), k0),
741- [0, 0, 0],
742- "{NAME}: the coefficient-unit census fired on the 4:2:0 control"
743- );
744- assert_eq!(
745- delta(crate::decode::census_nonsub_coded(), kc0),
746- [0, 0, 0],
747- "{NAME}: the coded-unit census fired on the 4:2:0 control"
748- );
749- }
750-
751- /// lane-inter4 r2: the 32x32-level inter `PARTITION_HORZ`/`PARTITION_VERT`
752- /// strips (32x16 / 16x32) carrying a REAL residual -- the capability r1
753- /// found missing ("a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs
754- /// rectangular residual coding"). The strip's own rectangular max
755- /// transform (`TX_32X16`/`TX_16X32`) is read through the rect var-tx tree,
756- /// its coefficients through [`TxbSet::LumaRect32x16Inter`] /
757- /// `ChromaRect16x8`, and inverted with the rect (sqrt2-scaled) inverse
758- /// transform.
759- ///
760- /// `--min-partition-size=16 --max-partition-size=32` keeps the superblock
761- /// level (64x32, still refused -- no 64-point rect transform) out, so
762- /// every counted hit is a 32-level strip. The source is textured and
763- /// translating precisely so the strips are NOT skip: a flat source (r1's)
764- /// makes aomenc code them skip and proves nothing about the residual.
765- /// Both `--enable-tx-size-search` arms run: `=0` exercises the
766- /// whole-block rect transform with no `txfm_partition` symbol at all,
767- /// `=1` the rect var-tx tree (no-split rect unit, or the split into square
768- /// sub-transforms).
769- ///
770- /// 8-bit AND 10-bit. Every decoded frame is compared to ffmpeg on Y, U and
771- /// V; a refusal is counted, never SKIPped; an attempt that carried no rect
772- /// inter residual is counted separately and still required pixel-exact.
773- /// Temporal (MFMV) motion-vector candidates, on a real aomenc stream
774- /// whose compound blocks feed the next frame's motion field
775- /// (`av1_copy_frame_mvs` -> `av1_setup_motion_field` -> `add_tpl_ref_mv`).
776- ///
777- /// lane-interbis r1 pinned this recipe because it is the one the rect
778- /// gate's attempt 1 decoded FULLY and still mismatched ffmpeg (a
779- /// 32x32 NEARESTMV block at mi (24, 40) of decode-order frame 5 took its
780- /// nearest candidate from a temporal cell holding the wrong reference:
781- /// `build_motion_field` stored a compound block's FIRST reference where
782- /// libaom stores its second). Every fully decoded attempt is compared
783- /// plane by plane; a refusal is counted, never SKIPped; the temporal
784- /// candidate counter must fire on a compared attempt, or the gate proves
785- /// nothing.
786- #[test]
787- fn a_real_aomenc_inter_sequence_with_temporal_mv_candidates_decodes_pixel_exact() {
788- const NAME: &str =
789- "a_real_aomenc_inter_sequence_with_temporal_mv_candidates_decodes_pixel_exact";
790- let _gate_lock = lock_gate_counters();
791- if !have_ffmpeg() {
792- eprintln!("SKIP {NAME}: no ffmpeg");
793- return;
794- }
795- if !have_aomenc() {
796- eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
797- return;
798- }
799- let (width, height, frame_count) = (192usize, 128usize, 6usize);
800- for bit_depth in [8u32, 10u32] {
801- let (mut named_refusals, mut compared, mut tmv_proved) = (0u32, 0u32, 0usize);
802- for attempt in 0..2u32 {
803- let tx_search = if attempt == 0 { "0" } else { "1" };
804- let duration = frame_count as f64 / 25.0;
805- // The pinned source: horizontal structure translating along X
806- // at 3 px/frame, which makes aomenc code compound LAST+GOLDEN
807- // blocks whose stored motion field the last frame reads back.
808- let source = format!(
809- "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
810- geq=lum='128+58*sin((X+N*3)/6)+18*sin(Y/23)',format=yuv420p"
811- );
812- let pix_fmt = if bit_depth == 10 {
813- "yuv420p10le"
814- } else {
815- "yuv420p"
816- };
817- let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
818- .args([
819- "-v",
820- "error",
821- "-f",
822- "lavfi",
823- "-i",
824- &source,
825- "-t",
826- &duration.to_string(),
827- "-pix_fmt",
828- pix_fmt,
829- "-strict",
830- "-1",
831- "-f",
832- "yuv4mpegpipe",
833- "-",
834- ])
835- .stdin(Stdio::null())
836- .stdout(Stdio::piped())
837- .stderr(Stdio::piped()), None, |c| c.output())
838- .expect("ffmpeg failed to run");
839- assert!(
840- y4m.status.success(),
841- "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
842- String::from_utf8_lossy(&y4m.stderr)
843- );
844- let depth_arg = format!("--bit-depth={bit_depth}");
845- let input_depth_arg = format!("--input-bit-depth={bit_depth}");
846- let tx_arg = format!("--enable-tx-size-search={tx_search}");
847- let args: Vec<&str> = vec![
848- "--codec=av1",
849- "--passes=1",
850- "--end-usage=q",
851- "--cq-level=34",
852- "--cpu-used=0",
853- "--threads=1",
854- "--row-mt=0",
855- "--sb-size=64",
856- &depth_arg,
857- &input_depth_arg,
858- "--enable-restoration=0",
859- "--enable-palette=0",
860- "--deltaq-mode=0",
861- "--enable-filter-intra=0",
862- "--enable-cfl-intra=0",
863- "--enable-intrabc=0",
864- "--lag-in-frames=0",
865- // Per-arm overrides go LAST (aomenc keeps the last
866- // occurrence of a repeated --enable-* flag).
867- &tx_arg,
868- "--enable-rect-partitions=1",
869- "--enable-ab-partitions=0",
870- "--enable-1to4-partitions=0",
871- "--min-partition-size=16",
872- "--max-partition-size=32",
873- "--obu",
874- "-o",
875- "-",
876- "-",
877- ];
878- let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
879- assert!(
880- out.status.success(),
881- "aomenc refused the fixture: {}",
882- String::from_utf8_lossy(&out.stderr)
883- );
884- let stream = out.stdout;
885- let before = decode::tmv_hits();
886- let frames = match decode_stream(&stream) {
887- Err(e) => {
888- let msg = e.to_string();
889- assert!(
890- msg.contains("unsupported"),
891- "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
892- attempt {attempt}): {msg}"
893- );
894- named_refusals += 1;
895- eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
896- continue;
897- }
898- Ok(frames) => frames,
899- };
900- let tmv = decode::tmv_hits() - before;
901- let ffmpeg_frames = if bit_depth == 10 {
902- ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
903- } else {
904- ffmpeg_decode_sequence(&stream, width, height, frame_count)
905- };
906- assert_eq!(frames.len(), frame_count);
907- for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
908- assert_eq!(
909- got.y, want.y,
910- "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit)"
911- );
912- assert_eq!(
913- got.u, want.u,
914- "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit)"
915- );
916- assert_eq!(
917- got.v, want.v,
918- "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit)"
919- );
920- }
921- compared += 1;
922- tmv_proved += tmv;
923- }
924- eprintln!(
925- "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {compared} \
926- pixel-exact attempts, blocks with a temporal MV candidate={tmv_proved}"
927- );
928- assert!(
929- compared > 0,
930- "{NAME} ({bit_depth}-bit): every attempt refused -- gate proved nothing"
931- );
932- assert!(
933- tmv_proved > 0,
934- "{NAME} ({bit_depth}-bit): no compared attempt ever folded a temporal MV \
935- candidate into a block's stack -- gate proved nothing"
936- );
937- }
938- }
939-
940- /// lane-refstamp r1: `av1_setup_motion_field`'s `ref_stamp` budget in the
941- /// presence of FORWARD KEY FRAMES (`--enable-fwd-kf=1`), which is the only
942- /// configuration where a *forward* reference slot (BWDREF/ALTREF2/ALTREF)
943- /// holds a key frame while temporal MV projection runs. libaom's
944- /// `motion_field_projection` returns 0 for such a start frame, so it costs
945- /// no `ref_stamp`; ours used to project the (empty) field and report
946- /// success, spending the slot ALTREF/LAST2 should have had and losing
947- /// their temporal candidates.
948- ///
949- /// Both bit depths; EVERY decoded frame (including the hidden alt-refs)
950- /// compared to the oracle in decode order; a refusal is counted, never
951- /// SKIPped. Two hard counters make the gate non-vacuous: frames that
952- /// actually took the >=2-intra-forward-refs `ref_stamp` path, and blocks
953- /// that folded a temporal MV candidate into their stack.
954- #[test]
955- fn a_real_aomenc_inter_sequence_with_forward_keyframes_and_temporal_mvs_decodes_pixel_exact() {
956- const NAME: &str = "a_real_aomenc_inter_sequence_with_forward_keyframes_and_temporal_mvs_decodes_pixel_exact";
957- let _gate_lock = lock_gate_counters();
958- if !have_ffmpeg() {
959- eprintln!("SKIP {NAME}: no ffmpeg");
960- return;
961- }
962- if !have_aomenc() {
963- eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
964- return;
965- }
966- let (width, height, frame_count) = (192usize, 128usize, 24usize);
967- for bit_depth in [8u32, 10u32] {
968- let (mut named_refusals, mut compared, mut tmv_proved, mut stamp_proved) =
969- (0u32, 0u32, 0usize, 0usize);
970- let mut stamp2_proved = 0usize;
971- for attempt in 0..2u32 {
972- let duration = frame_count as f64 / 25.0;
973- // Natural-ish motion: structure translating along X at 3 px per
974- // frame plus a slow vertical drift, the source family the
975- // temporal-MV gate already decodes fully.
976- let source = format!(
977- "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
978- geq=lum='128+58*sin((X+N*3)/6)+18*sin((Y+N*2)/23)',format=yuv420p"
979- );
980- let pix_fmt = if bit_depth == 10 {
981- "yuv420p10le"
982- } else {
983- "yuv420p"
984- };
985- let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
986- .args([
987- "-v",
988- "error",
989- "-f",
990- "lavfi",
991- "-i",
992- &source,
993- "-t",
994- &duration.to_string(),
995- "-pix_fmt",
996- pix_fmt,
997- "-strict",
998- "-1",
999- "-f",
1000- "yuv4mpegpipe",
1001- "-",
1002- ])
1003- .stdin(Stdio::null())
1004- .stdout(Stdio::piped())
1005- .stderr(Stdio::piped()), None, |c| c.output())
1006- .expect("ffmpeg failed to run");
1007- assert!(
1008- y4m.status.success(),
1009- "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
1010- String::from_utf8_lossy(&y4m.stderr)
1011- );
1012- let depth_arg = format!("--bit-depth={bit_depth}");
1013- let input_depth_arg = format!("--input-bit-depth={bit_depth}");
1014- let cq_arg = format!("--cq-level={}", if attempt == 0 { 34 } else { 45 });
1015- let args: Vec<&str> = vec![
1016- "--codec=av1",
1017- "--passes=1",
1018- "--end-usage=q",
1019- &cq_arg,
1020- "--cpu-used=0",
1021- "--threads=1",
1022- "--row-mt=0",
1023- "--sb-size=64",
1024- &depth_arg,
1025- &input_depth_arg,
1026- "--enable-restoration=0",
1027- "--enable-palette=0",
1028- "--deltaq-mode=0",
1029- "--enable-filter-intra=0",
1030- "--enable-cfl-intra=0",
1031- "--enable-intrabc=0",
1032- "--enable-rect-partitions=1",
1033- "--enable-ab-partitions=0",
1034- "--enable-1to4-partitions=0",
1035- "--min-partition-size=16",
1036- "--max-partition-size=32",
1037- // Per-arm/feature overrides go LAST (aomenc keeps the LAST
1038- // occurrence of a repeated --enable-* flag).
1039- "--enable-order-hint=1",
1040- "--enable-ref-frame-mvs=1",
1041- "--enable-fwd-kf=1",
1042- "--fwd-kf-dist=8",
1043- "--kf-max-dist=1000",
1044- "--lag-in-frames=16",
1045- "--auto-alt-ref=1",
1046- "--arnr-maxframes=0",
1047- "--obu",
1048- "-o",
1049- "-",
1050- "-",
1051- ];
1052- let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
1053- assert!(
1054- out.status.success(),
1055- "aomenc refused the fixture: {}",
1056- String::from_utf8_lossy(&out.stderr)
1057- );
1058- let stream = out.stdout;
1059- let before_tmv = decode::tmv_hits();
1060- let before_stamp = crate::motion_field::refstamp_intra_frames();
1061- if let Err(e) = decode_stream(&stream) {
1062- let msg = e.to_string();
1063- assert!(
1064- msg.contains("unsupported"),
1065- "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
1066- attempt {attempt}): {msg}"
1067- );
1068- named_refusals += 1;
1069- eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
1070- continue;
1071- }
1072- let tmv = decode::tmv_hits() - before_tmv;
1073- let stamp = crate::motion_field::refstamp_intra_frames().0 - before_stamp.0;
1074- let stamp2 = crate::motion_field::refstamp_intra_frames().1 - before_stamp.1;
1075- // Every frame, hidden ones included, compared in DECODE order.
1076- let (total, hidden) = decode_all_frames_vs_oracle(
1077- &stream,
1078- &format!("{NAME}-{bit_depth}bit-attempt{attempt}"),
1079- );
1080- eprintln!(
1081- "{NAME} ({bit_depth}-bit attempt {attempt}): {total} frames decoded \
1082- ({hidden} hidden), temporal candidates={tmv}, frames with a key/intra \
1083- forward ref={stamp} (two or more: {stamp2})"
1084- );
1085- compared += 1;
1086- tmv_proved += tmv;
1087- stamp_proved += stamp;
1088- stamp2_proved += stamp2;
1089- }
1090- assert!(
1091- compared > 0,
1092- "{NAME} ({bit_depth}-bit): every attempt refused ({named_refusals}) -- gate \
1093- proved nothing"
1094- );
1095- assert!(
1096- tmv_proved > 0,
1097- "{NAME} ({bit_depth}-bit): no compared attempt folded a temporal MV candidate \
1098- into a block's stack -- gate proved nothing"
1099- );
1100- assert!(
1101- stamp_proved > 0,
1102- "{NAME} ({bit_depth}-bit): no compared attempt ever had a forward reference \
1103- holding a key/intra frame ({stamp2_proved} frames had two) -- the ref_stamp \
1104- path this gate exists for never ran"
1105- );
1106- }
1107- }
1108-
1109- #[test]
1110- // lane-inter4 r2: RED, kept (not weakened, not deleted) -- the rect inter
1111- // residual path IS implemented and reached, but no aomenc recipe swept
1112- // this round produced a stream whose FIRST rect inter block is a 32x16 /
1113- // 16x32 one: real motion content always codes a 16x8/8x16 inter leaf (or
1114- // an intra rect strip) earlier in the tile, and both of those still refuse
1115- // by name, so the decode stops before any 32-level 2:1 strip. The 16x8
1116- // shape additionally needs `default_inter_ext_tx_cdf[2][TX_8X8]` (the
1117- // 12-symbol DTT9_IDTX_1DDCT row, only reachable through a rect
1118- // transform), which this round did not add. See lanes/inter4-r2.report.md.
1119- // Un-ignored 2026-09-04: the intra-rect-strip and 16-level AB/1:4 inter refusals that blocked every attempt are gone and the gate passes.
1120- fn a_real_aomenc_inter_sequence_with_a_coded_rectangular_residual_decodes_pixel_exact() {
1121- const NAME: &str =
1122- "a_real_aomenc_inter_sequence_with_a_coded_rectangular_residual_decodes_pixel_exact";
1123- let _gate_lock = lock_gate_counters();
1124- if !have_ffmpeg() {
1125- eprintln!("SKIP {NAME}: no ffmpeg");
1126- return;
1127- }
1128- if !have_aomenc() {
1129- eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
1130- return;
1131- }
1132- let (width, height, frame_count) = (192usize, 128usize, 6usize);
1133- for bit_depth in [8u32, 10u32] {
1134- let (mut named_refusals, mut matched, mut out_of_scope, mut oos_mismatch) =
1135- (0u32, 0u32, 0u32, 0u32);
1136- let (mut tu_proved, mut split_proved) = (0usize, 0usize);
1137- for attempt in 0..16u32 {
1138- // Two sources (a translating textured ramp, and testsrc2's
1139- // natural motion) x two quantisers x two tx-size-search arms x
1140- // two motion steps.
1141- let tx_search = if attempt % 2 == 0 { "0" } else { "1" };
1142- let cq = [34, 22][(attempt / 2 % 2) as usize];
1143- let natural = attempt / 4 % 2 == 1;
1144- let sp = 3 + (attempt / 8) * 5;
1145- let duration = frame_count as f64 / 25.0;
1146- // Continuous-tone, mid-frequency, translating: a flat or
1147- // banded source makes aomenc code the strips `skip` (r1's
1148- // gate) and its screen-content detector fires on the
1149- // synthetic ramps, stopping the decode at an unrelated intra
1150- // refusal long before any inter strip.
1151- // Structure ALONG one axis is what makes aomenc's RD pick a
1152- // 2:1 rect partition on that axis: horizontal bands drifting
1153- // vertically favour PARTITION_HORZ (32x16 strips), the
1154- // transposed source PARTITION_VERT (16x32).
1155- let lum = if natural {
1156- format!("128+58*sin((Y+N*{sp})/6)+18*sin(X/23)")
1157- } else {
1158- format!("128+58*sin((X+N*{sp})/6)+18*sin(Y/23)")
1159- };
1160- let source = format!(
1161- "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
1162- geq=lum='{lum}',format=yuv420p"
1163- );
1164- let pix_fmt = if bit_depth == 10 {
1165- "yuv420p10le"
1166- } else {
1167- "yuv420p"
1168- };
1169- let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1170- .args([
1171- "-v",
1172- "error",
1173- "-f",
1174- "lavfi",
1175- "-i",
1176- &source,
1177- "-t",
1178- &duration.to_string(),
1179- "-pix_fmt",
1180- pix_fmt,
1181- "-strict",
1182- "-1",
1183- "-f",
1184- "yuv4mpegpipe",
1185- "-",
1186- ])
1187- .stdin(Stdio::null())
1188- .stdout(Stdio::piped())
1189- .stderr(Stdio::piped()), None, |c| c.output())
1190- .expect("ffmpeg failed to run");
1191- assert!(
1192- y4m.status.success(),
1193- "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
1194- String::from_utf8_lossy(&y4m.stderr)
1195- );
1196- let cq_arg = format!("--cq-level={cq}");
1197- let depth_arg = format!("--bit-depth={bit_depth}");
1198- let input_depth_arg = format!("--input-bit-depth={bit_depth}");
1199- let tx_arg = format!("--enable-tx-size-search={tx_search}");
1200- let args: Vec<&str> = vec![
1201- "--codec=av1",
1202- "--passes=1",
1203- "--end-usage=q",
1204- &cq_arg,
1205- "--cpu-used=0",
1206- "--threads=1",
1207- "--row-mt=0",
1208- "--sb-size=64",
1209- &depth_arg,
1210- &input_depth_arg,
1211- "--enable-restoration=0",
1212- "--enable-palette=0",
1213- "--deltaq-mode=0",
1214- "--enable-filter-intra=0",
1215- "--enable-cfl-intra=0",
1216- "--enable-intrabc=0",
1217- "--lag-in-frames=0",
1218- // Per-arm overrides go LAST: aomenc keeps the last
1219- // occurrence of a repeated --enable-* flag.
1220- &tx_arg,
1221- "--enable-rect-partitions=1",
1222- "--enable-ab-partitions=0",
1223- "--enable-1to4-partitions=0",
1224- "--min-partition-size=16",
1225- "--max-partition-size=32",
1226- "--obu",
1227- "-o",
1228- "-",
1229- "-",
1230- ];
1231- let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
1232- assert!(
1233- out.status.success(),
1234- "aomenc refused the fixture: {}",
1235- String::from_utf8_lossy(&out.stderr)
1236- );
1237- let stream = out.stdout;
1238- let before = (
1239- decode::rect_inter_tu_hits(),
1240- decode::rect_inter_txsplit_hits(),
1241- );
1242- let frames = match decode_stream(&stream) {
1243- Err(e) => {
1244- let msg = e.to_string();
1245- assert!(
1246- msg.contains("unsupported"),
1247- "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
1248- attempt {attempt}): {msg}"
1249- );
1250- named_refusals += 1;
1251- eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
1252- continue;
1253- }
1254- Ok(frames) => frames,
1255- };
1256- let after = (
1257- decode::rect_inter_tu_hits(),
1258- decode::rect_inter_txsplit_hits(),
1259- );
1260- let (tu, split) = (after.0 - before.0, after.1 - before.1);
1261- let ffmpeg_frames = if bit_depth == 10 {
1262- ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
1263- } else {
1264- ffmpeg_decode_sequence(&stream, width, height, frame_count)
1265- };
1266- assert_eq!(frames.len(), frame_count);
1267- let mismatched = frames
1268- .iter()
1269- .zip(&ffmpeg_frames)
1270- .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
1271- if tu + split == 0 {
1272- out_of_scope += 1;
1273- if mismatched {
1274- oos_mismatch += 1;
1275- eprintln!(
1276- "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \
1277- coded rect inter transform units -- another shape's defect"
1278- );
1279- }
1280- continue;
1281- }
1282- for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
1283- assert_eq!(
1284- got.y, want.y,
1285- "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit, tx_search={tx_search})"
1286- );
1287- assert_eq!(
1288- got.u, want.u,
1289- "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit, tx_search={tx_search})"
1290- );
1291- assert_eq!(
1292- got.v, want.v,
1293- "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit, tx_search={tx_search})"
1294- );
1295- }
1296- tu_proved += tu;
1297- split_proved += split;
1298- matched += 1;
1299- }
1300- eprintln!(
1301- "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \
1302- attempts carrying a coded rect inter residual, whole-block rect TUs={tu_proved}, \
1303- rect trees that split={split_proved}, {out_of_scope} attempts carried none \
1304- ({oos_mismatch} of them mismatched)"
1305- );
1306- assert_eq!(
1307- oos_mismatch, 0,
1308- "{NAME}: {oos_mismatch} attempt(s) with no coded rect inter residual decoded but \
1309- mismatched ffmpeg -- a defect of another shape, not a pass"
1310- );
1311- assert!(
1312- tu_proved > 0,
1313- "{NAME} ({bit_depth}-bit): no pixel-exact attempt ever coded a rectangular inter \
1314- residual (tu={tu_proved}, split={split_proved}, {named_refusals} refusals, \
1315- {out_of_scope} out of scope) -- gate proved nothing"
1316- );
1317- }
1318- }
1319-
1320- /// lane-intersub8: `PARTITION_SPLIT` below 8x8 on an INTER frame -- four
1321- /// `BLOCK_4X4` inter sub-blocks with one shared 4x4 chroma unit per plane,
1322- /// predicted the sub8x8 way (2x2 chroma piece per luma sub-block mv,
1323- /// `dec_build_inter_predictors`' `is_sub8x8` branch). Reality of the shape
1324- /// was established BEFORE the code (class refusal-from-own-desync): the
1325- /// oracle `aomdec`'s `EC_TRACE` prints `EC_PART_VAL ... bsize=3 value=3`
1326- /// on this recipe's inter frames.
1327- ///
1328- /// Attempts 0..7 run `--enable-rect-partitions=0`, where aomenc can only
1329- /// pick SPLIT below 8x8; attempts 8..15 repeat the schedule with rect on,
1330- /// where it picks HORZ/VERT below 8x8 far more often than SPLIT -- the VERT
1331- /// arm (two `BLOCK_4X8` inter leaves, `decode_inter_sub8_rect2`) is what the
1332- /// `rect_fired` assert pins. The HORZ twin decodes but is refused by name
1333- /// (lane-intersub8 r3: a measured sweep desyncs the block to its right).
1334- #[test]
1335- fn a_real_aomenc_inter_sequence_with_a_sub8x8_inter_split_decodes_pixel_exact() {
1336- const NAME: &str =
1337- "a_real_aomenc_inter_sequence_with_a_sub8x8_inter_split_decodes_pixel_exact";
1338- let _gate_lock = lock_gate_counters();
1339- if !have_ffmpeg() {
1340- eprintln!("SKIP {NAME}: no ffmpeg");
1341- return;
1342- }
1343- if !have_aomenc() {
1344- eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
1345- return;
1346- }
1347- let (width, height, frame_count) = (192usize, 128usize, 6usize);
1348- let mut fired = 0u32;
1349- // lane-intersub8 r3: attempts 8..15 repeat the same schedule with
1350- // `--enable-rect-partitions=1`, where aomenc picks PARTITION_VERT below
1351- // 8x8 (two BLOCK_4X8 inter leaves, one shared 4x4 chroma unit predicted
1352- // from BOTH sub-blocks' mvs). The HORZ twin is still refused by name.
1353- let mut rect_fired = 0u32;
1354- // lane-intersub8 r5: the two rect axes counted apart. Attempts 16..23
1355- // are the same recipe family with the geq source TRANSPOSED (the sine
1356- // that moves runs along Y, not X): measured over a 56-arm sweep
1357- // (~/.cache/intersub8-sweep-r5.log, cq {8,12,14,16,20,26,32} x sp
1358- // {3,6,9,12} x both depths, rect on), aomenc picks PARTITION_HORZ
1359- // below 8x8 on that source and PARTITION_VERT on the untransposed one
1360- // -- neither schedule reaches the other axis, so both are needed.
1361- let (mut horz_fired, mut vert_fired) = (0u32, 0u32);
1362- // Rect (non-square) masked-compound blocks on attempts that DECODED
1363- // and were pixel-compared -- never off a refused stream (class
1364- // counter-from-refused-stream). This is the shape whose
1365- // `compound_type`/`wedge_idx` CDF row lane-intersub8 r4 fixed.
1366- let mut rect_masked = 0usize;
1367- let mut refusals: Vec<String> = Vec::new();
1368- let mut out_of_scope_mismatch = 0u32;
1369- for bit_depth in [8u32, 10u32] {
1370- for attempt in 0..24u32 {
1371- let rect = if attempt >= 16 { 1 } else { attempt / 8 };
1372- let rect_arg = format!("--enable-rect-partitions={rect}");
1373- // lane-intersub8 r2, measured schedule (sweep of cq
1374- // {8,10,12,14,16,18,20} x sp {3,6,9,12} x both depths,
1375- // `decode_probe`'s `sub8_inter_split:` counter vs an ffmpeg
1376- // rawvideo compare): sub-8x8 inter SPLIT groups fire at
1377- // (8-bit, cq 12, sp 3) = 1 group and (10-bit, cq 12, sp 6) =
1378- // 3 groups, both pixel-exact. cq 8 and 10 are NOT used: at
1379- // those quantizers this recipe also carries a CDEF defect of
1380- // another shape -- three luma samples of |d| = 1 on
1381- // decode-order frames 3/4, zero sub-8x8 inter split groups,
1382- // and the identical recipe re-encoded with `--enable-cdef=0`
1383- // decodes all six frames exact. Deferred to a CDEF lane
1384- // rather than hidden: cq 16..20 are all exact, so this gate
1385- // is not selecting quantizers that hide a defect of its own
1386- // shape.
1387- // Attempts 16..23: the (cq, sp) pairs the r5 sweep measured
1388- // as HORZ-firing on the transposed source -- 8-bit
1389- // (14,3)/(20,3)/(32,9), 10-bit (12,3)/(16,3); the rest of the
1390- // eight are non-firing neighbours kept so a schedule that
1391- // stops firing shows up as out-of-scope, not as a silent pass.
1392- const HORZ_SCHEDULE: [(u32, u32); 8] = [
1393- (14, 3),
1394- (20, 3),
1395- (32, 9),
1396- (12, 3),
1397- (16, 3),
1398- (12, 9),
1399- (14, 9),
1400- (26, 3),
1401- ];
1402- let (cq, sp) = if attempt >= 16 {
1403- HORZ_SCHEDULE[(attempt - 16) as usize]
1404- } else {
1405- (
1406- [12, 14][(attempt % 2) as usize],
1407- 3 + ((attempt % 8) / 2) * 3,
1408- )
1409- };
1410- let duration = frame_count as f64 / 25.0;
1411- let source = if attempt >= 16 {
1412- format!(
1413- "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
1414- geq=lum='128+58*sin((Y+N*{sp})/6)+18*sin(X/23)',format=yuv420p"
1415- )
1416- } else {
1417- format!(
1418- "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
1419- geq=lum='128+58*sin((X+N*{sp})/6)+18*sin(Y/23)',format=yuv420p"
1420- )
1421- };
1422- let pix_fmt = if bit_depth == 10 {
1423- "yuv420p10le"
1424- } else {
1425- "yuv420p"
1426- };
1427- let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1428- .args([
1429- "-v",
1430- "error",
1431- "-f",
1432- "lavfi",
1433- "-i",
1434- &source,
1435- "-t",
1436- &duration.to_string(),
1437- "-pix_fmt",
1438- pix_fmt,
1439- "-strict",
1440- "-1",
1441- "-f",
1442- "yuv4mpegpipe",
1443- "-",
1444- ])
1445- .stdin(Stdio::null())
1446- .stdout(Stdio::piped())
1447- .stderr(Stdio::piped()), None, |c| c.output())
1448- .expect("ffmpeg failed to run");
1449- assert!(
1450- y4m.status.success(),
1451- "{NAME}: ffmpeg refused the fixture: {}",
1452- String::from_utf8_lossy(&y4m.stderr)
1453- );
1454- let cq_arg = format!("--cq-level={cq}");
1455- let depth_arg = format!("--bit-depth={bit_depth}");
1456- let input_depth_arg = format!("--input-bit-depth={bit_depth}");
1457- let args: Vec<&str> = vec![
1458- "--codec=av1",
1459- "--passes=1",
1460- "--end-usage=q",
1461- &cq_arg,
1462- "--cpu-used=0",
1463- "--threads=1",
1464- "--row-mt=0",
1465- "--sb-size=64",
1466- &depth_arg,
1467- &input_depth_arg,
1468- "--enable-restoration=0",
1469- "--enable-palette=0",
1470- "--deltaq-mode=0",
1471- "--enable-filter-intra=0",
1472- "--enable-cfl-intra=0",
1473- "--enable-intrabc=0",
1474- "--lag-in-frames=0",
1475- "--enable-obmc=0",
1476- "--enable-tx-size-search=1",
1477- // Per-arm overrides last (aomenc keeps the LAST occurrence).
1478- "--enable-rect-partitions=0",
1479- "--enable-ab-partitions=0",
1480- "--enable-1to4-partitions=0",
1481- "--min-partition-size=4",
1482- "--max-partition-size=16",
1483- &rect_arg,
1484- "--obu",
1485- "-o",
1486- "-",
1487- "-",
1488- ];
1489- let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
1490- assert!(
1491- out.status.success(),
1492- "{NAME}: aomenc refused the fixture: {}",
1493- String::from_utf8_lossy(&out.stderr)
1494- );
1495- let stream = out.stdout;
1496- let before = decode::sub8_inter_split_hits();
1497- let before_rect = decode::sub8_inter_rect_hits();
1498- let before_masked = decode::rect_masked_compound_hits();
1499- let frames = match decode_stream(&stream) {
1500- Err(e) => {
1501- let msg = e.to_string();
1502- assert!(
1503- msg.contains("unsupported"),
1504- "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
1505- attempt {attempt}): {msg}"
1506- );
1507- refusals.push(format!("{bit_depth}-bit attempt {attempt}: {msg}"));
1508- continue;
1509- }
1510- Ok(frames) => frames,
1511- };
1512- let split_groups = decode::sub8_inter_split_hits() - before;
1513- let rect_now = decode::sub8_inter_rect_hits();
1514- let rect_groups = (rect_now.0 - before_rect.0) + (rect_now.1 - before_rect.1);
1515- let groups = split_groups + rect_groups;
1516- let ffmpeg_frames = if bit_depth == 10 {
1517- ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
1518- } else {
1519- ffmpeg_decode_sequence(&stream, width, height, frame_count)
1520- };
1521- assert_eq!(frames.len(), frame_count);
1522- let mismatched = frames
1523- .iter()
1524- .zip(&ffmpeg_frames)
1525- .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
1526- if groups == 0 {
1527- // Out of scope: no sub-8x8 inter split in this attempt.
1528- if mismatched {
1529- out_of_scope_mismatch += 1;
1530- eprintln!(
1531- "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \
1532- sub-8x8 inter group -- another shape's defect"
1533- );
1534- }
1535- refusals.push(format!(
1536- "{bit_depth}-bit attempt {attempt}: decoded, but no sub-8x8 inter split"
1537- ));
1538- continue;
1539- }
1540- for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
1541- assert_eq!(
1542- got.y, want.y,
1543- "luma frame {i} ({bit_depth}-bit attempt {attempt}, {groups} sub-8x8 \
crates/ec-av1/src/stream/tests/t06.rsdeleted+0 -4444

Diff too large; view file

crates/ec-av1/src/stream/tests/t07.rsdeleted+0 -4479

Diff too large; view file

crates/ec-av1/src/stream/tests/t08.rsdeleted+0 -4540

Diff too large; view file

crates/ec-av1/src/stream/tests/t09.rsdeleted+0 -4486

Diff too large; view file

crates/ec-av1/src/stream/tests/t10.rsdeleted+0 -4293

Diff too large; view file

crates/ec-av1/src/tool_cache.rsdeleted+0 -326

Diff too large; view file

scripts/build-aom-affine-oracle.shdeleted+0 -48

Diff too large; view file

scripts/build-aom-oracle.shdeleted+0 -56

Diff too large; view file

scripts/check-aom-oracle-rungs.shdeleted+0 -225

Diff too large; view file

scripts/instrument-aom-oracle.shdeleted+0 -1528

Diff too large; view file