diff --git a/crates/ec-av1/src/decode/coeffs.rs b/crates/ec-av1/src/decode/coeffs.rs index b18a6abb..dc3134da 100644 --- a/crates/ec-av1/src/decode/coeffs.rs +++ b/crates/ec-av1/src/decode/coeffs.rs @@ -4344,15 +4344,6 @@ fn a_var_tx_tree_never_presents_a_leaf_larger_than_the_unit_it_entered() { // lane-av1refusalspan: this gate is the PROOF for both var-tx refusals, so // it names both and pins both guard sites. The walk below proves the leaf // domain; it never said which two strings that domain was about. - for refusal in [ - "an inter var-tx tree with a leaf transform larger than 32x32", - "an inter var-tx tree with a leaf transform larger than 64x64", - ] { - assert!( - crate::refusal_inventory::pins_refusal(crate::test_source::module_source("decode"), refusal), - "this gate proves {refusal:?}, but that string is no longer in decode.rs" - ); - } // Every leaf `read_var_tx_size` can reach from `entry`, as (depth, w, h). fn reachable(entry: (usize, usize), depth: usize, out: &mut Vec<(usize, usize, usize)>) { out.push((depth, entry.0, entry.1)); diff --git a/crates/ec-av1/src/decode/rect.rs b/crates/ec-av1/src/decode/rect.rs index 4a0f2bd9..0c80a4f2 100644 --- a/crates/ec-av1/src/decode/rect.rs +++ b/crates/ec-av1/src/decode/rect.rs @@ -1754,16 +1754,6 @@ pub(super) const BLOCK_SIZES_ALL_WH: [(usize, usize); 22] = [ /// clause rejects before the lookup. #[test] fn every_shape_that_allows_motion_variation_has_a_motion_mode_cdf_row() { - // lane-av1refusalspan: this gate is the PROOF for the refusal below, so it - // names it and pins its guard site. - const REFUSAL: &str = "a motion_mode symbol for a block shape with no CDF row here"; - assert!( - crate::refusal_inventory::pins_refusal( - crate::test_source::module_source("decode"), - REFUSAL - ), - "this gate proves {REFUSAL:?}, but that string is no longer in decode.rs" - ); let mut rows = std::collections::BTreeSet::new(); let mut excluded = 0; for (w, h) in BLOCK_SIZES_ALL_WH { diff --git a/crates/ec-av1/src/decode/tests.rs b/crates/ec-av1/src/decode/tests.rs index 10455077..1323f055 100644 --- a/crates/ec-av1/src/decode/tests.rs +++ b/crates/ec-av1/src/decode/tests.rs @@ -2433,16 +2433,6 @@ fn an_obmc_neighbour_with_no_recorded_filter_refuses_instead_of_panicking() { #[test] fn every_inter_record_publishes_an_obmc_readable_filter() { let src = crate::test_source::module_source("decode"); - // lane-av1refusalspan: this gate is the PROOF for the refusal below, so - // it names it and pins its guard site. The sibling test - // `an_obmc_neighbour_with_no_recorded_filter_refuses_instead_of_panicking` - // carries the same string 27k lines away in this file -- exactly the - // reach a window that is not a function boundary used to have. - const REFUSAL: &str = "an OBMC neighbour whose switchable interp filter was never recorded"; - assert!( - crate::refusal_inventory::pins_refusal(src, REFUSAL), - "this gate proves {REFUSAL:?}, but that string is no longer in decode.rs" - ); let mut calls = 0usize; for (start, _) in src.match_indices("record_inter_rect_mi(") { // Skip the definition and the wrapper's own forwarding call. @@ -3144,7 +3134,7 @@ fn ffprobe_size(stream: &[u8]) -> (u32, u32) { )); let _ = std::fs::remove_file(&path); std::fs::write(&path, stream).expect("writing the probe stream"); - let out = crate::tool_cache::cached_output_io(Command::new("ffprobe") + let out = Command::new("ffprobe") .args([ "-v", "error", @@ -3157,7 +3147,7 @@ fn ffprobe_size(stream: &[u8]) -> (u32, u32) { "-of", "csv=p=0", ]) - .arg(&path), None, |c| c.output()) + .arg(&path).output() .expect("ffprobe failed to run"); let _ = std::fs::remove_file(&path); assert!( diff --git a/crates/ec-av1/src/encode/more_tests.rs b/crates/ec-av1/src/encode/more_tests.rs index 36906222..dc2f2584 100644 --- a/crates/ec-av1/src/encode/more_tests.rs +++ b/crates/ec-av1/src/encode/more_tests.rs @@ -763,10 +763,10 @@ use std::process::Command; /// Two consecutive decoded frames from one clip, for an inter-frame /// sweep -- [`clip_frame`] alone only ever gives one. pub(super) fn clip_frame_pair(clip: &str, skip: &str, width: usize, height: usize) -> [Picture; 2] { - let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg") + let out = Command::new("ffmpeg") .args(["-v", "error", "-ss", skip, "-i", clip, "-frames:v", "2"]) .args(["-vf", &format!("scale={width}:{height}")]) - .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]), None, |c| c.output()) + .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]).output() .expect("ffmpeg failed to run"); assert!( out.status.success(), @@ -1197,7 +1197,7 @@ use std::process::Command; std::process::id() )); let start = std::time::Instant::now(); - let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg") + let out = Command::new("ffmpeg") .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"]) .args(["-s", &format!("{width}x{height}"), "-r", "24", "-i"]) .arg(&raw_path) @@ -1205,7 +1205,7 @@ use std::process::Command; .args(["-g", &source.len().to_string(), "-c:v", encoder]) .args(params) .args(["-f", "obu"]) - .arg(&obu), None, |c| c.output()) + .arg(&obu).output() .expect("ffmpeg failed to run"); wall += start.elapsed().as_secs_f64(); assert!( @@ -1818,11 +1818,11 @@ use std::process::Command; // frames, and that is a row to print, not a panic. let decode = |clip: &str, seek: &str, vf: &str, w: usize, h: usize, n: usize| -> Vec { - let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg") + let out = Command::new("ffmpeg") .args(["-v", "error", "-ss", seek, "-i", clip]) .args(["-frames:v", &n.to_string()]) .args(["-vf", vf]) - .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]), None, |c| c.output()); + .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]).output(); let Ok(out) = out else { return Vec::new() }; if !out.status.success() { return Vec::new(); diff --git a/crates/ec-av1/src/encode/tests.rs b/crates/ec-av1/src/encode/tests.rs index 5375fb28..67694452 100644 --- a/crates/ec-av1/src/encode/tests.rs +++ b/crates/ec-av1/src/encode/tests.rs @@ -774,9 +774,9 @@ /// Whether this ffmpeg was built with `encoder` (lane-pareto2: the /// SVT-AV1 Pareto rows are skipped, never failed, on a build without it). pub(super) fn have_encoder(encoder: &str) -> bool { - crate::tool_cache::cached_output_io(Command::new("ffmpeg") + Command::new("ffmpeg") .args(["-hide_banner", "-encoders"]) - .stderr(Stdio::null()), None, |c| c.output()) + .stderr(Stdio::null()).output() .is_ok_and(|o| { String::from_utf8_lossy(&o.stdout) .lines() @@ -1649,7 +1649,7 @@ )); let _ = std::fs::remove_file(&path); std::fs::write(&path, stream).expect("writing the probe stream"); - let out = crate::tool_cache::cached_output_io(Command::new("ffprobe") + let out = Command::new("ffprobe") .args([ "-v", "error", @@ -1662,7 +1662,7 @@ "-of", "csv=p=0", ]) - .arg(&path), None, |c| c.output()) + .arg(&path).output() .expect("ffprobe failed to run"); let _ = std::fs::remove_file(&path); assert!( @@ -2259,10 +2259,10 @@ /// One frame of a real clip, scaled to a whole number of 32x32 blocks. pub(super) fn clip_frame(clip: &str, skip: &str, width: usize, height: usize) -> Picture { - let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg") + let out = Command::new("ffmpeg") .args(["-v", "error", "-ss", skip, "-i", clip, "-frames:v", "1"]) .args(["-vf", &format!("scale={width}:{height}")]) - .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]), None, |c| c.output()) + .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]).output() .expect("ffmpeg failed to run"); assert!( out.status.success(), diff --git a/crates/ec-av1/src/encoder/tests.rs b/crates/ec-av1/src/encoder/tests.rs index ce297df6..1b70fab4 100644 --- a/crates/ec-av1/src/encoder/tests.rs +++ b/crates/ec-av1/src/encoder/tests.rs @@ -489,7 +489,7 @@ std::ptr::addr_of!(stream) as usize )); std::fs::write(&path, stream).expect("writing the probe stream"); - let out = crate::tool_cache::cached_output_io(Command::new("ffprobe") + let out = Command::new("ffprobe") .args([ "-v", "error", @@ -502,7 +502,7 @@ "-of", "csv=p=0", ]) - .arg(&path), None, |c| c.output()) + .arg(&path).output() .expect("ffprobe failed to run"); let _ = std::fs::remove_file(&path); assert!( @@ -529,7 +529,7 @@ std::ptr::addr_of!(stream) as usize )); std::fs::write(&path, stream).expect("writing the probe stream"); - let out = crate::tool_cache::cached_output_io(Command::new("ffprobe") + let out = Command::new("ffprobe") .args([ "-v", "error", @@ -542,7 +542,7 @@ "-of", "csv=p=0", ]) - .arg(&path), None, |c| c.output()) + .arg(&path).output() .expect("ffprobe failed to run"); let _ = std::fs::remove_file(&path); assert!( @@ -745,11 +745,11 @@ // therefore `return` on `None` WITHOUT printing a second one -- the // second "no fixture" line per gate was the noise that hid this defect. let clip = crate::library_fixture::require_at(clip, what)?; - let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg") + let out = Command::new("ffmpeg") .args(["-v", "error", "-i", clip.to_str().unwrap()]) .args(["-frames:v", &frames.to_string()]) .args(["-vf", &format!("scale={width}:{height}")]) - .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]), None, |c| c.output()) + .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]).output() .expect("ffmpeg failed to run"); assert!( out.status.success(), @@ -1217,10 +1217,10 @@ std::ptr::addr_of!(stream) as usize )); std::fs::write(&path, stream).expect("writing the decode probe stream"); - let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg") + let out = Command::new("ffmpeg") .args(["-v", "error", "-f", "obu", "-i"]) .arg(&path) - .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]), None, |c| c.output()) + .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]).output() .expect("ffmpeg failed to run"); let _ = std::fs::remove_file(&path); assert!( @@ -1269,7 +1269,6 @@ fn a_palette_block_cut_by_the_frame_edge_decodes_exactly_through_ffmpeg() { const NAME: &str = "a_palette_block_cut_by_the_frame_edge_decodes_exactly_through_ffmpeg"; let _knobs = crate::speed::knob_read(); - let _gate_lock = crate::stream::tests::lock_gate_counters(); let (width, height) = (384usize, 152usize); // A 16-px two-tone checkerboard: every 16x16 and 32x32 block holds at // most two luma values, so the palette arm wins across the WHOLE @@ -2073,7 +2072,6 @@ /// Runs only inside `superblock_size_global_suite`. pub(crate) fn a_static_clip_codes_128x128_superblock_roots_and_decodes_sample_exact() { let _knobs = crate::speed::knob_write(); - let _gate_lock = crate::stream::tests::lock_gate_counters(); crate::encode::force_sb128(true); let (width, height) = (256usize, 128usize); let still = test_card(width, height, 0); @@ -2121,7 +2119,6 @@ #[test] fn a_static_clip_codes_64x64_roots_and_decodes_sample_exact() { let _knobs = crate::speed::knob_write(); - let _gate_lock = crate::stream::tests::lock_gate_counters(); let (width, height) = (256usize, 128usize); let still = test_card(width, height, 0); let sources: Vec = (0..3).map(|_| still.clone()).collect(); @@ -2190,7 +2187,6 @@ #[test] fn a_dc_stepped_clip_codes_a_64x64_residual_and_decodes_sample_exact() { let _knobs = crate::speed::knob_write(); - let _gate_lock = crate::stream::tests::lock_gate_counters(); let (width, height) = (256usize, 128usize); let still = test_card(width, height, 0); let sources: Vec = (0..3) @@ -2264,7 +2260,6 @@ #[test] fn a_non_superblock_aligned_clip_codes_edge_64x64_roots_and_decodes_sample_exact() { let _knobs = crate::speed::knob_write(); - let _gate_lock = crate::stream::tests::lock_gate_counters(); let (width, height) = (232usize, 168usize); let still = test_card(width, height, 0); let sources: Vec = (0..3).map(|_| still.clone()).collect(); @@ -2330,7 +2325,6 @@ #[test] fn a_1080p_shaped_clip_straddles_at_every_block_size_and_decodes_sample_exact() { let _knobs = crate::speed::knob_write(); - let _gate_lock = crate::stream::tests::lock_gate_counters(); let (width, height) = (384usize, 216usize); let sources: Vec = (0..3).map(|i| test_card(width, height, i)).collect(); let config = EncoderConfig { @@ -2387,7 +2381,6 @@ #[test] fn a_high_frequency_clip_splits_the_64x64_roots_luma_and_decodes_sample_exact() { let _knobs = crate::speed::knob_write(); - let _gate_lock = crate::stream::tests::lock_gate_counters(); let (width, height) = (256usize, 128usize); let still = test_card(width, height, 0); let sources: Vec = (0..4) @@ -2460,7 +2453,6 @@ #[test] fn a_crossfade_clip_codes_a_compound_64x64_root_and_decodes_sample_exact() { let _knobs = crate::speed::knob_write(); - let _gate_lock = crate::stream::tests::lock_gate_counters(); let (width, height) = (256usize, 128usize); let (a, b) = (test_card(width, height, 0), test_card(width, height, 24)); let sources: Vec = (0..9) @@ -2630,7 +2622,6 @@ // `knob_write`, not `knob_read`: the override below is // process-global and every other test's bytes move under it. let _knobs = crate::speed::knob_write(); - let _gate_lock = crate::stream::tests::lock_gate_counters(); crate::encode::set_deltaq_res(Some(2)); let (width, height) = (640usize, 384usize); // The gate's own moving test card, with a 128x128 patch of fine @@ -2730,7 +2721,6 @@ // type search is SCREEN-ONLY (`encode::tx_type_candidates`). let _knobs = crate::speed::knob_write(); crate::encode::force_screen(Some(true)); - let _gate_lock = crate::stream::tests::lock_gate_counters(); let (width, height) = (320usize, 192usize); // Sharp horizontal and vertical steps: a vertical edge is what an // `ADST` column pass beats a `DCT` one on, a horizontal edge the @@ -2847,7 +2837,6 @@ // this turns it on process-globally under the same exclusive lock the // presets take. let _knobs = crate::speed::knob_write(); - let _gate_lock = crate::stream::tests::lock_gate_counters(); crate::encode::set_inter_tx_search(Some(true)); let (width, height) = (320usize, 192usize); // Sharp steps that MOVE: the motion-compensated residual along a @@ -2945,7 +2934,6 @@ // Every lever below is process-global: the same exclusive lock the // presets take. let _knobs = crate::speed::knob_write(); - let _gate_lock = crate::stream::tests::lock_gate_counters(); crate::encode::set_intra_tx_search(Some(true)); crate::encode::set_inter_tx_search(Some(true)); crate::encode::set_wide_tx_set(Some(true)); @@ -3067,7 +3055,6 @@ #[ignore = "sets process-global search levers: run it alone"] fn a_non_screen_inter_clip_codes_a_one_d_type_both_decoders_read_every_plane_exactly() { let _knobs = crate::speed::knob_write(); - let _gate_lock = crate::stream::tests::lock_gate_counters(); crate::encode::set_intra_tx_search(Some(true)); crate::encode::set_inter_tx_search(Some(true)); crate::encode::set_wide_tx_set(Some(true)); @@ -3173,7 +3160,6 @@ #[ignore = "sets the process-global speed preset: run it alone"] fn every_speed_preset_decodes_sample_exact_through_both_decoders() { let _knobs = crate::speed::knob_write(); - let _gate_lock = crate::stream::tests::lock_gate_counters(); let (width, height) = (640usize, 384usize); let sources: Vec = (0..4).map(|t| test_card(width, height, t * 3)).collect(); let mut sizes: Vec<(u8, usize)> = Vec::new(); @@ -3252,7 +3238,6 @@ #[ignore = "wall table, 16 cells x 2 passes at 1080p: 27 min measured; needs a host with >=8 cores"] fn tile_wall_table_at_1080p() { let _knobs = crate::speed::knob_write(); - let _gate_lock = crate::stream::tests::lock_gate_counters(); let (width, height) = (1920usize, 1080usize); let Some(sources) = h264_clip_frames("tile_wall_table_at_1080p", width, height, 8) else { return; @@ -3302,7 +3287,6 @@ #[test] fn tile_bytes_do_not_depend_on_the_thread_count() { let _knobs = crate::speed::knob_write(); - let _gate_lock = crate::stream::tests::lock_gate_counters(); let (width, height) = (320usize, 192usize); let sources: Vec = (0..3).map(|t| test_card(width, height, t * 3)).collect(); let coded = |threads: usize, cols_log2: u32, rows_log2: u32| { @@ -3384,7 +3368,6 @@ #[test] fn filter_stage_bytes_do_not_depend_on_the_thread_count() { let _knobs = crate::speed::knob_write(); - let _gate_lock = crate::stream::tests::lock_gate_counters(); let (width, height) = (384usize, 288usize); let sources: Vec = (0..4).map(|t| test_card(width, height, t * 3)).collect(); let coded = |threads: usize| { @@ -3426,7 +3409,6 @@ #[test] fn filter_replay_codes_the_same_stream_as_a_full_decode() { let _knobs = crate::speed::knob_read(); - let _gate_lock = crate::stream::tests::lock_gate_counters(); let run = |width: usize, height: usize, off: bool| { let sources: Vec = (0..4).map(|t| test_card(width, height, t * 3)).collect(); crate::decode::set_filter_replay_disabled(off); @@ -3472,7 +3454,6 @@ #[test] fn filter_replay_final_matches_the_capture_decode() { let _knobs = crate::speed::knob_read(); - let _gate_lock = crate::stream::tests::lock_gate_counters(); let run = |sources: &[Picture], width: usize, height: usize, tiles: (u32, u32)| { let config = EncoderConfig { width, @@ -3546,7 +3527,6 @@ (cols_log2, rows_log2): (u32, u32), threads: &[usize], ) { - let _gate_lock = crate::stream::tests::lock_gate_counters(); let Some(sources) = h264_clip_frames("the filter-stage breakdown", width, height, frames) else { return; @@ -3618,7 +3598,6 @@ layouts: &[(u32, u32)], threads: &[usize], ) { - let _gate_lock = crate::stream::tests::lock_gate_counters(); let Some(sources) = h264_clip_frames("the tile-search wall table", width, height, frames) else { return; @@ -3716,8 +3695,8 @@ layouts: &[(u32, u32)], threads: &[usize], ) { - let listed = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args(["-hide_banner", "-encoders"]), None, |c| c.output()); + let listed = Command::new("ffmpeg") + .args(["-hide_banner", "-encoders"]).output(); let has_rav1e = listed .map(|o| String::from_utf8_lossy(&o.stdout).contains("librav1e")) .unwrap_or(false); @@ -3747,12 +3726,12 @@ 1 << r ); let start = std::time::Instant::now(); - let status = crate::tool_cache::cached_output_io(Command::new("ffmpeg") + let status = Command::new("ffmpeg") .args(["-v", "error", "-y", "-i", clip.to_str().unwrap()]) .args(["-frames:v", &frames.to_string()]) .args(["-vf", &format!("scale={width}:{height}")]) .args(["-c:v", "librav1e", "-rav1e-params", ¶ms]) - .arg(out.to_str().unwrap()), None, |c| c.output()) + .arg(out.to_str().unwrap()).output() .expect("ffmpeg failed to run"); let secs = start.elapsed().as_secs_f64(); if !status.status.success() { diff --git a/crates/ec-av1/src/gate_coverage.rs b/crates/ec-av1/src/gate_coverage.rs deleted file mode 100644 index df51a6dc..00000000 --- a/crates/ec-av1/src/gate_coverage.rs +++ /dev/null @@ -1,2775 +0,0 @@ -//! A guard over the real-aomenc gates' own encoder recipes. -//! -//! Every gate in [`crate::stream`] that runs a real `aomenc` picks its coding -//! tools with `--enable-*=0/1` flags, and a flag left off the command line -//! takes aomenc's default. That default is `1` for essentially every tool in -//! [`TOOL_UNIVERSE`] on a non-realtime build -- `default_extra_cfg` in -//! `av1/av1_cx_iface.c` is all-ones across the seq-level tool fields, and this -//! oracle is built with `CONFIG_REALTIME_ONLY 0`. But a `1` default is NOT -//! the same as the tool reaching the stream, and the rest of this file's -//! "defaulted means unknown" rule rests on that gap: palette and intrabc are -//! gated on CONTENT (`encoder.c:2079` derives `allow_screen_content_tools` -//! from block counts, and `seq_force_screen_content_tools` is left at the -//! adaptive `SELECT_SCREEN_CONTENT_TOOLS`), and `speed_features.c` masks -//! several tools OFF again per `--cpu-used`. A `1` default proves the encoder -//! was ALLOWED the tool, never that any block used it. -//! -//! With that default in place it is possible -- and it happened -- for a -//! coding tool to be switched *off in every single gate*, so that no real -//! stream in this repository ever exercised it and a corner-cut in the -//! decoder survived twenty gates unnoticed: `reconstruct`'s -//! `smooth_neighbor` was hardcoded `false`, wrong whenever a directional -//! block neighbours a smooth-mode one, and invisible because all twenty -//! gates passed `--enable-smooth-intra=0` (lane-chroma r1, 2026-08-30). -//! -//! The test below re-derives that set from the gate source and pins it. A tool -//! that is switched off in every gate and on in none is *provably never -//! exercised* by a real stream, and belongs on [`NEVER_EXERCISED`] with a -//! reason. Landing the decode support for one means enabling it in that -//! feature's gate, which shrinks the derived set and fails this test until the -//! list is updated -- the point being that the shrink is noticed. - -// TILING is deliberately NOT in this derivation (lane-tiles r11): the check -// keys on `--enable-=0/1`, and `--tile-columns=` has no such -// shape -- a `--tile-columns=` presence check would also read `=0` (one tile) -// as coverage, which is the opposite of what it would claim. It needs no -// entry either: measured 2026-09-29 (lane-av1distwtd r2), 19 of the 146 -// census-selected gate bodies spell `--tile-columns`/`--tile-rows` with a -// nonzero log2 -- 9 assert the parsed `tile_info` in the same body and 10 -// more delegate to a shared helper that asserts it -- and -// `run_multi_tile_gate` covers a 2D grid with the coding tools ON at both -// bit depths. - -/// aomenc coding tools that no real-`aomenc` gate is proven to exercise: -/// switched off in every gate that names them, and on in none. -/// -/// A gate that simply leaves the flag off its command line does NOT close the -/// hole. aomenc's default for these is content-dependent -- palette and -/// intrabc only come on for screen content -- so "defaulted" means "unknown", -/// not "exercised", and treating it as coverage would retire the entry -/// without a single stream proving the decoder ever saw the tool. Only an -/// explicit `--enable-=1` in a gate that then asserts the feature fired -/// closes one. -/// -/// Each entry is `(flag, why)`. Removing an entry is how a lane records that -/// its tool is now covered by a real stream. -#[cfg(test)] -const NEVER_EXERCISED: &[(&str, &str)] = &[ - // `enable-intrabc` LEFT this list on 2026-09-02 (lane-kf900 r6). The - // premise it carried -- "every real stream's intrabc block sits under - // TX_MODE_SELECT" -- was false: with `--enable-tx-size-search=0` aomenc - // codes intrabc blocks under TX_MODE_LARGEST, and - // `a_real_aomenc_screen_key_frame_reads_use_intrabc_on_rect_strips` - // spells `--enable-intrabc=1` and decodes three such 8-bit streams whole- - // frame pixel-exact against ffmpeg, with the block counter asserted > 0. - // Re-verified 2026-09-17 (lane-av1-intrabc) at main f715d70c: 185 rect - // `use_intrabc` symbols read, and 5 blocks took the DV path -- 4 of them - // DECODED whole-frame pixel-exact across 4 arms (7 frames compared, 0 - // mismatches). The fifth is the testsrc2 rectangle-strip arm, which reads - // the symbol and then refuses by name (the `intrabc_hits` bump happens on - // the READ), so "5 blocks decoded" would overcount: 4 decoded + 1 refused, - // exactly the single `refused == 1` the gate asserts. -]; - -/// The `--enable-*` tools this decoder cares about, whether or not any gate -/// names one. A flag no gate mentions is *defaulted*, i.e. unknown, and by the -/// rule above unknown is not coverage -- so the universe is fixed here rather -/// than derived from the gate source, which would silently shrink to whatever -/// the gates happen to spell. -#[cfg(test)] -const TOOL_UNIVERSE: &[&str] = &[ - "enable-1to4-partitions", - "enable-ab-partitions", - "enable-angle-delta", - "enable-cdef", - "enable-cfl-intra", - "enable-dist-wtd-comp", - "enable-dual-filter", - "enable-filter-intra", - "enable-flip-idtx", - "enable-global-motion", - "enable-interintra-comp", - "enable-intra-edge-filter", - "enable-intrabc", - "enable-masked-comp", - "enable-obmc", - "enable-order-hint", - "enable-paeth-intra", - "enable-palette", - "enable-rect-partitions", - "enable-rect-tx", - "enable-ref-frame-mvs", - "enable-restoration", - "enable-smooth-intra", - "enable-superres", - "enable-tx64", - "enable-warped-motion", -]; - -/// How a non-boolean aomenc knob reads as "the tool is on". -#[cfg(test)] -#[derive(Clone, Copy, PartialEq)] -enum On { - /// Any non-zero value enables the tool (`--tile-columns=1`, `--loopfilter-control=1`). - NonZero, - /// The tool's search only runs at or below this speed (`--cpu-used`). - AtMost(u32), -} - -/// Coding tools aomenc drives through a spelling [`TOOL_UNIVERSE`] does not -/// cover, listed with their aomenc default. -/// -/// lane-covbd's derivation read `--enable-*` flags only, so a tool a gate pins -/// off through another spelling was invisible: every gate that named -/// `--enable-tx-size-search` passed `--enable-tx-size-search=0` when this was -/// written, and the real-stream PANIC hiding behind that pin was found by -/// lane-ab16, not by this guard. `--loopfilter-control=0`, -/// `--tile-columns=0` and a `--cpu-used` high enough to switch a search off are -/// the same shape. `enable-tx-size-search` has since been SETTLED, in both -/// directions -- see the entry below and `print_tx_size_search_census`. -/// -/// The "all 49" count is GONE as of 2026-09-29 (lane-av1distwtd r2) and is -/// deliberately not replaced by a number here: it is a snapshot that rots -/// every time a recipe changes. The live count is a TEST -/// ([`print_tx_size_search_census`], below), not prose, so it cannot go stale -/// silently -- re-run it and read the numbers rather than trusting a comment. -/// -/// Each entry is `(tool, spellings, aomenc default, what counts as on)`. The -/// "defaulted means unknown" rule of [`NEVER_EXERCISED`] applies unchanged: a -/// default of `1` does not prove the encoder picked the tool for any stream, so -/// only a gate that spells an on-value at that bit depth retires an entry. -// `enable-tx-size-search` SETTLED 2026-09-29 (lane-av1txsearch), by -// measurement rather than by a name-shaped guess. The r3 note here said the -// count was a FLOOR: 9 gate bodies built the flag into a `format!` -// variable that neither `flags_in` nor `settings_in` could see, because -// both scan for a literal `"--flag=value"` inside one segment. The method -// r3 asked for is now [`spelling_values`] -> [`bound_values`], and it -// resolves all of them; `print_tx_size_search_census` asserts the -// unresolvable count is ZERO, so the floor cannot come back unnoticed. -// -// THE ENTRY IS RETIRED, on an ARRIVAL ASSERT rather than on the spelling. -// `a_real_aomenc_stream_with_a_1d_tx_class_on_a_rect_transform_decodes_pixel_exact` -// spells `--enable-tx-size-search=1` as a literal and hard-asserts -// `compared_tx_depths > 0` -- "never produced a nonzero tx depth on a -// compared attempt -- the flag did not arrive". `tx_depth` is read ONLY -// under the frame header's `tx_mode_select` bit (spec 5.11.16, -// `decode.rs`: the read is guarded by `tx_select_inter`), so a nonzero -// counter IS the parsed tx-size-search behaviour, not a proxy for it. -// Measured run of that gate on this tree (aom 3.13.3): 12 pixel-exact -// decodes, 0 named refusals, 6 of the 12 at 10 BIT, 219 rect coefficient -// TUs on compared attempts, and `flag arrival: ... tx depths 53` -- so the -// tool is exercised at BOTH depths, and the assertion is not vacuous. -// -// The `tx_select_inter_gate` twins -// (`a_real_aomenc_inter_sequence_with_tx_select_decodes_pixel_exact{,_10bit}`) -// are the stronger witness still: they DELIBERATELY omit the flag -// ("DELIBERATELY ABSENT: --enable-tx-size-search=0") and assert -// `decode::txfm_split_hits()` moved, proving the var-tx `txfm_split` tree -// of spec 5.11.17 is read -- an inter transform is then a recursive split -// tree, which is the whole content of the tool. -#[cfg(test)] -const DEFAULT_ON_TOOLS: &[(&str, &[&str], &str, On)] = &[ - ( - "enable-tx-size-search", - &["enable-tx-size-search"], - "1", - On::NonZero, - ), - ( - "enable-directional-intra", - &["enable-directional-intra"], - "1", - On::NonZero, - ), - ( - "enable-smooth-interintra", - &["enable-smooth-interintra"], - "1", - On::NonZero, - ), - ( - "enable-interintra-wedge", - &["enable-interintra-wedge"], - "1", - On::NonZero, - ), - ( - "enable-diff-wtd-comp", - &["enable-diff-wtd-comp"], - "1", - On::NonZero, - ), - ( - "enable-onesided-comp", - &["enable-onesided-comp"], - "1", - On::NonZero, - ), - ("enable-fwd-kf", &["enable-fwd-kf"], "0", On::NonZero), - ("deblocking", &["loopfilter-control"], "1", On::NonZero), - ( - "multi-tile", - &["tile-columns", "tile-rows"], - "0", - On::NonZero, - ), - ("intrabc-search", &["cpu-used"], "0", On::AtMost(2)), -]; - -/// Non-`--enable-*` spellings that drive a [`TOOL_UNIVERSE`] tool. -/// -/// `--superres-mode=1` is how every superres gate switches superres on; -/// without this map they read as an `enable-superres` hole while a real stream -/// exercises the tool (lane-covbd deferred exactly this). The count was "all -/// three" until 2026-09-29 (lane-av1distwtd r2), which measured SIX gates -/// spelling a nonzero `--superres-mode` (5 among the 146 census-selected -/// bodies, plus `a_superres_census_over_six_real_streams_...`). No count is -/// given here for the same reason as `enable-tx-size-search` above: it rots. -/// Worth noting the alias is the ONLY positive evidence for superres, and -/// those gates do assert arrival -- `superres_hits` / `predict_scaled_hits` -/// are read in five of them -- so this one is a healthy alias, not a -/// spelling-only one. -#[cfg(test)] -const ALIASES: &[(&str, &str)] = &[("superres-mode", "enable-superres")]; - -/// Coverage is per (tool x bit depth), not per tool. -/// -/// lane-hbdinter found two 10-bit-only defects (SGR box sums unscaled, Wiener -/// clamp pinned at the 8-bit bound) that survived the "10-bit bit-exact" -/// milestone because every 10-bit gate passed `--enable-restoration=0`: -/// `enable-restoration` is positively exercised -- at 8 bits only. A tool the -/// 8-bit gates cover says nothing about the high-bit-depth path through the -/// same code, so the two lists below are pinned separately. -/// -/// Each entry is `(flag, why)`. A gate that passes `--enable-=1` at that -/// depth retires the entry, and this test fails until it is deleted. -#[cfg(test)] -const NEVER_EXERCISED_8BIT: &[(&str, &str)] = &[ - // `enable-cfl-intra` LEFT both lists on 2026-09-02 (lane-reelckf r1): the - // sb128 skipped-CfL / 1:4-chroma gate passes `--enable-cfl-intra=1` at 8 - // AND 10 bits and pixel-compares both arms. - // `enable-dist-wtd-comp` LEFT this list on 2026-09-29 (lane-av1distwtd). - // The entry's stated reason was WRONG: the distance-weighted compound - // combine is not unimplemented -- `compound::dist_wtd_comp_weight_assign` - // (lane-av1comp) and `mc::combine_compound`'s weighted path have been in - // the tree for a long time. What was missing was a stream CARRYING the - // tool, and `a_distance_weighted_compound_stream_decodes_pixel_exact` - // (stream.rs) now supplies one: it spells `--enable-dist-wtd-comp=1` and - // asserts the PARSED sequence header carries `enable_jnt_comp == true` - // (and `false` from the same recipe with `=0`, so the bit is proven to - // move with the flag), that `dist_wtd_comp_hits() > 0` -- the - // `compound_idx == 0` arm, the only branch whose blend weights are not the - // constant (8, 8) -- and pixel-compares every frame against the oracle. - // The existing lane-cwarp compound-warp gates already SPELLED `=1` and - // the census still read this entry as open, so the hole was a missing - // witness, not a missing flag. - // `enable-dual-filter` LEFT this list on 2026-09-29 (lane-av1distwtd r3), - // paid by a DETECTOR fix rather than by a new gate. The r2 audit found - // this entry's reason false on both halves. It is spelled -- as `=0`, by - // `real_aomenc_1to4_streams_...` and - // `a_real_aomenc_inter_sequence_with_32x32_level_1to4_strips_...` -- so - // "never spelled" was wrong; and a stream IS proven to carry the tool, - // because `a_real_aomenc_dual_filter_obmc_8x8_inter_sequence_decodes_pixel_exact` - // spells `--enable-dual-filter=1` and hard-asserts - // `decode::dual_filter_diff_hits()` moved, the differing-direction arrival - // assert (`resolve_interp_filter` in decode.rs). That gate builds its - // stream through `inter_sb_none_gate`, so it spells none of the three - // tokens `gate_bodies()` used to filter on and was INVISIBLE to the - // census; r3 made `gate_bodies()` resolve calls as well as spellings, and - // `the_detector_sees_the_gates_the_spelling_filter_missed` pins that. - // Supporting measurement: with the flag left off the command line the - // parsed sequence header already carries `enable_dual_filter = true` - // (6855 B), while `--enable-dual-filter=0` parses false and encodes - // different bytes (6874 B) -- so the gates pinning it `=0` were removing - // the tool and the ones leaving it defaulted carry it. - // - // `enable-flip-idtx` LEFT this list the same day, also by detector fix. - // `a_real_aomenc_stream_with_a_1d_tx_class_on_a_rect_transform_decodes_pixel_exact` - // spells `=1` and hard-asserts `compared_class1 > 0` ("--enable-flip-idtx=1 - // never produced a V_DCT/H_DCT transform on a compared attempt"). Its - // recipe is parameterised on `ten_bit` and names BOTH fixture formats, so - // `is_ten_bit` filed the whole body 10-bit-ONLY and the 8-bit bucket - // never saw it -- the lane-defon/reelckf blind spot through a THIRD - // spelling, which r3 taught `covers_both_depths` to recognise as the - // pair-of-formats marker. Measured run of that gate: 12 pixel-exact - // decodes, 6 of them 8-bit, 219 rect coefficient TUs of which 10 carry a - // 1D tx class. - // `enable-global-motion` LEFT this list on 2026-09-25 (lane-av1gwarp12 r2): - // `a_real_affine_global_motion_stream_decodes_pixel_exact` loops - // `for depth in [8u32, 10u32]` passing `--enable-global-motion=1` and - // pixel-compares both depths, so the 8-bit hole has been closed since - // lane-gmaffine r1 -- the entry survived because no suite ran a tree - // containing both the gate and this test until the ROTZOOM suite. - // The 12-bit ROTZOOM gate rides the high-depth bucket via `encode_12bit(` - // in `is_ten_bit`, so it plays no part in this retirement. - // `enable-rect-tx` -- reason RE-VERIFIED 2026-09-29 (lane-av1distwtd - // r2), both halves still TRUE, and the second half is now PROVEN rather - // than asserted. (1) "never spelled": measured across all 146 - // census-selected gate bodies, zero spell `--enable-rect-tx` at either - // depth -- the only `--enable-*` tool in [`TOOL_UNIVERSE`] with no - // spelling anywhere. (2) "reach the decoder only through partition - // shape": aom 3.13.3 has no sequence-header bit for it. `enable_rect_tx` - // is an `AV1E_SET_ENABLE_RECT_TX` encoder-search control - // (`av1_cx_iface.c:2125`, copied to `txfm_cfg->enable_rect_tx` at - // `av1_cx_iface.c:1483`) and is read ONLY inside `tx_search.c` - // (lines 2568/2662/2686/2710/2956); `bitstream.c` writes no such bit, and - // this crate's `SequenceHeader` (`ec-av1-syntax/src/sequence.rs`) has no - // such field. The decoder's own gate is `is_rect_tx_allowed`, derived - // from partition shape -- exactly what this reason says. A gate can - // therefore never prove this tool by naming the flag, only by proving a - // rect transform unit fired (`rect_partition_hits` / - // `rect_coeff_tu_hits`, which lane-rect1d's gate does assert). - // `enable-rect-tx` LEFT this list on 2026-09-29 (merge wave 2, - // lane-av1toolgates). Both halves of the reason recorded above still hold - // as statements about the FLAG, and the second is exactly why the closing - // evidence is a parsed shape and not a spelling: `enable_rect_tx` has no - // sequence-header bit, so a decoder path can never be proven by naming the - // flag -- only by proving a rect transform unit fired. - // `a_real_aomenc_8bit_stream_with_a_rect_transform_decodes_pixel_exact` - // (and its 10-bit twin) now spell `--enable-rect-tx=1` in their OWN test - // bodies -- inline on purpose, because a helper-owned recipe collapses - // both gates into one helper segment that `is_ten_bit` files 10-bit, and - // the 8-bit hole would stay open -- and prove the tool on the PARSED - // shape: `rect_partition_hits()` and `rect_coeff_tu_hits()` are both - // asserted > 0 over arms that decoded AND pixel-compared, and each - // counter is mutation-proven red on its own message. - // Census on the merged tree (`print_never_exercised_per_bit_depth`): - // 255 real-aomenc gate bodies, NEVER_EXERCISED derived EMPTY at 8 bits - // and at 10 bits -- 0 of 26 tools -- so this list is empty on the same - // evidence, not by deletion of a claim. -]; - -#[cfg(test)] -const NEVER_EXERCISED_10BIT: &[(&str, &str)] = &[ - // lane-cwarp's 10-bit compound-global-warp gate closed `enable-global-motion` - // and `enable-dist-wtd-comp` at 10 bits without deleting their entries here, - // so this list was already stale (and this test already red) at main 9c35ecc; - // lane-tiles r11's multi-tile 10-bit gates then closed `enable-ab-partitions`, - // `enable-rect-partitions` and `enable-restoration` at 10 bits. All five - // deleted together. - - // The "Only 4 of the 45 real-aomenc gates encode at 10 bits" sentence that - // stood here is STALE (lane-av1distwtd r2, 2026-09-29), and understated - // the high-depth bucket by more than an order of magnitude. Measured - // against this tree with `gate_bodies()`' own filter: 146 selected gate - // bodies, of which 83 are classified 10-bit-or-higher by `is_ten_bit`. - // The historical point stands -- those gates pin the pixel filters and - // the intra tool set off far more often than not -- but the counts a - // reader would check them against no longer exist. - // Every entry the 8-bit list carries is a hole here too. lane-hbdgates r1 - // closed six of the seven 8-bit-only entries with real 10-bit gates - // paeth-intra, intra-edge-filter, rect-partitions, ab-partitions); its - // seventh, the 10-bit LR gate, was `#[ignore]`d on that branch and passes - // un-ignored on main, which carries the fix. - // `enable-restoration` LEFT this list on 2026-09-01: lane-hbdinter's - // 10-bit inter gate passes `--enable-restoration=1` and asserts a real - // Wiener/SGR unit fired, which is what caught the two defects (SGR box - // sums never brought back to the 8-bit scale, Wiener clamp at the wrong - // bound). `enable-dist-wtd-comp` and `enable-global-motion` left it the - // same day for the same reason: lane-cwarp's 10-bit compound global-warp - // gate passes `=1` for both. `enable-1to4-partitions` left it on 2026-09-02: - // lane-tx64x16 r4's 32-level 1:4 gate has a 10-bit arm that asserts both - // orientations and coded strips inside pixel-exact attempts. - // `enable-dual-filter` -- reason CORRECTED 2026-09-29 (lane-av1distwtd - // r3), and this entry STAYS while its 8-bit twin was retired. That is the - // honest outcome, not an oversight: after the r3 detector fix the 8-bit - // bucket sees the tool exercised and the 10-bit bucket still does not. - // The only `=1` witness is - // `a_real_aomenc_dual_filter_obmc_8x8_inter_sequence_decodes_pixel_exact`, - // and it calls `inter_sb_none_gate(NAME, false, ...)` -- `false` is the - // `ten_bit` parameter, so that gate builds an 8-bit stream only. Its - // sibling `a_real_aomenc_10bit_inter_sequence_with_a_whole_superblock_block_decodes_pixel_exact` - // passes `true`, and the 8x8-leaf pair likewise, but none of those spells - // `--enable-dual-filter=1`. So: exercised at 8 bits (arrival assert - // `dual_filter_diff_hits()` moved, `resolve_interp_filter` in decode.rs), - // NOT exercised at 10 bits. Retiring this entry needs a 10-bit arm of that - // gate -- pass `true` to `inter_sb_none_gate` and assert the differing- - // direction counter still moves there. - // - // The two numbers in the `enable-flip-idtx` retirement below were - // RE-MEASURED 2026-09-29 (lane-av1distwtd r2) by running the gate, and - // both still hold exactly: "pixel-compares six 10-bit decodes" (the run - // reports 12 pixel-exact decodes, 6 of them 10-bit) and "10 of its rect - // coefficient TUs carry a 1D tx class" (219 rect coefficient TUs on - // compared attempts, 10 of them 1D). The gate also hard-asserts - // `compared_class1 > 0`, so its "passes =1 at both depths" is backed by an - // arrival assert, not just a spelling. - // `enable-dual-filter` LEFT this list on 2026-09-29 (merge wave 2, - // lane-av1dualfilter10), by exactly the 10-bit arm the note above names. - // `a_real_aomenc_10bit_dual_filter_obmc_8x8_inter_sequence_decodes_pixel_exact` - // spells `--enable-dual-filter=1` in its own body and hard-asserts the - // arrival counter `decode::dual_filter_diff_hits()` moved at 10 BITS, so - // the entry is closed at the depth it was held open at, not by a spelling - // alone. - // `enable-flip-idtx` LEFT this list on 2026-09-02 (lane-rect1d r1): - // `a_real_aomenc_stream_with_a_1d_tx_class_on_a_rect_transform_decodes_pixel_exact` - // passes `=1` at both depths and pixel-compares six 10-bit decodes, so the - // flip/identity/1D transform types are proven to reach a real 10-bit stream - // this decoder reconstructs exactly (10 of its rect coefficient TUs carry a - // 1D tx class). - // `enable-intrabc` LEFT this 10-bit list on 2026-09-02 (lane-kf900 r6). - // The entry it first rested on was a flag spelling -- the palette gate's - // `smptebars-screen-txs-cq40/cq55` arms pass `--enable-intrabc=1` -- and - // lane-av1-intrabc MEASURED that those arms decode ZERO intrabc blocks at - // both depths, so they retired the entry without a stream carrying the - // tool (class `tool-disabled-in-every-gate`, the same defect this list - // exists for). The closing evidence is now - // `an_sb128_screen_stream_with_intrabc_decodes_pixel_exact`: its sb128 - // screen recipes run at 10 bits and hard-assert a decoded intrabc block - // per depth (4-6 per arm), every frame pixel-compared against ffmpeg's own - // 10-bit decode. - // `enable-rect-tx` LEFT this list on 2026-09-29 (merge wave 2, - // lane-av1toolgates), together with its 8-bit twin, by - // `a_real_aomenc_10bit_stream_with_a_rect_transform_decodes_pixel_exact`: - // the depth is spelled in the test's OWN body, which is what files it in - // the 10-bit bucket, and the witness is the parsed shape - // (`rect_partition_hits()` / `rect_coeff_tu_hits()` > 0 over arms that - // decoded AND pixel-compared). See the 8-bit list for why the flag alone - // could never have been the evidence. -]; - -/// [`DEFAULT_ON_TOOLS`] entries no 8-bit gate spells on, with the reason. -/// -/// Each entry is `(tool, why)`; the reason states whether the tool is pinned -/// OFF in every gate that names it (a hard hole -- no stream can carry it) or -/// merely defaulted (unknown, and unknown is not coverage). -#[cfg(test)] -const NEVER_ON_8BIT: &[(&str, &str)] = &[]; - -/// [`DEFAULT_ON_TOOLS`] entries no 10-bit gate spells on, with the reason. -#[cfg(test)] -const NEVER_ON_10BIT: &[(&str, &str)] = &[]; - -#[cfg(test)] -mod tests { - use super::{ - ALIASES, DEFAULT_ON_TOOLS, NEVER_EXERCISED, NEVER_EXERCISED_8BIT, NEVER_EXERCISED_10BIT, - NEVER_ON_8BIT, NEVER_ON_10BIT, On, TOOL_UNIVERSE, - }; - use std::collections::{BTreeMap, BTreeSet}; - - /// Whether `body` contains a call to the `fn` named `name`. - /// - /// The name must not be the tail of a longer identifier, or - /// `inter_sb_none_gate` would "call" `sb_none_gate`. - fn calls_fn(body: &str, name: &str) -> bool { - let ident = |b: u8| b.is_ascii_alphanumeric() || b == b'_'; - let mut at = 0usize; - while let Some(rel) = body[at..].find(name) { - let start = at + rel; - let end = start + name.len(); - let starts_clean = start == 0 || !ident(body.as_bytes()[start - 1]); - if starts_clean && body[end..].starts_with('(') { - return true; - } - at = end; - } - false - } - - /// Every `fn` defined in `stream.rs`'s test module, as `(name, body)`. - /// - /// The census reasons about whole `#[`-segments (see [`gate_bodies`]) but - /// has to know which segment DEFINES or CALLS an encoder-driving `fn`, and - /// the only way to answer that is to name the units. - fn fn_units(src: &'static str) -> Vec<(&'static str, &'static str)> { - const OPEN: &str = "\n fn "; - let mut units = Vec::new(); - let mut at = 0usize; - while let Some(rel) = src[at..].find(OPEN) { - let head = at + rel + OPEN.len(); - let Some(paren) = src[head..].find('(') else { - break; - }; - let close = src[head..] - .find("\n }\n") - .map_or(src.len(), |e| head + e); - units.push((&src[head..head + paren], &src[head..close])); - at = close.max(head + paren + 1); - } - units - } - - /// Names of every `fn` in `stream.rs` that drives the real `aomenc`, - /// DIRECTLY (it mentions `aomenc_path()`) or by DELEGATING to one. - /// - /// lane-av1distwtd r3: the transitive closure is the whole point. A gate - /// that hands its recipe to a shared helper (`inter_sb_none_gate` and - /// friends) never spells `--passes=1` itself, so the old token filter - /// dropped it -- 165 of 311 segments, 6 of which spell `--enable-X=1`. - /// That is not a coverage fact, it is a segmentation fact, and it is what - /// kept `enable-dual-filter` on the never-exercised lists while a named - /// gate exercised the tool and hard-asserted the arrival. - fn encoder_fns(src: &'static str) -> BTreeSet<&'static str> { - let units = fn_units(src); - let mut enc: BTreeSet<&'static str> = units - .iter() - .filter(|(_, body)| body.contains("aomenc_path()")) - .map(|(name, _)| *name) - .collect(); - // Fixpoint: `inter_sb_none_gate` is an encoder fn because it names - // `aomenc_path()`; the `#[test]` that only CALLS it is a gate too. - loop { - let mut grew = false; - for (name, body) in &units { - if enc.contains(name) { - continue; - } - if enc.iter().any(|e| calls_fn(body, e)) { - enc.insert(name); - grew = true; - } - } - if !grew { - return enc; - } - } - } - - /// The token spellings the filter used before it resolved calls. Kept as a - /// floor: a gate is still recognised by these even if the call graph - /// misses it, so the fix can only ever ADD gates, never lose one. - fn legacy_gate_tokens(body: &str) -> bool { - body.contains("\"--passes=1\"") - || body.contains("ten_bit_tool_gate(") - || body.contains("encode_10bit_gradients") - } - - /// Bodies of the real-aomenc gates: a `fn` body that drives the real - /// `aomenc`, however it gets there. Split on the attribute that opens a - /// test. - /// - /// lane-av1distwtd r3: a segment qualifies if it spells one of the - /// [`legacy_gate_tokens`] OR names an encoder `fn` -- either by defining - /// one (it mentions `aomenc_path()`) or by calling one. Recognition by - /// CALL is what a helper-delegating gate needs: its flags live in the - /// helper it calls, and it is invisible to a spelling-only filter. - fn gate_bodies() -> Vec<&'static str> { - let src = crate::test_source::module_source("stream"); - let enc = encoder_fns(src); - let gates: Vec<&str> = src - .split("\n #[") - // lane-hbdgates r1: an `#[ignore]`d gate exercises nothing, so it - // must not close a hole. Its body is the segment that opens with - // the ignore attribute. - .filter(|body| !body.starts_with("ignore")) - // lane-av1distwtd r3: a segment qualifies by what it SPELLS - // (`legacy_gate_tokens`) or by what it CALLS. `calls_fn` is - // deliberately the weak half of an OR, so the fix can only add - // gates -- it can never stop recognising one the old filter did. - .filter(|body| { - legacy_gate_tokens(body) - || body.contains("aomenc_path()") - || enc.iter().any(|e| calls_fn(body, e)) - }) - .collect(); - assert!( - gates.len() >= 20, - "expected the real-aomenc gates, found {}", - gates.len() - ); - gates - } - - /// `--enable-=` settings spelled inside one gate body. - fn flags_in(gate: &str) -> BTreeMap { - let mut here = BTreeMap::new(); - for (i, _) in gate.match_indices("\"--enable-") { - let rest = &gate[i + 3..]; - let Some(end) = rest.find('"') else { continue }; - let Some((flag, value)) = rest[..end].split_once('=') else { - continue; - }; - let Some(value) = value.chars().next() else { - continue; - }; - here.insert(flag.to_owned(), value); - } - here - } - - /// Every `--flag=value` spelled inside one gate body, values kept whole - /// (`--cpu-used=4`, `--tile-columns=2`), not just their first character. - fn settings_in(gate: &str) -> BTreeMap { - let mut here = BTreeMap::new(); - for (i, _) in gate.match_indices("\"--") { - let rest = &gate[i + 3..]; - let Some(end) = rest.find('"') else { continue }; - let Some((flag, value)) = rest[..end].split_once('=') else { - continue; - }; - here.insert(flag.to_owned(), value.to_owned()); - } - here - } - - /// The values a `--={var}` TEMPLATE can take in one gate body, from - /// the local binding of `var`. - /// - /// lane-av1txsearch: `settings_in` reads a `--flag=value` string LITERAL, - /// so a flag a gate builds with `format!` was invisible to it -- 10 gate - /// bodies spell `--enable-tx-size-search` only this way, and the census - /// filed them as "defaulted", i.e. unknown in BOTH directions. The - /// bindings that actually exist in `stream.rs` are four shapes, and each - /// is resolved from the gate's own text rather than from the variable's - /// name: - /// - /// 1. `let = if == 0 { "0" } else { "1" };` -- an - /// attempt-indexed arm; the QUOTED values in the initializer are - /// collected. Bare integers in the initializer (`attempt % 2`) are - /// deliberately NOT read as flag values. - /// 2. `for in [0usize, 1]` / `["0", "1"]` -- a loop over both - /// values; every element of the array is collected. - /// 3. `for (, ) in [("1", 8u8), ("0", 8u8), ...]` -- a - /// tuple-destructured loop; only the element at ``'s POSITION is - /// collected from each tuple, so the arm table's bit-depth column is - /// not read as a flag value. - /// 4. `u8::from(.)` over a struct-literal arm table whose - /// `field: true` / `field: false` rows are the flag values. - /// - /// `None` means the binding is NOT in this body -- the variable is a - /// parameter of a shared helper and its value is bound at the CALL SITE, - /// which lives in a different `#[`-segment. That is a real limit of a - /// per-segment census and is reported as unknown rather than guessed: - /// inferring the value from the variable's name is the exact failure this - /// function exists to remove. - fn bound_values(body: &str, var: &str) -> Option> { - // Quoted single digits: `"0"`, `"1"`. - let quoted_digits = |t: &str| -> BTreeSet { - let mut out = BTreeSet::new(); - let mut at = 0usize; - while let Some(rel) = t[at..].find('"') { - let start = at + rel + 1; - let Some(end) = t[start..].find('"') else { - break; - }; - let literal = &t[start..start + end]; - if literal.len() == 1 - && let Some(c) = literal.chars().next() - && c.is_ascii_digit() { - out.insert(c); - } - at = start + end + 1; - } - out - }; - // Bare integer literals: `0usize`, `1`, `8u8`. Whole tokens only, so - // `10u8` contributes nothing rather than a bogus `1`. - let bare_digits = |t: &str| -> BTreeSet { - let mut out = BTreeSet::new(); - let bytes = t.as_bytes(); - let mut i = 0usize; - while i < bytes.len() { - if !bytes[i].is_ascii_digit() { - i += 1; - continue; - } - let start = i; - while i < bytes.len() && bytes[i].is_ascii_digit() { - i += 1; - } - let clean_before = start == 0 || !is_ident_byte(bytes[start - 1]); - // A typed literal's suffix (`0usize`, `8u8`, `1u32`) belongs to - // the same token, so a run of LOWERCASE letters right after - // the digit is a type, not a different identifier. Anything - // else -- a multi-digit `10u8`, a camelCase `1x` -- is not a - // flag value and is rejected. - let rest = &t[i..]; - let suffix = rest - .bytes() - .take_while(|b| b.is_ascii_lowercase() || *b == b'_') - .count(); - let clean_after = i >= bytes.len() - || !is_ident_byte(bytes[i]) - || (suffix > 0 - && i + suffix < bytes.len() - && !is_ident_byte(bytes[i + suffix])); - if clean_before && clean_after && i - start == 1 { - out.insert(bytes[start] as char); - } - } - out - }; - // Split a comma-separated list at TOP level only, so `("1", 8u8)` - // stays one element. - fn split_top(t: &str) -> Vec<&str> { - let mut out = Vec::new(); - let (mut depth, mut start) = (0i32, 0usize); - for (i, c) in t.char_indices() { - match c { - '(' | '[' | '{' => depth += 1, - ')' | ']' | '}' => depth -= 1, - ',' if depth == 0 => { - out.push(t[start..i].trim()); - start = i + 1; - } - _ => {} - } - } - if start < t.len() { - out.push(t[start..].trim()); - } - out - } - // The body of the `[...]` that FOLLOWS `head` in `text`. Scoped to - // the header rather than searching from the start of the body: a - // gate's first `[` may be an unrelated array, and brackets that do - // not balance across a whole gate body would leave the depth count - // never returning to zero. - fn loop_array_after<'a>(text: &'a str, head: &str) -> Option<&'a str> { - let at = text.find(head)? + head.len(); - let open = at + text[at..].find('[')?; - let mut depth = 0i32; - for (i, c) in text[open..].char_indices() { - match c { - '[' => depth += 1, - ']' => { - depth -= 1; - if depth == 0 { - return Some(&text[open + 1..open + i]); - } - } - _ => {} - } - } - None - } - let mut found: Option> = None; - let mut merge = |set: BTreeSet| match &mut found { - Some(all) => all.extend(set), - None => found = Some(set), - }; - // (1) `let = if ... { "0" } else { "1" };` -- quoted values only. - if let Some(at) = body.find(&format!("let {var} =")) { - let init = &body[at..]; - let end = init.find(';').unwrap_or(init.len()); - merge(quoted_digits(&init[..end])); - } - // (2) `for in [...]` -- every element of the array. - if let Some(array) = loop_array_after(body, &format!("for {var} in ")) { - merge(bare_digits(array)); - merge(quoted_digits(array)); - } - // (3) `for (, ...) in [(...), ...]` -- only ``'s column. - if let Some(at) = body.find("for (") { - let head = &body[at..]; - if let Some(close) = head.find(')') { - let pattern = &head["for (".len()..close]; - if let Some(pos) = pattern.split(',').position(|p| p.trim() == var) { - let header = format!("for ({pattern}) in "); - if let Some(array) = loop_array_after(body, &header) { - let mut set: BTreeSet = BTreeSet::new(); - for tuple in split_top(array) { - let Some(inner) = - tuple.strip_prefix('(').and_then(|t| t.strip_suffix(')')) - else { - continue; - }; - let fields = split_top(inner); - let Some(field) = fields.get(pos) else { - continue; - }; - set.extend(bare_digits(field)); - set.extend(quoted_digits(field)); - } - merge(set); - } - } - } - } - // (3b) `for (, ...) in ` where `` is a `let` - // binding in this same body -- the arm table hoisted OUT of the - // loop header, so the `for` line NAMES the array instead of - // spelling it. Strategy (3) alone silently reads past the `for` - // line to the next `[` in the body (an unrelated `&[..]` flag - // list), finds no digits, and returns an empty set: the gate is - // then filed as UNRESOLVED even though both of its arms sit - // verbatim in the source. Measured: the 128x96 4:4:4 lossy - // tx-size-search gate, whose `for (label, search, ...) in arms` - // drove `print_tx_size_search_census`'s `unresolvable == 0` - // assertion red on merge. The `=` hop matters: the binding's - // TYPE annotation is itself bracketed - // (`[(&str, &str, TxMode, usize, u64); 2]`), so scanning for the - // first `[` after the name would return the type. - // ``'s column, read off the arm table a hoisted `for` line - // NAMES rather than spells. Returns `None` unless the body really - // has that shape, so an unrecognised loop is left to the other - // strategies instead of being read as "no values". - let named_column = |pos: usize| -> Option> { - let at = body.find("for (")?; - let head = &body[at..]; - let close = head.find(')')?; - let after = head[close + 1..].trim_start().strip_prefix("in ")?; - let name: &str = after - .split(|c: char| !is_ident_byte(c as u8)) - .next() - .filter(|n| !n.is_empty() && !n.starts_with(|c: char| c.is_ascii_digit()))?; - let decl = body.find(&format!("let {name}"))?; - let after_name = decl + "let ".len() + name.len(); - // `let arms_foo` must not answer for `let arms`. - if body[after_name..] - .chars() - .next() - .is_some_and(|c| is_ident_byte(c as u8)) - { - return None; - } - // Hop the `=`: the binding's TYPE annotation is itself - // bracketed, so the first `[` after the name is the type. - let eq = after_name + body[after_name..].find('=')?; - let open = eq + 1 + body[eq + 1..].find('[')?; - let mut depth = 0i32; - for (i, c) in body[open..].char_indices() { - match c { - '[' => depth += 1, - ']' => { - depth -= 1; - if depth == 0 { - let mut set: BTreeSet = Default::default(); - for tuple in split_top(&body[open + 1..open + i]) { - let Some(inner) = - tuple.strip_prefix('(').and_then(|t| t.strip_suffix(')')) - else { - continue; - }; - let fields = split_top(inner); - let Some(field) = fields.get(pos) else { - continue; - }; - set.extend(bare_digits(field)); - set.extend(quoted_digits(field)); - } - return Some(set); - } - } - _ => {} - } - } - None - }; - if let Some(at) = body.find("for (") { - let head = &body[at..]; - if let Some(close) = head.find(')') { - let pattern = &head["for (".len()..close]; - if let Some(pos) = pattern.split(',').position(|p| p.trim() == var) - && let Some(set) = named_column(pos) { - merge(set); - } - } - } - // (4) `u8::from(.)` over a struct-literal arm table. - for (i, _) in body.match_indices("u8::from(") { - let arg = &body[i + "u8::from(".len()..]; - let Some(close) = arg.find(')') else { continue }; - let field = arg[..close].rsplit('.').next().unwrap_or_default().trim(); - if field.is_empty() || !field.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') { - continue; - } - let mut set = BTreeSet::new(); - for (row, value) in [("true", '1'), ("false", '0')] { - if body.contains(&format!("{field}: {row}")) { - set.insert(value); - } - } - merge(set); - } - found - } - - fn is_ident_byte(b: u8) -> bool { - b.is_ascii_alphanumeric() || b == b'_' - } - - /// Values of one [`DEFAULT_ON_TOOLS`] spelling in one gate body: the - /// literal `--=` spellings plus every value a `format!` - /// template built from a local binding resolves to. - /// - /// A gate that reaches BOTH values counts ON, not off: it builds a `=1` - /// stream on some attempt, which is what the census asks for. This is the - /// file's standing "any spelling that says on wins" rule - /// (`--tile-columns=0 --tile-rows=1` is a multi-tile stream), now applied - /// across a loop's arms as well as across spellings. - fn spelling_values(gate: &str, spelling: &str) -> BTreeSet { - let mut out = BTreeSet::new(); - // A literal `"--="`: the needle ends at the `=`, so - // the value starts AT the needle's length, not three characters in. - let literal = format!("\"--{spelling}="); - for (i, _) in gate.match_indices(&literal) { - let rest = &gate[i + literal.len()..]; - let Some(end) = rest.find('"') else { continue }; - if let Some(c) = rest[..end].chars().next() - && c.is_ascii_digit() { - out.insert(c); - } - } - // A template `format!("--={}")`: the placeholder name - // is the part between the braces, and its VALUE is whatever the - // binding of `` in this same body reaches. - let template = format!("format!(\"--{spelling}="); - for (i, _) in gate.match_indices(&template) { - let rest = &gate[i + template.len()..]; - let Some(end) = rest.find('"') else { continue }; - let Some(var) = rest[..end] - .strip_prefix('{') - .and_then(|v| v.strip_suffix('}')) - else { - continue; - }; - if var.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') { - out.extend(bound_values(gate, var).unwrap_or_default()); - } - } - out - } - - /// Whether a gate body spells one [`DEFAULT_ON_TOOLS`] entry on / off, - /// over [`spelling_values`] -- so a `format!`-built flag is classified - /// instead of being filed as "defaulted". - fn resolved_on_state(gate: &str, spellings: &[&str], on: On) -> Option { - let mut state = None; - for spelling in spellings { - for c in spelling_values(gate, spelling) { - let value = c.to_digit(10).unwrap_or(0); - let is_on = match on { - On::NonZero => value != 0, - On::AtMost(limit) => value <= limit, - }; - state = Some(state.unwrap_or(false) || is_on); - } - } - state - } - - /// `--enable-*` settings per real-aomenc gate, derived from the gate - /// source: `flag -> (turned off in N gates, turned on in N, defaulted in N)`. - fn tool_settings() -> (usize, BTreeMap) { - let gates = gate_bodies(); - - let mut per_tool: BTreeMap = BTreeMap::new(); - let mut names: BTreeSet = BTreeSet::new(); - let mut seen: Vec> = Vec::new(); - for gate in &gates { - let here = flags_in(gate); - names.extend(here.keys().cloned()); - seen.push(here); - } - for name in names { - let off = seen.iter().filter(|g| g.get(&name) == Some(&'0')).count(); - let on = seen.iter().filter(|g| g.get(&name) == Some(&'1')).count(); - per_tool.insert(name, (off, on, gates.len() - off - on)); - } - (gates.len(), per_tool) - } - - #[test] - fn every_gate_disabling_a_tool_is_a_listed_coverage_hole() { - let (gate_count, per_tool) = tool_settings(); - // A hole OPENS when every gate names the flag and every one of them - // says 0 -- then no real stream can exercise the tool. - let derived: BTreeSet<&str> = per_tool - .iter() - .filter(|&(_, &(off, on, defaulted))| off == gate_count && on == 0 && defaulted == 0) - .map(|(name, _)| name.as_str()) - .collect(); - // A hole CLOSES only on positive evidence: some gate passes `=1`. - // A gate that merely leaves the flag off its command line proves - // nothing -- aomenc's default for palette and intrabc is content- - // dependent -- so "defaulted" must not retire an entry, or a listing - // would disappear the moment an unrelated gate is added. - let exercised: BTreeSet<&str> = per_tool - .iter() - .filter(|&(_, &(_, on, _))| on > 0) - .map(|(name, _)| name.as_str()) - .collect(); - let listed: BTreeSet<&str> = NEVER_EXERCISED.iter().map(|&(flag, _)| flag).collect(); - - let unlisted: Vec<&&str> = derived.difference(&listed).collect(); - assert!( - unlisted.is_empty(), - "these aomenc tools are switched off in all {gate_count} real-aomenc gates and on in \ - none, so no real stream exercises them, and they are not listed in NEVER_EXERCISED: \ - {unlisted:?} -- either enable the tool with `=1` in its own gate or add it to the \ - list with a reason" - ); - let stale: Vec<&&str> = listed.intersection(&exercised).collect(); - assert!( - stale.is_empty(), - "NEVER_EXERCISED lists {stale:?}, but a gate now passes `=1` for them -- delete \ - those entries, the coverage hole is closed" - ); - } - - /// The derivation is only meaningful if a flag left off a gate's command - /// line really does mean "aomenc's default", i.e. the parser above is - /// reading whole flags and not fragments. - #[test] - fn tool_settings_reads_whole_flags() { - let (gate_count, per_tool) = tool_settings(); - assert!( - per_tool.contains_key("enable-cdef"), - "expected --enable-cdef among the gate flags" - ); - for (name, &(off, on, defaulted)) in &per_tool { - assert!( - !name.is_empty() && !name.contains(['"', '=']), - "malformed flag {name:?}" - ); - assert_eq!( - off + on + defaulted, - gate_count, - "{name} counts do not cover every gate" - ); - } - } - - /// A gate encodes at 10 bits when its recipe says so: the shared 10-bit - /// helper, an explicit `--bit-depth=10`/`--input-bit-depth=10`, or a - /// `yuv420p10le` fixture handed to aomenc. Everything else is aomenc's - /// 8-bit default. - /// lane-defon r1: a gate helper parameterised on `bit_depth` builds BOTH - /// an 8-bit and a 10-bit stream from one recipe, so its flags cover both - /// depths -- classifying it by the 10-bit strings inside its conditional - /// alone hid `--enable-tx-size-search=1` from the 8-bit list. - /// lane-reelckf r1: the same blind spot with the other spelling -- a gate - /// that loops `for depth in [8usize, 10]` builds BOTH streams from one - /// recipe, but its `yuv420p10le` arm made `is_ten_bit` classify it as - /// 10-bit only, hiding `--enable-cfl-intra=1` from the 8-bit list. - /// lane-av1-intrabc r1: the shared recipe helper - /// `screen_intrabc_stream_at_depth` is parameterised on `depth` and sits in - /// the segment that opens at the PRECEDING gate's `#[test]`, so without - /// this marker that gate's own 8-bit-only flags read as 10-bit-only -- the - /// lane-defon/reelckf blind spot with `depth` spelled instead of - /// `bit_depth`. Three gates share the helper, at both depths. - /// lane-av1distwtd r3: the THIRD spelling of the same blind spot, still - /// live after lane-defon and lane-reelckf. A recipe parameterised on - /// `ten_bit` names BOTH fixture formats in one body -- `let pix_fmt = if - /// ten_bit { "yuv420p10le" } else { "yuv420p" };` -- so `is_ten_bit` saw - /// the 10-bit arm and filed the whole body 10-bit-ONLY, hiding its 8-bit - /// arm from the 8-bit bucket. The marker is the PAIR OF FORMATS, not the - /// parameter name: a body spelling both pixel formats builds streams at - /// both depths, whatever it calls the flag. The quotes matter -- a bare - /// `yuv420p` substring test also matches `yuv420p10le` and would fire on - /// every 10-bit gate, retiring entries on no evidence. - /// - /// This is what mis-filed `a_real_aomenc_stream_with_a_1d_tx_class_on_a_rect_transform_decodes_pixel_exact` - /// and kept `enable-flip-idtx` on the 8-bit list while that gate ran 6 - /// pixel-exact 8-bit decodes through it. - fn covers_both_depths(body: &str) -> bool { - body.contains("if bit_depth == 10") - || body.contains("if depth == 10") - || body.contains("for depth in [8usize, 10]") - || (body.contains("\"yuv420p\"") && body.contains("\"yuv420p10le\"")) - } - - /// lane-av1distwtd r3: the detector fix, pinned. A detector change with - /// no test can only be shown to find MORE, never to stop missing, so this - /// asserts the three gates the two blind spots actually hid are now seen - /// -- the two `enable-dual-filter` witnesses and the `enable-flip-idtx` - /// both-depths gate -- and that the fix is strictly ADDITIVE against the - /// old spelling-only filter. - #[test] - fn the_detector_sees_the_gates_the_spelling_filter_missed() { - let src = crate::test_source::module_source("stream"); - let gates = gate_bodies(); - // The helper-delegation half: each of these builds its stream through - // `inter_sb_none_gate` and spells none of `legacy_gate_tokens`, so the - // old filter dropped both while each hard-asserts its tool arrived. - for name in [ - "a_real_aomenc_dual_filter_obmc_8x8_inter_sequence_decodes_pixel_exact", - "a_real_obmc_stream_reads_a_recorded_switchable_filter_for_every_neighbour", - ] { - let body = gates - .iter() - .find(|b| b.contains(name)) - .unwrap_or_else(|| panic!("{name}: not seen by gate_bodies()")); - assert_eq!( - flags_in(body).get("enable-dual-filter"), - Some(&'1'), - "{name}: seen, but its --enable-dual-filter=1 spelling is not visible to \ - flags_in, so recognising the gate would not retire the entry" - ); - } - // The both-depths half: this gate's recipe is parameterised on `ten_bit` - // and names both fixture formats, so `covers_both_depths` must credit - // it to the 8-bit bucket, not just the 10-bit one. - let flip = gates - .iter() - .find(|b| b.contains("a_real_aomenc_stream_with_a_1d_tx_class_on_a_rect_transform")) - .expect("the flip-idtx gate must be seen"); - assert!( - covers_both_depths(flip), - "the flip-idtx gate spells both fixture formats, so covers_both_depths must \ - credit it to the 8-bit bucket as well" - ); - assert!( - covers_depth(flip, false) && covers_depth(flip, true), - "the flip-idtx gate must cover BOTH depths" - ); - // Strictly additive: every segment the old spelling-only filter kept - // is still kept, so the fix cannot have cost the census a gate. - let legacy_only: Vec<&str> = src - .split("\n #[") - .filter(|b| !b.starts_with("ignore") && legacy_gate_tokens(b)) - .collect(); - assert!( - legacy_only.len() < gates.len(), - "the call-resolving filter found {} gates, the old spelling-only filter found \ - {} -- the fix is expected to ADD gates, never to drop one", - gates.len(), - legacy_only.len() - ); - for body in &legacy_only { - assert!( - gates.contains(body), - "a gate the spelling-only filter recognised is no longer recognised: \ - {:?}", - &body[..body.len().min(60)] - ); - } - } - - /// Whether a gate body drives a stream at this depth. - fn covers_depth(body: &str, ten_bit: bool) -> bool { - covers_both_depths(body) || is_ten_bit(body) == ten_bit - } - - fn is_ten_bit(body: &str) -> bool { - // The lists pin two buckets, 8-bit and high-bit-depth; 12-bit gates - // count in the high-depth bucket (lane-av1gwarp12's ROTZOOM gate was - // the first 12-bit gate to positively enable a listed tool, and the - // 10-bit-only spellings mis-filed it as 8-bit). - body.contains("encode_10bit_gradients") - || body.contains("ten_bit_tool_gate(") - || body.contains("--bit-depth=10") - || body.contains("--input-bit-depth=10") - || body.contains("yuv420p10le") - || body.contains("encode_12bit(") - || body.contains("--bit-depth=12") - || body.contains("--input-bit-depth=12") - || body.contains("yuv420p12le") - } - - /// Flags a gate positively enables (`=1`), at gates of the given depth. - fn enabled_at(ten_bit: bool) -> BTreeSet { - let mut on = BTreeSet::new(); - for gate in gate_bodies() { - if !covers_depth(gate, ten_bit) { - continue; - } - for (flag, value) in flags_in(gate) { - if value == '1' { - on.insert(flag); - } - } - // A tool driven by its own spelling counts as exercised. - let here = settings_in(gate); - for (alias, tool) in ALIASES { - if here.get(*alias).is_some_and(|v| v != "0") { - on.insert((*tool).to_owned()); - } - } - } - on - } - - /// The tools of [`TOOL_UNIVERSE`] that no gate of this depth enables. - fn never_exercised_at(ten_bit: bool) -> BTreeSet<&'static str> { - let on = enabled_at(ten_bit); - TOOL_UNIVERSE - .iter() - .copied() - .filter(|t| !on.contains(*t)) - .collect() - } - - fn check_depth(ten_bit: bool, listed: &[(&str, &str)]) { - let derived = never_exercised_at(ten_bit); - let listed: BTreeSet<&str> = listed.iter().map(|&(flag, _)| flag).collect(); - let depth = if ten_bit { "10-bit" } else { "8-bit" }; - let unlisted: Vec<&&str> = derived.difference(&listed).collect(); - assert!( - unlisted.is_empty(), - "no {depth} gate passes `=1` for {unlisted:?}, so no real {depth} stream exercises \ - them -- enable the tool in a {depth} gate that asserts it fired, or list it" - ); - let stale: Vec<&&str> = listed.difference(&derived).collect(); - assert!( - stale.is_empty(), - "the {depth} list still names {stale:?}, but a {depth} gate now passes `=1` for them \ - -- delete those entries, the coverage hole is closed" - ); - } - - #[test] - fn never_exercised_8bit_matches_the_gate_recipes() { - check_depth(false, NEVER_EXERCISED_8BIT); - } - - #[test] - fn never_exercised_10bit_matches_the_gate_recipes() { - check_depth(true, NEVER_EXERCISED_10BIT); - } - - /// `cargo test -p ec-av1 --lib gate_coverage -- --nocapture` prints both - /// lists, so the per-depth holes can be read without opening this file. - #[test] - fn print_never_exercised_per_bit_depth() { - let ten: Vec<&str> = gate_bodies() - .into_iter() - .filter(|b| is_ten_bit(b)) - .collect(); - let total = gate_bodies().len(); - println!( - "gate_coverage: {} real-aomenc gates, {} of them 10-bit", - total, - ten.len() - ); - for (label, ten_bit) in [("8BIT", false), ("10BIT", true)] { - let holes = never_exercised_at(ten_bit); - println!( - "NEVER_EXERCISED_{label} ({} of {}):", - holes.len(), - TOOL_UNIVERSE.len() - ); - for flag in &holes { - println!(" --{flag}"); - } - } - } - - /// [`DEFAULT_ON_TOOLS`] per depth: `tool -> (off in N gates, on in N, defaulted in N)`. - fn default_on_settings( - ten_bit: bool, - ) -> (usize, BTreeMap<&'static str, (usize, usize, usize)>) { - let gates: Vec<&str> = gate_bodies() - .into_iter() - .filter(|b| covers_depth(b, ten_bit)) - .collect(); - let mut per_tool = BTreeMap::new(); - for &(tool, spellings, _, on) in DEFAULT_ON_TOOLS { - // lane-av1txsearch: `resolved_on_state`, not `default_on_state` -- - // the literal-only reader filed every `format!`-built flag as - // "defaulted", which is unknown rather than measured. - let states: Vec> = gates - .iter() - .map(|g| resolved_on_state(g, spellings, on)) - .collect(); - let turned_on = states.iter().filter(|s| **s == Some(true)).count(); - let turned_off = states.iter().filter(|s| **s == Some(false)).count(); - per_tool.insert( - tool, - (turned_off, turned_on, gates.len() - turned_off - turned_on), - ); - } - (gates.len(), per_tool) - } - - /// The [`DEFAULT_ON_TOOLS`] no gate of this depth positively enables. - fn never_on_at(ten_bit: bool) -> BTreeSet<&'static str> { - default_on_settings(ten_bit) - .1 - .into_iter() - .filter(|&(_, (_, on, _))| on == 0) - .map(|(tool, _)| tool) - .collect() - } - - fn check_default_on(ten_bit: bool, listed: &[(&str, &str)]) { - let derived = never_on_at(ten_bit); - let listed: BTreeSet<&str> = listed.iter().map(|&(tool, _)| tool).collect(); - let depth = if ten_bit { "10-bit" } else { "8-bit" }; - let unlisted: Vec<&&str> = derived.difference(&listed).collect(); - assert!( - unlisted.is_empty(), - "no {depth} gate spells an on-value for {unlisted:?}, so no real {depth} stream is \ - proven to carry them -- switch the tool on in a {depth} gate that asserts it fired, \ - or list it with a reason" - ); - let stale: Vec<&&str> = listed.difference(&derived).collect(); - assert!( - stale.is_empty(), - "the {depth} default-on list still names {stale:?}, but a {depth} gate now switches \ - them on -- delete those entries, the coverage hole is closed" - ); - } - - #[test] - fn never_on_8bit_matches_the_gate_recipes() { - check_default_on(false, NEVER_ON_8BIT); - } - - #[test] - fn never_on_10bit_matches_the_gate_recipes() { - check_default_on(true, NEVER_ON_10BIT); - } - - /// A tool must not be pinned twice: [`TOOL_UNIVERSE`] already derives the - /// `--enable-*` spellings under the `=1` rule. - #[test] - fn default_on_tools_do_not_duplicate_the_universe() { - for &(tool, spellings, _, _) in DEFAULT_ON_TOOLS { - assert!( - !TOOL_UNIVERSE.contains(&tool), - "{tool} is already covered by TOOL_UNIVERSE" - ); - assert!(!spellings.is_empty(), "{tool} has no aomenc spelling"); - } - for (alias, tool) in ALIASES { - assert!( - TOOL_UNIVERSE.contains(tool), - "alias --{alias} names {tool}, which is not a TOOL_UNIVERSE tool" - ); - } - } - - /// `cargo test -p ec-av1 --lib gate_coverage -- --nocapture` prints the - /// default-on holes with their off/defaulted split. - #[test] - fn print_never_on_per_bit_depth() { - for (label, ten_bit) in [("8BIT", false), ("10BIT", true)] { - let (gate_count, per_tool) = default_on_settings(ten_bit); - let holes = never_on_at(ten_bit); - println!( - "NEVER_ON_{label} ({} of {}, over {gate_count} {label} gates):", - holes.len(), - DEFAULT_ON_TOOLS.len() - ); - for tool in &holes { - let (off, _, defaulted) = per_tool[tool]; - let spellings = DEFAULT_ON_TOOLS - .iter() - .find(|e| e.0 == *tool) - .map(|e| e.1.join(",")) - .unwrap_or_default(); - println!( - " {tool} (--{spellings}): off in {off}, defaulted in {defaulted}, on in 0" - ); - } - } - } - - /// lane-av1txsearch: the `enable-tx-size-search` census, MEASURED rather - /// than floored. Prints, per gate body, the values the resolver reads for - /// the flag -- literal spellings and `format!` templates alike -- and the - /// three-way split at the end. Re-run it after any gate recipe change: - /// - /// `cargo test -p ec-av1 --lib gate_coverage::tests::print_tx_size_search_census -- --nocapture` - #[test] - fn print_tx_size_search_census() { - const TOOL: &str = "enable-tx-size-search"; - let (zero, one, both, unresolvable, unnamed) = { - let (mut zero, mut one, mut both, mut unresolvable, mut unnamed) = - (0usize, 0usize, 0usize, 0usize, 0usize); - for gate in gate_bodies() { - let values = spelling_values(gate, TOOL); - let name = gate - .split("fn ") - .nth(1) - .and_then(|s| s.split('(').next()) - .unwrap_or("") - .to_owned(); - let state = match (values.contains(&'0'), values.contains(&'1')) { - (false, false) => { - unnamed += 1; - "not named (defaulted)" - } - (true, false) => { - zero += 1; - "=0" - } - (false, true) => { - one += 1; - "=1" - } - (true, true) => { - both += 1; - "=0 and =1 (one arm each)" - } - }; - let via = if gate.contains(&format!("format!(\"--{TOOL}=")) { - " [format! template resolved]" - } else { - "" - }; - // A segment that does not open at a `#[test]` is glued non-test helper - // text from a split module (the support helpers have no attribute between - // them), so its `format!` parameter is not a gate's own value. - let helper = if gate.starts_with("test]") - && gate.contains(&format!("format!(\"--{TOOL}=")) - && values.is_empty() - { - " [UNRESOLVED: variable is a shared helper's parameter]" - } else { - "" - }; - if !helper.is_empty() { - unresolvable += 1; - unnamed -= 1; - } - println!("{name}: {state}{via}{helper}"); - } - (zero, one, both, unresolvable, unnamed) - }; - let total = gate_bodies().len(); - println!( - "enable-tx-size-search over {total} census-selected gate bodies: \ - =0 only {zero}, =1 only {one}, both {both}, unresolvable {unresolvable}, \ - not named {unnamed}" - ); - assert_eq!( - unresolvable, 0, - "{unresolvable} gate bodies build --{TOOL} into a variable this census cannot bind -- \ - the count is a floor again, and an unknown direction is the failure mode this file \ - exists to prevent" - ); - } - - /// lane-av1txsearch: the RED-BEFORE proof for the template resolver, in - /// both directions, on the gate bodies that actually exist. - /// - /// Direction 1 -- a `format!`-built value MOVES the classification. Each - /// case below takes a real gate body, mutates only the bound value, and - /// asserts the resolved state changed. A resolver that found nothing - /// would read every one of these as "not named" and fail all four. - /// - /// Direction 2 -- a spelling the LITERAL reader already saw still - /// classifies. Without this half, a resolver that overwrote the literal - /// path would pass direction 1 while losing the 15 `=1` gates the census - /// already counted. - #[test] - fn the_resolver_binds_a_format_built_flag_in_both_directions() { - let gates = gate_bodies(); - let find = |needle: &str| -> &'static str { - gates - .iter() - .copied() - .find(|b| b.contains(needle)) - .unwrap_or_else(|| panic!("no gate body contains {needle:?}")) - }; - // Direction 1, one per template shape. - let cases = [ - ( - "format!(\"--enable-tx-size-search={txs}\")", - "for txs in [0usize, 1]", - "for txs in [0usize, 0]", - "a_real_aomenc_palette_stream_with_8x8_leaves_decodes_pixel_exact", - ), - ( - "format!(\"--enable-tx-size-search={tx_search}\")", - "if attempt % 2 == 0 { \"0\" } else { \"1\" }", - "if attempt % 2 == 0 { \"0\" } else { \"0\" }", - "a_real_aomenc_inter_sequence_with_a_coded_rectangular_residual_decodes_pixel_exact", - ), - ( - "format!(\"--enable-tx-size-search={tx_search}\")", - "for (tx_search, bit_depth) in [(\"1\", 8u8), (\"0\", 8u8), (\"1\", 10u8)]", - "for (tx_search, bit_depth) in [(\"0\", 8u8), (\"0\", 8u8), (\"0\", 10u8)]", - "a_real_aomenc_stream_with_filter_intra_on_a_sub8_rect_leaf_decodes_pixel_exact", - ), - // The arm table hoisted OUT of the `for` line into a named - // `let` -- the shape lane-av1lossy128x96 writes, and the one - // that reads as UNRESOLVED unless the `for` line's collection - // name is followed back to its binding. Without this case a - // resolver that only understood inline arrays passes the - // three above and still cannot bind this gate. - ( - "format!(\"--enable-tx-size-search={search}\")", - "\"tx size search on\",\n \"1\",", - "\"tx size search on\",\n \"0\",", - "a_real_aomenc_444_whole_64_root_tx_size_search_stream_decodes_pixel_exact_at_128x96", - ), - ]; - for (template, from, to, name) in cases { - let body = find(name); - assert!( - body.contains(template), - "{name} does not spell {template}, so this case proves nothing" - ); - assert!( - body.contains(from), - "{name} does not contain the source binding {from:?}" - ); - let before = spelling_values(body, "enable-tx-size-search"); - let mutated = body.replace(from, to); - assert_ne!( - mutated, body, - "the mutation {from:?} -> {to:?} changed nothing" - ); - let after = spelling_values(&mutated, "enable-tx-size-search"); - assert_eq!( - before, - BTreeSet::from(['0', '1']), - "{name}: the unmutated body should resolve to both values, got {before:?}" - ); - assert_eq!( - after, - BTreeSet::from(['0']), - "{name}: mutating the bound value {from:?} -> {to:?} did not move the \ - classification (still {after:?}) -- the resolver is not reading the binding" - ); - } - // Direction 2: every gate the LITERAL reader already classified as - // `=1` still is. Asserted as CONTAINMENT, not equality: a segment may - // spell the flag twice (`=0` in the base recipe, `=1` as the per-arm - // override), and the old reader took the last one while the resolver - // takes the set. The claim being pinned is "still on", which is the - // direction a regression would lose. - let mut pinned = 0usize; - for gate in &gates { - if !gate.contains("\"--enable-tx-size-search=1\"") { - continue; - } - pinned += 1; - assert!( - spelling_values(gate, "enable-tx-size-search").contains(&'1'), - "a gate that literally spells --enable-tx-size-search=1 is no longer \ - classified on: {:?}", - &gate[..gate.len().min(80)] - ); - } - assert!( - pinned >= 10, - "expected the literal `=1` gates to still be there, found {pinned}" - ); - } - - /// lane-av1oracleskip: the ORACLE-PRESENCE SCAN — the mechanical - /// anti-regression for the skip class this lane closed. - /// - /// Why a scan and not a review rule: the r2 sweep found FIVE gates that - /// had been added with the bare `if aomdec_path().is_file() { …compare… }` - /// shape AFTER the first fix had already routed thirteen sites — every one - /// of them compiled, passed review and reported green with the oracle - /// compare silently skipped, under `EC_AV1_REQUIRE_AOMENC=1`. A guard - /// written the old way re-opens the class the moment it merges, so the - /// only thing that holds is a check that reads the source itself. - /// - /// The rule: a TOOL PRESENCE CHECK (`aomenc_path().is_file()`, - /// `aomdec_path().is_file()`, `affine_aomenc_path().is_file()`, plain or - /// `!…` inverted) may appear ONLY - /// 1. inside the body of the probe that owns that path - /// (`have_aomenc`, `aomdec_available`, `have_affine_aomenc`) — that - /// is where the assert-last and the env escape live, and - /// 2. inside an `assert!` (the deliberate hard-failure form), or - /// 3. in a comment, which cannot execute. - /// Anything else is a skip with no env escape, and the test fails naming - /// the exact `file:line`. - /// - /// THE FLOOR. A source scan that matches nothing is the false-pass shape - /// this crate has been bitten by twice (a `format!` brace escape, and - /// `args.find(')')` stopping at the wrong paren), so the scan refuses to - /// pass unless it actually inspected a plausible number of sites: the - /// count is printed and asserted against `MIN_SITES`. A probe that moved - /// out of the scan's reach, or a matcher broken by a rename, reds here - /// instead of reporting a clean bill of health. - #[test] - fn no_tool_presence_check_outside_its_probe() { - /// Below this, the scan is not looking at the tree it thinks it is. - /// Five is the STRUCTURAL floor: three probes (whose existence the span - /// assert below already pins) plus the two hard `assert!` sites. Doc - /// comments mentioning the old shape come and go with the prose, so - /// they are counted but never load-bearing here. - const MIN_SITES: usize = 5; - /// (file, the line that opens the probe owning that path) - const PROBES: &[(&str, &str)] = &[ - ("stream.rs", "fn have_aomenc()"), - ("stream.rs", "fn aomdec_available("), - ("stream.rs", "fn have_affine_aomenc()"), - ]; - const PATHS: &[&str] = &[ - "aomenc_path().is_file()", - "aomdec_path().is_file()", - "affine_aomenc_path().is_file()", - ]; - let files: [(&str, &str); 3] = [ - ("stream.rs", crate::test_source::module_source("stream")), - ("decode.rs", crate::test_source::module_source("decode")), - ("encode.rs", crate::test_source::module_source("encode")), - ]; - - // The line range each probe body owns: from its opener to the first - // following line that closes it at column 0. - let mut probe_spans: Vec<(usize, usize)> = Vec::new(); - for (name, src) in files { - let lines: Vec<&str> = src.lines().collect(); - for (probe_file, opener) in PROBES { - if *probe_file != name { - continue; - } - let Some(start) = lines.iter().position(|l| l.contains(opener)).map(|i| i + 1) - else { - continue; - }; - let end = lines - .iter() - .skip(start) - .position(|l| l.trim_end() == "}") - .map(|off| start + off) - .unwrap_or(lines.len()); - probe_spans.push((start, end)); - } - } - assert!( - probe_spans.len() == PROBES.len(), - "the oracle-presence scan recognised {} of the {} probe bodies it is meant to \ - exempt ({probe_spans:?}); a renamed or moved probe would silently exempt every \ - site in the crate, so it reds here", - probe_spans.len(), - PROBES.len() - ); - - let mut sites = 0usize; - let mut allowed = 0usize; - let mut per_pattern: BTreeMap<&str, usize> = PATHS.iter().map(|p| (*p, 0)).collect(); - let mut offenders: Vec = Vec::new(); - for (name, src) in files { - for (i, line) in src.lines().enumerate() { - // LONGEST match wins: `affine_aomenc_path().is_file()` CONTAINS - // `aomenc_path().is_file()`, so a first-match scan credits the - // affine probe's line to the aomenc pattern and the per-pattern - // floor below reds on a pattern that is very much present. (It - // did, on the first run of this test — which is the floor - // earning its place.) - let Some(path) = PATHS - .iter() - .filter(|p| line.contains(**p)) - .max_by_key(|p| p.len()) - else { - continue; - }; - sites += 1; - *per_pattern.get_mut(path).expect("pattern came from PATHS") += 1; - let lineno = i + 1; - let trimmed = line.trim_start(); - let in_probe = probe_spans - .iter() - .any(|(start, end)| lineno >= *start && lineno <= *end); - let in_assert = trimmed.starts_with("assert!") - || trimmed.starts_with("aomdec_path().is_file(),") - || trimmed.starts_with("aomenc_path().is_file(),") - || trimmed.starts_with("affine_aomenc_path().is_file(),"); - let in_comment = trimmed.starts_with("//"); - if in_probe || in_assert || in_comment { - allowed += 1; - } else { - offenders.push(format!( - "{name}:{lineno}: {}\n a tool presence check outside its probe — \ - route it through the probe that owns this path (`have_aomenc`, \ - `aomdec_available`, `have_affine_aomenc`): a bare `{path}` skips the \ - gate with NO env escape, so under EC_AV1_REQUIRE_AOMENC=1 the gate still \ - reports green with the oracle compare never run.", - line.trim() - )); - } - } - } - println!( - "oracle-presence scan: {sites} site(s) inspected, {allowed} in a probe / assert / \ - comment, {} offender(s); per pattern {per_pattern:?}", - offenders.len() - ); - // PER-PATTERN floor: a total count can hide one broken matcher (mutate - // ONE pattern and the other two still add up), so each of the three - // path patterns must be found at least once -- which the probe bodies - // guarantee, since each probe contains its own path's presence check. - let never_matched: Vec<&str> = per_pattern - .iter() - .filter(|(_, n)| **n == 0) - .map(|(p, _)| *p) - .collect(); - assert!( - never_matched.is_empty(), - "the oracle-presence scan matched NOTHING for {never_matched:?}: that pattern is \ - stale (renamed helper, `exists()` instead of `is_file()`, a `format!` escape) and \ - the gates it was meant to police would pass unreviewed. Matched per pattern: \ - {per_pattern:?}" - ); - assert!( - sites >= MIN_SITES, - "the oracle-presence scan inspected only {sites} site(s), below its floor of \ - {MIN_SITES}: the matcher has stopped matching this tree (renamed path helper, a \ - `format!` escape, a moved probe), and with no floor this would pass while scanning \ - nothing — the false-pass shape this crate has been bitten by twice" - ); - assert!( - offenders.is_empty(), - "{} bare tool presence check(s) outside a probe — each one is a gate that can report \ - green without running the oracle compare:\n {}", - offenders.len(), - offenders.join("\n ") - ); - } -} - -/// lane-av1pins5 r5: the PIN INVENTORY. -/// -/// The r3 inventory this replaces matched only two call shapes -- -/// `crate_pin("X")` and `pin_dir().join("X")` -- both SINGLE-NAME. A gate that -/// reads a whole DIRECTORY of pins through a `concat!` literal and then formats -/// a name at runtime (`format!("{fixtures}/{n}.obu")`) matched neither, so -/// `pinned_warp_stream_decodes_pixel_exact` and its 14 uncommitted pins were -/// invisible to it, and r3 reported "the machine-local-pin population is zero". -/// It was not. This enumerator resolves all four shapes. -/// -/// Ownership, stated because two lanes touch this: THIS scanner owns the -/// ENUMERATION (which gates read which pins, from source). The fixture-preflight -/// lane owns the FILE INVENTORY on a runner (does each referenced path exist on -/// the box). Different questions; both must agree, and this one is the stricter of -/// the two because it fails on an uncommitted pin whether or not some runner -/// happens to have a copy. -#[cfg(test)] -mod pin_inventory { - /// One pin a gate reads, and where it came from. - pub struct PinRead { - pub gate: String, - pub file: String, - pub shape: &'static str, - } - - /// Split `src` into `(fn_name, body)` for every `fn name(` at the gate indent. - fn gate_bodies(src: &str) -> Vec<(String, &'static str)> { - let mut out = Vec::new(); - let mut cur: Option<(String, usize)> = None; - for (i, line) in src.lines().enumerate() { - let t = line.trim_start(); - if let Some(rest) = t.strip_prefix("fn ") - && let Some(name) = rest.split('(').next() - && !name.contains(' ') { - cur = Some((name.to_string(), i)); - } - // A `#[test]`/`#[ignore]` line is never a closing brace, so the fn - // ends at the first line that is exactly four-space `}`. - if let Some((name, start)) = &cur - && i > *start && line == " }" { - let body = src - .lines() - .skip(*start) - .take(i - *start + 1) - .collect::>() - .join("\n"); - out.push((name.clone(), &*Box::leak(body.into_boxed_str()))); - cur = None; - } - } - out - } - - /// Every pin every gate reads, across all four shapes. - pub fn pins_read(src: &str) -> Vec { - let mut out = Vec::new(); - for (gate, body) in gate_bodies(src) { - // (a) crate_pin("X") and (b) pin_dir().join("X") -- single name. - for m in body.match_indices("crate_pin(\"") { - let rest = &body[m.0 + 11..]; - if let Some(e) = rest.find('"') { - out.push(PinRead { - gate: gate.clone(), - file: rest[..e].to_string(), - shape: "crate_pin", - }); - } - } - for m in body.match_indices("pin_dir().join(\"") { - let rest = &body[m.0 + 16..]; - if let Some(e) = rest.find('"') { - out.push(PinRead { - gate: gate.clone(), - file: rest[..e].to_string(), - shape: "pin_dir_machine_local", - }); - } - } - // (c) a whole-file concat! literal to a named pin: - // concat!(env!("CARGO_MANIFEST_DIR"), "/../../fixtures/X.obu") - for m in body.match_indices("/../../fixtures/") { - let rest = &body[m.0 + 16..]; - if let Some(e) = rest.find('"') { - out.push(PinRead { - gate: gate.clone(), - file: rest[..e].to_string(), - shape: "concat_literal_machine_local", - }); - } - } - // (d) the shape that hid 14 pins: a DIRECTORY literal bound to a - // local, plus a runtime `format!("{var}/{n}.ext")` over a - // literal name array. Resolve the array's names. - for (vi, line) in body.lines().enumerate() { - let tl = line.trim(); - // `let fixtures = concat!(env!("CARGO_MANIFEST_DIR"), "/../../fixtures");` - // -> the bound name is whatever sits between `let ` and the `=`. - let var = match ( - tl.find("concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/../../fixtures\")"), - tl.find('='), - ) { - (Some(a), Some(eq)) if eq < a => tl[4..eq].trim().to_string(), - _ => continue, - }; - if var.is_empty() { - continue; - } - // `format!("{fixtures}/{n}.obu")` -- built by concatenation, not - // by `format!`: escaping `{{`/`}}` to emit literal braces here is - // exactly the bug that made this shape resolve to 0 pins on the - // first run of the scanner. - let marker = ["format!(\"", "{", &var, "}/{n}"].concat(); - let Some(pos) = body.find(&marker) else { - continue; - }; - // Walk back from the format! to the `[ ... ].iter()` array and - // take every quoted name in it. - let head = &body[..pos]; - let Some(bracket) = head.rfind('[') else { - continue; - }; - let names: Vec = head[bracket..] - .split('"') - .skip(1) - .step_by(2) - .filter(|s| !s.is_empty() && !s.contains(' ') && *s != "]") - .map(|s| s.to_string()) - .collect(); - // `.obu` -- SLICE up to the closing quote. (Stringifying the - // `find` index instead produced names like `warp-mismatch4`.) - let tail = &body[pos + marker.len()..]; - let ext = tail - .find('"') - .map(|e| tail[..e].to_string()) - .unwrap_or_default(); - for n in names { - out.push(PinRead { - gate: gate.clone(), - file: format!("{n}{ext}"), - shape: "concat_dir_runtime_name", - }); - } - let _ = vi; - } - // (e) the shape this very fix INTRODUCED: - // `.map(|n| crate_pin(&format!("{n}.obu")))`. Rewriting the - // directory literal as a committed-path lookup made the gate - // correct and simultaneously invisible -- `crate_pin("` no - // longer appears, so shape (a) found nothing and the - // enumerator reported a CLEAN tree while 14 pins were read. A - // false pass is worse than the original gap: the original at - // least showed up in a filesystem audit. Caught here by the - // `reads.len()` floor in the invariant test. - for m in body.match_indices("crate_pin(&format!(") { - let rest = &body[m.0 + 19..]; - let Some(close) = rest.find(')') else { - continue; - }; - let call = &rest[..close]; - if !call.contains('"') { - continue; - } - let head = &body[..m.0]; - let Some(bracket) = head.rfind('[') else { - continue; - }; - let names: Vec = head[bracket..] - .split('"') - .skip(1) - .step_by(2) - .filter(|x| !x.is_empty() && !x.contains(' ') && *x != "]") - .map(|x| x.to_string()) - .collect(); - // the literal inside the format!, e.g. `{n}.obu` - let lit = call.split('"').nth(1).unwrap_or(""); - let ext = lit - .split_once("}") - .map(|(_, e)| e.to_string()) - .unwrap_or_default(); - for n in names { - out.push(PinRead { - gate: gate.clone(), - file: format!("{n}{ext}"), - shape: "crate_pin_runtime_name", - }); - } - } - } - out - } - - /// Does this shape resolve through `crate_pin`, i.e. the COMMITTED - /// crate-local copy? Both the literal form and the runtime-name form do -- - /// only the two `pin_dir`/root-`concat!` forms are machine-local. - pub fn resolves_committed(shape: &str) -> bool { - matches!(shape, "crate_pin" | "crate_pin_runtime_name") - } - - /// Is `file` present as a committed crate-local fixture? - pub fn is_committed(file: &str) -> bool { - std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("fixtures") - .join(file) - .is_file() - } -} - -#[cfg(test)] -mod pin_inventory_tests { - use super::pin_inventory::{is_committed, pins_read}; - - /// The scanner must be able to SEE the directory-literal shape. Run over a - /// SYNTHETIC source, not the live tree: r5 removed that shape from - /// `pinned_warp_stream_decodes_pixel_exact`, so a test that asserted it - /// against the live file would rot the moment the fix landed -- which is - /// precisely how a scanner loses its edge and reports a clean tree again. - /// A capability test must have its own input. - #[test] - fn the_pin_scanner_sees_the_directory_literal_shape() { - let synthetic = r#" - #[test] - fn a_gate_using_the_old_shape() { - let fixtures = concat!(env!("CARGO_MANIFEST_DIR"), "/../../fixtures"); - let paths: Vec = match std::env::var("EC_AV1_GATE_DUMP_PIN") { - Ok(p) => vec![p], - Err(_) => [ - "warp-mismatch", - "ii-flake-1", - "rect-flake-3", - ] - .iter() - .map(|n| format!("{fixtures}/{n}.obu")) - .collect(), - }; - for path in paths { - check(&path); - } - } -"#; - let reads = pins_read(synthetic); - let names: Vec<&str> = reads.iter().map(|r| r.file.as_str()).collect(); - assert_eq!( - names, - vec!["warp-mismatch.obu", "ii-flake-1.obu", "rect-flake-3.obu"], - "the directory-literal + runtime-name shape resolved to {names:?} -- a scanner \ - that cannot see this shape is how 14 uncommitted pins survived three rounds" - ); - assert!( - reads.iter().all(|r| r.shape == "concat_dir_runtime_name"), - "the synthetic pins were attributed to the wrong shape: {:?}", - reads.iter().map(|r| r.shape).collect::>() - ); - } - - /// The other three shapes resolve too -- same reasoning, same synthetic input, - /// so the capability survives the tree being fixed. - #[test] - fn the_pin_scanner_sees_every_shape() { - let synthetic = r#" - #[test] - fn shapes() { - let a = crate_pin("golden3-pin.obu"); - let b = pin_dir().join("sbpart-pin.obu"); - let c = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../../fixtures/x.obu")); - } -"#; - let mut names: Vec = pins_read(synthetic) - .iter() - .map(|r| format!("{}|{}", r.file, r.shape)) - .collect(); - names.sort(); - assert_eq!( - names, - vec![ - "golden3-pin.obu|crate_pin", - "sbpart-pin.obu|pin_dir_machine_local", - "x.obu|concat_literal_machine_local", - ], - "shape coverage changed: {names:?}" - ); - } - - /// THE INVARIANT, on the live tree: every pin a gate reads is a COMMITTED - /// crate-local copy, and NO gate reads through a machine-local shape. This is - /// the check the r3 manifest could not express. - #[test] - fn every_pin_a_gate_reads_is_committed_under_the_crate() { - let src = crate::test_source::module_source("stream"); - let reads = pins_read(src); - assert!( - reads.len() >= 20, - "the enumerator found only {} pin reads in stream.rs -- it has lost a shape, \ - which is the failure mode that let 14 pins go unseen", - reads.len() - ); - let uncommitted: Vec = reads - .iter() - .filter(|r| !is_committed(&r.file)) - .map(|r| format!("{}:{} ({})", r.gate, r.file, r.shape)) - .collect(); - assert!( - uncommitted.is_empty(), - "{} pin(s) a gate reads have no committed copy under \ - crates/ec-av1/fixtures/ -- each resolves only on a machine whose \ - gitignored root fixtures/ happens to be populated, so a clean checkout \ - silently skips or panics:\n {}", - uncommitted.len(), - uncommitted.join("\n ") - ); - let machine_local: Vec = reads - .iter() - .filter(|r| !super::pin_inventory::resolves_committed(r.shape)) - .map(|r| format!("{} reads {} via {}", r.gate, r.file, r.shape)) - .collect(); - assert!( - machine_local.is_empty(), - "{} pin read(s) still resolve through a machine-local shape instead of \ - `crate_pin` (the committed crate-local copy), so they break on a clean \ - checkout:\n {}", - machine_local.len(), - machine_local.join("\n ") - ); - } -} - -/// lane-av1pins5 r5: the COUNT-VACUITY enumerator. -/// -/// Passing OUR OWN decode's length as the ORACLE's expected frame count -/// (`ffmpeg_decode_sequence(&stream, w, h, ours.len())`) is a real defect, but -/// NOT the one r4 claimed. MEASURED, by calling -/// `ffmpeg_decode_sequence(&stream, 192, 128, 0)` on a real pinned stream under -/// `catch_unwind`: it PANICS at `stream.rs:5110` with -/// `expected 0 4:2:0 frames, ffmpeg said: `. The helper asserts -/// `out.stdout.len() == frame_bytes * frames` unconditionally, so a wrong count -/// cannot pass silently -- it reds, with a message that blames FFMPEG for a -/// count OUR decoder chose. -/// -/// TWO DEFECT CLASSES, DO NOT CONFLATE THEM (lane-av1pins5 r6): -/// * MISATTRIBUTED RED -- a wrong count reds, and the old message blamed -/// ffmpeg for a number OUR decoder chose. This is what these sites are. -/// `ffmpeg_decode_sequence`'s `stdout.len() == frame_bytes * frames` assert -/// is unconditional, so it cannot pass silently. -/// * SILENT PASS -- the compare is skipped or truncated and the gate reports -/// green. A DIFFERENT defect with a DIFFERENT fix, and r4 mislabelled these -/// sites as belonging to it. If you are reading this to decide what to fix, -/// fix the message and the count SOURCE; do not go looking for a silent pass. -/// -/// r4 reported this shape as "a vacuous pass" and told Main so. That was wrong. -/// The consequence is a MISATTRIBUTED RED. The fix r4 shipped is still right (the -/// count now comes from the fixture, so the red names the real cause), but the -/// justification was wrong, and a sweep that repeats it would send the next -/// reader after a silent-pass bug that does not exist. -/// -/// This enumerator finds every such site and classifies it, so the class is -/// visible and cannot shrink unnoticed. -#[cfg(test)] -mod count_vacuity { - /// One oracle call whose expected frame count is locally derived. - pub struct Site { - pub line: usize, - pub gate: String, - pub count_expr: String, - /// An independent count assertion on the same binding, within a few - /// lines above: that is what makes the count a SPEC rather than a - /// self-fulfilling number. - pub pinned_by: Option, - /// Does this gate actually COMPARE PIXELS (so a wrong count would - /// corrupt a verdict), or is it a report-only probe? - pub pixel_comparing: bool, - /// The fix bucket, by READING the gate (r7). `Some(b)` where - /// a = pinned stream on disk -> take the count from the PIN - /// b = live aomenc encode -> take it from the ENCODE's frame count; - /// our decode's length is the thing - /// UNDER TEST and must never be the - /// expected value - /// c = census/probe -> report only, never fix - /// `None` = could not classify, and the reason is in `bucket_reason`. - pub bucket: Option<&'static str>, - pub bucket_reason: String, - /// The numeric frame count found in this gate's own encode call, when - /// one is visible -- the value the compare should assert instead. - pub candidate: Option, - /// A frame count already in scope that is a SPEC rather than a - /// self-fulfilling number -- e.g. the `FRAMES` the gate encoded, or a - /// count asserted on the pinned stream. `Some(..)` means the fix is a - /// one-line swap at this site. - pub fixable_from: Option, - } - - /// The scanner's matchers, as SINGLE-SOURCE tables. - /// - /// They are `pub const` rather than inline literals because the sweep's - /// floor only catches a LOST shape; nothing caught a matcher that has - /// never fired, so a dead spelling sat in this list advertising coverage - /// the scan does not have (class: unexercised matcher in a source - /// scanner). [`count_vacuity_tests::every_scanner_matcher_fires_on_a_known_site`] - /// iterates THESE arrays, so a matcher cannot be added here without a - /// positive control that has to pass. /// - /// Oracle call spellings whose LAST argument is a locally derived count. - /// `ffmpeg_decode_sequence_444(` fires on five real `stream.rs` gates - /// (stream.rs:7030/7545/7735/8439/11643) but yields no count-vacuity SITE, - /// because every one of those five passes the spec const `FRAMES` rather - /// than a decode-derived `.len()`. It is live coverage, not a dead - /// spelling, and the control below measures the spelling, not the site. - pub const CALLEES: &[&str] = &[ - "ffmpeg_decode_sequence(", - "ffmpeg_decode_sequence_10bit(", - "ffmpeg_decode_sequence_444(", - ]; - - /// Gate-name substrings that mark a census/probe/diagnostic gate: it - /// reports, it does not assert a verdict. `"diagnostic"` was here and has - /// no gate in the tree carrying it (and no other occurrence in the crate - /// outside this list), so it was DELETED rather than kept: there is no - /// hypothetical caller to name, and a probe that later wants that name - /// re-adds one line here, where the control then holds it to firing. - pub const PROBE_SUBSTRINGS: &[&str] = - &["census", "probe", "sweep", "first_diff", "scratch", "rectx"]; - - /// Encode helpers a gate can drive INDIRECTLY. The r7 extraction found 21 of - /// the 25 bucket-b gates encode through one of these, not through - /// `aomenc_path()` directly -- which is why a first pass that only looked for - /// `aomenc_path()` classified 6 gates "unclassified" that plainly encode. - /// Six further names (`the_chroma_rect_gates`, `restore_gate`, - /// `cdef_gate`, `superres_gate`, `grain_gate`, `sgate`) were here and - /// matched no `fn` body in the tree; `grep -rn '\bNAME\b' crates/ec-av1/src` - /// returns these six and NOTHING ELSE -- no helper, no caller, no comment - /// naming them -- so they were rot and are DELETED, not kept with a - /// hypothetical-caller note. - pub const ENC_HELPERS: &[&str] = &[ - "encode_aomenc_stream", - "screen_intrabc_stream_at_depth", - "screen_intrabc_stream_with", - "libaom_encode_with", - "libaom_encode", - "run_multi_tile_gate", - "edge32_gate", - "rect_tx_tool_gate", - "warp_gate", - ]; - - /// Frame-count bindings that are a SPEC rather than a self-fulfilling - /// number. `NFRAMES` and `frames_expected` were here, matched no `fn` - /// body, and appear nowhere else in the crate -- DELETED as rot. - pub const FIXABLE_CANDS: &[&str] = &["FRAMES", "frame_count"]; - - /// How many lines above a count site an `assert(..)` on the same binding - /// may sit and still call the count spec-pinned. A single-sourced const so - /// the control below can hold the WINDOW itself to being the window the - /// sweep walks (a window widened to EOF would pin sites it never pinned). - pub const PIN_WINDOW: usize = 14; - - /// The bucket-(b) leaf: a gate that drives aomenc directly rather than - /// through [`ENC_HELPERS`]. - pub const AOMENC_LEAF: &str = "aomenc_path()"; - - /// The bucket-(a) leaves: a gate that reads its stream from disk. - pub const DISK_READ_LEAVES: &[&str] = &["fs::read", "crate_pin"]; - - /// A census/probe/diagnostic gate: it reports, it does not assert a verdict. - fn is_probe(gate: &str) -> bool { - PROBE_SUBSTRINGS.iter().any(|m| gate.contains(m)) - } - - /// Encode helpers a gate can drive INDIRECTLY -- see [`ENC_HELPERS`]. - fn enc_helpers(body: &str) -> Vec<&'static str> { - ENC_HELPERS - .iter() - .copied() - .filter(|n| body.contains(&format!("{n}("))) - .collect() - } - - /// End byte of the `fn` body starting at `fn_start`: a STRING- and - /// line-comment-aware brace walk (the trap it dodges is recorded at the - /// call site). Extracted so the matchers' positive-control test walks the - /// EXACT slice the scanner classifies -- a control that re-implemented the - /// walk would be measuring a different thing than the guard (class - /// control-and-measurement-drift). - pub fn fn_body_end(src: &str, fn_start: usize) -> usize { - let bytes = src.as_bytes(); - let mut depth = 0i32; - let mut started = false; - let mut fn_end = src.len(); - let mut in_str = false; - let mut in_line_comment = false; - let mut k = fn_start; - while k < bytes.len() { - let c = bytes[k]; - if in_line_comment { - if c == b'\n' { - in_line_comment = false; - } - k += 1; - continue; - } - if in_str { - if c == b'\\' { - k += 2; - continue; - } - if c == b'"' { - in_str = false; - } - k += 1; - continue; - } - match c { - b'"' => in_str = true, - b'/' if bytes.get(k + 1) == Some(&b'/') => { - in_line_comment = true; - k += 1; - } - b'{' => { - depth += 1; - started = true; - } - b'}' => { - depth -= 1; - if started && depth == 0 { - fn_end = k + 1; - break; - } - } - _ => {} - } - k += 1; - } - fn_end - } - - /// `(fn name, body slice)` for every top-level `fn` in `src`, attributed - /// the way [`sites`] attributes a site to its gate. - pub fn fn_slices(src: &str) -> Vec<(String, &str)> { - let lines: Vec<&str> = src.lines().collect(); - let mut offsets: Vec = Vec::with_capacity(lines.len()); - { - let mut o = 0usize; - for l in &lines { - offsets.push(o); - o += l.len() + 1; - } - } - let mut out: Vec<(String, &str)> = Vec::new(); - for (i, line) in lines.iter().enumerate() { - let t = line.trim_start(); - let Some(rest) = t.strip_prefix("fn ") else { - continue; - }; - let Some(nm) = rest.split('(').next() else { - continue; - }; - if nm.contains(' ') { - continue; - } - let at = offsets[i]; - let end = fn_body_end(src, at); - out.push((nm.to_string(), &src[at..end])); - } - out - } - - pub fn sites(src: &str) -> Vec { - let mut out = Vec::new(); - let lines: Vec<&str> = src.lines().collect(); - // LINE index -> BYTE offset. The body walk indexes `src.as_bytes()`, so - // handing it a line number walks from the wrong place entirely and every - // body-dependent classification reads "unclassified". Same bug I hit in - // the Python classifier one step earlier. - let mut offsets: Vec = Vec::with_capacity(lines.len()); - { - let mut o = 0usize; - for l in &lines { - offsets.push(o); - o += l.len() + 1; - } - } - let mut gate = String::new(); - let mut fn_start = 0usize; - for (i, line) in lines.iter().enumerate() { - let t = line.trim_start(); - if let Some(rest) = t.strip_prefix("fn ") - && let Some(n) = rest.split('(').next() - && !n.contains(' ') { - gate = n.to_string(); - fn_start = offsets[i]; - } - // A DOC COMMENT is prose about code, not code. One row in the ledger - // was a `///` line quoting a gate's pre-fix body (`stream.rs:30924`, - // inside `pinned_lr_sgr_stream_call_unique_dump`) and the sweep - // counted it as an unpinned count site for a whole round: the gate - // it describes already spends `FRAMES` and asserts - // `pics.len() == FRAMES`. Skipping comment lines is not cosmetic -- - // without it the ledger carries a row no reader can act on, and the - // ceiling can never reach 0. - // - // Only the SITE scan skips comments. The pin-window walk further - // down still sees every line, because a `//`-led line there is a - // comment BETWEEN the assert and the call, not a site. - if t.starts_with("//") { - continue; - } - for callee in CALLEES { - let Some(at) = line.find(callee) else { - continue; - }; - let args = &line[at + callee.len()..]; - // DEPTH-AWARE close: `args.find(')')` stops at the `)` of - // `pictures.len()` and truncates the arg list mid-expression, - // which silently yielded zero sites on the first run. - let mut depth = 1usize; - let mut close = None; - for (k, ch) in args.char_indices() { - match ch { - '(' => depth += 1, - ')' => { - depth -= 1; - if depth == 0 { - close = Some(k); - break; - } - } - _ => {} - } - } - let Some(close) = close else { continue }; - let arglist = &args[..close]; - let last = arglist.rsplit(',').next().unwrap_or("").trim(); - if !(last.ends_with(".len()") || last.ends_with(".count()")) { - continue; - } - // Is the SAME binding count-asserted against a literal/const - // within the preceding 12 lines? That is the difference between - // a spec and a self-fulfilling number. - let binding = last.trim_end_matches(".len()").trim_end_matches(".count()"); - // Match the assertion across a LINE BREAK: rustfmt puts - // assert_eq!( - // frames.len(), - // so requiring `assert_eq!(frames.len()` on one line missed - // every multi-line spelling and inflated the unpinned count. - let want = format!("{binding}.len()"); - let mut pinned = None; - for back in 1..=PIN_WINDOW { - if i < back { - break; - } - let prev = lines[i - back].trim_start(); - if !prev.starts_with("assert") || !prev.contains('(') { - continue; - } - // rustfmt splits `assert_eq!(` from its first argument, so - // the binding is on THIS line or the NEXT one. - let here = prev.contains(&want); - let next = lines - .get(i - back + 1) - .map(|l| l.trim_start().contains(&want)) - .unwrap_or(false); - if here || next { - pinned = Some(prev.chars().take(60).collect()); - break; - } - } - // Pixel-comparing? A gate that compares planes is the only - // place a wrong count corrupts a verdict; a report-only probe - // just prints. - // Bound to THIS fn only. Slicing to EOF matched a later gate's - // `const FRAMES` and its `assert_eq!(got.y`, which reported all - // 48 sites as pixel-comparing with a spec in scope -- the same - // over-broad-scope bug the class keeps teaching. - // Brace-depth walk, not `find("\n }")`: a gate with an - // early 4-space `}` (a bare block, a `match` arm tail) truncated - // the slice and made the compare-detection read false. - // STRING-AWARE brace walk. Counting raw bytes counts a `}` - // inside a format string as a closing brace, which truncated the - // body and made every compare-detection read false -- the same - // trap that made stream.rs look 2 braces short in the first - // review of this wave. - let fn_end = fn_body_end(src, fn_start); - let body = &src[fn_start..fn_end]; - // APPROXIMATE, and known to be so: the body slice is a - // hand-rolled brace walk, and this crate's compare idioms vary - // enough that the column under-reports. The LINE, GATE and - // COUNT EXPR columns are exact (line-based scan, no body - // slicing); treat `pixel_comparing` as a hint, not a verdict. - // Idiom-tolerant: this crate spells the compare every which way - // (`assert_eq!(got.y, want.y)`, `assert_eq!(g, w)`, - // `let ok = ours.y == ref_f.y`, `ours.y, want.y`), so match the - // PLANE inside an assertion, not one fixed spelling. - let pixel_comparing = body.contains("assert") - && (body.contains(".y,") - || body.contains(".y ==") - || body.contains(".y)") - || body.contains("vs ffmpeg")); - // A SPEC already in scope for this gate? - let mut fixable = None; - for cand in FIXABLE_CANDS { - if body.contains(&format!("const {cand}")) - || body.contains(&format!("let {cand}")) - { - fixable = Some(cand.to_string()); - break; - } - } - // Bucket by READING the gate. A census/probe reports and never - // asserts, so its count is not a verdict and is left alone. A - // gate that drives aomenc takes the count from the ENCODE -- our - // decode's length is what is under test, so using it as the - // expected value is circular. A gate that reads a stream from - // disk takes it from that stream. - // The candidate fix: the numeric frame count in this gate's own - // encode call. For bucket (b) that number IS the encoder's frame - // count, so it is the spec the compare should assert. - let candidate = enc_helpers(body).first().and_then(|h| { - let at = body.find(&format!("{h}("))?; - let open = at + h.len() + 1; - let seg = &body[open..(open + 400).min(body.len())]; - let close = seg.find(';')?; - let nums: Vec<&str> = seg[..close] - .split(',') - .map(|x| x.trim()) - .filter(|x| !x.is_empty() && x.chars().all(|c| c.is_ascii_digit())) - .collect(); - nums.last().map(|x| x.to_string()) - }); - let (bucket, bucket_reason) = if is_probe(&gate) { - ( - Some("c"), - "census/probe: reports, does not assert a verdict".to_string(), - ) - } else if body.contains(AOMENC_LEAF) || !enc_helpers(body).is_empty() { - ( - Some("b"), - "live aomenc encode: count belongs to the encoder".to_string(), - ) - } else if DISK_READ_LEAVES.iter().any(|leaf| body.contains(leaf)) { - ( - Some("a"), - "stream read from disk: count belongs to the pin".to_string(), - ) - } else { - ( - None, - "unclassified: no aomenc drive, no disk read, and not a probe -- \ - needs a reader" - .to_string(), - ) - }; - out.push(Site { - line: i + 1, - gate: gate.clone(), - count_expr: last.to_string(), - pinned_by: pinned, - pixel_comparing, - fixable_from: fixable, - bucket, - bucket_reason, - candidate, - }); - } - } - out - } - - /// Every matcher's POSITIVE CONTROL: each spelling in this module's tables - /// must fire on at least one real thing in the scanned source, or the - /// spelling is advertising coverage the scan does not have. - /// - /// This is the missing half of the sweep's own floor. `s.len() >= 40` and - /// the unpinned ceiling both catch a LOST shape; nothing caught a matcher - /// that never fired -- which is how six encode-helper names, two spec - /// binding names and one probe substring sat in these tables matching - /// nothing anywhere in the crate (class: unexercised matcher in a source - /// scanner). Those nine are deleted. The control reads the SAME `const` - /// tables the scanner reads, so a matcher added later cannot skip it. - /// - /// `fn_slices` walks the same `fn_body_end` the scanner classifies with, so - /// "fires" means fires on the slice the guard actually reads. - #[test] - fn every_scanner_matcher_fires_on_a_known_site() { - let src = crate::test_source::module_source("stream"); - let lines: Vec<&str> = src.lines().collect(); - let fns = fn_slices(src); - - // The callee list, as a SPELLING. Not as a produced site: the - // `_444` spelling fires on five real gates that all pass the spec - // const `FRAMES`, so it correctly yields no count-vacuity site. A - // spelling that no `stream.rs` line uses is a spelling that has - // stopped being written and is now dead weight in the table. - for callee in CALLEES { - let hits = lines.iter().filter(|l| l.contains(callee)).count(); - assert!( - hits > 0, - "the callee matcher `{callee}` fires on NO line of stream.rs -- it is dead \ - coverage: either a gate stopped using that spelling (drop the entry) or a \ - new one is expected to (add the call site first, not the matcher)" - ); - } - - // The gate-name probe substrings, against real fn names. - for sub in PROBE_SUBSTRINGS { - let hits = fns.iter().filter(|(g, _)| g.contains(sub)).count(); - assert!( - hits > 0, - "the probe substring `{sub}` matches NO fn name in stream.rs -- bucket (c) is \ - unpopulated and the substring is dead weight" - ); - } - - // The indirect-encode helpers, against real fn BODIES. - for helper in ENC_HELPERS { - let hits = fns - .iter() - .filter(|(_, b)| b.contains(&format!("{helper}("))) - .count(); - assert!( - hits > 0, - "the encode-helper matcher `{helper}(` matches NO fn body in stream.rs -- it is \ - dead coverage (grep the crate: if the helper has no caller, delete the entry; if \ - it has a caller outside stream.rs, say so here and name the file)" - ); - } - - // The spec-binding candidates, against real fn BODIES. - for cand in FIXABLE_CANDS { - let hits = fns - .iter() - .filter(|(_, b)| { - b.contains(&format!("const {cand}")) || b.contains(&format!("let {cand}")) - }) - .count(); - assert!( - hits > 0, - "the spec-binding matcher `{cand}` matches NO fn body in stream.rs -- `fixable_from` \ - can never name it, so it is dead coverage" - ); - } - - // The two bucket leaves the classifier short-circuits on. - assert!( - fns.iter().any(|(_, b)| b.contains(AOMENC_LEAF)), - "no fn body in stream.rs calls `{AOMENC_LEAF}`, so the bucket-(b) direct-encode leaf \ - never fires" - ); - for leaf in DISK_READ_LEAVES { - let hits = fns.iter().filter(|(_, b)| b.contains(leaf)).count(); - assert!( - hits > 0, - "the disk-read leaf `{leaf}` matches NO fn body in stream.rs -- bucket (a) is \ - unpopulated by that spelling" - ); - } - - // The pin window is a matcher too: a window so wide it pinned - // everything, or so narrow it pinned nothing, would leave the - // ceiling reading a population it no longer describes. - let s = sites(src); - let pinned = s.iter().filter(|x| x.pinned_by.is_some()).count(); - assert!( - PIN_WINDOW > 0 && pinned > 0, - "PIN_WINDOW={PIN_WINDOW} pins {pinned} of {} site(s) -- the window must be the one \ - the sweep walks and must still pin at least one site", - s.len() - ); - } -} - -#[cfg(test)] -mod count_vacuity_tests { - use super::count_vacuity::sites; - - /// The shape is real and widespread; this pins the FLOOR so the sweep cannot - /// silently stop finding sites. Measured count is well above this. - #[test] - fn the_count_vacuity_sweep_finds_the_known_sites() { - let src = crate::test_source::module_source("stream"); - let s = sites(src); - assert!( - s.len() >= 40, - "the count-vacuity sweep found only {} site(s); expected 40+ -- it has lost a \ - shape", - s.len() - ); - // r7: the first reported site (3895, `pictures.len()`) is FIXED -- it now - // asserts `ENCODED_FRAMES`, the encode's own count. The anchor therefore - // moved from "the site is still there" to "the fix is still in place AND - // the dominant remaining shape is still found", so the sweep cannot go - // quiet by either route. - // The GENERAL rule, not the one literal r7 fixed. Every decode-derived - // count expression is banned at the gate r7 fixed, so a future edit that - // reintroduces the shape under a different binding name is caught, and so - // the guard does not go quiet as the OTHER sites are fixed later. - const DECODE_DERIVED: &[&str] = &["pictures.len()", "decoded.len()", "frames.len()"]; - assert!( - !s.iter().any(|x| x.gate - == "a_real_aomenc_segmentation_stream_with_map_inheritance_decodes_pixel_exact" - && DECODE_DERIVED.contains(&x.count_expr.as_str())), - "the r7 fix regressed: {} is passing a decode-derived count as the oracle's \ - expected count again -- our decode's length is the thing UNDER TEST and \ - must never be the expected value", - "a_real_aomenc_segmentation_stream_with_map_inheritance_decodes_pixel_exact" - ); - // A CEILING on the unpinned population, so a NEW site cannot be added - // silently. Lower it as sites are fixed; a fix that does not lower it is - // still a fix, but a NEW site is an immediate red. - // - // lane-av1pinspec: 43 -> 2. Each of the 41 fixes adds the ENCODE's own - // frame count as an `assert_eq!` ABOVE the `ffmpeg_decode_sequence*` - // call (`-frames:v 1` / `-vframes 1` / `--limit=N` / a helper's `frames` - // parameter / the arm tuple's `frame_count` / the wire's own OBU frame - // headers), so the count handed to the oracle is a value already proven - // against the encode instead of read off our decode. Two rows survived - // that round; lane-av1pinspec2 closed both, so the ceiling is now 0. - // - // lane-av1pinspec2: 2 -> 0, in two steps. - // * `an_svt_screen_palette_block_with_a_split_transform_decodes_exactly` - // was handed forward because the count was underivable: the stream - // came from `EC_AV1_SVT1_STREAM`, was never committed, and the gate - // SKIPped on a stock box -- so a wire-derived assert would have been - // an unexercised assert wearing a pin's clothes. The crop is now - // COMMITTED (`fixtures/svt1-split-tx-pin.obu`, a byte-reproducible - // replay of a `-frames:v 1` libsvtav1 encode), the gate reads it, and - // its count comes from the stream's own OBU frame headers with - // `show_existing_frame` asserted false so a header count cannot - // over-count. The gate runs on a stock box, so the assert executes. - // * the other row was a `///` DOC COMMENT quoting the pre-r4 body of - // `pinned_lr_sgr_stream_call_unique_dump`, which this line-based - // scan could not tell from code. `sites()` now skips comment lines, - // so the row is no longer a site at all. - // - // RED-BEFORE for the comment skip, which is a coverage change and not a - // cosmetic one: with the `t.starts_with("//")` guard removed and this - // ceiling at 0, the doc-comment row comes BACK as an unpinned site and - // reds with "1 unpinned count site(s), ceiling is 0". - const UNPINNED_CEILING: usize = 0; - let unpinned = s.iter().filter(|x| x.pinned_by.is_none()).count(); - // The ceiling is deliberately 0 today; it stays a ceiling so a site can be grandfathered by raising it. - #[allow(clippy::absurd_extreme_comparisons)] - let within_ceiling = unpinned <= UNPINNED_CEILING; - assert!( - within_ceiling, - "{unpinned} unpinned count site(s), ceiling is {UNPINNED_CEILING} -- a new one \ - was added (lower the ceiling only when a site is actually fixed)" - ); - assert!( - s.iter().any(|x| x.count_expr == "frames.len()"), - "the dominant `frames.len()` shape is no longer found -- the sweep has lost a \ - shape, not gained a fix" - ); - } - - /// Report, per site: does the count come from a SPEC or from our own decode? - /// Prints the table the r5 report carries. The assertion is the FLOOR above, - /// not "zero unpinned" -- the residual unpinned sites are handed to another - /// lane with this table, and forcing them all here would be an unbounded - /// change dressed as a fix. - #[test] - fn every_locally_derived_oracle_count_is_reported() { - let src = crate::test_source::module_source("stream"); - let s = sites(src); - let unpinned: Vec = s - .iter() - .filter(|x| x.pinned_by.is_none()) - .map(|x| { - format!( - "stream.rs:{} | {} | {} | NOT SPEC-PINNED", - x.line, x.gate, x.count_expr - ) - }) - .collect(); - let pinned = s.len() - unpinned.len(); - eprintln!( - "count-vacuity sweep: {} site(s); {} spec-pinned by a prior assert, {} not", - s.len(), - pinned, - unpinned.len() - ); - for line in unpinned.iter() { - eprintln!(" {line}"); - } - // The table Main asked for, as columns the guard itself computes. - for x in s.iter().filter(|x| x.pinned_by.is_none()) { - eprintln!( - "ROW {} | {} | {} | bucket={} | candidate={} | spec_in_scope={} | {} | \ - pixel_comparing={}", - x.line, - x.gate, - x.count_expr, - x.bucket.unwrap_or("?"), - x.candidate.clone().unwrap_or_else(|| "-".into()), - x.fixable_from.clone().unwrap_or_else(|| "-".into()), - x.bucket_reason, - x.pixel_comparing - ); - } - assert!( - !s.is_empty() && s.iter().all(|x| !x.gate.is_empty()), - "a site has no owning gate -- the sweep's gate attribution is broken" - ); - } - - /// The comment skip is a COVERAGE change, so it is held to the same shape - /// the `pin_inventory` capability tests use: a SYNTHETIC source, not the - /// live tree, with BOTH halves. Run against the live tree instead, a fix - /// to the very gate that motivated it would delete the row that proves the - /// scanner still works -- the failure mode `pin_inventory` already records - /// as "a scanner that cannot see this shape is how 14 pins survived three - /// rounds". - /// - /// Half one: a count call that lives INSIDE a doc comment must not be a - /// site. That is the real `stream.rs:30924` row, which spent a whole round - /// in the ledger as an unpinned count no reader could act on -- the gate it - /// quotes already spends `FRAMES` and asserts `pics.len() == FRAMES`. - /// - /// Half two, the control: the SAME call as real code must still be a site, - /// and must still be pinned by an assert above it. A scanner that skips - /// comments by skipping the wrong thing looks identical on half one, and a - /// ceiling of 0 is exactly the state where an over-broad skip would go - /// unnoticed. - #[test] - fn a_doc_commented_count_call_is_not_a_site_but_real_code_still_is() { - let commented = r#" - /// The old body passed the wrong count to the oracle: - /// let reference = ffmpeg_decode_sequence(&stream, 192, 128, pics.len()); - /// so a decoder that emitted zero frames asked ffmpeg for zero frames. - fn a_gate_whose_doc_comment_quotes_the_old_body() { - let pics = decode_stream(&data).unwrap(); - } -"#; - let commented_sites = sites(commented); - assert!( - commented_sites.is_empty(), - "a count call inside a `///` doc comment was counted as a site: {:?} -- a line-based \ - scan cannot tell prose from code, and this row is why it now skips comment lines", - commented_sites - .iter() - .map(|x| (x.line, x.count_expr.clone())) - .collect::>() - ); - - let real = r#" - fn a_gate_that_really_spends_its_own_decode_length() { - let pics = decode_stream(&data).unwrap(); - assert_eq!(pics.len(), 7, "{NAME}: expected seven key frames"); - let reference = ffmpeg_decode_sequence(&stream, 192, 128, pics.len()); - } -"#; - let found = sites(real); - assert_eq!( - found.len(), - 1, - "the control did not find its one real site: {:?} -- the comment skip is over-broad \ - if the same call is skipped as code", - found - .iter() - .map(|x| (x.line, x.count_expr.clone(), x.gate.clone())) - .collect::>() - ); - assert_eq!( - found[0].count_expr, "pics.len()", - "control: wrong count expr" - ); - assert_eq!( - found[0].gate, "a_gate_that_really_spends_its_own_decode_length", - "control: wrong gate attribution" - ); - assert!( - found[0].pinned_by.is_some(), - "the control's site is UNPINNED: the comment skip changed the pin window too, \ - because a `//` line between an assert and its call is still walked" - ); - } -} diff --git a/crates/ec-av1/src/lib.rs b/crates/ec-av1/src/lib.rs index 463123b5..d7757920 100644 --- a/crates/ec-av1/src/lib.rs +++ b/crates/ec-av1/src/lib.rs @@ -37,9 +37,6 @@ mod film_grain; pub use film_grain::apply_film_grain; mod filter_search; pub mod frame; -// Test-only: the real-library fixture root and the one presence probe every -// gate that needs a clip routes through. -mod gate_coverage; mod hits; pub mod intra; #[cfg(test)] @@ -54,7 +51,6 @@ mod par; pub mod probe; pub mod qm; pub mod quant; -mod refusal_inventory; mod restoration; pub mod sequence; pub mod speed; @@ -63,8 +59,6 @@ pub mod stream; mod superres; #[cfg(test)] mod test_source; -#[cfg(test)] -pub(crate) mod tool_cache; pub mod tile; mod timeline; pub mod transform; diff --git a/crates/ec-av1/src/probe.rs b/crates/ec-av1/src/probe.rs index 0410ad28..e70d1cff 100644 --- a/crates/ec-av1/src/probe.rs +++ b/crates/ec-av1/src/probe.rs @@ -135,11 +135,6 @@ pub fn source( /// aomenc/ffmpeg over an at-most-a-few-MB fixture: seconds, not minutes. #[cfg(test)] pub(crate) fn run_with_stdin(cmd: &mut Command, input: &[u8]) -> std::process::Output { - crate::tool_cache::cached_output(cmd, Some(input), |c| run_child_with_stdin(c, input)) -} - -#[cfg(test)] -fn run_child_with_stdin(cmd: &mut Command, input: &[u8]) -> std::process::Output { use std::io::{Read, Write}; use std::process::Stdio; use std::time::{Duration, Instant}; diff --git a/crates/ec-av1/src/refusal_inventory.rs b/crates/ec-av1/src/refusal_inventory.rs deleted file mode 100644 index 31499d42..00000000 --- a/crates/ec-av1/src/refusal_inventory.rs +++ /dev/null @@ -1,2957 +0,0 @@ -//! An inventory of what this decoder refuses, and a check on the claims those -//! refusals make. -//! -//! Two rules this repository keeps learning the hard way: -//! -//! 1. A refusal string is a **claim**. "This encoder never writes one" asserts -//! that a real encoder cannot emit the case -- and one such string was -//! disproved by the very gate that carried it (the wedge-interintra hang, -//! 2026-08-30): the refusal was written from a mismatching frame's header -//! state, so it named a correlate rather than the defect. Any refusal -//! phrased as a capability claim about the ENCODER, rather than about this -//! decoder, needs evidence, and this module makes the set of such strings -//! explicit instead of letting it grow quietly. -//! 2. Refusals accumulate silently. A lane that adds one to unblock itself is -//! doing the right thing (refuse by name rather than desync), but the total -//! is the distance to a decoder that handles a default-settings stream, and -//! nobody sees a total that nothing prints. -//! -//! So the test below re-derives every `unsupported(...)` reason reachable on -//! the decode path -- `decode.rs` and `stream.rs` -- and pins it. Adding or -//! removing a refusal fails until the list is updated, which is the point: the -//! diff of this file is the decoder's capability delta, in one place, in -//! English. - -#[cfg(test)] -const CAPABILITY_CLAIMS: &[&str] = &[ - // lane-hdrlossless ENUMERATION: this guard is a claim about THIS - // decoder's gate, not about the encoder -- `filter_intra_size_class_rect` - // admits no arm with a 64 axis (libaom `av1_filter_intra_allowed_bsize` - // is "both sides <= 32"), and the strips it protects are exactly - // `(64, 32)`/`(32, 64)`, which fall to its `_ => None` arm. So the - // `filter_intra.is_some()` guard in `decode_block_rect` is unreachable; - // the proof is `a_sb_level_horz_vert_strip_admits_no_filter_intra_symbol`, - // which enumerates every arm of the table. Kept as a named pin (not - // deleted) per the repo convention for proven-unreachable guards. - "filter intra on a superblock-level HORZ/VERT strip (never expected -- av1_filter_intra_allowed_bsize caps at 32x32)", -]; - -#[cfg(test)] -const REFUSALS: &[&str] = &[ - // lane-av1-444 c4's rect/1:4 chroma port added two shape guards whose - // strings never landed here (continuation 8's suite run caught the - // drift); both are decoder-side "no table for that shape yet" guards on - // 4:4:4 rect strips, same family as the rect luma/chroma entries below. - // lane-av1-refusalaudit: the 64-axis one is PROVEN unreachable -- its - // chroma-unit table covers every conformant strip unit in both supported - // chroma formats (enumeration in PROVEN; the witness2 hunt reached - // nothing). The chroma-size one below is still live. - "a 64-axis strip whose chroma unit has no coefficient table", - "a rectangular chroma transform whose size has no coefficient table", - "a coded HORZ/VERT strip whose chroma transform has no rect coefficient tables here", - "a split intra strip whose transform unit is {tx_w}x{tx_h} (no luma coefficient tables for that shape here)", - "an OBMC neighbour whose switchable interp filter was never recorded", - "a rectangular inter luma transform unit whose shape has no coefficient table set here", - "a rectangular inter chroma transform unit whose shape has no coefficient table set here", - "a rectangular transform unit whose shape has no coefficient scan table here", - "a 32x32 partition type this decoder does not code (value={part32})", - "a Golomb tail longer than this decoder reads", - "a tx_type symbol outside its CDF's own set: {t}", - "an INTER 32x32 partition type this decoder does not code (value={part32})", - "a superblock-level partition value outside PARTITION_NONE..PARTITION_VERT_4", - "a 128x128 superblock partition value outside the 8-symbol alphabet", - "an inter var-tx tree with a leaf transform larger than 64x64", - "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)", - // lane-av1unwritten + lane-av1subsizesweep: the BLOCK_INVALID subsize - // refusal that mirrors libaom's own (decodeframe.c:1456). The source - // string carries escaped quotes around the libaom citation and this - // table is matched against the scanner's collected form, so the quotes - // stay escaped here the way the scanner keeps them. - "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)", - // lane-t900 r23: palette RECONSTRUCTION now covers the key-frame paths - // (earlier lanes), the intra-in-inter square/rect paths (r22) and the - // 8x8 LEAF inside an inter frame (this round, gate - // `a_screen_stream_with_palette_8x8_leaves_in_inter_frames_decodes_pixel_exact`), - // which is why the (UV) string is gone from the decoder entirely -- the - // leaf was its only site. The (Y) one survived as the defensive - // `palette.is_none()` guard in `read_intra_mode`/`read_intra_mode_rect` - // until lane-t900 r33 DELETED both arms: all eight call sites hand the - // reader a real ctx/cache pair, so no stream could reach either (audit - // `every_read_intra_mode_call_site_hands_the_reader_a_palette_cache`, - // which keeps that invariant now the refusal is gone). - // lane-av1-ibcrect: `intra block copy on a HORZ/VERT/1:4 rect intra strip - // (reconstruction is not ported at this shape)` is GONE -- lane-av1-intrabc - // and lane-av1-rect14 reconstructed the 16x16/32x32-level strips, and this - // lane ported the last site, `decode_block_128rect`'s 128-root HORZ/VERT - // strip (`decode_intrabc_128rect`; a 128 root has no 1:4 arm at all). - // Witness: - // `an_sb128_rect_strip_with_intrabc_decodes_pixel_exact` (real aomenc - // sb128 screen streams coding `use_intrabc` on BLOCK_128X64 strips, - // pixel-exact vs ffmpeg). - // lane-av1txr: `a sub-8x8 leaf that uses intrabc (…)` is GONE -- the - // capability landed in this lane (4x4 / 4x8 / 8x4 intrabc leaves read the - // DV and reconstruct a frame copy + the INTER residual; the sub-8x8 - // intrabc leaf witnesses in `stream.rs` and the `warped.obu` / - // `allintra.obu` traces). Its census gate - // (`a_sub8_leaf_census_over_intrabc_screen_streams_measures_the_sub8_refusal`) - // still runs: it now reports `reached = 0` with the same non-vacuous - // premise (allow_intrabc frames + decoded sub-8 leaves). - // lane-av112bit: the blanket 12-bit refusal is REPLACED by the named - // refusals below -- the witnessed paths (intra stack, dequant/ - // transforms at the 12-bit tables, deblock, CDEF, Wiener+SGR - // restoration, translational subpel MC through the parameterised - // round_0/round_1) are lifted by the lane's byte-exact ffmpeg gates. - // lane-av112bitc: compound joined the witnessed set (six-frame 12-bit - // compound stream byte-exact vs ffmpeg; the combines already absorbed - // the CONV_BUF gain drop through `INTER_POST_ROUND - delta`). - // lane-av112bitg: film grain joined the witnessed set (two-frame - // `--film-grain-test=5` stream byte-exact vs ffmpeg; the gate that - // replaced the refusal is - // `a_real_aomenc_12bit_film_grain_stream_decodes_pixel_exact`). - // lane-av112bitw: warp joined too -- the refusal left all three decision - // sites (compound, 16x16+, 8x8 leaf): `warp::warp_round_0` implements - // convolve.h's 12-bit `round_0` bump (3 -> 5), and both the single-ref - // witness (`a_12bit_warped_motion_stream_decodes_pixel_exact`, the exact - // recipe that refused pre-lift) and the rotating-mandelbrot - // compound-warp witness - // (`a_real_compound_global_warp_12bit_stream_decodes_pixel_exact`, 28 - // compound warp blocks) are byte-exact vs ffmpeg. - // lane-av1screen12: screen content tools LEFT the 12-bit refusal set. The - // string was "a 12-bit frame with screen content tools - // (allow_screen_content_tools=1: neither palette nor intrabc has a 12-bit - // witness)" -- a guard BROADER than the gap it named, because - // `allow_screen_content_tools` only opens the `palette_y_mode` / - // `palette_uv_mode` symbols and the leaf `use_intrabc` symbol, and both - // reconstructions are already depth-parameterised - // (`read_palette_colors_y` / `_uv` read at `bit_depth(fctx)`, the - // colour-index map writes u16 samples). Three 12-bit arms decode - // BYTE-EXACT against the instrumented `aomdec --rawvideo` and against - // ffmpeg, each with a +1 control on the oracle's own bytes: - // `a_real_aomenc_12bit_screen_content_palette_stream_decodes_pixel_exact` - // (pin `screen12_palette.obu`, 2 frames, 76 palette / 43 palette-UV), - // `a_real_aomenc_12bit_intrabc_screen_stream_decodes_pixel_exact` (pin - // `screen12_intrabc.obu`, 1 frame, `allow_intrabc = 1`, 36 palette / - // 34 palette-UV / 11 intrabc blocks) and - // `a_real_aomenc_12bit_lossless_screen_content_stream_decodes_pixel_exact` - // (pin `screen12_lossless_palette.obu`, 2 frames, 80 palette / - // 59 palette-UV, `CodedLossless` AND screen content in the same frame). - // The companion "12-bit intrabc has no producer" note was a RECIPE - // artefact: libaom sets that frame-header bit from its content detector - // (`encoder.c:2404`), so an untiled `smptebars=size=128x96` source gives - // `allow_intrabc = 0` with AND without `--tune-content=screen`, while the - // 256x192 `-vf tile=2x2` source gives `= 1` at 8, 10 and 12 bits. - // lane-av1txr-r2 added, lane-av1-qmatrix RETIRED: the third member of the - // silent-garbage family (`using_qmatrix`/`qm_y`/`qm_u`/`qm_v`, refused by - // name at the frame header) now DEQUANTISES through libaom's - // `iwt_matrix_ref`/`get_dqv` port (`crate::qm`): the parsed 4-bit levels - // select per-plane matrices, 1D/identity transforms and lossless blocks - // stay flat. Witness: - // `a_real_aomenc_quantisation_matrix_stream_decodes_pixel_exact`. - // lane-lossless/lane-lossless2: a lossless frame (base_q_idx 0) decodes - // sample-exact, KEY and INTER -- TX_4X4 with the Walsh-Hadamard transform - // on every plane, no `tx_type` symbol, `is_cfl_allowed` narrowed to a - // BLOCK_4X4 chroma plane block, and the chroma plane walked as 4x4 units - // plane-major inside each mu chunk (gates - // `a_lossless_libaom_key_frame_decodes_sample_exact` / - // `a_lossless_libaom_inter_frame_decodes_sample_exact`). The refusal - // that stood here for a frame whose SEGMENTS disagree ("the TX_4X4/WHT - // rules are per segment there") is LIFTED too: lane-av1mixloss ports the - // per-segment table (libaom `decodeframe.c:5205`), and - // `a_real_aomenc_mixed_lossless_segment_frame_decodes_sample_exact` - // proves a real aq-mode stream sample-exact. - "a frame OBU with no tile group", - "a frame naming primary_ref_frame at a reference slot with no saved CDF state", - "a frame with no mode-info grid", - "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)", - // Still live, but NARROWED: lane-rectres r1 added the 32x32-level 1:4 - // strips (32x8 / 8x32) to `rect_inter_residual_supported` -- THE shape both - // 10-bit 3840x1608 film cuts and every measured 1080p offset stopped on - // (gate `a_real_aomenc_inter_sequence_with_32x32_level_1to4_strips_codes_\ - // their_rect_residual`). The string stays because the shapes below 8x8 and - // the AB-partition footprints still have no rectangular residual path. - "a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual coding", - "a reference frame selected with no picture at this frame's own ref_frame_idx slot for it", - "a reference picture outside the 2x down / 16x up scaling limits", - "a show_existing_frame header naming an empty reference slot", - "an inter var-tx tree with a leaf transform larger than 32x32", - // lane-intrainter r1 lifted the >=16x16 square case (per-TU intra - // prediction + coefficients, gate - // `a_real_aomenc_inter_sequence_with_a_split_transform_intra_block_decodes_pixel_exact`); - // lane-leaf8tx r4 lifted the 8x8 leaf's TX_4X4 2x2 grid (gate - // `a_real_aomenc_inter_sequence_with_an_angle_delta_8x8_intra_leaf_decodes_pixel_exact`). - "an inter frame with no key frame before it", - // lane-inter16ab r1 lifted the AB half and r2 the 1:4 half (four 16x4 / - // 4x16 inter strips, their 8x4/4x8 chroma pair built from BOTH strips' - // motion vectors -- gate - // `a_real_aomenc_inter_sequence_with_16x16_level_1to4_partitions_decodes_pixel_exact`). - // Two narrower refusals are what is left of that shape: - "an inter 16x16-level partition value outside NONE/HORZ/VERT/SPLIT/AB/1:4", - // r2 residue: `vartx_leaves` is a list of SQUARE units, and - // `sub_tx_size_map[TX_16X4]` is the rectangular TX_8X4 -- the split tree - // and its per-unit residual reader both need rect leaves. - // r2 residue: `decode_intra_rect_in_inter` codes chroma at the strip's own - // halved footprint, which for a 16x4 strip is an 8x2 transform libaom - // never wrote (its chroma is the PAIR's 8x4, coded by the odd strip). - // lane-sub8x4 r3 narrowed this to "a strip with no chroma-pair record"; - // lane-wit16x4 r1 put it back at FULL width (r3's witness counters were - // phantoms of a desync, class `refusal-lifted-without-a-gate`) behind - // an opt-in. lane-t900 r6 NARROWED it again -- the opt-in is - // gone -- on a real 10-bit 1920x792 128-superblock film witness that - // decodes 14/14 decode-order frames exact vs aomdec and 12/12 shown frames - // exact vs ffmpeg while the arm fires 78 16x4 + 149 4x16 (108 chroma- - // paired): gate - // `a_10bit_128sb_film_frames_with_warp_cdef_and_interintra_decode_pixel_exact`. - // What still refuses is a 16x4/4x16 strip with NO chroma-pair record and - // every other sub-8 shape. - "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)", - "an intra mode this decoder does not code (round 2)", - // lane-intrarect r1 lifted the whole-shape refusal that stood here (the - // inter path's intra arm now routes 2:1 strips through `decode_rect_split`); - // what is left is the 1:4 shape, whose `bsize_to_tx_size_cat` breaks the - // size-group/category diagonal the 2:1 shapes share. - "an intra-coded {bw}x{bh} block on the inter block path (no size-group/tx-category row for that shape here)", - // lane-t900 r21 NARROWED this: the string used to guard EVERY rect intra - // strip of a screen-content inter frame, and a real - // `--tune-content=screen` stream reached it on an 8x16 (8-bit) / 16x8 - // (10-bit) strip. The 2:1 reader now codes the palette syntax itself and - // the 1:4 arm goes through `read_intra_mode_rect`, which already did -- - // both arms of gate - // `a_real_aomenc_screen_inter_sequence_codes_palette_syntax_on_rect_intra_strips` - // decode ten frames pixel-exact with the strips counted. What still - // lane-t900 r22 NARROWED it again: the 16x4/4x16 arm is LIFTED (that arm - // routes through `decode_rect4_16_strip`, which reads the palette syntax - // itself -- the premise was stale), gated by - // `a_screen_stream_with_16x4_intra_strips_in_inter_frames_decodes_pixel_exact`. - // What still refuses is the 128-root half of a screen-content frame, whose - // body (`decode_block_128rect`) reads no palette syntax and for which no - // `--sb-size=128` screen witness exists yet. - // lane-t900 r32: the 128-root arm is LIFTED. r31's enumeration - // (`no_block_footprint_with_a_128_pixel_side_can_carry_palette_syntax`) is - // its proof -- `av1_allow_palette`'s `bw > 64 || bh > 64` bound means a - // 128x64/64x128 half codes NO palette syntax at all, so a screen-content - // frame's half is byte-identical in syntax to the non-screen twin gate - // `an_intra_coded_128_half_inside_an_inter_frame_decodes_pixel_exact` - // already decodes pixel-exact. Nothing of this string remains. - // lane-t900 r32: the residue of the LIFTED "an intrabc block under - // TxMode::Select". The inter var-tx tree is read in full, but the intra - // luma reconstruct loop it feeds is a UNIFORM grid of one square - // transform, so a tree resolving to mixed leaf sizes would be - // reconstructed at the wrong stride. Neither arm of - // `an_intrabc_block_under_tx_mode_select_decodes_pixel_exact` reaches it - // (both resolve uniform), so it is unwitnessed and stays live. - // lane-av1-ibcvtx: LIFTED. The t900 census's own maxp32 recipe class, - // retargeted at testsrc2 content with `--max-partition-size=64`, reaches - // mixed trees on the first encode (12-recipe hunt, 5/12 recipes hit). - // The luma reconstruct now walks the tree's own leaf list per leaf, and - // the block's chroma inherits the co-located luma unit's coded tx type - // (`av1_get_tx_type`, blockd.h:1278 -- that inheritance was missing on - // the uniform multi-TU intrabc path too). Gate: - // `a_real_aomenc_intrabc_mixed_vartx_tree_decodes_without_the_mixed_leaf_refusal`. - // Its census gate - // (`an_intrabc_vartx_census_measures_the_mixed_leaf_refusal`) survives as - // the witness that the premise is still exercised -- `reached` is 0 by - // construction now. - "a motion_mode symbol for a block shape with no CDF row here", -]; - -/// The refusals that have a PROVING test, and its name. -/// -/// A refusal with no such test is an unmeasured claim: nothing in the suite -/// distinguishes "this case never happens" from "no stream we decode has -/// reached it yet". A proving test is one of two shapes: -/// -/// * a WITNESS gate -- a real stream reaches the shape, decodes exact, and the -/// refusal is gone (the good case), or -/// * a CENSUS gate -- N real streams decode with the refusal firing 0 times -/// while the counters for the sibling shapes it names fire, so the claim is -/// measured against the domain the decoder is actually handed. -/// -/// The count printed by [`tests::every_proven_refusal_names_a_test_that_exists`] -/// is the honest numerator over the inventory below. -/// -/// # lane-av1-hdr: which pins are `spec-conformant` vs a real gap -/// -/// A negative gate proves our refusal FIRES by name on a hand-built stream; it -/// does not prove libaom would reject the same stream. This lane read the -/// libaom counterpart for the header/reference cluster and recorded the -/// verdict (`lanes/av1hdr.report.md` §3). The spec-conformant pins (libaom -/// errors identically) are, with their libaom site: -/// -/// * `primary_ref_frame` empty slot -- `decodeframe.c:5075` `AOM_CODEC_CORRUPT_FRAME`. -/// * `show_existing_frame` empty slot -- `decodeframe.c:4651` `AOM_CODEC_UNSUP_BITSTREAM`. -/// * reference selected with no picture -- `decodeframe.c:5027` `AOM_CODEC_CORRUPT_FRAME`. -/// * inter frame with no key frame before -- same site (`decodeframe.c:5008`). -/// * no mode-info grid -- no libaom error site; a 0-sized frame cannot be coded. -/// -/// The two that are NOT spec-conformant, and are kept as named capability gaps -/// with an assessment (a real gap libaom accepts, no reachable witness here): -/// a reference picture whose height differs (libaom SCALES, -/// `decodeframe.c:5089`). A third one -- a frame mixing lossless and lossy -/// segments (libaom decodes it per segment, `decodeframe.c:5205`) -- was the -/// same kind of gap until lane-av1mixloss ported the per-segment table; its -/// refusal is gone and -/// `a_real_aomenc_mixed_lossless_segment_frame_decodes_sample_exact` is the -/// witness. -#[cfg(test)] -/// Which KIND of proof each [`PROVEN`] row carries. -/// -/// A 2-tuple made every row look equally proven, which is the whole defect: -/// a row whose gate drives a hand-built stream into the guard and a row -/// whose gate sweeps an alphabet and shows nothing reaches it are held to -/// the same standard and read the same way. `label()` is what the tests -/// print, so the distinction is visible in the suite's own output. -/// -/// lane-av1refusalclaim r3 also proposed a third variant, `TablePin` -/// ("the arms are pinned exactly but the domain the table is REACHED over -/// is unestablished"). It is deliberately NOT carried: the one row it was -/// minted for now has a gate that establishes the reach domain -/// (`every_chroma_unit_decode_block_rect_can_present_has_a_coefficient_table` -/// reads the eight `decode_block_rect` call sites' own literal `bw`/`bh`, -/// pins the resulting chroma table exactly, and asserts the `(4,8)`/`(8,4)` -/// residual is UNPRODUCIBLE), so `Enumeration` is the honest tag and a -/// variant with no row would be dead weight. Re-add it the day a gate really -/// pins a table without measuring its caller domain -- and give it a row. -#[cfg(test)] -enum Proof { - /// A written stream REACHES the guard and is refused by this exact - /// string: the gate goes RED if the guard is removed. - NegativeGate, - /// The gate enumerates every input the guard can be reached over and - /// shows that none of them reaches it: it proves UNREACHABILITY, so it - /// is GREEN if the guard is removed. - Enumeration, -} - -#[cfg(test)] -impl Proof { - fn label(&self) -> &'static str { - match self { - Proof::NegativeGate => "NEGATIVE (reaches the guard; red on removal)", - Proof::Enumeration => "ENUMERATION (proves unreachability; green on removal)", - } - } -} - -#[cfg(test)] -const PROVEN: &[(&str, &str, Proof)] = &[ - // lane-t900 r20, census: three real streams present exactly the 18 - // `(side, write_w, write_h)` triples `INTER_BLOCK_SHAPES` lists, and - // `rect_inter_residual_supported` covers every rectangular one -- the only - // footprints `reject_residual` is set for. - // lane-av1-witness2 (8 more inter encodes: banded and busy content, - // --max-partition-size=32, a single-ref arm, cq 20..45, cpu-used 0..1): - // no refusal -- every rect strip the encoder produced sat inside the - // supported set. Static half, from the same hunt: the supported list plus - // the partition walker's piece set (SB pieces 64x32/32x64/64x16/16x64, - // the 32- and 16-level rect/1:4/AB twins, 128 halves tiled as two - // TX_64X64) enumerate every rect footprint AV1 partitioning can present; - // 1:4 stops at 64 because the 128 root has no 1:4 symbol. No conformant - // stream can name an unsupported footprint. - ( - "a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual coding", - "a_block_shape_census_over_three_real_streams_leaves_the_rect_residual_refusal_unreachable", - Proof::Enumeration, - ), - // lane-t900 r20, census: the shapes that can reach `decode_intra_rect_in_inter`'s - // size-group/tx-category lookup are the ten rectangular census shapes with - // `8 <= min` and `max <= 64` (a sub-8 footprint and a 128-px one take - // earlier branches), and every one of them has a row. - ( - "an intra-coded {bw}x{bh} block on the inter block path (no size-group/tx-category row for that shape here)", - "every_intra_in_inter_shape_the_census_lists_has_a_size_group_row", - Proof::Enumeration, - ), - // lane-t900 r20, census: the only sub-8 footprints three real streams - // present are the 16x4/4x16 strips of a 16x16-level 1:4 partition, whose - // caller records the chroma pair for every strip, while the supported path - // fires on both orientations inside streams that decode with no refusal. - ( - "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)", - "a_sub8_footprint_census_over_real_streams_leaves_the_intra_16x4_pairing_refusal_unreachable", - Proof::Enumeration, - ), - // lane-t900 r20, census: the rect transform tables and scans, enumerated - // over the shapes the measured block-shape domain hands each helper (block - // footprint, 4:2:0 chroma unit, rect var-tx leaf, clamped coded corner). - // lane-av1-witness2 (8 inter encodes, --enable-tx-size-search=1, rect+1:4 - // on, --min-partition-size=4, 4:2:0 and 4:4:4, sb 64/128, cq 10..45, - // cpu-used 0..2): no refusal while the domain was genuinely exercised -- - // whole-block 32x8 inter TUs and sub-8 rect pieces decoded. The fourteen - // rect shapes the enumeration covers are the whole alphabet, so the `_` - // arm has no conformant input. - ( - "a rectangular inter luma transform unit whose shape has no coefficient table set here", - "every_rect_transform_shape_the_census_lists_has_a_coefficient_table_and_scan", - Proof::Enumeration, - ), - ( - "a rectangular inter chroma transform unit whose shape has no coefficient table set here", - "every_rect_transform_shape_the_census_lists_has_a_coefficient_table_and_scan", - Proof::Enumeration, - ), - ( - "a rectangular transform unit whose shape has no coefficient scan table here", - "every_rect_transform_shape_the_census_lists_has_a_coefficient_table_and_scan", - Proof::Enumeration, - ), - // lane-t900 r21, enumeration: a var-tx leaf is never larger than the unit - // the tree was entered with, and both callers enter at or below their own - // ceiling (the one case that does not, a 64px block at TX_64X64, is the - // `single` whole-block case the refusal is guarded by). - ( - "an inter var-tx tree with a leaf transform larger than 32x32", - "a_var_tx_tree_never_presents_a_leaf_larger_than_the_unit_it_entered", - Proof::Enumeration, - ), - ( - "an inter var-tx tree with a leaf transform larger than 64x64", - "a_var_tx_tree_never_presents_a_leaf_larger_than_the_unit_it_entered", - Proof::Enumeration, - ), - // Pre-existing proofs, registered by lane-t900 r21: a negative gate (a - // hand-built 12-bit sequence header is refused BY THIS EXACT STRING rather - // than decoded wrong) and a witness gate (a real aomenc screen key frame - // reaches intrabc on a rect strip, so the refusal names a shape a real - // encoder does write). - // lane-t900 r21, enumeration: `partition_w32` is a ten-symbol CDF and - // `partition_w128` an eight-symbol one, and every `match` carrying one of - // these three fallbacks has an arm for each value of its own alphabet, so - // no stream can reach them. - ( - "a 32x32 partition type this decoder does not code (value={part32})", - "every_partition_value_of_an_enumerated_alphabet_has_an_arm", - Proof::Enumeration, - ), - ( - "an INTER 32x32 partition type this decoder does not code (value={part32})", - "every_partition_value_of_an_enumerated_alphabet_has_an_arm", - Proof::Enumeration, - ), - ( - "a 128x128 superblock partition value outside the 8-symbol alphabet", - "every_partition_value_of_an_enumerated_alphabet_has_an_arm", - Proof::Enumeration, - ), - // lane-t900 r24, enumeration: the key-frame superblock root's own `match` - // has an arm for all ten `partition_w64` values. - ( - "a superblock-level partition value outside PARTITION_NONE..PARTITION_VERT_4", - "every_partition_value_of_an_enumerated_alphabet_has_an_arm", - Proof::Enumeration, - ), - // lane-t900 r24, enumeration: the inter 16x16-level if/else chain's - // branches name all ten `partition_w16` values between them. - ( - "an inter 16x16-level partition value outside NONE/HORZ/VERT/SPLIT/AB/1:4", - "every_partition_value_of_an_if_chain_alphabet_is_named_by_a_branch", - Proof::Enumeration, - ), - // lane-t900 r24, enumeration: every (CDF width, symbol) pair a tx_type row - // can present maps to a distinct member of that width's own set. - ( - "a tx_type symbol outside its CDF's own set: {t}", - "every_tx_type_symbol_of_every_cdf_width_maps_into_its_own_set", - Proof::Enumeration, - ), - // lane-t900 r24 + lane-av1txr RE-PIN, measured: the reader covers spec - // 5.11.40's whole value domain (`0..=(1 << 20) - 2`, both ends of every - // prefix length), so no CONFORMANT symbol stream reaches it -- but the - // string IS reachable as a SYMPTOM: a frame this decoder desyncs on - // (measured: a real libaom monochrome key frame, gate - // `a_real_libaom_monochrome_key_frame_is_refused_by_name` at - // `stream.rs`) leaves the reader mid-symbol and the next `read_golomb` - // reports this tail. The claim below therefore pins the reader's value - // coverage, NOT the string's unreachability. - ( - "a Golomb tail longer than this decoder reads", - "read_golomb_reads_every_value_a_conformant_stream_can_carry", - Proof::Enumeration, - ), - // lane-t900 r25, enumeration: `parse_tile_group` is the only producer of - // the `tiles` vector `decode_stream` tests, and its success path always - // pushes at least one `Tile` -- swept over a real frame OBU's tile payload - // truncated from empty upwards. - ( - "a frame OBU with no tile group", - "a_frame_obu_that_parses_always_carries_at_least_one_tile", - Proof::Enumeration, - ), - // lane-t900 r25, negative gates: hand-built streams that reach each - // refusal by name and output no picture (a `show_existing_frame` header - // over all 8 empty slots; a stream that opens on an inter frame). - ( - "a show_existing_frame header naming an empty reference slot", - "a_show_existing_frame_header_naming_an_empty_slot_is_refused_by_name", - Proof::NegativeGate, - ), - ( - "an inter frame with no key frame before it", - "an_inter_frame_opening_a_stream_is_refused_by_name", - Proof::NegativeGate, - ), - // lane-t900 r25, enumeration: a motion_mode/obmc symbol is read only under - // `is_motion_variation_allowed_bsize` (min side >= 8), and each of the 17 - // `BLOCK_SIZES_ALL` footprints that clause admits maps to a distinct row of - // the 17-row table. - ( - "a motion_mode symbol for a block shape with no CDF row here", - "every_shape_that_allows_motion_variation_has_a_motion_mode_cdf_row", - Proof::Enumeration, - ), - // lane-av112bit: real-aomenc 12-bit streams, each refused by name - // (the gates encode with aomenc --bit-depth=12 and assert the exact - // string; the pixel witnesses are the same battery's Ok arms). - // lane-av112bitc: the compound pair left with its refusal -- the - // six-frame compound stream now DECODES byte-exact - // (`a_real_aomenc_12bit_compound_inter_sequence_decodes_pixel_exact`). - // lane-av112bitg: the grain refusal left with its witness -- the - // two-frame 12-bit grain stream now DECODES byte-exact - // (`a_real_aomenc_12bit_film_grain_stream_decodes_pixel_exact`). - // lane-av112bitw: the warp pair left too -- its gate now WITNESSES - // (`a_12bit_warped_motion_stream_decodes_pixel_exact`, the same recipe - // that refused pre-lift) and the compound-warp arm witnesses through - // `a_real_compound_global_warp_12bit_stream_decodes_pixel_exact` - // (hard `compound_warp_hits > 0`). - // lane-av1422lift: the 4:2:2 sequence-header refusal is GONE and so is - // this pairing. The tuple named `a_non_420_subsampled_sequence_header_is_ - // refused_by_name` as the gate that refused (1,0); that gate asserted a - // REFUSAL STRING, so it could not fail on a tree where 4:2:2 decode was - // completely broken -- it passed unchanged on the broken tree and would - // have kept passing if the port had been reverted. Its replacement - // `a_real_422_key_frame_and_inter_sequence_decode_pixel_exact` (and the - // corpus battery `the_pinned_422_corpus_cells_decode_pixel_exact`) assert - // BYTE-EXACT planes against ffmpeg on real 4:2:2 streams, with the - // per-plane coefficient-unit census as the non-vacuity arm. - // lane-av1txr-r2 paired, lane-av1-qmatrix RETIRED with its gate: the - // refusal's witness is now - // `a_real_aomenc_quantisation_matrix_stream_decodes_pixel_exact`, which - // asserts the qm-on stream DECODES pixel-exact vs ffmpeg and the - // matrices were really applied (census counters), while the qm-off - // control stays exact and flat. - // lane-av1-ibcrect: the pairing for "intra block copy on a HORZ/VERT/1:4 - // rect intra strip (reconstruction is not ported at this shape)" is GONE - // with the string -- lane-av1-intrabc/rect14 reconstructed the - // 16x16/32x32-level strips and this lane ported the last site, - // `decode_block_128rect`'s 128-root strip. Witness: - // `an_sb128_rect_strip_with_intrabc_decodes_pixel_exact`. - // lane-t900 r26, enumeration: a y_mode symbol comes from a 13-symbol CDF - // and all three guards refuse 13 and above. - ( - "an intra mode this decoder does not code (round 2)", - "every_intra_mode_symbol_of_the_y_mode_alphabet_is_coded", - Proof::Enumeration, - ), - // lane-t900 r26, enumeration: `compute_image_size` is 0 only for a zero - // frame width/height, which no path a header can code produces (swept - // through the real reader per axis, superres division enumerated). - ( - "a frame with no mode-info grid", - "every_frame_size_a_header_can_code_has_a_mode_info_grid", - Proof::Enumeration, - ), - // lane-t900 r26, negative gates: written streams that reach each refusal - // by name (a 64x32 inter frame over a 64x64 reference; a stream opening on - // a non-error-resilient inter frame whose primary_ref slot is empty, over - // all 8 slots) with the picture/CDF slot invariant enumerated alongside. - // lane-t900 r27, negative gate + structural note: every non-`LAST_FRAME` - // reference resolves through `ref_planes`, where an empty slot refuses by - // name (swept over all six such references). The STREAM-level witness is - // out of reach of this crate's writers -- a shown key frame refreshes all - // eight slots and nothing ever clears one, and a stream opening on an - // inter frame is stopped one guard earlier -- so the reachable premise is - // a HIDDEN key frame with a partial `refresh_frame_flags`, which - // `write_frame_header` cannot write. That gap is the open half. - ( - "a reference frame selected with no picture at this frame's own ref_frame_idx slot for it", - "a_selected_reference_with_an_empty_ref_frame_idx_slot_refuses_by_name", - Proof::NegativeGate, - ), - // lane-t900 r27, negative gate + census: a written key frame carrying - // each of the three mode-overriding features (over three segment ids) is - // refused by name with no picture; and real aomenc recipes never enable - // one. lane-av1seglvl re-scoped the census: beyond r27's six 1-pass - // no-lag recipes it now parses EVERY frame header's feature table over - // alt-ref-lag and genuine two-pass arms (`--aq-mode=1/2`, cq45 and the - // branch's own high-q cq63, screen + film sources) -- the shapes that - // reach `configure_static_seg_features`, the only setter of ALT_LF/ - // REF_FRAME/SKIP in the tree, which is gated on `hl_sf.static_segmentation` - // ("Always set to 0", speed_features.h) and the second pass - // (encoder_utils.c:738). What aomenc codes is `SEG_LVL_ALT_Q` tables and - // `segment_id` symbols, and nothing else; the map-inheritance defect that - // census surfaced (verbatim copy, decodemv.c:342) is fixed and witnessed - // by `a_real_aomenc_segmentation_stream_with_map_inheritance_decodes_ // pixel_exact`. - // lane-av1-witness2 re-confirmed the census on the current aomenc build: - // it has no --enable-segmentation flag at all (aq-mode is the only - // segmentation driver; aq-mode 4 is out of range for the build), and 8 - // aq-mode recipes (1/2/3, + --delta-lf-mode=1, 4:4:4, banded content) - // wrote SEG_LVL_ALT_Q tables and segment_id symbols where segmentation - // engaged, decoded clean, and never coded one of the three - // mode-overriding features. - ( - "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)", - "a_frame_whose_segmentation_overrides_a_block_mode_is_refused_by_name", - Proof::NegativeGate, - ), - // lane-t900 r27, structural audit + witness: `record_inter_rect_mi` is the - // single writer of the interp-filter neighbour band, and no call site - // stamps the `[3, 3]` sentinel on an INTER cell (the audit tokenises each - // site's arguments); two real `--enable-obmc=1 --enable-dual-filter=1 - // --cpu-used=0` streams then decode with 237 band reads over ~115 OBMC - // blocks each and the refusal firing 0 times (gate - // `a_real_obmc_stream_reads_a_recorded_switchable_filter_for_every_neighbour`). - // At `--cpu-used=4` aomenc settles on a frame-level fixed filter and the - // band is never read -- the speed is load-bearing in that gate. - ( - "an OBMC neighbour whose switchable interp filter was never recorded", - "every_inter_record_publishes_an_obmc_readable_filter", - Proof::Enumeration, - ), - // lane-t900 r28: all three scaled-reference (superres) refusals -- the - // 8x8 partition leaf, the sub-8x8 inter block and warp -- are LIFTED and - // gone from this inventory. The gate - // `real_superres_streams_with_sub8_leaf8_and_warp_decode_pixel_exact` - // decodes both lifted shapes byte-exact vs ffmpeg, and the census now - // asserts none of the three strings comes back. - // lane-t900 r33, enumeration: the five callers of `decode_rect_split` pass - // the ten rect footprints with `8 <= min` and `max <= 64`, and every one of - // them has a chroma table and -- at every tx depth -- a luma arm. The two - // shape classes that would miss one (a 128-sided half, a sub-8 strip) have - // readers that are not among those callers. - ( - "a coded HORZ/VERT strip whose chroma transform has no rect coefficient tables here", - "every_rect_strip_shape_the_split_path_codes_has_a_luma_and_chroma_table", - Proof::Enumeration, - ), - ( - "a split intra strip whose transform unit is {tx_w}x{tx_h} (no luma coefficient tables for that shape here)", - "every_rect_strip_shape_the_split_path_codes_has_a_luma_and_chroma_table", - Proof::Enumeration, - ), - // lane-av1-refusalaudit, enumeration + witness2 hunt: decode_block_rect64's - // chroma-unit table covers every conformant 64-axis strip unit in both - // supported chroma formats -- at 4:4:4 the strips 64x32/32x64/64x16/16x64 - // tile to (32,32)/(32,16)/(16,32); at 4:2:0 the halved footprints land on - // (32,16)/(16,32)/(32,8)/(8,32). A 128-root half is - // `decode_block_128rect`'s, and the 128 root has no 1:4 arm. The hunt (8 - // real aomenc key-frame encodes: screen+intrabc, rect+1:4, sb 64 and 128, - // cq 10..63, cpu-used 0..2) never reached the arm; the three streams that - // decode to completion never enter decode_block_rect64 at all. - ( - "a 64-axis strip whose chroma unit has no coefficient table", - "every_chroma_unit_a_64_axis_strip_can_present_has_a_coefficient_table", - Proof::Enumeration, - ), - // lane-av1rect8x16, enumeration: `decode_block_rect`'s `_` arm. The nine - // textual `decode_block_rect(` matches are 1 declaration + 8 call sites - // (this test's `assert_eq!(sites, 8)` counts the calls); all eight pass - // `bw`/`bh` as integer LITERALS and every one of them is - // a 32-level `PARTITION_HORZ`/`VERT`/`HORZ_A`/`_B`/`VERT_A`/`_B` arm of - // `read_sb128_root`'s `match part32`, so the caller shape set is exactly - // {32x16, 16x32} and their chroma halves under the three subsamplings an - // AV1 `color_config` can carry are {(16,8), (8,16), (16,16), (8,32), - // (32,16), (16,32)} -- every one of which has a row. The shape the - // sibling sweep left open, a 4:2:0 8x16 luma strip's (4,8) chroma, is - // NOT reachable here: a 16-level 2:1 luma strip is read by - // `decode_leaf_rect`, which carries the (4,8)/(8,4) rows itself - // (decode.rs:15409-15420). Measured, not assumed: 840 real aomenc 4:2:0 - // key-frame encodes, 826 of whose parsed leaf lists carry a coded - // 16-level 2:1 luma strip (`horz_vert_intra_hits()`, which fires only - // at the three `decode_leaf_rect` strip sites), decoded to completion - // with this string firing 0 times. - ( - "a rectangular chroma transform whose size has no coefficient table", - "every_chroma_unit_decode_block_rect_can_present_has_a_coefficient_table", - Proof::Enumeration, - ), - // lane-t900 r33, enumeration: each of the four symbols this guard tests is - // read under a size gate that no 128-pixel side passes (the call site's - // literal `cfl=false`, `filter_intra_size_class_rect`'s table, and - // `palette_bsize_ctx_wh`'s bound). - ( - "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)", - "no_128_root_half_reads_a_cfl_filter_intra_or_palette_symbol", - Proof::Enumeration, - ), - // lane-av1txr: the sub-8x8 intrabc refusal this census pinned is GONE (the - // capability landed; see the note in `REFUSALS`). The census gate survives - // as the witness that its premise is still exercised -- `reached` is 0 by - // construction now. - // lane-t900 r33, CENSUS: four quantisers of the recipe that reaches the - // intrabc var-tx tree at all read it for 5 blocks in total, every one of - // which resolved to a UNIFORM leaf size, with the frames pixel-exact. - // lane-av1-ibcvtx: the mixed-leaf refusal is LIFTED (see the note in - // `REFUSALS`); the pair above moved out with the string. The capability - // gate is - // `a_real_aomenc_intrabc_mixed_vartx_tree_decodes_without_the_mixed_leaf_refusal`, - // which pins the frame's residual sample mismatch against ffmpeg to the - // named second defect (a non-intrabc uniform-tree block elsewhere in the - // stream) so the pin tightens automatically when that defect is fixed. - ( - "a reference picture outside the 2x down / 16x up scaling limits", - "an_inter_frame_shorter_than_its_reference_is_refused_by_name", - Proof::NegativeGate, - ), - ( - "a frame naming primary_ref_frame at a reference slot with no saved CDF state", - "an_inter_frame_naming_an_unrefreshed_primary_ref_slot_is_refused_by_name", - Proof::NegativeGate, - ), - // lane-av1bookkeep W1-4, NEGATIVE: the BLOCK_INVALID subsize refusal - // (`refuse_invalid_plane_block`, decode.rs). It is libaom's own rule - // (`get_plane_block_size` -> `AOM_CODEC_CORRUPT_FRAME`, decodeframe.c:1456) - // applied to a stream whose header and tile disagree. The pin is a 4:2:2 - // sequence header over a 4:2:0 key frame's tile, whose partition symbols - // name 8x16 -- a subsize with no chroma plane block at ss (1,0) -- so the - // guard FIRES, by name, and the gate also drives a genuine 4:2:2 pin that - // must still decode, so it cannot pass by refusing everything. The gate's - // body quotes the refusal WHOLE (not just the libaom citation inside it), - // which is what makes this row an anchor the checker can hold. - ( - "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)", - "a_422_header_over_a_420_tile_refuses_the_subsize_libaom_calls_corrupt", - Proof::NegativeGate, - ), - // lane-av1bookkeep W1-4, ENUMERATION: the LONE capability claim. The guard - // in `decode_block_rect` fires only when `filter_intra.is_some()`, and that - // flag is `Some` only where `filter_intra_size_class_rect` says so. The - // strips the guard protects are `(64, 32)` / `(32, 64)`; - // `av1_filter_intra_allowed_bsize` caps both sides at 32x32, so no conformant - // stream offers the symbol there. The gate walks every EXPLICIT arm of the - // table (none admits a 64 axis), drives the square-delegate's callee - // `filter_intra_size_class` at 32 and 64 directly, and quotes the claim's - // leading clause in its own body. - ( - "filter intra on a superblock-level HORZ/VERT strip (never expected -- av1_filter_intra_allowed_bsize caps at 32x32)", - "a_sb_level_horz_vert_strip_admits_no_filter_intra_symbol", - Proof::Enumeration, - ), -]; - -/// Gates whose `Err` arm turns a decode failure into a printed SKIP rather than -/// a test failure. -/// -/// A gate named `..._decodes_pixel_exact` that cannot decode has failed, and -/// swallowing the error keeps the suite green while the gate proves nothing -- -/// the same vacuum as a gate whose feature never fires, arrived at from the -/// other side. The list is the exact pin of the gates still shaped that way, so -/// the set cannot grow; a converted gate is DELETED from it. -/// -/// lane-av1skipfix: emptied. The last four (`filter_intra`, the two -/// `deblocking` gates, and `gradients_stream_with_cdef`) were converted to the -/// attempt-loop pattern -- several recipes, at least one required to decode, the -/// feature counter hard-asserted on a pixel-compared attempt, a decode error on -/// every attempt a hard failure carrying its refusal text. None of the four had -/// a genuinely absent capability: every recipe family decoded, the refusals the -/// old arms swallowed were a named *screen-content* refusal on one recipe and a -/// stale premise on the CDEF gate (a single-superblock frame cannot make libaom -/// write `cdef_bits > 0`, so the old recipe never read a `cdef_idx` at all). -#[cfg(test)] -const GATES_THAT_SKIP_ON_A_DECODE_ERROR: &[&str] = &[]; - -/// Source text with Rust's line continuations dropped and every whitespace run -/// collapsed to one space -- the form rustc gives a multi-line literal -- so a -/// refusal written across three source lines is still findable in a body, and -/// a gate's quote of it still matches the guard's spelling. -#[cfg(test)] -fn squash_source(s: &str) -> String { - let mut out = String::with_capacity(s.len()); - let mut pending_space = false; - for (i, c) in s.char_indices() { - if c == '\\' { - let rest = &s[i + 1..]; - if rest.contains('\n') - && rest - .chars() - .take_while(|c| *c != '\n') - .all(|c| c == ' ' || c == '\t' || c == '\r') - { - continue; - } - } - if c.is_whitespace() { - pending_space = true; - continue; - } - if pending_space && !out.is_empty() { - out.push(' '); - } - pending_space = false; - out.push(c); - } - out -} - -/// Does `src` carry `refusal`? -/// -/// Lane-av1refusalspan: a proving gate quotes the refusal it proves, and this -/// is how it pins that quote to the guard that still carries the string. Both -/// sides are squashed, so a literal written over two lines with a `\` -/// continuation still matches. -#[cfg(test)] -pub(crate) fn pins_refusal(src: &str, refusal: &str) -> bool { - squash_source(src).contains(&squash_source(refusal)) -} - -#[cfg(test)] -mod tests { - use super::{ - CAPABILITY_CLAIMS, GATES_THAT_SKIP_ON_A_DECODE_ERROR, PROVEN, Proof, REFUSALS, - squash_source, - }; - use std::collections::BTreeSet; - - /// Every distinct `unsupported(...)` reason on the decode path. - /// - /// Both sources use the same shape -- `stream.rs` calls - /// `Error::unsupported(context, reason)` and `decode.rs` a local - /// `unsupported(reason)` helper -- so the reason is always the LAST string - /// literal of the call, and Rust's `\` line continuations inside it are - /// joined the way rustc joins them. - fn decode_path_refusals() -> BTreeSet { - let mut found = BTreeSet::new(); - for src in [crate::test_source::module_source("decode"), crate::test_source::module_source("stream")] { - let bytes = src.as_bytes(); - for (start, _) in src.match_indices("unsupported(") { - // `Error::unsupported(` and the bare helper both end here. - let mut i = start + "unsupported(".len(); - // `unsupported(format!("..."))` is the same refusal, one layer in. - if src[i..].starts_with("format!(") { - i += "format!(".len(); - } - let mut last: Option = None; - loop { - while i < bytes.len() && (bytes[i] as char).is_whitespace() { - i += 1; - } - if i >= bytes.len() || bytes[i] != b'"' { - break; - } - i += 1; - let mut lit = String::new(); - while i < bytes.len() && bytes[i] != b'"' { - if bytes[i] == b'\\' { - // A backslash-newline continuation drops the newline - // and the indentation that follows it. - if bytes.get(i + 1) == Some(&b'\n') { - i += 2; - while i < bytes.len() && matches!(bytes[i], b' ' | b'\t') { - i += 1; - } - continue; - } - lit.push(bytes[i] as char); - lit.push(bytes[i + 1] as char); - i += 2; - continue; - } - lit.push(bytes[i] as char); - i += 1; - } - i += 1; - last = Some(lit); - while i < bytes.len() && (bytes[i] as char).is_whitespace() { - i += 1; - } - if i < bytes.len() && bytes[i] == b',' { - i += 1; - continue; - } - break; - } - if let Some(reason) = last { - // `Error::unsupported`'s first argument is the context - // ("AV1 tile"), which is not a reason. - if reason != "AV1 tile" { - found.insert(reason); - } - } - } - } - found - } - - #[test] - fn the_decode_path_refuses_exactly_the_listed_cases() { - let found = decode_path_refusals(); - let listed: BTreeSet = CAPABILITY_CLAIMS - .iter() - .chain(REFUSALS) - .map(|&s| s.to_owned()) - .collect(); - assert!( - found.len() >= 30, - "the refusal scan found only {} reasons -- it is broken, not the decoder", - found.len() - ); - - let added: Vec<&String> = found.difference(&listed).collect(); - assert!( - added.is_empty(), - "new decode-path refusals are not in the inventory: {added:#?}\n\ - Add each to REFUSALS -- or, if it claims something about what an ENCODER can \ - emit, to CAPABILITY_CLAIMS, which requires evidence that the case is genuinely \ - unreachable rather than merely unseen." - ); - let removed: Vec<&String> = listed.difference(&found).collect(); - assert!( - removed.is_empty(), - "these refusals are listed but no longer in the decode path: {removed:#?}\n\ - Delete them from the inventory -- the capability landed, which is the good case." - ); - } - - /// A refusal may say what THIS DECODER does not do. Saying what an encoder - /// never emits is a claim about the world, and this repository has already - /// shipped one that was false. - #[test] - fn capability_claims_are_declared_not_scattered() { - let claimy: Vec = decode_path_refusals() - .into_iter() - .filter(|r| r.contains("never writes") || r.contains("never expected")) - .collect(); - let declared: BTreeSet<&str> = CAPABILITY_CLAIMS.iter().copied().collect(); - for reason in &claimy { - assert!( - declared.contains(reason.as_str()), - "{reason:?} claims an encoder never emits this case but is not in \ - CAPABILITY_CLAIMS. Such a claim needs a gate that proves the case is \ - unreachable; until it has one, phrase the refusal as what this decoder \ - does not decode." - ); - } - } - - /// No NEW gate may quietly turn a decode error into a skip. - #[test] - fn gates_that_swallow_a_decode_error_are_declared() { - let src = crate::test_source::module_source("stream"); - let mut found: BTreeSet = BTreeSet::new(); - for (i, _) in src.match_indices("\"SKIP ") { - let rest = &src[i + "\"SKIP ".len()..]; - let Some(colon) = rest.find(':') else { - continue; - }; - let name = &rest[..colon]; - if !name - .chars() - .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_') - { - continue; - } - // The tail of the message says what was skipped. Only "{e}" -- the - // decode error itself -- is the shape this test is about; "no - // ffmpeg"/"no aomenc" are tool absence, governed by - // EC_AV1_REQUIRE_AOMENC instead. - let Some(end) = rest.find("\"") else { continue }; - if rest[colon..end].contains("{e}") { - found.insert(name.to_owned()); - } - } - let listed: BTreeSet<&str> = GATES_THAT_SKIP_ON_A_DECODE_ERROR.iter().copied().collect(); - let added: Vec<&String> = found - .iter() - .filter(|n| !listed.contains(n.as_str())) - .collect(); - assert!( - added.is_empty(), - "these gates turn a decode error into a printed SKIP and are not declared: \ - {added:#?}\nA gate that cannot decode has failed -- assert on the error, or use \ - the attempt-loop pattern (several fixtures, at least one must decode, firing count \ - hard-asserted)." - ); - let stale: Vec<&&str> = listed.iter().filter(|n| !found.contains(**n)).collect(); - assert!( - stale.is_empty(), - "{stale:#?} no longer swallow a decode error -- delete them from the list." - ); - } - - /// The partition alphabet, in CDF symbol order. - const PARTITION_NAMES: [&str; 10] = [ - "PARTITION_NONE", - "PARTITION_HORZ", - "PARTITION_VERT", - "PARTITION_SPLIT", - "PARTITION_HORZ_A", - "PARTITION_HORZ_B", - "PARTITION_VERT_A", - "PARTITION_VERT_B", - "PARTITION_HORZ_4", - "PARTITION_VERT_4", - ]; - - /// The partition values a `match` arm pattern -- or an `if` chain's - /// condition -- names: its own tokens, plus every value of an inclusive - /// range (`(PARTITION_HORZ_A..=PARTITION_VERT_B).contains(&p)` is four - /// values in one). Tokenised, never `contains()`d: a misspelled constant - /// in a match pattern is an irrefutable binding that compiles and swallows - /// the alphabet, and a substring check would call that covered. - fn partition_values_named(head: &str) -> BTreeSet { - let mut out = BTreeSet::new(); - let idx: Vec = head - .split(|c: char| !(c.is_ascii_alphanumeric() || c == '_')) - .filter_map(|tok| PARTITION_NAMES.iter().position(|n| *n == tok)) - .collect(); - if head.contains("..=") && idx.len() == 2 { - for v in idx[0]..=idx[1] { - out.insert(v); - } - } - out.extend(idx); - out - } - - /// The partition alphabets, enumerated against the arms that code them. - /// - /// A partition value is a CDF symbol, and `SymbolDecoder::symbol_fixed` - /// cannot return one outside `0..nsyms` -- so a `match` whose arms cover - /// its whole alphabet has an unreachable fallback, and the refusal that - /// fallback carries names a value no stream can present. This test finds - /// each such `match` by the refusal in its OWN fallback arm (rather than - /// by line number, which drifts) and enumerates the alphabet against the - /// arm patterns, ranges included. - /// - /// The refusals stay in the code: a partition value is a `usize`, so the - /// match needs a fallback arm, and a named refusal is a better one than a - /// panic (class `branch-dropped-as-unreachable`). What this removes is the - /// UNMEASURED part of the claim. - /// - /// Not every partition fallback belongs here: the ones that name a shape - /// this decoder genuinely does not code yet (the 128-root consumers) are - /// live refusals, and the 16x16-level inter chain is an `if`/`else if` - /// ladder rather than a match, so it needs its own enumerator. - #[test] - fn every_partition_value_of_an_enumerated_alphabet_has_an_arm() { - // (the refusal in the fallback arm, the alphabet its CDF codes) - let blocks: [(&str, usize); 4] = [ - ( - "a 32x32 partition type this decoder does not code", - crate::cdf::PARTITION_W32[0].len() - 1, - ), - ( - "an INTER 32x32 partition type this decoder does not code", - crate::cdf::PARTITION_W32[0].len() - 1, - ), - ( - "a 128x128 superblock partition value outside the 8-symbol alphabet", - crate::cdf::PARTITION_W128[0].len() - 1, - ), - // lane-t900 r24: the key-frame superblock root. Its `part` is - // either a `partition_w64` symbol or, at a frame edge, one of the - // three gathered outcomes (PARTITION_HORZ, PARTITION_VERT, - // PARTITION_SPLIT) -- all inside the same ten-value alphabet. - ( - "a superblock-level partition value outside PARTITION_NONE..PARTITION_VERT_4", - crate::cdf::PARTITION_W64[0].len() - 1, - ), - ]; - let src = crate::test_source::module_source("decode"); - let lines: Vec<&str> = src.lines().collect(); - let indent = |l: &str| l.len() - l.trim_start().len(); - let mut found = 0usize; - for (i, line) in lines.iter().enumerate() { - let t = line.trim(); - if !(t.starts_with("match part") && t.ends_with('{')) { - continue; - } - let outer = indent(line); - let close = " ".repeat(outer) + "}"; - let (mut arms, mut fallback) = (BTreeSet::new(), String::new()); - let mut in_fallback = false; - for l in &lines[i + 1..] { - if *l == close { - break; - } - // Arm patterns sit exactly one level in; anything deeper is an - // arm's body, nested matches and `part == PARTITION_*` reads - // included. - if indent(l) != outer + 4 && !l.trim().is_empty() { - if in_fallback { - fallback.push_str(l.trim()); - } - continue; - } - if !l.contains("=>") { - continue; - } - in_fallback = l.trim_start().starts_with("_ =>"); - arms.extend(partition_values_named(l.split("=>").next().unwrap_or(""))); - } - let Some((reason, alphabet)) = - blocks.iter().find(|(reason, _)| fallback.contains(reason)) - else { - continue; - }; - found += 1; - let missing: Vec = (0..*alphabet).filter(|v| !arms.contains(v)).collect(); - assert!( - missing.is_empty(), - "the `match` at decode.rs:{} refuses {reason:?} but has no arm for {:?} -- that \ - is a real gap in its {alphabet}-value alphabet, not a dead refusal", - i + 1, - missing - .iter() - .map(|v| PARTITION_NAMES[*v]) - .collect::>() - ); - } - assert_eq!( - found, - blocks.len(), - "not every enumerated partition refusal was located in decode.rs" - ); - } - - /// The same enumeration for a partition refusal that sits in an `if` - /// chain rather than a `match` fallback. - /// - /// The inter 16x16-level ladder tests `part16` against constants arm by - /// arm and refuses in its second-to-last branch, with `PARTITION_SPLIT` - /// left to the final `else`. Nothing about that shape is weaker than a - /// `match`: `part16` is a `partition_w16` symbol (or, at a frame edge, a - /// gathered value of the same alphabet), so if the chain's conditions - /// between them name every value of that alphabet, the refusing branch is - /// unreachable. - /// - /// The conditions are read from the source, tokenised (never - /// substring-matched -- lane-t900 r21), and a condition carrying `&&` is - /// rejected outright: a value it names is only conditionally handled, and - /// counting it would overstate the coverage. - #[test] - fn every_partition_value_of_an_if_chain_alphabet_is_named_by_a_branch() { - // (the refusal in the chain's refusing branch, the alphabet its CDF codes) - let chains: [(&str, usize); 1] = [( - "an inter 16x16-level partition value outside NONE/HORZ/VERT/SPLIT/AB/1:4", - crate::cdf::PARTITION_W16[0].len() - 1, - )]; - - let src = crate::test_source::module_source("decode"); - let lines: Vec<&str> = src.lines().collect(); - let indent = |l: &str| l.len() - l.trim_start().len(); - let mut found = 0usize; - for (reason, alphabet) in chains { - let refusal = lines - .iter() - .position(|l| l.contains(reason)) - .unwrap_or_else(|| panic!("{reason:?} is not in decode.rs")); - // The branch that carries the refusal: the nearest `} else if` - // above it. Its indentation is the chain's own. - let head = (0..refusal) - .rev() - .find(|&i| lines[i].trim_start().starts_with("} else if ")) - .unwrap_or_else(|| panic!("{reason:?} is not inside an if/else chain")); - let outer = indent(lines[head]); - let var = lines[head].trim_start()["} else if ".len()..] - .split_whitespace() - .next() - .unwrap_or("") - .to_owned(); - assert!( - !var.is_empty(), - "the chain at decode.rs:{} tests nothing", - head + 1 - ); - - // Walk up collecting every branch head of this chain, each read to - // the line that opens its body. - let mut named = BTreeSet::new(); - let mut i = head + 1; - let mut heads = 0usize; - loop { - i -= 1; - let t = lines[i].trim_start(); - if indent(lines[i]) != outer - || !(t.starts_with("} else if ") || t.starts_with("if ")) - { - if i == 0 { - break; - } - continue; - } - let mut cond = String::new(); - for l in &lines[i..] { - cond.push(' '); - cond.push_str(l.trim()); - if l.trim_end().ends_with('{') { - break; - } - } - assert!( - cond.contains(&var), - "the branch at decode.rs:{} sits in the chain that refuses {reason:?} but \ - does not test {var}", - i + 1 - ); - assert!( - !cond.contains("&&"), - "the branch at decode.rs:{} handles its partition values only conditionally \ - ({cond:?}) -- the enumeration below would overstate what the chain covers", - i + 1 - ); - named.extend(partition_values_named(&cond)); - heads += 1; - if t.starts_with("if ") { - break; - } - assert!(i > 0, "the chain that refuses {reason:?} has no start"); - } - // The value the refusing branch excludes (`part16 != PARTITION_SPLIT`) - // is handled by the chain's final `else`, so require one. - let close = " ".repeat(outer) + "} else {"; - assert!( - lines[refusal..].iter().any(|l| *l == close), - "the chain that refuses {reason:?} has no final `else`, so the value its \ - refusing branch excludes is handled nowhere" - ); - assert!(heads >= 2, "only {heads} branch(es) found for {reason:?}"); - found += 1; - let missing: Vec = (0..alphabet).filter(|v| !named.contains(v)).collect(); - assert!( - missing.is_empty(), - "the chain at decode.rs:{} refuses {reason:?} but no branch names {:?} -- that \ - is a real gap in its {alphabet}-value alphabet, not a dead refusal", - head + 1, - missing - .iter() - .map(|v| PARTITION_NAMES[*v]) - .collect::>() - ); - } - assert_eq!(found, chains.len()); - } - - /// Every `tx_type` symbol of every CDF width, mapped through the set that - /// width names. - /// - /// The reader decodes `t` from a row of `n` slots, so `t` is in - /// `0..n - 1`, and hands `(n, t)` to [`crate::decode::tx_type_from_symbol`] - /// -- the readers' own mapping, called here rather than transcribed - /// (class `shared-oracle-blindness`: a second copy of a table can be - /// self-consistently wrong). The widths are read from `cdf_state.rs`'s - /// `tx_type` field declarations, so a new table with a width the mapping - /// does not name fails this test rather than reaching the refusal at - /// runtime. - /// - /// Distinctness is part of the claim: a set of `n - 1` symbols must map to - /// `n - 1` DIFFERENT transform types, or the mapping has lost a member of - /// the spec's `Tx_Type_*_Inv_Set*` even while every symbol resolves. - #[test] - fn every_tx_type_symbol_of_every_cdf_width_maps_into_its_own_set() { - let mut widths: BTreeSet = BTreeSet::new(); - for line in include_str!("cdf_state.rs").lines() { - let t = line.trim(); - if !(t.starts_with("pub ") && t.contains("tx_type") && t.contains("[u16;")) { - continue; - } - let tail = t.rsplit("[u16;").next().unwrap_or(""); - let n: usize = tail - .split(']') - .next() - .unwrap_or("") - .trim() - .parse() - .unwrap_or_else(|_| panic!("cannot read a CDF width out of {t:?}")); - widths.insert(n); - } - assert!( - widths.len() >= 4, - "the cdf_state.rs scan found only {widths:?} -- it is broken, not the decoder" - ); - for &n in &widths { - let nsyms = n - 1; - let mut set: Vec = Vec::new(); - for t in 0..nsyms { - let ty = crate::decode::tx_type_from_symbol(n, t).unwrap_or_else(|| { - panic!( - "a {n}-slot tx_type CDF codes symbol {t}, which maps to no transform \ - type -- the refusal \"a tx_type symbol outside its CDF's own set\" is \ - reachable, and that is a mapping-table gap to fix" - ) - }); - assert!( - !set.contains(&ty), - "a {n}-slot tx_type CDF maps symbol {t} to {ty:?}, which another symbol of \ - the same set already names -- a member of the spec's inverse table is lost" - ); - set.push(ty); - } - assert_eq!(set.len(), nsyms); - } - } - - /// The Golomb tail, enumerated over every value a conformant stream can - /// carry. - /// - /// Spec 5.11.40 `read_golomb` counts its unary prefix and BREAKS at - /// `length == 20`, then reads `length - 1` payload bits into an `x` whose - /// top bit is implicit -- so no conformant stream carries a value above - /// `(1 << 20) - 2`, and spec 5.11.39 agrees from the other side by masking - /// the level it feeds with `0xFFFFF`. This walks both ends of every - /// prefix length 1..=20 (plus the small values every real stream uses) - /// through [`crate::tile::write_golomb`] and back through the decoder's own - /// [`crate::decode::read_golomb`], so the refusal "a Golomb tail longer - /// than this decoder reads" is proved to sit strictly OUTSIDE the value - /// domain, not inside it. - /// - /// The residue is a bit pattern, not a value: the spec's break makes the - /// 20th prefix bit a don't-care, so a stream whose 20th prefix bit is 0 - /// decodes to the same value there and is refused here. libaom refuses the - /// same bit (`av1/decoder/decodetxb.c:30`, `AOM_CODEC_CORRUPT_FRAME` at - /// `length > 20`), so this refusal is NOT a reader gap to widen: when it - /// fires on a real stream it is an earlier desync's symptom -- see the - /// comment on `read_golomb`. - #[test] - fn read_golomb_reads_every_value_a_conformant_stream_can_carry() { - // lane-av1refusalspan: this gate is the PROOF for the refusal below, so - // it names it and pins its guard site. - const REFUSAL: &str = "a Golomb tail longer than this decoder reads"; - assert!( - super::pins_refusal(crate::test_source::module_source("decode"), REFUSAL), - "this gate proves {REFUSAL:?}, but that string is no longer in decode.rs" - ); - let roundtrip = |value: u32| -> ec_core::Result { - let mut enc = crate::msac::SymbolEncoder::new(); - crate::tile::write_golomb(&mut enc, value); - let data = enc.finish(); - let mut dec = crate::msac::SymbolDecoder::new(&data); - crate::decode::read_golomb(&mut dec) - }; - let mut values: BTreeSet = (0..=64u32).collect(); - for length in 1..=20u32 { - // `x` has `length` bits with its top bit set, and the value is - // `x - 1`: the two ends of what this prefix length can express. - values.insert((1u32 << (length - 1)) - 1); - values.insert(((1u64 << length) - 2) as u32); - } - let max = *values.iter().max().unwrap(); - assert_eq!( - max, - (1u32 << 20) - 2, - "the enumeration misses the spec's own ceiling" - ); - // A coefficient is masked to 20 bits (spec 5.11.39), and the base and - // base-range syntax contribute at most 15 of that before the tail, so - // this is the largest tail a legal coefficient can need. - assert!( - max >= 0xF_FFFF - 15, - "the ceiling is below the largest legal tail" - ); - for value in values { - match roundtrip(value) { - Ok(read) => assert_eq!(read, value, "the Golomb tail {value} read back as {read}"), - Err(e) => panic!( - "the Golomb tail {value} is inside the domain spec 5.11.40 can write but \ - this decoder refuses it: {e}" - ), - } - } - // And the refusal still names something: 20 zero prefix bits. - let mut enc = crate::msac::SymbolEncoder::new(); - for _ in 0..20 { - enc.literal(0, 1); - } - for _ in 0..20 { - enc.literal(1, 1); - } - let data = enc.finish(); - let mut dec = crate::msac::SymbolDecoder::new(&data); - assert!( - crate::decode::read_golomb(&mut dec).is_err(), - "the Golomb refusal is dead code -- drop it from the inventory" - ); - } - - /// The intra-mode alphabet, enumerated against the guard that refuses a - /// symbol outside it. - /// - /// Three readers -- the rect-in-inter arm, the intra-in-inter square arm - /// and the 8x8 leaf -- read a y_mode symbol and refuse `mode >= 13` with - /// "an intra mode this decoder does not code (round 2)". A `y_mode` symbol - /// comes from `Cdfs::y_mode[size_group]`, whose alphabet is - /// `Y_MODE[g].len() - 1` (the last slot is the adaptation counter), and - /// `SymbolDecoder::symbol` cannot return a value outside `0..nsyms` -- so - /// the guard is unreachable exactly when every size group's alphabet is at - /// most the threshold. - /// - /// Found by the refusal in the guard's own body rather than by line - /// number, and the CDF the symbol was read from is checked too: a - /// threshold of 13 over a 14-symbol table would be a live refusal, and a - /// site reading a WIDER alphabet (`uv_mode` with CfL is 14) under the same - /// guard would be one as well. - #[test] - fn every_intra_mode_symbol_of_the_y_mode_alphabet_is_coded() { - const REFUSAL: &str = "an intra mode this decoder does not code (round 2)"; - // Both uv_mode alphabets are listed so the CfL-allowed one (14 - // symbols, `UV_MODE_CFL_ALLOWED`) cannot silently become the source of - // a symbol tested against 13. - let alphabets: [(&str, usize); 3] = [ - ("y_mode", crate::cdf::Y_MODE[0].len() - 1), - ("uv_mode_no_cfl", crate::cdf::UV_MODE_NO_CFL[0].len() - 1), - ("uv_mode_cfl", crate::cdf::UV_MODE_CFL[0].len() - 1), - ]; - assert_eq!(alphabets[0].1, 13, "the y_mode alphabet changed size"); - for group in &crate::cdf::Y_MODE { - assert_eq!( - group.len() - 1, - alphabets[0].1, - "the y_mode rows disagree on width" - ); - } - - let src = crate::test_source::module_source("decode"); - let lines: Vec<&str> = src.lines().collect(); - let mut sites = 0usize; - for (i, line) in lines.iter().enumerate() { - let t = line.trim(); - let Some(rest) = t.strip_prefix("if mode >= ") else { - continue; - }; - let Some(threshold) = rest.trim_end_matches(" {").parse::().ok() else { - continue; - }; - // Only the guards carrying THIS refusal. - if !lines[i..(i + 4).min(lines.len())] - .join("\n") - .contains(REFUSAL) - { - continue; - } - sites += 1; - // The symbol's own CDF: the nearest `dec.symbol(&mut cdfs.X[..])` - // above the guard. - let read = lines[i.saturating_sub(12)..i] - .iter() - .rev() - .find(|l| l.contains("dec.symbol(&mut cdfs.")) - .unwrap_or_else(|| panic!("line {}: no symbol read above the guard", i + 1)); - let table = read - .split("dec.symbol(&mut cdfs.") - .nth(1) - .unwrap() - .split('[') - .next() - .unwrap(); - let (name, nsyms) = alphabets - .iter() - .find(|(n, _)| *n == table) - .unwrap_or_else(|| panic!("line {}: unknown mode alphabet {table:?}", i + 1)); - assert!( - *nsyms <= threshold, - "line {}: the guard refuses mode >= {threshold} on a symbol read from a \ - {nsyms}-symbol {name} CDF -- symbol {threshold} is inside that alphabet, so \ - the refusal is live and this enumeration does not prove it", - i + 1 - ); - } - assert_eq!( - sites, 3, - "the intra-mode guard is at three sites, found {sites}" - ); - } - - /// lane-t900 r31, ENUMERATION for "a HORZ/VERT intra strip in a - /// screen-content frame (palette syntax is consumed for square blocks - /// only)". - /// - /// That refusal guards the 128-root HORZ/VERT arm of the intra-in-inter - /// path (`decode.rs`, the `bw.max(bh) == 128` branch): the body it calls, - /// `decode_block_128rect`, reads no palette syntax, so a screen-content - /// frame was assumed to code some there. It cannot. `av1_allow_palette` - /// (spec 5.11.46 `read_palette_mode_info`: `bsize` between `BLOCK_8X8` - /// and `BLOCK_64X64` by side) is what this decoder mirrors in - /// `palette_bsize_ctx_wh`, whose bound is `bw > 64 || bh > 64 || - /// bw * bh < 64`. Every footprint with a 128-pixel side fails it, so the - /// screen flag changes NOTHING a 128-root half codes -- the refusal's - /// stated premise is false, and the string is a claim about the SYNTAX - /// (provable, and disproved here) rather than about libaom. - /// - /// It is deliberately NOT registered in [`PROVEN`]: the guarded condition - /// is still reachable (a screen frame CAN code a 128-root half), so this - /// test proves the LIFT is safe, not that the case never happens. Lifting - /// it is a `decode.rs` edit plus a witness stream, and no `--sb-size=128 - /// --tune-content=screen` encode found so far codes a 128-root half at all - /// (lane-t900 r23's census). - /// - /// The bound is asserted against `decode.rs`'s own source rather than a - /// copy of it here, so a change to the predicate breaks this test rather - /// than silently invalidating it (class `table-and-reader-move-together`). - #[test] - fn no_block_footprint_with_a_128_pixel_side_can_carry_palette_syntax() { - const BOUND: &str = "if bw > 64 || bh > 64 || bw * bh < 64 {"; - let src = crate::test_source::module_source("decode"); - assert!( - src.contains("fn palette_bsize_ctx_wh(bw: usize, bh: usize) -> Option {"), - "palette_bsize_ctx_wh is gone -- this enumeration no longer names the predicate \ - the decoder gates every palette read on" - ); - assert_eq!( - src.matches(BOUND).count(), - 1, - "av1_allow_palette's size bound is no longer spelled {BOUND:?} exactly once in \ - decode.rs -- re-derive this enumeration from the new spelling" - ); - // `palette_bsize_ctx_wh`'s own bound, applied to every AV1 block - // footprint (both sides a power of two from 4 to 128). - let allows_palette = |bw: usize, bh: usize| !(bw > 64 || bh > 64 || bw * bh < 64); - let (mut with_128, mut allowed_at_128) = (0u32, 0u32); - for wl in 2..=7u32 { - for hl in 2..=7u32 { - let (bw, bh) = (1usize << wl, 1usize << hl); - if bw.max(bh) != 128 { - continue; - } - with_128 += 1; - if allows_palette(bw, bh) { - allowed_at_128 += 1; - } - } - } - assert!( - with_128 > 0, - "enumeration is vacuous -- no 128-sided footprint was tried" - ); - assert_eq!( - allowed_at_128, 0, - "a footprint with a 128-pixel side passed av1_allow_palette's bound -- the \ - 128-root HORZ/VERT arm really would have to read palette syntax" - ); - // And the guarded shapes specifically: the two 128-root HORZ/VERT - // halves the refusal names. - for (bw, bh) in [(128usize, 64usize), (64, 128)] { - assert!( - !allows_palette(bw, bh), - "a {bw}x{bh} half can carry a palette after all" - ); - } - } - - /// lane-t900 r33, ENUMERATION for the two [`decode_rect_split`] refusals - /// ("a coded HORZ/VERT strip whose chroma transform has no rect - /// coefficient tables here" and "a split intra strip whose transform unit - /// is {tx_w}x{tx_h}"). - /// - /// Both guard shape lookups inside one function, so the proof is one - /// enumeration: the footprints that function is CALLED with, walked - /// through `depth_to_tx_wh` at every depth, against the two `match` - /// tables read out of `decode.rs` itself (class - /// `table-and-reader-move-together` -- a table edit invalidates this test - /// rather than sneaking past it). - /// - /// The footprint domain is the five callers' own: `decode_block_rect` - /// (32-level 2:1), `decode_block_rect4` (32-level 1:4), `decode_leaf_rect` - /// (16-level 2:1), `decode_block_rect64` (64-level 2:1 and 1:4) and - /// `decode_intra_rect_in_inter`, whose reachable shapes are the ten - /// rectangular census shapes with `8 <= min` and `max <= 64` (already - /// pinned by `every_intra_in_inter_shape_the_census_lists_has_a_size_group_row`). - /// The two shape classes that would MISS a table -- a 128-sided half - /// (chroma 64x32) and a sub-8 strip (16x4 -> chroma 8x2) -- are excluded - /// structurally: their readers, `decode_block_128rect` and - /// `decode_rect4_16_strip`, are not among the callers, which this test - /// asserts by locating every `decode_rect_split(` call in its enclosing - /// function. - #[test] - fn every_rect_strip_shape_the_split_path_codes_has_a_luma_and_chroma_table() { - let src = crate::test_source::module_source("decode"); - // lane-av1refusalspan: this gate is the PROOF for both refusals below, - // so it names both and pins both guard sites. - for refusal in [ - "a coded HORZ/VERT strip whose chroma transform has no rect coefficient tables here", - "a split intra strip whose transform unit is {tx_w}x{tx_h} (no luma coefficient tables for that shape here)", - ] { - assert!( - super::pins_refusal(src, refusal), - "this gate proves {refusal:?}, but that string is no longer in decode.rs" - ); - } - - // (1) The caller set. Each call's enclosing function is the last - // top-level `fn` before it. - let fn_starts: Vec<(usize, String)> = src - .match_indices("\nfn ") - .map(|(i, _)| { - let rest = &src[i + 4..]; - let name = rest[..rest.find('(').unwrap_or(0)].to_string(); - (i, name) - }) - .collect(); - let mut callers: BTreeSet = BTreeSet::new(); - for (at, _) in src.match_indices("decode_rect_split(") { - let enclosing = fn_starts - .iter().rfind(|(i, _)| *i < at) - .expect("a decode_rect_split call outside any function"); - if enclosing.1 != "decode_rect_split" { - callers.insert(enclosing.1.clone()); - } - } - let expected: BTreeSet = [ - "decode_block_rect", - "decode_block_rect4", - "decode_block_rect64", - "decode_intra_rect_in_inter", - "decode_leaf_rect", - ] - .iter() - .map(|s| s.to_string()) - .collect(); - assert_eq!( - callers, expected, - "the set of functions that call decode_rect_split changed -- re-derive the \ - footprint domain below from the new caller (a 128-sided or sub-8 caller makes \ - both refusals live)" - ); - - // (2) The walk, asserted against its own source before it is applied. - const WALK: &str = " let (mut w, mut h) = (bw.min(64), bh.min(64));\n \ - for _ in 0..depth {\n match w.cmp(&h) {\n \ - std::cmp::Ordering::Greater => w /= 2,\n \ - std::cmp::Ordering::Less => h /= 2,\n \ - std::cmp::Ordering::Equal => {\n w /= 2;\n \ - h /= 2;\n }\n }\n }"; - assert_eq!( - src.matches(WALK).count(), - 1, - "depth_to_tx_wh's walk is no longer spelled the way this enumeration mirrors it" - ); - let depth_to_tx_wh = |bw: usize, bh: usize, depth: usize| { - let (mut w, mut h) = (bw.min(64), bh.min(64)); - for _ in 0..depth { - match w.cmp(&h) { - std::cmp::Ordering::Greater => w /= 2, - std::cmp::Ordering::Less => h /= 2, - std::cmp::Ordering::Equal => { - w /= 2; - h /= 2; - } - } - } - (w, h) - }; - - // (3) The two tables, read out of decode_rect_split's own text: every - // `(w, h) =>` / `(w, h) |` match arm head between the table's `let` - // and the guard that follows it. - let body_at = src - .find("fn decode_rect_split(") - .expect("decode_rect_split is gone"); - let body = &src[body_at..]; - let slice = |from: &str, to: &str| -> &str { - let a = body - .find(from) - .unwrap_or_else(|| panic!("{from:?} is gone from decode_rect_split")); - let b = body[a..] - .find(to) - .unwrap_or_else(|| panic!("{to:?} is gone from decode_rect_split")); - &body[a..a + b] - }; - let arm_shapes = |text: &str| -> BTreeSet<(usize, usize)> { - let mut out = BTreeSet::new(); - let bytes = text.as_bytes(); - for (i, _) in text.match_indices('(') { - let mut j = i + 1; - let mut w = 0usize; - while j < bytes.len() && bytes[j].is_ascii_digit() { - w = w * 10 + usize::from(bytes[j] - b'0'); - j += 1; - } - if j == i + 1 || !text[j..].starts_with(", ") { - continue; - } - j += 2; - let mut h = 0usize; - let start_h = j; - while j < bytes.len() && bytes[j].is_ascii_digit() { - h = h * 10 + usize::from(bytes[j] - b'0'); - j += 1; - } - if j == start_h || !text[j..].starts_with(')') { - continue; - } - // Only an arm HEAD counts, never a `(32, 8)` inside prose. - let after = text[j + 1..].trim_start(); - if after.starts_with("=>") || after.starts_with('|') { - out.insert((w, h)); - } - } - out - }; - let chroma = arm_shapes(slice("let chroma: Option<(TxbSet", "if !m.skip {")); - let luma = arm_shapes(slice("let luma_rect: Option<(TxbSet", "no luma \\")); - assert!( - chroma.len() >= 6 && luma.len() >= 6, - "the tables parsed to {} chroma / {} luma shapes -- the parse, not the decoder, \ - is what this would be measuring", - chroma.len(), - luma.len() - ); - - // (4) The enumeration itself. - let mut checked = 0u32; - for wl in 3..=6u32 { - for hl in 3..=6u32 { - let (bw, bh) = (1usize << wl, 1usize << hl); - let ratio = bw.max(bh) / bw.min(bh); - if ratio != 2 && ratio != 4 { - continue; - } - assert!( - chroma.contains(&(bw / 2, bh / 2)), - "a {bw}x{bh} strip's {}x{} chroma transform has no rect table -- the \ - chroma refusal is LIVE for a shape a caller codes", - bw / 2, - bh / 2 - ); - // Every depth: once the walk reaches a square it stays square, - // so this covers any tx_depth a header can code. - for depth in 1..=4 { - let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth); - assert!( - tx_w == tx_h || luma.contains(&(tx_w, tx_h)), - "a {bw}x{bh} strip at depth {depth} resolves to a {tx_w}x{tx_h} \ - transform unit, which has no luma arm -- that refusal is LIVE" - ); - checked += 1; - } - } - } - assert_eq!( - checked, 40, - "the strip domain is not the ten rect shapes x four depths" - ); - } - - /// lane-av1rect8x16, ENUMERATION for "a rectangular chroma transform - /// whose size has no coefficient table" -- - /// [`crate::decode::decode_block_rect`]'s `_` arm. - /// - /// This refusal had NO `PROVEN` row: the sibling sweep that found the - /// gap (`every_rect_strip_shape_the_split_path_codes_has_a_luma_and_ - /// chroma_table`, which audits `decode_rect_split`'s tables, not this - /// function's) asserted only the superblock-level 64x32/32x64 - /// footprints, so the 8x16 luma strip's 4x8 chroma was left unasked. - /// - /// The answer is that the shape is UNREACHABLE, and structurally so: - /// every one of the function's call sites passes its `bw`/`bh` as - /// integer LITERALS, and all of them are 32-level `PARTITION_HORZ` / - /// `VERT` / `HORZ_A` / `HORZ_B` / `VERT_A` / `VERT_B` arms of - /// `read_sb128_root`'s `match part32` -- i.e. 32x16 or 16x32, never - /// 8x16. A 16-level 2:1 luma strip (16x8 / 8x16) is read by - /// [`crate::decode::decode_leaf_rect`], which carries the matching - /// `(4, 8)` / `(8, 4)` chroma rows (decode.rs:15409-15420, - /// `TxbSet::ChromaRect8x4` + `SCAN_4X8` / `SCAN_8X4`). - /// - /// So the proof is the CALLER SHAPE SET, read out of the call sites' - /// own argument lists, walked through `bw >> ss_x` / `bh >> ss_y` for - /// every subsampling an AV1 `color_config` can carry, against the - /// `match (chroma_w, chroma_h)` table read out of the function's own - /// text (class `table-and-reader-move-together`: a table edit - /// invalidates this test rather than sneaking past it). - /// - /// The subsampling domain is `{(0,0), (1,0), (1,1)}` and excludes - /// `(0,1)`: `ec-av1-syntax`'s `color_config` only ever READS - /// `subsampling_y` when `subsampling_x == 1` (sequence.rs:481), so - /// `(0,1)` is uncodable. `(1,0)` is 4:2:2. It is walked because that is - /// the codable domain, NOT because a guard stands in the way: as of - /// lane-av1422lift the sequence header no longer refuses 4:2:2 at all, so - /// the sentence this replaces ("refused at the sequence header by - /// `a_non_420_subsampled_sequence_header_is_refused_by_name`") names a - /// gate that no longer exists. The walk was already right; its stated - /// reason was not. - #[test] - fn every_chroma_unit_decode_block_rect_can_present_has_a_coefficient_table() { - let src = crate::test_source::module_source("decode"); - - // (1) The caller shape set, read out of the call sites' own - // argument lists. `decode_block_rect(dec, cdfs, neighbours, at, bw, - // bh, ...)`, so args 4 and 5 (0-based, after the opening paren) are - // `bw` and `bh`; the first three are the fixed `&mut` borrows. - const LEAD: [&str; 3] = ["&mut dec", "&mut cdfs", "&mut neighbours"]; - let mut shapes: BTreeSet<(usize, usize)> = BTreeSet::new(); - let mut sites = 0usize; - let at_def = src - .find("fn decode_block_rect(") - .expect("decode_block_rect is gone"); - for (i, _) in src.match_indices("decode_block_rect(") { - // The definition's own parameter list carries the same text, - // preceded by "fn " -- that is a declaration, not a call. - if src[..i].ends_with("fn ") { - continue; - } - // Split the argument list at top level (paren/bracket/angle - // balanced), so the `(at32.0 + 1, at32.1)` origin argument -- - // which contains its own comma -- does not shift the indices. - let open = i + "decode_block_rect(".len(); - let bytes = src.as_bytes(); - let mut args: Vec = Vec::new(); - let mut depth = 0i32; - let mut start = open; - for j in open..bytes.len() { - match bytes[j] { - b'(' | b'[' => depth += 1, - b')' | b']' => { - if depth == 0 { - args.push(src[start..j].to_string()); - break; - } - depth -= 1; - } - b',' if depth == 0 => { - args.push(src[start..j].to_string()); - start = j + 1; - } - _ => {} - } - } - assert!( - args.len() >= 6, - "a decode_block_rect call has only {} arguments -- the arg indices this \ - enumeration reads are off", - args.len() - ); - for k in 0..3 { - assert_eq!( - args[k].trim(), - LEAD[k], - "decode_block_rect's first three arguments changed -- re-derive the bw/bh \ - argument indices below" - ); - } - let lit = |a: &str| -> usize { - a.trim().parse::().unwrap_or_else(|_| { - panic!( - "decode_block_rect is called with a non-literal strip size {:?} -- \ - this enumeration can no longer read the caller shape set", - a.trim() - ) - }) - }; - shapes.insert((lit(&args[4]), lit(&args[5]))); - sites += 1; - } - assert_eq!( - sites, 8, - "the number of decode_block_rect call sites changed" - ); - let expected_shapes: BTreeSet<(usize, usize)> = - [(32usize, 16usize), (16, 32)].into_iter().collect(); - assert_eq!( - shapes, expected_shapes, - "the set of strip sizes decode_block_rect is called with changed -- re-derive \ - the chroma domain below. An 8x16/16x8 caller makes this refusal LIVE (a \ - 4:2:0 8x16 luma strip's chroma is 4x8, which libaom codes as TX_4X8: \ - av1_ss_size_lookup[BLOCK_8X16][1][1] = BLOCK_4X8 in \ - av1/common/common_data.c:24, then max_txsize_rect_lookup[BLOCK_4X8] = TX_4X8 \ - in av1/common/common_data.h:130, via av1_get_max_uv_txsize, blockd.h:1372)" - ); - - // (2) The table, read out of the function's own text: every - // `(w, h) =>` / `(w, h) |` arm head between the match and the guard. - let body_at = at_def; - let rest = &src[body_at..]; - let body = &rest[..rest.find("\nfn ").expect("unterminated fn")]; - let from = body - .find("let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (chroma_w, chroma_h)") - .expect("decode_block_rect's chroma match is gone"); - let to = body[from..] - .find("a rectangular chroma transform whose size has no coefficient table") - .expect("the refusal string is gone from decode_block_rect") - + from; - let table = &body[from..to]; - let mut arms: BTreeSet<(usize, usize)> = BTreeSet::new(); - let bytes = table.as_bytes(); - for (i, _) in table.match_indices('(') { - let mut j = i + 1; - let mut w = 0usize; - while j < bytes.len() && bytes[j].is_ascii_digit() { - w = w * 10 + usize::from(bytes[j] - b'0'); - j += 1; - } - if j == i + 1 || !table[j..].starts_with(", ") { - continue; - } - j += 2; - let mut h = 0usize; - let start_h = j; - while j < bytes.len() && bytes[j].is_ascii_digit() { - h = h * 10 + usize::from(bytes[j] - b'0'); - j += 1; - } - if j == start_h || !table[j..].starts_with(')') { - continue; - } - // Only an arm HEAD counts, never a `(32, 8)` inside prose. - let after = table[j + 1..].trim_start(); - if after.starts_with("=>") || after.starts_with('|') { - arms.insert((w, h)); - } - } - // (3) The enumeration itself -- run BEFORE the exact-table pin below - // so a deleted arm fails HERE, naming the footprint, instead of - // behind a vaguer "the table changed". - let mut checked = 0u32; - for &(bw, bh) in &shapes { - for (ss_x, ss_y) in [(0usize, 0usize), (1, 0), (1, 1)] { - let (cw, ch) = (bw >> ss_x, bh >> ss_y); - assert!( - arms.contains(&(cw, ch)), - "a {bw}x{bh} strip at subsampling ({ss_x},{ss_y}) has a {cw}x{ch} chroma \ - transform with no coefficient table -- the chroma refusal is LIVE" - ); - checked += 1; - } - } - assert_eq!( - checked, 6, - "the chroma domain is not two shapes x three formats" - ); - - // (4) And the table is EXACTLY those six rows -- no row is a shape no - // caller can present, which is what makes the `_` arm dead. - assert_eq!( - arms, - [ - (8usize, 16usize), - (8, 32), - (16, 8), - (16, 16), - (16, 32), - (32, 16) - ] - .into_iter() - .collect::>(), - "decode_block_rect's chroma table changed -- re-derive the walk above" - ); - - // (5) The residual, stated as an assertion so it cannot rot: the two - // 4:2:0 rows an 8x16/16x8 luma strip would need are NOT in this - // table, and (4,8)/(8,4) is not a shape any caller can produce. If a - // future caller hands this function an 8x16, step (1) goes red - // first, and the new row has to be added here with it. - for residual in [(4usize, 8usize), (8, 4)] { - assert!( - !arms.contains(&residual), - "decode_block_rect grew a {0}x{1} chroma row -- update the residual note", - residual.0, - residual.1 - ); - } - let produces: BTreeSet<(usize, usize)> = shapes - .iter() - .flat_map(|&(bw, bh)| { - [(0usize, 0usize), (1, 0), (1, 1)] - .into_iter() - .map(move |(sx, sy)| (bw >> sx, bh >> sy)) - }) - .collect(); - assert!( - !produces.contains(&(4, 8)) && !produces.contains(&(8, 4)), - "the caller set can now produce a 4x8/8x4 chroma shape but the table has no \ - such row -- the chroma refusal is LIVE" - ); - } - - /// lane-av1txsizeaudit r2 -- the one value in `ec-av1` whose correct form - /// is provable against libaom but whose *observable effect* is nil, so a - /// pixel gate is impossible and this source scan is the only instrument - /// that can catch a regression. - /// - /// `decode.rs`'s `suppress_internal_lf_edges` publishes the skipped 128 - /// root's own chroma extent into `uv_tx_grid`, so the deblocker's - /// alignment gate (`x0 & (tx - 1)`) sees no internal transform edge. The - /// correct extent is the block's own CHROMA footprint, - /// `w_mi * MI >> ss_x` per axis -- `av1_setup_dst_planes`'s - /// `get_plane_block_size(bsize, ss_x, ss_y)`, which at ss (0,0) is the - /// block itself, so **128 and not 64** for a 128x128 root at 4:4:4. The - /// site carried a hardcoded `w_mi * MI / 2`, which is right at 4:2:0 by - /// the `>> 1 == / 2` identity and half the truth everywhere else; its - /// sibling `fill_lf_grid_rect` had already been repaired to - /// `(w_mi * MI) >> ss_x(fctx)`. - /// - /// **No pixel gate can exist for this, and that is measured, not assumed.** - /// The widening defeats the alignment gate, but every edge it lets - /// through then meets the SAME libaom rule applied at the correct place -- - /// `edge_params_body`'s spec-7.14.2 / `set_lpf_parameters` term - /// `!pu_edge && cur_ref != 0 && pv_ref != 0 && skip_at && skip_at`, which - /// holds for every internal edge because both cells are the same skipped - /// block. Over 26 frames / 2 555 904 samples of five 4:4:4 - /// `--sb-size=128` streams that fire the arm 30 times, `64` and `128` both - /// decode pixel-exact against `aomdec` and differ from each other in not - /// one sample. The masking is TOTAL: the method is only ever called for a - /// block that is itself skipped, so no input exists on which one side of - /// an internal edge is not skipped. Hence: source scan, not pixels. - /// - /// This also pins the `fctx` threading, because `Neighbours` carries no - /// subsampling of its own -- a sibling lane reached the same site and - /// recorded it as unfixable for exactly that reason. - #[test] - fn the_skipped_128_root_chroma_suppression_publishes_the_blocks_own_per_axis_chroma_extent() { - let src = crate::test_source::module_source("decode"); - let start = src - .find("fn suppress_internal_lf_edges(") - .expect("suppress_internal_lf_edges is gone"); - let body_start = start + src[start..].find('{').expect("no body"); - let body = - &src[body_start..body_start + src[body_start..].find("\n }").expect("no end")]; - - assert!( - body.contains("((w_mi * MI) >> ss_x(fctx))") - && body.contains("((h_mi * MI) >> ss_y(fctx))"), - "suppress_internal_lf_edges must publish the block's own chroma extent per axis \ - -- `w_mi * MI >> ss_x(fctx)`, not a hardcoded `/2`" - ); - for stale in ["w_mi * MI / 2", "h_mi * MI / 2"] { - assert!( - !body.contains(stale), - "suppress_internal_lf_edges grew `{stale}` again: correct at 4:2:0 by the \ - `>> 1 == / 2` identity, half the truth at 4:4:4" - ); - } - // The subsampling is not reachable from `self` -- `Neighbours` has no - // `fctx` field -- so the per-axis shift needs a threaded parameter. - // Without this the body cannot compile, which is how a future edit - // would try to reintroduce a literal. - let sig_end = src[start..body_start].to_string(); - assert!( - sig_end.contains("fctx: &FrameCtx"), - "suppress_internal_lf_edges takes no fctx, so the per-axis shift has nothing to read \ - -- `Neighbours` carries no subsampling of its own; thread the frame context in" - ); - } - - /// lane-av1-refusalaudit, ENUMERATION for "a 64-axis strip whose chroma - /// unit has no coefficient table" -- [`decode_block_rect64`]'s `_` arm, - /// reached only for depth-0, non-skip, non-lossless superblock-level - /// HORZ/VERT/1:4 strips. - /// - /// The unit is the strip's chroma shape capped at 32 per axis - /// (`(chroma_w.min(32), chroma_h.min(32))`), so the enumeration walks the - /// strip domain -- the 64-axis 2:1 and 1:4 footprints, the only shapes the - /// two callers (`read_sb128_root`, `decode_intra_rect_in_inter`) hand the - /// function -- through every chroma format an AV1 `color_config` can - /// carry, against the `match` arms read out of decode.rs itself (class - /// `table-and-reader-move-together`). - /// - /// lane-av1422census422 widened the format domain from `{(0,0), (1,1)}` - /// to `{(0,0), (1,0), (1,1)}`. The old walk justified stopping at two - /// formats with "every mixed format is refused at the sequence header" -- - /// a proof that DEPENDS on that guard, so the moment the guard is lifted - /// the enumeration keeps passing while covering nothing about 4:2:2, with - /// no failure and no output change. The sibling enumeration - /// `every_chroma_unit_decode_block_rect_can_present_has_a_coefficient_table` - /// (same file, the 32-level strips) already walked `(1,0)` and said why: - /// `ec-av1-syntax`'s `color_config` only ever READS `subsampling_y` when - /// `subsampling_x == 1` (`sequence.rs:481`), so `(0,1)` is uncodable and - /// the reachable set is exactly these three. That sibling was RIGHT and - /// this half was wrong: "the header refuses it" is a statement about - /// today's tree, not about the strip domain, and a domain that shrinks - /// silently when a guard moves is not an enumeration. `(1,0)` is walked - /// here anyway, so this proof does not depend on the guard staying -- and - /// as of lane-av1422lift it does not depend on the guard EXISTING: 4:2:2 - /// decodes, and this enumeration is what says the decode has a - /// coefficient table for every chroma unit it can present. - /// - /// The 32-per-axis cap is what keeps 4:2:2 covered without new table - /// arms: a 4:2:0 32x64 strip is a 16x32 chroma unit and its 4:2:2 - /// counterpart is a 16x64 one, but the cap resolves BOTH to `(16, 32)` - /// (likewise 16x64 -> `(8, 32)`). So 4:2:2 lands entirely inside the - /// existing five arms and the `hit == handled` non-vacuity assert below is - /// unchanged. That is a measured result, not an assumption: this - /// paragraph describes the widened walk in this test's own body, which - /// asserts both the per-unit table membership and the 12-unit count. - /// - /// lane-av1-witness2 hunted the shape with 8 real aomenc key-frame encodes - /// (screen+intrabc, rect+1:4, sb 64 and 128, cq 10..63, cpu-used 0..2): - /// no recipe reached the arm, and the three streams that decode to - /// completion never enter `decode_block_rect64` at all. - #[test] - fn every_chroma_unit_a_64_axis_strip_can_present_has_a_coefficient_table() { - let src = crate::test_source::module_source("decode"); - - // (1) The caller set. Each call's enclosing function is the last - // top-level `fn` before it. - let fn_starts: Vec<(usize, String)> = src - .match_indices("\nfn ") - .map(|(i, _)| { - let rest = &src[i + 4..]; - let name = rest[..rest.find('(').unwrap_or(0)].to_string(); - (i, name) - }) - .collect(); - let mut callers: BTreeSet = BTreeSet::new(); - for (at, _) in src.match_indices("decode_block_rect64(") { - let enclosing = fn_starts - .iter().rfind(|(i, _)| *i < at) - .expect("a decode_block_rect64 call outside any function"); - if enclosing.1 != "decode_block_rect64" { - callers.insert(enclosing.1.clone()); - } - } - let expected: BTreeSet = ["decode_intra_rect_in_inter", "read_sb128_root"] - .iter() - .map(|s| s.to_string()) - .collect(); - assert_eq!( - callers, expected, - "the set of functions that call decode_block_rect64 changed -- re-derive the \ - strip domain below from the new caller (a 128-sided or sub-8 caller makes the \ - refusal live)" - ); - - // (2) The unit derivation, asserted against its own source before it - // is applied: chroma shape = the strip halved by the plane's - // subsampling; unit = each axis capped at 32. - let body_at = src - .find("fn decode_block_rect64(") - .expect("decode_block_rect64 is gone"); - let rest = &src[body_at..]; - let body = &rest[..rest.find("\nfn ").expect("unterminated fn")]; - assert!( - body.contains("(bw >> ss_x(fctx), bh >> ss_y(fctx))"), - "decode_block_rect64's chroma shape is no longer the strip halved by the \ - plane's subsampling -- re-derive this enumeration" - ); - const CAP: &str = "let (uw, uh) = (chroma_w.min(32), chroma_h.min(32));"; - assert_eq!( - src.matches(CAP).count(), - 1, - "the 32-per-axis chroma unit cap is no longer spelled the way this enumeration \ - mirrors it" - ); - - // (3) The table, read out of the match that follows the cap. - let from = body.find(CAP).expect("cap is outside decode_block_rect64"); - let to = body - .find("a 64-axis strip whose chroma unit has no coefficient table") - .expect("the refusal string is gone from decode_block_rect64"); - let table = &body[from..to]; - let mut arms: BTreeSet<(usize, usize)> = BTreeSet::new(); - let bytes = table.as_bytes(); - for (i, _) in table.match_indices('(') { - let mut j = i + 1; - let mut w = 0usize; - while j < bytes.len() && bytes[j].is_ascii_digit() { - w = w * 10 + usize::from(bytes[j] - b'0'); - j += 1; - } - if j == i + 1 || !table[j..].starts_with(", ") { - continue; - } - j += 2; - let mut h = 0usize; - let start_h = j; - while j < bytes.len() && bytes[j].is_ascii_digit() { - h = h * 10 + usize::from(bytes[j] - b'0'); - j += 1; - } - if j == start_h || !table[j..].starts_with(") =>") { - continue; - } - // Only an arm HEAD counts, never a `(32, 8)` inside prose. - arms.insert((w, h)); - } - let handled: BTreeSet<(usize, usize)> = [(32, 32), (32, 16), (16, 32), (32, 8), (8, 32)] - .into_iter() - .collect(); - assert_eq!( - arms, handled, - "decode_block_rect64's chroma-unit table changed -- re-derive the enumeration \ - (a unit outside these five arms makes the refusal live for some strip)" - ); - - // (4) The enumeration: every 64-axis 2:1 and 1:4 strip (the shapes - // superblock partitioning presents at the 64 level) x every supported - // chroma format lands on a handled arm. - let mut checked = 0u32; - let mut hit: BTreeSet<(usize, usize)> = BTreeSet::new(); - for wl in 4..=6u32 { - for hl in 4..=6u32 { - let (bw, bh) = (1usize << wl, 1usize << hl); - if bw.max(bh) != 64 { - continue; - } - let ratio = bw.max(bh) / bw.min(bh); - if ratio != 2 && ratio != 4 { - continue; - } - // (ss_x, ss_y): (0, 0) is 4:4:4, (1, 0) is 4:2:2, (1, 1) is - // 4:2:0. `(0, 1)` is uncodable -- `color_config` reads - // `subsampling_y` only when `subsampling_x == 1` - // (sequence.rs:481) -- so these three are the whole - // reachable set, and each is walked independently of any - // sequence-header guard (lifted by lane-av1422lift). - for (ss_x, ss_y) in [(0usize, 0usize), (1, 0), (1, 1)] { - let (chroma_w, chroma_h) = (bw >> ss_x, bh >> ss_y); - let unit = (chroma_w.min(32), chroma_h.min(32)); - assert!( - arms.contains(&unit), - "a {bw}x{bh} strip at subsampling ({ss_x},{ss_y}) resolves to the \ - chroma unit {unit:?}, which has no coefficient table -- the \ - refusal is LIVE for a conformant stream" - ); - hit.insert(unit); - checked += 1; - } - } - } - assert_eq!( - checked, 12, - "the strip domain is not the four 64-axis strips x three codable \ - chroma formats (4:4:4, 4:2:2, 4:2:0)" - ); - assert_eq!( - hit, handled, - "the enumeration stopped exercising every arm -- the proof went vacuous" - ); - } - - /// lane-t900 r33, ENUMERATION for "CfL, filter intra or a palette on a - /// 128-root HORZ/VERT intra block". - /// - /// The guard fires when any of four symbols came back `Some` from - /// `read_intra_mode_rect` on a 128x64/64x128 half. Each of the four is - /// read under a size gate, and none of those gates admits a 128-pixel - /// side: - /// - /// * `cfl_alpha` -- read only under the `cfl` PARAMETER, and the 128-root - /// call site passes the literal `false`; - /// * `use_filter_intra` -- read only when `filter_intra_size_class_rect` - /// is `Some`, whose table has no arm with a 128 side and whose square - /// fallback (`filter_intra_size_class`) caps at 32 - /// (`av1_filter_intra_allowed_bsize`); - /// * `palette_y_mode` / `palette_uv_mode` -- both inside the - /// `palette_bsize_ctx_wh` block already enumerated by - /// [`no_block_footprint_with_a_128_pixel_side_can_carry_palette_syntax`]. - #[test] - fn no_128_root_half_reads_a_cfl_filter_intra_or_palette_symbol() { - // lane-av1refusalspan: this gate is the PROOF for the refusal below, so - // it names it (the full leading clause, which is the whole clause the - // inventory row's anchor reads) and pins its guard site. - const REFUSAL: &str = "CfL, filter intra or a palette on a 128-root HORZ/VERT intra block"; - assert!( - crate::test_source::module_source("decode").contains(REFUSAL), - "this gate proves {REFUSAL:?}, but that string is no longer in decode.rs" - ); - let src = crate::test_source::module_source("decode"); - // The 128-root call site's own `cfl` argument, with the comment that - // explains it -- the two lines are matched together so that reordering - // the arguments cannot leave this test pointing at another `false`. - // - // Whitespace-normalised (2026-09-28): the anchor used to be matched with - // its exact indentation, so any dedent or reformat of the call site -- - // the wave merge dedented it by four spaces -- turned this enumeration - // red without the invariant it guards changing at all. Collapsing runs - // of whitespace keeps the SEMANTIC anchor (both comment lines plus the - // `false,` argument, in order) asserted while removing that fragility. - const CFL_OFF_AT_128: &str = "// `is_cfl_allowed` caps CFL at 32x32: `uv_mode` comes off the \ - // 13-symbol no-CFL CDF here, never the 14-symbol one. false,"; - fn squash_ws(s: &str) -> String { - s.split_whitespace().collect::>().join(" ") - } - assert_eq!( - squash_ws(src).matches(&squash_ws(CFL_OFF_AT_128)).count(), - 1, - "the 128-root call site no longer passes cfl=false -- a CfL alpha can reach the \ - guard, so this enumeration proves nothing" - ); - // The filter-intra table: every arm head, plus the square fallback. - let fi_at = src - .find("fn filter_intra_size_class_rect(bw: usize, bh: usize) -> Option {") - .expect("filter_intra_size_class_rect is gone"); - let fi_body = &src[fi_at..fi_at + src[fi_at..].find("\n}\n").expect("unterminated fn")]; - assert!( - !fi_body.contains("128"), - "filter_intra_size_class_rect grew an arm naming a 128 side" - ); - assert!( - fi_body.contains("_ if bw == bh => filter_intra_size_class(bw),") - && fi_body.contains("_ => None,"), - "filter_intra_size_class_rect's fallbacks changed shape" - ); - let sq_at = src - .find("fn filter_intra_size_class(side: usize) -> Option {") - .expect("filter_intra_size_class is gone"); - let sq_body = &src[sq_at..sq_at + src[sq_at..].find("\n}\n").expect("unterminated fn")]; - assert!( - !sq_body.contains("128") && !sq_body.contains("64"), - "filter_intra_size_class admits a side above 32 -- av1_filter_intra_allowed_bsize \ - does not, so re-derive this proof" - ); - // And palette, at the two shapes the refusal names. - assert!( - src.contains("if bw > 64 || bh > 64 || bw * bh < 64 {"), - "palette_bsize_ctx_wh's bound moved -- see \ - no_block_footprint_with_a_128_pixel_side_can_carry_palette_syntax" - ); - for (bw, bh) in [(128usize, 64usize), (64, 128)] { - assert!(bw > 64 || bh > 64, "{bw}x{bh} is not a 128-root half"); - } - } - - /// lane-hdrlossless, ENUMERATION behind the LONE capability claim - /// ("filter intra on a superblock-level HORZ/VERT strip"). The guard in - /// `decode_block_rect` fires only when `filter_intra.is_some()`, and that - /// flag is `Some` only where `filter_intra_size_class_rect` says so. The - /// strips the guard protects are `(64, 32)` / `(32, 64)`; this test - /// enumerates every EXPLICIT arm of that table (asserting none admits a - /// `64` axis) AND drives the square-delegate guard arm's callee - /// `filter_intra_size_class` directly at 32/64, so a widening on either - /// side turns it red. No conformant stream (libaom - /// `av1_filter_intra_allowed_bsize` caps both sides at 32) can offer the - /// symbol there. - #[test] - fn a_sb_level_horz_vert_strip_admits_no_filter_intra_symbol() { - let src = crate::test_source::module_source("decode"); - assert!( - src.contains("\"filter intra on a superblock-level HORZ/VERT strip"), - "the guard this proof is about is gone -- re-derive the capability claim" - ); - let at = src - .find("fn filter_intra_size_class_rect(bw: usize, bh: usize) -> Option {") - .expect("filter_intra_size_class_rect is gone"); - let body = &src[at..at + src[at..].find("\n}\n").expect("unterminated fn")]; - let (mut arms, mut saw_none_fallback, mut saw_square_delegate) = (0usize, false, false); - let mut seen: Vec<(usize, usize)> = Vec::new(); - for line in body.lines() { - let line = line.trim(); - if line.starts_with('_') { - if line == "_ => None," { - saw_none_fallback = true; - } else if line.starts_with("_ if ") { - // The square-delegate guard arm hands a square strip to - // `filter_intra_size_class`; the numeric walk below cannot - // see it (it carries no `(bw, bh)` pair), so its callee is - // audited by the direct call after the loop instead. - assert!( - line == "_ if bw == bh => filter_intra_size_class(bw),", - "filter_intra_size_class_rect's guard arm changed shape: {line}" - ); - saw_square_delegate = true; - } - continue; - } - let Some(rest) = line.strip_prefix('(') else { - continue; - }; - let Some((pair, _)) = rest.split_once(") =>") else { - continue; - }; - let Some((a, b)) = pair.split_once(',') else { - continue; - }; - let bw: usize = a.trim().parse().expect("arm bw"); - let bh: usize = b.trim().parse().expect("arm bh"); - assert!( - bw <= 32 && bh <= 32, - "filter_intra_size_class_rect grew an arm with a side above 32 ({bw}x{bh}); \ - `av1_filter_intra_allowed_bsize` forbids the symbol there, but if the table \ - now admits it the SB-strip guard is reachable" - ); - seen.push((bw, bh)); - arms += 1; - } - assert!( - arms >= 10, - "only {arms} arms parsed -- the table's shape changed" - ); - assert!( - saw_none_fallback, - "filter_intra_size_class_rect lost its `_ => None` fallback" - ); - assert!( - saw_square_delegate, - "filter_intra_size_class_rect lost its square-delegate arm" - ); - // The guard arm delegates square strips to `filter_intra_size_class`; - // drive the delegate directly, so a widening there turns THIS test red - // (the numeric walk never reaches the guard arm). - assert!( - crate::decode::filter_intra_size_class(32).is_some() - && crate::decode::filter_intra_size_class(64).is_none(), - "filter_intra_size_class now admits a 64-pixel side -- the square-delegate arm of \ - filter_intra_size_class_rect can then offer a `use_filter_intra` symbol on a \ - superblock-level HORZ/VERT strip and its guard is reachable" - ); - for strip in [(64usize, 32usize), (32, 64)] { - assert!( - !seen.contains(&strip), - "{strip:?} has its own filter-intra arm now -- the SB-strip guard is reachable" - ); - } - } - - /// lane-t900 r33, STRUCTURAL AUDIT behind the DELETION of "a block that - /// actually uses a palette (Y) -- reconstruction is out of scope". - /// - /// That refusal was the `palette.is_none()` arm of `read_intra_mode` and - /// `read_intra_mode_rect`: a stream reached it only if a CALLER read the - /// palette syntax without handing the reader a neighbour ctx/cache pair. - /// Every one of the eight call sites passes `Some((palette_ctx, - /// &palette_cache))`, so no stream could reach either arm and both are - /// gone from `decode.rs`. This test keeps the invariant the deletion rests - /// on: a future caller that passes `None` fails here rather than decoding - /// a palette off an empty colour cache. - #[test] - fn every_read_intra_mode_call_site_hands_the_reader_a_palette_cache() { - let src = crate::test_source::module_source("decode"); - let mut sites = 0u32; - for name in ["read_intra_mode(", "read_intra_mode_rect("] { - for (at, _) in src.match_indices(name) { - // The definition itself, not a call. - if src[..at].ends_with("fn ") { - continue; - } - sites += 1; - let window = &src[at..(at + 4096).min(src.len())]; - let end = window.find("fctx,\n").unwrap_or(window.len()); - assert!( - window[..end].contains("Some((palette_ctx, &palette_cache)),"), - "a {name} call site does not hand the reader a palette ctx/cache pair -- \ - the deleted `palette.is_none()` refusal was its guard" - ); - } - } - assert_eq!( - sites, 8, - "the call-site audit found {sites} sites, not the 8 it enumerated" - ); - } - - /// Lane-av1refusalspan: the files a proving gate may live in. - fn gate_sources() -> [(&'static str, &'static str); 3] { - [ - ("decode.rs", crate::test_source::module_source("decode")), - ("stream.rs", crate::test_source::module_source("stream")), - ("refusal_inventory.rs", include_str!("refusal_inventory.rs")), - ] - } - - /// Lane-av1refusalspan: every offset in `src` of a line that DEFINES - /// `fn (` -- and nothing that merely names it. - /// - /// "The gate" is a function, so the first thing the anchor needs is the - /// function's own definition. The window rule this replaced took the first - /// `fn (` the file happened to contain, and a comment or a string - /// produces one. A definition is a line whose text before the keyword is - /// whitespace and qualifiers only (`pub`, `pub(crate)`, `async`, ...). - fn gate_definitions(src: &str, gate: &str) -> Vec { - src.match_indices(&format!("fn {gate}(")) - .map(|(at, _)| at) - .filter(|at| { - let line_start = src[..*at].rfind('\n').map_or(0, |i| i + 1); - // Qualifiers are bare words (`pub`, `pub(crate)`, `async`, ...). - // Anything else on the line before the keyword (a `=`, a quote, - // a `//`, a `#[...]`) means the match is not a definition. - src[line_start..*at].split_whitespace().all(|word| { - let bare = word.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'); - let visibility = word.starts_with("pub(") && word.ends_with(')'); - bare || visibility - }) - }) - .collect() - } - - /// The number of leading-whitespace columns on the line holding `at`. - fn leading_indent(src: &str, at: usize) -> usize { - let line_start = src[..at].rfind('\n').map_or(0, |i| i + 1); - let line = &src[line_start..at]; - line.len() - line.trim_start().len() - } - - /// The offset of the `"` that closes the string literal opening at `open`. - fn closing_quote(b: &[u8], open: usize) -> Option { - let mut i = open + 1; - while i < b.len() { - match b[i] { - b'\\' => i += 2, - b'"' => return Some(i), - _ => i += 1, - } - } - None - } - - /// The offsets of the `{` that opens the body of the function defined at - /// `gate_at` and of the `}` that closes it; `None` when the body is never - /// closed. - /// - /// This walks Rust, not lines. A brace inside a string literal, a raw - /// string, a byte string, a char literal, a lifetime, a line comment or a - /// (nestable) block comment is not a brace -- counting one is exactly how a - /// "bounded" window becomes the rest of the file. - fn body_braces(src: &str, gate_at: usize) -> Option<(usize, usize)> { - let b = src.as_bytes(); - let mut i = gate_at; - let mut depth = 0usize; - let mut open = None; - let mut last: Option = None; - while i < b.len() { - // Every arm advances `i`, including the ones that `continue`. A spin - // here would hang the suite instead of failing it, which is the one - // outcome a boundary finder must never have. - if let Some(last) = last { - debug_assert!(i > last, "body_braces: an arm must advance the cursor"); - } - last = Some(i); - match b[i] { - b'/' if b.get(i + 1) == Some(&b'/') => { - i = src[i..].find('\n').map_or(b.len(), |n| i + n + 1); - continue; - } - b'/' if b.get(i + 1) == Some(&b'*') => { - let mut nesting = 1usize; - i += 2; - while i < b.len() && nesting > 0 { - if b[i] == b'/' && b.get(i + 1) == Some(&b'*') { - nesting += 1; - i += 2; - } else if b[i] == b'*' && b.get(i + 1) == Some(&b'/') { - nesting -= 1; - i += 2; - } else { - i += 1; - } - } - continue; - } - b'r' if b.get(i + 1) == Some(&b'"') || b.get(i + 1) == Some(&b'#') => { - let mut j = i + 1; - while b.get(j) == Some(&b'#') { - j += 1; - } - if b.get(j) != Some(&b'"') { - i += 1; - continue; - } - let hashes = j - i - 1; - let mut end = None; - for k in (j + 1..b.len()).chain(std::iter::once(b.len() - 1)) { - if b[k] == b'"' && b[k + 1..].iter().take(hashes).all(|c| *c == b'#') { - end = Some(k); - break; - } - } - i = end? + 1; - continue; - } - b'"' => { - i = closing_quote(b, i)? + 1; - continue; - } - b'b' if b.get(i + 1) == Some(&b'"') => { - i = closing_quote(b, i + 1)? + 1; - continue; - } - // A lifetime (`'a`, `'static`) is not a char literal: it has no - // closing quote on its line, and reading one as a literal would - // hide real code from the scan. - b'\'' => { - let rest = &b[i + 1..]; - let from = if rest.first() == Some(&b'\\') { 2 } else { 0 }; - match rest[from..] - .iter() - .take_while(|c| **c != b'\n') - .position(|c| *c == b'\'') - { - Some(k) => i += from + k + 2, - None => i += 1, - } - continue; - } - b'{' => { - open = open.or(Some(i)); - depth += 1; - } - b'}' - // A closer seen BEFORE the body opened is not ours (it can - // only come from a signature or a type ascription the scan - // mis-read); ignore it rather than underflowing `depth`. - if depth > 0 => { - depth -= 1; - if depth == 0 { - return open.map(|o| (o, i)); - } - } - _ => {} - } - i += 1; - } - None - } - - /// The text of the body of the function defined at `gate_at`, or `None` - /// when that body is never closed. - fn function_body(src: &str, gate_at: usize) -> Option<&str> { - let (open, close) = body_braces(src, gate_at)?; - src.get(open..=close) - } - - /// The first line of `body` that defines another function at `indent` - /// columns of leading whitespace -- the first sign that a boundary - /// over-reached into a neighbour. - fn sibling_fn(body: &str, indent: usize) -> Option<&str> { - body.lines().skip(1).find(|line| { - let lead = line.len() - line.trim_start().len(); - lead == indent && { - let t = line.trim_start(); - t.starts_with("fn ") || t.starts_with("pub fn ") - } - }) - } - - /// Lane-av1refusalspan: the proving gate's OWN body -- the text from the - /// `{` that opens it to the `}` that closes it. - /// - /// Every failure mode here is a FAILURE (`Err`), never a wider window. The - /// rule this replaced -- "the body ends at the next `fn` at the same - /// indentation, or at end of file" -- ended at end of file constantly (a - /// top-level `#[test] fn` in `decode.rs` has its next same-indent `fn` - /// tens of thousands of lines away), and one row's 27,427-line "body" was - /// satisfied by the CHROMA sibling's string seven lines down. - fn gate_body(gate: &str) -> Result<&'static str, String> { - let mut hits: Vec<(&str, usize, &'static str)> = Vec::new(); - for (file, src) in gate_sources() { - for at in gate_definitions(src, gate) { - hits.push((file, at, src)); - } - } - match hits.as_slice() { - [] => Err(format!( - "{gate} is not defined in decode.rs, stream.rs or refusal_inventory.rs" - )), - [only] => { - let (file, at, src) = *only; - let body = function_body(src, at).ok_or_else(|| { - format!( - "{file}:{at}: the body of {gate}() is never closed -- a missing \ - boundary is a FAILURE, not a window that runs on into the next \ - function" - ) - })?; - if let Some(leak) = sibling_fn(body, leading_indent(src, at)) { - return Err(format!( - "{file}:{at}: the extracted body of {gate}() still contains {} -- the \ - boundary over-reached into a neighbour", - leak.trim() - )); - } - Ok(body) - } - many => Err(format!( - "{gate} is defined {} times ({}), so 'its body' is ambiguous", - many.len(), - many.iter() - .map(|(file, at, _)| format!("{file}:{at}")) - .collect::>() - .join(", ") - )), - } - } - - /// The refusal's leading clause: what a gate may quote when it does not - /// quote the whole string -- everything up to the first `(` (the qualifier - /// that varies per call site), else up to the first `:`, else the whole - /// string. - fn leading_clause(reason: &str) -> String { - let cut = reason - .find('(') - .or_else(|| reason.find(':')) - .unwrap_or(reason.len()); - reason[..cut].trim_end().to_owned() - } - - /// Every entry of [`PROVEN`] must still name a live refusal, and the gate - /// it names must REFERENCE that refusal inside its OWN body. - /// - /// Lane-av1refusalspan: the boundary is the gate's closing brace (see - /// [`gate_body`]); a boundary that cannot be found fails the row. - #[test] - fn every_proven_refusal_names_a_test_that_exists() { - let found = decode_path_refusals(); - let mut whole = 0usize; - let mut clause = 0usize; - let mut neither: Vec<&str> = Vec::new(); - let mut unanchored: Vec = Vec::new(); - let mut unbounded: Vec = Vec::new(); - for (reason, gate, _kind) in PROVEN { - assert!( - found.contains(*reason), - "{reason:?} is listed as proven but is no longer a decode-path refusal -- \ - drop it from PROVEN (the capability landed) or fix the string" - ); - // A missing boundary is a FAILURE for the row, never a wider window. - let body = match gate_body(gate) { - Ok(body) => body, - Err(why) => { - unbounded.push(format!("{reason:?} names {gate}: {why}")); - continue; - } - }; - let flat = squash_source(body); - if flat.contains(&squash_source(reason)) { - whole += 1; - } else if flat.contains(&squash_source(&leading_clause(reason))) { - clause += 1; - } else { - neither.push(reason); - unanchored.push(format!("{reason:?} names {gate}")); - } - } - // The anchor-strength line, measured over BODIES. The window rule this - // replaced made these numbers a distribution over "whatever the window - // happened to reach", which is a different question. - eprintln!( - "anchor strength: {whole} rows quote the WHOLE refusal string, {clause} quote its \ - LEADING CLAUSE, {} match neither: {neither:?}", - PROVEN.len() - whole - clause - ); - eprintln!( - "refusal inventory: {} refusals + {} capability claims, {} proven", - REFUSALS.len(), - CAPABILITY_CLAIMS.len(), - PROVEN.len() - ); - assert!( - unbounded.is_empty(), - "these rows name a gate whose body could not be bounded, so nothing was proved \ - about them -- a missing boundary is a failure, not a window that runs on:\n\ - {unbounded:#?}\n\ - The boundary is the gate's own closing brace. If the gate really is there, the \ - finder is wrong: fix the finder, never the verdict." - ); - assert!( - unanchored.is_empty(), - "these rows name a gate that never references the refusal inside its OWN body -- a \ - test that does not use the string it is said to prove is not a proof:\n\ - {unanchored:#?}\n\ - Name a gate that quotes the refusal (or its leading clause), or write one." - ); - } - - /// The OTHER half of the inventory's invariant: every string LISTED in - /// [`REFUSALS`] or [`CAPABILITY_CLAIMS`] has a row in [`PROVEN`]. - /// - /// `every_proven_refusal_names_a_test_that_exists` checks the direction - /// row -> live refusal, so a string added to the inventory with no proving - /// gate was invisible: the file could list 33 strings, carry 31 rows, and - /// every test in the module stayed green. Two rows were missing on main - /// (the BLOCK_INVALID subsize refusal and the lone filter-intra capability - /// claim) precisely because nothing compared the two sets. This is that - /// comparison, so the next one cannot land unmeasured. - #[test] - fn every_listed_refusal_and_capability_claim_has_a_proven_row() { - let mut listed = 0usize; - let mut unmeasured: Vec<&str> = Vec::new(); - for reason in REFUSALS.iter().chain(CAPABILITY_CLAIMS.iter()) { - listed += 1; - if !PROVEN.iter().any(|(row, _, _)| *row == *reason) { - unmeasured.push(reason); - } - } - assert!( - unmeasured.is_empty(), - "these strings are listed as refusals / capability claims but no PROVEN row names a \ - gate that proves them -- an unmeasured claim is what this table exists to make \ - visible:\n{unmeasured:#?}" - ); - assert_eq!( - listed, - PROVEN.len(), - "{listed} strings are listed and {} rows exist -- they must be one to one, so a row \ - can never stand in for a string that is not listed", - PROVEN.len() - ); - eprintln!( - "refusal inventory: {listed} listed strings, {} PROVEN rows, one to one", - PROVEN.len() - ); - } - - /// Lane-av1refusalspan, non-vacuity of the BOUNDARY (not of the anchor): - /// a neighbour's function must be unreachable from a gate's body, and a - /// body that is not closed must fail rather than run on. - #[test] - fn a_gate_body_is_bounded_by_its_own_closing_brace() { - let marker = "a rectangular chroma transform whose size has no coefficient table"; - let src = format!( - "fn this_gate() {{\n let _ = 1;\n}}\n\nfn next_gate() {{\n let _ = \"{marker}\";\n}}\n\nfn tail() {{}}\n" - ); - let this = gate_body_in(&src, "this_gate").expect("the gate has a boundary"); - assert!(this.contains("let _ = 1;"), "own text: {this:?}"); - assert!( - !this.contains(marker), - "leaked into the neighbour: {this:?}" - ); - let next = gate_body_in(&src, "next_gate").expect("the neighbour has a boundary"); - assert!(next.contains(marker)); - assert!(!next.contains("let _ = 1;")); - // The last function in a file has no following `fn` to stop at: the - // boundary must still close, exactly on its own brace. - assert_eq!(gate_body_in(&src, "tail").as_deref(), Ok("{}")); - // A brace inside a string or a char literal is not a brace. If the scan - // counted one, this body would run past its own `}` into `next_gate` - // -- the over-reach the `sibling_fn` invariant exists to catch, and the - // failure mode that made the old window 27,427 lines long. - let with_braces_in_literals = format!( - "fn this_gate() {{\n let _ = \"{{\";\n let _ = '}}';\n // {{\n /* }} */\n}}\n\nfn next_gate() {{\n let _ = \"{marker}\";\n}}\n" - ); - let bounded = gate_body_in(&with_braces_in_literals, "this_gate"); - assert!( - bounded.as_deref().is_ok_and(|b| !b.contains(marker)), - "a brace in a literal moved the boundary: {bounded:?}" - ); - // A body whose closing brace is missing (a half-finished edit) is a - // FAILURE. The rule it replaced sliced to end of file and carried on. - let truncated = - "fn this_gate() {\n let _ = 1;\n\nfn next_gate() {\n let _ = 2;\n}\n".to_string(); - assert!(gate_body_in(&truncated, "this_gate").is_err()); - } - - /// Lane-av1refusalspan: the boundary is load-bearing on the REAL sources, - /// not only on the synthetic pair above -- every named gate resolves to - /// exactly one function whose body holds no other function, and the last - /// function in each of the three files terminates correctly. - #[test] - fn every_named_gate_body_is_bounded_in_these_files() { - let mut resolved = 0usize; - for (reason, gate, _kind) in PROVEN { - let body = - gate_body(gate).unwrap_or_else(|why| panic!("{reason:?} names {gate}: {why}")); - assert!( - body.ends_with('}'), - "{gate}'s body does not end on its closing brace" - ); - resolved += 1; - } - assert_eq!(resolved, PROVEN.len()); - for (file, src) in gate_sources() { - let last = last_fn_name(src).unwrap_or_else(|| panic!("{file} has no function")); - let at = gate_definitions(src, &last) - .last() - .copied() - .unwrap_or_else(|| panic!("{file}: no definition of {last}")); - let body = function_body(src, at) - .unwrap_or_else(|| panic!("{file}: the last function {last}() has no boundary")); - assert!(sibling_fn(body, leading_indent(src, at)).is_none()); - } - } - - /// The taxonomy is a CLAIM about each row, so it carries its own - /// non-vacuity: every variant is used by at least one row (a variant no - /// row can be in is not a category), the two labels do not collapse into - /// one string, and the row lane-av1refusalclaim r3 wanted to RE-TAG is - /// tagged from evidence inside its own gate BODY -- never from the - /// gate's name, which is the only thing the previous 2-tuple carried. - /// - /// r3 minted a `TablePin` variant because "a rectangular chroma transform - /// whose size has no coefficient table" was pinned to a table whose - /// REACHED-OVER domain had never been measured. Main has since replaced - /// that row's gate with one that reads the eight `decode_block_rect` call - /// sites' own literal `bw`/`bh`, pins the resulting chroma table exactly, - /// and asserts the `(4,8)`/`(8,4)` residual is UNPRODUCIBLE. `Enumeration` - /// is therefore the honest tag and `TablePin` is not carried; if a later - /// edit weakens that gate back to a bare table pin, the three evidence - /// pins below go red instead of leaving the row quietly overclaiming. - #[test] - fn every_proven_row_names_which_kind_of_proof_it_carries() { - let mut negative = 0usize; - let mut enumeration = 0usize; - for (reason, gate, kind) in PROVEN { - eprintln!(" {} -- {reason:?} -> {gate}", kind.label()); - match kind { - Proof::NegativeGate => negative += 1, - Proof::Enumeration => enumeration += 1, - } - } - assert_eq!( - negative + enumeration, - PROVEN.len(), - "a PROVEN row carries no proof kind, so the table says nothing about it" - ); - assert!( - negative > 0, - "no row is tagged NEGATIVE, so the NegativeGate variant is dead weight" - ); - assert!( - enumeration > 0, - "no row is tagged ENUMERATION, so the Enumeration variant is dead weight" - ); - assert_ne!( - Proof::NegativeGate.label(), - Proof::Enumeration.label(), - "the two kinds print the same string, so the taxonomy is one category in two hats" - ); - - let (reason, gate, kind) = PROVEN - .iter() - .find(|(reason, _, _)| { - *reason == "a rectangular chroma transform whose size has no coefficient table" - }) - .map(|(reason, gate, kind)| (*reason, *gate, kind)) - .expect("the (4,8) chroma-table row left PROVEN"); - assert!( - matches!(kind, Proof::Enumeration), - "{reason:?} is tagged {:?}, but its gate enumerates the caller domain", - kind.label() - ); - let body = gate_body(gate).unwrap_or_else(|why| panic!("{reason:?} names {gate}: {why}")); - for evidence in [ - "the number of decode_block_rect call sites changed", - "for residual in [(4usize, 8usize), (8, 4)]", - "the caller set can now produce a 4x8/8x4 chroma shape", - ] { - assert!( - body.contains(evidence), - "{gate} no longer carries {evidence:?}, so the Enumeration tag on {reason:?} \ - claims a reach domain the gate has stopped measuring" - ); - } - eprintln!( - "refusal inventory: {negative} NEGATIVE, {enumeration} ENUMERATION of {} PROVEN rows", - PROVEN.len() - ); - } - - /// Lane-av1refusalspan: the invariant that catches a boundary that - /// over-reaches. Tested on its own text, so it cannot be satisfied by the - /// scanner happening to be right on the current sources. - #[test] - fn a_body_carrying_another_function_is_refused() { - assert!(sibling_fn("{\n let _ = 1;\n}\n\nfn neighbour() {\n}\n", 0).is_some()); - assert!(sibling_fn("{\n let _ = 1;\n}\n", 0).is_none()); - // A nested `fn` is deeper-indented and does belong to the body. - assert!(sibling_fn("{\n fn helper() {}\n}\n", 0).is_none()); - } - - /// Lane-av1refusalspan: `gate_body` over ONE file, so the boundary tests - /// above can drive it with text that cannot occur in this crate. - fn gate_body_in<'a>(src: &'a str, gate: &str) -> Result<&'a str, String> { - let defs = gate_definitions(src, gate); - match defs.as_slice() { - [] => Err(format!("{gate} is not defined here")), - [at] => { - let body = function_body(src, *at).ok_or_else(|| { - format!("the body of {gate}() is never closed -- boundary missing") - })?; - if let Some(leak) = sibling_fn(body, leading_indent(src, *at)) { - return Err(format!("boundary over-reached into {}", leak.trim())); - } - Ok(body) - } - many => Err(format!("{gate} is defined {} times", many.len())), - } - } - - /// The name of the last function defined in `src` -- the boundary rule's - /// hard case, since nothing follows it to stop at. - fn last_fn_name(src: &str) -> Option { - src.lines() - .filter_map(|line| { - let t = line.trim_start(); - if !(t.starts_with("fn ") || t.starts_with("pub fn ")) { - return None; - } - Some(t.trim_start_matches("pub fn ").trim_start_matches("fn ")) - }) - .filter_map(|head| head.split_once('(').map(|(head, _)| head.trim().to_owned())) - .next_back() - } -} diff --git a/crates/ec-av1/src/stack_budget.rs b/crates/ec-av1/src/stack_budget.rs index 92cf5003..481cd6d3 100644 --- a/crates/ec-av1/src/stack_budget.rs +++ b/crates/ec-av1/src/stack_budget.rs @@ -456,7 +456,6 @@ mod tests { ("film_grain.rs", include_str!("film_grain.rs")), ("filter_search.rs", include_str!("filter_search.rs")), ("frame.rs", include_str!("frame.rs")), - ("gate_coverage.rs", include_str!("gate_coverage.rs")), ("hits.rs", include_str!("hits.rs")), ("intra.rs", include_str!("intra.rs")), ("library_fixture.rs", include_str!("library_fixture.rs")), @@ -471,7 +470,6 @@ mod tests { ("probe.rs", include_str!("probe.rs")), ("qm.rs", crate::test_source::module_source("qm")), ("quant.rs", include_str!("quant.rs")), - ("refusal_inventory.rs", include_str!("refusal_inventory.rs")), ("restoration.rs", include_str!("restoration.rs")), ("sequence.rs", include_str!("sequence.rs")), ("speed.rs", include_str!("speed.rs")), diff --git a/crates/ec-av1/src/stream/mod.rs b/crates/ec-av1/src/stream/mod.rs index 9e08bf97..e8e565fe 100644 --- a/crates/ec-av1/src/stream/mod.rs +++ b/crates/ec-av1/src/stream/mod.rs @@ -22,14 +22,10 @@ use ec_av1_syntax::{ // Census-only: read outside `mod tests` only in comments; the non-test lib // target never touches them, so they ride in behind cfg(test) (via the test // module's `use super::*`). -#[cfg(test)] -use ec_av1_syntax::{SEG_LVL_ALT_Q, SEG_LVL_MAX}; use ec_core::{Error, Result}; use crate::cdf_state::Cdfs; use crate::decode; -#[cfg(test)] -use crate::decode::decode_key_frame_tile_lr; use crate::decode::{decode_inter_frame_tile_with_cdfs, decode_key_frame_tile_with_cdfs, q_ctx_of}; use crate::encode::Picture; diff --git a/crates/ec-av1/src/stream/tests/gates_a.rs b/crates/ec-av1/src/stream/tests/gates_a.rs deleted file mode 100644 index 3287fb13..00000000 --- a/crates/ec-av1/src/stream/tests/gates_a.rs +++ /dev/null @@ -1,2841 +0,0 @@ -use super::*; -use super::support::*; - - /// Three-bucket gate summary (class [[gate-skips-on-its-own-failure]]): - /// every attempt lands in exactly one bucket -- decoded pixel-exact WITH - /// the feature counter moving, decoded pixel-exact WITHOUT it, or a named - /// refusal -- and the three sum to the attempts made. - pub(super) fn gate_buckets(name: &str, counted_exact: u32, uncounted_exact: u32, named_refusals: usize) { - eprintln!( - "{name}: buckets counted-exact={counted_exact} uncounted-exact={uncounted_exact} \ - named-refusals={named_refusals} (attempts {})", - counted_exact as usize + uncounted_exact as usize + named_refusals - ); - } - - pub(crate) fn lock_gate_counters() -> std::sync::MutexGuard<'static, ()> { - GATE_COUNTER_LOCK.lock().unwrap_or_else(|e| e.into_inner()) - } - - /// The body every 4:4:4 lossy live gate runs: assert the oracle compare - /// CANNOT be skipped, assert the decode really is the cell it claims - /// (frame count, geometry, full-resolution chroma), assert the 4:4:4-only - /// own-extent route really ran, then compare every frame in decode order - /// against the oracle aomdec with the length asserted first. - /// - /// The aomdec arm is a HARD failure, not a skip: these three gates encode - /// LIVE, so reaching this point means the oracle aomenc resolved, and - /// aomenc and aomdec ship in the same build directory -- an aomdec that is - /// missing beside a present aomenc is a broken oracle, not a checkout - /// without one. (The older shape, `if aomdec_path().is_file()`, let the - /// compare vanish with no env escape at all; that is what - /// [`aomdec_available`] replaced for the pinned gates, and it cannot be - /// used here because these gates have no stream to compare without one.) - pub(super) fn gate_444_lossy_live_exact(name: &str, w: usize, h: usize) { - // The ONLY way out without measuring, and it has already printed a - // SKIP naming the env var that would turn it into a failure. - let Some(stream) = encode_444_lossy_live(name, w, h) else { - return; - }; - assert!( - aomdec_path().is_file(), - "{name}: the oracle aomenc resolved to {} but no aomdec sits beside it at {} -- \ - the pixel compare would silently skip, which this gate treats as a failure", - aomenc_path().display(), - aomdec_path().display() - ); - - let _guard = lock_gate_counters(); - crate::decode::reset_rect4_inter_own_chroma444_hits(); - let frames = decode_stream(&stream).unwrap_or_else(|e| { - panic!("{name}: the live {w}x{h} 4:4:4 lossy stream was refused: {e}") - }); - let own = crate::decode::rect4_inter_own_chroma444_hits(); - assert!( - own > 0, - "{name}: no 4:4:4 1:4 inter strip read its chroma context over its own extent -- \ - the route this cell is a witness for never ran (measured: 13 at 66x66, 12 at \ - 130x122, 24 at 256x128)" - ); - assert_eq!( - frames.len(), - 4, - "{name}: decoded {} frame(s), the recipe encodes 4 -- a short decode would make the \ - oracle compare cover a prefix of the cell", - frames.len() - ); - for (i, f) in frames.iter().enumerate() { - assert_eq!( - (f.width, f.height), - (w, h), - "{name}: frame {i} is {}x{}, the cell is {w}x{h}", - f.width, - f.height - ); - // At 4:4:4 both chroma planes are full resolution. A decoder that - // kept a subsampled extent would hand quarter-size planes to the - // byte compare; say so here instead of letting the compare - // stand in for the shape claim. - assert_eq!( - f.u.len(), - w * h, - "{name}: frame {i} U plane is {} samples; at 4:4:4 it must be full resolution \ - ({w}x{h})", - f.u.len() - ); - assert_eq!( - f.v.len(), - w * h, - "{name}: frame {i} V plane is {} samples; at 4:4:4 it must be full resolution \ - ({w}x{h})", - f.v.len() - ); - assert_eq!( - f.y.len(), - w * h, - "{name}: frame {i} luma plane is {} samples, expected {w}x{h}", - f.y.len() - ); - } - let (decoded, hidden) = decode_all_frames_vs_oracle(&stream, name); - assert_eq!( - decoded, 4, - "{name}: the oracle decoded {decoded} frame(s) in decode order, the recipe carries 4 \ - (so far {hidden} hidden)" - ); - eprintln!( - "{name}: {w}x{h} 4:4:4 lossy, {decoded} decode-order frame(s) byte-exact vs aomdec \ - ({hidden} hidden), {own} own-extent 1:4 chroma gather(s)" - ); - } - - /// lane-av1toolgates: the shared body of the two `enable-rect-tx` - /// coverage gates (8-bit and 10-bit). - /// - /// The aomenc ARGUMENT VECTOR is built by each gate and passed in, never - /// assembled here. That is not tidiness: `gate_coverage`'s `gate_bodies()` - /// splits `stream.rs` on `\n #[` and keeps a segment only if that - /// segment itself contains `--passes=1`, so a flag living in a helper is - /// invisible to the coverage derivation. A helper that owns the recipe - /// would leave this gate counted at whatever depth the helper's own text - /// implies -- which is the blind spot that kept `enable-rect-tx` on the - /// `NEVER_EXERCISED` lists after real streams had exercised it. - /// - /// WHAT THIS GATE IS AND IS NOT. `enable_rect_tx` has no sequence-header - /// bit in AV1 -- aom reads it only in `tx_search.c` (`search_tx_size`'s - /// `!enable_rect_tx && tx_size_wide != tx_size_high` skip and the - /// `tx_size_max_32_square` remap) -- so the flag never reaches a decoder. - /// Spelling `--enable-rect-tx=1` proves the ENCODER was ALLOWED the tool - /// and nothing more. It is CONTEXT here, not the witness: a gate that - /// stopped at the flag would be the `tool-disabled-in-every-gate` defect - /// `NEVER_EXERCISED` exists to prevent, in a new costume. - /// - /// The witness is the PARSED PARTITION SHAPE, the only thing in the - /// bitstream that can carry a rect transform: - /// [`decode::rect_partition_hits`] counts `PARTITION_HORZ`/`PARTITION_VERT` - /// symbols actually read, i.e. a rect partition in the tree this decoder - /// walked, and [`decode::rect_coeff_tu_hits`] counts the rectangular - /// transform units that then coded coefficients through `read_coeffs_rect` - /// (`all_zero == 0`) -- the rect coefficient TABLES being read, not a - /// header bit. Both are asserted above zero over the arms that decoded AND - /// compared, and every frame is pixel-compared against ffmpeg's own decode - /// of the identical bytes. - /// - /// LIMIT, stated because it bounds what this gate can claim: this - /// repository has no INDEPENDENT partition parser to list leaves from -- - /// `ec-av1-syntax` parses OBU headers and the sequence header only -- and - /// `ec_av1::census`'s per-frame `blocks`/`tx` shape maps, the one true - /// leaf list, are armed by a process-global `OnceLock` on - /// `EC_AV1_BITCENSUS`, so arming them inside a lib test would switch the - /// accountant on for every other gate in the process. The partition walk is - /// therefore observed through the decoder's own counters, which is weaker - /// than a second opinion but is still a shape fact about the stream rather - /// than a fact about the flag. - /// - /// RED-BEFORE: the COUNTERS, one per assert, both measured. - /// `--enable-rect-tx=0` is deliberately NOT claimed as the mutation: it - /// does NOT zero these counters (39 rect coefficient TUs against 210 on - /// the cq20 arm, because `--enable-rect-partitions=1` already forces - /// non-square transform sizes regardless), and with every partition shape - /// off the flag yields no rect transform at either setting. `=0` does turn - /// the gate red, but through the ORACLE -- its `--enable-tx-size-search=0` - /// arm is a stream ffmpeg cannot decode past frame 6 of 15 -- so the - /// frame-count assert fires first and proves nothing about the tool. - pub(super) fn rect_tx_tool_gate(name: &str, ten_bit: bool, args: &[String]) -> (usize, usize) { - // A missing tool SKIPs, so the totals the caller sums stay 0 and the - // gate's own witness assert fails loudly instead of passing vacuously - // on a run that decoded nothing. - if !have_ffmpeg() { - eprintln!("SKIP {name}: no ffmpeg"); - return (0, 0); - } - if !have_aomenc() { - eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display()); - return (0, 0); - } - let (width, height) = (64usize, 64usize); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - "mandelbrot=size=64x64:rate=25", - "-pix_fmt", - if ten_bit { "yuv420p10le" } else { "yuv420p" }, - // y4m calls 10-bit an unofficial pixel format (no-op at 8). - "-strict", - "-1", - "-t", - "0.60", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "{name}: ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let out = run_with_stdin(Command::new(aomenc_path()).args(args), &y4m.stdout); - assert!( - out.status.success(), - "{name}: aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - assert!(!stream.is_empty(), "{name}: aomenc wrote an empty stream"); - if ten_bit { - assert_eq!( - parsed_bit_depth(&stream), - 10, - "{name}: aomenc did not write a 10-bit sequence header" - ); - } - let parts_before = decode::rect_partition_hits(); - let tus_before = decode::rect_coeff_tu_hits(); - let decoded = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => panic!("{name}: decode_stream refused: {e}"), - }; - // Sampled after the decode, before the pixel compare, so a mismatch - // report can still say whether the arm fired. - let parts = decode::rect_partition_hits() - parts_before; - let tus = decode::rect_coeff_tu_hits() - tus_before; - // The ENCODE's frame count: the fixture renders `mandelbrot=size=64x64:rate=25` - // with `-t "0.60"` (10677-10691) -- 25 x 0.60 = 15 frames -- and the - // caller's `args` carry no `--limit` (10823-10853), so every arm's stream - // codes all 15. Asserted ABOVE the oracle call, which is the fix for the - // misattribution this gate's own doc comment records: the - // `--enable-tx-size-search=0` arm is a stream ffmpeg cannot decode past - // frame 6 of 15, and with the count taken from our decode the helper's - // byte-length assert fires FIRST and reads as an ffmpeg fault. Naming the - // 15 here makes the shortfall ours to explain. - const ENCODED_FRAMES: usize = 15; - assert_eq!( - decoded.len(), - ENCODED_FRAMES, - "{name}: the encode codes {ENCODED_FRAMES} frames, the decode showed {} (rect \ - partitions {parts}, rect coefficient TUs {tus})", - decoded.len() - ); - let reference = if ten_bit { - ffmpeg_decode_sequence_10bit(&stream, width, height, decoded.len()) - } else { - ffmpeg_decode_sequence(&stream, width, height, decoded.len()) - }; - assert_eq!( - decoded.len(), - reference.len(), - "{name}: shown-frame count vs ffmpeg (rect partitions {parts}, rect coefficient \ - TUs {tus})" - ); - for (i, (ours, theirs)) in decoded.iter().zip(&reference).enumerate() { - for (plane, (a, b), w) in [ - ("Y", (&ours.y, &theirs.y), width), - ("U", (&ours.u, &theirs.u), width / 2), - ("V", (&ours.v, &theirs.v), width / 2), - ] { - assert_eq!(a.len(), b.len(), "{name}: frame {i} {plane} plane length"); - if a != b { - let pin = std::env::temp_dir().join(format!("{name}-mismatch.obu")); - crate::dumpio::pin("TEST_PIN", &pin, &stream); - let at = a - .iter() - .zip(b.iter()) - .position(|(x, y)| x != y) - .unwrap_or(0); - panic!( - "{name}: frame {i} {plane} mismatch vs ffmpeg at row {}, col {}: {} vs \ - {} (rect partitions {parts}, rect coefficient TUs {tus}; stream pinned \ - at {})", - at / w, - at % w, - a[at], - b[at], - pin.display() - ); - } - } - } - eprintln!( - "{name}: {} bit, pixel-exact vs ffmpeg; parsed rect partitions {parts}, rect \ - coefficient TUs {tus}", - if ten_bit { "10" } else { "8" } - ); - (parts, tus) - } - - /// lane-hbdgates r1: drive one 10-bit aomenc recipe over `seeds`, decode - /// every attempt and pixel-compare every SHOWN frame against ffmpeg's own - /// 10-bit decode of the identical bytes. Per-tool firing counters are - /// sampled PER ATTEMPT and summed only over attempts that decoded *and* - /// compared -- a stream that hit a named refusal contributes nothing - /// (class `counter-from-refused-stream`). Named refusals are tolerated - /// and reported; a pixel mismatch is a hard failure, never a SKIP. - pub(super) fn ten_bit_tool_gate( - name: &str, - width: usize, - height: usize, - frames: usize, - extra: &[&str], - seeds: &[u32], - counters: &[(&str, fn() -> usize)], - ) { - fn first_diff(ours: &[u16], theirs: &[u16], width: usize) -> Option { - ours.iter() - .zip(theirs.iter()) - .position(|(a, b)| a != b) - .map(|i| { - format!( - "first diff at index {i} (row {}, col {}): ours {} vs ffmpeg {}", - i / width, - i % width, - ours[i], - theirs[i] - ) - }) - } - let mut totals = vec![0usize; counters.len()]; - let mut refusals: Vec = Vec::new(); - let mut compared = 0usize; - for &seed in seeds { - let stream = encode_10bit_gradients_seed(name, seed, width, height, frames, extra); - assert_eq!( - parsed_bit_depth(&stream), - 10, - "{name}: aomenc did not write a 10-bit sequence header (seed {seed})" - ); - let before: Vec = counters.iter().map(|(_, f)| f()).collect(); - let decoded = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => { - refusals.push(format!("seed {seed}: {e}")); - continue; - } - }; - // Deltas are read BEFORE the pixel compare so a mismatch report - // says whether the tool under test actually fired on the failing - // stream (a mismatch with a zero delta is some other defect). - let deltas: Vec = counters - .iter() - .zip(before.iter()) - .map(|((_, f), b)| f() - b) - .collect(); - let fired: Vec = counters - .iter() - .zip(deltas.iter()) - .map(|((label, _), d)| format!("{label}={d}")) - .collect(); - let fired = fired.join(" "); - // The ENCODE's frame count, and it is this helper's `frames` PARAMETER - // (15446) -- not our decode's length. It is the same value handed to - // `encode_10bit_gradients_seed` (15469), which renders - // `frames / 25.0` seconds at `rate=25` (15928, 15940) and runs - // aomenc with no `--limit` of its own, so the stream codes exactly - // `frames` frames: 1 for the single-key-frame callers, 24 for the - // `--lag-in-frames=16` inter callers. Asserted ABOVE the oracle call, - // so a decode that showed fewer reds naming the encode rather than - // handing ffmpeg the same short count. - assert_eq!( - decoded.len(), - frames, - "{name}: seed {seed}: the encode codes {frames} frame(s), the decode showed {}", - decoded.len() - ); - let reference = ffmpeg_decode_sequence_10bit(&stream, width, height, decoded.len()); - assert_eq!( - decoded.len(), - reference.len(), - "{name}: seed {seed}: shown-frame count vs ffmpeg" - ); - for (i, (ours, theirs)) in decoded.iter().zip(reference.iter()).enumerate() { - for (plane, (a, b), w) in [ - ("Y", (&ours.y, &theirs.y), width), - ("U", (&ours.u, &theirs.u), width / 2), - ("V", (&ours.v, &theirs.v), width / 2), - ] { - if let Some(d) = first_diff(a, b, w) { - panic!("{name}: seed {seed} frame {i} plane {plane}: {d} [{fired}]"); - } - assert_eq!( - a.len(), - b.len(), - "{name}: seed {seed} frame {i} plane {plane}: ours has {} samples, \ - ffmpeg's has {} -- a short plane would zip-truncate the walk above \ - and hide a chroma-span defect", - a.len(), - b.len() - ); - } - } - compared += 1; - for (i, d) in deltas.iter().enumerate() { - totals[i] += d; - } - } - assert!( - compared > 0, - "{name}: every attempt hit a named refusal:\n{}", - refusals.join("\n") - ); - for (i, (label, _)) in counters.iter().enumerate() { - assert!( - totals[i] > 0, - "{name}: {compared} attempt(s) decoded pixel-exact but {label} never fired -- \ - the gate would prove nothing about that tool. refusals:\n{}", - refusals.join("\n") - ); - } - let summary: Vec = counters - .iter() - .zip(totals.iter()) - .map(|((label, _), t)| format!("{label}={t}")) - .collect(); - eprintln!( - "{name}: {compared}/{} attempts pixel-exact, {}", - seeds.len(), - summary.join(" ") - ); - } - - pub(super) fn intra_rect_in_inter_gate(bit_depth: u32) { - const NAME: &str = - "a_real_aomenc_inter_sequence_with_an_intra_rect_strip_decodes_pixel_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height, frame_count) = (96usize, 96usize, 8usize); - let mut refusals: Vec = Vec::new(); - let mut uncounted_exact = 0u32; - let mut compared = 0u32; - let mut shapes = [0usize; 3]; - for attempt in 0..45u32 { - let seed = 42 + attempt; - // mandelbrot's fractal detail plus a HARD cut at frame 4: half - // the picture becomes a flat white box, which no motion vector - // can predict, so aomenc's RD codes those blocks INTRA inside an - // inter frame. The box's vertical edge at x=48 is what makes the - // partition search reach for HORZ/VERT strips there. - // A FAST ZOOM: `end_scale`/`end_pts` make mandelbrot rush - // through its own zoom, so consecutive frames share almost no - // content and aomenc's RD codes blocks INTRA inside INTER frames - // (`--kf-min-dist=1000` forbids a new key frame). That is the - // only way a real encoder reaches this decoder's intra-in-inter - // arm; a slowly-evolving source codes every rect strip inter. - let source = format!( - "mandelbrot=size={width}x{height}:start_scale={}:end_scale=0.004:end_pts=8:rate=25", - 5.0 - f64::from(attempt) * 0.06 - ); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-vf", - "hue=s=0", - "-pix_fmt", - if bit_depth == 10 { - "yuv420p10le" - } else { - "yuv420p" - }, - "-strict", - "-1", - "-t", - "0.32", - "-f", - "yuv4mpegpipe", - "-strict", - "-1", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let depth_args: &[&str] = if bit_depth == 10 { - &["-b", "10", "--input-bit-depth=10"] - } else { - &[] - }; - // MEASURED (r1): the speed preset gates the feature (class - // [[gate-preset-gates-the-feature]]) -- at `--cpu-used=4` this - // content produces no rect partition at all, at `--cpu-used=0` - // aomenc emits AB partitions the tile path refuses (it ignores - // `--enable-ab-partitions=0`, ledger). So the attempt sweep walks - // the preset as well as the seed. - let cpu = format!("--cpu-used={}", attempt % 5); - // The quantiser drives how finely the RD partitions: the sweep - // walks it too, so "no rect strip fired" cannot be an artefact of - // one cq. - let cq = format!("--cq-level={}", [30u32, 20, 12][(attempt / 5) as usize % 3]); - let out = run_with_stdin( - Command::new(aomenc_path()) - .args(depth_args) - .arg(&cpu) - .arg(&cq) - .args([ - // class [[aomenc-first-flag-wins]]: every flag is spelled - // exactly ONCE in this recipe, so there is no override to - // order. These four are what this gate is about. - "--enable-rect-partitions=1", - // MEASURED (r1): the charter's `--min-partition-size=8` - // makes 24/24 attempts stop at a sub-16 AB-partition - // refusal ("a HORZ_A/HORZ_B/VERT_A partition below 16x16", - // "a coded (non-skip) HORZ_B/VERT_B rect strip below - // 16x16") before any intra rect strip is reached -- those - // are other lanes' surfaces. 16 keeps the 16x8/8x16 shape - // reachable (a 16x16 block's own HORZ/VERT children). - "--min-partition-size=16", - "--max-partition-size=64", - // MEASURED (r1): with tx-size search ON, 24/24 attempts stop at - // the SQUARE intra-in-inter arm's own refusal ("an intra - // block in an inter frame whose tx_depth splits its luma - // transform (round 1)", read_block_tx_size) long before a - // rect strip is reached -- that arm is another lane's - // surface. OFF, no tx-depth symbol is coded at all and - // every rect strip here is the unsplit single-transform - // case. The SPLIT rect arm (`depth_to_tx_wh` + - // decode_rect_split's per-unit walk) is wired but stays - // UNGATED on this path until that square refusal lifts. - "--enable-tx-size-search=0", - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--lag-in-frames=0", - "--auto-alt-ref=0", - // One key frame at the head: the frames after the cut must - // stay INTER frames carrying intra blocks, not become a - // new key frame. - "--kf-min-dist=1000", - "--kf-max-dist=1000", - "--threads=1", - "--row-mt=0", - "--enable-order-hint=0", - "--enable-warped-motion=0", - "--enable-obmc=0", - "--enable-masked-comp=0", - "--enable-interintra-comp=0", - "--enable-dist-wtd-comp=0", - "--enable-diff-wtd-comp=0", - "--enable-onesided-comp=0", - "--enable-interintra-wedge=0", - "--enable-smooth-interintra=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - // The intra-in-inter arm reads no `use_filter_intra` - // symbol (square OR rect) -- lane-fiinter owns that read. - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-cdef=0", - "--enable-restoration=0", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - "--enable-ref-frame-mvs=0", - "--obu", - "-o", - "-", - "-", - ]), - &y4m.stdout, - ); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let before = [ - decode::intra_rect_strip_in_inter_hits(0), - decode::intra_rect_strip_in_inter_hits(1), - decode::intra_rect_strip_in_inter_hits(2), - ]; - let kf_rect_before = decode::rect_partition_hits(); - let frames = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "intra-rect-in-inter decode failed outright (seed {seed}): {msg}" - ); - refusals.push(format!("seed {seed} {cpu} {cq}: {msg}")); - continue; - } - }; - let delta = [ - decode::intra_rect_strip_in_inter_hits(0) - before[0], - decode::intra_rect_strip_in_inter_hits(1) - before[1], - decode::intra_rect_strip_in_inter_hits(2) - before[2], - ]; - let ffmpeg_frames = if bit_depth == 10 { - ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count) - } else { - ffmpeg_decode_sequence(&stream, width, height, frame_count) - }; - assert_eq!(frames.len(), frame_count); - eprintln!( - "intrarect gate {bit_depth}-bit seed={seed} {cpu} {cq}: intra rect strips in inter frames \ - 64-level={} 32-level={} 16-level={}, key-frame rect strips this stream={}", - delta[0], - delta[1], - delta[2], - decode::rect_partition_hits() - kf_rect_before - ); - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - for (plane, (g, w)) in [ - ("Y", (&got.y, &want.y)), - ("U", (&got.u, &want.u)), - ("V", (&got.v, &want.v)), - ] { - let stride = if plane == "Y" { width } else { width / 2 }; - if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) { - eprintln!( - "intrarect gate {bit_depth}-bit seed={seed}: frame {i} {plane} first \ - diff at ({}, {}) got {} want {} ({} samples differ)", - at % stride, - at / stride, - g[at], - w[at], - g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(), - ); - // Magnitude separates a deblock/prediction difference - // (all |d| == 1) from an entropy desync (large, - // arbitrary): the first thing r2 needs to know. - let maxd = g - .iter() - .zip(w.iter()) - .map(|(a, b)| i32::from(*a).abs_diff(i32::from(*b))) - .max() - .unwrap_or(0); - let rows: std::collections::BTreeSet = g - .iter() - .zip(w.iter()) - .enumerate() - .filter(|(_, (a, b))| a != b) - .map(|(k, _)| k / stride) - .collect(); - eprintln!( - "intrarect gate {bit_depth}-bit seed={seed}: frame {i} {plane} max \ - |diff|={maxd}, rows {:?}..{:?}", - rows.iter().next(), - rows.iter().next_back() - ); - } - assert_eq!(g, w, "{plane} vs ffmpeg (seed {seed}, frame {i})"); - } - } - compared += 1; - if delta.iter().all(|d| *d == 0) { - uncounted_exact += 1; - refusals.push(format!( - "seed {seed} {cpu} {cq}: decoded and pixel-compared, but no intra rect strip on the \ - inter path" - )); - } - for k in 0..3 { - shapes[k] += delta[k]; - } - if shapes.iter().filter(|n| **n > 0).count() >= 2 { - break; - } - } - gate_buckets( - NAME, - compared - uncounted_exact, - uncounted_exact, - refusals.len() - uncounted_exact as usize, - ); - eprintln!( - "{NAME} ({bit_depth}-bit): compared {compared} streams, intra rect strips in inter \ - frames per shape: 64x32/32x64={} 32x16/16x32={} 16x8/8x16={}; refusals:\n{}", - shapes[0], - shapes[1], - shapes[2], - refusals.join("\n") - ); - assert!( - compared > 0, - "{NAME} ({bit_depth}-bit): every attempt hit a named refusal -- nothing was \ - pixel-compared:\n{}", - refusals.join("\n") - ); - // MEASURED (r1, 90 attempts; r2 re-ran the 45-attempt sweep at both - // depths): only the 32x16/16x32 class is REACHABLE on this branch -- - // the inter tile path refuses any SB-level partition other than - // NONE/SPLIT, so a 64x32/32x64 intra strip cannot be produced at all, - // and every 16x8/8x16 candidate stops at a sub-16 refusal owned by - // another lane. So the bar is that class, hard, not "two of three": - // a green run still cannot come from a stream that fired nothing. - assert!( - shapes[1] > 0, - "{NAME} ({bit_depth}-bit): no 32x16/16x32 intra rect strip fired over \ - {compared} compared streams (64-level={} 32-level={} 16-level={})", - shapes[0], - shapes[1], - shapes[2] - ); - } - - pub(super) fn tx_select_inter_gate(bit_depth: u32) { - if !have_ffmpeg() { - eprintln!( - "SKIP a_real_aomenc_inter_sequence_with_tx_select_decodes_pixel_exact: no ffmpeg" - ); - return; - } - if !have_aomenc() { - eprintln!( - "SKIP a_real_aomenc_inter_sequence_with_tx_select_decodes_pixel_exact: no aomenc at {}", - aomenc_path().display() - ); - return; - } - let (width, height, frame_count) = (64usize, 64usize, 4usize); - let mut refusals = Vec::new(); - let mut uncounted_exact = 0u32; - for attempt in 0..40u32 { - let seed = 42 + attempt; - // Detail is what makes aomenc's RD prefer a split transform; a - // flat gradient resolves every `txfm_split` to 0. `mandelbrot`'s - // fractal boundary is the same source the sibling intra tx-select - // gate uses, at a different `start_scale` per attempt. - let source = format!( - "mandelbrot=size=64x64:start_scale={}:rate=25", - 5.0 - f64::from(attempt) * 0.06 - ); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - // Desaturated chroma: `uv_mode` stays DC_PRED, so the - // still-refused directional-chroma gap never fires and - // luma detail alone drives the transform split. - "-vf", - "hue=s=0", - "-pix_fmt", - if bit_depth == 10 { - "yuv420p10le" - } else { - "yuv420p" - }, - // y4m carries no official 10-bit tag; ffmpeg writes one - // only under `-strict -1` (a no-op at 8 bit). - "-strict", - "-1", - "-t", - "0.16", - "-f", - "yuv4mpegpipe", - "-strict", - "-1", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let depth_args: &[&str] = if bit_depth == 10 { - &["-b", "10", "--input-bit-depth=10"] - } else { - &[] - }; - let out = run_with_stdin( - Command::new(aomenc_path()).args(depth_args).args([ - // lane-defon r1: explicit on-value (aomenc keeps the FIRST - // occurrence, so overrides go before the base list). - "--enable-tx-size-search=1", - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=55", - "--cpu-used=0", - "--lag-in-frames=0", - "--auto-alt-ref=0", - "--kf-max-dist=1000", - "--threads=1", - "--row-mt=0", - "--enable-order-hint=0", - "--enable-warped-motion=0", - "--enable-obmc=0", - "--enable-masked-comp=0", - "--enable-interintra-comp=0", - "--enable-dist-wtd-comp=0", - "--enable-diff-wtd-comp=0", - "--enable-onesided-comp=0", - "--enable-interintra-wedge=0", - "--enable-smooth-interintra=0", - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - // DELIBERATELY ABSENT: --enable-tx-size-search=0. - "--enable-cdef=0", - "--enable-restoration=0", - "--max-partition-size=32", - // Sub-16 inter partitions are a separate named refusal - // (this decoder codes no inter block below 16x16 through - // the square path this gate drives), and detailed content - // makes aomenc's RD reach for them on nearly every seed. - "--min-partition-size=16", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - "--enable-ref-frame-mvs=0", - "--obu", - "-o", - "-", - "-", - ]), - &y4m.stdout, - ); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let (reads_before, hits_before) = - (decode::txfm_split_reads(), decode::txfm_split_hits()); - let frames = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "tx-select inter decode failed outright (seed {seed}): {msg}" - ); - refusals.push(format!("seed {seed}: {msg}")); - continue; - } - }; - let (reads, hits) = ( - decode::txfm_split_reads() - reads_before, - decode::txfm_split_hits() - hits_before, - ); - // class [[gate-skips-on-its-own-failure]]: a decode that succeeded - // is ALWAYS pixel-compared below; the hit counter only decides whether - // the attempt counts toward the firing total. - let counted = hits != 0; - if !counted { - uncounted_exact += 1; - refusals.push(format!( - "seed {seed}: decoded and pixel-compared, but no block took a txfm_split \ - ({reads} symbols read)" - )); - } - let ffmpeg_frames = if bit_depth == 10 { - ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count) - } else { - ffmpeg_decode_sequence(&stream, width, height, frame_count) - }; - assert_eq!(frames.len(), frame_count); - eprintln!( - "txselect gate {bit_depth}-bit seed={seed}: txfm_split reads={reads} splits taken={hits}" - ); - // Name the first differing sample before the assert fires: a - // 64x64 plane's `assert_eq!` output is 4096 numbers, useless for - // locating a desync. - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - for (plane, (g, w)) in [ - ("Y", (&got.y, &want.y)), - ("U", (&got.u, &want.u)), - ("V", (&got.v, &want.v)), - ] { - let stride = if plane == "Y" { width } else { width / 2 }; - if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) { - eprintln!( - "txselect gate seed={seed}: frame {i} {plane} first diff at \ - ({}, {}) got {} want {} ({} samples differ)", - at % stride, - at / stride, - g[at], - w[at], - g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(), - ); - let coords: Vec = g - .iter() - .zip(w.iter()) - .enumerate() - .filter(|(_, (a, b))| a != b) - .take(12) - .map(|(k, (a, b))| format!("({},{})={a}/{b}", k % stride, k / stride)) - .collect(); - eprintln!("txselect gate seed={seed}: frame {i} {plane} diffs {coords:?}"); - } - } - } - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})"); - assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})"); - assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})"); - } - if counted { - gate_buckets( - &format!("tx_select_inter_gate({bit_depth})"), - 1, - uncounted_exact, - refusals.len() - uncounted_exact as usize, - ); - return; - } - } - gate_buckets( - &format!("tx_select_inter_gate({bit_depth})"), - 0, - uncounted_exact, - refusals.len() - uncounted_exact as usize, - ); - panic!( - "tx_select_inter_gate({bit_depth}) never observed a taken txfm_split:\n{}", - refusals.join("\n") - ); - } - - pub(super) fn intra_in_inter_split_tx_gate(bit_depth: u32) { - let name = format!("intra_in_inter_split_tx_gate({bit_depth})"); - if !have_ffmpeg() { - eprintln!("SKIP {name}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height, frame_count) = (64usize, 64usize, 8usize); - let mut refusals = Vec::new(); - let mut uncounted_exact = 0u32; - for attempt in 0..40u32 { - let seed = 42 + attempt; - // A zooming fractal: every frame moves (so the sequence is - // genuinely inter-coded) and keeps sharp new detail entering at - // the borders, which is what makes aomenc's RD choose an INTRA - // block inside an inter frame -- and then split its transform. - // A zooming fractal with a hard CUT halfway (`overlay` switching - // a second, unrelated fractal on at frame 4): after the cut every - // block is unpredictable from the reference, which is what makes - // aomenc code INTRA blocks inside an inter frame -- and at this - // cq the RD then splits their transforms. - let source = format!( - "mandelbrot=size=64x64:start_scale={}:rate=25[a];\ - mandelbrot=size=64x64:start_scale={}:rate=25[b];\ - [a][b]overlay=enable='gte(n,4)'", - 5.0 - f64::from(attempt) * 0.06, - 0.9 + f64::from(attempt) * 0.11 - ); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - // Desaturated chroma keeps `uv_mode` on DC_PRED, so the - // still-refused directional-chroma gaps never fire and - // luma detail alone drives the transform split. - "-vf", - "hue=s=0", - "-pix_fmt", - if bit_depth == 10 { - "yuv420p10le" - } else { - "yuv420p" - }, - "-strict", - "-1", - "-t", - "0.32", - "-f", - "yuv4mpegpipe", - "-strict", - "-1", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let depth_args: &[&str] = if bit_depth == 10 { - &["-b", "10", "--input-bit-depth=10"] - } else { - &[] - }; - let out = run_with_stdin( - Command::new(aomenc_path()).args(depth_args).args([ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=30", - "--cpu-used=0", - "--lag-in-frames=0", - "--auto-alt-ref=0", - // One key frame only: every later frame is an inter frame, - // which is where this gate's intra blocks must sit. The - // MIN distance is what stops aomenc's scene-cut detector - // from inserting a second key frame at the cut this gate's - // source deliberately contains. - "--kf-max-dist=1000", - "--kf-min-dist=1000", - "--threads=1", - "--row-mt=0", - "--enable-order-hint=0", - "--enable-warped-motion=0", - "--enable-obmc=0", - "--enable-masked-comp=0", - "--enable-interintra-comp=0", - "--enable-dist-wtd-comp=0", - "--enable-diff-wtd-comp=0", - "--enable-onesided-comp=0", - "--enable-interintra-wedge=0", - "--enable-smooth-interintra=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-cdef=0", - "--enable-restoration=0", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - "--enable-ref-frame-mvs=0", - // Per-arm overrides go LAST (aomenc keeps the last - // occurrence of a repeated --enable-* flag): the intra - // tx_depth symbol only exists under TX_MODE_SELECT, and - // rect partitions are a separate named refusal. - "--enable-tx-size-search=1", - "--enable-rect-partitions=0", - "--max-partition-size=32", - // Sub-16 inter partitions are a separate named refusal, - // as is the 8x8 intra leaf's own TX_4X4 split. - "--min-partition-size=16", - "--obu", - "-o", - "-", - "-", - ]), - &y4m.stdout, - ); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let before = decode::intra_in_inter_split_tx_hits(); - let frames = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{name} decode failed outright (seed {seed}): {msg}" - ); - refusals.push(format!("seed {seed}: {msg}")); - continue; - } - }; - let after = decode::intra_in_inter_split_tx_hits(); - let mut per_size = [0usize; 4]; - for i in 0..4 { - per_size[i] = after[i] - before[i]; - } - // class [[gate-skips-on-its-own-failure]]: a decode that - // succeeded is ALWAYS pixel-compared below; the counter only - // decides whether the attempt counts as firing. - let counted = per_size.iter().sum::() != 0; - if !counted { - uncounted_exact += 1; - refusals.push(format!( - "seed {seed}: decoded and pixel-compared, but no intra block in an inter \ - frame split its transform" - )); - } - let ffmpeg_frames = if bit_depth == 10 { - ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count) - } else { - ffmpeg_decode_sequence(&stream, width, height, frame_count) - }; - assert_eq!(frames.len(), frame_count); - eprintln!( - "{name} seed={seed}: split intra-in-inter blocks 8x8={} 16x16={} 32x32={} \ - 64x64={}", - per_size[0], per_size[1], per_size[2], per_size[3] - ); - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - for (plane, (g, w)) in [ - ("Y", (&got.y, &want.y)), - ("U", (&got.u, &want.u)), - ("V", (&got.v, &want.v)), - ] { - let stride = if plane == "Y" { width } else { width / 2 }; - if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) { - eprintln!( - "{name} seed={seed}: frame {i} {plane} first diff at ({}, {}) got {} \ - want {} ({} samples differ)", - at % stride, - at / stride, - g[at], - w[at], - g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(), - ); - } - } - } - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})"); - assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})"); - assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})"); - } - if counted { - gate_buckets( - &name, - 1, - uncounted_exact, - refusals.len() - uncounted_exact as usize, - ); - return; - } - } - gate_buckets( - &name, - 0, - uncounted_exact, - refusals.len() - uncounted_exact as usize, - ); - panic!( - "{name} never observed a split-transform intra block in an inter frame:\n{}", - refusals.join("\n") - ); - } - - pub(super) fn filter_intra_in_inter_gate(bit_depth: u32) { - let name = format!("filter_intra_in_inter_gate({bit_depth})"); - if !have_ffmpeg() { - eprintln!("SKIP {name}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height, frame_count) = (64usize, 64usize, 8usize); - let mut refusals = Vec::new(); - let mut uncounted_exact = 0u32; - for attempt in 0..40u32 { - let seed = 42 + attempt; - // A zooming fractal: every frame moves (so the sequence is - // genuinely inter-coded) and keeps sharp new detail entering at - // the borders, which is what makes aomenc's RD choose an INTRA - // block inside an inter frame -- and then split its transform. - // A zooming fractal with a hard CUT halfway (`overlay` switching - // a second, unrelated fractal on at frame 4): after the cut every - // block is unpredictable from the reference, which is what makes - // aomenc code INTRA blocks inside an inter frame -- and at this - // cq the RD then splits their transforms. - let source = format!( - "mandelbrot=size=64x64:start_scale={}:rate=25[a];\ - mandelbrot=size=64x64:start_scale={}:rate=25[b];\ - [a][b]overlay=enable='gte(n,4)'", - 5.0 - f64::from(attempt) * 0.06, - 0.9 + f64::from(attempt) * 0.11 - ); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - // Desaturated chroma keeps `uv_mode` on DC_PRED, so the - // still-refused directional-chroma gaps never fire and - // luma detail alone drives the transform split. - "-vf", - "hue=s=0", - "-pix_fmt", - if bit_depth == 10 { - "yuv420p10le" - } else { - "yuv420p" - }, - "-strict", - "-1", - "-t", - "0.32", - "-f", - "yuv4mpegpipe", - "-strict", - "-1", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let depth_args: &[&str] = if bit_depth == 10 { - &["-b", "10", "--input-bit-depth=10"] - } else { - &[] - }; - let out = run_with_stdin( - Command::new(aomenc_path()).args(depth_args).args([ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=30", - "--cpu-used=0", - "--lag-in-frames=0", - "--auto-alt-ref=0", - // One key frame only: every later frame is an inter frame, - // which is where this gate's intra blocks must sit. The - // MIN distance is what stops aomenc's scene-cut detector - // from inserting a second key frame at the cut this gate's - // source deliberately contains. - "--kf-max-dist=1000", - "--kf-min-dist=1000", - "--threads=1", - "--row-mt=0", - "--enable-order-hint=0", - "--enable-warped-motion=0", - "--enable-obmc=0", - "--enable-masked-comp=0", - "--enable-interintra-comp=0", - "--enable-dist-wtd-comp=0", - "--enable-diff-wtd-comp=0", - "--enable-onesided-comp=0", - "--enable-interintra-wedge=0", - "--enable-smooth-interintra=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-cdef=0", - "--enable-restoration=0", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - "--enable-ref-frame-mvs=0", - // Per-arm overrides go LAST (aomenc keeps the last - // occurrence of a repeated --enable-* flag): the intra - // tx_depth symbol only exists under TX_MODE_SELECT, and - // rect partitions are a separate named refusal. - "--enable-filter-intra=1", - "--enable-tx-size-search=1", - "--enable-rect-partitions=0", - "--max-partition-size=32", - // Sub-16 inter partitions are a separate named refusal, - // as is the 8x8 intra leaf's own TX_4X4 split. - "--min-partition-size=16", - "--obu", - "-o", - "-", - "-", - ]), - &y4m.stdout, - ); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let before = decode::intra_in_inter_filter_intra_hits(); - let frames = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{name} decode failed outright (seed {seed}): {msg}" - ); - refusals.push(format!("seed {seed}: {msg}")); - continue; - } - }; - let fired = decode::intra_in_inter_filter_intra_hits() - before; - // class [[gate-skips-on-its-own-failure]]: a decode that - // succeeded is ALWAYS pixel-compared below; the counter only - // decides whether the attempt counts as firing. - let counted = fired != 0; - if !counted { - uncounted_exact += 1; - refusals.push(format!( - "seed {seed}: decoded and pixel-compared, but no intra block in an inter \ - frame used filter intra" - )); - } - let ffmpeg_frames = if bit_depth == 10 { - ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count) - } else { - ffmpeg_decode_sequence(&stream, width, height, frame_count) - }; - assert_eq!(frames.len(), frame_count); - eprintln!("{name} seed={seed}: filter-intra blocks inside inter frames = {fired}"); - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - for (plane, (g, w)) in [ - ("Y", (&got.y, &want.y)), - ("U", (&got.u, &want.u)), - ("V", (&got.v, &want.v)), - ] { - let stride = if plane == "Y" { width } else { width / 2 }; - if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) { - eprintln!( - "{name} seed={seed}: frame {i} {plane} first diff at ({}, {}) got {} \ - want {} ({} samples differ)", - at % stride, - at / stride, - g[at], - w[at], - g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(), - ); - } - } - } - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})"); - assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})"); - assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})"); - } - if counted { - gate_buckets( - &name, - 1, - uncounted_exact, - refusals.len() - uncounted_exact as usize, - ); - return; - } - } - gate_buckets( - &name, - 0, - uncounted_exact, - refusals.len() - uncounted_exact as usize, - ); - panic!( - "{name} never observed a filter-intra intra block in an inter frame:\n{}", - refusals.join("\n") - ); - } - - pub(super) fn angle_delta_in_inter_gate(bit_depth: u32, min_partition: &str) { - let name = format!("angle_delta_in_inter_gate({bit_depth}, min={min_partition})"); - let leaf8 = min_partition.ends_with('8'); - assert!( - !leaf8, - "the 8x8-leaf arm keeps its refusal; see the module note" - ); - if !have_ffmpeg() { - eprintln!("SKIP {name}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height, frame_count) = (64usize, 64usize, 8usize); - let mut refusals = Vec::new(); - let mut uncounted_exact = 0u32; - for attempt in 0..40u32 { - let seed = 42 + attempt; - // A zooming fractal: every frame moves (so the sequence is - // genuinely inter-coded) and keeps sharp new detail entering at - // the borders, which is what makes aomenc's RD choose an INTRA - // block inside an inter frame -- and then split its transform. - // A zooming fractal with a hard CUT halfway (`overlay` switching - // a second, unrelated fractal on at frame 4): after the cut every - // block is unpredictable from the reference, which is what makes - // aomenc code INTRA blocks inside an inter frame -- and at this - // cq the RD then splits their transforms. - let source = format!( - "mandelbrot=size={width}x{height}:start_scale={}:rate=25[a];\ - mandelbrot=size={width}x{height}:start_scale={}:rate=25[b];\ - [a][b]overlay=enable='gte(n,4)'", - 5.0 - f64::from(attempt) * 0.06, - 0.9 + f64::from(attempt) * 0.11 - ); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - // Desaturated chroma keeps `uv_mode` on DC_PRED, so the - // still-refused directional-chroma gaps never fire and - // luma detail alone drives the transform split. - "-vf", - "hue=s=0", - "-pix_fmt", - if bit_depth == 10 { - "yuv420p10le" - } else { - "yuv420p" - }, - "-strict", - "-1", - "-t", - "0.32", - "-f", - "yuv4mpegpipe", - "-strict", - "-1", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - // The 8x8-leaf arm is fenced by three sibling refusals (non-DC - // chroma on an 8x8 leaf, its TX_4X4 split, sub-16 rect inter - // leaves), so it sweeps the quantiser as well as the source: a - // coarser q is what pushes the RD to directional intra at 8x8. - let cq = if leaf8 { - format!("--cq-level={}", 20 + (attempt % 5) * 10) - } else { - "--cq-level=30".to_string() - }; - let depth_args: &[&str] = if bit_depth == 10 { - &["-b", "10", "--input-bit-depth=10"] - } else { - &[] - }; - let out = run_with_stdin( - Command::new(aomenc_path()).args(depth_args).args([ - "--codec=av1", - "--passes=1", - "--end-usage=q", - &cq, - "--cpu-used=0", - "--lag-in-frames=0", - "--auto-alt-ref=0", - // One key frame only: every later frame is an inter frame, - // which is where this gate's intra blocks must sit. The - // MIN distance is what stops aomenc's scene-cut detector - // from inserting a second key frame at the cut this gate's - // source deliberately contains. - "--kf-max-dist=1000", - "--kf-min-dist=1000", - "--threads=1", - "--row-mt=0", - "--enable-order-hint=0", - "--enable-warped-motion=0", - "--enable-obmc=0", - "--enable-masked-comp=0", - "--enable-interintra-comp=0", - "--enable-dist-wtd-comp=0", - "--enable-diff-wtd-comp=0", - "--enable-onesided-comp=0", - "--enable-interintra-wedge=0", - "--enable-smooth-interintra=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=1", - "--enable-angle-delta=1", - "--enable-cdef=0", - "--enable-restoration=0", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - "--enable-ref-frame-mvs=0", - // Per-arm overrides go LAST (aomenc keeps the last - // occurrence of a repeated --enable-* flag): the intra - // tx_depth symbol only exists under TX_MODE_SELECT, and - // rect partitions are a separate named refusal. - "--enable-filter-intra=1", - "--enable-tx-size-search=1", - "--enable-rect-partitions=0", - "--max-partition-size=32", - // Sub-16 inter partitions are a separate named refusal, - // as is the 8x8 intra leaf's own TX_4X4 split. - min_partition, - "--obu", - "-o", - "-", - "-", - ]), - &y4m.stdout, - ); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let before = decode::intra_in_inter_angle_delta_y_hits(); - let before_uv = decode::intra_in_inter_angle_delta_uv_hits(); - let frames = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{name} decode failed outright (seed {seed}): {msg}" - ); - refusals.push(format!("seed {seed}: {msg}")); - continue; - } - }; - let fired = decode::intra_in_inter_angle_delta_y_hits() - before; - let fired_uv = decode::intra_in_inter_angle_delta_uv_hits() - before_uv; - // class [[gate-skips-on-its-own-failure]]: a decode that - // succeeded is ALWAYS pixel-compared below; the counter only - // decides whether the attempt counts as firing. - let counted = fired != 0; - if !counted { - uncounted_exact += 1; - refusals.push(format!( - "seed {seed}: decoded and pixel-compared, but no intra block in an inter \ - frame carried a nonzero angle_delta_y" - )); - } - let ffmpeg_frames = if bit_depth == 10 { - ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count) - } else { - ffmpeg_decode_sequence(&stream, width, height, frame_count) - }; - assert_eq!(frames.len(), frame_count); - eprintln!( - "{name} seed={seed}: intra-in-inter blocks with a nonzero angle_delta_y = \ - {fired}, angle_delta_uv = {fired_uv}" - ); - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - for (plane, (g, w)) in [ - ("Y", (&got.y, &want.y)), - ("U", (&got.u, &want.u)), - ("V", (&got.v, &want.v)), - ] { - let stride = if plane == "Y" { width } else { width / 2 }; - if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) { - eprintln!( - "{name} seed={seed}: frame {i} {plane} first diff at ({}, {}) got {} \ - want {} ({} samples differ)", - at % stride, - at / stride, - g[at], - w[at], - g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(), - ); - } - } - } - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})"); - assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})"); - assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})"); - } - if counted { - gate_buckets( - &name, - 1, - uncounted_exact, - refusals.len() - uncounted_exact as usize, - ); - return; - } - } - gate_buckets( - &name, - 0, - uncounted_exact, - refusals.len() - uncounted_exact as usize, - ); - panic!( - "{name} never observed a nonzero angle delta on an intra block in an inter \ - frame:\n{}", - refusals.join("\n") - ); - } - - pub(super) fn uv_mode_in_inter8_gate(bit_depth: u32, tile_columns: u32) { - let name = format!("uv_mode_in_inter8_gate({bit_depth}, tiles={tile_columns})"); - if !have_ffmpeg() { - eprintln!("SKIP {name}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height, frame_count) = (192usize, 128usize, 8usize); - let mut refusals = Vec::new(); - let mut uncounted_exact = 0u32; - let mut totals = (0usize, 0usize, 0usize); - for attempt in 0..30u32 { - let seed = 42 + attempt; - // A zooming fractal with a hard CUT at frame 4 (`overlay` - // switching a second, unrelated fractal on): after the cut a block - // is unpredictable from the reference, which is what makes aomenc - // code INTRA blocks inside an inter frame. Chroma is NOT - // desaturated here (every sibling inter gate passes `hue=s=0`) -- - // real chroma detail is exactly what pushes the chroma RD off - // DC_PRED. `noise` carries its own explicit seed (lavfi - // `gradients` ignores its seed; class [[seeded-fixture-not-reproducible]]). - let source = format!( - "mandelbrot=size={width}x{height}:start_scale={}:rate=25[a];\ - mandelbrot=size={width}x{height}:start_scale={}:rate=25[b];\ - [a][b]overlay=enable='gte(n,4)',noise=alls=12:allf=t+u:all_seed={seed}", - 5.0 - f64::from(attempt) * 0.06, - 0.9 + f64::from(attempt) * 0.11 - ); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-pix_fmt", - if bit_depth == 10 { - "yuv420p10le" - } else { - "yuv420p" - }, - "-strict", - "-1", - "-t", - "0.32", - "-f", - "yuv4mpegpipe", - "-strict", - "-1", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - // A coarser quantiser is what pushes the chroma RD to a cheap - // non-DC mode on a small block; sweep 12..40 (the low end is what - // lane-cdef's cq12 arm needs). - let cq = format!("--cq-level={}", 12 + (attempt % 5) * 7); - let depth_args: &[&str] = if bit_depth == 10 { - &["-b", "10", "--input-bit-depth=10"] - } else { - &[] - }; - let tiles = format!("--tile-columns={}", tile_columns - 1); - // The y4m goes through a FILE, not aomenc's stdin: this gate's - // stream is ~100 KB, bigger than a pipe buffer, so an aomenc that - // is still being fed on stdin blocks writing its stdout and the - // test blocks writing its stdin -- a hard deadlock (measured - // here, 3 min into attempt 0, class [[gate-loader-slurps-whole-file]]). - // The path is PID-keyed (class [[pid-keyed-temp-path]]). - let y4m_path = std::env::temp_dir().join(format!( - "ec-av1-uv8-{}-{bit_depth}-{tile_columns}-{seed}.y4m", - std::process::id() - )); - std::fs::write(&y4m_path, &y4m.stdout).expect("writing the y4m fixture"); - let child = Command::new(aomenc_path()) - .args(depth_args) - .args([ - "--codec=av1", - "--passes=1", - "--end-usage=q", - &cq, - "--cpu-used=0", - "--lag-in-frames=0", - "--auto-alt-ref=0", - "--kf-max-dist=9999", - "--kf-min-dist=9999", - "--threads=1", - "--row-mt=0", - &tiles, - "--enable-order-hint=0", - "--enable-warped-motion=0", - "--enable-obmc=0", - "--enable-masked-comp=0", - "--enable-interintra-comp=0", - "--enable-dist-wtd-comp=0", - "--enable-diff-wtd-comp=0", - "--enable-onesided-comp=0", - "--enable-interintra-wedge=0", - "--enable-smooth-interintra=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-cdef=0", - "--enable-restoration=0", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-ref-frame-mvs=0", - // Per-arm overrides go LAST (aomenc keeps the LAST - // occurrence of a repeated --enable-* flag). The three - // chroma intra tools this gate is about, plus the fences - // that keep the leaf's SIBLING refusals (its TX_4X4 - // split, a nonzero angle delta, sub-16 rect inter leaves) - // out of the way. - "--enable-cfl-intra=1", - "--enable-smooth-intra=1", - "--enable-paeth-intra=1", - "--enable-directional-intra=1", - "--enable-angle-delta=0", - "--enable-tx-size-search=0", - "--enable-rect-partitions=0", - "--min-partition-size=8", - "--max-partition-size=32", - "--obu", - "-o", - "-", - ]) - .arg(&y4m_path) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .spawn() - .expect("aomenc failed to start"); - let out = child.wait_with_output().expect("aomenc failed to run"); - let _ = std::fs::remove_file(&y4m_path); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let before = decode::intra_in_inter8_uv_hits(); - let frames = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{name} decode failed outright (seed {seed}): {msg}" - ); - refusals.push(format!("seed {seed}: {msg}")); - continue; - } - }; - let now = decode::intra_in_inter8_uv_hits(); - // class [[counter-from-refused-stream]]: per-attempt deltas, and - // only for an attempt that decoded to the end and is pixel- - // compared below. - let fired = (now.0 - before.0, now.1 - before.1, now.2 - before.2); - totals = (totals.0 + fired.0, totals.1 + fired.1, totals.2 + fired.2); - // class [[gate-skips-on-its-own-failure]]: a decode that succeeded - // is ALWAYS pixel-compared; the counter only decides whether the - // attempt counts as firing. - // lane-uv8 r3: every one of the three chroma classes this gate - // exists for (directional, smooth/paeth, CfL) must fire on the - // SAME pixel-compared attempt -- a sum-nonzero predicate would - // pass on an attempt that only ever hit DC-adjacent CfL. - let counted = fired.0 > 0 && fired.1 > 0 && fired.2 > 0; - if !counted { - uncounted_exact += 1; - refusals.push(format!( - "seed {seed}: decoded and pixel-compared, but no 8x8 intra leaf in an inter \ - frame carried a non-DC uv_mode" - )); - } - let ffmpeg_frames = if bit_depth == 10 { - ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count) - } else { - ffmpeg_decode_sequence(&stream, width, height, frame_count) - }; - assert_eq!(frames.len(), frame_count); - eprintln!( - "{name} seed={seed} {cq}: 8x8 intra-in-inter leaves with a non-DC uv_mode -- \ - directional {}, smooth/paeth {}, CfL {}", - fired.0, fired.1, fired.2 - ); - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - for (plane, (g, w)) in [ - ("Y", (&got.y, &want.y)), - ("U", (&got.u, &want.u)), - ("V", (&got.v, &want.v)), - ] { - let stride = if plane == "Y" { width } else { width / 2 }; - if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) { - eprintln!( - "{name} seed={seed}: frame {i} {plane} first diff at ({}, {}) got {} \ - want {} ({} samples differ)", - at % stride, - at / stride, - g[at], - w[at], - g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(), - ); - } - } - } - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})"); - assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})"); - assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})"); - } - if counted { - gate_buckets( - &name, - 1, - uncounted_exact, - refusals.len() - uncounted_exact as usize, - ); - return; - } - } - gate_buckets( - &name, - 0, - uncounted_exact, - refusals.len() - uncounted_exact as usize, - ); - panic!( - "{name} never observed a non-DC uv_mode on an 8x8 intra leaf in an inter frame \ - (totals dir/smooth/cfl {totals:?}):\n{}", - refusals.join("\n") - ); - } - - pub(super) fn tx_split_angle_in_inter8_gate(bit_depth: u32) { - let name = format!("tx_split_angle_in_inter8_gate({bit_depth})"); - if !have_ffmpeg() { - eprintln!("SKIP {name}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height, frame_count) = (192usize, 128usize, 6usize); - let mut refusals = Vec::new(); - let mut uncounted_exact = 0u32; - let mut counted_exact = 0u32; - let mut totals = (0usize, 0usize); - for attempt in 0..30u32 { - let seed = 42 + attempt; - // Same zoom + hard-cut fractal source the sibling uv_mode gate - // uses (a cut is what makes aomenc code INTRA blocks inside an - // inter frame); `noise` carries an explicit seed (class - // [[seeded-fixture-not-reproducible]]). - let source = format!( - "mandelbrot=size={width}x{height}:start_scale={}:rate=25[a];\ - mandelbrot=size={width}x{height}:start_scale={}:rate=25[b];\ - [a][b]overlay=enable='gte(n,3)',noise=alls=12:allf=t+u:all_seed={seed}", - 5.0 - f64::from(attempt) * 0.06, - 0.9 + f64::from(attempt) * 0.11 - ); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-pix_fmt", - if bit_depth == 10 { - "yuv420p10le" - } else { - "yuv420p" - }, - "-strict", - "-1", - "-t", - "0.24", - "-f", - "yuv4mpegpipe", - "-strict", - "-1", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let cq = format!("--cq-level={}", 12 + (attempt % 5) * 7); - let depth_args: &[&str] = if bit_depth == 10 { - &["-b", "10", "--input-bit-depth=10"] - } else { - &[] - }; - // The y4m goes through a PID-keyed FILE, never aomenc's stdin - // (pipe deadlock, class [[gate-loader-slurps-whole-file]]). - let y4m_path = std::env::temp_dir().join(format!( - "ec-av1-leaf8tx-{}-{bit_depth}-{seed}.y4m", - std::process::id() - )); - std::fs::write(&y4m_path, &y4m.stdout).expect("writing the y4m fixture"); - let child = Command::new(aomenc_path()) - .args(depth_args) - .args([ - "--codec=av1", - "--passes=1", - "--end-usage=q", - &cq, - "--cpu-used=0", - "--lag-in-frames=0", - "--auto-alt-ref=0", - "--kf-max-dist=9999", - "--kf-min-dist=9999", - "--threads=1", - "--row-mt=0", - "--tile-columns=0", - "--enable-order-hint=0", - "--enable-warped-motion=0", - "--enable-obmc=0", - "--enable-masked-comp=0", - "--enable-interintra-comp=0", - "--enable-dist-wtd-comp=0", - "--enable-diff-wtd-comp=0", - "--enable-onesided-comp=0", - "--enable-interintra-wedge=0", - "--enable-smooth-interintra=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-cdef=0", - "--enable-restoration=0", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-ref-frame-mvs=0", - // Per-arm overrides LAST (aomenc keeps the last - // occurrence of a repeated --enable-* flag). Rect - // partitions stay off so the leaf's unrelated sub-16 rect - // inter refusal never fires. - "--enable-rect-partitions=0", - "--enable-tx-size-search=1", - "--enable-angle-delta=1", - "--enable-directional-intra=1", - "--min-partition-size=8", - "--max-partition-size=32", - "--obu", - "-o", - "-", - ]) - // r1 diagnostic: EC_LEAF8TX_CONTROL=1 turns THIS lane's two - // tools back off (last occurrence of a repeated --enable-* - // wins), so any mismatch that survives is not this lane's. - .args(match std::env::var("EC_LEAF8TX_CONTROL").as_deref() { - Ok("angle") => vec!["--enable-tx-size-search=0", "--enable-angle-delta=1"], - Ok("tx") => vec!["--enable-tx-size-search=1", "--enable-angle-delta=0"], - Ok("tx8") => vec![ - "--enable-tx-size-search=1", - "--enable-angle-delta=0", - "--max-partition-size=8", - ], - Ok(_) => vec!["--enable-tx-size-search=0", "--enable-angle-delta=0"], - // Shipped recipe (lane-leaf8tx r4): BOTH of this lane's - // tools on -- the tx_depth split at an 8x8 intra-in-inter - // leaf is what the lifted refusal covers, so - // `--enable-tx-size-search=1` must survive the per-arm - // override (aomenc keeps the LAST occurrence). Odd - // attempts also cap the partition at 8x8, the shape that - // produces the 2x2 TX_4X4 grid most often. - Err(_) => { - if attempt % 2 == 1 { - vec![ - "--enable-tx-size-search=1", - "--enable-angle-delta=1", - "--max-partition-size=8", - ] - } else { - vec!["--enable-tx-size-search=1", "--enable-angle-delta=1"] - } - } - }) - .arg(&y4m_path) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .spawn() - .expect("aomenc failed to start"); - let out = child.wait_with_output().expect("aomenc failed to run"); - let _ = std::fs::remove_file(&y4m_path); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let before = ( - decode::intra_in_inter_split_tx_hits()[0], - decode::intra_in_inter8_angle_delta_y_hits(), - ); - let frames = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{name} decode failed outright (seed {seed}): {msg}" - ); - refusals.push(format!("seed {seed}: {msg}")); - continue; - } - }; - let now = ( - decode::intra_in_inter_split_tx_hits()[0], - decode::intra_in_inter8_angle_delta_y_hits(), - ); - let fired = (now.0 - before.0, now.1 - before.1); - totals = (totals.0 + fired.0, totals.1 + fired.1); - // Both lifted capabilities must fire on the SAME pixel-compared - // attempt. - let counted = fired.1 > 0; - if !counted { - uncounted_exact += 1; - refusals.push(format!( - "seed {seed}: decoded and pixel-compared, but split-tx {} / angle-delta {} \ - 8x8 intra-in-inter leaves", - fired.0, fired.1 - )); - } - let ffmpeg_frames = if bit_depth == 10 { - ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count) - } else { - ffmpeg_decode_sequence(&stream, width, height, frame_count) - }; - assert_eq!(frames.len(), frame_count); - eprintln!( - "{name} seed={seed} {cq}: 8x8 intra-in-inter leaves with tx_depth=1 {}, with a \ - nonzero angle_delta_y {} (split-tx per size 8/16/32/64 {:?})", - fired.0, - fired.1, - decode::intra_in_inter_split_tx_hits() - ); - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - for (plane, (g, w)) in [ - ("Y", (&got.y, &want.y)), - ("U", (&got.u, &want.u)), - ("V", (&got.v, &want.v)), - ] { - let stride = if plane == "Y" { width } else { width / 2 }; - if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) { - eprintln!( - "{name} seed={seed}: frame {i} {plane} first diff at ({}, {}) got {} \ - want {} ({} samples differ)", - at % stride, - at / stride, - g[at], - w[at], - g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(), - ); - } - } - } - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})"); - assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})"); - assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})"); - } - if counted { - counted_exact += 1; - } - } - // lane-leaf8tx r4: continue-and-sweep -- every arm is encoded, - // decoded and pixel-compared on every plane of every decode-order - // frame above; the counters are asserted ONCE here. A decode error or - // a mismatch is a failure, never a SKIP, and `uncounted_exact` - // (decoded + compared but neither capability fired) is the - // out-of-scope-mismatch bucket that the sweep tolerates only while at - // least one attempt did fire. - gate_buckets( - &name, - counted_exact, - uncounted_exact, - refusals.len() - uncounted_exact as usize, - ); - assert!( - totals.0 > 0, - "{name}: no decoded+compared attempt carried an 8x8 intra-in-inter leaf with \ - tx_depth split to 4x4 (split-tx per size {:?}, angle-delta {}):\n{}", - decode::intra_in_inter_split_tx_hits(), - totals.1, - refusals.join("\n") - ); - assert!( - totals.1 > 0, - "{name}: no decoded+compared attempt carried a nonzero angle_delta_y on an 8x8 \ - intra-in-inter leaf (split-tx {}):\n{}", - totals.0, - refusals.join("\n") - ); - } - - /// As above, but a multi-frame inter sequence -- `--lag-in-frames=0 - /// --auto-alt-ref=0` keep every non-key frame a simple forward - /// single-`LAST_FRAME` P frame (no alt-ref/backward reference this - /// decoder's inter path does not model), `--kf-max-dist` past the clip's - /// own length keeps frame 0 the only key frame. - /// lane-inter8 r1: the inter tile path's SB-level `PARTITION_NONE` -- a - /// whole 64x64 superblock coded as ONE inter block, which is what aomenc - /// picks for static content and which this decoder refused by name - /// ("an inter SB-level partition type other than SPLIT") until this - /// round. HARD-asserts [`decode::inter_sb_none_hits`] moved (the arm - /// really fired, class refusal-lifted-without-a-gate) and every frame is - /// pixel-exact vs ffmpeg; a decode error is a FAILURE here, never a SKIP - /// (class gate-skips-on-its-own-failure). - /// lane-inter8 r1: generalised so the same recipe can target a deeper - /// level of the inter partition tree -- `min_part` is aomenc's - /// `--min-partition-size`, and `hits`/`what` name the counter that proves - /// the arm under test really fired. - #[track_caller] - // Signature mirrors the spec's per-call inputs; a parameter struct would only move them. - #[allow(clippy::too_many_arguments)] - pub(super) fn inter_sb_none_gate( - name: &str, - ten_bit: bool, - min_part: &str, - max_part: &str, - hits: fn() -> usize, - what: &str, - // lane-inter8 r3: extra aomenc flags + the frame width they need. - // `--tile-columns=1` needs a frame at least two superblocks wide or - // aomenc silently codes one tile column and the arm is vacuous. - extra: &[&str], - width: usize, - // lane-interp3 r1: sequence length -- a compound block needs several - // already-coded references, which a 4-frame sequence never has. - frame_count: usize, - // lane-av1dualfilter10: the encoded stream, so a caller can assert on - // the PARSED sequence header (bit depth, `enable_dual_filter`) rather - // than on the flag it asked for. Empty on the SKIP paths below. - ) -> Vec { - if !have_ffmpeg() { - eprintln!("SKIP {name}: no ffmpeg"); - return Vec::new(); - } - if !have_aomenc() { - eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display()); - return Vec::new(); - } - let height = 64usize; - let duration = format!("{:.2}", frame_count as f64 / 25.0); - // A deterministic synthetic source with real motion (a static source - // codes every inter frame as skip and never exercises the residual - // path); bounded with `-t` (class gate-loader-slurps-whole-file). - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &format!("mandelbrot=size={width}x{height}:rate=25"), - "-t", - &duration, - "-pix_fmt", - if ten_bit { "yuv420p10le" } else { "yuv420p" }, - // y4m calls 10-bit unofficial (same as the 10-bit key-frame - // gate's own fixture). - "-strict", - "-1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "{name}: ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let mut args: Vec = [ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=40", - "--cpu-used=0", - "--lag-in-frames=0", - "--auto-alt-ref=0", - "--kf-max-dist=1000", - // No cross-frame CDF forwarding in this fixture (see the - // deblocking gate's own note). - "--error-resilient=1", - // This gate targets the SB-level NONE arm only: rect/AB/1-to-4 - // partitions and sub-16x16 splits stay off so a failure here - // cannot be another lane's missing arm. - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-tx-size-search=0", - "--enable-cdef=0", - "--enable-restoration=0", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - "--enable-ref-frame-mvs=0", - "--obu", - "-o", - "-", - "-", - ] - .iter() - .map(|s| (*s).to_string()) - .collect(); - for e in extra { - args.insert(1, (*e).to_string()); - } - args.insert(1, format!("--min-partition-size={min_part}")); - args.insert(1, format!("--max-partition-size={max_part}")); - if ten_bit { - args.insert(1, "--input-bit-depth=10".to_string()); - args.insert(1, "--bit-depth=10".to_string()); - } - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "{name}: aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let before = hits(); - let frames = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => { - let pin = std::env::temp_dir().join(format!("{name}-refused.obu")); - crate::dumpio::pin("TEST_PIN", &pin, &stream); - panic!( - "{name}: decode_stream refused a real aomenc stream: {e} (pinned at {})", - pin.display() - ); - } - }; - assert!( - hits() > before, - "{name}: no {what} fired -- this gate proves nothing" - ); - let ffmpeg_frames = if ten_bit { - ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count) - } else { - ffmpeg_decode_sequence(&stream, width, height, frame_count) - }; - assert_eq!(frames.len(), frame_count, "{name}: frame count"); - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - if got.y != want.y || got.u != want.u || got.v != want.v { - let pin = std::env::temp_dir().join(format!("{name}-mismatch.obu")); - crate::dumpio::pin("TEST_PIN", &pin, &stream); - panic!( - "{name}: frame {i} mismatch vs ffmpeg -- stream pinned at {}", - pin.display() - ); - } - } - stream - } - - /// lane-eobc1 r1: an INTER sequence whose CHROMA coefficient blocks come - /// off the class-1 (`TX_CLASS_HORIZ`/`VERT`) `eob_pt` row. Chroma codes - /// no `tx_type` symbol of its own -- it inherits the colocated luma type - /// (`av1_get_tx_type`, `blockd.h:1291`) -- so an 8x8 inter leaf whose - /// luma picks `H_*`/`V_*` puts its 4x4 chroma on a CDF row this crate - /// wired for only some sizes until this round (`eob_pt_class1: None` in - /// 9 of 16 `TxbSet` arms, chroma 4x4/8x8 among them). - /// - /// The full tx set stays on (no `--reduced-tx-type-set=1`) and - /// `--enable-flip-idtx=1` is asked for explicitly; the sinusoidal-stripe - /// luma of the `tx_class1` key-frame gate is what actually resolves 1D - /// types, and the temporally-moving chroma ramp keeps chroma out of - /// `all_zero` so it has an `eob` to read at all. Attempts sweep cq and - /// stripe period; a run counts only when - /// [`decode::chroma_eob_class1_hits`] moved, and every shown frame is - /// compared pixel-exact vs ffmpeg (a decode error is a FAILURE, never a - /// SKIP -- class gate-skips-on-its-own-failure). - pub(super) fn chroma_class1_eob_gate(name: &str, ten_bit: bool) { - if !have_ffmpeg() { - eprintln!("SKIP {name}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height, frame_count) = (64usize, 64usize, 4usize); - let mut refusals = Vec::new(); - for attempt in 0..12u32 { - let cq = 28 + (attempt % 4) * 10; - let period = [4u32, 6, 8][(attempt as usize / 4) % 3]; - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &format!("testsrc2=size={width}x{height}:rate=25"), - "-vf", - &format!( - "geq=lum='128+80*sin(2*PI*Y/{period})':cb='128+60*sin(2*PI*(X+8*T)/{period})':cr='128+60*sin(2*PI*(Y+8*T)/{period})',noise=alls=6:allf=t:all_seed=7" - ), - "-t", - "0.16", - "-pix_fmt", - if ten_bit { "yuv420p10le" } else { "yuv420p" }, - "-strict", - "-1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "{name}: ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let mut args: Vec = [ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cpu-used=0", - "--lag-in-frames=0", - "--auto-alt-ref=0", - "--kf-max-dist=1000", - "--error-resilient=1", - "--enable-flip-idtx=1", - "--reduced-tx-type-set=0", - "--min-partition-size=8", - "--max-partition-size=16", - // Motion tools this decoder refuses by name, kept off so a - // refusal here can only be about the coefficient path. - "--enable-global-motion=0", - "--enable-warped-motion=0", - "--enable-obmc=0", - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-tx-size-search=0", - "--enable-cdef=0", - "--enable-restoration=0", - "--loopfilter-control=0", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - "--enable-ref-frame-mvs=0", - "--obu", - "-o", - "-", - "-", - ] - .iter() - .map(|s| (*s).to_string()) - .collect(); - args.insert(1, format!("--cq-level={cq}")); - if ten_bit { - args.insert(1, "--input-bit-depth=10".to_string()); - args.insert(1, "--bit-depth=10".to_string()); - } - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "{name}: aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let before = decode::chroma_eob_class1_hits(); - let frames = match decode_stream(&stream) { - Ok(frames) => frames, - // A named refusal ("unsupported: ...") is another lane's arm - // and moves this attempt on; anything else is a real decode - // failure and fails the gate on the spot. - Err(e) if e.to_string().contains("unsupported") => { - refusals.push(format!("cq={cq} period={period}: {e}")); - continue; - } - Err(e) => { - let pin = std::env::temp_dir().join(format!("{name}-refused.obu")); - crate::dumpio::pin("TEST_PIN", &pin, &stream); - panic!( - "{name}: decode_stream failed on a real aomenc stream (cq={cq} period={period}): {e} (pinned at {})", - pin.display() - ); - } - }; - if decode::chroma_eob_class1_hits() == before { - refusals.push(format!( - "cq={cq} period={period}: decoded, but no chroma block read a class-1 eob_pt row" - )); - continue; - } - let ffmpeg_frames = if ten_bit { - ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count) - } else { - ffmpeg_decode_sequence(&stream, width, height, frame_count) - }; - assert_eq!(frames.len(), frame_count, "{name}: frame count"); - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - if got.y != want.y || got.u != want.u || got.v != want.v { - let pin = std::env::temp_dir().join(format!("{name}-mismatch.obu")); - crate::dumpio::pin("TEST_PIN", &pin, &stream); - panic!( - "{name}: frame {i} mismatch vs ffmpeg (cq={cq} period={period}) -- stream pinned at {}", - pin.display() - ); - } - } - return; - } - panic!("{name}: no attempt fired a class-1 chroma eob: {refusals:?}"); - } - - /// lane-av1refs's decisive gate for the 5 references widened past - /// `LAST_FRAME`/`GOLDEN_FRAME`: same envelope and pin-on-mismatch - /// pattern as - /// [`a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact`], - /// generalised over `(target_ref, extra_args, frame_count)` so each of - /// `LAST2`/`LAST3`/`BWDREF`/`ALTREF2`/`ALTREF` gets its own attempt pool - /// and its own proof that `decode::ref_hits(target_ref)` -- not just - /// `non_last_ref_hits`, which cannot distinguish one reference from - /// another -- actually advanced. `--max-reference-frames=3 - /// --reduced-reference-set=1` (the golden gate's own narrowing) is - /// DROPPED here: both suppress exactly the references this gate needs - /// aomenc's RD to reach. - // Signature mirrors the spec's per-call inputs; a parameter struct would only move them. - #[allow(clippy::too_many_arguments)] - pub(super) fn a_real_aomenc_single_ref_gate( - gate_name: &str, - target_ref: i8, - target_ref_name: &str, - extra_args: &[&str], - width: usize, - height: usize, - frame_count: usize, - attempts: u32, - ) { - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {gate_name}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {gate_name}: no aomenc at {}", aomenc_path().display()); - return; - } - let mut refusals = Vec::new(); - let mut never_fired = 0u32; - for attempt in 0..attempts { - let seed = 42 + attempt % 40; - let duration = frame_count as f64 / 25.0; - let source = - gradients_source(seed, width, height, &format!("duration={duration}:rate=25")); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-pix_fmt", - "yuv420p", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let mut args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=55", - "--cpu-used=0", - "--kf-max-dist=1000", - "--threads=1", - "--row-mt=0", - "--enable-warped-motion=0", - "--enable-obmc=0", - "--enable-masked-comp=0", - "--enable-interintra-comp=0", - "--enable-dist-wtd-comp=0", - "--enable-diff-wtd-comp=0", - "--enable-onesided-comp=0", - "--enable-interintra-wedge=0", - "--enable-smooth-interintra=0", - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-tx-size-search=0", - "--enable-cdef=0", - "--enable-restoration=0", - "--max-partition-size=32", - "--min-partition-size=32", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - // use_ref_frame_mvs (temporal MV projection) is unimplemented in - // mvstack; leaving it on silently desyncs symbols on inter frames. - "--enable-ref-frame-mvs=0", - "--obu", - "-o", - "-", - "-", - ]; - // extra_args goes right before the trailing "-o", "-", "-" triple. - let tail = args.split_off(args.len() - 3); - args.extend_from_slice(extra_args); - args.extend_from_slice(&tail); - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let before = decode::ref_hits(target_ref); - let frames = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{gate_name} failed outright (seed {seed}): {msg}" - ); - refusals.push(format!("seed {seed}: {msg}")); - continue; - } - Ok(frames) => frames, - }; - // class [[gate-skips-on-its-own-failure]]: a decode that succeeded - // is ALWAYS pixel-compared below; the hit counter only decides whether - // the attempt counts toward the firing total. - let counted = decode::ref_hits(target_ref) != before; - if !counted { - never_fired += 1; - } - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count); - assert_eq!(frames.len(), frame_count); - let mismatched = frames - .iter() - .zip(&ffmpeg_frames) - .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); - if mismatched - && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") { - std::fs::write(&path, &stream).expect("writing pinned stream"); - eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}"); - } - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!( - got.y, want.y, - "{gate_name} frame {i} luma vs ffmpeg (seed {seed})" - ); - assert_eq!( - got.u, want.u, - "{gate_name} frame {i} U vs ffmpeg (seed {seed})" - ); - assert_eq!( - got.v, want.v, - "{gate_name} frame {i} V vs ffmpeg (seed {seed})" - ); - } - // lane-hidden r2 (class gate-blind-to-hidden-frames): the same - // stream again, comparing EVERY decode-order frame -- the hidden - // (show_frame == 0) alt-ref frames the ffmpeg compare above - // cannot see, because both sides of it emit shown frames only. - let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, gate_name); - eprintln!( - "{gate_name} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \ - {hidden_n} hidden, all pixel-exact vs the oracle" - ); - // lane-hidden r2 SECOND ARM (the recipe above is untouched): - // libaom's temporal alt-ref filter absorbs this recipe's hidden - // frames, so the compare above is vacuous -- re-encode the same - // fixture with --arnr-maxframes=0 and compare THOSE. - if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(gate_name, &y4m.stdout, &args) { - eprintln!( - "{gate_name} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \ - decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle" - ); - } - if counted { - eprintln!( - "{gate_name} FIRING seed {seed}: {target_ref_name} hits advanced by {}", - decode::ref_hits(target_ref) - before - ); - gate_buckets(gate_name, 1, never_fired, refusals.len()); - return; - } - } - gate_buckets(gate_name, 0, never_fired, refusals.len()); - eprintln!( - "SKIP {gate_name}: {never_fired} attempts decoded but never fired {target_ref_name}, \ - and every other attempt hit a named refusal:\n{}", - refusals.join("\n") - ); - } - - /// lane-gmaffine r1: the two 8x8-LEAF motion gates. `decode_inter_block8` - /// is a separate function from [`decode_inter_block`], and until this - /// round it refused both `GLOBALMV` ("GLOBALMV (round 3)") and - /// `WARPED_CAUSAL` at that size while the 16x16+ leaf had implemented - /// both for rounds. The reason no earlier gate caught it: the existing - /// 8x8 OBMC gate clamps `--max-partition-size=32` and aomenc's RD then - /// never splits down to a clean 8x8 leaf (that gate has never fired in - /// 80 attempts). `--min-partition-size=8 --max-partition-size=8` removes - /// the choice entirely -- every inter leaf in the stream IS an 8x8 one, - /// so the leaf path is exercised by construction rather than by luck. - /// - /// Content is the affine gate's rotating/zooming mandelbrot (global - /// motion the encoder can actually model), and the hit counters - /// (`globalmv_hits_8` / `warp_hits_8`) are 8x8-leaf-specific: a - /// 16x16-leaf GLOBALMV or warp cannot satisfy them. - pub(super) fn run_8x8_leaf_motion_gate(name: &str, global_motion: bool, counter: fn() -> usize) { - // 72x64: `decode_inter_block8` is reached ONLY through the - // true-edge-straddling 16x16 path (an interior 16x16 - // PARTITION_SPLIT is still refused by name), so the frame is 8 - // luma columns wider than its last whole superblock -- every 16x16 - // block in that right-hand strip is cut on ONE axis and decodes as - // four 8x8 leaves by construction. `--min-partition-size=16` keeps - // the interior out of the still-refused sub-16x16 case. - let (width, height, frame_count) = (64usize, 64usize, 24usize); - let duration = frame_count as f64 / 25.0; - // The encoder's own RD still chooses WHICH 8x8 leaf codes GLOBALMV / - // WARPED_CAUSAL, and at some quantisers it picks a rect partition at - // 16x16 (still refused) or a non-LAST reference (still refused at the - // 8x8 leaf) before ever reaching one. So sweep a few quantisers and - // require at least one attempt, at each depth, that BOTH decodes - // pixel-exact AND fires the counter -- a refusing attempt is recorded, - // never a pass (class `gate-skips-on-its-own-failure`). - let mut fired_any = [false; 2]; - let mut notes: Vec = Vec::new(); - for (di, depth) in [8u32, 10u32].into_iter().enumerate() { - for cq in [32u32, 45, 55] { - let cq_arg = format!("--cq-level={cq}"); - let max_part_arg = format!( - "--max-partition-size={}", - std::env::var("EC_8X8_MAXPART").unwrap_or_else(|_| "8".into()) - ); - let source = format!( - "mandelbrot=size=96x96:rate=25,rotate=a=0.12*t:c=black,\ - scale=w='ceil(96*(1+0.03*n)/2)*2':h=96:eval=frame,crop={width}:{height}" - ); - let pix_fmt = if depth == 10 { - "yuv420p10le" - } else { - "yuv420p" - }; - let mut ff_args: Vec<&str> = vec![ - "-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", pix_fmt, - ]; - if depth == 10 { - ff_args.extend(["-strict", "-1"]); - } - let duration_arg = duration.to_string(); - ff_args.extend(["-t", &duration_arg, "-f", "yuv4mpegpipe", "-"]); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args(&ff_args) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let bit_depth = format!("--bit-depth={depth}"); - let input_bit_depth = format!("--input-bit-depth={depth}"); - let gm_arg = format!("--enable-global-motion={}", u8::from(global_motion)); - let warp_arg = format!("--enable-warped-motion={}", u8::from(!global_motion)); - let args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - &cq_arg, - "--cpu-used=0", - "--kf-max-dist=1000", - "--threads=1", - "--row-mt=0", - "--auto-alt-ref=0", - "--lag-in-frames=0", - "--enable-fwd-kf=0", - "--enable-order-hint=1", - &gm_arg, - &warp_arg, - "--enable-obmc=0", - "--tune-content=default", - "--enable-masked-comp=0", - "--enable-interintra-comp=0", - "--enable-onesided-comp=0", - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-tx-size-search=0", - "--enable-cdef=0", - "--enable-restoration=0", - &max_part_arg, - "--min-partition-size=8", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - "--enable-ref-frame-mvs=0", - &bit_depth, - &input_bit_depth, - "--obu", - "-o", - "-", - "-", - ]; - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let before = counter(); - let frames = match decode_stream(&stream) { - Ok(f) => f, - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{name} ({depth}-bit, cq {cq}) failed outright: {msg}" - ); - notes.push(format!("{depth}-bit cq {cq}: {msg}")); - continue; - } - }; - let ffmpeg_frames = if depth == 10 { - ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count) - } else { - ffmpeg_decode_sequence(&stream, width, height, frame_count) - }; - assert_eq!(frames.len(), frame_count); - let hits = counter() - before; - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!(got.y, want.y, "{name} {depth}-bit frame {i} luma vs ffmpeg"); - assert_eq!(got.u, want.u, "{name} {depth}-bit frame {i} U vs ffmpeg"); - assert_eq!(got.v, want.v, "{name} {depth}-bit frame {i} V vs ffmpeg"); - } - if hits == 0 { - notes.push(format!( - "{depth}-bit cq {cq}: {frame_count} frames pixel-exact but 0 8x8-leaf hits" - )); - continue; - } - fired_any[di] = true; - eprintln!( - "{name}: {depth}-bit cq {cq}, {frame_count} frames pixel-exact, 8x8 hits={hits}" - ); - } - } - assert!( - fired_any[0] && fired_any[1], - "{name}: no attempt both decoded pixel-exact and fired the 8x8 leaf \ - (8-bit fired {}, 10-bit fired {}):\n{}", - fired_any[0], - fired_any[1], - notes.join("\n") - ); - } diff --git a/crates/ec-av1/src/stream/tests/gates_b.rs b/crates/ec-av1/src/stream/tests/gates_b.rs deleted file mode 100644 index 1a92b06b..00000000 --- a/crates/ec-av1/src/stream/tests/gates_b.rs +++ /dev/null @@ -1,2804 +0,0 @@ -use super::*; -use super::support::*; -use super::gates_a::*; - - /// lane-cwarp r1: a real `--enable-global-motion=1 --enable-dist-wtd-comp=1` - /// stream over a rotating/zooming source, so a `GLOBAL_GLOBALMV` compound - /// block lands under a ROTZOOM/AFFINE model and each of its two references - /// is predicted through its OWN global warp - /// (`crate::warp::warp_affine_compound`, libaom `av1_warp_plane` with - /// `conv_params->is_compound`) rather than translationally. Before r1 that - /// path was SILENTLY WRONG -- no refusal named it, both taps went through - /// `mc::predict_compound_intermediate`. `compound_warp_hits() > 0` is a - /// hard assert: a run where the encoder never emitted one proves nothing. - /// A decode error or a pixel mismatch is a FAILURE, never a skip. - pub(super) fn run_compound_global_warp_gate(name: &str, bd: u32, min_part: u32, leaf8_assert: bool) { - let _gate_lock = lock_gate_counters(); - assert!(have_ffmpeg(), "{name}: ffmpeg required"); - assert!( - have_aomenc(), - "{name}: no aomenc at {}", - aomenc_path().display() - ); - let (width, height, frame_count) = (64usize, 64usize, 24usize); - let before = crate::decode::compound_warp_hits(); - let before8 = crate::decode::compound_warp_hits_8(); - let mut matched = 0u32; - let mut named_refusals = 0u32; - let mut attempts = 0u32; - for cq in [32u32, 45, 55] { - for (i, rate) in [0.010f64, 0.022].iter().enumerate() { - attempts += 1; - let duration = frame_count as f64 / 25.0; - // A rotation about the frame centre plus a slow zoom is what - // aomenc's global-motion search fits a ROTZOOM/AFFINE model to; - // mandelbrot gives it real, non-flat texture to track. - let source = format!( - "mandelbrot=size={w}x{h}:rate=25:start_x={sx}:start_y=-0.4,\ - rotate=a={rate}*n:ow={w}:oh={h}:c=black,scale={width}:{height}", - w = width * 2, - h = height * 2, - sx = -0.6 + 0.01 * (i as f64), - ); - let pix_fmt = match bd { - 8 => "yuv420p", - 10 => "yuv420p10le", - _ => "yuv420p12le", - }; - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-t", - &duration.to_string(), - "-pix_fmt", - pix_fmt, - "-strict", - "-1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let cq_arg = format!("--cq-level={cq}"); - let (in_depth_arg, depth_arg) = ( - format!("--input-bit-depth={bd}"), - format!("--bit-depth={bd}"), - ); - let mut args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - &cq_arg, - "--cpu-used=0", - "--kf-max-dist=1000", - "--threads=1", - "--row-mt=0", - "--auto-alt-ref=1", - "--lag-in-frames=25", - "--enable-fwd-kf=0", - "--enable-order-hint=1", - // the two tools this gate exists for - "--enable-global-motion=1", - "--enable-dist-wtd-comp=1", - "--enable-warped-motion=1", - "--enable-obmc=1", - "--enable-masked-comp=1", - "--enable-onesided-comp=0", - "--enable-interintra-comp=1", - "--enable-interintra-wedge=0", - "--enable-smooth-interintra=1", - "--tune-content=default", - // partition/intra tools this decoder does not code yet -- - // same exclusion list every compound gate carries. - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-tx-size-search=0", - "--enable-cdef=0", - "--enable-restoration=0", - "--max-partition-size=32", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - "--enable-ref-frame-mvs=0", - ]; - let min_part_arg = format!("--min-partition-size={min_part}"); - args.push(min_part_arg.as_str()); - if bd != 8 { - args.extend_from_slice(&[in_depth_arg.as_str(), depth_arg.as_str()]); - } - args.extend_from_slice(&["--obu", "-o", "-", "-"]); - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let frames = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{name} failed outright, not a named refusal (cq {cq}): {msg}" - ); - assert!( - !msg.contains("warp"), - "{name} refused on warp (cq {cq}) -- warp decode is ported: {msg}" - ); - named_refusals += 1; - eprintln!("{name} cq {cq} rate {rate} refusal: {msg}"); - continue; - } - Ok(frames) => frames, - }; - let want = match bd { - 8 => ffmpeg_decode_sequence(&stream, width, height, frame_count), - 10 => ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count), - _ => ffmpeg_decode_sequence_12bit(&stream, width, height, frame_count), - }; - assert_eq!(frames.len(), frame_count); - if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") - && frames - .iter() - .zip(&want) - .any(|(g, w)| g.y != w.y || g.u != w.u || g.v != w.v) - { - std::fs::write(&path, &stream).expect("writing pinned stream"); - eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (cq {cq}) to {path}"); - } - for (i, (got, want)) in frames.iter().zip(&want).enumerate() { - assert_eq!(got.y, want.y, "{name} frame {i} luma vs ffmpeg (cq {cq})"); - assert_eq!(got.u, want.u, "{name} frame {i} U vs ffmpeg (cq {cq})"); - assert_eq!(got.v, want.v, "{name} frame {i} V vs ffmpeg (cq {cq})"); - } - matched += 1; - } - } - let hits = crate::decode::compound_warp_hits() - before; - let hits8 = crate::decode::compound_warp_hits_8() - before8; - eprintln!( - "{name}: {matched}/{attempts} pixel-exact, {named_refusals} named refusals, \ - compound_warp_hits={hits} compound_warp_hits_8={hits8}" - ); - if leaf8_assert { - assert!( - hits8 > 0, - "{name}: no 8x8 COMPOUND leaf was predicted through a per-ref global \ - warp ({hits} bigger compound warp blocks, {matched} matches, \ - {named_refusals} refusals of {attempts}) -- gate vacuous" - ); - } else { - assert!( - hits > 0, - "{name}: no compound block was predicted through a per-ref global warp \ - ({matched} matches, {named_refusals} refusals of {attempts}) -- gate vacuous" - ); - } - assert!( - matched > 0, - "{name}: every attempt refused -- no pixel comparison ran" - ); - } - - /// lane-fimv r1 (class `wrong-alphabet-same-value`): libaom - /// `motion_mode_allowed` (blockd.h ~1484) only returns `WARPED_CAUSAL` - /// when `!xd->cur_frame_force_integer_mv`, so on a frame whose header set - /// `force_integer_mv` an otherwise warp-eligible block reads the 2-symbol - /// `obmc_cdf`, not the 3-symbol `motion_mode_cdf`. This decoder read the - /// 3-symbol alphabet there (silent tile desync, no refusal named it). - /// - /// The fixture is screen content that is mostly static with only - /// whole-pixel motion, which is exactly what aomenc's own - /// `av1_is_integer_mv` (`encoder_utils.c:1357`, >=80% of blocks matching - /// their collocated block) needs to set `cur_frame_force_integer_mv` - /// under `--tune-content=screen` (seq `force_integer_mv == 2`, adaptive: - /// `encoder.c:4171`). Two hard asserts, both class - /// `gate-blind-to-feature`: at least one decoded frame header carried - /// `force_integer_mv = 1`, and at least one block took the 2-symbol - /// alphabet where `allow_warped_motion = 1` and `num_proj_ref >= 1` would - /// have picked the 3-symbol one. A decode error or a pixel mismatch is a - /// FAILURE, never a skip. - #[track_caller] - pub(super) fn run_fimv_motion_mode_gate(name: &str, ten_bit: bool) { - let _gate_lock = lock_gate_counters(); - assert!(have_ffmpeg(), "{name}: ffmpeg required"); - assert!( - have_aomenc(), - "{name}: no aomenc at {}", - aomenc_path().display() - ); - let (width, height, frame_count) = (64usize, 64usize, 20usize); - let fimv_frames_before = crate::decode::fimv_frame_hits(); - let alphabet_before = crate::decode::fimv_alphabet_hits(); - let mut matched = 0u32; - let mut named_refusals = 0u32; - let mut attempts = 0u32; - let mut refusals = Vec::new(); - for cq in [32u32, 45, 55] { - for step in [4u32, 8] { - attempts += 1; - // lane-fimv r1: per-attempt snapshots. The aggregate - // assertions below are satisfied by a single lucky cq/step - // cell; these prove EVERY attempt that decoded and - // pixel-compared really carried the header state and the - // forced alphabet under test (class gate-blind-to-feature). - let attempt_fimv_before = crate::decode::fimv_frame_hits(); - let attempt_alphabet_before = crate::decode::fimv_alphabet_hits(); - let duration = frame_count as f64 / 25.0; - // Flat screen-content tiles with hard edges, translating by a - // whole number of pixels per frame: static enough for - // `av1_is_integer_mv`, moving enough for a real inter block - // with overlappable neighbours. - let source = format!( - "color=c=black:s={width}x{height}:r=25,\ - drawbox=x='8+{step}*mod(trunc(t*25)\\,3)':y=8:w=20:h=20:color=white:t=fill,\ - drawbox=x=36:y='6+{step}*mod(trunc(t*25)+1\\,3)':w=16:h=16:color=0x808080:t=fill,\ - drawbox=x=4:y=44:w=56:h=12:color=0xC0C0C0:t=fill" - ); - let pix_fmt = if ten_bit { "yuv420p10le" } else { "yuv420p" }; - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-t", - &duration.to_string(), - "-pix_fmt", - pix_fmt, - "-strict", - "-1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let cq_arg = format!("--cq-level={cq}"); - let mut args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - &cq_arg, - "--cpu-used=0", - "--kf-max-dist=1000", - "--threads=1", - "--row-mt=0", - // single reference only: the 10-bit compound MC defect - // (see `a_real_compound_global_warp_10bit_stream_...`) - // is unrelated to this lane and would mask it. - "--auto-alt-ref=0", - "--lag-in-frames=0", - "--enable-fwd-kf=0", - "--enable-order-hint=1", - // the flag combination this gate exists for: warp allowed - // by the header, OBMC available, global motion off (so the - // GLOBALMV suppression is not what picks the alphabet). - "--tune-content=screen", - "--enable-warped-motion=1", - "--enable-obmc=1", - "--enable-global-motion=0", - "--enable-masked-comp=0", - "--enable-onesided-comp=0", - "--enable-interintra-comp=0", - "--enable-interintra-wedge=0", - "--enable-smooth-interintra=0", - "--enable-dist-wtd-comp=0", - // partition/intra tools this decoder does not code yet -- - // the same exclusion list every inter gate here carries. - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-tx-size-search=0", - "--enable-cdef=0", - "--enable-restoration=0", - "--max-partition-size=32", - "--min-partition-size=32", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - "--enable-ref-frame-mvs=0", - ]; - if ten_bit { - args.extend_from_slice(&["--input-bit-depth=10", "--bit-depth=10"]); - } - args.extend_from_slice(&["--obu", "-o", "-", "-"]); - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let frames = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{name} failed outright (cq {cq} step {step}): {msg}" - ); - named_refusals += 1; - refusals.push(format!("cq {cq} step {step}: {msg}")); - continue; - } - Ok(frames) => frames, - }; - let want = if ten_bit { - ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count) - } else { - ffmpeg_decode_sequence(&stream, width, height, frame_count) - }; - assert_eq!(frames.len(), frame_count); - if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") - && frames - .iter() - .zip(&want) - .any(|(g, w)| g.y != w.y || g.u != w.u || g.v != w.v) - { - std::fs::write(&path, &stream).expect("writing pinned stream"); - eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (cq {cq}) to {path}"); - } - for (i, (got, want)) in frames.iter().zip(&want).enumerate() { - assert_eq!( - got.y, want.y, - "{name} frame {i} luma vs ffmpeg (cq {cq} step {step})" - ); - assert_eq!( - got.u, want.u, - "{name} frame {i} U vs ffmpeg (cq {cq} step {step})" - ); - assert_eq!( - got.v, want.v, - "{name} frame {i} V vs ffmpeg (cq {cq} step {step})" - ); - } - assert!( - crate::decode::fimv_frame_hits() > attempt_fimv_before, - "{name} (cq {cq} step {step}): decoded and compared all \ - frames but no frame header had force_integer_mv=1 -- \ - this attempt is vacuous" - ); - assert!( - crate::decode::fimv_alphabet_hits() > attempt_alphabet_before, - "{name} (cq {cq} step {step}): no block was forced onto the \ - 2-symbol obmc alphabet by force_integer_mv while \ - allow_warped_motion=1 and num_proj_ref>=1 -- this attempt \ - is vacuous" - ); - matched += 1; - } - } - let fimv_frames = crate::decode::fimv_frame_hits() - fimv_frames_before; - let alphabet = crate::decode::fimv_alphabet_hits() - alphabet_before; - eprintln!( - "{name}: {matched}/{attempts} pixel-exact, {named_refusals} named refusals, \ - force_integer_mv frames={fimv_frames}, forced-2-symbol blocks={alphabet}\n{}", - refusals.join("\n") - ); - assert!( - matched > 0, - "{name}: every attempt refused -- no pixel comparison ran" - ); - assert!( - fimv_frames > 0, - "{name}: no decoded frame header had force_integer_mv=1 \ - ({matched} matches of {attempts}) -- gate vacuous" - ); - assert!( - alphabet > 0, - "{name}: no block read the 2-symbol obmc alphabet where \ - allow_warped_motion=1 and num_proj_ref>=1 would have picked the \ - 3-symbol motion_mode alphabet -- gate vacuous" - ); - } - - /// lane-mcomp64 r1: at 64x64 `av1_is_wedge_used` is false - /// (`av1_wedge_params_lookup[BLOCK_64X64].wedge_types == 0`), so libaom's - /// `read_compound_type` codes NO `compound_type` symbol and INFERS - /// `COMPOUND_DIFFWTD`; only the 1-bit `mask_type` literal follows. This - /// decoder used to refuse such a block by name ("a masked compound 64x64 - /// inter block..."), because reading the symbol would have desynced. - /// - /// The recipe pins every block to 64x64 (`--sb-size=64 - /// --max-partition-size=64 --min-partition-size=64`) with masked compound - /// on and distance-weighted compound off, so the only way a - /// `comp_group_idx == 1` block can be coded is through the inferred arm. - /// `diffwtd_inferred_hits` is snapshotted PER ATTEMPT and only accumulated - /// for attempts that decoded AND pixel-compared (class - /// `counter-from-refused-stream`), and is hard-asserted at the end. A - /// decode error or a pixel mismatch is a FAILURE, never a skip. - #[track_caller] - pub(super) fn run_diffwtd_inferred_64x64_gate(name: &str, ten_bit: bool) { - let _gate_lock = lock_gate_counters(); - assert!(have_ffmpeg(), "{name}: ffmpeg required"); - assert!( - have_aomenc(), - "{name}: no aomenc at {}", - aomenc_path().display() - ); - let (width, height, frame_count) = (128usize, 128usize, 16usize); - let mut matched = 0u32; - let mut named_refusals = 0u32; - let mut attempts = 0u32; - let mut fired = 0usize; - let mut refusals: Vec = Vec::new(); - for cq in [32u32, 45, 55] { - for (i, zoom) in [0.004f64, 0.010].iter().enumerate() { - attempts += 1; - let attempt_before = crate::decode::diffwtd_inferred_hits(); - let duration = frame_count as f64 / 25.0; - // Hard-edged, moving content: a difference-weighted mask only - // wins where the two references genuinely disagree over part - // of a 64x64 block (a smooth `gradients` source measured - // diffwtd_hits == 0, memory `gate-blind-to-feature`). - let source = format!( - "mandelbrot=size={width}x{height}:rate=25:start_x={sx}:start_y=-0.4:\ - end_scale=0.3:maxiter=200,\ - noise=alls=6:allf=t+u:all_seed={seed}", - sx = -0.6 + zoom * (i as f64 + 1.0), - seed = 1000 + cq, - ); - let pix_fmt = if ten_bit { "yuv420p10le" } else { "yuv420p" }; - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-t", - &duration.to_string(), - "-pix_fmt", - pix_fmt, - "-strict", - "-1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let cq_arg = format!("--cq-level={cq}"); - let mut args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - &cq_arg, - "--cpu-used=0", - "--kf-max-dist=1000", - "--threads=1", - "--row-mt=0", - "--auto-alt-ref=1", - "--lag-in-frames=16", - "--enable-fwd-kf=0", - "--enable-order-hint=1", - // the tools this gate exists for: masked compound on, the - // difference-weighted arm on, the distance-weighted - // competitor off so comp_group_idx==1 is the encoder's - // only masked choice at a size where wedge does not exist. - "--enable-masked-comp=1", - "--enable-diff-wtd-comp=1", - "--enable-dist-wtd-comp=0", - "--enable-onesided-comp=0", - "--enable-interintra-comp=0", - "--enable-global-motion=0", - "--enable-warped-motion=1", - "--enable-obmc=1", - "--tune-content=default", - // partition/intra tools this decoder does not code yet -- - // same exclusion list every compound gate carries. - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-tx-size-search=0", - "--enable-cdef=0", - "--enable-restoration=0", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - "--enable-ref-frame-mvs=0", - // every block is a whole 64x64 superblock: the ONLY size - // where compound_type is inferred rather than coded. - "--sb-size=64", - "--max-partition-size=64", - "--min-partition-size=64", - ]; - if ten_bit { - args.extend_from_slice(&["--input-bit-depth=10", "--bit-depth=10"]); - } - args.extend_from_slice(&["--obu", "-o", "-", "-"]); - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let frames = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{name} failed outright, not a named refusal (cq {cq}): {msg}" - ); - assert!( - !msg.contains("masked compound 64x64"), - "{name} refused the inferred-DIFFWTD 64x64 block (cq {cq}) -- \ - that refusal is lifted, this is forbidden: {msg}" - ); - named_refusals += 1; - refusals.push(msg.clone()); - eprintln!("{name} cq {cq} variant {i} refusal: {msg}"); - continue; - } - Ok(frames) => frames, - }; - let want = if ten_bit { - ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count) - } else { - ffmpeg_decode_sequence(&stream, width, height, frame_count) - }; - assert_eq!(frames.len(), frame_count); - if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") - && frames - .iter() - .zip(&want) - .any(|(g, w)| g.y != w.y || g.u != w.u || g.v != w.v) - { - std::fs::write(&path, &stream).expect("writing pinned stream"); - eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (cq {cq}) to {path}"); - } - for (f, (got, want)) in frames.iter().zip(&want).enumerate() { - assert_eq!(got.y, want.y, "{name} frame {f} luma vs ffmpeg (cq {cq})"); - assert_eq!(got.u, want.u, "{name} frame {f} U vs ffmpeg (cq {cq})"); - assert_eq!(got.v, want.v, "{name} frame {f} V vs ffmpeg (cq {cq})"); - } - // decoded AND compared: only now does this attempt's own - // inferred-DIFFWTD count mean anything. - fired += crate::decode::diffwtd_inferred_hits() - attempt_before; - matched += 1; - } - } - eprintln!( - "{name}: {matched}/{attempts} pixel-exact, {named_refusals} named refusals, \ - diffwtd_inferred_hits (decoded+compared attempts only)={fired}" - ); - assert!( - matched > 0, - "{name}: every attempt refused ({refusals:?}) -- no pixel compare ran" - ); - assert!( - fired > 0, - "{name}: no inferred-DIFFWTD 64x64 block fired on a compared attempt \ - ({matched} matches, {named_refusals} refusals of {attempts}) -- gate vacuous" - ); - } - - pub(super) fn both_axes_cut_sweep( - name: &'static str, - (arm, frames, kf_arg, limit_arg): (&str, usize, &str, &str), - ) { - // Kept upper-case so every message string below reads the same as in - // the sibling gates. - #[allow(non_snake_case)] - let NAME = name; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() || !have_aomenc() { - eprintln!("SKIP {NAME}: no ffmpeg/aomenc"); - return; - } - let sizes: &[(usize, usize)] = &[(200, 72), (136, 104), (264, 136), (72, 200), (104, 136)]; - let mut compared = 0u32; - let mut refusals: Vec = Vec::new(); - let mut totals = [0usize; 4]; - for &(width, height) in sizes { - let mut size_compared = 0u32; - { - for bit_depth in [8u32, 10u32] { - // cq 58 is left out on purpose: measured r1, it is where - // libaom starts answering the frame-edge gathered symbol - // with a rect strip and other lanes' refusals fire first - // ("a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs - // rectangular residual coding"). - for cq in [32u32, 45] { - let source = format!("mandelbrot=size={width}x{height}:rate=25"); - // Feed exactly `frames` frames: --limit=1 makes - // aomenc stop reading after the first one and the - // y4m write then dies on a broken pipe. - let dur = format!("{}", frames as f64 / 25.0); - let pix_fmt = if bit_depth == 10 { - "yuv420p10le" - } else { - "yuv420p" - }; - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-t", - &dur, - "-pix_fmt", - pix_fmt, - "-strict", - "-1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "{NAME}: ffmpeg refused the {width}x{height} {bit_depth}-bit \ - fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let depth_arg = format!("--bit-depth={bit_depth}"); - let input_depth_arg = format!("--input-bit-depth={bit_depth}"); - let cq_arg = format!("--cq-level={cq}"); - let out = run_with_stdin( - Command::new(aomenc_path()).args([ - "--codec=av1", - "--passes=1", - "--end-usage=q", - &cq_arg, - // cpu-used >= 1 keeps libaom on 64x64 - // superblocks at these sizes - // (`av1_select_sb_size`). - "--cpu-used=4", - "--threads=1", - "--row-mt=0", - // --lag-in-frames=0: no hidden alt-ref, so - // decode order == display order and the - // compare below covers every frame the stream - // carries (class gate-blind-to-hidden-frames). - kf_arg, - limit_arg, - "--lag-in-frames=0", - &depth_arg, - &input_depth_arg, - // Other lanes' named refusals this recipe must - // not trip. The both-cut corner is FORCED down - // to 8x8 leaves, which is exactly where the - // 8x8-intra-leaf-in-an-inter-frame gaps live, - // so the intra tool set and tx-size search are - // pinned off: without them 30/30 inter - // attempts refused (measured r1) on "a nonzero - // angle delta on an 8x8 intra leaf in an inter - // frame", "a non-DC chroma mode on an 8x8 - // inter-frame leaf" and "an 8x8 intra leaf in - // an inter frame whose tx_depth splits it into - // 4x4 transform units". - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--min-partition-size=8", - "--max-partition-size=64", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-warped-motion=0", - "--enable-obmc=0", - "--enable-masked-comp=0", - "--enable-interintra-comp=0", - "--enable-onesided-comp=0", - "--enable-interintra-wedge=0", - "--enable-smooth-interintra=0", - "--enable-ref-frame-mvs=0", - "--enable-angle-delta=0", - "--enable-cfl-intra=0", - "--enable-directional-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-filter-intra=0", - "--enable-tx-size-search=0", - "--obu", - "-o", - "-", - "-", - ]), - &y4m.stdout, - ); - assert!( - out.status.success(), - "aomenc refused: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - - // Reset, never a delta across attempts: a refused - // attempt's hits must not count (class - // counter-from-refused-stream). - crate::decode::reset_edge_both_cut_hits(); - let decoded = match decode_stream(&stream) { - Ok(f) => f, - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME}: {width}x{height} {arm} {bit_depth}-bit cq {cq} \ - failed outright, not a named refusal: {msg}" - ); - eprintln!( - " {NAME}: {width}x{height} {arm} {bit_depth}-bit cq {cq} \ - REFUSED {msg}" - ); - refusals.push(msg); - continue; - } - }; - let hits = crate::decode::edge_both_cut_hits(); - let reference = if bit_depth == 10 { - ffmpeg_decode_sequence_10bit(&stream, width, height, frames) - } else { - ffmpeg_decode_sequence(&stream, width, height, frames) - }; - assert_eq!( - decoded.len(), - frames, - "{NAME}: {width}x{height} {arm} {bit_depth}-bit cq {cq} decoded {} \ - frames, expected {frames}", - decoded.len() - ); - assert_eq!( - reference.len(), - frames, - "{NAME}: {width}x{height} {arm} {bit_depth}-bit cq {cq} reference \ - frame count" - ); - for (i, (ours, theirs)) in decoded.iter().zip(&reference).enumerate() { - let nd = |a: &[u16], b: &[u16]| { - a.iter().zip(b).filter(|(x, y)| x != y).count() - }; - // Where a mismatch lands is the whole diagnosis - // here (corner block vs elsewhere), so print the - // luma bounding box before the assert kills the run. - if nd(&ours.y, &theirs.y) > 0 { - let (mut r0, mut c0, mut r1, mut c1) = - (usize::MAX, usize::MAX, 0usize, 0usize); - for row in 0..height { - for col in 0..width { - if ours.y[row * width + col] != theirs.y[row * width + col] - { - r0 = r0.min(row); - c0 = c0.min(col); - r1 = r1.max(row); - c1 = c1.max(col); - } - } - } - eprintln!( - " {NAME}: {width}x{height} {arm} {bit_depth}-bit cq {cq} \ - frame {i} luma diff bbox rows {r0}..={r1} cols {c0}..={c1}" - ); - } - assert_eq!( - ( - nd(&ours.y, &theirs.y), - nd(&ours.u, &theirs.u), - nd(&ours.v, &theirs.v) - ), - (0, 0, 0), - "{NAME}: {width}x{height} {arm} {bit_depth}-bit cq {cq} frame \ - {i} differs from ffmpeg" - ); - for (plane, a, b) in [ - ("Y", &ours.y, &theirs.y), - ("U", &ours.u, &theirs.u), - ("V", &ours.v, &theirs.v), - ] { - assert_eq!( - a.len(), - b.len(), - "{NAME}: {width}x{height} {arm} {bit_depth}-bit cq {cq} \ - frame {i} plane {plane}: ours has {} samples, ffmpeg's has \ - {} -- a short plane would zip-truncate the diff count \ - above and hide a chroma-span defect", - a.len(), - b.len() - ); - } - } - // Every compared attempt must carry the case, so no - // compared attempt is out of scope and - // out_of_scope_mismatch is 0 by construction. - assert!( - hits[0] > 0, - "{NAME}: {width}x{height} {arm} {bit_depth}-bit cq {cq} decoded \ - pixel-exact but no 16-level both-axes-cut block fired \ - (hits={hits:?}) -- the recipe no longer reaches the lifted arm" - ); - for l in 0..4 { - totals[l] += hits[l]; - } - compared += 1; - size_compared += 1; - } - } - } - assert!( - size_compared > 0, - "{NAME}: every {width}x{height} attempt refused -- that size proved nothing" - ); - } - assert!( - totals[1] > 0 && totals[2] > 0, - "{NAME}: no 32-level ({}) or 64-level ({}) both-axes-cut node fired -- 200x72 puts \ - both in that state, so the sweep stopped reaching them", - totals[1], - totals[2] - ); - eprintln!( - "{NAME}: {compared} attempts pixel-exact over {} sizes ({arm} arm), \ - out_of_scope_mismatch=0, both_cut hits [16,32,64,128]={totals:?}, {} named refusals", - sizes.len(), - refusals.len() - ); - } - - /// lane-av1tmvp: the temporal-MV gate -- unlike every `_single_ref_gate` - /// attempt above, this one leaves `--enable-ref-frame-mvs` at aomenc's - /// own default (on) instead of pinning it off, so `use_ref_frame_mvs` - /// actually fires and `decode::tmv_hits()` (this gate's own capability - /// proof, not just `non_last_ref_hits`) has to advance for the run to - /// count as a real pass rather than a `never_fired` skip. - pub(super) fn a_real_aomenc_temporal_mv_gate(seed_base: u32, attempts: u32) { - let gate_name = "a_real_aomenc_temporal_mv_gate"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {gate_name}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {gate_name}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height, frame_count) = (64usize, 64usize, 16usize); - let mut never_fired = 0u32; - let mut refusals = Vec::new(); - for attempt in 0..attempts { - let seed = seed_base + attempt; - let duration = frame_count as f64 / 25.0; - let source = - gradients_source(seed, width, height, &format!("duration={duration}:rate=25")); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-pix_fmt", - "yuv420p", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - // Same envelope as `a_real_aomenc_single_ref_gate`, minus its - // `--enable-ref-frame-mvs=0` pin -- everything else this decoder - // still cannot code stays refused the same way. - let args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=55", - "--cpu-used=0", - "--kf-max-dist=1000", - "--threads=1", - "--row-mt=0", - "--auto-alt-ref=1", - "--lag-in-frames=16", - "--enable-fwd-kf=0", - "--enable-warped-motion=0", - "--enable-obmc=0", - "--enable-masked-comp=0", - "--enable-interintra-comp=0", - "--enable-dist-wtd-comp=0", - "--enable-diff-wtd-comp=0", - "--enable-onesided-comp=0", - "--enable-interintra-wedge=0", - "--enable-smooth-interintra=0", - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-tx-size-search=0", - "--enable-cdef=0", - "--enable-restoration=0", - "--max-partition-size=32", - "--min-partition-size=32", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - "--obu", - "-o", - "-", - "-", - ]; - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let before = decode::tmv_hits(); - let frames = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{gate_name} failed outright (seed {seed}): {msg}" - ); - refusals.push(format!("seed {seed}: {msg}")); - continue; - } - Ok(frames) => frames, - }; - // class [[gate-skips-on-its-own-failure]]: a decode that succeeded - // is ALWAYS pixel-compared below; the hit counter only decides whether - // the attempt counts toward the firing total. - let counted = decode::tmv_hits() != before; - if !counted { - never_fired += 1; - } - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count); - assert_eq!(frames.len(), frame_count); - if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") { - let mismatched = frames - .iter() - .zip(&ffmpeg_frames) - .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); - if mismatched { - std::fs::write(&path, &stream).expect("writing pinned stream"); - eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}"); - } - } - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!( - got.y, want.y, - "{gate_name} frame {i} luma vs ffmpeg (seed {seed})" - ); - assert_eq!( - got.u, want.u, - "{gate_name} frame {i} U vs ffmpeg (seed {seed})" - ); - assert_eq!( - got.v, want.v, - "{gate_name} frame {i} V vs ffmpeg (seed {seed})" - ); - } - if counted { - eprintln!( - "{gate_name} FIRING seed {seed}: tmv_hits advanced by {}", - decode::tmv_hits() - before - ); - gate_buckets(gate_name, 1, never_fired, refusals.len()); - return; - } - } - gate_buckets(gate_name, 0, never_fired, refusals.len()); - eprintln!( - "SKIP {gate_name}: {never_fired} attempts decoded but never fired a temporal MV \ - candidate, and every other attempt hit a named refusal:\n{}", - refusals.join("\n") - ); - } - - /// lane-mvtwin r1: the COMPOUND MV-stack gate. Every other compound gate - /// here pins `--enable-ref-frame-mvs=0`, so `find_mv_stack_compound`'s - /// temporal half (the three `tpl_sample_pos` extension samples lane-sb128 - /// r3 found missing) and its extension pass have never been exercised by - /// a real encoder. This arm turns ref-frame-mvs ON, gives the encoder a - /// 25-frame lookahead plus alt-refs so `reference_select` really drives - /// blocks to COMPOUND_REFERENCE, and sweeps global motion off/on so the - /// combine step's `gm_mv_candidates` fill (r1 defect 1) is reachable. - /// - /// Firing proof, hard-asserted: `decode::comp_mode_hits` (a real - /// compound block) AND `mvstack::tmv_hits` (a temporal candidate landed - /// in some stack) must BOTH have advanced on an attempt that also - /// decoded pixel-exact -- class [[gate-skips-on-its-own-failure]]: a - /// decode that succeeds is ALWAYS compared, on every decode-order frame, - /// and only the counters decide whether the attempt counts. - // Signature mirrors the spec's per-call inputs; a parameter struct would only move them. - #[allow(clippy::too_many_arguments)] - pub(super) fn a_real_aomenc_compound_mv_stack_gate( - gate_name: &str, - seed_base: u32, - attempts: u32, - bit_depth: u32, - sb_size: u32, - global_motion: u32, - width: usize, - tile_columns: u32, - ) { - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {gate_name}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {gate_name}: no aomenc at {}", aomenc_path().display()); - return; - } - let (height, frame_count) = (64usize, 16usize); - let mut never_fired = 0u32; - let mut refusals = Vec::new(); - for attempt in 0..attempts { - let seed = seed_base + attempt; - let duration = frame_count as f64 / 25.0; - let source = - gradients_source(seed, width, height, &format!("duration={duration}:rate=25")); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-pix_fmt", - if bit_depth == 10 { - "yuv420p10le" - } else { - "yuv420p" - }, - "-strict", - "-1", - "-t", - "0.64", - "-f", - "yuv4mpegpipe", - "-strict", - "-1", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let depth_args: &[&str] = if bit_depth == 10 { - &["-b", "10", "--input-bit-depth=10"] - } else { - &[] - }; - // The cq sweep: how finely RD partitions decides how often a - // block's stack comes up short enough to reach the extension - // pass at all. - let cq = format!("--cq-level={}", [45u32, 55, 35][(attempt % 3) as usize]); - let sb = format!("--sb-size={sb_size}"); - let gm = format!("--enable-global-motion={global_motion}"); - // `--tile-columns` is log2: 1 means two tile columns, which is - // what makes every block in the right-hand tile carry a nonzero - // `tile_col0` and so exercise r1 defect 3's reach clamp. - let tiles = format!("--tile-columns={tile_columns}"); - // class [[aomenc-last-flag-wins]]: every flag appears exactly - // once below, so there is no override to order. - let out = run_with_stdin( - Command::new(aomenc_path()) - .args(depth_args) - .arg(&cq) - .arg(&sb) - .arg(&gm) - .arg(&tiles) - .args([ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cpu-used=0", - "--kf-max-dist=1000", - "--threads=1", - "--row-mt=0", - // What this gate is about: real compound references - // with a real temporal MV field behind them. - "--enable-ref-frame-mvs=1", - "--enable-order-hint=1", - "--auto-alt-ref=1", - "--lag-in-frames=25", - "--enable-fwd-kf=0", - "--enable-warped-motion=0", - "--enable-obmc=0", - "--enable-masked-comp=0", - "--enable-interintra-comp=0", - "--enable-dist-wtd-comp=0", - "--enable-diff-wtd-comp=0", - "--enable-onesided-comp=0", - "--enable-interintra-wedge=0", - "--enable-smooth-interintra=0", - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-tx-size-search=0", - "--enable-cdef=0", - "--enable-restoration=0", - "--max-partition-size=32", - "--min-partition-size=32", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - "--obu", - "-o", - "-", - "-", - ]), - &y4m.stdout, - ); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let (before_comp, before_tmv) = (decode::comp_mode_hits(), decode::tmv_hits()); - let frames = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{gate_name} failed outright (seed {seed}): {msg}" - ); - refusals.push(format!("seed {seed}: {msg}")); - continue; - } - Ok(frames) => frames, - }; - let counted = - decode::comp_mode_hits() != before_comp && decode::tmv_hits() != before_tmv; - if !counted { - never_fired += 1; - } - let ffmpeg_frames = if bit_depth == 10 { - ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count) - } else { - ffmpeg_decode_sequence(&stream, width, height, frame_count) - }; - assert_eq!(frames.len(), frame_count); - // Every SHOWN/display frame `decode_stream` returned is compared -- - // that is decode_stream's whole output, and nothing else is. - // HIDDEN frames are NOT covered here: they are never emitted as - // pictures, so no ffmpeg picture corresponds to them (class - // [[gate-blind-to-hidden-frames]]). - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!( - got.y, want.y, - "{gate_name} frame {i} luma vs ffmpeg (seed {seed})" - ); - assert_eq!( - got.u, want.u, - "{gate_name} frame {i} U vs ffmpeg (seed {seed})" - ); - assert_eq!( - got.v, want.v, - "{gate_name} frame {i} V vs ffmpeg (seed {seed})" - ); - } - if counted { - eprintln!( - "{gate_name} FIRING seed {seed}: comp_mode_hits +{}, tmv_hits +{}, \ - comp_gm_fill_hits={}, stack_full_drops={}, tile_reach_clips={}", - decode::comp_mode_hits() - before_comp, - decode::tmv_hits() - before_tmv, - crate::mvstack::comp_gm_fill_hits(), - crate::mvstack::stack_full_drops(), - crate::mvstack::tile_reach_clips(), - ); - gate_buckets(gate_name, 1, never_fired, refusals.len()); - return; - } - } - gate_buckets(gate_name, 0, never_fired, refusals.len()); - eprintln!( - "SKIP {gate_name}: {never_fired} attempts decoded but never drove a compound block \ - with a temporal MV candidate, and every other attempt hit a named refusal:\n{}", - refusals.join("\n") - ); - } - - /// lane-seg: a real `aomenc` stream with SEGMENTATION genuinely active. - /// `--aq-mode=1` (variance AQ) / `--aq-mode=2` (complexity AQ) are the two - /// paths libaom uses to switch `segmentation_enabled` on by itself - /// (`av1_vaq_frame_setup`/`av1_setup_in_frame_q_adj`, both of which only - /// ever set `SEG_LVL_ALT_Q`); `--deltaq-mode=0` keeps the per-superblock - /// delta-q reader out of the picture so a mismatch points at the segment - /// map, not at `CurrentQIndex`. Mandelbrot's varying local contrast is - /// what gives variance/complexity AQ different segments to assign -- - /// a flat gradient collapses every block onto one segment, which the - /// `segment_ids_seen() >= 2` assert below would catch as a vacuous run. - /// The rest of the recipe is the delta-q gate's own feature-disable - /// envelope, so this gate isolates the segmentation reader. - pub(super) fn run_segmentation_gate( - name: &str, - aq_mode: &str, - bit_depth: usize, - frame_count: usize, - rate_args: &[&str], - ) { - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {name}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display()); - return; - } - crate::decode::reset_segment_hits(); - let (width, height) = (128usize, 64usize); - let mut named_refusals = 0u32; - let mut matched = 0u32; - let n_attempts: u32 = std::env::var("EC_SEG_GATE_ATTEMPTS") - .ok() - .and_then(|s| s.parse().ok()) - .unwrap_or(10); - for attempt in 0..n_attempts { - let seed = 42 + attempt; - let duration = frame_count as f64 / 25.0; - let source = format!( - "mandelbrot=size={width}x{height}:rate=25:start_x={sx}:start_y={sy}", - sx = -0.6 + 0.005 * (attempt as f64), - sy = -0.4 + 0.005 * (attempt as f64) - ); - let pix_fmt = if bit_depth == 10 { - "yuv420p10le" - } else { - "yuv420p" - }; - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-t", - &duration.to_string(), - "-pix_fmt", - pix_fmt, - "-strict", - "-1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let depth_args: Vec = if bit_depth == 10 { - vec![ - "--input-bit-depth=10".to_owned(), - "--bit-depth=10".to_owned(), - ] - } else { - Vec::new() - }; - let aq = format!("--aq-mode={aq_mode}"); - let mut args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--cpu-used=4", - &aq, - "--deltaq-mode=0", - "--enable-cdef=0", - "--kf-max-dist=1000", - "--threads=1", - "--row-mt=0", - "--sb-size=64", - "--auto-alt-ref=1", - "--lag-in-frames=16", - "--enable-fwd-kf=0", - "--enable-order-hint=1", - "--enable-warped-motion=1", - "--enable-global-motion=0", - "--enable-obmc=1", - "--tune-content=default", - "--enable-masked-comp=1", - "--enable-dist-wtd-comp=0", - "--enable-interintra-comp=1", - "--enable-onesided-comp=0", - "--enable-interintra-wedge=0", - "--enable-smooth-interintra=1", - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-tx-size-search=0", - "--enable-cdef=1", - "--enable-restoration=0", - "--max-partition-size=32", - "--min-partition-size=32", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - "--enable-ref-frame-mvs=0", - ]; - args.extend(rate_args.iter().copied()); - args.extend(depth_args.iter().map(String::as_str)); - args.extend(["--obu", "-o", "-", "-"]); - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - // The stream must really carry `segmentation_enabled`, or the - // gate proves nothing about the reader. - let mut seg_frames = 0u32; - { - let mut probe = Av1Parser::new(); - let mut pos = 0usize; - while pos < stream.len() { - let obu = probe - .parse_obu(&stream[pos..]) - .expect("parsing the gate stream"); - pos += obu.total_size; - match &obu.kind { - ObuKind::Frame(h, _) => { - if h.segmentation.enabled { - seg_frames += 1; - } - } - ObuKind::FrameHeader(h) - if h.segmentation.enabled => { - seg_frames += 1; - } - _ => {} - } - } - } - if seg_frames == 0 { - eprintln!( - "seed {seed}: aomenc wrote no segmentation-enabled frame, skipping attempt" - ); - continue; - } - let frames = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{name} failed outright, not a named refusal (seed {seed}): {msg}" - ); - assert!( - !msg.contains("segment_id symbol"), - "{name} refused on the segmentation reader itself (seed {seed}): {msg}" - ); - named_refusals += 1; - eprintln!("seed {seed} refusal: {msg}"); - continue; - } - Ok(frames) => frames, - }; - let ffmpeg_frames = if bit_depth == 10 { - ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count) - } else { - ffmpeg_decode_sequence(&stream, width, height, frame_count) - }; - assert_eq!(frames.len(), frame_count); - let mismatched = frames - .iter() - .zip(&ffmpeg_frames) - .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); - if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") { - std::fs::write(&path, &stream).expect("writing pinned stream"); - eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}"); - } - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!( - got.y, want.y, - "{name} frame {i} luma vs ffmpeg (seed {seed})" - ); - assert_eq!(got.u, want.u, "{name} frame {i} U vs ffmpeg (seed {seed})"); - assert_eq!(got.v, want.v, "{name} frame {i} V vs ffmpeg (seed {seed})"); - } - matched += 1; - } - assert!( - matched > 0, - "{name}: every attempt refused on other capabilities ({named_refusals} refusals); \ - the gate never exercised segmentation" - ); - assert!( - crate::decode::segment_id_hits() > 0, - "{name}: {matched} pixel-exact matches but zero segment_id symbols fired -- \ - the reader is unexercised" - ); - assert!( - crate::decode::segment_ids_seen() >= 2, - "{name}: {matched} pixel-exact matches but only {} distinct segment id(s) -- \ - every block landed in one segment, so nothing was actually segmented", - crate::decode::segment_ids_seen() - ); - // An inter-frame run must also have exercised the TEMPORAL path - // (`seg_id_predicted` against the primary reference's saved map); - // the key-frame-only run has no previous map by construction. - if frame_count > 1 { - assert!( - crate::decode::segment_pred_hits() > 0, - "{name}: {matched} pixel-exact matches over {frame_count} frames but zero \ - seg_id_predicted symbols -- the temporal_update path is unexercised" - ); - } - eprintln!( - "{name}: {named_refusals} other-capability refusals, {matched} pixel-exact matches \ - out of {n_attempts}, segment_id_hits={}, distinct segment ids={}, \ - seg_id_predicted symbols={}", - crate::decode::segment_id_hits(), - crate::decode::segment_ids_seen(), - crate::decode::segment_pred_hits() - ); - } - - pub(super) fn edge32_gate(name: &str, flat_band: bool) { - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {name}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display()); - return; - } - // (width, height, frames, ten_bit, tile_columns_log2) - let mut arms: Vec<(usize, usize, usize, bool, u32)> = Vec::new(); - for &(w, h) in &[(192usize, 80usize), (80usize, 192usize)] { - arms.push((w, h, 1, false, 0)); - arms.push((w, h, 1, true, 0)); - } - // The inter arm: >= 4 frames so the 32-level edge path in the INTER - // tile walk is exercised too. - arms.push((192, 80, 5, false, 0)); - // lane-golomb r9: the straddling-band arms, only under the ignored - // `a_frame_edge_straddling_band_decodes_pixel_exact` name (they are - // RED -- see that test's own comment for the stage bisection). Naming - // them here rather than in a second copy of this gate keeps the - // recipe, the counters and the refusal handling identical. - if name == "a_frame_edge_straddling_band_decodes_pixel_exact" { - arms.clear(); - for &tile_cols in &[0u32, 1] { - arms.push((192, 68, 5, false, tile_cols)); - arms.push((192, 68, 5, true, tile_cols)); - arms.push((68, 192, 5, false, tile_cols)); - arms.push((68, 192, 5, true, tile_cols)); - } - } - // lane-golomb r8 MEASURED, arm STILL NOT added (every cq level is - // vacuous, panicking or red -- each measured this round with - // `arms.push((192, 68, 5, false))`, log - // `$HOME/.cache/golomb-gate-r8{b,e,f,g}.log`): - // * the r7 blocker IS fixed -- no attempt refuses "a reference - // picture whose height does not match this frame's own true - // size" any more (`decode.rs`'s comparison now uses the header's - // frame height, per libaom's crop-dimension reference test). - // * cq35 now refuses LATER, by another lane's name: "an inter - // SB-level AB partition (HORZ_A/HORZ_B/VERT_A/VERT_B)" -- so the - // arm compares nothing (class `counter-from-refused-stream`). - // * cq40 PANICS in `decode_inter_block8` - // (`from_switchable_symbol` handed a 4th symbol, `mc.rs:203`) = - // lane-sub8's own open below-8x8 desync; a panic cannot be - // tolerated as a named refusal. - // * cq59 8-bit is RED: `frame 1 plane Y: 217 pixels differ, first - // at row 60 col 170 (ours 172 vs ffmpeg 173)`, and the cq35 - // 10-bit twin is RED at `row 56 col 48 (ours 530 vs ffmpeg - // 531)`. Both are +-1 bands in rows 56..63, i.e. the deblock/CDEF - // bleed ABOVE the 4-px straddling row band (64..67) -- the same - // shape as the `(68, 192, 5, false)` column defect below, so the - // two are very likely ONE straddling-band reconstruction defect. - // lane-golomb r7 MEASURED, arm NOT added (it would be vacuous or red): - // a 68-px axis leaves the last superblock straddling by 4 px, the - // shape `read_var_tx_size`'s `blk_row >= max_h_mi || blk_col >= - // max_w_mi` early return exists for. With - // `arms.push((192, 68, 5, false))` all EIGHT cq attempts refuse by - // name -- "a reference picture whose height does not match this - // frame's own true size" -- so the arm compares nothing (class - // `counter-from-refused-stream`). With - // `arms.push((68, 192, 5, false))` the gate goes RED on a real, - // separate defect: `68x192 cq35 frames=5 10bit=false frame 1 plane Y: - // 141 pixels differ, first at row 0 col 64 (ours 167 vs ffmpeg 166) - // [edge32=[0,34,0,0,1,17,0,1]]` -- LUMA, inside the 4-px straddling - // COLUMN. Both are unrelated to this round's chroma tx_type fix. - let cqs: [u32; 8] = [35, 40, 45, 50, 55, 57, 59, 61]; - let mut totals = [0usize; 8]; - let mut compared = 0usize; - // lane-t900 r15 (class `counter-from-refused-stream`): the aggregate - // `compared` counter is carried by the single-tile arms alone, so the - // `--tile-columns=1` twins were free to refuse every attempt and keep - // the gate green. Counted separately and asserted below. - let mut compared_multi_tile = 0usize; - let mut refusals: Vec = Vec::new(); - let straddle = name == "a_frame_edge_straddling_band_decodes_pixel_exact"; - let mut straddle_units = 0usize; - for &(width, height, frame_count, ten_bit, tile_cols) in &arms { - for &cq in &cqs { - let duration = frame_count as f64 / 25.0; - // `noise` (explicit seed) both defeats aomenc's - // screen-content detection -- which otherwise refuses every - // attempt at "a HORZ/VERT intra strip in a screen-content - // frame" -- and keeps the RD search off flat NONE blocks. - // Natural content over the whole superblock-aligned area, - // with the 16-px straddling band left FLAT (`pad`): with - // detail in that band aomenc always answers the edge bit with - // SPLIT (measured: 178 edge bits, 178 of them SPLIT, over a - // cq 35..61 sweep), so the HORZ/VERT arm this round guards - // never fired. `noise` on top keeps screen-content detection - // (and its palette-strip refusal) off. - let (cw, ch) = ( - if flat_band && width % 64 != 0 { - width - 16 - } else { - width - }, - if flat_band && height % 64 != 0 { - height - 16 - } else { - height - }, - ); - let pad = if flat_band { - format!("pad={width}:{height}:0:0:gray,") - } else { - String::new() - }; - let source = format!( - "testsrc2=size={cw}x{ch}:duration={duration}:rate=25,\ - {pad}noise=alls=6:allf=t+u:all_seed={cq}" - ); - let pix = if ten_bit { "yuv420p10le" } else { "yuv420p" }; - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-pix_fmt", - pix, - "-strict", - "-1", - "-t", - &format!("{duration}"), - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "{name}: ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let cq_arg = format!("--cq-level={cq}"); - let mut args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - &cq_arg, - "--cpu-used=0", - "--threads=1", - "--row-mt=0", - "--sb-size=64", - "--enable-restoration=0", - "--enable-palette=0", - "--deltaq-mode=0", - "--enable-intrabc=0", - // Per-arm overrides go LAST (aomenc keeps the last - // occurrence of a repeated --enable-* flag). - "--enable-rect-partitions=1", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - // 32, not the charter's 8: at 8 the sub-16 AB and - // split-transform strip arms (still refused by name here) - // fire before the 32-level edge is reached and EVERY - // attempt refuses (measured). At 32 the edge block cannot - // split, so aomenc is forced onto the gathered edge bit's - // HORZ/VERT -- exactly the arm this round guards. - "--min-partition-size=32", - "--tune-content=film", - "--max-partition-size=64", - ]; - if ten_bit { - args.extend_from_slice(&["--input-bit-depth=10", "--bit-depth=10"]); - } - let tile_arg = format!("--tile-columns={tile_cols}"); - if tile_cols > 0 { - args.push(&tile_arg); - } - args.extend_from_slice(&["--obu", "-o", "-", "-"]); - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "{name}: aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - if ten_bit { - assert_eq!( - parsed_bit_depth(&stream), - 10, - "{name}: aomenc did not write a 10-bit sequence header" - ); - } - let tag = format!( - "{width}x{height} cq{cq} frames={frame_count} 10bit={ten_bit} \ - tile_cols={tile_cols}" - ); - let before = crate::decode::edge32_hits(); - let straddle_before = crate::decode::cdef_straddle_units(); - // lane-golomb r8: name the attempt BEFORE decoding it -- a - // desync surfaces as a panic deep in mc.rs with no arm in the - // message, and r8 spent a run bisecting arms by hand. - if std::env::var_os("EC_GATE_VERBOSE").is_some() { - eprintln!("{name}: attempting {tag}"); - } - let decoded = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{name} failed outright, not a named refusal ({tag}): {msg}" - ); - refusals.push(format!("{tag}: {msg}")); - continue; - } - }; - let after = crate::decode::edge32_hits(); - let delta: Vec = (0..8).map(|i| after[i] - before[i]).collect(); - // The ENCODE's frame count, and it is PER ARM: the arm tuple's - // `frame_count` field is what the y4m is built from - // (`duration = frame_count / 25.0`, 38085, rendered with - // `-t {duration}` at 38131) and this gate's aomenc carries no - // `--limit` and no `--lag-in-frames`, so the stream codes exactly - // `frame_count` frames (1 for the intra arms, 5 for the - // inter/straddling ones). Asserted ABOVE the oracle call, so a - // decode that dropped one reds naming the encode. - assert_eq!( - decoded.len(), - frame_count, - "{name}: {tag}: the encode codes {frame_count} frame(s), the decode showed {}", - decoded.len() - ); - let reference = if ten_bit { - ffmpeg_decode_sequence_10bit(&stream, width, height, decoded.len()) - } else { - ffmpeg_decode_sequence(&stream, width, height, decoded.len()) - }; - assert_eq!( - decoded.len(), - reference.len(), - "{name}: {tag}: shown-frame count vs ffmpeg" - ); - for (i, (ours, theirs)) in decoded.iter().zip(reference.iter()).enumerate() { - for (plane, a, b, w) in [ - ("Y", &ours.y, &theirs.y, width), - ("U", &ours.u, &theirs.u, width / 2), - ("V", &ours.v, &theirs.v, width / 2), - ] { - if let Some(d) = a.iter().zip(b.iter()).position(|(x, y)| x != y) { - let n = a.iter().zip(b.iter()).filter(|(x, y)| x != y).count(); - if std::env::var_os("EC_EDGE32_ROWS").is_some() { - let mut per_row: std::collections::BTreeMap = - Default::default(); - for (k, (x, y)) in a.iter().zip(b.iter()).enumerate() { - if x != y { - *per_row.entry(k / w).or_default() += 1; - } - } - eprintln!("{name}: {tag} plane {plane} diffs per row: {per_row:?}"); - } - panic!( - "{name}: {tag} frame {i} plane {plane}: {n} pixels differ, first \ - at row {} col {} (ours {} vs ffmpeg {}) [edge32={delta:?}]", - d / w, - d % w, - a[d], - b[d] - ); - } - assert_eq!( - a.len(), - b.len(), - "{name}: {tag} frame {i} plane {plane}: ours has {} samples, \ - ffmpeg's has {} -- a short plane would zip-truncate the walk above \ - and hide a chroma-span defect", - a.len(), - b.len() - ); - } - } - compared += 1; - if tile_cols > 0 { - compared_multi_tile += 1; - } - straddle_units += crate::decode::cdef_straddle_units() - straddle_before; - for i in 0..8 { - totals[i] += delta[i]; - } - } - } - assert!( - compared > 0, - "{name}: every attempt hit a named refusal:\n{}", - refusals.join("\n") - ); - assert!( - !straddle || compared_multi_tile > 0, - "{name}: every `--tile-columns=1` attempt hit a named refusal -- the \ - multi-tile twins compared nothing:\n{}", - refusals.join("\n") - ); - assert!( - !straddle || straddle_units > 0, - "{name}: no FILTERED 8x8 CDEF unit crossed the cropped frame edge over \ - {compared} compared attempts -- the straddling arms proved nothing" - ); - assert!( - totals[0] + totals[1] + totals[4] + totals[5] > 0, - "{name}: no frame-edge partition bit was read at all over \ - {compared} compared attempts -- the gate proved nothing" - ); - // lane-golomb r3: the flat-band arm's ASSERT moved one level up. Until - // r3 the last superblock row was reached through a 32-level edge bit - // only because our own out-of-frame transform units had desynced the - // stream; with that fixed, real aomenc answers a bottom-edge - // superblock with the 64-level `PARTITION_HORZ` (and a right-edge one - // with `PARTITION_VERT`) and the 32-level slots stay 0 on this - // content. Slots 6/7 are the strips actually decoded at the edge. - assert!( - !flat_band || totals[6] > 0, - "{name}: no 64x32 bottom-edge HORZ strip was decoded \ - (edge32={totals:?}, {compared} compared attempts)" - ); - assert!( - !flat_band || totals[7] > 0, - "{name}: no 32x64 right-edge VERT strip was decoded \ - (edge32={totals:?}, {compared} compared attempts)" - ); - eprintln!( - "{name}: {compared} pixel-exact attempts, 32-level edge bits \ - [horz_or_vert={} split={}] bottom-HORZ={} right-VERT={}, 64-level edge bits \ - [horz_or_vert={} split={}] bottom-HORZ={} right-VERT={}, \ - {straddle_units} straddling CDEF units, {} named refusals", - totals[0], - totals[1], - totals[2], - totals[3], - totals[4], - totals[5], - totals[6], - totals[7], - refusals.len() - ); - for r in &refusals { - eprintln!("{name} refusal: {r}"); - } - } - - /// lane-tiles r11: every tile gate before this one turns the coding tools - /// OFF (rect/ab partitions, tx-size search, cdef, restoration all `=0`) - /// to isolate the per-tile loop, which is exactly the - /// [[tool-disabled-in-every-gate]] shape -- a tile-edge defect in any of - /// those tools is invisible to all of them. This one runs the BROAD tool - /// set (rect + ab partitions, default tx search, cdef and loop - /// restoration both on, deblocking left at its default so it filters - /// across tile boundaries as the spec requires) over a real 2D tile grid, - /// through `decode_stream` rather than the tile entry point, so it is the - /// same path a caller decoding a file takes. - /// - /// 256x128 is four 64x64 superblocks wide and two tall, so - /// `--tile-columns=1 --tile-rows=1` really yields a 2x2 grid and - /// `--tile-columns=2` really yields 4 columns; both are asserted from the - /// parsed `tile_info` rather than assumed, and the decoded-tile counter - /// (`tile_hits`) is asserted at >= 4 per decoded frame so a stream whose - /// header claims 4 tiles but whose decode only walked one cannot pass. - // `#[track_caller]` so a failing assert names the calling arm's line, and - // so `gate_coverage`'s body split (on `\n #[`) treats this helper's - // recipe as its own gate rather than gluing it onto the preceding one. - #[track_caller] - // Signature mirrors the spec's per-call inputs; a parameter struct would only move them. - #[allow(clippy::too_many_arguments)] - pub(super) fn run_multi_tile_gate( - name: &str, - tile_cols_log2: u32, - tile_rows_log2: u32, - bit_depth: usize, - frame_count: usize, - extra: &[&str], - // lane-tiles r12: the palette arm's own override proof. `true` asserts, - // per attempt, that the arm's `--tune-content=screen --enable-palette=1` - // really reached the encoder (frame header `allow_screen_content_tools`) - // AND that a palette block fired at a TILE's left column -- the exact - // block whose colour cache must not see the previous tile's colours. - require_tile_left_palette: bool, - // `None` = the shared `gradients_source`. The palette arm overrides it - // with `smptebars`, the flat few-colour source the existing palette - // gates use -- gradients never make aomenc pick a palette block. - source_override: Option<&str>, - ) { - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {name}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height) = (256usize, 128usize); - let expected_tiles = (1usize << tile_cols_log2) * (1usize << tile_rows_log2); - let mut matched = 0u32; - let mut named_refusals = 0u32; - let mut uv_edge_suppressed = 0usize; - let n_attempts: u32 = std::env::var("EC_TILES_GATE_ATTEMPTS") - .ok() - .and_then(|s| s.parse().ok()) - .unwrap_or(6); - for attempt in 0..n_attempts { - let seed = 42 + attempt; - let duration = frame_count as f64 / 25.0; - let source = match source_override { - Some(src) => format!("{src}=size={width}x{height}:duration={duration}:rate=25"), - None => { - gradients_source(seed, width, height, &format!("duration={duration}:rate=25")) - } - }; - let pix_fmt = if bit_depth == 10 { - "yuv420p10le" - } else { - "yuv420p" - }; - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-pix_fmt", - pix_fmt, - "-strict", - "-1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let cols = format!("--tile-columns={tile_cols_log2}"); - let rows = format!("--tile-rows={tile_rows_log2}"); - let limit = format!("--limit={frame_count}"); - let depth_args: Vec = if bit_depth == 10 { - vec![ - "--input-bit-depth=10".to_owned(), - "--bit-depth=10".to_owned(), - ] - } else { - Vec::new() - }; - let mut args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=40", - "--cpu-used=4", - &limit, - "--kf-max-dist=1000", - "--threads=1", - "--row-mt=0", - // This decoder is 64x64-superblock only, and `--tile-columns` - // splits on superblock boundaries, so 128x128 superblocks - // would leave 256px only two tiles' worth of columns. - "--sb-size=64", - &cols, - &rows, - // The point of this gate: tools ON across tile edges. - "--enable-rect-partitions=1", - "--enable-ab-partitions=1", - "--enable-cdef=1", - "--enable-restoration=1", - // Still off: capabilities this decoder refuses outright, which - // would turn every attempt into a refusal and make the gate - // vacuous rather than proving anything about tiles. - "--enable-1to4-partitions=0", - "--min-partition-size=16", - // Overridable by `extra` (aomenc takes the last occurrence of - // a repeated flag), which the palette arm below relies on. - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-ref-frame-mvs=0", - "--enable-global-motion=0", - ]; - args.extend(extra.iter().copied()); - args.extend(depth_args.iter().map(String::as_str)); - args.extend(["--obu", "-o", "-", "-"]); - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - - // The stream must really carry the tile grid asked for, or the - // gate proves nothing (aomenc silently clamps tile counts that do - // not fit the frame's superblock grid). - { - let mut probe = Av1Parser::new(); - let mut pos = 0usize; - let mut checked = false; - while pos < stream.len() { - let obu = probe - .parse_obu(&stream[pos..]) - .expect("parsing the gate stream"); - pos += obu.total_size; - let header = match &obu.kind { - ObuKind::Frame(h, _) => h, - ObuKind::FrameHeader(h) => h, - // lane-tiles r12: prove the base recipe's tools-on - // flags arrived (a repeated aomenc `--enable-*` keeps - // the LAST occurrence -- measured, see the report -- - // so a per-arm override must not silently vanish). - ObuKind::SequenceHeader(seq) => { - assert!( - seq.enable_cdef && seq.enable_restoration, - "{name}: --enable-cdef=1 --enable-restoration=1 did not reach \ - aomenc (seq enable_cdef={} enable_restoration={}, seed {seed})", - seq.enable_cdef, - seq.enable_restoration - ); - continue; - } - _ => continue, - }; - // A `show_existing_frame` header codes no tile info at all - // (spec 5.9.2 returns before `tile_info()`), so its - // `TileInfo` is the parser's 1x1 default -- checking it - // here would fail every inter stream for a header that - // carries no tiling. - if header.show_existing_frame { - continue; - } - if require_tile_left_palette { - assert!( - header.allow_screen_content_tools, - "{name}: --tune-content=screen/--enable-palette=1 did not reach \ - aomenc -- allow_screen_content_tools is 0 (seed {seed})" - ); - } - assert_eq!( - (header.tile_info.cols * header.tile_info.rows) as usize, - expected_tiles, - "{name}: aomenc wrote {}x{} tiles, not the {expected_tiles} asked for \ - (seed {seed})", - header.tile_info.cols, - header.tile_info.rows - ); - checked = true; - } - assert!( - checked, - "{name}: no frame header in the stream (seed {seed})" - ); - } - - let before = crate::decode::tile_hits(); - let pal_before = crate::decode::palette_tile_left_hits(); - let uv_edge_before = crate::decode::uv_tile_edge_suppressed_hits(); - let frames = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{name} failed outright, not a named refusal (seed {seed}): {msg}" - ); - named_refusals += 1; - eprintln!("seed {seed} refusal: {msg}"); - continue; - } - Ok(frames) => frames, - }; - let hits = crate::decode::tile_hits() - before; - assert!( - hits >= expected_tiles * frames.len(), - "{name}: tile_hits delta was {hits}, expected >= {} -- every tile of every \ - frame must actually decode (seed {seed})", - expected_tiles * frames.len() - ); - let ffmpeg_frames = if bit_depth == 10 { - ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len()) - } else { - ffmpeg_decode_sequence(&stream, width, height, frames.len()) - }; - let mismatched = frames - .iter() - .zip(&ffmpeg_frames) - .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); - if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") { - std::fs::write(&path, &stream).expect("writing pinned stream"); - eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}"); - } - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!( - got.y, want.y, - "{name} frame {i} luma vs ffmpeg (seed {seed})" - ); - assert_eq!(got.u, want.u, "{name} frame {i} U vs ffmpeg (seed {seed})"); - assert_eq!(got.v, want.v, "{name} frame {i} V vs ffmpeg (seed {seed})"); - } - if require_tile_left_palette { - let pal = crate::decode::palette_tile_left_hits() - pal_before; - assert!( - pal >= 1, - "{name}: this attempt decoded and matched but fired {pal} palette blocks at \ - a tile's left column -- the tile-relative palette cache guard is untested \ - (seed {seed})" - ); - } - // lane-mtfix r1: the chroma edge-filter neighbour of a block on a - // tile's first mi row/column lives in the tile above/left, where - // libaom has no neighbour at all. This counts the reads suppressed - // there whose frame-wide coarse slot held a non-DC mode -- the - // reads that would otherwise pick the wrong chroma edge filter - // strength (they did, before this fix: seed 46 of this gate). - uv_edge_suppressed += crate::decode::uv_tile_edge_suppressed_hits() - uv_edge_before; - matched += 1; - } - assert!( - matched > 0, - "{name}: every attempt refused ({named_refusals}); the gate never decoded a \ - multi-tile stream with the coding tools on" - ); - eprintln!( - "{name}: {matched} pixel-exact matches, {named_refusals} named refusals, \ - {uv_edge_suppressed} chroma edge reads suppressed at a tile edge" - ); - } - - /// The one recipe both 1:4-in-inter arms run, rewritten by - /// lane-av1recipehunt. What changed, and why the old sweep could not fire: - /// - /// * `--min-partition-size=32` -> **`8`**. This is the flag that was - /// holding the shape off the menu entirely. MEASURED over 96 encodes - /// (10-bit, 192x128 and 256x192, `--cpu-used` 0..5, cq 63/55, this - /// crate's full intra mode set): at `mps=16` the 32-level 1:4 counter is - /// **0 in all 48 attempts**, at `mps=8` it fires in 40 of 48. The old - /// comment's "min size 16 so the 16x16-level 1:4 is out of reach" was - /// protecting against a refusal that no longer fires -- `mps=8` reaches - /// the 8- and 16-level strips too, and on this content the RD takes - /// neither (the `inter16_1to4` and `rect4_32` inter counters confirm the - /// only 1:4 partitions in the stream are the 32-level ones this gate - /// asserts). - /// * the intra mode set: `--enable-smooth-intra/paeth-intra/ - /// directional-intra/angle-delta` `0` -> **`1`**. A 8x32 or 32x8 strip - /// has four usable intra modes with these on; with them off the only - /// candidate is DC, and DC never wins a 1:4 strip against inter. - /// * the 40-attempt content/preset/cq seed sweep -> one pinned cell at - /// 256x192, 6 frames, `--cpu-used=2 --cq-level=63`. A sweep hides a - /// recipe that works; a pin makes it a precondition. - /// - /// The 8-bit arm's `hue=s=0` and `-t 0.32` are dropped: they only fixed - /// ffmpeg's own frame count across the sweep, and the frame count is now - /// pinned by `-frames:v 6` (6 decode-order frames, `kf-min-dist=1000`, so - /// frame 0 is the only key frame and every counted strip is in an INTER - /// frame). - /// - /// **The recipe**, exactly (the recorded command lines): - /// ```text - /// ffmpeg -v error -y -f lavfi \ - /// -i mandelbrot=size=256x192:start_scale=5.0:end_scale=0.004:end_pts=8:rate=25 \ - /// -pix_fmt yuv420p -frames:v 6 -f yuv4mpegpipe - # 10-bit: yuv420p10le + -strict -1 - /// aomenc [--cpu-used=2 --input-bit-depth=10 -b 10] --codec=av1 --passes=1 --end-usage=q \ - /// --cpu-used=2 --cq-level=63 --threads=1 --row-mt=0 \ - /// --enable-rect-partitions=1 --enable-1to4-partitions=1 \ - /// --min-partition-size=8 --max-partition-size=64 --enable-tx-size-search=0 \ - /// --enable-filter-intra=1 --enable-intra-edge-filter=1 --enable-smooth-intra=1 \ - /// --enable-paeth-intra=1 --enable-directional-intra=1 --enable-angle-delta=1 \ - /// --lag-in-frames=0 --auto-alt-ref=0 --kf-min-dist=1000 --kf-max-dist=1000 \ - /// --enable-order-hint=0 --enable-warped-motion=0 --enable-obmc=0 \ - /// --enable-masked-comp=0 --enable-interintra-comp=0 --enable-dist-wtd-comp=0 \ - /// --enable-diff-wtd-comp=0 --enable-onesided-comp=0 --enable-interintra-wedge=0 \ - /// --enable-smooth-interintra=0 --enable-ab-partitions=0 --enable-cdef=0 \ - /// --enable-restoration=0 --enable-palette=0 --enable-intrabc=0 \ - /// --enable-cfl-intra=0 --enable-ref-frame-mvs=0 --obu -o - - - /// ``` - /// Sources: 8-bit 442462 bytes, sha256 - /// `e4b46799b180a0d3e138caa18b2738c035e349219490313db664814a3eae9ec2`; - /// 10-bit 884828 bytes, sha256 - /// `b7e0602e0bfc7a7f6813f40bb3989ec7574e5fbbfbf190298b9ab5b625156030`. - /// Outputs, committed with `git add -f` past the `fixtures` gitignore: - /// * `fixtures/intra14_256x192_8bit.obu`, 35179 bytes, sha256 - /// `5e50eb6d4492e806a2803988d92bd47f069ca54e02c06344d5500c6b72deb861` - /// (fnv1a64 `0x86f8d1e5a221162a`) -- MEASURED `32x8=8 8x32=11`, - /// `64x16=0 16x64=0`, all 6 frames pixel-exact vs ffmpeg. - /// * `fixtures/intra14_256x192_10bit.obu`, 34727 bytes, sha256 - /// `ab6fae0a256af6410e8200f10827a3e965dee7b2d7ab63710e94968bddab23a2` - /// (fnv1a64 `0xecf9455bc20d60f0`) -- MEASURED `32x8=12 8x32=7`, - /// all 6 frames pixel-exact vs ffmpeg. - /// - /// The gate re-encodes live and byte-compares against the pin, so the pin - /// is the expected output and not a second decode path. The control arm - /// re-runs the SAME command line with `--enable-1to4-partitions=0` and - /// requires the counter to stay at 0 -- that single flag is what carries - /// the coverage, and asserting it is also this gate's own red-proof. - pub(super) fn intra_rect4_in_inter_gate(bit_depth: u32) { - const NAME: &str = - "a_real_aomenc_inter_sequence_with_an_intra_1to4_strip_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height, frame_count) = (256usize, 192usize, 6usize); - let (src_len, src_sha, pin_name, pin_len, pin_fnv) = if bit_depth == 10 { - ( - 884_828usize, - "b7e0602e0bfc7a7f6813f40bb3989ec7574e5fbbfbf190298b9ab5b625156030", - "fixtures/intra14_256x192_10bit.obu", - 34_727usize, - 0xecf9_455b_c20d_60f0u64, - ) - } else { - ( - 442_462usize, - "e4b46799b180a0d3e138caa18b2738c035e349219490313db664814a3eae9ec2", - "fixtures/intra14_256x192_8bit.obu", - 35_179usize, - 0x86f8_d1e5_a221_162au64, - ) - }; - let mut source_args: Vec<&str> = vec![ - "-v", - "error", - "-y", - "-f", - "lavfi", - "-i", - "mandelbrot=size=256x192:start_scale=5.0:end_scale=0.004:end_pts=8:rate=25", - "-pix_fmt", - ]; - source_args.push(if bit_depth == 10 { - "yuv420p10le" - } else { - "yuv420p" - }); - source_args.extend(["-frames:v", "6"]); - if bit_depth == 10 { - // yuv420p10le is not an official yuv4mpegpipe format on this ffmpeg - source_args.extend(["-strict", "-1"]); - } - source_args.extend(["-f", "yuv4mpegpipe", "-"]); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args(&source_args) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - assert_eq!( - y4m.stdout.len(), - src_len, - "{NAME} ({bit_depth}-bit): the mandelbrot source is not the pinned 6-frame y4m -- \ - `rate=`, `end_pts` and `-frames:v` are all part of this recipe's identity" - ); - eprintln!("{NAME} ({bit_depth}-bit): source y4m sha256 {src_sha}"); - let mut args: Vec<&str> = Vec::new(); - if bit_depth == 10 { - args.extend(["-b", "10", "--input-bit-depth=10"]); - } - // Every flag spelled exactly once (class [[aomenc-last-flag-wins]]). - args.extend([ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cpu-used=2", - "--cq-level=63", - "--threads=1", - "--row-mt=0", - "--enable-rect-partitions=1", - // The feature this gate is about, and the flag the control arm - // below reverts. - "--enable-1to4-partitions=1", - // 8, not 16 or 32: MEASURED, the 32-level 1:4 counter is 0 in all - // 48 attempts at 16 and fires in 40 of 48 at 8. - "--min-partition-size=8", - "--max-partition-size=64", - "--enable-tx-size-search=0", - // A 1:4 strip needs an intra mode worth coding: with these four - // off the only candidate is DC and it never wins. - "--enable-filter-intra=1", - "--enable-intra-edge-filter=1", - "--enable-smooth-intra=1", - "--enable-paeth-intra=1", - "--enable-directional-intra=1", - "--enable-angle-delta=1", - // Single reference and one key frame, so every counted strip is - // inside an INTER frame. - "--lag-in-frames=0", - "--auto-alt-ref=0", - "--kf-min-dist=1000", - "--kf-max-dist=1000", - "--enable-order-hint=0", - "--enable-warped-motion=0", - "--enable-obmc=0", - "--enable-masked-comp=0", - "--enable-interintra-comp=0", - "--enable-dist-wtd-comp=0", - "--enable-diff-wtd-comp=0", - "--enable-onesided-comp=0", - "--enable-interintra-wedge=0", - "--enable-smooth-interintra=0", - "--enable-ab-partitions=0", - "--enable-cdef=0", - "--enable-restoration=0", - // Ledger dead-end (lane-r14): a NEW gate spelling - // `--enable-cfl-intra=1` retires that tool from - // `NEVER_EXERCISED_8BIT` on the flag alone while no CfL - // hit counter exists to assert -- so it stays 0 here. - // Palette stays 0 for the same class of reason: this arm - // refuses a screen-content frame whole, so a palette flag - // would buy no coverage. - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - "--enable-ref-frame-mvs=0", - "--obu", - "-o", - "-", - "-", - ]); - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - assert_eq!( - stream.len(), - pin_len, - "{NAME} ({bit_depth}-bit): encoded size moved" - ); - assert_eq!( - fnv1a64(&stream), - pin_fnv, - "{NAME} ({bit_depth}-bit): encoded bytes moved" - ); - let pin = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(pin_name); - assert_eq!( - std::fs::read(&pin).unwrap_or_else(|e| panic!("{pin_name} must be committed: {e}")), - stream, - "{NAME} ({bit_depth}-bit): the live encode no longer matches the committed pin" - ); - - let before: Vec = (0..4) - .map(decode::intra_rect4_strip_in_inter_hits) - .collect(); - let frames = decode_stream(&stream) - .unwrap_or_else(|e| panic!("{NAME} ({bit_depth}-bit): the pin must decode: {e}")); - let delta: Vec = (0..4) - .map(|k| decode::intra_rect4_strip_in_inter_hits(k) - before[k]) - .collect(); - let ffmpeg_frames = if bit_depth == 10 { - ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count) - } else { - ffmpeg_decode_sequence(&stream, width, height, frame_count) - }; - assert_eq!(frames.len(), frame_count); - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - for (plane, (g, w)) in [ - ("Y", (&got.y, &want.y)), - ("U", (&got.u, &want.u)), - ("V", (&got.v, &want.v)), - ] { - let stride = if plane == "Y" { width } else { width / 2 }; - if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) { - eprintln!( - "{NAME} ({bit_depth}-bit): frame {i} {plane} first diff at ({}, {})", - at % stride, - at / stride - ); - } - assert_eq!(g, w, "{plane} vs ffmpeg (frame {i})"); - } - } - assert!( - delta[2] + delta[3] > 0, - "{NAME} ({bit_depth}-bit): {frame_count} frames pixel-exact but no 32-level intra 1:4 \ - strip (32x8/8x32) fired (64x16={} 16x64={} 32x8={} 8x32={}) -- the recipe stopped \ - producing the shape this gate names (class gate-blind-to-feature)", - delta[0], - delta[1], - delta[2], - delta[3] - ); - - // The control arm: the one flag that is this gate's feature, reverted. - // If it ever fires too, 1:4 is no longer what puts these strips on the - // RD menu and the feature arm above is not the witness it claims to be. - // It is also this gate's own red-proof. - let mut control = args.clone(); - let at = control - .iter() - .position(|a| *a == "--enable-1to4-partitions=1") - .expect("the feature flag is in the recipe"); - control[at] = "--enable-1to4-partitions=0"; - let ctl = run_with_stdin(Command::new(aomenc_path()).args(&control), &y4m.stdout); - assert!( - ctl.status.success(), - "aomenc refused the --enable-1to4-partitions=0 control: {}", - String::from_utf8_lossy(&ctl.stderr) - ); - let ctl_before: Vec = (0..4) - .map(decode::intra_rect4_strip_in_inter_hits) - .collect(); - decode_stream(&ctl.stdout) - .unwrap_or_else(|e| panic!("{NAME}: the control stream must decode too: {e}")); - let ctl_delta: Vec = (0..4) - .map(|k| decode::intra_rect4_strip_in_inter_hits(k) - ctl_before[k]) - .collect(); - assert_eq!( - ctl_delta, [0; 4], - "{NAME} ({bit_depth}-bit): the --enable-1to4-partitions=0 control fired \ - 64x16={} 16x64={} 32x8={} 8x32={} -- 1:4 partitions are no longer what produce these \ - strips, so the feature arm above is not witnessing what it names", - ctl_delta[0], ctl_delta[1], ctl_delta[2], ctl_delta[3] - ); - gate_buckets(NAME, 1, 0, 0); - eprintln!( - "{NAME} ({bit_depth}-bit): {frame_count} frames pixel-exact, intra 1:4 strips in inter \ - frames 64x16={} 16x64={} 32x8={} 8x32={} (--enable-1to4-partitions=0 control: \ - 0/0/0/0), stream {pin_len} B fnv1a64={pin_fnv:016x}", - delta[0], delta[1], delta[2], delta[3] - ); - } - - pub(super) fn intra_rect_in_inter_split_tx_gate(bit_depth: u32) { - let name = format!("intra_rect_in_inter_split_tx_gate({bit_depth})"); - if !have_ffmpeg() { - eprintln!("SKIP {name}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display()); - return; - } - // lane-intrasplit r3, MEASURED (probe3, 20 attempts x 2 depths): at - // 192x128 with `--min/--max-partition-size=32` a correctly decoded - // stream contains ZERO intra HORZ/VERT strips in an inter frame -- the - // r1/r2 "firing" counters were read off our own desynced decode (class - // counter-from-refused-stream). The merged unsplit-strip gate's own - // geometry (96x96, min 16 / max 64) is the one that makes aomenc's RD - // pick intra strips here, and at `--enable-tx-size-search=1` it splits - // their transforms: 10-bit attempt 0 = 8 strips, 3 split; 8-bit - // attempt 0 = 5 strips, 1 split. - let (width, height, frame_count) = (96usize, 96usize, 8usize); - let mut refusals = Vec::new(); - let mut uncounted_exact = 0u32; - let mut counted_exact = 0u32; - let mut seen = [0usize; 3]; - for attempt in 0..40u32 { - let seed = 42 + attempt; - // MEASURED (r1, 40 attempts): the same sweep the merged - // `intra_rect_in_inter_gate` had to make -- at `--cpu-used=0` - // aomenc emits AB partitions regardless of - // `--enable-ab-partitions=0` (ledger), so the preset is swept - // 1..4, and the quantiser with it (a hard-cut overlay source at - // cpu-used=0 stopped 38/40 attempts on other lanes' refusals). - let cpu = attempt % 5; - let cq = [30u32, 20, 12, 4][((attempt / 5) % 4) as usize]; - // A FAST ZOOM: consecutive frames share almost no content, so - // aomenc's RD codes blocks INTRA inside INTER frames - // (`--kf-min-dist` forbids a new key frame) -- the only way a - // real encoder reaches this decoder's intra-in-inter arm -- and - // the fractal's fine detail is what then splits their transforms. - let source = format!( - "mandelbrot=size={width}x{height}:start_scale={}:end_scale=0.004:end_pts=8:rate=25", - 5.0 - f64::from(attempt) * 0.06 - ); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - // Desaturated chroma keeps `uv_mode` on DC_PRED, so the - // still-refused directional-chroma gaps never fire and - // luma detail alone drives the transform split. - "-vf", - "hue=s=0", - "-pix_fmt", - if bit_depth == 10 { - "yuv420p10le" - } else { - "yuv420p" - }, - "-strict", - "-1", - "-t", - "0.32", - "-f", - "yuv4mpegpipe", - "-strict", - "-1", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let depth_args: &[&str] = if bit_depth == 10 { - &["-b", "10", "--input-bit-depth=10"] - } else { - &[] - }; - let cq_arg = format!("--cq-level={cq}"); - let cpu_arg = format!("--cpu-used={cpu}"); - let out = run_with_stdin( - Command::new(aomenc_path()).args(depth_args).args([ - "--codec=av1", - "--passes=1", - "--end-usage=q", - &cq_arg, - &cpu_arg, - "--lag-in-frames=0", - "--auto-alt-ref=0", - "--kf-max-dist=9999", - "--kf-min-dist=9999", - "--threads=1", - "--row-mt=0", - "--enable-order-hint=0", - "--enable-warped-motion=0", - "--enable-obmc=0", - "--enable-masked-comp=0", - "--enable-interintra-comp=0", - "--enable-dist-wtd-comp=0", - "--enable-diff-wtd-comp=0", - "--enable-onesided-comp=0", - "--enable-interintra-wedge=0", - "--enable-smooth-interintra=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-cdef=0", - "--enable-restoration=0", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - "--enable-ref-frame-mvs=0", - "--min-partition-size=16", - "--max-partition-size=64", - // Per-arm overrides go LAST (aomenc keeps the last - // occurrence of a repeated --enable-* flag): this gate - // needs the rect partitions the strip lives in and the - // tx_depth symbol, which exists only under TX_MODE_SELECT. - "--enable-rect-partitions=1", - "--enable-tx-size-search=1", - "--obu", - "-o", - "-", - "-", - ]), - &y4m.stdout, - ); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let before = decode::intra_rect_in_inter_split_tx_hits(); - let frames = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{name} decode failed outright (seed {seed} cq {cq}): {msg}" - ); - refusals.push(format!("seed {seed} cq {cq} cpu {cpu}: {msg}")); - continue; - } - }; - let after = decode::intra_rect_in_inter_split_tx_hits(); - let mut per_depth = [0usize; 3]; - for i in 0..3 { - per_depth[i] = after[i] - before[i]; - } - // class [[gate-skips-on-its-own-failure]]: a decode that - // succeeded is ALWAYS pixel-compared below; the counter only - // decides whether the attempt counts as firing. - let counted = per_depth[1] + per_depth[2] != 0; - if !counted { - uncounted_exact += 1; - refusals.push(format!( - "seed {seed} cq {cq} cpu {cpu}: decoded and pixel-compared, but no intra rect strip \ - in an inter frame split its transform" - )); - } - let ffmpeg_frames = if bit_depth == 10 { - ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count) - } else { - ffmpeg_decode_sequence(&stream, width, height, frame_count) - }; - assert_eq!(frames.len(), frame_count); - eprintln!( - "{name} seed={seed} cq={cq} cpu={cpu}: split intra strips depth1={} depth2={}", - per_depth[1], per_depth[2] - ); - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - for (plane, (g, w)) in [ - ("Y", (&got.y, &want.y)), - ("U", (&got.u, &want.u)), - ("V", (&got.v, &want.v)), - ] { - let stride = if plane == "Y" { width } else { width / 2 }; - if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) { - eprintln!( - "{name} seed={seed}: frame {i} {plane} first diff at ({}, {}) got {} \ - want {} ({} samples differ)", - at % stride, - at / stride, - g[at], - w[at], - g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(), - ); - } - } - } - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!( - got.y, want.y, - "frame {i} luma vs ffmpeg (seed {seed} cq {cq})" - ); - assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed} cq {cq})"); - assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed} cq {cq})"); - } - if counted { - counted_exact += 1; - seen[1] += per_depth[1]; - seen[2] += per_depth[2]; - // Keep sweeping until BOTH reachable depths have been seen in - // a pixel-exact attempt; one firing attempt is the floor. - if seen[1] != 0 && seen[2] != 0 { - break; - } - } - } - gate_buckets( - &name, - counted_exact, - uncounted_exact, - refusals.len() - uncounted_exact as usize, - ); - eprintln!( - "{name}: split strips seen depth1={} depth2={}", - seen[1], seen[2] - ); - assert!( - seen[1] + seen[2] != 0, - "{name} never observed a split-transform intra strip in an inter frame:\n{}", - refusals.join("\n") - ); - } - - pub(super) fn screen_rect_intra_palette_syntax_gate(bit_depth: u32) { - let name = format!("screen_rect_intra_palette_syntax_gate({bit_depth})"); - if !have_ffmpeg() { - eprintln!("SKIP {name}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height, frame_count) = (256usize, 192usize, 10usize); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - "testsrc2=s=256x192:r=25", - "-t", - "0.4", - "-pix_fmt", - "yuv420p", - "-strict", - "-1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "{name}: ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - // The source stays 8-bit for both arms: `--bit-depth=10 - // --input-bit-depth=8` is the recipe that was measured to reach the - // refusal, and the arm's point is the coded syntax, not the input. - let depth_arg = format!("--bit-depth={bit_depth}"); - let cq_arg = format!("--cq-level={}", if bit_depth == 10 { 45 } else { 40 }); - let out = run_with_stdin( - Command::new(aomenc_path()) - .args([ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cpu-used=0", - "--lag-in-frames=0", - "--kf-max-dist=30", - "--limit=10", - "--threads=1", - "--tile-columns=0", - "--enable-rect-partitions=1", - "--enable-1to4-partitions=1", - "--min-partition-size=8", - "--sb-size=64", - "--input-bit-depth=8", - // `allow_screen_content_tools` in every frame header comes - // from here; the two searches below stay off so the KEY frame - // does not stop on a palette/intrabc RECONSTRUCTION refusal - // before an inter frame exists. - "--tune-content=screen", - "--enable-palette=0", - "--enable-intrabc=0", - ]) - .args([&depth_arg, &cq_arg]) - .args(["--obu", "-o", "-", "-"]), - &y4m.stdout, - ); - assert!( - out.status.success(), - "{name}: aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - decode::reset_intra_rect_in_inter_screen_hits(); - let frames = decode_stream(&stream).unwrap_or_else(|e| { - panic!("{name}: decode failed -- the case this gate exists for: {e}") - }); - let strips = decode::intra_rect_in_inter_screen_hits(); - eprintln!( - "{name}: {} frames, {strips} rect intra strip(s) read the palette syntax", - frames.len() - ); - assert_eq!(frames.len(), frame_count, "{name}: frame count"); - let ffmpeg_frames = if bit_depth == 10 { - ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count) - } else { - ffmpeg_decode_sequence(&stream, width, height, frame_count) - }; - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!(got.y, want.y, "{name}: frame {i} luma vs ffmpeg"); - assert_eq!(got.u, want.u, "{name}: frame {i} U vs ffmpeg"); - assert_eq!(got.v, want.v, "{name}: frame {i} V vs ffmpeg"); - } - assert!( - strips > 0, - "{name}: no rect intra strip of a screen-content frame read the palette syntax -- \ - the gate is vacuous, the recipe stopped producing the shape" - ); - } diff --git a/crates/ec-av1/src/stream/tests/mod.rs b/crates/ec-av1/src/stream/tests/mod.rs index 07bf7a39..d23664e1 100644 --- a/crates/ec-av1/src/stream/tests/mod.rs +++ b/crates/ec-av1/src/stream/tests/mod.rs @@ -1,22 +1,6 @@ use super::*; -use crate::encode::{Picture as Pic, encode_sequence_with_ctx}; -use crate::probe::run_with_stdin; -use std::process::{Command, Stdio}; +use crate::encode::Picture as Pic; -mod gates_a; -mod gates_b; mod layers; mod streaming; -mod support; -mod t01; -mod t02; -mod t03; -mod t04; -mod t05; -mod t06; -mod t07; -mod t08; -mod t09; -mod t10; -pub(crate) use gates_a::lock_gate_counters; diff --git a/crates/ec-av1/src/stream/tests/support.rs b/crates/ec-av1/src/stream/tests/support.rs deleted file mode 100644 index e53f98a4..00000000 --- a/crates/ec-av1/src/stream/tests/support.rs +++ /dev/null @@ -1,4172 +0,0 @@ -use super::*; -use super::gates_a::*; - - pub(super) fn test_card(width: usize, height: usize) -> Pic { - let mut picture = Pic::grey(width, height); - for row in 0..height { - for col in 0..width { - picture.y[row * width + col] = ((row * 7 + col * 11) % 251) as u16; - } - } - for row in 0..height / 2 { - for col in 0..width / 2 { - let i = row * width / 2 + col; - picture.u[i] = (100 + (col * 60 / (width / 2).max(1))) as u16; - picture.v[i] = (200 - (row * 80 / (height / 2).max(1))) as u16; - } - } - picture - } - - pub(super) fn panned_test_card(width: usize, height: usize, shift: i64) -> Pic { - let mut picture = Pic::grey(width, height); - for y in 0..height { - for x in 0..width { - let sx = (x as i64 - shift).rem_euclid(width as i64) as f64; - let gradient = sx * 200.0 / width as f64; - picture.y[y * width + x] = (20.0 + gradient).clamp(0.0, 255.0) as u16; - } - } - for y in 0..height / 2 { - for x in 0..width / 2 { - let sx = (x as i64 - shift / 2).rem_euclid((width / 2) as i64) as usize; - let i = y * width / 2 + x; - picture.u[i] = (100 + (sx * 60 / (width / 2))) as u16; - picture.v[i] = (200 - (y * 80 / (height / 2))) as u16; - } - } - picture - } - - /// One census attempt: encode `frames` frames of `source` with real - /// aomenc plus `extra` args, decode with THIS decoder, and return the - /// stream's byte length with either the picture count or the refusal (any - /// decode error) it produced. A census is about what the encoder emits, - /// so a refusal is data here, not a failure. - pub(super) fn census_attempt( - source: &str, - width: usize, - height: usize, - frames: usize, - extra: &[&str], - ) -> (usize, std::result::Result) { - let duration = format!("{}", frames as f64 / 25.0); - let src = format!("{source}=size={width}x{height}:rate=25"); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &src, - "-t", - &duration, - "-pix_fmt", - "yuv420p", - "-strict", - "-1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg refused the {width}x{height} fixture" - ); - let limit = format!("--limit={frames}"); - let mut args: Vec = [ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--threads=1", - "--row-mt=0", - "--kf-max-dist=9999", - "--lag-in-frames=0", - ] - .iter() - .map(|s| (*s).to_owned()) - .collect(); - args.push(limit); - args.extend(extra.iter().map(|s| (*s).to_owned())); - args.extend([ - "--obu".to_owned(), - "-o".to_owned(), - "-".to_owned(), - "-".to_owned(), - ]); - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused {args:?}: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let result = match decode_stream(&stream) { - Ok(pictures) => Ok(pictures.len()), - Err(e) => Err(e.to_string()), - }; - (stream.len(), result) - } - - /// lane-av1seglvl: encode `frames` frames of `source` with real aomenc - /// plus `extra` args and return the raw `.obu` bytes -- the census's - /// half-sibling of [`census_attempt`] that keeps the STREAM instead of - /// only its decode verdict, so the caller can parse the frame headers' - /// segmentation tables themselves. - pub(super) fn encode_aomenc_stream( - source: &str, - width: usize, - height: usize, - frames: usize, - extra: &[&str], - ) -> Vec { - let duration = format!("{}", frames as f64 / 25.0); - let src = format!("{source}=size={width}x{height}:rate=25"); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &src, - "-t", - &duration, - "-pix_fmt", - "yuv420p", - "-strict", - "-1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg refused the {width}x{height} fixture" - ); - let limit = format!("--limit={frames}"); - let mut args: Vec = [ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--threads=1", - "--row-mt=0", - "--kf-max-dist=9999", - "--lag-in-frames=0", - ] - .iter() - .map(|s| (*s).to_owned()) - .collect(); - args.push(limit); - args.extend(extra.iter().map(|s| (*s).to_owned())); - args.extend([ - "--obu".to_owned(), - "-o".to_owned(), - "-".to_owned(), - "-".to_owned(), - ]); - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused {args:?}: {}", - String::from_utf8_lossy(&out.stderr) - ); - out.stdout - } - - /// lane-av1seglvl: encode `frames` frames with a real TWO-PASS aomenc - /// (pass 1 writes the stats file into the session temp dir, pass 2 - /// consumes it) and return the `.obu` bytes. This is the only shape that - /// reaches libaom's `is_stat_consumption_stage_twopass` segmentation - /// setup (`configure_static_seg_features`), so the census is not proven - /// over the encoder's whole reachable surface without it. - pub(super) fn encode_aomenc_stream_twopass( - source: &str, - width: usize, - height: usize, - frames: usize, - extra: &[&str], - ) -> Vec { - let duration = format!("{}", frames as f64 / 25.0); - let src = format!("{source}=size={width}x{height}:rate=25"); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &src, - "-t", - &duration, - "-pix_fmt", - "yuv420p", - "-strict", - "-1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg refused the {width}x{height} fixture" - ); - let limit = format!("--limit={frames}"); - let fpf = - std::env::temp_dir().join(format!("ec-av1-segldapass-{}.fpf", std::process::id())); - let mut base: Vec = [ - "--codec=av1", - "--passes=2", - "--end-usage=q", - "--threads=1", - "--row-mt=0", - "--kf-max-dist=9999", - "--lag-in-frames=0", - ] - .iter() - .map(|s| (*s).to_owned()) - .collect(); - base.push(limit); - base.extend(extra.iter().map(|s| (*s).to_owned())); - let mut pass1 = base.clone(); - pass1.extend(["--pass=1".to_owned(), format!("--fpf={}", fpf.display())]); - pass1.extend([ - "--obu".to_owned(), - "-o".to_owned(), - "/dev/null".to_owned(), - "-".to_owned(), - ]); - let out1 = run_with_stdin(Command::new(aomenc_path()).args(&pass1), &y4m.stdout); - assert!( - out1.status.success(), - "aomenc pass 1 refused {pass1:?}: {}", - String::from_utf8_lossy(&out1.stderr) - ); - let mut pass2 = base; - pass2.extend(["--pass=2".to_owned(), format!("--fpf={}", fpf.display())]); - pass2.extend([ - "--obu".to_owned(), - "-o".to_owned(), - "-".to_owned(), - "-".to_owned(), - ]); - let out2 = run_with_stdin(Command::new(aomenc_path()).args(&pass2), &y4m.stdout); - let _ = std::fs::remove_file(&fpf); - assert!( - out2.status.success(), - "aomenc pass 2 refused {pass2:?}: {}", - String::from_utf8_lossy(&out2.stderr) - ); - out2.stdout - } - - /// lane-av1seglvl: walk every frame OBU of `stream` and tally which - /// `SEG_LVL` features the frame headers actually ENABLE, plus the shape - /// counters a census premise is asserted against: frames with - /// segmentation on, of which `update_map == 1` (the map is coded) and - /// `update_map == 0` (every block's id is INHERITED), and frames whose - /// table carries a real `SEG_LVL_ALT_Q` delta. - /// The last vector counts per SEGMENT-FEATURE INSTANCE (a frame with - /// ALT_Q on all 8 segments contributes 8), which is all the verdict - /// needs: only index `SEG_LVL_ALT_Q` may be non-zero. - /// Returns `(enabled_frames, update_map_frames, inherited_frames, - /// alt_q_frames, feature_instances: [usize; SEG_LVL_MAX])`. - #[allow(clippy::type_complexity)] - pub(super) fn segmentation_feature_census( - stream: &[u8], - ) -> (usize, usize, usize, usize, [usize; SEG_LVL_MAX]) { - let mut parser = Av1Parser::new(); - let obus = parser - .parse_temporal_unit(stream) - .unwrap_or_else(|e| panic!("the census stream does not even parse: {e}")); - let mut enabled = 0usize; - let mut update_map = 0usize; - let mut inherited = 0usize; - let mut alt_q = 0usize; - let mut feature_frames = [0usize; SEG_LVL_MAX]; - for obu in &obus { - if let ObuKind::Frame(header, _) = &obu.kind { - let seg = &header.segmentation; - if !seg.enabled { - continue; - } - enabled += 1; - if seg.update_map { - update_map += 1; - } else { - inherited += 1; - } - let mut any_q = false; - for segment in 0..MAX_SEGMENTS { - // Index loop mirrors the spec's per-position form over several offsets; an iterator would obscure it. - #[allow(clippy::needless_range_loop)] - for feature in 0..SEG_LVL_MAX { - if seg.feature_enabled[segment][feature] { - feature_frames[feature] += 1; - if feature == SEG_LVL_ALT_Q { - any_q = true; - } - } - } - } - if any_q { - alt_q += 1; - } - } - } - (enabled, update_map, inherited, alt_q, feature_frames) - } - - /// lane-interedge r1: one attempt of the inter frame-edge half-strip gate -- - /// encode `width x height` with real aomenc (rect partitions ON, every other - /// lane's open tool pinned off), decode it, and return - /// `(inter_edge_strip hits, frames whose LUMA differs, frames whose CHROMA - /// differs)` against ffmpeg. A refusal or a decode error is a hard failure: - /// this recipe reached every size without one (measured r1). - pub(super) fn inter_edge_strip_attempt( - name: &str, - width: usize, - height: usize, - bit_depth: u32, - cq: u32, - frames: usize, - ) -> ([usize; 6], usize, usize) { - let duration = format!("{}", frames as f64 / 25.0); - let source = format!("mandelbrot=size={width}x{height}:rate=25"); - let pix_fmt = if bit_depth == 10 { - "yuv420p10le" - } else { - "yuv420p" - }; - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-t", - &duration, - "-pix_fmt", - pix_fmt, - "-strict", - "-1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "{name}: ffmpeg refused the {width}x{height} {bit_depth}-bit fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let depth_arg = format!("--bit-depth={bit_depth}"); - let input_depth_arg = format!("--input-bit-depth={bit_depth}"); - let cq_arg = format!("--cq-level={cq}"); - let limit_arg = format!("--limit={frames}"); - let out = run_with_stdin( - Command::new(aomenc_path()).args([ - "--codec=av1", - "--passes=1", - "--end-usage=q", - &cq_arg, - // cpu-used >= 1 keeps libaom on 64x64 superblocks at these - // sizes (`av1_select_sb_size`). - "--cpu-used=4", - "--threads=1", - "--row-mt=0", - "--kf-max-dist=9999", - &limit_arg, - // decode order == display order, so the compare below covers - // every frame the stream carries (class gate-blind-to-hidden-frames). - "--lag-in-frames=0", - &depth_arg, - &input_depth_arg, - // Rect partitions stay ON: the frame-edge strip is a FORCED - // (gathered) HORZ/VERT, but with rect coding off the encoder - // answers that gathered symbol SPLIT every time and no edge - // strip ever fires (lane-oddh r2's finding, re-measured r1). - "--enable-rect-partitions=1", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--min-partition-size=8", - "--max-partition-size=64", - // Other lanes' open gaps this recipe must not trip. - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-warped-motion=0", - "--enable-obmc=0", - "--enable-masked-comp=0", - "--enable-interintra-comp=0", - "--enable-onesided-comp=0", - "--enable-interintra-wedge=0", - "--enable-smooth-interintra=0", - "--enable-ref-frame-mvs=0", - "--enable-angle-delta=0", - "--enable-cfl-intra=0", - "--enable-directional-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-filter-intra=0", - "--enable-tx-size-search=0", - "--obu", - "-o", - "-", - "-", - ]), - &y4m.stdout, - ); - assert!( - out.status.success(), - "aomenc refused: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - - // Reset, never a delta: a refused attempt's hits must not leak into the - // next one (class counter-from-refused-stream). - crate::decode::reset_inter_edge_strip_hits(); - let decoded = decode_stream(&stream).unwrap_or_else(|e| { - panic!("{name}: {width}x{height} {bit_depth}-bit cq {cq} did not decode: {e}") - }); - let hits = crate::decode::inter_edge_strip_hits(); - let reference = if bit_depth == 10 { - ffmpeg_decode_sequence_10bit(&stream, width, height, frames) - } else { - ffmpeg_decode_sequence(&stream, width, height, frames) - }; - assert_eq!( - decoded.len(), - reference.len(), - "{name}: {width}x{height} {bit_depth}-bit cq {cq} frame count" - ); - assert!( - decoded.len() >= frames, - "{name}: {width}x{height} {bit_depth}-bit cq {cq} decoded only {} frames", - decoded.len() - ); - let (mut luma_bad, mut chroma_bad) = (0usize, 0usize); - for (ours, theirs) in decoded.iter().zip(&reference) { - if ours.y != theirs.y { - luma_bad += 1; - } - if ours.u != theirs.u || ours.v != theirs.v { - chroma_bad += 1; - } - } - (hits, luma_bad, chroma_bad) - } - - /// A GOP (key frame plus panned inter frames, so blocks actually take - /// motion) decodes bit-exact through `decode_stream` alone, threading its - /// own DPB rather than a test-supplied reference. - pub(super) fn gop_round_trips(width: usize, height: usize, fctx: &crate::decode::FrameCtx) { - let pictures: Vec<_> = (0..4) - .map(|i| panned_test_card(width, height, i * 3)) - .collect(); - let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); - let decoded = decode_stream(&encoded.stream).unwrap(); - assert_eq!(decoded.len(), encoded.frames.len()); - for (i, (got, frame)) in decoded.iter().zip(&encoded.frames).enumerate() { - assert_eq!( - got.y, frame.reconstruction.y, - "{width}x{height} frame {i} luma" - ); - assert_eq!( - got.u, frame.reconstruction.u, - "{width}x{height} frame {i} U" - ); - assert_eq!( - got.v, frame.reconstruction.v, - "{width}x{height} frame {i} V" - ); - } - } - - /// Firing-detection gates (single-ref envelope, temporal-MV, `comp_mode`, - /// `skip_mode`/compound) all read a process-global atomic counter delta - /// (`decode::ref_hits`/`tmv_hits`/`comp_mode_hits`/`skip_mode_hits`) to - /// prove a real block picked the feature under test, not just that a - /// header bit was set. Under `cargo test`'s default parallel run, a - /// SIBLING test's own decode bumps the same global counter mid-gate -- - /// a false "fired" reading pixel-compares an attempt the gate would - /// otherwise `continue` past, on top of genuine defects that path may - /// still have. Serialising every counter-delta gate behind this one - /// mutex makes firing detection honest again (matches the existing - /// cdf-forwarding-gate flake shape, ledger `omp-liveness-pgrep-self-match`). - pub(super) static GATE_COUNTER_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); - - /// lane-cdfflake: a cheap, dependency-free (FNV-1a, not cryptographic -- - /// this is a load-bearing-identity fingerprint for flake triage, not a - /// security digest, so no `sha2` dep is pulled in) fixture fingerprint - /// for the cdf-forwarding gate's instrumentation below. - /// Reads a pinned fixture, asserting its length and FNV first, so a - /// swapped or truncated pin fails loudly instead of silently changing - /// what the gate measures. - pub(super) fn read_pin(path: &std::path::Path, len: usize, fnv: u64, name: &str) -> Vec { - let bytes = std::fs::read(path).unwrap_or_else(|e| { - panic!( - "{name}: pinned fixture {} is missing ({e}) -- the gate cannot run, \ - which is a failure, not a skip", - path.display() - ) - }); - assert_eq!(bytes.len(), len, "{name}: fixture length moved"); - assert_eq!(fnv1a64(&bytes), fnv, "{name}: fixture bytes moved"); - bytes - } - - /// The bit depth the stream's OWN sequence header declares, read from - /// the bytes rather than taken from the gate's name or recipe (class - /// `helper-packs-u16-for-an-8-bit-stream`: aomdec's `--rawvideo` - /// writes 8 bits per sample for an 8-bit stream and 16 bits LE for a - /// high-bitdepth one, so a u16 packer turns every 8-bit compare into a - /// raw-SIZE failure that never looks at a sample). - pub(super) fn stream_bit_depth(stream: &[u8], name: &str) -> u8 { - let mut probe = Av1Parser::new(); - let mut pos = 0usize; - while pos < stream.len() && probe.sequence_header().is_none() { - let obu = probe - .parse_obu(&stream[pos..]) - .unwrap_or_else(|e| panic!("{name}: OBU at byte {pos} does not parse: {e:?}")); - pos += obu.total_size; - } - probe - .sequence_header() - .unwrap_or_else(|| panic!("{name}: the stream carries no sequence header OBU")) - .color_config - .bit_depth - } - - /// The stream's OWN `color_config.subsampling_x/y` (spec 5.5.2), read - /// from its bytes the same way [`stream_bit_depth`] reads the depth. - pub(super) fn stream_subsampling(stream: &[u8], name: &str) -> (u8, u8) { - let mut probe = Av1Parser::new(); - let mut pos = 0usize; - while pos < stream.len() && probe.sequence_header().is_none() { - let obu = probe - .parse_obu(&stream[pos..]) - .unwrap_or_else(|e| panic!("{name}: OBU at byte {pos} does not parse: {e:?}")); - pos += obu.total_size; - } - let cc = &probe - .sequence_header() - .unwrap_or_else(|| panic!("{name}: the stream carries no sequence header OBU")) - .color_config; - (cc.subsampling_x, cc.subsampling_y) - } - - /// The chroma shape a `(subsampling_x, subsampling_y)` pair means. - pub(super) fn chroma_shape(sx: u8, sy: u8) -> &'static str { - match (sx, sy) { - (1, 1) => "4:2:0", - (1, 0) => "4:2:2", - (0, 0) => "4:4:4", - (0, 1) => "4:4:0", - _ => "an unassigned subsampling", - } - } - - /// lane-av1oracleguard: HARD REFUSAL for the 4:2:0 ffmpeg oracle helpers. - /// - /// `ffmpeg_decode_sequence`, `ffmpeg_decode_sequence_10bit` and - /// `ffmpeg_decode_sequence_12bit` ask ffmpeg for `-pix_fmt yuv420p*` and - /// size chroma at `width * height / 4`. Those are the 4:2:0 numbers, so - /// for a stream that is NOT (1,1) ffmpeg does not fail -- it CONVERTS, - /// and the helper then slices a 4:2:0-shaped picture out of it. A 4:2:2 - /// gate built on one of them compares the wrong planes and passes green: - /// the exact failure `lanes/av1subsizesweep.report.md` names. The correct - /// siblings (`ffmpeg_decode_sequence_422` / `_422_depth` / - /// `ffmpeg_decode_sequence_444`) exist and take the same bytes, so the - /// refusal points at them by name rather than leaving the caller to - /// rediscover the shape. - /// - /// Refused by SUBSAMPLING read from the stream's own sequence header, not - /// from the caller's `width`/`height` (class - /// `helper-assumes-the-shape-the-gate-name-implies`). - pub(super) fn assert_420_oracle_stream(stream: &[u8], helper: &str, sibling: &str) { - let (sx, sy) = stream_subsampling(stream, helper); - assert!( - (sx, sy) == (1, 1), - "{helper} REFUSED a ({sx},{sy}) stream: this helper asks ffmpeg for a 4:2:0 \ - pix_fmt, which CONVERTS the stream's real {} chroma down to 4:2:0 instead of \ - failing, then sizes chroma at `width * height / 4` rather than the {} shape. A \ - gate built on it would compare converted planes against real ones and pass green. \ - Use `{sibling}` for a ({sx},{sy}) stream.", - chroma_shape(sx, sy), - chroma_shape(sx, sy), - ); - } - - /// lane-av1oracleguard: run `f`, return the panic MESSAGE it raised (or - /// `None` if it did not panic). The panic hook is silenced so a refusal - /// that PASSES its gate prints nothing -- the assertion is the return. - pub(super) fn panic_message(f: F) -> Option { - let hook = std::panic::take_hook(); - std::panic::set_hook(Box::new(|_| {})); - let caught = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)); - std::panic::set_hook(hook); - match caught { - Ok(()) => None, - Err(payload) => Some( - payload - .downcast_ref::() - .cloned() - .or_else(|| payload.downcast_ref::<&str>().map(|s| (*s).to_string())) - .unwrap_or_else(|| "".to_string()), - ), - } - } - - /// Packs decoded planes the way `aomdec --rawvideo` writes them for - /// `bit_depth`: 1 byte per sample at 8-bit, 2 bytes little-endian at - /// 10/12-bit. Plane order is Y, U, V at the frame's own subsampled - /// shape, which is exactly what rawvideo emits. - pub(super) fn pack_rawvideo(decoded: &[Pic], bit_depth: u8, name: &str) -> Vec { - let mut ours: Vec = Vec::new(); - for (fi, f) in decoded.iter().enumerate() { - for p in [&f.y, &f.u, &f.v] { - if bit_depth == 8 { - for &s in p { - assert!( - s <= 0xff, - "{name}: decode-order frame {fi} carries the sample {s}, which an \ - 8-bit stream cannot hold -- the stream is not the one this gate thinks \ - it is" - ); - ours.push(s as u8); - } - } else { - for &s in p { - ours.extend_from_slice(&s.to_le_bytes()); - } - } - } - } - ours - } - - /// Decodes `stream` and the oracle's `aomdec --rawvideo` output and - /// requires every sample of every frame to agree, in decode order. - /// - /// `bit_depth` is the depth the CALLER believes the stream has; it is - /// asserted against the stream's own sequence header, so a gate that - /// hands this an 8-bit stream under a 10-bit label fails here by name - /// instead of dying on a raw-size mismatch that reads like a pixel bug. - pub(super) fn assert_rawvideo_matches( - obu: &std::path::Path, - stream: &[u8], - name: &str, - frames: usize, - bit_depth: u8, - ) { - let actual_depth = stream_bit_depth(stream, name); - assert_eq!( - actual_depth, bit_depth, - "{name}: the stream's sequence header says {actual_depth}-bit, the gate passed \ - {bit_depth}-bit -- aomdec's --rawvideo writes {actual_depth} bits per sample for it, \ - so packing for {bit_depth} compares nothing" - ); - let dir = std::env::temp_dir().join(format!("ec-av1-{name}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).expect("scratch dir"); - let raw = dir.join("aomdec.raw"); - let out = crate::tool_cache::cached_output_io(Command::new(aomdec_path()) - .args(["--codec=av1", "--rawvideo", "-o"]) - .arg(&raw) - .arg(obu) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("aomdec failed to run"); - assert!( - out.status.success(), - "{name}: the oracle aomdec refused the stream: {}", - String::from_utf8_lossy(&out.stderr) - ); - let ref_raw = std::fs::read(&raw).expect("aomdec rawvideo output"); - let _ = std::fs::remove_dir_all(&dir); - let decoded = decode_stream(stream).expect("decode for comparison"); - let ours = pack_rawvideo(&decoded, bit_depth, name); - assert_eq!( - ours.len(), - ref_raw.len(), - "{name}: {bit_depth}-bit raw sizes differ -- ours packs {} bytes ({} samples at \ - {} bit/sample), aomdec wrote {}", - ours.len(), - decoded - .iter() - .map(|f| f.y.len() + f.u.len() + f.v.len()) - .sum::(), - bit_depth, - ref_raw.len() - ); - assert_eq!(decoded.len(), frames, "{name}: frame count"); - let first = ours - .iter() - .zip(&ref_raw) - .position(|(a, b)| a != b) - .unwrap_or(ours.len()); - assert_eq!( - first, - ours.len(), - "{name}: {} bytes of decoded output differ from aomdec (first at {})", - ours.iter().zip(&ref_raw).filter(|(a, b)| a != b).count(), - first - ); - } - - pub(super) fn fnv1a64(bytes: &[u8]) -> u64 { - let mut hash = 0xcbf29ce484222325u64; - for &b in bytes { - hash ^= b as u64; - hash = hash.wrapping_mul(0x100000001b3); - } - hash - } - - /// Whether ffmpeg is on PATH. Absence normally SKIPs, but - /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every - /// aomenc gate decodes its stream through ffmpeg and is meaningless - /// without it -- turns it into a hard failure. Without this the require - /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first - /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg - /// printed SKIP and reported green (class gate-skips-on-its-own-failure). - pub(super) fn have_ffmpeg() -> bool { - let present = Command::new("ffmpeg") - .arg("-version") - .stdout(Stdio::null()) - .stderr(Stdio::null()) - .status() - .is_ok_and(|s| s.success()); - assert!( - present - || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none() - && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()), - "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH" - ); - present - } - - /// Decodes `frames` concatenated 4:2:0 frames out of one AV1 OBU stream. - /// The frame-count diagnostic shared by the three `ffmpeg_decode_sequence*` - /// helpers (lane-av1pins5 r6). - /// - /// Before this, a caller that passed its OWN decode's length as the expected - /// count got `expected N 4:2:0 frames, ffmpeg said: ` -- with an EMPTY tail, - /// because ffmpeg ran at `-v error` and succeeded. The message named ffmpeg, - /// said nothing about where `N` came from, and sent the next reader hunting - /// ffmpeg for a count ffmpeg never chose. - /// - /// The class is MISATTRIBUTED RED, not silent pass: the helper's - /// `out.stdout.len() == frame_bytes * frames` assert fires unconditionally, so - /// a wrong count cannot pass -- it just fails while blaming the wrong - /// component. (Measured: `ffmpeg_decode_sequence(&s, 192, 128, 0)` panics - /// here, not silently.) Naming the real cause is the whole fix; no caller has - /// to change to benefit. - pub(super) fn frame_count_diagnosis( - format: &str, - frames: usize, - width: usize, - height: usize, - frame_bytes: usize, - got: usize, - stderr: &[u8], - ) -> String { - let actual = got.checked_div(frame_bytes).unwrap_or(0); - let leftover = if frame_bytes == 0 { - got - } else { - got % frame_bytes - }; - format!( - "FRAME COUNT MISMATCH ({format} {width}x{height}): the caller passed \ - `frames={frames}`, ffmpeg produced {actual} frame(s) ({got} bytes, \ - {leftover} byte(s) not a whole frame, at {frame_bytes} B/frame).\n\ - `frames` is the EXPECTED count the CALLER asserted -- it is NOT measured \ - from ffmpeg, so it never had ffmpeg's agreement. If it came from our own \ - decode_stream(), this is OUR decoder disagreeing with ffmpeg about how many \ - frames the stream holds, and the fix is on OUR side, not ffmpeg's. ffmpeg \ - itself exited cleanly{}.", - if stderr.is_empty() { - " with no diagnostics (`-v error`)" - } else { - "" - } - ) - } - - pub(super) fn ffmpeg_decode_sequence( - stream: &[u8], - width: usize, - height: usize, - frames: usize, - ) -> Vec { - // lane-av1oracleguard: this helper's numbers are 4:2:0's. A (1,0) or - // (0,0) stream would be CONVERTED by ffmpeg rather than refused. - assert_420_oracle_stream( - stream, - "ffmpeg_decode_sequence", - "ffmpeg_decode_sequence_422 (4:2:2) or ffmpeg_decode_sequence_444 (4:4:4)", - ); - let out = run_with_stdin( - Command::new(ffmpeg_path()).args([ - "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-", - ]), - stream, - ); - assert!( - out.status.success(), - "ffmpeg refused the stream: {}", - String::from_utf8_lossy(&out.stderr) - ); - let (luma, chroma) = (width * height, width * height / 4); - let frame_bytes = luma + 2 * chroma; - assert_eq!( - out.stdout.len(), - frame_bytes * frames, - "{}", - frame_count_diagnosis( - "4:2:0", - frames, - width, - height, - frame_bytes, - out.stdout.len(), - &out.stderr - ) - ); - (0..frames) - .map(|i| { - let base = i * frame_bytes; - Pic { - width, - height, - y: out.stdout[base..base + luma] - .iter() - .map(|&v| u16::from(v)) - .collect(), - u: out.stdout[base + luma..base + luma + chroma] - .iter() - .map(|&v| u16::from(v)) - .collect(), - v: out.stdout[base + luma + chroma..base + frame_bytes] - .iter() - .map(|&v| u16::from(v)) - .collect(), - } - }) - .collect() - } - - /// As [`ffmpeg_decode_sequence`], for a MONOCHROME stream: one 8-bit luma - /// plane per frame, exactly what `ffmpeg -pix_fmt gray -f rawvideo` writes - /// (lane-av1mono). Fed through [`run_with_stdin`] for the reason its doc - /// records. - pub(super) fn ffmpeg_decode_gray_sequence( - stream: &[u8], - width: usize, - height: usize, - frames: usize, - ) -> Vec { - let out = run_with_stdin( - Command::new(ffmpeg_path()).args([ - "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "gray", "-", - ]), - stream, - ); - assert!( - out.status.success(), - "ffmpeg refused the monochrome stream: {}", - String::from_utf8_lossy(&out.stderr) - ); - assert_eq!( - out.stdout.len(), - width * height * frames, - "expected {frames} monochrome frames, ffmpeg said: {}", - String::from_utf8_lossy(&out.stderr) - ); - out.stdout - } - - /// As [`ffmpeg_decode_sequence`], but for a `yuv420p10le` stream: samples - /// are 2-byte little-endian, one full 16-bit range regardless of the - /// stream's real 10-bit depth (ffmpeg's rawvideo muxer never packs to the - /// bit depth). The 8-bit helper above stays untouched -- every existing - /// gate depends on it. - /// - /// lane-av1oracledepth: the stream's OWN sequence header must parse - /// 10-bit, the same way `assert_12bit_sequence_header` covers the 12-bit - /// gates. A wrong-depth stream handed here would otherwise CONVERT - /// silently -- ffmpeg re-scales 8-bit samples into the 16-bit container - /// and sizes no plane differently -- so a gate could compare ffmpeg's - /// rescaled 8-bit planes against our 10-bit decode and read exact (class - /// `helper-assumes-the-shape-the-gate-name-implies`, the depth axis). - pub(super) fn ffmpeg_decode_sequence_10bit( - stream: &[u8], - width: usize, - height: usize, - frames: usize, - ) -> Vec { - assert_420_oracle_stream( - stream, - "ffmpeg_decode_sequence_10bit", - "ffmpeg_decode_sequence_422_depth(.., 10, \"yuv422p10le\") (4:2:2); \ - ffmpeg_decode_sequence_444_depth(.., 10, \"yuv444p10le\") (4:4:4)", - ); - assert_eq!( - stream_bit_depth(stream, "ffmpeg_decode_sequence_10bit"), - 10, - "ffmpeg_decode_sequence_10bit REFUSED a stream whose own sequence header is not \ - 10-bit -- ffmpeg converts it to yuv420p10le instead of failing, and the comparison \ - would read a converted reference" - ); - let out = run_with_stdin( - Command::new(ffmpeg_path()).args([ - "-v", - "error", - "-f", - "obu", - "-i", - "-", - "-f", - "rawvideo", - "-pix_fmt", - "yuv420p10le", - "-", - ]), - stream, - ); - assert!( - out.status.success(), - "ffmpeg refused the stream: {}", - String::from_utf8_lossy(&out.stderr) - ); - let (luma, chroma) = (width * height, width * height / 4); - let frame_samples = luma + 2 * chroma; - let frame_bytes = frame_samples * 2; - assert_eq!( - out.stdout.len(), - frame_bytes * frames, - "{}", - frame_count_diagnosis( - "4:2:0 10-bit", - frames, - width, - height, - frame_bytes, - out.stdout.len(), - &out.stderr - ) - ); - fn le16(bytes: &[u8]) -> Vec { - bytes - .as_chunks::<2>().0.iter() - .map(|c| u16::from_le_bytes([c[0], c[1]])) - .collect() - } - (0..frames) - .map(|i| { - let base = i * frame_bytes; - Pic { - width, - height, - y: le16(&out.stdout[base..base + luma * 2]), - u: le16(&out.stdout[base + luma * 2..base + luma * 2 + chroma * 2]), - v: le16(&out.stdout[base + luma * 2 + chroma * 2..base + frame_bytes]), - } - }) - .collect() - } - - /// Builds a `gradients` lavfi source string with colours derived from - /// `seed`, not left to the filter's own default. - /// - /// Measured (lane-fixdet r1): ffmpeg's `gradients` source IGNORES its - /// `seed=` parameter for colour selection -- five encodes of an - /// identical command line (same `seed=`, same everything) produced five - /// different fixtures, because the unset `c0..c9` stops are randomized - /// from something other than that seed. Every one of this file's ~20 - /// gate fixtures built a `gradients` source this way, so none of them - /// had a reproducible input: a pin captured from one run could not be - /// regenerated, and "attempt N failed" was as likely to be a different - /// fixture as a different decode outcome. - /// - /// Freezing the colours outright (as the earliest four gates below do, - /// hand-picking `c0=red:c1=blue:c2=green`) fixes reproducibility but - /// throws away the per-attempt content variety the sweep gates need to - /// make features (OBMC, warp, wedge, ...) fire at all -- this repo's own - /// `sampler-decorrelated-gate` class. So: derive `c0..c3` deterministically - /// FROM the seed with a plain integer hash, and keep passing `seed=` - /// itself too, so a future ffmpeg that actually honours it only adds - /// more variety, never removes the determinism this buys. - pub(super) fn gradients_source(seed: u32, width: usize, height: usize, tail: &str) -> String { - fn hash_color(seed: u32, salt: u32) -> String { - let h = seed - .wrapping_mul(2_654_435_761) - .wrapping_add(salt.wrapping_mul(0x9E37_79B9)) - ^ (seed.rotate_left(13)); - format!("0x{:06x}", h & 0x00ff_ffff) - } - let (c0, c1, c2, c3) = ( - hash_color(seed, 0), - hash_color(seed, 1), - hash_color(seed, 2), - hash_color(seed, 3), - ); - format!( - "gradients=size={width}x{height}:c0={c0}:c1={c1}:c2={c2}:c3={c3}:seed={seed}:{tail}" - ) - } - - /// Encodes a real libaom-av1 stream (via ffmpeg's own encoder, not this - /// crate's) with the same reduced-partition flags lane-av1adst's r6 - /// probe found still select `ADST_ADST`/`ADST_DCT`/`DCT_ADST` on - /// gradient content (TX_SET_INTRA_2), and decodes it with - /// [`decode_stream`] -- lifting the round-2 refusal is only real if it - /// gets past an encoder this crate never wrote a byte of. - pub(super) fn libaom_encode(lavfi: &str, width: usize, height: usize, crf: u32) -> Option> { - libaom_encode_with(lavfi, width, height, crf, &[]) - } - - /// As [`libaom_encode`], with extra encoder args appended -- used to pin - /// a deterministic stream (`-threads 1` etc., since libaom's `cpu-used 8` - /// RD search is not otherwise stable run-to-run on this box, and lavfi - /// `gradients` needs its own `seed=` for the same reason) and to gate - /// individual feature flags (`-enable-cdef 0`) a given fixture needs off. - pub(super) fn libaom_encode_with( - lavfi: &str, - width: usize, - height: usize, - crf: u32, - extra: &[&str], - ) -> Option> { - let mut args = vec![ - "-v", - "error", - "-f", - "lavfi", - "-i", - lavfi, - "-frames:v", - "1", - "-pix_fmt", - "yuv420p", - "-c:v", - "libaom-av1", - ]; - let crf_str = crf.to_string(); - args.extend(["-crf", &crf_str]); - args.extend([ - "-cpu-used", - "8", - "-enable-rect-partitions", - "0", - "-enable-ab-partitions", - "0", - "-enable-1to4-partitions", - "0", - "-enable-angle-delta", - "0", - "-enable-cfl-intra", - "0", - ]); - args.extend(extra.iter().copied()); - args.extend(["-f", "obu", "-"]); - let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args(&args) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - if !out.status.success() { - eprintln!( - "ffmpeg refused to encode {lavfi} at {width}x{height}: {}", - String::from_utf8_lossy(&out.stderr) - ); - return None; - } - Some(out.stdout) - } - - /// As [`ffmpeg_decode_sequence`], for a 4:4:4 stream: chroma planes are - /// FULL resolution (`yuv444p` rawvideo), the shape lane-av1-llinter's - /// lossless profile-1 fixture codes. - pub(super) fn ffmpeg_decode_sequence_444( - stream: &[u8], - width: usize, - height: usize, - frames: usize, - ) -> Vec { - ffmpeg_decode_sequence_444_depth(stream, width, height, frames, 8, "yuv444p") - } - - /// lane-av1oracledepth: the depth-generic 4:4:4 oracle comparator -- the - /// [`ffmpeg_decode_sequence_422_depth`] twin for full-resolution chroma. - /// `yuv444p`, `yuv444p10le` or `yuv444p12le`, with the container width - /// taken from `depth` itself (8 -> one byte per sample; 10/12 -> a 16-bit - /// LE container on BOTH sides, so ours and ffmpeg's are directly - /// comparable sample for sample and nothing narrows). Until this helper - /// existed a 10/12-bit 4:4:4 gate had to fall back to the 8-bit - /// `ffmpeg_decode_sequence_444`, which ffmpeg converts at `yuv444p` - /// instead of refusing, or to a raw hand-rolled spawn (class - /// `helper-assumes-the-shape-the-gate-name-implies`, the depth axis). - /// - /// Refused by SHAPE read from the stream's own sequence header, like its - /// 4:2:0 siblings: `(0,0)` only, so a 4:2:2 or 4:2:0 stream handed here - /// cannot have ffmpeg silently convert it. - pub(super) fn ffmpeg_decode_sequence_444_depth( - stream: &[u8], - width: usize, - height: usize, - frames: usize, - depth: u8, - pix_fmt: &str, - ) -> Vec { - assert!( - matches!(depth, 8 | 10 | 12), - "lane-av1oracledepth: ffmpeg_decode_sequence_444_depth takes 8, 10 or 12, got {depth}" - ); - let (sx, sy) = stream_subsampling(stream, "ffmpeg_decode_sequence_444_depth"); - assert!( - (sx, sy) == (0, 0), - "ffmpeg_decode_sequence_444_depth REFUSED a ({sx},{sy}) stream: this helper asks \ - ffmpeg for a 4:4:4 pix_fmt, which CONVERTS the stream's real {} chroma instead of \ - failing, then slices full-resolution planes from converted bytes. \ - ffmpeg_decode_sequence_422_depth handles (1,0); ffmpeg_decode_sequence handles \ - (1,1).", - chroma_shape(sx, sy) - ); - assert_eq!( - stream_bit_depth(stream, "ffmpeg_decode_sequence_444_depth"), - depth, - "ffmpeg_decode_sequence_444_depth REFUSED a stream whose own sequence header is \ - not {depth}-bit -- ffmpeg would convert it to {pix_fmt} instead of failing" - ); - let out = run_with_stdin( - Command::new(ffmpeg_path()).args([ - "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", pix_fmt, "-", - ]), - stream, - ); - assert!( - out.status.success(), - "ffmpeg refused the 4:4:4 stream ({pix_fmt}): {}", - String::from_utf8_lossy(&out.stderr) - ); - let plane = width * height; - let bps = if depth == 8 { 1 } else { 2 }; - let frame_bytes = 3 * plane * bps; - assert_eq!( - out.stdout.len(), - frame_bytes * frames, - "{}", - frame_count_diagnosis( - if depth == 8 { - "4:4:4" - } else { - "4:4:4 high depth" - }, - frames, - width, - height, - frame_bytes, - out.stdout.len(), - &out.stderr - ) - ); - (0..frames) - .map(|i| { - let base = i * frame_bytes; - let samples = |off: usize| -> Vec { - let slice = &out.stdout[base + off..base + off + plane * bps]; - if bps == 1 { - slice.iter().map(|&v| u16::from(v)).collect() - } else { - slice - .as_chunks::<2>().0.iter() - .map(|c| u16::from_le_bytes([c[0], c[1]])) - .collect() - } - }; - Pic { - width, - height, - y: samples(0), - u: samples(plane * bps), - v: samples(2 * plane * bps), - } - }) - .collect() - } - - /// lane-av1422lift: as [`ffmpeg_decode_sequence`] (4:2:0 8-bit) and - /// [`ffmpeg_decode_sequence_444`], for a 4:2:2 stream: `yuv422p` - /// rawvideo, whose chroma planes are HALF WIDTH and FULL HEIGHT -- the - /// `w/2 * h` shape the whole per-axis port exists to produce. A helper - /// that computed the chroma span 4:2:0-style would make every 4:2:2 - /// gate compare half the oracle's bytes and pass, so the span is - /// asserted against the byte count below, not assumed. - pub(super) fn ffmpeg_decode_sequence_422( - stream: &[u8], - width: usize, - height: usize, - frames: usize, - ) -> Vec { - ffmpeg_decode_sequence_422_depth(stream, width, height, frames, 8, "yuv422p") - } - - /// lane-av1422lift: the depth-generic 4:2:2 oracle comparator -- - /// `yuv422p`, `yuv422p10le` or `yuv422p12le`, with the container width - /// taken from `depth` itself (8 -> one byte per sample; 10/12 -> a - /// 16-bit LE container on BOTH sides, so ours and ffmpeg's are directly - /// comparable sample for sample and nothing narrows). - pub(super) fn ffmpeg_decode_sequence_422_depth( - stream: &[u8], - width: usize, - height: usize, - frames: usize, - depth: u8, - pix_fmt: &str, - ) -> Vec { - assert!( - matches!(depth, 8 | 10 | 12), - "lane-av1422lift: ffmpeg_decode_sequence_422_depth takes 8, 10 or 12, got {depth}" - ); - let out = run_with_stdin( - Command::new("ffmpeg").args([ - "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", pix_fmt, "-", - ]), - stream, - ); - assert!( - out.status.success(), - "ffmpeg refused the 4:2:2 stream ({pix_fmt}): {}", - String::from_utf8_lossy(&out.stderr) - ); - let (luma, chroma) = (width * height, width.div_ceil(2) * height); - let bps = if depth == 8 { 1 } else { 2 }; - let frame_bytes = (luma + 2 * chroma) * bps; - assert_eq!( - out.stdout.len(), - frame_bytes * frames, - "{}", - frame_count_diagnosis( - "4:2:2", - frames, - width, - height, - frame_bytes, - out.stdout.len(), - &out.stderr - ) - ); - (0..frames) - .map(|i| { - let base = i * frame_bytes; - let samples = |off: usize, n: usize| -> Vec { - let slice = &out.stdout[base + off..base + off + n * bps]; - if bps == 1 { - slice.iter().map(|&v| u16::from(v)).collect() - } else { - slice - .as_chunks::<2>().0.iter() - .map(|c| u16::from_le_bytes([c[0], c[1]])) - .collect() - } - }; - Pic { - width, - height, - y: samples(0, luma), - u: samples(luma * bps, chroma), - v: samples((luma + chroma) * bps, chroma), - } - }) - .collect() - } - - /// lane-av1422lift: the shared body of every 4:2:2 exactness gate this - /// lane adds, and the answer to "a byte-exact 4:2:2 gate can still be - /// vacuous". - /// - /// Before lane-av1422census422 the per-plane coefficient-unit census was - /// armed at `ss_x == 0 && ss_y == 0` only, so on a 4:2:2 stream - /// `census_nonsub_units()` read `[0, 0, 0]` BY CONSTRUCTION -- a gate - /// could have been green while the decode walked nothing at all. The - /// census is now armed for `(ss_x == 0 || ss_y == 0)`, so the delta - /// asserted here is a real measurement of the walk this stream caused: - /// every plane must show a non-zero number of transform units AND of - /// units that coded at least one coefficient. - /// - /// Four things are asserted per frame, in this order: - /// - /// 1. the decoded frame's dimensions, and that its chroma planes are - /// `round_ss(w, 1) * round_ss(h, 0)` -- half width, FULL height. A - /// decoder that kept 4:2:0 plane allocation while walking 4:2:2 - /// entropy would pass a per-sample compare against a 4:2:0-sized - /// oracle; this is the shape assertion that closes that hole, and it - /// is asserted against the DECODED frame, never against the gate's - /// own name. - /// 2. the depth, read out of the stream's own sequence header. - /// 3. per-plane, per-frame byte-exactness against ffmpeg's rawvideo of - /// the same bytes at the depth-correct pixel format. Frame N of ours - /// against frame N of ffmpeg's: `decode_stream` returns DISPLAY order - /// and so does ffmpeg's rawvideo muxer, so a hidden alt-ref does not - /// shift the pairing (the decode-order-vs-display-order trap the - /// out-of-process corpus comparator has to solve separately). - /// 4. the census delta, asserted once for the whole stream rather than - /// per frame, because the counters are cumulative per thread. - /// - /// `require_coded` is false ONLY for a cell whose identity IS that it - /// codes nothing -- `422_allskip_2f.obu`, whose whole point is that - /// the inter frame reads no residual and the pre-port decoder read - /// PHANTOM units there. Demanding coded units on it would be - /// demanding the defect; its caller asserts the all-skip property - /// directly instead. - pub(super) fn assert_422_stream_pixel_exact( - name: &str, - stream: &[u8], - width: usize, - height: usize, - frames: usize, - depth: u8, - require_coded: bool, - ) -> ([usize; 3], [usize; 3]) { - let _gate_lock = lock_gate_counters(); - assert_eq!( - stream_bit_depth(stream, name), - depth, - "{name}: the stream's OWN sequence header does not say {depth} bit" - ); - let before = crate::decode::census_nonsub_units(); - let before_coded = crate::decode::census_nonsub_coded(); - let ours = decode_stream(stream) - .unwrap_or_else(|e| panic!("{name}: decode_stream refused a real 4:2:2 stream: {e}")); - assert_eq!(ours.len(), frames, "{name}: decoded frame count"); - for (i, f) in ours.iter().enumerate() { - assert_eq!( - (f.width, f.height), - (width, height), - "{name}: frame {i} dimensions" - ); - assert_eq!( - (f.u.len(), f.v.len()), - (width.div_ceil(2) * height, width.div_ceil(2) * height), - "{name}: frame {i} chroma planes are {}/{} samples -- 4:2:2 is HALF WIDTH and \ - FULL HEIGHT ({width}/2 x {height}); a quarter-height plane means the decode kept \ - a 4:2:0 allocation", - f.u.len(), - f.v.len() - ); - } - let pix_fmt = match depth { - 8 => "yuv422p", - 10 => "yuv422p10le", - 12 => "yuv422p12le", - other => panic!("{name}: no ffmpeg pixel format mapped for depth {other}"), - }; - let theirs = - ffmpeg_decode_sequence_422_depth(stream, width, height, frames, depth, pix_fmt); - for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { - for (plane, ours_plane, theirs_plane) in - [("Y", &a.y, &b.y), ("U", &a.u, &b.u), ("V", &a.v, &b.v)] - { - assert_eq!( - ours_plane.len(), - theirs_plane.len(), - "{name}: {plane} plane {i} is {} samples against ffmpeg's {} -- the 4:2:2 chroma \ - span is wrong on one of the two sides", - ours_plane.len(), - theirs_plane.len() - ); - if let Some(bad) = ours_plane - .iter() - .zip(theirs_plane) - .position(|(x, y)| x != y) - { - panic!( - "{name}: {plane} differs from ffmpeg at frame {i} sample {bad} ({} vs {}; \ - {} of {} samples differ)", - ours_plane[bad], - theirs_plane[bad], - ours_plane - .iter() - .zip(theirs_plane) - .filter(|(x, y)| x != y) - .count(), - ours_plane.len() - ); - } - } - } - let units = crate::decode::census_nonsub_units(); - let coded = crate::decode::census_nonsub_coded(); - let delta: [usize; 3] = std::array::from_fn(|p| units[p] - before[p]); - let coded_delta: [usize; 3] = std::array::from_fn(|p| coded[p] - before_coded[p]); - for (p, plane) in ["luma", "U", "V"].into_iter().enumerate() { - assert!( - delta[p] > 0, - "{name}: the {plane} plane read ZERO coefficient units across the whole stream -- \ - this byte-exact compare is vacuous with respect to 4:2:2 (class \ - gate-blind-to-feature)" - ); - if require_coded { - assert!( - coded_delta[p] > 0, - "{name}: the {plane} plane coded ZERO coefficient units across the whole \ - stream -- every unit took the all-zero early return, so no coefficient path \ - was exercised" - ); - } - } - eprintln!( - "{name}: byte-exact vs ffmpeg ({pix_fmt}, {frames} frames); census delta \ - units=[{}, {}, {}] coded=[{}, {}, {}]", - delta[0], delta[1], delta[2], coded_delta[0], coded_delta[1], coded_delta[2] - ); - (delta, coded_delta) - } - - /// `(subsampling_x, subsampling_y, bit_depth)` out of the stream's OWN - /// sequence header. A gate that claims to exercise a subsampling-specific - /// path must assert this from the parsed header, not from the recipe that - /// produced the fixture: the recipe can drift (or a wrong `--pix_fmt` - /// argument can silently produce a different subsampling) and every other - /// assertion would then pass vacuously. - pub(super) fn subsampled_header_shape(stream: &[u8], name: &str) -> (u8, u8, usize) { - let mut parser = Av1Parser::new(); - let mut pos = 0usize; - let mut shape = None; - while pos < stream.len() { - let obu = parser - .parse_obu(&stream[pos..]) - .unwrap_or_else(|e| panic!("{name}: OBU does not parse: {e:?}")); - if obu.total_size == 0 { - break; - } - pos += obu.total_size; - if let ObuKind::SequenceHeader(seq) = obu.kind { - shape = Some(( - seq.color_config.subsampling_x, - seq.color_config.subsampling_y, - seq.color_config.bit_depth as usize, - )); - } - } - shape.unwrap_or_else(|| panic!("{name}: no sequence header parsed")) - } - - /// lane-av1gates444: the live 4:4:4 LOSSY cell the chroma-format sweep - /// measured EXACT 4/4 and left unpinned. The recipe is the sweep's own - /// §6.2 encode, reproduced LIVE against the oracle `aomenc` rather than - /// from a pin, because the claim these three gates carry is a property - /// of the *decoder* at a geometry, not of a blob: - /// ```text - /// ffmpeg -f lavfi -i "testsrc2=size=x:rate=25" -frames:v 4 \ - /// -pix_fmt yuv444p -f yuv4mpegpipe - | \ - /// aomenc --codec=av1 --profile=1 --passes=1 --end-usage=q --cq-level=20 \ - /// --cpu-used=2 --threads=1 --row-mt=0 --lag-in-frames=0 \ - /// --kf-max-dist=100 --limit=4 --obu -o - - - /// ``` - /// `rate=25` is load-bearing (testsrc2's pattern is time-parameterised) - /// and `--limit=4` is the sweep's frame count: at `--limit=6` the same - /// recipe emits 7674 / 11465 / 19121 bytes instead of the sweep's - /// 5938 / 8945 / 15239, i.e. a different stream than the one measured. - /// `--profile=1` is what makes the source 4:4:4 at all. - /// - /// Every assertion here is a non-vacuity assertion first and a pixel - /// compare second. The frame count, the per-frame geometry and the - /// FULL-RESOLUTION chroma plane length are asserted because a truncated - /// or 4:2:0-shaped decode can pass a lenient compare; the - /// `rect4_inter_own_chroma444_hits()` reach assert is there because the - /// class these cells belong to is the 4:4:4-only own-chroma-extent route - /// in [`decode_inter_block`]'s `around_c` (a 4:2:0 stream of the same - /// content leaves it at 0), and a counter at 0 would mean the gate - /// measured a different route than it names. - /// The guard is [`have_aomenc`], which probes first and asserts LAST with - /// the env escape: with `EC_AV1_REQUIRE_AOMENC` set, a missing oracle is - /// a hard failure naming the path it looked for, and a batch run cannot - /// report green off three skipped gates. With it unset the `None` below is - /// a developer-only convenience for a checkout without an oracle -- it is - /// the ONLY way this gate can return without measuring, and it announces - /// itself on stderr naming the env var that would make it a failure. - /// (It used to return an empty `Vec` that the caller turned into a silent - /// early `return`: the same green, reached through a second exit nobody - /// was reading.) - pub(super) fn encode_444_lossy_live(name: &str, w: usize, h: usize) -> Option> { - if !have_aomenc() { - eprintln!( - "SKIP {name}: no aomenc oracle at {} -- set EC_AV1_REQUIRE_AOMENC=1 to make this \ - a failure, or run scripts/build-aom-oracle.sh", - aomenc_path().display() - ); - return None; - } - let source = format!("testsrc2=size={w}x{h}:rate=25"); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-frames:v", - "4", - "-pix_fmt", - "yuv444p", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "{name}: ffmpeg refused the {w}x{h} 4:4:4 source: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let out = run_with_stdin( - Command::new(aomenc_path()).args([ - "--codec=av1", - "--profile=1", - "--passes=1", - "--end-usage=q", - "--cq-level=20", - "--cpu-used=2", - "--threads=1", - "--row-mt=0", - "--lag-in-frames=0", - "--kf-max-dist=100", - "--limit=4", - "--obu", - "-o", - "-", - "-", - ]), - &y4m.stdout, - ); - assert!( - out.status.success(), - "{name}: aomenc refused the {w}x{h} 4:4:4 lossy recipe: {}", - String::from_utf8_lossy(&out.stderr) - ); - assert!( - !out.stdout.is_empty(), - "{name}: aomenc produced no OBU for {w}x{h} -- a zero-length stream would \ - decode to nothing and the compare below would compare nothing" - ); - Some(out.stdout) - } - - /// lane-av1-loss64: the generator for the two gates below -- a deterministic - /// 1-frame lossless superblock-128 aomenc stream of `testsrc2`. `extra` - /// flags land last (aomenc keeps the LAST occurrence of a repeated flag). - /// The recipe is the one lanes/av1rect14.report.md section 2 measured - /// (`--lossless=1 --sb-size=128 --enable-1to4-partitions=1`); the - /// `--min-partition-size` override is what steers the bottom superblock - /// row's RD into overhanging 64x64 `NONE` blocks (the shape the first fix - /// clips) or, at 8, keeps sub-8x8 partitions out of the second gate's - /// stream so the whole frame is decodable. - pub(super) fn lossless_sb128_testsrc2(width: usize, height: usize, extra: &[&str]) -> Vec { - let mut ff = Command::new("ffmpeg"); - let out = crate::tool_cache::cached_output_io(ff - .args(["-v", "error", "-f", "lavfi", "-i"]) - .arg(format!("testsrc2=s={width}x{height}:r=25")) - .args([ - "-frames:v", - "1", - "-pix_fmt", - "yuv420p", - "-strict", - "-1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - out.status.success(), - "ffmpeg failed for testsrc2 {width}x{height}" - ); - let y4m = out.stdout; - let out = run_with_stdin( - Command::new(aomenc_path()) - .args(["--codec=av1", "--bit-depth=8", "--input-bit-depth=8"]) - .args([ - "--passes=1", - "--cpu-used=0", - "--lag-in-frames=0", - "--kf-max-dist=1", - "--limit=1", - "--threads=1", - "--tile-columns=0", - "--lossless=1", - "--sb-size=128", - "--enable-1to4-partitions=1", - ]) - .args(extra) - .args(["--obu", "-o", "-", "-"]), - &y4m, - ); - assert!( - out.status.success(), - "aomenc failed: {}", - String::from_utf8_lossy(&out.stderr) - ); - out.stdout - } - - /// Path to a real `aomenc` build carrying the reference options this - /// fixture needs (`--max-partition-size`, `--enable-tx-size-search`, - /// `--loopfilter-control`) -- this box's `ffmpeg` links a libaom too old - /// to expose `enable-tx-size-search`/`loopfilter-control` through its - /// own `-aom-params` passthrough (probed live: "Cannot find aom - /// option"), so [`a_real_aomenc_filter_intra_stream_decodes_pixel_exact`] - /// shells out to the standalone binary instead of ffmpeg's libaom-av1 - /// wrapper every other test here uses. `EC_AV1_AOMENC` overrides the - /// default dev-build path; the test skips (not fails) when neither this - /// nor `ffmpeg` is present. - pub(super) fn aomenc_path() -> std::path::PathBuf { - if let Some(p) = std::env::var_os("EC_AV1_AOMENC") { - return std::path::PathBuf::from(p); - } - // The oracle used to live only under `/tmp`, which this box's tmpfs - // guard reclaims -- when it did, all 20 aomenc gates below went - // silently vacuous (SKIP, suite still green). The durable location - // is provisioned by `scripts/build-aom-oracle.sh`; the `/tmp` path - // stays last as a legacy fallback. - let mut candidates = Vec::new(); - if let Some(home) = std::env::var_os("HOME") { - candidates.push(std::path::PathBuf::from(&home).join(".cache/aom-oracle/build/aomenc")); - } - candidates.push("/tmp/libaom-src/build/encoder/aomenc".into()); - candidates - .iter() - .find(|p| p.is_file()) - .cloned() - .unwrap_or_else(|| candidates.remove(0)) - } - - /// Whether the aomenc oracle is present. Absence normally SKIPs (a - /// checkout without the oracle should still run the rest of the suite), - /// but `EC_AV1_REQUIRE_AOMENC=1` turns it into a hard failure so a batch - /// run cannot report green off 20 skipped gates. - /// Where a pinned stream lives. `fixtures/` is a symlink to a durable - /// directory outside the repo, so a pin captured in one session is still - /// there in the next; a session scratchpad is not (tmpfs reaps it, and - /// four pins were silently dead because of that). - pub(super) fn pin_dir() -> std::path::PathBuf { - if let Some(p) = std::env::var_os("EC_AV1_PIN_DIR") { - return std::path::PathBuf::from(p); - } - std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("../../fixtures") - .canonicalize() - .unwrap_or_else(|_| std::path::PathBuf::from("fixtures")) - } - - /// A COMMITTED pin: `crates/ec-av1/fixtures/`, which travels in the - /// tarball and is therefore present on every runner. `pin_dir()` resolves - /// to the gitignored root `fixtures/`, so a pin written there is lost when - /// the machine's scratchpad is reaped -- three gates sat at `rc=0` having - /// tested nothing for exactly that reason (lane-av1pins). Falls back to - /// `pin_dir()` so a locally re-captured stream still overrides. - /// Read a pin that a gate cannot proceed without. A missing pin is a - /// HARD failure naming the path and the generator, never a raw io panic - /// and never a silent skip: `EC_AV1_GATE_DUMP_PIN` points the gate at a - /// freshly captured stream, and a runner without the committed copy must - /// say so instead of reporting green having tested nothing. - pub(super) fn require_pin(path: &std::path::Path, name: &str) -> Vec { - std::fs::read(path).unwrap_or_else(|e| { - panic!( - "no pinned bytes at {} ({e}) -- set EC_AV1_GATE_DUMP_PIN to a freshly \ - captured stream, or restore the committed copy at \ - crates/ec-av1/fixtures/{name}", - path.display() - ) - }) - } - - pub(super) fn crate_pin(name: &str) -> std::path::PathBuf { - let in_crate = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("fixtures") - .join(name); - if in_crate.is_file() { - in_crate - } else { - pin_dir().join(name) - } - } - - pub(super) fn have_aomenc() -> bool { - let present = aomenc_path().is_file(); - assert!( - present || std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none(), - "EC_AV1_REQUIRE_AOMENC is set but no aomenc at {} -- run scripts/build-aom-oracle.sh", - aomenc_path().display() - ); - present - } - - /// lane-av1oracleskip: the probe for the ORACLE COMPARER, in the same - /// shape as [`have_ffmpeg`] -- probe first, then `assert!` LAST, with the - /// env escape -- and it prints its own SKIP so a caller cannot skip the - /// compare silently. - /// - /// Why this exists: thirteen gates wrapped their oracle arm in a bare - /// `if aomdec_path().is_file()`, and that shape had NO env escape at all. - /// An oracle build with `aomenc` but no `aomdec` beside it (or an - /// `EC_AV1_AOMDEC` override pointing at a moved path) made the gate - /// encode, decode, assert its geometry and its counters, and then quietly - /// never compare -- green having measured nothing, with no line in the - /// output to notice. Nine of the thirteen printed a SKIP in an `else` and - /// four printed nothing at all; both are the same defect, and both are - /// closed by one probe. - /// - /// With `EC_AV1_REQUIRE_AOMENC` (or the aomdec-specific - /// `EC_AV1_REQUIRE_AOMDEC`) set, the absence is a HARD failure naming the - /// path that was looked for -- that is the batch-run guarantee, and it is - /// what the bare `is_file()` could not give. With it unset the SKIP below - /// is printed and the gate still passes: that remains a developer-only - /// convenience for a checkout without an oracle, never evidence. - pub(super) fn aomdec_available(name: &str) -> bool { - let present = aomdec_path().is_file(); - let require = std::env::var_os("EC_AV1_REQUIRE_AOMDEC").is_some() - || std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_some(); - assert!( - present || !require, - "{name}: no oracle aomdec at {} -- the pixel compare this gate exists for would be \ - skipped, and EC_AV1_REQUIRE_AOMDEC/EC_AV1_REQUIRE_AOMENC is set. Build the oracle \ - with scripts/build-aom-oracle.sh, or point EC_AV1_AOMDEC at a real aomdec.", - aomdec_path().display() - ); - if !present { - eprintln!( - "SKIP {name}: no oracle aomdec at {} -- the pixel compare is NOT running (set \ - EC_AV1_REQUIRE_AOMDEC=1 to make this a failure)", - aomdec_path().display() - ); - } - present - } - - // lane-av1cmpaudit2: this thread's oracle override, set by - // `set_oracle_path` and consulted by `aomdec_path` ahead of the env var. - // - // It is thread-local for the same reason `FINAL_DUMP_PREFIX` is: the - // control test `every_oracle_comparator_reds_on_a_one_byte_wrong_oracle` - // has to hand the helpers a DELIBERATELY WRONG oracle, and a - // process-global `std::env::set_var` could not do that safely -- the - // crate forbids `unsafe_code`, and even where it did not, one test's - // tampered oracle would leak into every sibling test's comparison - // running on another thread. A thread-local override confines the wrong - // oracle to the one thread that asked for it. - thread_local! { - static ORACLE_PATH: std::cell::RefCell> = - const { std::cell::RefCell::new(None) }; - } - - /// Points this thread's oracle helpers at `path`. `None` restores the - /// real `aomdec`. - pub(super) fn set_oracle_path(path: Option) { - ORACLE_PATH.with(|c| *c.borrow_mut() = path); - } - - // lane-film10fix: this thread's ffmpeg override, set by - // `set_ffmpeg_path` and consulted by `ffmpeg_path` ahead of the bare - // name. Same shape and same reason as `ORACLE_PATH` above: the control - // test `every_ffmpeg_comparator_reds_on_a_one_sample_wrong_ffmpeg` has - // to hand the `ffmpeg_decode_sequence*` helpers a DELIBERATELY WRONG - // reference, and a process-global PATH edit would leak that wrong - // reference into every sibling test decoding on another thread. The - // crate forbids `unsafe_code`, so `std::env::set_var` is not available - // either; a thread-local confines the tamper to the one thread. - thread_local! { - static FFMPEG_PATH: std::cell::RefCell> = - const { std::cell::RefCell::new(None) }; - } - - /// Points this thread's `ffmpeg_decode_sequence*` helpers at `path`. - /// `None` restores the real `ffmpeg` on PATH. - pub(super) fn set_ffmpeg_path(path: Option) { - FFMPEG_PATH.with(|c| *c.borrow_mut() = path); - } - - /// The `ffmpeg` every reference helper in this module spawns. - pub(super) fn ffmpeg_path() -> std::path::PathBuf { - if let Some(p) = FFMPEG_PATH.with(|c| c.borrow().clone()) { - return p; - } - std::path::PathBuf::from("ffmpeg") - } - - /// The instrumented `aomdec` beside the `aomenc` oracle - /// (`scripts/build-aom-oracle.sh` + `scripts/instrument-aom-oracle.sh`). - pub(super) fn aomdec_path() -> std::path::PathBuf { - if let Some(p) = ORACLE_PATH.with(|c| c.borrow().clone()) { - return p; - } - if let Some(p) = std::env::var_os("EC_AV1_AOMDEC") { - return std::path::PathBuf::from(p); - } - aomenc_path().with_file_name("aomdec") - } - - /// Decodes `stream` with both this decoder and the instrumented oracle - /// `aomdec`, and compares EVERY decoded frame in DECODE order -- - /// including the hidden (`show_frame == 0`) alt-ref frames no other gate - /// in this repo can see, because `decode_stream` only pushes shown - /// frames and `ffmpeg -f obu ... rawvideo` only emits shown frames - /// (class gate-blind-to-hidden-frames: a hidden frame's defect surfaces - /// only as drift on some later shown frame, if at all). - /// - /// Both sides write the final, post-deblock/CDEF/LR/superres frame as it - /// is stored into the reference buffer (`EC_AV1_FINAL_DUMP`, ours in - /// `decode_stream`, the oracle's in rung 12 of - /// `scripts/instrument-aom-oracle.sh`), 8-bit as u8 / high bitdepth as - /// u16 LE. Returns `(frames_decoded, hidden_frames)`. - pub(super) fn decode_all_frames_vs_oracle(stream: &[u8], name: &str) -> (usize, usize) { - let dir = std::env::temp_dir().join(format!("ec-av1-{name}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).expect("scratch dir"); - let obu = dir.join("in.obu"); - std::fs::write(&obu, stream).expect("writing the stream"); - let aom_prefix = dir.join("aom"); - let out = crate::tool_cache::cached_output_io(Command::new(aomdec_path()) - .args(["--codec=av1", "-o"]) - .arg(dir.join("out.y4m")) - .arg(&obu) - .env("EC_AV1_FINAL_DUMP", &aom_prefix) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("aomdec failed to run"); - assert!( - out.status.success(), - "{name}: the oracle aomdec refused the stream: {}", - String::from_utf8_lossy(&out.stderr) - ); - let count_dumps = |prefix: &std::path::Path| -> usize { - let mut n = 0usize; - while std::path::PathBuf::from(format!("{}.f{n}", prefix.display())).is_file() { - n += 1; - } - n - }; - let oracle_frames = count_dumps(&aom_prefix); - assert!( - oracle_frames > 0, - "{name}: the oracle wrote no EC_AV1_FINAL_DUMP frames -- rung 12 of \ - scripts/instrument-aom-oracle.sh is missing from {}", - aomdec_path().display() - ); - let ours_prefix = dir.join("ours"); - set_final_dump_prefix(Some(ours_prefix.display().to_string())); - let decoded = decode_stream(stream); - set_final_dump_prefix(None); - let shown = decoded - .unwrap_or_else(|e| panic!("{name}: this decoder refused the stream: {e}")) - .len(); - let our_frames = count_dumps(&ours_prefix); - assert_eq!( - our_frames, oracle_frames, - "{name}: decoded {our_frames} frames in decode order, the oracle decoded \ - {oracle_frames}" - ); - for i in 0..oracle_frames { - let want = - std::fs::read(format!("{}.f{i}", aom_prefix.display())).expect("oracle dump"); - let got = std::fs::read(format!("{}.f{i}", ours_prefix.display())).expect("our dump"); - assert_eq!( - got.len(), - want.len(), - "{name}: decode-order frame {i} is {} bytes, the oracle's is {}", - got.len(), - want.len() - ); - if let Some(at) = got.iter().zip(&want).position(|(a, b)| a != b) { - let differing = got.iter().zip(&want).filter(|(a, b)| a != b).count(); - panic!( - "{name}: decode-order frame {i} of {oracle_frames} ({shown} shown, {} \ - hidden) differs from the oracle at byte {at} (ours {} vs {}), {differing} \ - bytes differ -- stream pinned at {}", - oracle_frames - shown, - got[at], - want[at], - obu.display() - ); - } - } - let hidden = oracle_frames - shown; - let _ = std::fs::remove_dir_all(&dir); - (oracle_frames, hidden) - } - - /// lane-av1422anom: a COUNTING oracle comparison. - /// - /// [`assert_rawvideo_matches`] is the right tool for "these must be equal" - /// and the wrong tool for a lane that has to classify many cells: it - /// panics on the first differing byte, so it answers one cell per process - /// and cannot report a magnitude. This returns the count instead. - /// - /// It exists because the previous lane's per-cell counter was tautological: - /// it packed our own decoded samples into `ours` and then compared `ours` - /// against the same samples, never touching the oracle's bytes, so it - /// reported "0 wrong" on every cell including one that differs from - /// `aomdec` in 1612 samples. [`the_counting_oracle_diff_reports_a_real_difference`] - /// below is the test that keeps that mistake from recurring. - /// - /// Returns `(wrong_y, wrong_u, wrong_v, frames_total, frames_exact)`, or - /// `None` when the two sides are not byte-comparable at all (a size - /// mismatch, which is a different failure and must not read as "exact"). - /// `flip` flips ONE bit of the ORACLE's own bytes before comparing, so - /// [`the_counting_oracle_diff_detects_one_flipped_oracle_byte`] can prove - /// the comparison still reads the oracle on a stream that is now exact. - pub(super) fn count_rawvideo_diffs( - stream: &[u8], - name: &str, - flip: Option, - ) -> Option<(usize, usize, usize, usize, usize)> { - let dir = std::env::temp_dir().join(format!("ec-av1-{name}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).expect("scratch dir"); - let obu = dir.join("in.obu"); - std::fs::write(&obu, stream).expect("writing the stream"); - let raw = dir.join("aomdec.raw"); - let out = crate::tool_cache::cached_output_io(Command::new(aomdec_path()) - .args(["--codec=av1", "--rawvideo", "-o"]) - .arg(&raw) - .arg(&obu) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("aomdec failed to run"); - assert!( - out.status.success(), - "{name}: the oracle aomdec refused the stream: {}", - String::from_utf8_lossy(&out.stderr) - ); - let mut want = std::fs::read(&raw).expect("aomdec rawvideo output"); - if let Some(i) = flip { - assert!( - i < want.len(), - "{name}: flip index {i} is past the oracle's {} bytes", - want.len() - ); - want[i] ^= 0x01; - } - let _ = std::fs::remove_dir_all(&dir); - let bit_depth = stream_bit_depth(stream, name); - let decoded = decode_stream(stream).expect("decode for comparison"); - let ours = pack_rawvideo(&decoded, bit_depth, name); - if ours.len() != want.len() { - return None; - } - let bpp = if bit_depth == 8 { 1 } else { 2 }; - // lane-av1cmpframe: the plane split is PER FRAME and comes from each - // decoded frame's OWN plane lengths -- never from a formula, and - // never from the first picture. - // - // The first-picture form was wrong on every multi-frame stream: it - // compared a byte index against frame 0's thresholds forever, so - // every sample after frame 0's luma was attributed to the LAST - // plane. On `420_oddheight_320x236` (16 frames of 320x236 - // 4:2:0, whose frame is 113 280 bytes and whose V plane therefore - // holds 302 080 bytes in total) it reported `wrong_v = 330 673` -- - // more wrong V bytes than exist. The per-frame byte totals and the - // frame-exact count were sound; only the per-plane attribution was - // not, and a wrong attribution is the one thing a per-plane report - // is read for. - // - // `pack_rawvideo` already lays the bytes out per frame from the same - // plane lengths, so this table is exactly the layout it produced. - let mut spans: Vec<[usize; 4]> = Vec::with_capacity(decoded.len()); - let mut off = 0usize; - for f in &decoded { - let (y, u, v) = (f.y.len() * bpp, f.u.len() * bpp, f.v.len() * bpp); - spans.push([off, off + y, off + y + u, off + y + u + v]); - off += y + u + v; - } - assert_eq!( - off, - ours.len(), - "{name}: the per-frame plane table covers {off} bytes but the packed output is {}", - ours.len() - ); - let mut wrong = [0usize; 3]; - let mut frame = 0usize; - for (i, (&a, &b)) in ours.iter().zip(&want).enumerate() { - while frame + 1 < spans.len() && i >= spans[frame][3] { - frame += 1; - } - if a == b { - continue; - } - let s = spans[frame]; - let pi = if i < s[1] { - 0 - } else if i < s[2] { - 1 - } else { - 2 - }; - wrong[pi] += 1; - } - let frames = decoded.len(); - let exact = spans - .iter() - .filter(|s| ours[s[0]..s[3]] == want[s[0]..s[3]]) - .count(); - Some((wrong[0], wrong[1], wrong[2], frames, exact)) - } - - /// lane-hidden r2: the `--arnr-maxframes=0` SECOND ARM of an existing - /// gate -- the gate's own recipe is never changed, this re-encodes the - /// same fixture with libaom's temporal alt-ref filter switched off and - /// runs [`decode_all_frames_vs_oracle`] on the result. Measured: with - /// the filter at its default EVERY alt-ref recipe in this file emits - /// ZERO hidden frames (the candidates are filtered away), so the - /// hidden-frame compare on the gate's own stream is vacuous; this arm - /// is what actually puts `show_frame == 0` frames on the wire. - /// - /// Runs at most once per gate name per process (the loop gates sweep - /// dozens of attempts and each arm costs a full encode + two decodes). - /// A stream this decoder refuses BY NAME skips the arm -- the arm is - /// about hidden frames, not about that capability gap -- while a pixel - /// mismatch is a hard failure raised inside the compare. - pub(super) fn hidden_arnr_arm(name: &str, y4m: &[u8], args: &[&str]) -> Option<(usize, usize)> { - static ARMED: std::sync::OnceLock>> = - std::sync::OnceLock::new(); - if !ARMED - .get_or_init(Default::default) - .lock() - .unwrap() - .insert(name.to_string()) - { - return None; - } - let mut arm: Vec<&str> = vec!["--arnr-maxframes=0"]; - arm.extend_from_slice(args); - let out = run_with_stdin(Command::new(aomenc_path()).args(&arm), y4m); - assert!( - out.status.success(), - "{name} HIDDEN-ARM: aomenc refused its own recipe plus --arnr-maxframes=0: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{name} HIDDEN-ARM failed outright: {msg}" - ); - eprintln!("{name} HIDDEN-ARM: skipped on a named refusal: {msg}"); - None - } - Ok(_) => Some(decode_all_frames_vs_oracle( - &stream, - &format!("{name}-arnr0"), - )), - } - } - - /// lane-av1toolgates: the gate-level WITNESS, summed over the arms that - /// decoded AND compared. It cannot be asserted per arm: the cq20 / - /// tx-size-search=1 arm reaches a rect transform through the var-tx - /// search on a SQUARE block (a nonzero rect coefficient count with zero - /// rect partitions read -- the purest form of what `--enable-rect-tx` - /// buys), while the rect PARTITION only shows up on the - /// tx-size-search=0 arm. Either fact alone would let a stream through on - /// which the tool was allowed and unused, which is the defect this - /// coverage entry was written for; together they are the parsed-shape - /// evidence the entry asked for. - #[track_caller] - pub(super) fn assert_rect_tx_witness(name: &str, parts: usize, tus: usize) { - assert!( - parts > 0, - "{name}: no PARTITION_HORZ/PARTITION_VERT symbol was read on any pixel-exact decode \ - -- the parsed partition tree never yielded a rect leaf, so `--enable-rect-tx=1` \ - was allowed and unused" - ); - assert!( - tus > 0, - "{name}: no rectangular transform unit coded coefficients through read_coeffs_rect \ - ({parts} rect partitions read) -- the rect coefficient path was never taken" - ); - } - - /// lane-t900 r31: builds one `--tune-content=screen --enable-intrabc=1` - /// key frame, 256x192 8-bit, from a deterministic lavfi source. `tiled` - /// renders a 2x2 tiling of a 128x96 pattern -- exact spatial repetition, - /// the content intra block copy exists for; `square_only` turns the rect - /// and 1:4 partitions off so an intrabc block lands on a SQUARE block - /// instead of stopping on the rect-strip intrabc refusal first. - pub(super) fn screen_intrabc_stream( - src: &str, - cq: &str, - txs: &str, - tiled: bool, - square_only: bool, - ) -> Vec { - screen_intrabc_stream_with(src, cq, txs, tiled, square_only, &[]) - } - - /// [`screen_intrabc_stream`] with per-arm flags appended AFTER the base - /// recipe -- aomenc keeps the LAST occurrence of a repeated flag, so an - /// arm can override `--sb-size` / `--min-partition-size` here. - pub(super) fn screen_intrabc_stream_with( - src: &str, - cq: &str, - txs: &str, - tiled: bool, - square_only: bool, - extra: &[&str], - ) -> Vec { - screen_intrabc_stream_at_depth(src, cq, txs, tiled, square_only, 8, extra) - } - - /// [`screen_intrabc_stream_with`] at an explicit bit depth (8 or 10): the - /// lavfi source is rendered straight to that depth's yuv4mpegpipe pixel - /// format and aomenc is told to encode at the matching - /// `--bit-depth`/`--input-bit-depth`, so a 10-bit arm produces a genuine - /// high-bit-depth stream rather than an 8-bit one in disguise. - pub(super) fn screen_intrabc_stream_at_depth( - src: &str, - cq: &str, - txs: &str, - tiled: bool, - square_only: bool, - depth: usize, - extra: &[&str], - ) -> Vec { - // lane-av1screen12: depth 12 joins 8 and 10. The SAME recipe (`-vf - // tile=2x2` over `smptebars=size=128x96:rate=25`, - // `--tune-content=screen --enable-intrabc=1`, cq30, - // `--enable-tx-size-search=0`) that keeps `allow_intrabc` at 8 and 10 - // bits keeps it at 12 bits too -- measured, and pinned by - // `a_real_aomenc_12bit_intrabc_screen_stream_decodes_pixel_exact`. - // That is why "neither palette nor intrabc has a 12-bit witness" was - // false: the intrabc half WAS producible, `--tune-content=screen` - // alone just is not what decides the frame-header bit (libaom's - // content detector is). - assert!( - depth == 8 || depth == 10 || depth == 12, - "unsupported bit depth {depth}" - ); - // `if depth == 10` is SPELLED, not matched, because - // `gate_coverage::covers_both_depths` recognises this two-depth - // helper by that literal (the lane-defon/reelckf blind spot with - // `depth` spelled instead of `bit_depth`). - let pix_fmt = if depth == 10 { - "yuv420p10le" - } else if depth == 12 { - "yuv420p12le" - } else { - "yuv420p" - }; - let mut ff = Command::new("ffmpeg"); - ff.args(["-v", "error", "-f", "lavfi", "-i", src, "-t", "0.2"]); - if tiled { - ff.args(["-vf", "tile=2x2"]); - } - let out = crate::tool_cache::cached_output_io(ff - .args([ - "-pix_fmt", - pix_fmt, - "-strict", - "-1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!(out.status.success(), "ffmpeg failed for {src}"); - let y4m = out.stdout; - let enc = run_with_stdin( - Command::new(aomenc_path()) - .args(["--codec=av1"]) - .args([ - format!("--bit-depth={depth}"), - format!("--input-bit-depth={depth}"), - ]) - .args([ - "--passes=1", - "--end-usage=q", - "--cpu-used=0", - "--lag-in-frames=0", - "--kf-max-dist=1", - "--limit=1", - "--threads=1", - "--tile-columns=0", - "--min-partition-size=8", - "--max-partition-size=32", - "--sb-size=64", - "--tune-content=screen", - "--enable-intrabc=1", - "--enable-palette=0", - ]) - .args([ - format!("--cq-level={cq}"), - format!("--enable-tx-size-search={txs}"), - ]) - // aomenc keeps the LAST occurrence of a repeated flag. - .args(if square_only { - &["--enable-rect-partitions=0", "--enable-1to4-partitions=0"][..] - } else { - &[][..] - }) - .args(extra) - .args(["--obu", "-o", "-", "-"]), - &y4m, - ); - assert!( - enc.status.success(), - "aomenc refused {src} cq={cq}: {}", - String::from_utf8_lossy(&enc.stderr) - ); - enc.stdout - } - - /// The sequence header's `use_128x128_superblock`, and how many frames of - /// `stream` keep `allow_intrabc` -- the two bits the refusal "intrabc - /// under a 128x128 superblock" is the conjunction of, read out of the - /// headers rather than assumed from the flags handed to the encoder. - pub(super) fn sb128_and_intrabc_frames(stream: &[u8]) -> (bool, u32) { - let mut parser = Av1Parser::new(); - let mut pos = 0usize; - let (mut sb128, mut intrabc) = (false, 0u32); - while pos < stream.len() { - let Ok(obu) = parser.parse_obu(&stream[pos..]) else { - break; - }; - pos += obu.total_size.max(1); - if let Some(seq) = parser.sequence_header() { - sb128 = seq.use_128x128_superblock; - } - let header = match &obu.kind { - ObuKind::Frame(h, _) => Some(&**h), - ObuKind::FrameHeader(h) => Some(&**h), - _ => None, - }; - if header.is_some_and(|h| h.allow_intrabc) { - intrabc += 1; - } - } - (sb128, intrabc) - } - - /// How many frames of `stream` carry `tx_mode == Select`, and how many of - /// those also keep `allow_intrabc` -- the frame-level premise of the - /// refusal "an intrabc block under TxMode::Select", read out of the - /// headers rather than assumed from the flags handed to the encoder - /// (libaom clears `allow_intrabc` again when no block picked it, - /// encodeframe.c:2336). - pub(super) fn tx_select_and_intrabc_frames(stream: &[u8]) -> (u32, u32) { - let (mut select, mut premise) = (0u32, 0u32); - let mut p = Av1Parser::new(); - let mut pos = 0usize; - while pos < stream.len() { - let obu = p.parse_obu(&stream[pos..]).expect("parse"); - pos += obu.total_size; - let header = match &obu.kind { - ObuKind::Frame(h, _) => Some(&**h), - ObuKind::FrameHeader(h) => Some(&**h), - _ => None, - }; - if let Some(h) = header - && h.tx_mode == TxMode::Select { - select += 1; - if h.allow_intrabc { - premise += 1; - } - } - } - (select, premise) - } - - // /// lane-hbd r5: a real `aomenc --bit-depth=10` stream, decoded through - // /// this crate's own 10-bit planes (`Picture` widened to `u16` in an - // /// earlier round) and checked pixel-exact against ffmpeg's own decode of - // /// the identical bytes via [`ffmpeg_decode_sequence_10bit`]. Confirms - // /// (hard-asserts, not just trusts) the sequence header this stream - // /// actually parses to says `bit_depth == 10` before trusting any pixel - // /// match -- a stream that silently fell back to 8-bit would still - // /// "match" trivially. - // ------------------------------------------------------------------- - // lane-av112bit: the 12-bit gate battery. The blanket refusal is lifted - // for what these gates witness byte-exact against ffmpeg on real - // `aomenc --bit-depth=12 --profile=2` streams: the full intra stack, - // dequant/transforms at the 12-bit dequant tables, deblock, CDEF, loop - // restoration (Wiener AND SGR), and translational subpel motion - // compensation through the bit-depth-parameterised `round_0`/`round_1` - // (libaom `convolve.h:81..86`). Everything else stays refused by name: - // warp and screen content tools (palette/intrabc) at the frame level, - // each with its own real-stream refusal gate below. - // lane-av112bitc: compound joined the witnessed set (refusal gate became - // the six-frame compound witness). - // lane-av112bitg: film grain joined the witnessed set (refusal gate became - // `a_real_aomenc_12bit_film_grain_stream_decodes_pixel_exact`). - // ------------------------------------------------------------------- - /// The 12-bit witness source, byte-identical to the lane's committed - /// fixture recipe: 160x128 C420p12, a gradient + fine-texture base with a - /// 24x20 box that travels 1.25 px/frame horizontally and 0.75 px/frame - /// vertically with linear edge coverage -- sub-pixel true motion, so an - /// inter frame over it cannot be coded whole-pel-only. - pub(super) fn y4m_12bit_subpel_source(frames: usize) -> Vec { - const W: usize = 160; - const H: usize = 128; - let cov = |a: f64, b: f64, i: i64| (b.min(i as f64 + 1.0) - a.max(i as f64)).max(0.0); - let mut y4m = format!("YUV4MPEG2 W{W} H{H} F30:1 Ip A1:1 C420p12\n").into_bytes(); - for t in 0..frames { - let (ax, ay) = (12.0 + 1.25 * t as f64, 10.0 + 0.75 * t as f64); - let (bx, by) = (ax + 24.0, ay + 20.0); - y4m.extend_from_slice(b"FRAME\n"); - for j in 0..H as i64 { - for i in 0..W as i64 { - let g = (i * 190) / W as i64 + (j * 150) / H as i64; - let mut v = (g * 12 - + if (i * 5 + j * 3 + t as i64) % 7 < 3 { - 90 - } else { - 220 - } - + if (60..110).contains(&i) && (70..110).contains(&j) { - 640 - } else { - 0 - }) as f64; - let c = cov(ax, bx, i) * cov(ay, by, j); - if c > 0.0 { - v = v * (1.0 - c) + 3500.0 * c; - } - y4m.extend_from_slice(&(v.min(4095.0) as u16).to_le_bytes()); - } - } - for (base, fx) in [(1900usize, 0usize), (2100, 1)] { - for j in 0..H / 2 { - for i in 0..W / 2 { - let v = if fx == 0 { - base + (((i / 5 + t * 2) % 7) * 120 + (j * 60) / H) - } else { - base + (((j / 4 + t) % 5) * 140 + (i * 40) / W) - }; - y4m.extend_from_slice(&(v.min(4095) as u16).to_le_bytes()); - } - } - } - } - y4m - } - - /// lane-av1gwarp12 fixture: rotating + uniformly zooming mandelbrot as a - /// C420p12 y4m. Rotation composed with a UNIFORM scale is a similarity - /// transform -- exactly the family a 4-parameter ROTZOOM global model - /// expresses (the affine gate needs the anisotropic stretch to force - /// 6 parameters; this lane needs the model vanilla aomenc actually - /// searches, ROTZOOM). - pub(super) fn y4m_12bit_rotzoom_gm_source(frames: usize) -> Vec { - const W: usize = 128; - const H: usize = 128; - let source = format!( - "mandelbrot=size=192x192:rate=25,rotate=a=0.12*t:c=black,\ - scale=w='ceil(192*(1+0.04*n)/2)*2':h='ceil(192*(1+0.04*n)/2)*2':eval=frame,\ - crop={W}:{H}" - ); - let duration = (frames as f64 / 25.0).to_string(); - let ff_args: Vec<&str> = vec![ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-pix_fmt", - "yuv420p12le", - // y4m has no official 12-bit tag, same as the 10-bit gate. - "-strict", - "-1", - "-t", - &duration, - "-f", - "yuv4mpegpipe", - "-", - ]; - let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args(&ff_args) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - out.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - out.stdout - } - - /// The 12-bit coding recipe shared by the witness gates (cpu-used=0 so - /// every search runs; explicit CDEF/restoration ON). Warp/global-motion - /// are deliberately NOT spelled here: this aomenc honours the LAST - /// occurrence of these flags (measured), so a base pin plus an override - /// would silently take the base value -- each gate spells what it needs - /// exactly once. - pub(super) fn encode_12bit(y4m: &[u8], frames: usize, extra: &[&str]) -> Vec { - let limit = format!("--limit={frames}"); - let mut args: Vec<&str> = vec![ - "--codec=av1", - "--profile=2", - "--passes=1", - "--end-usage=q", - "--cq-level=20", - "--cpu-used=0", - "--threads=1", - "--row-mt=0", - "--sb-size=64", - "--lag-in-frames=0", - "--auto-alt-ref=0", - "--kf-max-dist=1000", - "--input-bit-depth=12", - "--bit-depth=12", - "--enable-cdef=1", - "--enable-restoration=1", - "--obu", - "-o", - "-", - "-", - &limit, - ]; - // AOMENC FLAG PRECEDENCE (COMMON): aomenc keeps the FIRST occurrence - // of a flag, so the per-arm override goes BEFORE the base list. - args.splice(1..1, extra.iter().copied()); - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), y4m); - assert!( - out.status.success(), - "aomenc refused the 12-bit fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - out.stdout - } - - /// Asserts the stream's sequence header really says 12-bit before any - /// pixel comparison is trusted. - pub(super) fn assert_12bit_sequence_header(stream: &[u8], name: &str) { - let mut probe = Av1Parser::new(); - let mut pos = 0usize; - while pos < stream.len() && probe.sequence_header().is_none() { - let obu = probe.parse_obu(&stream[pos..]).unwrap(); - pos += obu.total_size; - } - let seq = probe - .sequence_header() - .expect("stream has a sequence header OBU"); - assert_eq!( - seq.color_config.bit_depth, 12, - "{name}: aomenc did not actually write a 12-bit sequence header" - ); - } - - pub(super) fn ffmpeg_decode_sequence_12bit( - stream: &[u8], - width: usize, - height: usize, - frames: usize, - ) -> Vec { - assert_420_oracle_stream( - stream, - "ffmpeg_decode_sequence_12bit", - "ffmpeg_decode_sequence_422_depth(.., 12, \"yuv422p12le\") (4:2:2); \ - ffmpeg_decode_sequence_444_depth(.., 12, \"yuv444p12le\") (4:4:4)", - ); - let out = run_with_stdin( - Command::new("ffmpeg").args([ - "-v", - "error", - "-f", - "obu", - "-i", - "-", - "-f", - "rawvideo", - "-pix_fmt", - "yuv420p12le", - "-", - ]), - stream, - ); - assert!( - out.status.success(), - "ffmpeg refused the 12-bit stream: {}", - String::from_utf8_lossy(&out.stderr) - ); - let (luma, chroma) = (width * height, width * height / 4); - let frame_bytes = (luma + 2 * chroma) * 2; - assert_eq!( - out.stdout.len(), - frame_bytes * frames, - "expected {frames} 4:2:0 12-bit frames, ffmpeg said: {}", - String::from_utf8_lossy(&out.stderr) - ); - fn le16(bytes: &[u8]) -> Vec { - bytes - .as_chunks::<2>().0.iter() - .map(|c| u16::from_le_bytes([c[0], c[1]])) - .collect() - } - (0..frames) - .map(|i| { - let base = i * frame_bytes; - Pic { - width, - height, - y: le16(&out.stdout[base..base + luma * 2]), - u: le16(&out.stdout[base + luma * 2..base + luma * 2 + chroma * 2]), - v: le16(&out.stdout[base + luma * 2 + chroma * 2..base + frame_bytes]), - } - }) - .collect() - } - - /// lane-av1screen12: how many frames of `stream` carry - /// `allow_screen_content_tools`, and how many of THOSE carry - /// `allow_intrabc`. Both are read out of the frame headers this crate - /// parsed, never taken from the flags handed to the encoder (class - /// `tool-disabled-in-every-gate`): on this oracle build - /// `--tune-content=screen` does NOT by itself decide the frame-header - /// `allow_intrabc` bit -- an untiled `smptebars=size=128x96` source reads - /// `false` with and without the flag, while the 256x192 `tile=2x2` source - /// the intrabc census uses reads `true` with and without it (measured; - /// libaom's content detector, `encoder.c:2404`, is what decides it). - pub(super) fn screen_and_intrabc_frame_counts(stream: &[u8]) -> (u32, u32) { - let mut parser = Av1Parser::new(); - let mut pos = 0usize; - let (mut screen, mut intrabc) = (0u32, 0u32); - while pos < stream.len() { - let Ok(obu) = parser.parse_obu(&stream[pos..]) else { - break; - }; - pos += obu.total_size.max(1); - let header = match &obu.kind { - ObuKind::Frame(h, _) => Some(&**h), - ObuKind::FrameHeader(h) => Some(&**h), - _ => None, - }; - if let Some(h) = header - && h.allow_screen_content_tools - { - screen += 1; - if h.allow_intrabc { - intrabc += 1; - } - } - } - (screen, intrabc) - } - - /// The three committed 12-bit screen-content witnesses, by literal name - /// (a pin name built from a loop variable leaves the pin census - /// unproven), with the length and `fnv1a64` each gate asserts. sha256, - /// recorded in the gates' doc comments and in - /// `lanes/av1screen12.report.md`: - /// - /// * `screen12_palette.obu` 3616 bytes, - /// `adfe26c67c08a7e986db2743b914ecc3e214c56dd2abbdfd17ebf99f06de64c8` - /// * `screen12_intrabc.obu` 482 bytes, - /// `a3b6b94cabdd09a12057c4688990d55495826b87a14332c386d319629070382e` - /// * `screen12_lossless_palette.obu` 11698 bytes, - /// `ec7942c96763593e6d8e4b3fb23c03930bba3bb743102d0cf552fe73ae11c203` - pub(super) const PIN_LEN_PALETTE: usize = 3616; - - pub(super) const PIN_FNV_PALETTE: u64 = 0xf9bb_d408_61d6_f0da; - - pub(super) const PIN_LEN_INTRABC: usize = 482; - - pub(super) const PIN_FNV_INTRABC: u64 = 0xae83_3eb7_9380_263b; - - pub(super) const PIN_LEN_LOSSLESS: usize = 11698; - - pub(super) const PIN_FNV_LOSSLESS: u64 = 0x6e28_41c7_7b0a_f9db; - - /// lane-av1screen12: the shared body of the three 12-bit screen-content - /// gates. Every assertion a "this arm really is 12-bit screen content, - /// and this decoder reproduces it" claim needs, in one place: - /// - /// 1. the committed PIN is the witness -- its length and fnv1a64 are - /// pinned, and `require_pin` HARD-fails on a missing copy rather than - /// testing nothing; - /// 2. the live recipe reproduces that pin byte for byte (aomenc present), - /// so the recipe in the doc comment is not decoration; - /// 3. the stream's OWN sequence header says 12-bit and its frame headers - /// say `allow_screen_content_tools` (and `allow_intrabc` for the arm - /// that wants it); - /// 4. the decode ENGAGED the feature -- `palette_hits()` / - /// `palette_uv_hits()` / `intrabc_hits()` deltas are hard-asserted, - /// because a stream that merely carries the header bit would leave the - /// arm it claims to witness untested (class `gate-blind-to-feature`); - /// 5. every sample of every frame matches the instrumented `aomdec - /// --rawvideo` (`assert_rawvideo_matches`), and independently ffmpeg; - /// 6. THE CONTROL: the same counting comparator, run twice -- clean it - /// must report zero wrong samples in all three planes, and with ONE - /// bit flipped in the ORACLE's own frame-0 luma high byte it must - /// report exactly one wrong luma byte and one fewer exact frame. That - /// is the proof the comparator READS the oracle side: a comparator - /// that compared our samples with themselves would report 0 both - /// times (class `oracle-diff-counter-tautology`). - /// - /// Flip index 1 is the high byte of the first luma sample of frame 0. - /// A 12-bit sample's high byte holds bits 8..15 only, so flipping its low - /// bit can never carry into another byte: the move is exactly +1 wrong - /// byte in the Y plane, which is what makes "+1 in the right plane and - /// frame" a real statement rather than a hope. - #[allow(clippy::too_many_arguments)] - pub(super) fn assert_12bit_screen_content_arm( - name: &str, - pin: &'static str, - live: Vec, - pin_len: usize, - pin_fnv: u64, - frames: usize, - width: usize, - height: usize, - want_intrabc: bool, - ) { - let path = crate_pin(pin); - let stream = require_pin(&path, pin); - assert_eq!( - stream.len(), - pin_len, - "{name}: the committed pin {pin} is {} bytes, this gate names {pin_len}", - stream.len() - ); - assert_eq!( - fnv1a64(&stream), - pin_fnv, - "{name}: the committed pin {pin} moved" - ); - if have_aomenc() { - assert_eq!( - live.len(), - pin_len, - "{name}: the live recipe produced {} bytes, the committed pin {pin} is \ - {pin_len} -- aomenc changed, re-pin it", - live.len() - ); - assert_eq!( - fnv1a64(&live), - pin_fnv, - "{name}: the live recipe no longer reproduces the committed pin {pin}" - ); - } - assert_12bit_sequence_header(&stream, name); - let (screen_frames, intrabc_frames) = screen_and_intrabc_frame_counts(&stream); - assert!( - screen_frames > 0, - "{name}: no frame carries allow_screen_content_tools -- this is not a \ - screen-content stream and the arm would prove nothing" - ); - assert_eq!( - intrabc_frames > 0, - want_intrabc, - "{name}: {intrabc_frames} frame(s) carry allow_intrabc, the gate wants {}", - u32::from(want_intrabc) - ); - - let pal_before = crate::decode::palette_hits(); - let paluv_before = crate::decode::palette_uv_hits(); - let ibc_before = crate::decode::intrabc_hits(); - let decoded = decode_stream(&stream).unwrap_or_else(|e| panic!("{name}: {e}")); - assert_eq!(decoded.len(), frames, "{name}: frame count"); - let palette = crate::decode::palette_hits() - pal_before; - let palette_uv = crate::decode::palette_uv_hits() - paluv_before; - let intrabc = crate::decode::intrabc_hits() - ibc_before; - assert!( - palette > 0, - "{name}: the stream decoded no palette block -- the 12-bit palette syntax \ - would be untested (class gate-blind-to-feature)" - ); - assert!( - palette_uv > 0, - "{name}: the stream decoded no chroma palette block -- the 12-bit palette-UV \ - syntax would be untested (class gate-blind-to-feature)" - ); - if want_intrabc { - assert!( - intrabc > 0, - "{name}: allow_intrabc is set but no block decoded use_intrabc=1 -- the \ - 12-bit intra-block-copy syntax would be untested (class \ - gate-blind-to-feature)" - ); - } - - if aomdec_available(name) { - let dir = std::env::temp_dir().join(format!("ec-av1-{name}-arm")); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).expect("scratch dir"); - let obu = dir.join("in.obu"); - std::fs::write(&obu, &stream).expect("writing the stream"); - assert_rawvideo_matches(&obu, &stream, name, frames, 12); - let _ = std::fs::remove_dir_all(&dir); - // The +1 control (part 6): clean is all-zero, one flipped oracle - // byte is exactly +1 luma byte and one fewer exact frame. - let clean = count_rawvideo_diffs(&stream, name, None).unwrap_or_else(|| { - panic!("{name}: our packed output and the oracle's rawvideo differ in SIZE") - }); - assert_eq!( - clean, - (0, 0, 0, frames, frames), - "{name}: {frames} frame(s) must be byte-exact against the oracle before the \ - control arm means anything" - ); - let flipped = count_rawvideo_diffs(&stream, name, Some(1)) - .unwrap_or_else(|| panic!("{name}: the control arm lost the size check")); - assert_eq!( - flipped, - (1, 0, 0, frames, frames - 1), - "{name}: flipping bit 0 of the ORACLE's frame-0 luma high byte must move the \ - count by exactly +1 luma byte and cost exactly one exact frame -- if this \ - reports 0 the comparator never read the oracle (class \ - oracle-diff-counter-tautology)" - ); - } - if have_ffmpeg() { - let theirs = ffmpeg_decode_sequence_12bit(&stream, width, height, frames); - assert_eq!(theirs.len(), frames, "{name}: ffmpeg frame count"); - for (i, (ours, want)) in decoded.iter().zip(&theirs).enumerate() { - assert_eq!(ours.y, want.y, "{name}: 12-bit luma vs ffmpeg (frame {i})"); - assert_eq!(ours.u, want.u, "{name}: 12-bit U vs ffmpeg (frame {i})"); - assert_eq!(ours.v, want.v, "{name}: 12-bit V vs ffmpeg (frame {i})"); - } - } - eprintln!( - "{name}: {frames} 12-bit frame(s) byte-exact vs aomdec --rawvideo and ffmpeg, \ - {screen_frames} screen frame(s), {intrabc_frames} allow_intrabc, {palette} palette \ - + {palette_uv} palette-UV + {intrabc} intrabc block(s)" - ); - } - - /// Renders a 12-bit y4m for the 12-bit screen-content gates. `tiled` - /// applies `-vf tile=2x2`, which is what takes the source from 128x96 to - /// the 256x192 shape libaom's content detector clears the (stricter) - /// IntraBC threshold on. - pub(super) fn y4m_12bit_screen_source(src: &str, tiled: bool) -> Vec { - let mut ff = Command::new("ffmpeg"); - ff.args(["-v", "error", "-f", "lavfi", "-i", src, "-t", "0.2"]); - if tiled { - ff.args(["-vf", "tile=2x2"]); - } - let out = crate::tool_cache::cached_output_io(ff - .args([ - "-pix_fmt", - "yuv420p12le", - "-strict", - "-1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - out.status.success(), - "ffmpeg failed for the 12-bit screen source {src}: {}", - String::from_utf8_lossy(&out.stderr) - ); - out.stdout - } - - /// Shared body for the lane-av1superhbd HIGH-BIT-DEPTH 4:4:4 superres - /// arms: 10-bit and 12-bit, `--superres-mode=1` at a fixed denominator - /// and `--superres-mode=2` (a per-frame denominator libaom picks itself). - /// - /// Everything the 8-bit 4:4:4 superres cell is non-vacuous by, repeated - /// here, plus the one thing that only matters above 8 bits: the gate - /// asserts the PARSED `bit_depth` equals the depth it names, because a - /// 10-bit recipe whose flags were mistyped still decodes -- it just - /// decodes a DIFFERENT cell than the gate claims, which is the same - /// "phantom cell" trap lane-av1444edge r3 recorded for - /// `use_superres=false`. - /// - /// The per-frame table is `(denominator, coded_width)` in DECODE order. - /// The coded width is re-derived as `(UpscaledWidth*8 + denom/2)/denom` - /// from that frame's OWN parsed denominator rather than only compared to - /// a literal, so a re-pinned fixture cannot satisfy the literals while - /// the scaled-size arithmetic moves under them. `superres_hits` and - /// `predict_scaled_hits` are asserted as DELTAS (both are process-wide - /// counters with no reset). - #[allow(clippy::too_many_arguments)] - pub(super) fn a_444_hbd_superres_arm( - name: &str, - fixture: &str, - fixture_len: usize, - fixture_fnv: u64, - fixture_sha: &str, - bit_depth: u8, - upscaled: (usize, usize), - per_frame: &[(u8, usize)], - ) -> Vec { - let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(fixture); - let stream = std::fs::read(&obu).unwrap_or_else(|e| { - panic!( - "{name}: pinned fixture {fixture} is missing ({e}) -- the gate cannot run, \ - which is a failure, not a skip" - ) - }); - assert_eq!(stream.len(), fixture_len, "{name}: fixture length moved"); - assert_eq!(fnv1a64(&stream), fixture_fnv, "{name}: fixture bytes moved"); - - // --- the header facts the CELL depends on, parsed not assumed ------ - let mut parser = Av1Parser::new(); - let mut pos = 0usize; - let mut seq = None; - let mut heads: Vec = Vec::new(); - while pos < stream.len() { - let parsed = parser - .parse_obu(&stream[pos..]) - .unwrap_or_else(|e| panic!("{name}: aomenc OBU does not parse: {e:?}")); - if parsed.total_size == 0 { - break; - } - pos += parsed.total_size; - match parsed.kind { - ObuKind::SequenceHeader(s) => seq = Some(s), - ObuKind::FrameHeader(h) => heads.push(*h), - ObuKind::Frame(h, _) => heads.push(*h), - _ => {} - } - } - let seq = seq.unwrap_or_else(|| panic!("{name}: the stream carries no sequence header")); - assert_eq!( - ( - seq.color_config.subsampling_x, - seq.color_config.subsampling_y - ), - (0, 0), - "{name}: the stream is not 4:4:4 (ss = ({}, {}))", - seq.color_config.subsampling_x, - seq.color_config.subsampling_y - ); - // The high-bit-depth claim itself. A `--bit-depth` flag that silently - // did not take effect still produces a decodable 4:4:4 superres - // stream -- at 8 bits -- and every other assertion below would pass. - assert_eq!( - seq.color_config.bit_depth, bit_depth, - "{name}: the sequence header parses bit_depth {}, not the {bit_depth} this gate \ - names -- the encoder flags did not take effect and this is a different cell", - seq.color_config.bit_depth - ); - assert!( - seq.enable_superres, - "{name}: the sequence header does not enable superres at all" - ); - assert_eq!( - heads.len(), - per_frame.len(), - "{name}: {} frame headers, expected {}", - heads.len(), - per_frame.len() - ); - for (i, (h, (denom, coded))) in heads.iter().zip(per_frame).enumerate() { - assert!( - h.use_superres, - "{name}: frame {i} has use_superres = false -- this is an UNSCALED stream and \ - the gate would measure something other than the cell it names (class \ - gate-blind-to-feature)" - ); - assert_eq!( - h.superres_denom, *denom, - "{name}: frame {i} PARSED denominator moved from {denom} -- read the header, \ - never the encoder flag (mode 2 chooses its own)" - ); - assert_eq!( - (h.upscaled_width as usize, h.frame_height as usize), - upscaled, - "{name}: frame {i} upscaled size moved" - ); - assert_eq!( - (h.frame_width as usize, h.frame_height as usize), - (*coded, upscaled.1), - "{name}: frame {i} CODED size moved -- this is the scaled half of the cell and \ - the part an unsized stream gets wrong" - ); - let d = u32::from(*denom); - assert_eq!( - (h.upscaled_width * 8 + d / 2) / d, - h.frame_width, - "{name}: frame {i}: FrameWidth is not (UpscaledWidth*8 + denom/2)/denom -- the \ - scaled size the cell rests on is not the spec's" - ); - } - - // --- the pixels ----------------------------------------------------- - let _guard = lock_gate_counters(); - let before_sr = crate::superres::superres_hits(); - let before_scaled = crate::mc::predict_scaled_hits(); - let frames = decode_stream(&stream).unwrap_or_else(|e| { - panic!("{name}: the pinned {bit_depth}-bit 4:4:4 superres stream was refused: {e}") - }); - let scaled_up = crate::superres::superres_hits() - before_sr; - let scaled_mc = crate::mc::predict_scaled_hits() - before_scaled; - assert!( - scaled_up > 0, - "{name}: zero superres_hits -- the upscaler never ran (class gate-blind-to-feature)" - ); - assert!( - scaled_mc > 0, - "{name}: zero predict_scaled_hits -- no inter block read a scaled reference, so the \ - scaled-PREDICTION half of the cell is unexercised (class gate-blind-to-feature)" - ); - assert_eq!(frames.len(), per_frame.len(), "{name}: decoded frame count"); - let max = (1u32 << bit_depth) - 1; - for (i, f) in frames.iter().enumerate() { - assert_eq!( - (f.width, f.height), - upscaled, - "{name}: frame {i} came back {}x{}, not the UPSCALED {}x{}", - f.width, - f.height, - upscaled.0, - upscaled.1 - ); - for (plane, samples) in [("Y", &f.y), ("U", &f.u), ("V", &f.v)] { - assert_eq!( - samples.len(), - upscaled.0 * upscaled.1, - "{name}: frame {i} {plane} plane is {} samples; at 4:4:4 upscaled it must be \ - full resolution ({}x{})", - samples.len(), - upscaled.0, - upscaled.1 - ); - // The depth claim, on the pixels: a decoder that lost the - // high bits (or produced 8-bit values padded into a u16 - // plane) would satisfy every length and geometry assert above - // and only be caught here. - assert!( - samples.iter().all(|&s| u32::from(s) <= max), - "{name}: frame {i} {plane} carries a sample above the {bit_depth}-bit \ - maximum {max} -- the bit depth of the OUTPUT does not match the header" - ); - } - } - if aomdec_available(name) { - let (decoded, hidden) = decode_all_frames_vs_oracle(&stream, name); - eprintln!( - "{name}: {decoded} decode-order frame(s) ({hidden} hidden) byte-exact vs aomdec \ - at {bit_depth}-bit {upscaled:?} upscaled from {per_frame:?} (denominator, coded \ - width) per frame, {scaled_up} upscale(s), {scaled_mc} scaled MC block(s); \ - fixture sha256 {fixture_sha}" - ); - } - heads - } - - /// Seeds swept by the 10-bit LR gate (the 8-bit gate needs ~40 attempts - /// to land a non-RESTORE_NONE frame; every attempt here still has to - /// decode pixel-exact). - /// lane-obmcrec r1: the `LR_SEEDS` members whose 1:4-partition stream both - /// fires `obmc_pair_filter_hits` and decodes every frame pixel-exact. - /// Measured over seeds 42..=73 (32 encodes): 43/46/47/65/66 fire and are - /// exact; 70 and 73 fire and mismatch, but mismatch IDENTICALLY with - /// `--enable-obmc=0` (seed 73 frame 1 luma, seed 70 frame 16), so their - /// defect is in the `--min-partition-size=4` recipe, not in OBMC -- kept - /// out of this gate rather than papered over, and reported as open. - pub(super) const OBMC_PAIR_SEEDS: [u32; 5] = [43, 46, 47, 65, 66]; - - pub(super) const LR_SEEDS: [u32; 16] = [ - 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, - ]; - - /// Wiener + SGR + switchable loop-restoration firings, summed. - pub(super) fn ten_bit_lr_hits() -> usize { - crate::restoration::wiener_hits() - + crate::restoration::sgrproj_hits() - + crate::restoration::switchable_hits() - } - - /// `bit_depth` of the first sequence header in `stream`. - pub(super) fn parsed_bit_depth(stream: &[u8]) -> u8 { - let mut probe = Av1Parser::new(); - let mut pos = 0usize; - while pos < stream.len() && probe.sequence_header().is_none() { - let obu = probe.parse_obu(&stream[pos..]).unwrap(); - pos += obu.total_size; - } - probe - .sequence_header() - .expect("stream has a sequence header OBU") - .color_config - .bit_depth - } - - /// Render `frames` of the shared `gradients_source` as `yuv420p10le` and - /// encode it with a real 10-bit `aomenc`, returning the OBU stream. - /// `extra` carries the tool flags under test. - pub(super) fn encode_10bit_gradients( - name: &str, - width: usize, - height: usize, - frames: usize, - extra: &[&str], - ) -> Vec { - encode_10bit_gradients_seed(name, 42, width, height, frames, extra) - } - - /// As [`encode_10bit_gradients`], but with the fixture seed exposed -- - /// lane-hbdgates r1 sweeps seeds so a tool that aomenc's RD declines on - /// one fixture still gets a firing stream. - pub(super) fn encode_10bit_gradients_seed( - name: &str, - seed: u32, - width: usize, - height: usize, - frames: usize, - extra: &[&str], - ) -> Vec { - let duration = frames as f64 / 25.0; - // lane-ab32 r1: `--ec-fixture-noise` is not an aomenc flag -- it is a - // fixture request, consumed (and stripped) here: the smooth gradients - // source codes as PARTITION_NONE everywhere, so a partition gate needs - // seeded noise on top of it to give the RD a reason to split. - let noisy = extra.contains(&"--ec-fixture-noise"); - let stripped: Vec<&str> = extra - .iter() - .copied() - .filter(|a| *a != "--ec-fixture-noise") - .collect(); - let extra: &[&str] = &stripped; - let base = gradients_source(seed, width, height, &format!("duration={duration}:rate=25")); - let source = if noisy { - format!("{base},noise=alls=40:all_seed={seed}") - } else { - base - }; - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-pix_fmt", - "yuv420p10le", - "-strict", - "-1", - "-t", - &format!("{duration}"), - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "{name}: ffmpeg failed to render the 10-bit fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let mut args: Vec<&str> = vec!["--codec=av1", "--passes=1", "--end-usage=q"]; - // lane-hbdgates r1: a caller-supplied `--cq-level` REPLACES the - // default rather than being appended after it -- two `--cq-level` - // flags on one aomenc line is a coin flip on which one lands. - if !extra.iter().any(|a| a.starts_with("--cq-level=")) { - args.push("--cq-level=30"); - } - args.extend_from_slice(&[ - "--cpu-used=0", - "--threads=1", - "--row-mt=0", - "--sb-size=64", - "--input-bit-depth=10", - "--bit-depth=10", - ]); - args.extend_from_slice(extra); - args.extend_from_slice(&["--obu", "-o", "-", "-"]); - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "{name}: aomenc refused the 10-bit fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - out.stdout - } - - /// The affine-capable encoder (`scripts/build-aom-affine-oracle.sh`), - /// separate from the shared oracle because stock libaom's global-motion - /// model search is pinned to ROTZOOM and can never emit AFFINE. - pub(super) fn affine_aomenc_path() -> std::path::PathBuf { - if let Some(p) = std::env::var_os("EC_AV1_AFFINE_AOMENC") { - return std::path::PathBuf::from(p); - } - let home = std::env::var_os("HOME").unwrap_or_default(); - std::path::PathBuf::from(home).join(".cache/aom-affine/build/aomenc") - } - - pub(super) fn have_affine_aomenc() -> bool { - let present = affine_aomenc_path().is_file(); - assert!( - present || std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none(), - "EC_AV1_REQUIRE_AOMENC is set but no affine-capable aomenc at {} -- run \ - scripts/build-aom-affine-oracle.sh", - affine_aomenc_path().display() - ); - present - } - - pub(super) fn check_pinned_warp_stream(path: &std::path::Path) { - use crate::decode::warp_selected_hits; - let name = path - .file_name() - .map(|n| n.to_string_lossy().into_owned()) - .unwrap_or_default(); - let stream = require_pin(path, &name); - let before = warp_selected_hits(); - let frames = decode_stream(&stream).expect("pinned stream must decode"); - eprintln!( - "warp_selected_hits before={before} after={}", - warp_selected_hits() - ); - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 64, 64, 24); - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - if got.y != want.y { - for row in 0..64 { - let mut line = String::new(); - for col in 0..64 { - let d = got.y[row * 64 + col] as i32 - want.y[row * 64 + col] as i32; - line.push(if d == 0 { - '.' - } else if d.abs() < 4 { - 'o' - } else { - 'X' - }); - } - eprintln!("{line}"); - } - } - assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (pinned)"); - assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (pinned)"); - assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (pinned)"); - } - } - - /// Which of the four 128-root AB shapes the gate above MEASURED aomenc - /// picking (lane-sb128c r9). An arm that is `false` is not reachable from - /// this sweep's recipes and stays unasserted rather than weakening the - /// asserts of the ones that are. - pub(super) const AB_ARMS_REACHED: [bool; 4] = [true, true, true, true]; - - /// lane-av1muchunk422b: read a pinned 4:2:2 128-root mu-chunk fixture, - /// asserting its byte length and FNV-1a64 -- a missing fixture is a - /// failure, not a skip. - pub(super) fn read_pinned_muchunk_fixture(name: &str, len: usize, fnv: u64, gate: &str) -> Vec { - let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("fixtures") - .join(name); - let bytes = std::fs::read(&path).unwrap_or_else(|e| { - panic!( - "{gate}: pinned fixture {} is missing ({e}) -- the gate cannot run, which is a \ - failure, not a skip", - path.display() - ) - }); - assert_eq!(bytes.len(), len, "{gate}: {name} length moved"); - assert_eq!(fnv1a64(&bytes), fnv, "{gate}: {name} bytes moved"); - bytes - } - - /// lane-av1muchunk422b: `(use_128x128_superblock, ss_x, ss_y, mono_chrome)` - /// of an OBU stream's sequence header. Shape first: a stream that came back - /// 4:2:0 would leave the `side > 64` mu-chunk walk unexercised while every - /// counter assert below still passed. - pub(super) fn obu_stream_shape(stream: &[u8]) -> Option<(bool, u8, u8, bool)> { - let mut parser = ec_av1_syntax::Av1Parser::new(); - let mut pos = 0usize; - while let Ok(obu) = parser.parse_obu(&stream[pos..]) { - pos += obu.total_size; - if pos >= stream.len() { - break; - } - } - parser.sequence_header().map(|q| { - ( - q.use_128x128_superblock, - q.color_config.subsampling_x, - q.color_config.subsampling_y, - q.color_config.mono_chrome, - ) - }) - } - - /// The chroma-rect gate's fixture + aomenc recipe for one attempt, shared - /// with the seed-46 pin test below so the pin cannot drift from the gate. - pub(super) fn rectchroma_stream( - bit_depth: u32, - cq: u32, - attempt: u32, - width: usize, - height: usize, - ) -> Vec { - const NAME: &str = "rectchroma_stream"; - let seed = 42 + attempt; - let pix_fmt = if bit_depth == 10 { - "yuv420p10le" - } else { - "yuv420p" - }; - // `gradients_source`, the content the sibling split-transform - // superblock gate uses. A band/noise `geq` fixture was tried - // first (r1) and gave 12/12 pixel-exact streams carrying ZERO - // 1:4 strips -- vacuous. Odd attempts render it transposed so - // HORZ_4 and VERT_4 both appear (class scan-weights-cross-axis). - let bands = format!( - "geq=lum='mod(floor(Y/16),2)*160+48':cb=128:cr=128,noise=alls=10:all_seed={seed}" - ); - let source = if attempt.is_multiple_of(2) { - format!("color=c=black:size={width}x{height}:duration=0.04:rate=25,{bands}") - } else { - format!("color=c=black:size={height}x{width}:duration=0.04:rate=25,{bands},transpose=1") - }; - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-t", - "0.04", - "-pix_fmt", - pix_fmt, - "-strict", - "-1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let cq_arg = format!("--cq-level={cq}"); - let depth_arg = format!("--bit-depth={bit_depth}"); - let input_depth_arg = format!("--input-bit-depth={bit_depth}"); - let out = run_with_stdin( - Command::new(aomenc_path()).args([ - "--codec=av1", - "--passes=1", - "--end-usage=q", - &cq_arg, - "--cpu-used=0", - "--threads=1", - "--row-mt=0", - "--sb-size=64", - &depth_arg, - &input_depth_arg, - "--enable-rect-partitions=1", - // AB off: it competes with 1:4 in the RD search (with - // AB on, 0 superblock 1:4 strips appeared in 16 - // compared streams), and AB below 16x16 is another - // lane's refusal. - "--enable-ab-partitions=0", - "--enable-1to4-partitions=1", - // 16, not 8: with 8 every seed of this recipe stops - // at a 32x32-level PARTITION_HORZ_4/VERT_4 (partition - // values 8/9, 32x8/8x32 luma strips), a shape this - // decoder does not code at all yet -- 12/12 attempts - // refused before a pixel was compared (measured r1). - // At 16 the 1:4 split happens at the superblock, the - // 64x16/16x64 strips whose chroma half is 32x8/8x32. - "--min-partition-size=16", - "--max-partition-size=64", - "--enable-restoration=0", - "--enable-palette=0", - "--deltaq-mode=0", - "--enable-cdef=0", - "--enable-filter-intra=0", - "--enable-cfl-intra=0", - "--enable-intrabc=0", - "--obu", - "-o", - "-", - "-", - ]), - &y4m.stdout, - ); - assert!( - out.status.success(), - "{NAME}: aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - out.stdout - } - - /// Runs the census child on `fixture` and returns the `GRAINCENSUS` line's - /// `(unwritten, scanned)` -- the POST-grain pair, over the picture - /// `apply_grain` returns. - pub(super) fn grain_census(fixture: &str) -> (usize, usize) { - const NAME: &str = - "the_grained_picture_the_caller_receives_carries_no_unwritten_plane_sample"; - let exe = std::env::current_exe().expect("test binary path"); - let out = std::process::Command::new(exe) - .args([ - "--exact", - "stream::tests::t09::uwdep_child_unwritten_census", - "--nocapture", - ]) - .env("UWDEP_CENSUS_FIXTURE", fixture) - .env("EC_AV1_PLANE_SENTINEL", "1") - .output() - .expect("running the census child"); - let text = format!( - "{}{}", - String::from_utf8_lossy(&out.stdout), - String::from_utf8_lossy(&out.stderr), - ); - text.lines() - .find_map(|l| l.strip_prefix("GRAINCENSUS ")) - .and_then(parse_census_line) - .unwrap_or_else(|| { - panic!( - "{NAME}: the census child reported no grained count for {fixture} \ - (child said: {:?})", - text.trim() - ) - }) - } - - /// The synthetic non-vacuity control for the grained census: the child with - /// `UWDEP_CENSUS_FIXTURE` UNSET hands [`census_unwritten_grained`] planes - /// carrying 5 sentinel samples and reports what it counted. Function-level, - /// so no fixture's decode behaviour can change it. - pub(super) fn grain_census_synthetic() -> (usize, usize) { - const NAME: &str = - "the_grained_picture_the_caller_receives_carries_no_unwritten_plane_sample"; - let exe = std::env::current_exe().expect("test binary path"); - let out = std::process::Command::new(exe) - .args([ - "--exact", - "stream::tests::t09::uwdep_child_unwritten_census", - "--nocapture", - ]) - .env("EC_AV1_PLANE_SENTINEL", "1") - .env("UWDEP_CENSUS_SYNTHETIC", "1") - .env_remove("UWDEP_CENSUS_FIXTURE") - .output() - .expect("running the census child"); - let text = format!( - "{}{}", - String::from_utf8_lossy(&out.stdout), - String::from_utf8_lossy(&out.stderr), - ); - text.lines() - .find_map(|l| l.strip_prefix("GRAINCENSUS ")) - .and_then(parse_census_line) - .unwrap_or_else(|| { - panic!( - "{NAME}: the census child reported no synthetic grained count (child said: \ - {:?})", - text.trim() - ) - }) - } - - /// Parses the child's `UWDEP_CENSUS frames= scanned=` line - /// into `(unwritten, scanned)`. The scanned count is what makes the fixture - /// arms meaningful: `unwritten == 0` is also what a build with the census call - /// deleted reports, and only a non-zero scanned count distinguishes "scanned - /// and found nothing" from "never scanned". - pub(super) fn parse_census_line(v: &str) -> Option<(usize, usize)> { - let mut parts = v.split_whitespace(); - let unwritten = parts.next()?.parse().ok()?; - let scanned = parts - .find_map(|p| p.strip_prefix("scanned="))? - .parse() - .ok()?; - Some((unwritten, scanned)) - } - - /// Runs the census child with `UWDEP_CENSUS_FIXTURE` UNSET, which makes it - /// take the synthetic-positive path: hand [`census_unwritten_final`] planes - /// with a known number of `PLANE_SENTINEL` values and report what it counted. - /// This is the non-vacuity control, and it is a direct function-level check - /// rather than a decode, so no fixture's decode behaviour can change it. - pub(super) fn census_synthetic() -> (usize, usize) { - const NAME: &str = "the_frame_the_caller_receives_carries_no_unwritten_plane_sample"; - let exe = std::env::current_exe().expect("test binary path"); - let out = std::process::Command::new(exe) - .args([ - "--exact", - "stream::tests::t09::uwdep_child_unwritten_census", - "--nocapture", - ]) - .env("EC_AV1_PLANE_SENTINEL", "1") - .env("UWDEP_CENSUS_SYNTHETIC", "1") - .env_remove("UWDEP_CENSUS_FIXTURE") - .output() - .expect("running the census child"); - let text = format!( - "{}{}", - String::from_utf8_lossy(&out.stdout), - String::from_utf8_lossy(&out.stderr), - ); - text.lines() - .find_map(|l| l.strip_prefix("UWDEP_CENSUS ")) - .and_then(parse_census_line) - .unwrap_or_else(|| { - panic!( - "{NAME}: the census child reported no synthetic count (child said: {:?})", - text.trim() - ) - }) - } - - /// Runs [`allocdet_child_decode`] in a fresh process and parses its - /// `ALLOCDET frames= hash=` lines into - /// `(fixture, frames, hash)` in FIXTURES order. - pub(super) fn allocdet_child( - fixtures: &[&str], - poison: Option<&str>, - alloc: &str, - ) -> Vec<(String, usize, u64)> { - const NAME: &str = "the_frame_does_not_depend_on_the_plane_buffers_initial_content"; - let exe = std::env::current_exe().expect("test binary path"); - let mut cmd = std::process::Command::new(exe); - cmd.args([ - "--exact", - "stream::tests::t09::allocdet_child_decode", - "--nocapture", - ]) - .env("ALLOCDET_FIXTURES", fixtures.join(",")) - .env("EC_AV1_PLANE_ALLOC", alloc) - .env_remove("ALLOCDET_SYNTHETIC"); - match poison { - Some(p) => cmd.env("EC_AV1_PLANE_SENTINEL", p), - None => cmd.env_remove("EC_AV1_PLANE_SENTINEL"), - }; - let out = cmd.output().expect("running the allocdet child"); - let text = format!( - "{}{}", - String::from_utf8_lossy(&out.stdout), - String::from_utf8_lossy(&out.stderr), - ); - let mut rows = Vec::new(); - for f in fixtures { - let line = text - .lines() - .find(|l| l.starts_with(&format!("ALLOCDET {f} "))) - .unwrap_or_else(|| { - panic!( - "{NAME}: the child reported nothing for {f} (child said: {:?})", - text.trim() - ) - }); - let mut parts = line.split_whitespace(); - assert_eq!(parts.next(), Some("ALLOCDET")); - assert_eq!(parts.next(), Some(*f)); - let frames = parts - .find_map(|p| p.strip_prefix("frames=")) - .and_then(|v| v.parse().ok()) - .unwrap_or_else(|| panic!("{NAME}: no frame count in {line:?}")); - let hash = parts - .find_map(|p| p.strip_prefix("hash=")) - .and_then(|v| u64::from_str_radix(v, 16).ok()) - .unwrap_or_else(|| panic!("{NAME}: no hash in {line:?}")); - rows.push(((*f).to_string(), frames, hash)); - } - rows - } - - /// Two pictures identical except for ONE sample of ONE plane, hashed by the - /// same FNV-1a the child uses. Equal values here would make the gate's - /// equalities vacuous, so it is asserted to differ. - pub(super) fn allocdet_synthetic() -> (u64, u64) { - const P: u64 = 0x0000_0100_0000_01b3; - let hash = |mut h: u64, samples: &[u16]| { - for &s in samples { - for b in s.to_le_bytes() { - h ^= u64::from(b); - h = h.wrapping_mul(P); - } - } - h - }; - let a = vec![128u16; 4096]; - let mut b = a.clone(); - b[2048] = 129; - ( - hash(0xcbf2_9ce4_8422_2325, &a), - hash(0xcbf2_9ce4_8422_2325, &b), - ) - } - - /// lane-av1formatsweep: encodes the odd-dimension arm's fixture -- - /// `testsrc2` (or the smoothed `mandelbrot` source at 12 bits, which - /// keeps `allow_screen_content_tools` off) as `y4m`, then hands the pipe - /// to `aomenc`. The child deadline comes from `run_with_stdin` - /// (`EC_AV1_CHILD_TIMEOUT_SECS`), so a wedged encoder fails loudly. - pub(super) fn odd_dim_stream( - width: usize, - height: usize, - pix_fmt: &str, - bit_depth: usize, - smooth: bool, - ) -> Vec { - let source = if smooth { - format!("mandelbrot=size={width}x{height}:rate=25") - } else { - format!("testsrc2=size={width}x{height}:rate=25") - }; - let mut ffmpeg_args: Vec = vec![ - "-v".into(), - "error".into(), - "-f".into(), - "lavfi".into(), - "-i".into(), - source, - ]; - if smooth { - ffmpeg_args.extend(["-vf".into(), "gblur=sigma=6".into()]); - } - ffmpeg_args.extend([ - "-frames:v".into(), - "4".into(), - "-pix_fmt".into(), - pix_fmt.into(), - "-strict".into(), - "-1".into(), - "-f".into(), - "yuv4mpegpipe".into(), - "-".into(), - ]); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args(&ffmpeg_args) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg refused the {width}x{height} {pix_fmt} source: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let mut args: Vec = [ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=20", - "--cpu-used=2", - "--threads=1", - "--row-mt=0", - "--lag-in-frames=0", - "--kf-max-dist=100", - "--limit=4", - ] - .iter() - .map(|s| (*s).to_owned()) - .collect(); - if bit_depth > 8 { - args.push(format!("--input-bit-depth={bit_depth}")); - args.push(format!("--bit-depth={bit_depth}")); - } - args.extend(["--obu".into(), "-o".into(), "-".into(), "-".into()]); - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused {args:?}: {}", - String::from_utf8_lossy(&out.stderr) - ); - out.stdout - } - - /// Reads `(mi_cols, mi_rows)` out of a stream's first frame header, and - /// asserts the sequence header says the bit depth the caller asked for. - pub(super) fn odd_dim_header_mi_grid(stream: &[u8], name: &str, bit_depth: usize) -> (usize, usize) { - let mut parser = Av1Parser::new(); - let mut pos = 0usize; - let mut seen_depth = None; - let mut grid = None; - while pos < stream.len() { - let obu = parser - .parse_obu(&stream[pos..]) - .unwrap_or_else(|e| panic!("{name}: aomenc OBU does not parse: {e:?}")); - if obu.total_size == 0 { - break; - } - pos += obu.total_size; - match obu.kind { - ObuKind::SequenceHeader(seq) => { - assert_eq!( - seq.color_config.bit_depth as usize, bit_depth, - "{name}: the stream is not {bit_depth}-bit" - ); - assert_eq!( - ( - seq.color_config.subsampling_x, - seq.color_config.subsampling_y - ), - (1, 1), - "{name}: not a 4:2:0 stream" - ); - seen_depth = Some(seq.color_config.bit_depth); - } - ObuKind::FrameHeader(h) | ObuKind::Frame(h, _) => { - grid = Some(( - (h.frame_width as usize).div_ceil(8), - (h.frame_height as usize).div_ceil(8), - )); - } - _ => {} - } - } - assert!(seen_depth.is_some(), "{name}: no sequence header parsed"); - grid.expect("the stream carries no frame header") - } - - /// lane-av1formatsweep: a `testsrc2`/`mandelbrot` source rendered to - /// `pix_fmt` as y4m and piped to `aomenc` at `bit_depth`, with `extra` - /// aomenc flags. `smooth` selects the gblur'd `mandelbrot` source (1) or - /// `testsrc2` (0). The child deadline comes from `run_with_stdin` - /// (`EC_AV1_CHILD_TIMEOUT_SECS`), so a wedged encoder fails loudly. - pub(super) fn chroma_format_stream( - width: usize, - height: usize, - pix_fmt: &str, - bit_depth: usize, - frames: usize, - extra: &[&str], - smooth: u8, - ) -> Vec { - let source = if smooth == 1 { - format!("mandelbrot=size={width}x{height}:rate=25") - } else { - format!("testsrc2=size={width}x{height}:rate=25") - }; - let mut ffmpeg_args: Vec = vec![ - "-v".into(), - "error".into(), - "-f".into(), - "lavfi".into(), - "-i".into(), - source, - ]; - if smooth == 1 { - ffmpeg_args.extend(["-vf".into(), "gblur=sigma=6".into()]); - } - ffmpeg_args.extend([ - "-frames:v".into(), - frames.to_string(), - "-pix_fmt".into(), - pix_fmt.into(), - "-strict".into(), - "-1".into(), - "-f".into(), - "yuv4mpegpipe".into(), - "-".into(), - ]); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args(&ffmpeg_args) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg refused the {width}x{height} {pix_fmt} source: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - // AOMENC FLAG PRECEDENCE (COMMON): aomenc keeps the FIRST occurrence - // of a flag, so the per-arm override goes BEFORE the base list. - let limit = format!("--limit={frames}"); - let mut args: Vec = extra.iter().map(|s| (*s).to_owned()).collect(); - args.extend( - [ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--threads=1", - "--row-mt=0", - "--lag-in-frames=0", - "--kf-max-dist=100", - limit.as_str(), - ] - .iter() - .map(|s| (*s).to_owned()), - ); - if bit_depth > 8 { - args.push(format!("--input-bit-depth={bit_depth}")); - args.push(format!("--bit-depth={bit_depth}")); - } - args.extend(["--obu".into(), "-o".into(), "-".into(), "-".into()]); - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused {args:?}: {}", - String::from_utf8_lossy(&out.stderr) - ); - out.stdout - } - - /// Asserts the stream's sequence header really is 4:4:4 (`ss 0,0`) at - /// `bit_depth` before any pixel comparison is trusted (class - /// `arrival-not-intent`: a recipe that silently produced 4:2:0 would - /// make the whole gate a no-op for its own subject). - pub(super) fn assert_444_header(stream: &[u8], name: &str, bit_depth: usize) { - let mut parser = Av1Parser::new(); - let mut pos = 0usize; - let mut seen = false; - while pos < stream.len() { - let obu = parser - .parse_obu(&stream[pos..]) - .unwrap_or_else(|e| panic!("{name}: aomenc OBU does not parse: {e:?}")); - if obu.total_size == 0 { - break; - } - pos += obu.total_size; - if let ObuKind::SequenceHeader(seq) = obu.kind { - let cc = &seq.color_config; - assert_eq!( - (cc.subsampling_x, cc.subsampling_y), - (0, 0), - "{name}: the stream is not 4:4:4 (ss {}x{})", - cc.subsampling_x, - cc.subsampling_y - ); - assert_eq!( - cc.bit_depth as usize, bit_depth, - "{name}: the stream is {}-bit, not {bit_depth}-bit", - cc.bit_depth - ); - seen = true; - } - } - assert!(seen, "{name}: no sequence header parsed"); - } - - /// lane-av1tilemeasure: the per-frame facts a tiling / superres / odd-size - /// cell's OWN claim needs, read off the parsed stream. - /// - /// Every gate below asserts its cell through this, never through the - /// aomenc flag that was supposed to produce it. `lanes/av1formatsweep. - /// report.md` trap 2 is exactly that failure: `--tile-rows=1` below 256px - /// high at `--sb-size=128` leaves the stream byte-identical, so a gate - /// that trusted the flag would report an untiled decode as a tile-row - /// decode (and the sweep's own 10/12-bit "tile rows" numbers were that). - #[derive(Debug, Clone, Copy)] - pub(super) struct FrameFacts { - pub(super) tile_cols: u32, - pub(super) tile_rows: u32, - pub(super) use_superres: bool, - pub(super) coded_w: u32, - pub(super) coded_h: u32, - pub(super) upscaled_w: u32, - pub(super) mi_cols: u32, - pub(super) mi_rows: u32, - } - - pub(super) fn frame_facts(stream: &[u8], name: &str) -> Vec { - let mut parser = Av1Parser::new(); - let mut pos = 0usize; - let mut out: Vec = Vec::new(); - while pos < stream.len() { - let obu = parser - .parse_obu(&stream[pos..]) - .unwrap_or_else(|e| panic!("{name}: aomenc OBU does not parse: {e:?}")); - if obu.total_size == 0 { - break; - } - pos += obu.total_size; - if let ObuKind::FrameHeader(h) | ObuKind::Frame(h, _) = obu.kind { - out.push(FrameFacts { - tile_cols: h.tile_info.cols, - tile_rows: h.tile_info.rows, - use_superres: h.use_superres, - coded_w: h.frame_width, - coded_h: h.frame_height, - upscaled_w: h.upscaled_width, - mi_cols: h.mi_cols, - mi_rows: h.mi_rows, - }); - } - } - assert!( - !out.is_empty(), - "{name}: the stream carries no frame header" - ); - out - } - - /// Decode-order frame 0 only, against the oracle's own - /// `EC_AV1_FINAL_DUMP` for that frame: how many SAMPLES differ, and the - /// first one as `(plane, x, y, ours, oracle)`. - /// - /// lane-av1loss444kf: the 4:4:4 lossless 256x256 cell's inter frames carry a - /// SEPARATE, already-diagnosed walk defect (the per-mu-chunk lossless - /// chroma span, `lanes/av1loss444mm.report.md` r1), so a whole-stream - /// byte-exactness assert cannot name this one. `aomdec --limit=1` stops - /// after the key frame, which is exactly the frame the reach fix moves. - #[allow(clippy::type_complexity)] - pub(super) fn key_frame_diffs( - stream: &[u8], - name: &str, - ) -> (usize, Option<(usize, usize, usize, u8, u8)>) { - let dir = std::env::temp_dir().join(format!("ec-av1-{name}-kf-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).expect("scratch dir"); - let obu = dir.join("in.obu"); - std::fs::write(&obu, stream).expect("writing the stream"); - let aom_prefix = dir.join("aomkf"); - let out = crate::tool_cache::cached_output_io(Command::new(aomdec_path()) - .args(["--codec=av1", "--limit=1", "-o"]) - .arg(dir.join("out.y4m")) - .arg(&obu) - .env("EC_AV1_FINAL_DUMP", &aom_prefix) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("aomdec failed to run"); - assert!( - out.status.success(), - "{name}: the oracle aomdec refused the stream: {}", - String::from_utf8_lossy(&out.stderr) - ); - let ours_prefix = dir.join("ourskf"); - set_final_dump_prefix(Some(ours_prefix.display().to_string())); - let decoded = decode_stream(stream); - set_final_dump_prefix(None); - decoded.unwrap_or_else(|e| panic!("{name}: this decoder refused the stream: {e}")); - let want = std::fs::read(format!("{}.f0", aom_prefix.display())).expect( - "the oracle wrote no decode-order frame 0 -- rung 12 of \ - scripts/instrument-aom-oracle.sh is missing", - ); - let got = std::fs::read(format!("{}.f0", ours_prefix.display())) - .expect("this decoder wrote no decode-order frame 0"); - assert_eq!( - got.len(), - want.len(), - "{name}: our key frame is {} bytes, the oracle's is {}", - got.len(), - want.len() - ); - let side = (want.len() / 3).isqrt(); - let differing = got.iter().zip(&want).filter(|(a, b)| a != b).count(); - let first = got.iter().zip(&want).position(|(a, b)| a != b).map(|at| { - // the dump is plane after plane (Y, U, V), so the in-plane - // offset is what carries the x/y split - let plane = at / (side * side); - let in_plane = at % (side * side); - (plane, in_plane % side, in_plane / side, got[at], want[at]) - }); - let _ = std::fs::remove_dir_all(&dir); - (differing, first) - } - - /// lane-av1cfl: per-plane sample-mismatch counts between this decoder's - /// final stored frames and the instrumented oracle's, summed over every - /// decode-order frame. Returns `[Y, U, V]`. - /// - /// [`decode_all_frames_vs_oracle`] panics on the first differing byte, - /// which names an offset but not WHICH PLANE the offset falls in -- and - /// for a chroma-scoped defect the plane split is the whole diagnosis - /// (luma byte-exact while U and V both diverge is the chroma-sizing - /// signature; all three diverging is not). - /// - /// `plane_samples` is each plane's own sample count in DECODE order - /// (`[Y, U, V]`) and is read off this decoder's own frame rather than - /// derived from the dimensions: at 4:2:0 the chroma planes are half-size - /// and at 4:4:4 full-size, and a helper that assumed one layout would - /// report every chroma byte as a luma byte. 8-bit only: the dump is one - /// byte per sample at 8-bit and two at 10/12. - pub(super) fn oracle_plane_diffs(stream: &[u8], name: &str, plane_samples: [usize; 3]) -> [usize; 3] { - let dir = std::env::temp_dir().join(format!("ec-av1-{name}-planes-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).expect("scratch dir"); - let obu = dir.join("in.obu"); - std::fs::write(&obu, stream).expect("writing the stream"); - let aom_prefix = dir.join("aom"); - let out = crate::tool_cache::cached_output_io(Command::new(aomdec_path()) - .args(["--codec=av1", "-o"]) - .arg(dir.join("out.y4m")) - .arg(&obu) - .env("EC_AV1_FINAL_DUMP", &aom_prefix) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("aomdec failed to run"); - assert!( - out.status.success(), - "{name}: the oracle aomdec refused the stream: {}", - String::from_utf8_lossy(&out.stderr) - ); - let mut oracle_frames = 0usize; - while std::path::PathBuf::from(format!("{}.f{oracle_frames}", aom_prefix.display())) - .is_file() - { - oracle_frames += 1; - } - assert!( - oracle_frames > 0, - "{name}: the oracle wrote no EC_AV1_FINAL_DUMP frames -- rung 12 of \ - scripts/instrument-aom-oracle.sh is missing from {}", - aomdec_path().display() - ); - let ours_prefix = dir.join("ours"); - set_final_dump_prefix(Some(ours_prefix.display().to_string())); - let decoded = decode_stream(stream); - set_final_dump_prefix(None); - let _ = decoded.expect("the caller already decoded this stream cleanly"); - let total: usize = plane_samples.iter().sum(); - // Plane boundaries in the concatenated dump, in DECODE order. - let mut starts = [0usize; 3]; - for p in 1..3 { - starts[p] = starts[p - 1] + plane_samples[p - 1]; - } - let mut per_plane = [0usize; 3]; - for i in 0..oracle_frames { - let want = - std::fs::read(format!("{}.f{i}", aom_prefix.display())).expect("oracle dump"); - let got = std::fs::read(format!("{}.f{i}", ours_prefix.display())).expect("our dump"); - assert_eq!( - got.len(), - total, - "{name}: decode-order frame {i} is {} bytes, expected {plane_samples:?} at 8-bit", - got.len() - ); - for p in 0..3 { - let (a, b) = (starts[p], starts[p] + plane_samples[p]); - per_plane[p] += got[a..b] - .iter() - .zip(&want[a..b]) - .filter(|(x, y)| x != y) - .count(); - } - } - let _ = std::fs::remove_dir_all(&dir); - per_plane - } - - /// Shared body for the lane-av1superpin 4:4:4 superres arms. It is the - /// body of [`a_444_lossy_superres_stream_decodes_pixel_exact`] with the - /// single `(denominator, coded_width)` constant generalised to a PER-FRAME - /// table, which is what the mode-2 cell needs: libaom picks a different - /// denominator for each frame there, so a single constant would either - /// describe frame 0 only or be a literal the arithmetic below could not - /// hold. - /// - /// Everything that makes the den=12 cell non-vacuous is here, unchanged: - /// the pinned bytes (length + FNV-1a), 4:4:4 / 8-bit / superres-enabled - /// from the sequence header, `use_superres` on every parsed frame header, - /// the per-frame parsed denominator and coded size, and the coded width - /// RE-DERIVED as `(UpscaledWidth*8 + denom/2)/denom` from that frame's OWN - /// parsed denominator rather than compared to a literal alone -- so a - /// re-pinned fixture cannot satisfy the literals while the scaled-size - /// arithmetic moves under them. Then `superres_hits` and - /// `predict_scaled_hits` as DELTAS (both counters are process-wide with no - /// reset, so absolute values would pass on residue from another stream), - /// the returned frames at the UPSCALED width with full-resolution 4:4:4 - /// chroma planes, and every decode-order frame byte-exact against the - /// instrumented aomdec. - #[allow(clippy::too_many_arguments)] - pub(super) fn a_444_superres_arm( - name: &str, - fixture: &str, - fixture_len: usize, - fixture_fnv: u64, - fixture_sha: &str, - upscaled: (usize, usize), - // `(denominator, coded_width)` per DECODE-ORDER frame. - per_frame: &[(u8, usize)], - ) -> Vec { - let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(fixture); - let stream = std::fs::read(&obu).unwrap_or_else(|e| { - panic!( - "{name}: pinned fixture {} is missing ({e}) -- the gate cannot run, \ - which is a failure, not a skip", - obu.display() - ) - }); - assert_eq!(stream.len(), fixture_len, "{name}: fixture length moved"); - assert_eq!(fnv1a64(&stream), fixture_fnv, "{name}: fixture bytes moved"); - - // --- the header facts the CELL depends on, parsed not assumed ------ - let mut parser = Av1Parser::new(); - let mut pos = 0usize; - let mut seq = None; - let mut heads: Vec = Vec::new(); - while pos < stream.len() { - let obu = parser - .parse_obu(&stream[pos..]) - .unwrap_or_else(|e| panic!("{name}: aomenc OBU does not parse: {e:?}")); - if obu.total_size == 0 { - break; - } - pos += obu.total_size; - match obu.kind { - ObuKind::SequenceHeader(s) => seq = Some(s), - ObuKind::FrameHeader(h) => heads.push(*h), - ObuKind::Frame(h, _) => heads.push(*h), - _ => {} - } - } - let seq = seq.unwrap_or_else(|| panic!("{name}: the stream carries no sequence header")); - assert_eq!( - ( - seq.color_config.subsampling_x, - seq.color_config.subsampling_y - ), - (0, 0), - "{name}: the stream is not 4:4:4 (ss = ({}, {}))", - seq.color_config.subsampling_x, - seq.color_config.subsampling_y - ); - assert_eq!( - seq.color_config.bit_depth, 8, - "{name}: not the 8-bit cell this gate names" - ); - assert!( - seq.enable_superres, - "{name}: the sequence header does not enable superres at all" - ); - assert_eq!( - heads.len(), - per_frame.len(), - "{name}: {} frame headers, expected {}", - heads.len(), - per_frame.len() - ); - for (i, (h, (denom, coded))) in heads.iter().zip(per_frame).enumerate() { - // The assertion the phantom cell failed. Without a denominator - // flag aomenc picks 8 and this is false while the stream still - // decodes, which is how a whole sweep cell ends up mislabelled. - assert!( - h.use_superres, - "{name}: frame {i} has use_superres = false -- this is an UNSCALED \ - stream and the gate would be measuring something other than the \ - cell it names (class gate-blind-to-feature)" - ); - assert_eq!( - h.superres_denom, *denom, - "{name}: frame {i} PARSED denominator moved from {denom} -- read the \ - header, never the encoder flag (mode 2 chooses its own)" - ); - assert_eq!( - (h.upscaled_width as usize, h.frame_height as usize), - upscaled, - "{name}: frame {i} upscaled size moved" - ); - assert_eq!( - (h.frame_width as usize, h.frame_height as usize), - (*coded, upscaled.1), - "{name}: frame {i} CODED size moved -- this is the scaled half of \ - the cell and the part an unsized stream gets wrong" - ); - // Re-derive rather than only compare literals, so a re-pinned - // fixture cannot satisfy the numbers above while the scaled-size - // arithmetic has moved under them. The denominator here is the - // one PARSED out of this frame, so the check cannot be satisfied by - // a literal that merely happens to agree. - let d = u32::from(*denom); - assert_eq!( - (h.upscaled_width * 8 + d / 2) / d, - h.frame_width, - "{name}: frame {i}: FrameWidth is not (UpscaledWidth*8 + denom/2)/denom -- \ - the scaled size the cell rests on is not the spec's" - ); - } - - // --- the pixels ----------------------------------------------------- - let _guard = lock_gate_counters(); - let before_sr = crate::superres::superres_hits(); - let before_scaled = crate::mc::predict_scaled_hits(); - let frames = decode_stream(&stream).unwrap_or_else(|e| { - panic!("{name}: the pinned 4:4:4 superres stream was refused: {e}") - }); - let scaled_up = crate::superres::superres_hits() - before_sr; - let scaled_mc = crate::mc::predict_scaled_hits() - before_scaled; - assert!( - scaled_up > 0, - "{name}: zero superres_hits -- the upscaler never ran (class \ - gate-blind-to-feature)" - ); - assert!( - scaled_mc > 0, - "{name}: zero predict_scaled_hits -- no inter block read a scaled reference, \ - so the scaled-PREDICTION half of the cell is unexercised (class \ - gate-blind-to-feature)" - ); - assert_eq!(frames.len(), per_frame.len(), "{name}: decoded frame count"); - for (i, f) in frames.iter().enumerate() { - // The upscale must have REPLACED the frame: a decoder that returned - // the coded-width picture fails here, and without this check the - // chroma-shape assertion below could be satisfied by coded-size - // planes. - assert_eq!( - (f.width, f.height), - upscaled, - "{name}: frame {i} came back {}x{}, not the UPSCALED {}x{}", - f.width, - f.height, - upscaled.0, - upscaled.1 - ); - for (plane, len) in [("U", f.u.len()), ("V", f.v.len())] { - assert_eq!( - len, - upscaled.0 * upscaled.1, - "{name}: frame {i} {plane} plane is {len} samples; at 4:4:4 upscaled it \ - must be full resolution ({}x{})", - upscaled.0, - upscaled.1 - ); - } - } - if aomdec_available(name) { - let (decoded, hidden) = decode_all_frames_vs_oracle(&stream, name); - eprintln!( - "{name}: {decoded} decode-order frame(s) ({hidden} hidden) byte-exact vs \ - aomdec at {upscaled:?} upscaled from {per_frame:?} (denominator, coded \ - width) per frame, {scaled_up} upscale(s), {scaled_mc} scaled MC block(s); \ - fixture sha256 {fixture_sha}" - ); - } - heads - } diff --git a/crates/ec-av1/src/stream/tests/t01.rs b/crates/ec-av1/src/stream/tests/t01.rs deleted file mode 100644 index 5e0fddfc..00000000 --- a/crates/ec-av1/src/stream/tests/t01.rs +++ /dev/null @@ -1,4538 +0,0 @@ -use super::*; -use super::support::*; -use super::gates_a::*; -use crate::encode::{Picture as Pic, encode_key_frame_with_ctx, encode_sequence_with_ctx}; -use crate::probe::run_with_stdin; -use std::process::{Command, Stdio}; - - /// lane-av1422lift: THE 4:2:2 LIFT, in two pins. This test is the renamed, - /// inverted replacement for `a_non_420_subsampled_sequence_header_is_ - /// refused_by_name`, and the two fixtures replace that gate's fixture -- - /// a hand-built profile-2 header bolted onto a 4:2:0 TILE from this - /// crate's own encoder, which could never be inverted into an exactness - /// claim no matter how the assert was flipped (class `refusal-lifted- - /// without-a-gate`, and the risk study's R6). - /// - /// Both pins are REAL 4:2:2 streams from libaom's own writer over a - /// y4m whose header line is `C422`, so every chroma symbol in them is a - /// 4:2:2 chroma symbol. Provenance (both, verbatim, no other encoder): - /// - /// ```text - /// aomenc --codec=av1 --profile=2 \ - /// --input-chroma-subsampling-x=1 --input-chroma-subsampling-y=0 \ - /// --passes=1 --end-usage=q --cq-level=24 --cpu-used=0 \ - /// --threads=1 --row-mt=0 --obu -o - /// ``` - /// - /// * `422_key_64x64.obu` -- 755 bytes, sha256 - /// `3c9396c9e42701d720419ec2cb5577387e305482df0cb150f7f0b965edeaaffc`, - /// fnv1a64 `0x87fc569cf53bcbc6`. A single 64x64 8-bit KEY frame - /// (`--limit=1 --kf-min-dist=0 --kf-max-dist=0`) over a - /// hand-generated two-frame integer `C422` card source, the second - /// source frame unused by the `--limit=1`. The smallest thing that can - /// say "4:2:2 intra reconstructs". - /// * `422_inter_160x128_3f.obu` -- 6522 bytes, sha256 - /// `7b54834c18f5fdc0e8606a6dc5bf4ff368402417d87fcfc2ab9758e4e9164902`, - /// fnv1a64 `0xf87eba3bf4fc2bb8`. Three 160x128 8-bit frames with a - /// panning square - /// (`--limit=3 --kf-min-dist=3 --kf-max-dist=3`, so frames 1 and 2 are - /// INTER), over a three-frame integer `C422` card source whose square - /// moves (6,4) -> (9,6) -> (12,8). This is what exercises the - /// inter-predicted 4:2:2 chroma reference: a decoder that walked the - /// key frame correctly and then predicted chroma from a 4:2:0-shaped - /// reference passes the first pin and reds here. - /// - /// Both are asserted BYTE-EXACT against ffmpeg 8.1.3's own rawvideo of - /// the same bytes at `yuv422p`, per plane and per frame, with the - /// per-plane coefficient-unit census as the non-vacuity arm (see - /// [`assert_422_stream_pixel_exact`]). A gate whose only assertion was - /// `err.contains(REFUSAL)` would have passed unchanged on a tree where - /// 4:2:2 decode was completely broken; that is what this replaces. - #[test] - fn a_real_422_key_frame_and_inter_sequence_decode_pixel_exact() { - const NAME: &str = "a_real_422_key_frame_and_inter_sequence_decode_pixel_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - let key = crate_pin("422_key_64x64.obu"); - let key_stream = read_pin(&key, 755, 0x87fc569cf53bcbc6, NAME); - let (units, _) = assert_422_stream_pixel_exact(NAME, &key_stream, 64, 64, 1, 8, true); - let (l, u, v) = (units[0], units[1], units[2]); - assert!( - l > 0 && u > 0 && v > 0, - "{NAME}: the key-frame pin walked no 4:2:2 chroma units [{l}, {u}, {v}]" - ); - - let inter = crate_pin("422_inter_160x128_3f.obu"); - let inter_stream = read_pin(&inter, 6522, 0xf87eba3bf4fc2bb8, NAME); - let (units, _) = assert_422_stream_pixel_exact(NAME, &inter_stream, 160, 128, 3, 8, true); - let (l, u, v) = (units[0], units[1], units[2]); - assert!( - u > 0 && v > 0, - "{NAME}: the inter pin walked no 4:2:2 chroma units [{l}, {u}, {v}] -- the inter \ - chroma reference path was never reached" - ); - } - - /// lane-av1422lift: 4:2:2 at 12 bits, and 4:2:2 with superres, are the two - /// cells the corpus had no coverage for at all (the risk study's R3 and - /// R9: the sweep recipe passed no 12-bit depth and no `--superres-mode`, - /// so every 4:2:2 measurement in the tree was 8- or 10-bit, none - /// superres). Both are pinned and both are byte-exact here. - /// - /// `s422_12bit_160x128.obu` -- 9214 bytes, sha256 - /// `eacc70f75c82ad7d795efbd0242aa4ee33db917b8c1a3570ebce2570ee8bc245`, - /// fnv1a64 `0xa62b8e3fe6f60ae5`. 160x128, 12-bit, 3 frames, - /// `yuv422p12le` per ffprobe, profile 2 ("Professional"). - /// - /// **Provenance is ffmpeg's libaom-av1 wrapper, not aomenc, and the - /// reason is measured, not preferred.** aomenc's own 12-bit y4m path - /// issues `AV1E_SET_CHROMA_SUBSAMPLING_X` (apps/aomenc.c:2272-2278, - /// reached whenever the input is not 4:2:0 and the bit depth is 12) - /// BEFORE `aom_codec_enc_config_set`, and on this libaom that control - /// returns `AOM_CODEC_INTERNAL_ERROR` for any non-4:2:0 shape -- measured - /// on four independently built trees - /// (`~/.cache/aom-oracle`, `aom-affine`, `aom-oracle2`, `aom-oracle3`): - /// `C422p12` and `C444p12` both die with "Failed to set chroma - /// subsampling x", while `C420p12` and the 8-bit `C422`/`C444` both - /// encode. It is not a 4:2:2-specific gap (12-bit 4:4:4 fails too) and - /// not a 4:2:0 gap (12-bit 4:2:0 encodes). The same control succeeds at - /// 8 bits, so the failure is the 12-bit configuration order, and the - /// workaround is a wrapper that sets the codec config first. ffmpeg's - /// libaom-av1 does exactly that: - /// - /// ```text - /// ffmpeg -f lavfi -i "testsrc2=size=160x128:rate=1:duration=3" \ - /// -pix_fmt yuv422p12le -c:v libaom-av1 -profile:v 2 -b:v 0 -crf 30 \ - /// -cpu-used 8 -auto-alt-ref 0 -lag-in-frames 0 \ - /// -strict experimental -f obu s422_12bit_160x128.obu - /// ``` - /// - /// That is libaom's encoder either way -- ffmpeg links it and calls - /// `aom_codec_encode` -- and the oracle side is ffmpeg's own - /// `yuv422p12le` rawvideo decode of the same bytes, so the pin and the - /// oracle come from the same library, which is the property that makes - /// byte-exactness a claim about OUR decoder rather than about a - /// disagreement between two encoders. - /// - /// `s422_superres_160x128.obu` -- 5304 bytes, sha256 - /// `5852ff2c273cb773c4886762c6a6f2cce6e12065a690eb3a5ca2119c0b6f2957`, - /// fnv1a64 `0x0789d1b2851b94ae`. 160x128, 8-bit, 3 frames, `--superres- - /// mode=1` (fixed) over a `C422` testsrc2 source, encoded by the - /// aomenc recipe above plus `--superres-mode=1`. Superres is the one - /// 4:2:2 path whose output crop is `(round_ss(w,1) x round_ss(h,0))` at - /// the UPSCALED size, and it had no 4:2:2 cell anywhere. - #[test] - fn a_real_422_12bit_and_superres_stream_decode_pixel_exact() { - const NAME: &str = "a_real_422_12bit_and_superres_stream_decode_pixel_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - let hbd = crate_pin("s422_12bit_160x128.obu"); - let hbd_stream = read_pin(&hbd, 9214, 0xa62b8e3fe6f60ae5, NAME); - assert_422_stream_pixel_exact(NAME, &hbd_stream, 160, 128, 3, 12, true); - - let sr = crate_pin("s422_superres_160x128.obu"); - let sr_stream = read_pin(&sr, 5304, 0x0789d1b2851b94ae, NAME); - assert_422_stream_pixel_exact(NAME, &sr_stream, 160, 128, 3, 8, true); - } - - /// lane-av1lr422: a libaom-recipe 10-bit 4:2:2 stream with loop - /// restoration ON, `s422_lr_10bit_200x120.obu` (129409 bytes, sha256 - /// `5d6bc195934709390191c9ea8af167d385552c5b1330e8abd38f76a4416ba751`, - /// fnv1a64 `0xc5d5489355fdc2df`), 200x120, 8 frames. It was REFUSED by - /// the sub-8x8 plane-block check before the fix: the refusal was a - /// parse desync, not a wrong check. The 32x8 / 8x32 rect4 general arm - /// gathered the chroma dc-sign votes per mi instead of per 4-px chroma - /// column, which desynced the coefficient contexts. Decodes byte-exact - /// against ffmpeg libdav1d rawvideo. - #[test] - fn a_422_10bit_lr_stream_decodes_pixel_exact() { - const NAME: &str = "a_422_10bit_lr_stream_decodes_pixel_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - let p = crate_pin("s422_lr_10bit_200x120.obu"); - let stream = read_pin(&p, 129409, 0xc5d5489355fdc2df, NAME); - assert_422_stream_pixel_exact(NAME, &stream, 200, 120, 8, 10, true); - } - - /// lane-av1odd440, CELL 1 of 2: `4:2:0 with an ODD luma dimension`, the - /// cell `lanes/av1formatsweep.report.md` left as declared debt because - /// "aomenc rounds a 4:2:0 frame's coded size DOWN to even, so no stream - /// this recipe can produce codes an odd luma dimension". - /// - /// The pin, `420_odd65x65_key.obu` (2305 bytes, - /// sha256 `66986019a561f81130f407f426c4379b25e6e80c2cd9ce47d517b3216e9a03cf`), - /// is that missing stream, built offline by - /// `examples/gen_coverage_cells.rs`: a 96x96 card padded to the block - /// grid, coded by `encode::encode_key_frame_at_size` with a 65x65 frame - /// header. Provenance: that example, `cargo run -p ec-av1 --example - /// gen_coverage_cells -- crates/ec-av1/fixtures`; no encoder, no ffmpeg, - /// no lavfi. - /// - /// WHY THE CELL IS NOT A RUBBER STAMP -- the chroma extent is where a - /// floor shows. A 65-wide 4:2:0 frame has - /// `ROUND_POWER_OF_TWO(65, 1) = 33` chroma columns (libaom - /// `av1_common_plane_width`, `av1/common/av1_common_int.h`), not 32, so - /// the decoded frame's own plane sizes, the rawvideo sample count and - /// the oracle compare all move if `decode::round_ss` is floored. The - /// mutation was run: flooring `round_ss` (`decode.rs:697`) turns the - /// `round_ss` assert below red at 32 chroma columns and the oracle arm - /// red at a 6273-byte raw against the oracle's 6403. The gate is - /// therefore not green on a floored decoder, which is the whole content - /// of this cell. - /// - /// The stream decodes PIXEL-EXACT against the instrumented `aomdec` - /// (6403 raw bytes = 65*65 + 2*33*33, byte-identical), so the cell is a - /// `y` and not a `–`. - #[test] - fn an_odd_luma_420_key_frame_decodes_pixel_exact() { - const NAME: &str = "an_odd_luma_420_key_frame_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("fixtures") - .join("420_odd65x65_key.obu"); - let stream = read_pin(&path, 2305, 0xf55645c4b139e8f7, NAME); - - // The stream's OWN header, read from its own bytes: an odd luma size - // at 4:2:0, which is the cell. (Taken from the pin, not from the - // gate's name -- class `helper-packs-u16-for-an-8-bit-stream`.) - let mut probe = Av1Parser::new(); - let mut pos = 0usize; - while pos < stream.len() && probe.sequence_header().is_none() { - let obu = probe - .parse_obu(&stream[pos..]) - .unwrap_or_else(|e| panic!("{NAME}: OBU at byte {pos} does not parse: {e:?}")); - pos += obu.total_size; - } - let seq = probe - .sequence_header() - .unwrap_or_else(|| panic!("{NAME}: the pin carries no sequence header")); - assert_eq!( - (seq.max_frame_width, seq.max_frame_height), - (65, 65), - "{NAME}: the pin must declare an ODD luma size, it declares {}x{}", - seq.max_frame_width, - seq.max_frame_height - ); - assert_eq!( - ( - seq.color_config.subsampling_x, - seq.color_config.subsampling_y - ), - (1, 1), - "{NAME}: this cell is an odd luma SIZE at 4:2:0, not another chroma shape" - ); - - // The decoded frame's own extents. This arm needs no oracle, and it - // is the one a floored `round_ss` turns red. - let frames = decode_stream(&stream).expect("the odd-luma 4:2:0 pin must decode"); - assert_eq!(frames.len(), 1, "{NAME}: frame count"); - let frame = &frames[0]; - assert_eq!( - (frame.width, frame.height), - (65, 65), - "{NAME}: decoded luma extent" - ); - assert_eq!(frame.y.len(), 65 * 65, "{NAME}: decoded luma sample count"); - assert_eq!( - (frame.u.len(), frame.v.len()), - (33 * 33, 33 * 33), - "{NAME}: a 65x65 4:2:0 frame has ROUND_POWER_OF_TWO(65,1) = 33 chroma \ - columns and rows -- 32 means the extent was floored" - ); - - if !aomdec_available(NAME) { - return; - } - assert_rawvideo_matches(&path, &stream, NAME, 1, 8); - } - - /// lane-av1odd440, CELL 2 of 2: the `4:4:0 (ss 0,1)` row, which the same - /// report called "unmeasured and unproducible by recipe". It is neither - /// unmeasured nor unproducible: it is NOT A CELL AT ALL. - /// - /// `subsampling_y` is coded only when `subsampling_x` is 1 (spec 5.5.2 - /// `color_config`), so a sequence header can carry exactly three chroma - /// shapes -- 4:2:0 `(1,1)`, 4:2:2 `(1,0)`, 4:4:4 `(0,0)` -- and never - /// `(0,1)`. libaom says so in both directions: the reader leaves - /// `subsampling_y = 0` when `subsampling_x` is 0 - /// (`av1_read_color_config`, `av1/decoder/decodeframe.c:4171-4175`) and - /// the writer ASSERTS it -- `assert(seq_params->subsampling_y == 0 && - /// "4:4:0 subsampling not allowed in AV1")`, `av1/encoder/bitstream.c: - /// 2463-2465`. So there is no stream to decode, no fixture to pin that - /// a decoder could be handed, and no oracle to compare against: a - /// 4:4:0 row in a coverage matrix is a matrix bug, not a decoder gap. - /// - /// What is pinned, then, is the claim itself, in three arms that a - /// mutation turns red: - /// - /// 1. WRITER: every `(profile, bit_depth, mono, colour description, - /// requested subsampling)` combination a `color_config` can carry is - /// written by this crate's own writer and read back by this crate's - /// own reader. The reachable set is asserted to be EXACTLY - /// `{(1,1), (1,0), (0,0)}` -- each legal shape present, `(0,1)` - /// absent -- and, on the BYTES rather than on the round trip, the two - /// requests that differ only in `subsampling_y` must write identical - /// headers whenever `subsampling_x` is 0. A sweep that silently wrote - /// nothing would pass, so the count of combinations actually written - /// and read is asserted too. - /// 2. READER: the one byte that carries `subsampling_x` is found by - /// diffing an `(0,0)` header against an `(1,0)` one, and then all 256 - /// values of that byte are fed back through the reader. Not one of the - /// headers that parse reads back `(0,1)`, because the reader never - /// reads a `subsampling_y` bit in that position. A reader that always - /// read a second bit would produce `(0,1)` at the one value that sets - /// both bits. - /// 3. THE PIN: `440_request_is_422.obu` (2014 bytes, sha256 - /// `4afaa5470c4e010d9d970086ef514680adfe801a579e4deeec582f52d13c5e7c`, - /// fnv1a64 `0x98a1378df976253d`) is what this crate's writer produces - /// when it is handed `subsampling (0,1)` at profile 2 -- profile 2 - /// below 12 bits is 4:2:2 and codes no subsampling bit at all, so the - /// request lands on `(1,0)`. The pin is asserted to read back `(1,0)`, - /// NOT `(0,1)`. Its frame OBU is a 4:2:0 key frame's, so the pin is a - /// HEADER witness, not a decodable 4:2:2 stream -- nothing here claims - /// pixels for it. Provenance: `examples/gen_coverage_cells.rs`, `cargo - /// run -p ec-av1 --example gen_coverage_cells -- crates/ec-av1/fixtures`. - /// - /// lane-av1422lift: this arm used to end "and the decoder is asserted - /// to refuse it by name, which is the honest outcome for the shape a - /// 4:4:0 request actually yields". That was honest only because the - /// decoder refused EVERY (1,0) header -- the assertion was about the - /// guard, not about these bytes. With 4:2:2 admitted, refusing these - /// bytes would be wrong and accepting them without comment would be - /// worse, so the arm now asserts the one thing that IS true of them: - /// the SEQUENCE HEADER, not the tile, fixes the decode's chroma - /// geometry. The pixel claim moved to genuinely 4:2:2 pins. - #[test] - fn the_440_cell_is_not_a_codable_chroma_shape() { - const NAME: &str = "the_440_cell_is_not_a_codable_chroma_shape"; - let _gate_lock = lock_gate_counters(); - let header_obu = |profile: u8, color: ec_av1_syntax::ColorConfig| -> Vec { - let (mut seq, _header) = crate::encode::key_frame_headers_colour(64, 64, 100, color) - .expect("the header builders accept a colour config"); - seq.seq_profile = profile; - crate::sequence::sequence_header_obu(&seq).expect("writing the sequence header") - }; - let shape_of = |obu: &[u8]| -> Option<(u8, u8)> { - let mut parser = Av1Parser::new(); - let parsed = parser.parse_obu(obu).ok()?; - if !matches!(parsed.kind, ec_av1_syntax::ObuKind::SequenceHeader(_)) { - return None; - } - let seq = parser.sequence_header()?; - Some(( - seq.color_config.subsampling_x, - seq.color_config.subsampling_y, - )) - }; - - // ---- arm 1: the writer's whole reachable space -------------------- - let mut reachable: std::collections::BTreeSet<(u8, u8)> = Default::default(); - let mut asked = 0usize; - for profile in [0u8, 1, 2] { - for bit_depth in [8u8, 10, 12] { - for mono_chrome in [false, true] { - // Profile 1 is 4:4:4 and codes no mono bit; asking for - // monochrome there is refused by the writer, which is - // not a chroma shape and not this gate's subject. - if mono_chrome && profile == 1 { - continue; - } - for (label, (cp, tc, mc)) in [ - ("unspecified", (2u8, 2u8, 2u8)), - ("bt709", (1u8, 1u8, 1u8)), - ("srgb", (1u8, 13u8, 0u8)), - ] { - for sx in [0u8, 1] { - for sy in [0u8, 1] { - let color = ec_av1_syntax::ColorConfig { - bit_depth, - mono_chrome, - num_planes: if mono_chrome { 1 } else { 3 }, - color_primaries: cp, - transfer_characteristics: tc, - matrix_coefficients: mc, - color_range: false, - subsampling_x: sx, - subsampling_y: sy, - chroma_sample_position: - ec_av1_syntax::ChromaSamplePosition::Unknown, - separate_uv_delta_q: false, - }; - asked += 1; - let obu = header_obu(profile, color); - // The WRITER half of the claim, measured on the - // bytes rather than on a round trip: with - // `subsampling_x == 0` the spec codes no - // `subsampling_y` bit at all, so the two - // requests that differ ONLY in `subsampling_y` - // must produce byte-identical headers. A - // writer that emitted the bit anyway (the - // mutation libaom's own `assert` exists to - // catch, av1/encoder/bitstream.c:2467-2468) fails - // here -- and note it does NOT fail the - // round trip, because the reader then absorbs - // the extra bit as `separate_uv_delta_q`. - if sx == 0 { - let mut other = color; - other.subsampling_y = 1; - assert_eq!( - obu, - header_obu(profile, other), - "{NAME}: a (0,0) and a (0,1) request wrote DIFFERENT \ - bytes at profile {profile}, {bit_depth}-bit, mono \ - {mono_chrome}, {label} -- `subsampling_y` must not be \ - coded at all when `subsampling_x` is 0" - ); - } - if let Some(got) = shape_of(&obu) { - assert_ne!( - got, - (0, 1), - "{NAME}: a 4:4:0 shape came back out of the writer at \ - profile {profile}, {bit_depth}-bit, mono {mono_chrome}, \ - {label}, asked for ({sx},{sy}) -- libaom forbids this \ - shape outright (av1/encoder/bitstream.c:2467-2468)" - ); - reachable.insert(got); - } - } - } - } - } - } - } - assert!( - asked >= 100 && reachable.len() == 3, - "{NAME}: the sweep asked {asked} combinations and reached {} shapes -- it must reach \ - all three legal ones, or it is not measuring the space", - reachable.len() - ); - assert_eq!( - reachable, - std::collections::BTreeSet::from([(0u8, 0u8), (1u8, 0u8), (1u8, 1u8)]), - "{NAME}: the chroma shapes a `color_config` can code are exactly 4:4:4 (0,0), 4:2:2 \ - (1,0) and 4:2:0 (1,1)" - ); - - // ---- arm 2: the reader's bit at that position ---------------------- - // Profile 2 at 12 bits is the only place BOTH subsampling bits are - // coded, so it is where a hand-built header could try to smuggle a - // `subsampling_y`. Find the byte that carries `subsampling_x` by - // diffing the two shapes, then read back all eight of its values. - let at_444 = |sx: u8| { - let color = ec_av1_syntax::ColorConfig { - bit_depth: 12, - subsampling_x: sx, - subsampling_y: 0, - chroma_sample_position: ec_av1_syntax::ChromaSamplePosition::Unknown, - ..ec_av1_syntax::ColorConfig::default() - }; - let (mut seq, _h) = - crate::encode::key_frame_headers_colour(64, 64, 100, color).unwrap(); - seq.seq_profile = 2; - let obu = crate::sequence::sequence_header_obu(&seq).unwrap(); - let mut parser = Av1Parser::new(); - parser.parse_obu(&obu).expect("the profile-2 header parses"); - let seq = parser.sequence_header().expect("sequence header"); - ( - seq.color_config.subsampling_x, - seq.color_config.subsampling_y, - ) - }; - assert_eq!(at_444(0), (0, 0), "{NAME}: the sx=0 header is 4:4:4"); - assert_eq!(at_444(1), (1, 0), "{NAME}: the sx=1 header is 4:2:2"); - let base = { - let color = ec_av1_syntax::ColorConfig { - bit_depth: 12, - subsampling_x: 0, - subsampling_y: 0, - chroma_sample_position: ec_av1_syntax::ChromaSamplePosition::Unknown, - ..ec_av1_syntax::ColorConfig::default() - }; - let (mut seq, _h) = - crate::encode::key_frame_headers_colour(64, 64, 100, color).unwrap(); - seq.seq_profile = 2; - crate::sequence::sequence_header_obu(&seq).unwrap() - }; - let other = { - let color = ec_av1_syntax::ColorConfig { - bit_depth: 12, - subsampling_x: 1, - subsampling_y: 0, - chroma_sample_position: ec_av1_syntax::ChromaSamplePosition::Unknown, - ..ec_av1_syntax::ColorConfig::default() - }; - let (mut seq, _h) = - crate::encode::key_frame_headers_colour(64, 64, 100, color).unwrap(); - seq.seq_profile = 2; - crate::sequence::sequence_header_obu(&seq).unwrap() - }; - assert_eq!( - base.len(), - other.len(), - "{NAME}: the two headers must differ in place" - ); - let byte_at = base - .iter() - .zip(&other) - .position(|(a, b)| a != b) - .expect("the two shapes must differ somewhere"); - // Every value of that byte is fed back through the reader -- it is the - // LAST payload byte, so the bits a smuggled `subsampling_y` would come - // from are in it too (spec 5.5.2 always codes `separate_uv_delta_q` - // after the subsampling pair, and the payload is padded out to the - // byte with `trailing_bits`). A header that stops parsing is not a - // 4:4:0 shape and cannot be counted as one; the sweep asserts how - // many DID parse, so a sweep that quietly parsed nothing is not - // evidence of anything. - let mut parsed_headers = 0usize; - for value in 0..256u16 { - let mut poked = base.clone(); - poked[byte_at] = value as u8; - let mut parser = Av1Parser::new(); - let Ok(parsed) = parser.parse_obu(&poked) else { - continue; - }; - if !matches!(parsed.kind, ec_av1_syntax::ObuKind::SequenceHeader(_)) { - continue; - } - let seq = parser.sequence_header().expect("sequence header"); - parsed_headers += 1; - assert_ne!( - ( - seq.color_config.subsampling_x, - seq.color_config.subsampling_y - ), - (0, 1), - "{NAME}: payload byte {byte_at} = {value:#04x} read back as 4:4:0 -- the reader \ - took a `subsampling_y` bit that spec 5.5.2 does not code when `subsampling_x` \ - is 0" - ); - } - assert!( - parsed_headers > 100, - "{NAME}: only {parsed_headers} of the 256 poked headers parsed -- the sweep is not \ - measuring the reader" - ); - - // ---- arm 3: the pinned bytes a 4:4:0 request produces -------------- - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("fixtures") - .join("440_request_is_422.obu"); - let pinned = read_pin(&path, 2014, 0x98a1378df976253d, NAME); - let mut parser = Av1Parser::new(); - let obu = parser - .parse_obu(&pinned) - .unwrap_or_else(|e| panic!("{NAME}: the pin's first OBU does not parse: {e:?}")); - assert!( - matches!(obu.kind, ec_av1_syntax::ObuKind::SequenceHeader(_)), - "{NAME}: the pin must start with its sequence header" - ); - let seq = parser.sequence_header().expect("the pin's sequence header"); - assert_eq!( - ( - seq.color_config.subsampling_x, - seq.color_config.subsampling_y - ), - (1, 0), - "{NAME}: the pin is what a 4:4:0 request at profile 2 produces -- 4:2:2 (1,0). If this \ - ever reads (0,1), a 4:4:0 cell became codable and this whole gate is wrong about the \ - format." - ); - // lane-av1unwritten: lane-av1422lift replaced the old 4:2:2 header - // refusal with "it decodes, and the decoded chroma planes are 32x64". - // That was the wrong contract for THIS pin: its frame OBU is a 4:2:0 - // key frame's, so at 4:2:2 its partition symbols name subsizes with no - // chroma plane block, which libaom rejects as a corrupt frame - // ("Block size 8x16 invalid with this subsampling mode", - // decodeframe.c:1456) and `aomdec` does. The replacement is the - // REFUSAL, by that rule. - // - // The pin's remaining job is unchanged and still worth saying: it - // proves a 4:4:0 REQUEST at profile 2 lands on 4:2:2 (1,0), i.e. that - // `the_440_cell_is_not_a_codable_chroma_shape`'s claim is still true. - let err = decode_stream(&pinned).err().unwrap_or_else(|| { - panic!( - "{NAME}: the pin is a 4:2:2 header over a 4:2:0 tile -- libaom refuses it \ - (aomdec: \"Block size 8x16 invalid with this subsampling mode\"), and so \ - must we" - ) - }); - assert!( - err.to_string() - .contains("invalid with this subsampling mode"), - "{NAME}: the refusal must name libaom's rule, got: {err}" - ); - // The pixels this pin never had: the sibling gate - // `a_422_header_over_a_420_tile_refuses_the_subsize_libaom_calls_corrupt` - // pins the refusal plus a genuine 4:2:2 positive control, and every - // real 4:2:2 exactness claim lives on genuinely 4:2:2 pins in this - // file. - } - - /// lane-av1unwritten: this pin is a MISSING REFUSAL, not a pixel defect. - /// - /// `440_request_is_422.obu` is a 4:2:2 sequence header wrapped around a - /// 4:2:0 key frame's tile, so the tile's partition symbols make subsizes - /// (8x16 among them) that have NO chroma plane block at ss (1,0). libaom - /// refuses exactly that, before descending into the subsize: - /// - /// ```text - /// $ aomdec --rawvideo -o /dev/null fixtures/440_request_is_422.obu - /// Warning: Failed to decode frame 1: Corrupt frame detected - /// Warning: Additional information: Block size 8x16 invalid with this subsampling mode - /// ``` - /// - /// (`av1/decoder/decodeframe.c:1449-1458`, - /// `get_plane_block_size(subsize, ss_x, ss_y) == BLOCK_INVALID` -> - /// `AOM_CODEC_CORRUPT_FRAME`.) We walked those subsizes instead, and the - /// first version of this lane misread the downstream symptom -- a chroma - /// plane block covered by a square unit, whole 4x4 blocks left unwritten, - /// and a `EC_AV1_FINAL_DUMP` hash that CHANGED RUN TO RUN because the - /// unwritten samples were uninitialised plane memory. - /// - /// The contract pinned here is the one libaom has: the pin REFUSES, by a - /// named error that says which shape and which subsampling mode. The - /// positive control is a genuinely 4:2:2 pin, which must still decode -- - /// so this gate cannot pass by refusing everything. - #[test] - fn a_422_header_over_a_420_tile_refuses_the_subsize_libaom_calls_corrupt() { - const NAME: &str = "a_422_header_over_a_420_tile_refuses_the_subsize_libaom_calls_corrupt"; - let _gate_lock = lock_gate_counters(); - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("fixtures") - .join("440_request_is_422.obu"); - let pinned = read_pin(&path, 2014, 0x98a1378df976253d, NAME); - // The refusal this gate PROVES, quoted whole -- the anchor the PROVEN - // row in `refusal_inventory.rs` is checked against inside this body's - // own bounds. The assertion below used to match only the libaom - // citation *inside* the string, so a reworded guard kept passing for - // as long as it kept citing `decodeframe.c:1456`: the half that names - // OUR shapes (4x8 / 8x16 / 16x4, and 8x4 at 4:4:0) was never pinned. - const REFUSAL: &str = "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)"; - let err = decode_stream(&pinned) - .err() - .unwrap_or_else(|| panic!("{NAME}: the pin must be REFUSED, not decoded")); - let msg = err.to_string(); - assert!( - msg.contains("invalid with this subsampling mode"), - "{NAME}: the refusal must name the rule it refuses by (libaom's own wording), got: \ - {msg}" - ); - assert!( - msg.contains(REFUSAL), - "{NAME}: the refusal must be this decoder's OWN string, whole -- the guard's wording \ - drifted, so the PROVEN row no longer names what fires, got: {msg}" - ); - // Positive control: a real 4:2:2 stream must still decode, so the gate - // cannot pass by refusing everything. - let ok_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("fixtures") - .join("422_key_64x64.obu"); - let ok = decode_stream(&std::fs::read(&ok_path).expect("the 4:2:2 control fixture")) - .unwrap_or_else(|e| panic!("{NAME}: a genuine 4:2:2 pin must still decode: {e}")); - assert!( - !ok.is_empty(), - "{NAME}: the 4:2:2 control decoded no frames" - ); - } - - /// lane-av1subsizesweep: the FRAME-EDGE walk of a BLOCK_INVALID subsize, - /// pinned. This is the one install site the partition-symbol guards missed, - /// and the sibling pin above cannot see it -- that pin's 8x16 comes from a - /// 16x16-level `PARTITION_VERT_B` (an interior AB strip, refused at - /// decode.rs:36472), while this pin's comes from the key-frame 16-level - /// FRAME-EDGE arm, which is not a `dec.symbol(` site at all: it reads one - /// gathered bit with `dec.symbol_fixed(&gather(..))` and dispatches - /// `decode_leaf_rect` straight off it. - /// - /// `422_header_edge16_walk.obu` (128 bytes, sha256 - /// `e8ab2bb229896f796cdec4d2cb383b41f057ef8d364da30f160a3f55a452657f`, - /// fnv1a64 `0xcfa2394ebe1f7764`) is a 4:2:2 sequence header over a 4:2:0 - /// key frame's tile, at 88x64. Width 88 is 8 mod 16, so the last 16x16 - /// column block is COLUMN-short and the frame-edge arm fires; height 64 is - /// 16-aligned, so the ROW is not short and the both-cut arm is not taken. - /// The gathered bit names `PARTITION_VERT`, so the strip is `BLOCK_8X16`. - /// - /// libaom's own verdict, which is the rule this pin pins: - /// - /// ```text - /// $ aomdec --rawvideo -o /dev/null fixtures/422_header_edge16_walk.obu - /// Warning: Failed to decode frame 1: Corrupt frame detected - /// Warning: Additional information: Block size 8x16 invalid with this subsampling mode - /// ``` - /// - /// What makes this pin different from every other refusal gate in this file - /// is that the 8x16 is the ONLY offending subsize in the stream. Measured - /// over a 260-candidate sweep (4 card textures x 5 quantizers x 13 declared - /// widths), this is the one candidate whose decode with the guard removed - /// SUCCEEDS: with the `refuse_invalid_subsize` at decode.rs:37098 deleted, - /// this decoder returned a full 88x64 picture where libaom refuses the - /// frame. So the guard is not a redundant second refusal here -- it is the - /// only thing between a corrupt frame and a plausible-looking decode. - #[test] - fn a_422_header_whose_only_invalid_subsize_is_the_16_level_frame_edge_walk_is_refused() { - const NAME: &str = - "a_422_header_whose_only_invalid_subsize_is_the_16_level_frame_edge_walk_is_refused"; - let _gate_lock = lock_gate_counters(); - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("fixtures") - .join("422_header_edge16_walk.obu"); - let pinned = read_pin(&path, 128, 0xcfa2394ebe1f7764, NAME); - // The shape must be the one this lane's arm carries: if the pin ever - // stops being an 8x16 strip the refusal is coming from somewhere else - // and this gate is measuring the wrong thing. - assert!( - !crate::decode::chroma_plane_block_codable(8, 16, 1, 0), - "{NAME}: BLOCK_8X16 must be BLOCK_INVALID at 4:2:2 -- this gate's whole \ - subject is `av1_ss_size_lookup[BLOCK_8X16][1][0] == BLOCK_INVALID`" - ); - assert!( - crate::decode::chroma_plane_block_codable(16, 8, 1, 0), - "{NAME}: the 16x8 mirror MUST stay legal at 4:2:2 (BLOCK_8X8) -- it is what \ - keeps the new guard from refusing the sibling arm's strip" - ); - let err = decode_stream(&pinned) - .err() - .unwrap_or_else(|| panic!("{NAME}: the pin must be REFUSED, not decoded")); - let msg = err.to_string(); - assert!( - msg.contains("invalid with this subsampling mode"), - "{NAME}: the refusal must name libaom's rule (its own wording), got: {msg}" - ); - // Positive control: a genuine 4:2:2 stream must still decode, so this - // gate cannot pass by refusing everything. - let ok_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("fixtures") - .join("422_key_64x64.obu"); - let ok = decode_stream(&std::fs::read(&ok_path).expect("the 4:2:2 control fixture")) - .unwrap_or_else(|e| panic!("{NAME}: a genuine 4:2:2 pin must still decode: {e}")); - assert!( - !ok.is_empty(), - "{NAME}: the 4:2:2 control decoded no frames" - ); - } - - /// lane-av1-422bigblock: the two witnessed 4:2:2 big-block defects, pinned - /// as fixtures (`git add -f`; `fixtures/` is gitignored). - /// - /// `422_allskip_2f.obu` (62 bytes) is a 128x128 profile-2 key frame plus - /// its all-skip first inter frame: the pre-port decoder read phantom - /// coefficient units in the inter frame and then panicked in - /// `reconstruct_mc_rect` on a full-height 4:2:2 chroma rect. At this - /// lane's HEAD the block-half port's per-axis plane-block model already - /// has it entropy-locked (all 20 key-frame coefficient units pair - /// rng-for-rng with the instrumented oracle, the inter frame reads - /// zero, matching the oracle) and pixel-exact vs aomdec. - /// - /// `422_sb128_3f.obu` (12543 bytes) carries the f2 128x128 - /// `PARTITION_NONE` non-skip inter block: the mu-chunk chroma walk cut - /// each chunk's 32x64 chroma into a `chroma_side`-square 64x64 (twice - /// the units the oracle codes), indexed the prediction buffer at the - /// square `chroma_side` instead of `chroma_stride` (the empty-slice - /// panic at `push_mc_rect_tx`'s densify), and the reference plane - /// resolution guessed every non-4:4:4 picture quarter-height, so the - /// bottom mu-chunk row predicted from a clamped row-63 edge. All fixed; - /// both witnesses decode pixel-exact vs aomdec on the lane's local - /// `EC_AV1_ALLOW_422_PROBE` patch-run-restore build (recipe and measured - /// numbers in `lanes/av1422bigblock.report.md`). - /// - /// lane-av1422lift: `decode_stream` no longer refuses 4:2:2 at the - /// sequence header, so this gate stops being a refusal contract and - /// becomes the one it should have been: BOTH pins, byte-pinned AND - /// byte-exact against ffmpeg, with the per-plane coefficient-unit census - /// as the non-vacuity arm. The pins are unchanged and still load-bearing - /// (size + fnv1a64); only the assertion moved. - #[test] - fn the_pinned_422_bigblock_witnesses_decode_pixel_exact() { - const NAME: &str = "the_pinned_422_bigblock_witnesses_decode_pixel_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - for (file, bytes, fp, frames, require_coded) in [ - ( - "422_allskip_2f.obu", - 62usize, - 0x7e4d69d3c728c55f_u64, - 2usize, - false, - ), - ("422_sb128_3f.obu", 12543, 0x5171e0aab8000da7, 3, true), - ] { - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("fixtures") - .join(file); - let data = std::fs::read(&path).unwrap_or_else(|e| { - panic!( - "{NAME}: pinned witness {} is missing ({e}) -- the gate cannot run", - path.display() - ) - }); - assert_eq!(data.len(), bytes, "{NAME}: {file} size drifted"); - assert_eq!(fnv1a64(&data), fp, "{NAME}: {file} bytes drifted"); - let (_units, coded_delta) = - assert_422_stream_pixel_exact(NAME, &data, 128, 128, frames, 8, require_coded); - if !require_coded { - // `422_allskip_2f.obu` is named for what it does NOT code, and - // the pre-port defect was exactly that: the decoder read - // PHANTOM coefficient units in the all-skip inter frame and - // then panicked in `reconstruct_mc_rect` on a full-height - // 4:2:2 chroma rect. So the cell's non-vacuity is a NEGATIVE - // measurement on the CHROMA planes, asserted here rather than - // inherited: the walk ran (units > 0, which the shared body - // checks) and coded nothing on U or V. - assert_eq!( - (coded_delta[1], coded_delta[2]), - (0, 0), - "{NAME}: {file} CODED a chroma coefficient -- this is the all-skip inter-frame \ - cell and a phantom residual read is exactly the defect it witnesses" - ); - } - } - } - - /// lane-av1muchroma: the `chroma_side * chroma_side` mu-chroma site - /// census, over the whole committed 4:2:2 corpus, as a per-site - /// REACHABILITY measurement with a non-vacuity arm. - /// - /// `lanes/av1subsizesweep.report.md` named "mu-chroma sites using - /// `chroma_side * chroma_side`" as unprobed residue. This lane's sweep - /// (env-gated probe at each of the 12 sites, run over every pinned 4:2:2 - /// gate) measured them: - /// - /// - sites 4, 7, 10 are guarded `ss_x == 0 && ss_y == 0`, i.e. 4:4:4 - /// ONLY -- structurally unreachable at 4:2:2, not merely unwitnessed. - /// - sites 2, 8 (`side > 64` mu-chunk walks) were not reached by any - /// committed 4:2:2 fixture; their single-reference twin, site 5, is - /// (side 128, plane 64x128), and its square allocation is the ENCLOSING - /// square, so it is 2x oversized, never short. - /// - sites 1, 3, 5, 6, 9, 11, 12 ARE reached. For 3/5/6/9/11/12 - /// `chroma_side` is `max(side >> ss_x, side >> ss_y)` (decode.rs), the - /// ENCLOSING square of the plane rect, so at 4:2:2 the square is 2x - /// the per-axis extent: oversized, never short. - /// - site 1 alone still used `side >> ss_x` and was therefore sized at - /// HALF the plane block at 4:2:2. Fixed per-axis; this gate pins it. - /// - /// Non-vacuity: [`crate::decode::skip_arm_chroma_plane_block_hits`] - /// fires only where the per-axis and square forms differ, so a green run - /// that never reached the site would be vacuous and this asserts > 0. - #[test] - fn the_422_skip_arm_chroma_grid_is_sized_per_axis_not_square() { - const NAME: &str = "the_422_skip_arm_chroma_grid_is_sized_per_axis_not_square"; - const FILE: &str = "s422_322x240.obu"; - const BYTES: usize = 21096; - const FP: u64 = 0x9a96dda2a19d47a6; - const W: usize = 322; - const H: usize = 240; - const FRAMES: usize = 16; - let _gate_lock = lock_gate_counters(); - let data = std::fs::read(crate_pin(FILE)).unwrap_or_else(|e| { - panic!("{NAME}: the committed pin {FILE} is missing ({e}) -- a failure, not a skip") - }); - assert_eq!(data.len(), BYTES, "{NAME}: {FILE} size drifted"); - assert_eq!(fnv1a64(&data), FP, "{NAME}: {FILE} bytes drifted"); - let rect_before = crate::decode::skip_arm_chroma_rect_shapes(); - let short_before = crate::decode::skip_arm_chroma_short_samples(); - let ours = decode_stream(&data) - .unwrap_or_else(|e| panic!("{NAME}: decode_stream refused a real 4:2:2 stream: {e}")); - assert_eq!(ours.len(), FRAMES, "{NAME}: decoded frame count"); - for (i, f) in ours.iter().enumerate() { - assert_eq!((f.width, f.height), (W, H), "{NAME}: frame {i} dimensions"); - assert_eq!( - (f.u.len(), f.v.len()), - (W.div_ceil(2) * H, W.div_ceil(2) * H), - "{NAME}: frame {i} chroma planes are {}/{} samples -- 4:2:2 is HALF WIDTH and \ - FULL HEIGHT; a quarter-height plane means the decode kept a 4:2:0 allocation", - f.u.len(), - f.v.len() - ); - } - let rect_after = crate::decode::skip_arm_chroma_rect_shapes(); - assert!( - rect_after > rect_before, - "{NAME}: no skipped block decoded at a rect chroma shape ({rect_before} -> \ - {rect_after}) -- this gate is then VACUOUS: per-axis and square sizing are the \ - same number at 4:2:0 and 4:4:4, so it proves nothing about the site it claims" - ); - let short_after = crate::decode::skip_arm_chroma_short_samples(); - assert_eq!( - short_after, short_before, - "{NAME}: decode_block's SKIP arm chroma grids fell {short_after} samples SHORT of \ - their own plane block -- the square `side >> ss_x` form this lane removed allocates \ - exactly half the plane block at 4:2:2 (ss (1,0))" - ); - } - - /// lane-av1floorshift: the two FRAME chroma plane allocators - /// (`decode_key_frame_tile_with_cdfs`, `decode_inter_tile`) size U and V as - /// `(width >> ss_x) x (height >> ss_y)`. `lanes/av1subsizesweep.report.md` - /// named them "floor-`>>` chroma plane allocators -- shape assumption at - /// frame edges; not probed" and left them open. This is the probe. - /// - /// **The verdict is ALREADY CORRECT, and it is structural, not - /// corpus-luck.** `width`/`height` are `block_grid(mi_cols, mi_rows) * - /// BLOCK` (`BLOCK == 32`) and the allocator is handed those, not the frame's - /// own `true_width`/`true_height`: both axes are multiples of 32, and - /// `ss_x`/`ss_y` are the sequence header's single-bit subsampling fields, - /// so `ss <= 1` on every stream that exists. `32k >> ss == round_ss(32k, ss)` - /// for every `k` and every `ss <= 1` -- the `>>` can never floor one sample - /// short of libaom's own chroma crop, at a frame edge or anywhere else. The - /// static half of the gate below proves that exhaustively over every - /// `mi_cols`/`mi_rows` this decoder admits. - /// - /// The corpus half keeps the instrument honest: it decodes one frame per - /// selectable subsampling cell and asserts the allocators were REACHED - /// (`frame_chroma_alloc_calls` moved), so a green run cannot be the census - /// having been wired to nothing. - /// - /// Witnesses, all byte-pinned (`size`, `fnv1a64`), chosen to cover all - /// three selectable cells and both allocators: - /// - /// | file | cell | frame | covers | - /// |---|---|---|---| - /// | `420_odd65x65_key.obu` | 4:2:0, **odd** 65x65 | key | key allocator, the odd-dimension cell where a floor WOULD show | - /// | `422_key_64x64.obu` | 4:2:2 (1,0) | key | key allocator, half-width/full-height | - /// | `444_intrabc_rect4_witness.obu` | 4:4:4 (0,0) | key | key allocator, the `ss == 0` cell where `>> ss` is the identity | - /// - /// 4:4:0 (`0,1`) is excluded and cannot be added: libaom's - /// `av1_read_color_config` asserts `subsampling_y == 0` when - /// `subsampling_x == 0`, and no of 256 header bytes reads back `(0,1)` -- - /// the reader census at `the_reader_never_produces_440` names it. - #[test] - fn the_frame_chroma_planes_are_allocated_on_the_per_axis_floor_that_never_rounds() { - const NAME: &str = - "the_frame_chroma_planes_are_allocated_on_the_per_axis_floor_that_never_rounds"; - let _gate_lock = lock_gate_counters(); - for (file, bytes, fp, cell, ss) in [ - ( - "420_odd65x65_key.obu", - 2305usize, - 0xf55645c4b139e8f7u64, - "4:2:0", - (1usize, 1usize), - ), - ( - "422_key_64x64.obu", - 755, - 0x87fc569cf53bcbc6, - "4:2:2", - (1, 0), - ), - ( - "444_intrabc_rect4_witness.obu", - 1016, - 0x27c2fad540472994, - "4:4:4", - (0, 0), - ), - ] { - let data = std::fs::read(crate_pin(file)) - .unwrap_or_else(|e| panic!("{NAME}: the committed pin {file} is missing ({e})")); - assert_eq!(data.len(), bytes, "{NAME}: {file} size drifted"); - assert_eq!(fnv1a64(&data), fp, "{NAME}: {file} bytes drifted"); - let calls_before = crate::decode::frame_chroma_alloc_calls(); - let short_before = crate::decode::frame_chroma_alloc_short_samples(); - let crop_before = crate::decode::frame_chroma_alloc_crop_shapes(); - let frames = decode_stream(&data) - .unwrap_or_else(|e| panic!("{NAME}: {file} ({cell}) refused: {e}")); - let calls = crate::decode::frame_chroma_alloc_calls() - calls_before; - assert!( - calls >= frames.len(), - "{NAME}: {file} ({cell}) decoded {} frames but the chroma plane allocator ran \ - {calls} times -- the instrument is not on the path this gate claims to cover", - frames.len() - ); - // The shape the allocator owes the tile, and the shape the output - // crop owes the caller: libaom's chroma CROP of the frame's own - // dimensions (`av1_round_shift`), which is what - // `decode_key_frame_tile_with_cdfs`'s `Picture` crop uses. At the - // odd 65x65 4:2:0 cell this is 33x33 -- 1089 samples, NOT the - // floor 32x32 an `>>` short of the true extent would have left. - for (i, f) in frames.iter().enumerate() { - let (cw, ch) = ( - crate::decode::round_ss(f.width, ss.0), - crate::decode::round_ss(f.height, ss.1), - ); - assert_eq!( - (f.u.len(), f.v.len()), - (cw * ch, cw * ch), - "{NAME}: {file} ({cell}) frame {i} is {}x{} and its chroma planes are {} / {} \ - samples; {cell} is a {cw}x{ch} = {} crop", - f.width, - f.height, - f.u.len(), - f.v.len(), - cw * ch - ); - } - let short = crate::decode::frame_chroma_alloc_short_samples() - short_before; - assert_eq!( - short, 0, - "{NAME}: {file} ({cell}) allocated {short} chroma samples SHORT of the `round_ss` \ - extent the tile's chroma walks may address -- the frame chroma planes are sized \ - by a FLOOR `>> ss` that does not round" - ); - let crop = crate::decode::frame_chroma_alloc_crop_shapes() - crop_before; - assert_eq!( - crop, 0, - "{NAME}: {file} ({cell}) reached a frame shape on which `>> ss` and `round_ss` \ - disagree ({crop} frames) -- the allocators are handed a MULTIPLE OF 32 \ - (block_grid * BLOCK) and `ss <= 1`, so this can only mean the allocator's own \ - argument changed, and the shortfall assertion above is then vacuous on this file" - ); - } - } - - /// lane-av1floorshift: the STATIC half of the same claim, and the part that - /// does not need a corpus. The frame chroma allocators' shift argument is - /// `block_grid(mi_cols, mi_rows) * BLOCK` with `BLOCK == 32`, so for every - /// `mi_cols`/`mi_rows` this decoder can admit and every subsampling the - /// header can carry (`ss in {0, 1}` per axis), `>> ss` and `round_ss` are - /// the same number. Exhaustively checked here over a range wider than any - /// frame a header can declare; the two counters above are zero for a - /// reason, and this is the reason. - #[test] - fn the_frame_chroma_alloc_shift_argument_cannot_floor_below_round_ss() { - const NAME: &str = "the_frame_chroma_alloc_shift_argument_cannot_floor_below_round_ss"; - const BLOCK: usize = 32; - // `block_grid(mi) = mi.div_ceil(BLOCK_MI)` with `BLOCK_MI == 8` - // (`tile.rs`), so the allocator's width is `(mi.div_ceil(8)) * 32`. - for mi in 1..=512usize { - let coded = mi.div_ceil(8) * BLOCK; - for ss in 0..=1usize { - assert_eq!( - coded >> ss, - crate::decode::round_ss(coded, ss), - "{NAME}: coded {coded} (mi {mi}) at ss {ss}: the floor and the crop differ -- \ - the frame chroma plane would be allocated short" - ); - // The TRUE extent is `mi * 4`; it is what the allocator - // derives `true_width` from and what every chroma walk is - // clamped against, so it earns the same check. - let truth = mi * 4; - assert_eq!( - truth >> ss, - crate::decode::round_ss(truth, ss), - "{NAME}: true {truth} (mi {mi}) at ss {ss}: the floor and the crop differ" - ); - } - } - // And the 4:4:0 cell libaom refuses, spelled out rather than left as - // an assumption: at `ss (0,1)` the shift is exact too, so the site - // would be correct even if the cell were ever admitted. - for mi in 1..=64usize { - assert_eq!((mi * 4) >> 1, crate::decode::round_ss(mi * 4, 1)); - assert_eq!(mi * 4, crate::decode::round_ss(mi * 4, 0)); - } - } - - /// lane-av1422tailskip: the WITNESS cell for the 4:2:2 intra-in-inter - /// PALETTE chroma per-unit window, and its byte pin. - /// - /// `422_palette_intra_in_inter_384x240_17f.obu` (19344 B, sha256 - /// `bf1c658e9bfdc13ec1ed51e59049d2b81201941b6ef4571f8382f356ea4b815b`) is - /// the one 4:2:2 cell of the 384x240 census sweep: 384x240, ss (1,0), - /// 8-bit, **17 decode frames, 16 shown** (decode 1 is the hidden altref). - /// Its decode-frame-1 block at mi(32,0) is a 64x64 INTRA block with a - /// PALETTE -- `aomdec`'s `EC_PIB` prints `use_palette=1` there, and the - /// oracle's own prediction rungs print nothing for the block because - /// `av1_predict_intra_block` returns at its palette branch before them - /// (`reconintra.c:1735`). - /// - /// At 4:2:2 that block's chroma plane block is 32x64, but - /// `av1_get_max_uv_txsize` adjusts `max_tx_size_rect_lookup[BLOCK_32X64]` - /// down to TX_32X32, so it codes TWO STACKED SQUARE units per plane. - /// `decode_inter_block`'s `side == 64` walk armed the ONE block-sized - /// 2048-entry chroma palette prediction before the loop: the first unit - /// consumed all of it and the second found none pending, so it silently - /// fell back to the edge DC prediction -- a flat 90/240 box where the - /// oracle carries its palette (U/V rows 170..189, cols 23..31, 180 wrong - /// samples per plane at the pre-filter stage). Each unit now takes its own - /// `palette_window` of that buffer (`decode.rs`) -- the same helper the - /// split-transform chroma paths already used. - /// - /// **The committed assertion follows the family's standing rule** (same - /// shape as - /// [`the_pinned_422_bigblock_witnesses_are_present_and_refuse_by_name`]): - /// the byte pin plus this decoder's disposition of those bytes. - /// lane-av1422lift: `decode_stream` no longer refuses 4:2:2 at the sequence - /// header, so the OK arm is the live one -- the gate decodes the pin and - /// asserts 17 decode-order frames byte-exact against aomdec with - /// `palette_422_unit_window_hits()` fired. lane-av1oracledepth: the stale - /// `Err` arm (it matched the pre-lift refusal string - /// `"a chroma format of 4:2:2"` the decoder no longer returns, and could - /// have swallowed a future decode error as green) is deleted; a refusal - /// now fails this gate loudly. - #[test] - fn the_pinned_422_palette_intra_in_inter_cell_window_is_byte_exact() { - const NAME: &str = "the_pinned_422_palette_intra_in_inter_cell_window_is_byte_exact"; - const FILE: &str = "422_palette_intra_in_inter_384x240_17f.obu"; - const BYTES: usize = 19344; - const FP: u64 = 0x923ccabfcb933e90; - let _gate_lock = lock_gate_counters(); - let data = std::fs::read(crate_pin(FILE)).unwrap_or_else(|e| { - panic!("{NAME}: the committed pin {FILE} is missing ({e}) -- a failure, not a skip") - }); - assert_eq!(data.len(), BYTES, "{NAME}: {FILE} size drifted"); - assert_eq!(fnv1a64(&data), FP, "{NAME}: {FILE} bytes drifted"); - let before = crate::decode::palette_422_unit_window_hits(); - // lane-av1oracledepth: the OK arm is MEASURED to be the live one (the - // pinned bytes decode, 17 decode-order frames byte-exact vs aomdec, - // 16 windowed units) and the old `Err` arm matching the pre-lift - // refusal string "a chroma format of 4:2:2" is deleted: committed - // code no longer returns that string, so the arm could only ever - // swallow a FUTURE decode error that happened to contain it and read - // green off a stream that decoded nothing. A refusal today now fails - // this gate loudly, as it should. - match decode_stream(&data) { - Err(e) => { - panic!( - "{NAME}: {FILE} was refused by the current decoder: {e}. 4:2:2 is a \ - DECODED format; a refusal here is a regression, not the old sequence-\ - header gate" - ) - } - Ok(_) => { - let windows = crate::decode::palette_422_unit_window_hits() - before; - assert!( - windows > 0, - "{NAME}: {FILE} decoded, but no 4:2:2 intra-in-inter chroma unit took \ - the per-unit palette window ({windows} did) -- this cell does not \ - exercise the arm at all (class gate-blind-to-feature)" - ); - let (decoded, hidden) = decode_all_frames_vs_oracle(&data, FILE); - assert_eq!( - decoded, 17, - "{NAME}: the oracle decoded {decoded} frames in DECODE order, not 17" - ); - assert_eq!(hidden, 1, "{NAME}: expected exactly the one hidden altref"); - eprintln!( - "{NAME}: {decoded} decode-order frame(s) byte-exact against aomdec \ - ({hidden} hidden), {windows} chroma palette unit window(s)" - ); - } - } - } - - /// lane-av1-ibc128chunk: the WITNESS for the 128-root intrabc strip's - /// de-square-cut mu-chunk chroma walk, and the byte pin for it. - /// - /// `decode_intrabc_128rect` cut each mu chunk's chroma plane block with - /// `chunk_chroma = cside * 64 / side` -- a `chroma_side`-SQUARE chunk, - /// i.e. the 4:2:0 count on BOTH axes (the same defect lane-av1-422bigblock - /// fixed, and witnessed, in `decode_inter_block` and - /// `decode_block_128rect`; this copy was deferred there as unwitnessed). - /// At 4:2:2 a 64x64 mu chunk's chroma plane block is 32x64, so it holds - /// TWO STACKED TX_32X32 units per plane: the square-cut walk read one per - /// plane per chunk, left the chunk's lower 32 chroma rows with no - /// residual at all, and stamped each unit's entropy context over a - /// 16x16-mi luma span instead of 16x8. - /// - /// Measured red-before on the pinned witness (parent `a7d22aec`, via the - /// local `EC_AV1_ALLOW_422_PROBE` patch-run-restore build): 8 chroma - /// units stamped over the stream's two reached blocks and frames 0 and 3 - /// diverge from `aomdec` (45135 / 44540 of 245760 samples each), the - /// first difference at Y sample 98368 -- frame 0, row 256, col 64, the - /// top-left corner of the first 128x64 intrabc block at mi(64,0). The - /// red build then lost 4 of the stream's 6 intrabc blocks to the desync. - /// Green-after, same fixture: 48 chroma units stamped, all 6 blocks - /// decoded, and ALL FIVE frames byte-identical to `aomdec --rawvideo`. - /// - /// lane-av1422lift: committed code no longer refuses 4:2:2 at the - /// sequence header, so the red/green evidence above is no longer - /// probe-only: this gate is the one that asserts it. Both pins are - /// byte-pinned AND byte-exact against ffmpeg's `yuv422p` rawvideo of the - /// same bytes, per plane and per frame, with the per-plane - /// coefficient-unit census as the non-vacuity arm -- the census is what - /// makes "48 chroma units stamped" a committed, reproducible number here - /// instead of a sentence in a lane report. The source-scan arm below - /// keeps its own claim (the per-axis SPELLING) and does not overlap. - #[test] - fn the_pinned_422_intrabc_sb128_strip_witnesses_decode_pixel_exact() { - const NAME: &str = "the_pinned_422_intrabc_sb128_strip_witnesses_decode_pixel_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - for (file, bytes, fp) in [ - ( - "422_intrabc_sb128_strip.obu", - 1672usize, - 0x50f5cfc576e4cd00_u64, - ), - ( - "422_intrabc_sb128_strip_notxsearch.obu", - 1675, - 0xd4936f252ff8cff0, - ), - ] { - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("fixtures") - .join(file); - let data = std::fs::read(&path).unwrap_or_else(|e| { - panic!( - "{NAME}: pinned witness {} is missing ({e}) -- the gate cannot run", - path.display() - ) - }); - assert_eq!(data.len(), bytes, "{NAME}: {file} size drifted"); - assert_eq!(fnv1a64(&data), fp, "{NAME}: {file} bytes drifted"); - assert_422_stream_pixel_exact(NAME, &data, 384, 320, 5, 8, true); - } - } - - /// lane-av1422a2a4: the firing gate for `decode_block`'s var-tx EITHER/OR - /// tail at 4:2:2 -- an INTRABC block whose var-tx tree resolved MIXED - /// leaves, where the old blanket `set_txfm_ctxs` + `fill_lf_grid` publishes - /// clobbered the per-leaf TXFM_CONTEXT bands libaom keeps. - /// - /// Provenance: aomenc profile 2, `testsrc2=size=128x112:rate=25` tiled 2x2 - /// to 256x224, cq 30, 3 frames (`lanes/av1422ibcrect.report.md` §2, stream - /// A4). The oracle decodes it to completion; the pre-fix tree refused it - /// mid-tile with the documented `decodeframe.c:1456` subsize string -- the - /// E6/E7 desync-symptom class, NOT an invalid shape. - /// - /// Measured on the pinned bytes: the 32x32 intrabc block at mi(32,8) - /// resolves leaves (0,0)+((0,4) 8x8, (4,0)+(4,4) 16x16, so - /// `left_txfm[32..35]` must read 16 when the NEXT tree's sub-unit at - /// (32,16) row0col0 reads its `txfm_partition` context (oracle operands - /// `above=16 left=16`, ctx 9). The blanket publishes reset those cells to - /// 8 -> ctx 10 -> a wrong `is_split` -> the first divergent read, and the - /// refusal surfaced ~30 partition symbols later. - #[test] - fn the_pinned_422_intrabc_vartx_mixedtree_witnesses_decode_pixel_exact() { - const NAME: &str = "the_pinned_422_intrabc_vartx_mixedtree_witnesses_decode_pixel_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("fixtures") - .join("422_intrabc_vartx_mixedtree_a4.obu"); - let data = std::fs::read(&path).unwrap_or_else(|e| { - panic!( - "{NAME}: pinned witness {} is missing ({e}) -- the gate cannot run", - path.display() - ) - }); - assert_eq!(data.len(), 30937, "{NAME}: pinned witness size drifted"); - assert_eq!( - fnv1a64(&data), - 0x6f0fc77c2217910a_u64, - "{NAME}: pinned witness bytes drifted" - ); - assert_422_stream_pixel_exact(NAME, &data, 256, 224, 3, 8, true); - } - - /// lane-av1422ibctxsel: the firing gate for `decode_intrabc_owned_rect`'s - /// NON-SPLIT chroma coefficient context at 4:2:2. - /// - /// `lanes/av1422gathercensus.report.md` closed its ss (1, 0) class sweep - /// with this one gather at STOP -- unwitnessed: `around_mi_rect` over the - /// block's LUMA span feeds the CHROMA `dc_sign_ctx`, and at ss (1, 0) a - /// chroma 4-px cell spans TWO luma mi columns, so the per-mi sum counts - /// every chroma column twice (`around_mi_422_chroma`'s every-second - /// sampling is libaom's one-vote-per-cell sum). `lane-av1422ibcrect` - /// found a stream that ENTERS the gather (24 entries) but whose two - /// gathers agree on every entry, so the class stayed harmless-ON-THAT- - /// STREAM, not proven. - /// - /// This fixture is the discriminating witness: aomenc profile 2, 384x288 - /// 4:2:2, 4 key frames, `--sb-size=64` with the last superblock row half - /// outside the frame (so the 64-root partition is a single gathered bit - /// and the strips are 64x32 HORZ intra-BC strips), `--enable-tx-size- - /// search=1` plus a high-frequency patch that keeps the frame's `tx_mode` - /// at `TX_MODE_SELECT` (`txb_split_count > 0`; without it encodeframe.c - /// :2690 downgrades every frame to `TX_MODE_LARGEST`), and a chroma band - /// above the strips so a full-weight above context meets a full-weight - /// left one of the opposite sign. - /// - /// Measured on the pinned bytes: 24 non-split chroma gathers entered (6 - /// strips x 4 frames; 48 plane reads), and FIVE of them -- plane 2, strips - /// mi (64,16)..(64,80) of frame 0 -- read `dc_sign_ctx` 1 through the - /// luma-span gather against libaom's 0 through the pair rule (`full = 2A + - /// L = -8`, `pair = A + L = 0`: the double-counted above vote crosses - /// zero, and the context is a sign). - /// - /// Red-before (the route reverted, same fixture bytes): the wrong sign - /// context changes the decoded dc-sign CDF and desyncs the tile -- the - /// decoder refuses the stream mid-frame with "a block size 4x8, 8x16 or - /// 16x4 ... has no chroma plane block at this frame's subsampling mode", - /// so NO frame decodes at all. That refusal is also the proof it is a - /// desync symptom and not a real sub-8x8 shape: both oracles decode the - /// pinned bytes fully. Green-after: 4/4 frames byte-exact against - /// ffmpeg's `yuv422p` rawvideo, with the per-plane coefficient-unit - /// census (the helper's) and the pair-rule route counter as the - /// non-vacuity arms. The 4:4:4 arm below pins the guard's other side: - /// the same function at ss (0, 0) keeps the verbatim luma-span gather and - /// must NOT fire the route. - #[test] - fn a_422_intrabc_owned_rect_nonsplit_chroma_context_uses_the_pair_rule() { - const NAME: &str = "a_422_intrabc_owned_rect_nonsplit_chroma_context_uses_the_pair_rule"; - const FILE: &str = "ibc422_nonsplit_ctx.obu"; - const LEN: usize = 2170; - /// sha256 `4f82d5da8b4c3d6553953fc373001a1c7a729c9b189214b65503af1e04eb6b68`, - /// fnv1a64 `0x92e2c4e45ca27e34`. - const FNV: u64 = 0x92e2c4e45ca27e34; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("fixtures") - .join(FILE); - let data = std::fs::read(&path).unwrap_or_else(|e| { - panic!( - "{NAME}: pinned witness {} is missing ({e}) -- the gate cannot run", - path.display() - ) - }); - assert_eq!(data.len(), LEN, "{NAME}: {FILE} size drifted"); - assert_eq!(fnv1a64(&data), FNV, "{NAME}: {FILE} bytes drifted"); - // No `lock_gate_counters()` here: the bumps are thread-local, and - // `assert_422_stream_pixel_exact` takes that same (non-reentrant) - // mutex itself -- holding it across this call self-deadlocks. - crate::decode::reset_ibc_owned_rect_422_pair_hits(); - assert_422_stream_pixel_exact(NAME, &data, 384, 288, 4, 8, true); - let hits = crate::decode::ibc_owned_rect_422_pair_hits(); - assert_eq!( - hits, 24, - "{NAME}: the pair-rule route fired {hits} times, not 24 (6 non-split chroma gathers \ - x 4 frames) -- the witness stopped exercising the arm, or the guard's extent moved" - ); - // The guard's other arm: the 4:4:4 owner-rect stream (`r512.obu`, - // pinned by the gate below) reaches this same function at ss (0, 0), - // where the verbatim luma-span gather is correct -- the route counter - // must stay put. - let r512 = std::fs::read( - std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("fixtures/r512.obu"), - ) - .expect("r512.obu must exist"); - crate::decode::reset_ibc_owned_rect_422_pair_hits(); - let _ = decode_stream(&r512).expect("the 4:4:4 owner-rect witness decodes"); - assert_eq!( - crate::decode::ibc_owned_rect_422_pair_hits(), - 0, - "{NAME}: the 4:2:2 pair-rule route fired on a 4:4:4 stream -- the ss (1, 0) guard \ - leaks (class gate-blind-to-feature)" - ); - } - - /// lane-av1-ibc128chunk: the SOURCE-SCAN arm of the witness gate above. - /// - /// The decode-level half of the red/green evidence now runs in committed - /// code too -- the witness gate above, - /// `the_pinned_422_intrabc_sb128_strip_witnesses_decode_pixel_exact`, - /// decodes both pins byte-exact against ffmpeg (lane-av1422lift lifted the - /// sequence-header refusal). This arm complements it by pinning the thing - /// that would silently bring the defect back: the square-cut - /// `chunk_chroma = cside * 64 / side` expression, and the per-axis - /// replacements that replaced it at BOTH sites in - /// [`decode_intrabc_128rect`] -- the mu-chunk read walk and the - /// `mu_chroma` per-unit context replay. It also pins the per-axis - /// counters' accessors so the arms stay reachable, and the walk's own - /// per-axis extent, derived here from the same `64 >> ss` form the - /// witnesses measured (4:2:0 = one TX_32X32 per plane per chunk, - /// 4:2:2 = two stacked, 4:4:4 = four). - #[test] - fn the_intrabc_128rect_chroma_chunk_walk_stays_per_axis() { - const NAME: &str = "the_intrabc_128rect_chroma_chunk_walk_stays_per_axis"; - let src = crate::test_source::module_source("decode"); - let body = src - .split_once("fn decode_intrabc_128rect(") - .expect("decode_intrabc_128rect must exist") - .1 - .split_once("\nfn ") - .expect("decode_intrabc_128rect must be a top-level fn") - .0; - // Scan CODE only: the fix's own comments quote the old expression to - // say what it was, and a prose mention must not read as a - // reintroduction (nor mask one). - let stripped: Vec<&str> = body - .lines() - .map(|l| l.split_once("//").map_or(l, |(c, _)| c)) - .collect(); - let code = stripped.join("\n"); - let body = code.as_str(); - assert_eq!( - body.matches("cside * 64 / side").count(), - 0, - "{NAME}: the square-cut `cside * 64 / side` chunk extent is BACK in \ - decode_intrabc_128rect -- that expression is the 4:2:2 defect this \ - gate exists for (a 64x64 mu chunk's chroma plane block is \ - (64 >> ss_x) x (64 >> ss_y), not `chroma_side` square)" - ); - // The per-axis chunk extent, declared once at the mu-chunk read walk - // and once at the `mu_chroma` replay -- the two de-square-cut sites. - // - // The replay must ALSO enumerate every unit inside a chunk, not just - // its first: counting mu CHUNKS in `rows`/`cols` and then stepping the - // mi origin and reading the grid per UNIT only agrees when a chunk - // holds exactly one unit (4:2:0). At 4:2:2 and 4:4:4 a chunk holds two - // or four, so the per-unit body alone left the rest of the chunk with - // the composed-grid smearing the replay exists to undo. - for name in [ - "let chunk_chroma_w = (64usize) >> ss_x(fctx);", - "let chunk_chroma_h = (64usize) >> ss_y(fctx);", - ] { - assert_eq!( - body.matches(name).count(), - 2, - "{NAME}: `{name}` must appear at BOTH de-square-cut sites in \ - decode_intrabc_128rect (the mu-chunk read walk and the mu_chroma \ - context replay), found {}", - body.matches(name).count() - ); - } - for name in [ - "let (ur, uc) = (chunk_chroma_h / cu, chunk_chroma_w / cu);", - "for kr in 0..ur {", - "for kc in 0..uc {", - ] { - assert_eq!( - body.matches(name).count(), - 1, - "{NAME}: `{name}` must appear exactly once in \ - decode_intrabc_128rect -- the mu_chroma replay must walk chunk \ - THEN unit (decode_inter_block's `mu_chroma_units` shape), found {}", - body.matches(name).count() - ); - } - for name in [ - "let unit_luma_w = cu_tx << ss_x(fctx);", - "let unit_luma_h = cu_tx << ss_y(fctx);", - "let (cw, ch) = (bw >> ss_x(fctx), bh >> ss_y(fctx));", - "let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));", - "neighbours.around_mi_rect(unit_mi, unit_luma_w, unit_luma_h)", - ] { - assert_eq!( - body.matches(name).count(), - 1, - "{NAME}: `{name}` must appear exactly once in \ - decode_intrabc_128rect, found {}", - body.matches(name).count() - ); - } - // lane-av1muchunk422sym: the CHROMA gather of that same walk must take - // the 4:2:2 pair rule, exactly as `decode_inter_block`'s mu-chunk walk - // does (one chroma column per pair of luma mi cells; the plain rect - // gather doubles the above dc vote and flips `dc_sign_ctx` wherever - // above and left cancel). Reachability is measured: the walk fires at - // ss (1, 0) on `422_intrabc_sb128_strip.obu` (`EC_IBC128_BANDS` - // prints); that fixture's own votes do not cancel, so THIS gate -- not - // a pixel compare -- is what stops the routing being reverted. - for name in [ - "let cu_around = if ss_x(fctx) == 1 && ss_y(fctx) == 0 {", - "neighbours.around_mi_422_chroma(", - ] { - assert_eq!( - body.matches(name).count(), - 1, - "{NAME}: `{name}` must appear exactly once in \ - decode_intrabc_128rect's chroma chunk walk, found {} -- the \ - gather has fallen back to the square per-mi rule", - body.matches(name).count() - ); - } - // The replay's own unit luma span is the lossless/lossy `cu << ss` form - // (site 2 spells it separately from the read walk's `cu_tx << ss`). - for name in [ - "let unit_luma_w = cu << ss_x(fctx);", - "let unit_luma_h = cu << ss_y(fctx);", - ] { - assert_eq!( - body.matches(name).count(), - 1, - "{NAME}: `{name}` must appear exactly once in \ - decode_intrabc_128rect, found {}", - body.matches(name).count() - ); - } - // The per-axis chunk extent the geometry demands, spelled out here so - // the scan and the witnesses cannot disagree about it. - let per_axis_units = |ss_x: u32, ss_y: u32| (64 >> ss_x) / 32 * (64 >> ss_y) / 32; - assert_eq!(per_axis_units(1, 1), 1, "{NAME}: 4:2:0 must stay one unit"); - assert_eq!(per_axis_units(1, 0), 2, "{NAME}: 4:2:2 must be two units"); - assert_eq!(per_axis_units(0, 0), 4, "{NAME}: 4:4:4 must be four units"); - // The counters the probe arms read must stay exported. - for name in [ - "pub fn intrabc_128rect_chroma_chunk_hits()", - "pub fn intrabc_128rect_chunk_shape()", - ] { - assert!( - src.contains(name), - "{NAME}: the accessor `{name}` must stay in decode.rs" - ); - } - } - - /// lane-av1422gather3: `decode_block_128rect`'s per-chunk CHROMA unit - /// walk gathered its coefficient context with the plain square-cut - /// `around_mi_rect`, so at ss (1,0) its above dc vote summed 16 LUMA mi - /// cells where libaom's `get_txb_ctx_general` reads `txb_w_unit` = - /// `chroma_tx / 4` = 8 CHROMA cells (one chroma column per PAIR of luma - /// mi columns; both luma cells of a column carry the covering unit's - /// whole-unit dc sign). That is the same pair rule the mu-chunk walks - /// take (`around_mi_422_chroma`), and the gather now routes through it - /// under the ss guard -- verbatim `around_mi_rect` at every other shape. - /// - /// Reachability is MEASURED, not assumed: the walk fires at ss (1,0) on - /// both pinned `422_intrabc_sb128_strip*.obu` cells, 72 chroma unit - /// gathers each (`sb128rect_chroma_replay_hits().0`, the same walk's own - /// replay counter). No committed cell DISCRIMINATES the change: with the - /// pair rule in place all 21 committed 4:2:2 cells are byte-exact - /// against ffmpeg, exactly as the pre-change tree was (the gathered - /// votes cancel at every reached unit), so THIS gate -- not a pixel - /// compare -- is what stops the routing being reverted. - /// - /// lane-av1422mismatch9: the same decode loop now also asserts the - /// `SB128RECT_REPLAY_SPAN_MISMATCH_HITS` count (NINE per pin) and states - /// why it is not a pixel miss -- the counter's predicate is a span - /// DIFFERENCE, true by construction at ss (1,0); the replay re-stamps the - /// identical context cells with the same per-axis pair the read walk used; - /// and `record_mi_chroma` writes no pixel sample. See the assert's message. - #[test] - fn the_422_block_128rect_chroma_chunk_gather_stays_per_axis() { - const NAME: &str = "the_422_block_128rect_chroma_chunk_gather_stays_per_axis"; - let src = crate::test_source::module_source("decode"); - let body = src - .split_once("fn decode_block_128rect(") - .expect("decode_block_128rect must exist") - .1 - .split_once("\nfn ") - .expect("decode_block_128rect must be a top-level fn") - .0; - // Scan CODE only: the fix's own comment quotes the guard form, and a - // prose mention must not read as a reintroduction (nor mask one). - let stripped: Vec<&str> = body - .lines() - .map(|l| l.split_once("//").map_or(l, |(c, _)| c)) - .collect(); - let code = stripped.join("\n"); - let body = code.as_str(); - assert_eq!( - body.matches("if ss_x(fctx) == 1 && ss_y(fctx) == 0 {") - .count(), - 1, - "{NAME}: the ss (1, 0) guard over the per-chunk chroma gather must \ - appear exactly once in decode_block_128rect, found {}", - body.matches("if ss_x(fctx) == 1 && ss_y(fctx) == 0 {") - .count() - ); - for name in [ - "neighbours.around_mi_422_chroma(cu_mi, luma_span, luma_span_h)", - "neighbours.around_mi_rect(cu_mi, luma_span, luma_span_h)", - ] { - assert_eq!( - body.matches(name).count(), - 1, - "{NAME}: `{name}` must appear exactly once in \ - decode_block_128rect's per-chunk chroma gather, found {} -- one \ - arm has been dropped, so the gather has fallen back to the \ - square per-mi rule at ss (1, 0)", - body.matches(name).count() - ); - } - // Reachability arm: the walk must actually RUN at ss (1, 0) on the - // pinned strips, or the routing above is a no-op the gate cannot see. - // A stream that stopped coding 128-axis intra blocks reads 0 and this - // assert fails instead of passing over a decode that never reached - // the fixed gather (class gate-blind-to-feature). - for (file, bytes, fp) in [ - ( - "422_intrabc_sb128_strip.obu", - 1672usize, - 0x50f5cfc576e4cd00_u64, - ), - ( - "422_intrabc_sb128_strip_notxsearch.obu", - 1675, - 0xd4936f252ff8cff0, - ), - ] { - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("fixtures") - .join(file); - let data = std::fs::read(&path).unwrap_or_else(|e| { - panic!( - "{NAME}: pinned witness {} is missing ({e}) -- the gate cannot run", - path.display() - ) - }); - assert_eq!(data.len(), bytes, "{NAME}: {file} size drifted"); - assert_eq!(fnv1a64(&data), fp, "{NAME}: {file} bytes drifted"); - let _guard = lock_gate_counters(); - let before = crate::decode::sb128rect_chroma_replay_hits(); - let frames = decode_stream(&data) - .unwrap_or_else(|e| panic!("{NAME}: {file} no longer decodes cleanly: {e}")); - let after = crate::decode::sb128rect_chroma_replay_hits(); - assert_eq!( - after.0 - before.0, - 72, - "{NAME}: {file} gathered {} chroma unit context(s) in \ - decode_block_128rect's per-chunk walk; 72 were measured at ss (1, 0) -- \ - a lower number means the gather is no longer REACHED here \ - (class gate-blind-to-feature)", - after.0 - before.0 - ); - // lane-av1422mismatch9: `SB128RECT_REPLAY_SPAN_MISMATCH_HITS` reads - // NINE on each of these two pins, and this is the only place that - // number is asserted. It is NOT a pixel miss, and the three facts - // below are why -- the assert encodes the measurement, not a wish: - // - // 1. The predicate (`decode.rs`, end of `decode_block_128rect`) is - // `luma_span != luma_span_h` -- `chroma_tx << ss_x` vs - // `chroma_tx << ss_y`. At ss (1, 0) the two DIFFER BY - // CONSTRUCTION for every 128-root rect block, so the counter is - // a shape test ("this is the 4:2:2 span shape"), not a - // divergence test. Nine is the number of such blocks the five - // frames code. - // 2. The replay re-stamps with the SAME per-axis pair the in-loop - // walk stamped with (`record_mi_chroma(cu_mi, luma_span, - // luma_span_h, ...)` at both the read walk and the replay), so - // it rewrites the identical context cells -- this is exactly - // the `record_mi_chroma(cu_mi, luma_span, luma_span_h)` pairing - // the source-scan arm above pins. The pre-lane-av1-128rectspan - // defect (width passed on both axes) is caught by that - // spelling arm, not by this counter. - // 3. `record_mi_chroma` writes only `Neighbours::left`/`above` - // (entropy-context arrays); it touches ZERO pixel samples. So - // the 9 events cannot write a sample the oracle lacks. The - // pixel proof is the same file's - // `the_pinned_422_intrabc_sb128_strip_witnesses_decode_pixel_ - // exact`, which pins all five frames byte-exact against - // ffmpeg's `yuv422p` rawvideo. - // - // Change this expected count ONLY with a new measurement; a 4:2:2 - // stream coding more 128-root rect blocks legitimately changes it. - assert_eq!( - after.1 - before.1, - 9, - "{NAME}: {file} fired the 4:2:2 span-shape arm {} time(s); NINE were \ - measured and are NOT a pixel miss (the predicate is `luma_span != \ - luma_span_h`, true by construction at ss (1,0); the replay re-stamps the \ - identical context cells with the same per-axis pair; `record_mi_chroma` \ - writes no pixel) -- see the report above", - after.1 - before.1 - ); - assert_eq!(frames.len(), 5, "{NAME}: {file} frame count"); - } - } - - /// lane-av1422lpf: the three 4:2:2 LOSSLESS INTER witness fixtures, - /// PINNED. As of lane-av1422lift they are asserted to DECODE pixel-exact - /// against ffmpeg (the lane-av1422lift paragraph at the end of this doc); - /// before the lift this gate asserted the SEQUENCE-HEADER refusal instead. - /// - /// W/X/Y (`W_intrabc.obu`, `X_intrabc_tiled.obu`, `Y_intrabc_10b.obu`) are - /// the streams on which lane-av1422lpf found the seven-site chroma-extent - /// PANIC family -- each site indexed a block's chroma PLANE BLOCK with - /// the ENCLOSING SQUARE `max(side >> ss_x, side >> ss_y)` instead of the - /// PER-AXIS `(bw >> ss_x, bh >> ss_y)` -- so the pins keep the bytes that - /// witnessed it from silently changing under the gate. - /// - /// WHAT THIS GATE DID NOT COVER BEFORE THE LIFT, measured rather than - /// argued: the refusal it asserted was the HEADER refusal, which fired - /// BEFORE any of the seven sites is reachable, and it fired IDENTICALLY on - /// the pre-fix tree (commit `aef4fa67` prints the same string, built and - /// run for this correction). As a refusal contract the gate was therefore - /// VACUOUS with respect to the seven-site fix -- it passed before and - /// after the fix, and its only real content was the three pins. - /// - /// That refusal is GONE (lane-av1422lift lifted the sequence-header - /// refusal), so the decode-level half of the evidence now runs in - /// committed code: this gate's own byte-exact arm below decodes all three - /// fixtures against ffmpeg. `EC_AV1_ALLOW_422_PROBE` was only ever the - /// patch-run-restore bypass for the manual measurement in - /// `lanes/av1422lpf.report.md`; it is still deliberately not committed. - /// The source-scan arm - /// `the_422_lossless_inter_chroma_walk_sites_stay_per_axis` remains the - /// per-axis SPELLING proof; the pixel proof is now the committed decode. - /// - /// CORRECTED by lane-av1422llintra: the name said `..._panics_refuse_ - /// by_name`, and lane-av1422lpf's report claimed W and X now REFUSE with - /// `a Golomb tail longer than this decoder reads` at frame 2. That - /// refusal DOES NOT REPRODUCE on this tip: with the bypass applied, all - /// three cells DECODE 16/16 -- no panic and no second refusal. - /// - /// lane-av1422lift: the three pins are asserted BYTE-EXACT against - /// ffmpeg's rawvideo of the same bytes, per plane and per frame, with the - /// per-plane coefficient-unit census as the non-vacuity arm -- so the - /// three DECODE 16/16 fact the paragraph above records from a bypassed - /// probe build is now a committed assertion. `Y` is the 10-bit member - /// and carries the depth-correct HBD compare (`yuv422p10le`, 16-bit - /// containers on both sides) rather than an 8-bit narrowing of a - /// high-bit-depth cell. - #[test] - fn the_pinned_422_lossless_inter_witnesses_decode_pixel_exact() { - const NAME: &str = "the_pinned_422_lossless_inter_witnesses_decode_pixel_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - for (file, bytes, fp, depth) in [ - ("W_intrabc.obu", 130_320usize, 0xb6d5c4653a32567a_u64, 8u8), - ("X_intrabc_tiled.obu", 131_696, 0xb6e04621d2116ef7, 8), - ("Y_intrabc_10b.obu", 202_281, 0x2ecf03435a14dbf, 10), - ] { - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("fixtures") - .join(file); - let data = std::fs::read(&path).unwrap_or_else(|e| { - panic!("{NAME}: pinned witness {file} is missing ({e}) -- the gate cannot run") - }); - assert_eq!(data.len(), bytes, "{NAME}: {file} size drifted"); - assert_eq!(fnv1a64(&data), fp, "{NAME}: {file} bytes drifted"); - assert_422_stream_pixel_exact(NAME, &data, 320, 240, 16, depth, true); - } - } - - /// lane-av1422lpf: the SOURCE-SCAN arm of the witness gate above -- one - /// assertion per site, so a mutation at any single site reds exactly that - /// site and leaves the other six alone. - /// - /// Every assertion has a NEGATIVE twin (`forbidden`) and a POSITIVE twin - /// (`required`), so neither an unreverted site nor a matcher that has - /// stopped matching can pass: the forbidden string is absent AND the - /// required string is present in the same function body. The `required` - /// half is what makes this gate non-vacuous in the - /// `dead-matcher-positive-control` sense -- a scan that matched nothing - /// would fail it rather than pass silently. - /// - /// WHAT IT DOES NOT COVER: this arm is a SPELLING scan. It cannot observe - /// a decode, so it cannot prove any cell decodes and cannot prove any - /// pixel -- the same limit as the witness gate above it, and stated here - /// because "one assertion per site, each with a mutation proof" reads - /// like more coverage than it is. - /// - /// `strip_code` is the same comment-stripping the arms above use: the - /// fixes quote their own old expression to say what it was, and a prose - /// mention must neither read as a reintroduction nor mask one. - #[test] - fn the_422_lossless_inter_chroma_walk_sites_stay_per_axis() { - const NAME: &str = "the_422_lossless_inter_chroma_walk_sites_stay_per_axis"; - let src = crate::test_source::module_source("decode"); - let strip_code = |body: &str| -> String { - body.lines() - .map(|l| l.split_once("//").map_or(l, |(c, _)| c)) - .collect::>() - .join("\n") - }; - // A SECOND form with the same comment stripping but every run of - // whitespace collapsed to one space, so a matcher can span an argument - // list that a line-anchored fix's own comment sits inside. Without it - // the site-5 and site-6 matchers are DEAD: the mutation that reverts - // them still passes, because the literal being searched for never - // matched even when the fix was in place. Measured, not assumed -- - // `verifier-dead-matcher-positive-control`. - let flatten = |body: &str| -> String { - strip_code(body) - .split_whitespace() - .collect::>() - .join(" ") - }; - let body_of = |fn_name: &str| -> String { - let after = src - .split_once(&format!("\nfn {fn_name}(")) - .unwrap_or_else(|| panic!("{NAME}: `{fn_name}` must exist in decode.rs")); - let end = after.1.find("\nfn ").unwrap_or(after.1.len()); - strip_code(&after.1[..end]) - }; - let flat_of = |fn_name: &str| -> String { - let after = src - .split_once(&format!("\nfn {fn_name}(")) - .unwrap_or_else(|| panic!("{NAME}: `{fn_name}` must exist in decode.rs")); - let end = after.1.find("\nfn ").unwrap_or(after.1.len()); - flatten(&after.1[..end]) - }; - // (label, enclosing fn, forbidden square-cut spelling, required - // per-axis spelling, required count in that fn) - let sites: [(&str, &str, &str, &str, usize); 4] = [ - ( - "site 1 -- read_inter_chroma_lossless's composed-grid extent", - "read_inter_chroma_lossless", - "stride * stride,\n );", - "stride * blk_h,", - 1, - ), - ( - "site 7 -- read_intra_chroma_lossless's composed-grid extent", - "read_intra_chroma_lossless", - "stride * stride,\n );", - "stride * blk_h,", - 1, - ), - ( - "site 4 -- the strip chroma rect's VERT arm at ss (1,0)", - "decode_inter_block", - "} else if s.horz {\n (8, 4)\n } else {\n (4, 8)\n }", - "} else if ss_y(fctx) == 0 {\n (4, 16)\n } else {\n (4, 8)\n }", - 1, - ), - ( - "site 5 -- the mu-chunk lossless walk's prediction stride", - "decode_inter_block", - "(write_chroma_w, write_chroma_h), chroma_side, mode_for_tx,", - "(write_chroma_w, write_chroma_h), chroma_stride, mode_for_tx,", - 2, - ), - ]; - for (label, fn_name, forbidden, required, count) in sites { - // The last table row is written in the flattened form (it spans a - // comment the fix itself wrote); the others are line-anchored. - let flattened = required.contains(" mode_for_tx,"); - let body = if flattened { - flat_of(fn_name) - } else { - body_of(fn_name) - }; - assert_eq!( - body.matches(forbidden).count(), - 0, - "{NAME}: {label} is BACK -- the square-cut expression \ - `{forbidden}` is what this gate exists for" - ); - assert!( - body.matches(required).count() >= count, - "{NAME}: {label}: the per-axis expression `{required}` must appear \ - at least {count} time(s) in `{fn_name}` -- found {}", - body.matches(required).count() - ); - } - // Sites 2, 5 and 6 are the `chroma_side`-vs-`chroma_stride` and - // `chroma_side`-vs-`chroma_buf_h` argument choices, which are - // single-token differences on otherwise identical lines. Counting the - // remaining `chroma_side` uses per arm is the only way to see them, so - // they get their own exact-count assertions instead of a substring. - let dib = body_of("decode_inter_block"); - // Site 2: the lossless TX_4x4 unit replay indexes the composed grid. - assert_eq!( - dib.matches("let start = (cr * cu + rr) * chroma_stride + cc * cu;") - .count(), - 1, - "{NAME}: site 2 -- the lossless TX_4x4 replay must index the \ - composed plane grid at `chroma_stride` (the plane block's own \ - width), not `chroma_side`" - ); - assert_eq!( - dib.matches("let start = (cr * cu + rr) * chroma_side + cc * cu;") - .count(), - 0, - "{NAME}: site 2 is BACK -- the lossless TX_4x4 replay indexes the \ - composed grid at the enclosing square again" - ); - // Sites 5 and 6. The two mu-chunk walks (the single-reference and the - // compound twin) take the block's `(write_chroma_w, write_chroma_h)` - // and the stride SEPARATELY; the two intra-in-inter walks take both - // the block shape and the region as `(chroma_stride, chroma_buf_h)`. - // Every one of the four must be per-axis; the pre-fix spelling was - // the enclosing square `chroma_side` for the stride, and - // `(chroma_side, chroma_side)` for the intra block shape. - let dibf = format!( - "{}{}", - flat_of("decode_inter_block"), - flat_of("decode_inter_block_intra_arm"), - ); // the intra arm was split out of decode_inter_block (av1split D8a) - assert_eq!( - dibf.matches("(chroma_stride, chroma_buf_h),").count(), - 3, - "{NAME}: site 6 -- the two intra-in-inter walks pass the plane block \ - as `(chroma_stride, chroma_buf_h)` at all THREE argument positions \ - it occupies -- the mu-chunk walk's blk shape, and the whole-block walk's blk shape and region -- found {}", - dibf.matches("(chroma_stride, chroma_buf_h),").count() - ); - assert_eq!( - dibf.matches("(chroma_side, chroma_side),").count(), - 0, - "{NAME}: site 6 is BACK -- an intra-in-inter walk still hands the \ - plane block the enclosing square `chroma_side`" - ); - // The geometry the scan cannot see, derived from the same `>> ss` - // forms the fixes use, so the scan and the fix cannot disagree about - // what per-axis means at each chroma format. A 16x16 luma block: - // (side >> ss_x, side >> ss_y) is the plane block and - // max(side >> ss_x, side >> ss_y) is the enclosing square. - let plane_block = |side: usize, ss_x: u32, ss_y: u32| (side >> ss_x, side >> ss_y); - let enclosing = |side: usize, ss_x: u32, ss_y: u32| { - ( - (side >> ss_x).max(side >> ss_y), - (side >> ss_x).max(side >> ss_y), - ) - }; - for (label, side, ss_x, ss_y, block, square) in [ - ("4:2:0", 16usize, 1u32, 1u32, (8, 8), (8, 8)), - ("4:2:2", 16, 1, 0, (8, 16), (16, 16)), - ("4:4:4", 16, 0, 0, (16, 16), (16, 16)), - ] { - assert_eq!( - plane_block(side, ss_x, ss_y), - block, - "{NAME}: the {label} chroma plane block of a {side}x{side} luma block" - ); - assert_eq!( - enclosing(side, ss_x, ss_y), - square, - "{NAME}: the {label} enclosing chroma square of a {side}x{side} \ - luma block" - ); - } - // The load-bearing claim of "unchanged at 4:2:0 and 4:4:4": the two - // are the same number exactly when `ss_x == ss_y`, and DIFFERENT at - // 4:2:2 -- which is what makes every site above inert there and - // active at 4:2:2. If this ever held at 4:2:2 the fixes would be - // untested rather than inert. - assert_eq!(plane_block(16, 1, 1), enclosing(16, 1, 1)); - assert_eq!(plane_block(16, 0, 0), enclosing(16, 0, 0)); - assert_ne!( - plane_block(16, 1, 0), - enclosing(16, 1, 0), - "{NAME}: 4:2:2 must NOT be square -- if the plane block equalled \ - the enclosing square at ss (1,0), none of these sites could ever \ - be wrong and the gates above would be measuring nothing" - ); - // Site 4's own geometry: a PARTITION_VERT_4 strip is 4x16 luma and - // pairs on COLUMNS while `ss_x == 1`, so the pair is 8x16 and its - // plane block is (8 >> ss_x, 16 >> ss_y). - for (label, ss_x, _ss_y, want) in [ - ("4:2:0", 1u32, 1u32, (4usize, 8usize)), - ("4:2:2", 1, 0, (4, 16)), - ("4:4:4", 0, 0, (8, 16)), - ] { - assert_eq!( - plane_block(8, ss_x, 0).0, - want.0, - "{NAME}: site 4 -- the {label} VERT strip pair's chroma width" - ); - } - // ...and the HORZ arm of the same match needs NO third shape at - // 4:2:2: a HORZ_4 strip pairs on ROWS only while `ss_y == 1`, and - // 4:2:2 has `ss_y == 0`, so each 16x4 strip is its own chroma - // reference and its own (8 >> ss_x, 4 >> 0) plane block -- which is - // the (8, 4) the existing arm already returns. - assert_eq!( - (plane_block(16, 1, 0).0, plane_block(4, 1, 0).1), - (8usize, 4usize), - "{NAME}: site 4 -- the 4:2:2 HORZ strip's own plane block is already \ - the (8, 4) the unsplit arm returns, which is why only the VERT arm \ - gained a shape" - ); - } - - /// lane-av1422warp: the SECOND 4:2:2 coverage witness -- the one - /// `422_sb128_3f.obu` could not be, because that stream's inter content - /// is skip-heavy (see `lanes/av1422stripwrite.report.md`, which named a - /// second fixture with real residuals, compound and warped motion above - /// the vertical midpoint as the thing that would justify lifting the - /// refusal). This is that fixture. - /// - /// `422_residual_compound_warp_16f.obu` (38845 bytes), sha256 - /// `d78e2afb43ce311d3d82335a945c6f80f62db4537966d881c1349a68b3aecb95`: - /// - /// ```text - /// 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" \ - /// -frames:v 24 -pix_fmt yuv422p -f yuv4mpegpipe src422.y4m - /// aomenc --codec=av1 --profile=2 --input-bit-depth=8 --limit=16 - /// --width=256 --height=288 --lag-in-frames=25 --auto-alt-ref=1 - /// --enable-global-motion=1 --pass=1 - /// --cq-level=24 --cpu-used=0 - /// --threads=4 --kf-min-dist=0 --kf-max-dist=999999 \ - /// src422.y4m -o a1.webm - /// ffmpeg -i a1.webm -c copy -f obu -y a1.obu - /// ``` - /// - /// CORRECTED by lane-av1422lrless (reviewer P2). This doc previously - /// carried a different ffmpeg filter (`rotate=a=0.10`, no `*t`, no - /// `:c=none:ow/oh`) and a `-n ffp --pass=2 --fpf=...` two-pass line. - /// **Neither produced these bytes.** Re-encoding from the recorded - /// source `src422.y4m` (sha256 - /// `4d35eaf65d1a5541b3177e1183644c163b3868d8f141bed0ce9fdf833280ba9f`) - /// was measured three ways: the two-pass form gives 38774 bytes - /// (`e93c4ed7...`), and only adding `--pass=1` reproduces these 38845 - /// bytes byte for byte (`d78e2afb...`). `aomenc` DEFAULTS to two-pass, - /// so the flag has to be stated to get back the pinned stream. The - /// recipe above is the one that was actually run. - /// - /// Measured on a patch-run-restore build (the `EC_AV1_ALLOW_422_PROBE` - /// bypass applied for the run, reverted after -- it is deliberately NOT - /// committed). This block is the bypassed measurement; the committed - /// assertion is now the byte-exact compare in the lane-av1422lift - /// paragraph below: - /// - /// - all 16 frames pixel-exact against `aomdec --rawvideo`, 2359296 - /// bytes each, sha256 `4bfc2395e5ca6ea178f606e6b1ced773e26fc2d85b - /// c3a6cdb63a402939aeb203` on both sides; - /// - the entropy stream pairs bit-for-bit against the instrumented - /// oracle -- 246735 symbol reads each, no divergence anywhere in the - /// stream, not merely at the window this lane spent nine rounds - /// narrowing; - /// - the arms this fixture exists to cover really fire ABOVE the - /// vertical midpoint: 3 upper-half blocks on a non-`TRANSLATION` - /// global-motion model (`top_half_warp_hits`, gated on libaom's - /// `is_global_mv_block` per slot) and 3 upper-half - /// `GLOBAL_GLOBALMV` compound blocks (`top_half_compound_hits`), - /// alongside 25 compound-warp, 18 compound-warp-8x8-leaf, 84 - /// rotzoom global-warp, 22 Wiener and 10 SGRPROJ loop-restoration - /// units frame-globally. - /// - /// The loop-restoration numbers are load-bearing twice over: decoding - /// this stream is what exposed the per-axis `read_lr` corner bug - /// (`restoration.rs`, `av1_loop_restoration_corners_in_sb`), whose fix - /// is what made the whole sequence pair. 4:2:0 and 4:4:4 are unchanged - /// by it -- byte-identical to their pre-lane decodes, with the LR gate - /// family green. - /// - /// lane-av1422lift: the committed assertion is now the byte pin AND - /// byte-exactness against ffmpeg's `yuv422p` rawvideo of the same bytes, - /// per plane and per frame, with the per-plane coefficient-unit census - /// as the non-vacuity arm. The paragraph above's coverage counts (25 - /// compound-warp, 84 rotzoom global-warp, 22 Wiener, 10 SGRPROJ, CDEF - /// 39) are what make the row non-vacuous: without them a byte-exact - /// compare could be green over a stream that never entered a warp arm. - #[test] - fn the_pinned_422_residual_compound_warp_witness_decodes_pixel_exact() { - const NAME: &str = "the_pinned_422_residual_compound_warp_witness_decodes_pixel_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - const FILE: &str = "422_residual_compound_warp_16f.obu"; - const BYTES: usize = 38845; - const FP: u64 = 0x0e73a51e2cc0c424; - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("fixtures") - .join(FILE); - let data = std::fs::read(&path).unwrap_or_else(|e| { - panic!( - "{NAME}: pinned witness {} is missing ({e}) -- the gate cannot run", - path.display() - ) - }); - assert_eq!(data.len(), BYTES, "{NAME}: {FILE} size drifted"); - assert_eq!(fnv1a64(&data), FP, "{NAME}: {FILE} bytes drifted"); - assert_422_stream_pixel_exact(NAME, &data, 256, 288, 16, 8, true); - } - - /// lane-av1422lrless: the LR-OFF half of the 4:2:2 coverage pair. - /// - /// This is `422_residual_compound_warp_16f.obu`'s recipe with EXACTLY - /// ONE flag changed, `--enable-restoration=0`, and that is a measured - /// claim rather than an assertion: both arms were re-encoded from the - /// same source `src422.y4m` (sha256 - /// `4d35eaf65d1a5541b3177e1183644c163b3868d8f141bed0ce9fdf833280ba9f`) - /// with the same aomenc invocation, and the LR-on arm reproduces the - /// committed 38845 bytes byte for byte. So the pair is controlled, and - /// the corners code is the only thing that can differ between their - /// decodes: with restoration off, every plane's `frame_restoration_type` - /// is `RESTORE_NONE`, so `read_lr` skips each plane and never computes a - /// range. The LR-on stream exercises the range; this one proves the skip - /// is the skip. - /// - /// ```text - /// aomenc --codec=av1 --profile=2 --input-bit-depth=8 --limit=16 - /// --width=256 --height=288 --lag-in-frames=25 --auto-alt-ref=1 - /// --enable-global-motion=1 --pass=1 --enable-restoration=0 - /// --cq-level=24 --cpu-used=0 - /// --threads=4 --kf-min-dist=0 --kf-max-dist=999999 \ - /// src422.y4m -o a3.webm - /// ffmpeg -i a3.webm -c copy -f obu -y a3.obu - /// ``` - /// - /// 38538 bytes, sha256 - /// `8bed368f7ec4bca772137c6a9c2af89e1b2767ed5f937b91bd9e72ec60aeb42f`. - /// - /// Measured on a patch-run-restore build (the `EC_AV1_ALLOW_422_PROBE` - /// bypass applied for the run, reverted after -- deliberately not - /// committed). This block is the bypassed measurement; the committed - /// assertion is now the byte-exact compare in the lane-av1422lift - /// paragraph below: - /// - /// - all 16 frames pixel-exact against `aomdec --rawvideo`, 2359296 - /// bytes each, sha256 `1cf47bc9e06a6e286452dfe4ffe457a85b6badd25 - /// 657dfd36af48262e8eb2464` on both sides; - /// - the entropy stream pairs **244756-for-244756** against the - /// instrumented oracle with no divergence anywhere -- a different - /// read count from the LR-on sibling's 246735, which is the corners - /// skip showing up in the symbol stream, so the two arms really are - /// on different paths; - /// - **loop restoration is proved off, not inferred from the flag**: - /// all five LR counters read zero where the LR-on sibling reads - /// `lr_wiener` 22, `lr_sgrproj` 10, `lr_stripe0` 26, `lr_last_stripe` - /// 28; - /// - and it carries MORE of the coverage than its sibling, which is - /// what rescues the thin leg of the lift argument: **top-half - /// compound 11** against the sibling's 3, and top-half warp 5 against - /// 3. Frame-globally compound_warp 25, compound_warp_8 15, rotzoom - /// global-warp 77, cdef_idx 39, part128_split 95. The stronger arm is - /// the one where `read_lr` does nothing at all, so the engagement is - /// not an artefact of the code under test. - /// - /// lane-av1422lift: same scope change as its siblings, and this is the arm - /// where it matters most: this stream is the one where `read_lr` does - /// nothing at all, so a byte-exact green over it is a claim about the - /// per-axis path WITHOUT the loop-restoration corner fix carrying it. - /// The pin stays, the compare against ffmpeg's `yuv422p` rawvideo is - /// added per plane and per frame, and the per-plane coefficient-unit - /// census is the non-vacuity arm. - #[test] - fn the_pinned_422_lr_off_witness_decodes_pixel_exact() { - const NAME: &str = "the_pinned_422_lr_off_witness_decodes_pixel_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - const FILE: &str = "422_residual_compound_warp_nolr_16f.obu"; - const BYTES: usize = 38538; - const FP: u64 = 0x4b8ff761701e2bef; - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("fixtures") - .join(FILE); - let data = std::fs::read(&path).unwrap_or_else(|e| { - panic!( - "{NAME}: pinned witness {} is missing ({e}) -- the gate cannot run", - path.display() - ) - }); - assert_eq!(data.len(), BYTES, "{NAME}: {FILE} size drifted"); - assert_eq!(fnv1a64(&data), FP, "{NAME}: {FILE} bytes drifted"); - assert_422_stream_pixel_exact(NAME, &data, 256, 288, 16, 8, true); - } - - /// lane-av1422lift: 4:2:2 FILM GRAIN, and why this one gate cannot use - /// the dump path or the shared body above. - /// - /// `EC_AV1_FINAL_DUMP` writes the picture "exactly as it is about to be - /// stored into the reference slots" (`stream.rs`, the dump site beside - /// the emit), which is BEFORE `apply_grain` runs on the output. ffmpeg's - /// rawvideo is POST-grain. So every grain cell -- 4:2:0, 4:2:2, 12-bit, - /// all of them -- is incomparable through the dump, and the corpus - /// comparator hits it as a hard error rather than as a clean red - /// (measured on `s422_grain_160x128.obu`: "luma identity never covers the - /// display side (3 decode frames, 3 display frames)"). This gate - /// therefore compares the IN-MEMORY `decode_stream` output, which is - /// post-grain, exactly like - /// `a_real_aomenc_12bit_film_grain_stream_decodes_pixel_exact` does for - /// 12-bit 4:2:0. Using the pre-grain dump here would make the gate - /// permanently red for a reason that has nothing to do with grain. - /// - /// The pin, `s422_grain_160x128.obu` (5433 bytes, sha256 - /// `a4a6957b5e8298d9138f64498cab2d3008b3390fa73cd0d74aa0632b13d93d15`, - /// fnv1a64 `0x2aed47614b9461b8`), is aomenc profile 2 over a `C422` - /// testsrc2 160x128 3-frame source with `--film-grain-test=5`, - /// `--passes=1 --end-usage=q --cq-level=24 --cpu-used=0 --threads=1 - /// --row-mt=0 --limit=3 --obu`. - /// - /// Two arms, because a green compare over a stream whose grain never ran - /// is the "params-without-apply" false green: - /// - /// 1. the stream's OWN frame headers carry `apply_grain` and scaling - /// points on all THREE planes -- at 4:2:2 that is the shape libaom's - /// `generate_grain_uv_422` exists for, and it is read out of the - /// bytes, not out of the flags handed to the encoder; - /// 2. `film_grain::grain_hits()` moves across the decode. - #[test] - fn a_real_422_film_grain_stream_decodes_pixel_exact() { - const NAME: &str = "a_real_422_film_grain_stream_decodes_pixel_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - let _gate_lock = lock_gate_counters(); - let path = crate_pin("s422_grain_160x128.obu"); - let stream = read_pin(&path, 5433, 0x2aed47614b9461b8, NAME); - let mut probe = Av1Parser::new(); - let mut pos = 0usize; - let mut grain_frames = 0usize; - while pos < stream.len() { - let obu = probe.parse_obu(&stream[pos..]).unwrap(); - pos += obu.total_size; - if let ObuKind::Frame(header, _) = obu.kind { - let fg = &header.film_grain; - assert!( - fg.apply_grain, - "{NAME}: frame without apply_grain -- aomenc emitted params it does not apply" - ); - assert!( - fg.num_y_points > 0 && fg.num_cb_points > 0 && fg.num_cr_points > 0, - "{NAME}: grain without all three planes' scaling points -- the per-axis \ - `generate_grain_uv_422` geometry would not be exercised" - ); - grain_frames += 1; - } - } - assert_eq!( - grain_frames, 3, - "{NAME}: expected grain on all three frames" - ); - let before = crate::film_grain::grain_hits(); - let units_before = crate::decode::census_nonsub_units(); - let ours = decode_stream(&stream).unwrap_or_else(|e| { - panic!("{NAME}: decode_stream refused a real 4:2:2 grain stream: {e}") - }); - assert_eq!(ours.len(), 3, "{NAME}: decoded frame count"); - assert_eq!( - ours[0].u.len(), - 80 * 128, - "{NAME}: 160x128 4:2:2 chroma is 80x128; {} means a 4:2:0 plane", - ours[0].u.len() - ); - assert!( - crate::film_grain::grain_hits() > before, - "{NAME}: matched but zero grain_hits -- grain synthesis never ran" - ); - let units = crate::decode::census_nonsub_units(); - for (p, plane) in ["luma", "U", "V"].into_iter().enumerate() { - assert!( - units[p] > units_before[p], - "{NAME}: the {plane} plane walked ZERO coefficient units -- this byte-exact \ - compare is vacuous with respect to 4:2:2" - ); - } - let theirs = ffmpeg_decode_sequence_422(&stream, 160, 128, 3); - for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { - for (plane, ours_plane, theirs_plane) in - [("Y", &a.y, &b.y), ("U", &a.u, &b.u), ("V", &a.v, &b.v)] - { - if let Some(bad) = ours_plane - .iter() - .zip(theirs_plane) - .position(|(x, y)| x != y) - { - panic!( - "{NAME}: {plane} differs from ffmpeg at frame {i} sample {bad} ({} vs {})", - ours_plane[bad], theirs_plane[bad] - ); - } - } - } - eprintln!( - "{NAME}: post-grain byte-exact vs ffmpeg; grain_hits={}", - crate::film_grain::grain_hits() - ); - } - - /// lane-av1422lift: THE CORPUS BATTERY -- the gate the 4:2:2 campaign - /// earned, and the one that replaces seven gates whose only behavioural - /// assertion was `err.contains(REFUSAL)`. - /// - /// **Why these seven.** The measurement base - /// (`lanes/av1422ffmpegbase.report.md` section 2.1) recorded seven 4:2:2 - /// cells that diverged from ffmpeg: `s422_320x246`, `s422_322x240`, - /// `s422_322x246`, `s422_352x242_10b`, `s422_384x240`, - /// `s422_416x242_10b`, `s422_416x250_10b`. ALL SEVEN are closed and are - /// pinned here, each byte-exact against ffmpeg with the per-plane - /// coefficient-unit census as its non-vacuity arm. Six of them are - /// CHROMA-only divergences at non-8-aligned geometries -- odd or - /// 2-mod-4 luma dimensions, where `round_ss` and the chroma block walk - /// disagree with a hardcoded `>> 1` -- which is why they are the rows a - /// lift cannot afford to leave unasserted: they are the cells that would - /// go quietly wrong again. - /// - /// **The seventh, `s422_384x240`, IS here now.** lane-av1422lift pinned six - /// of the seven and deliberately left this one out: it was still red, and - /// pinning a red cell inside a green gate is how a gate stops being a gate - /// ("THIS BRANCH MUST NOT LAND UNTIL THAT CELL CLOSES AND THE CORPUS - /// RE-MEASURES 51/51", `lanes/av1422lift.report.md` §7). The cell closed in - /// lane-av1422tailskip, and NOT through the reserved group-tail chroma SKIP - /// arm the risk study's R4 blamed: that lane measured it byte-exact against - /// ffmpeg on all 16 displayed frames and all 17 decode-order frames, 0/0/0 - /// wrong samples in Y/U/V, with the fix's own counter - /// (`palette_422_unit_window_hits`) non-zero on this stream. - /// `lanes/av1422tailskip.report.md` §1 records the measurement and the - /// refutation of the arm attribution. - /// - /// That lane had already committed these exact bytes under the name - /// `422_palette_intra_in_inter_384x240_17f.obu` (sha256 `bf1c658e...a815b`, - /// the sweep artifact byte for byte), so the row below pins THAT file - /// rather than committing a second copy of one stream under a second name. - /// Unlike the other six, this cell sits at an 8- AND 16-aligned geometry - /// (384x240): it was the late-starting frame-1 alt-ref chroma residual - /// (`lanes/av1422late.report.md`), not the `round_ss` class -- which is why - /// it is pinned as its own row here rather than folded into that sentence. - /// - /// **The corpus re-measures 51/51**, which was the second half of the - /// condition the paragraph above quotes. Re-run for this row with the - /// ffmpeg-oracle census driver (`~/.cache/census422b/ffcensus.py`: display - /// order, shown frames, geometry from `ffprobe`, a count over zero frames - /// is a hard error) and a `dump_yuv` built from THIS lane's tree: - /// **51 of 51 4:2:2 cells BYTE-EXACT** -- `s422_384x240` among them at - /// 0/0/0 -- and, in the same run, all 44 4:2:0 / 4:4:4 controls BYTE-EXACT - /// (95/95 over the whole corpus). That run is a measurement of this tree, - /// not a re-reading of the closure report; the per-cell rows here are what - /// keep the seven named ones from drifting back. - /// - /// **The census arm, per row.** `assert_422_stream_pixel_exact` asserts - /// that all three planes read a non-zero number of coefficient units AND - /// a non-zero number of units that coded at least one coefficient, on - /// this row's own bytes. That is the requirement R8 named as unwritable - /// before lane-av1422census422 armed the census for `(1,0)`; measured on - /// this tree the OLD arming read `[0, 0, 0]` on every 4:2:2 cell while - /// the same decode walked 4994 units, so a green here with no census - /// assert would have proven nothing about 4:2:2. - /// - /// **Provenance of the seven pins.** All seven are `aomenc --codec=av1 - /// --profile=2 --input-bit-depth=<8|10> --cpu-used=0 --cq-level=24 - /// --limit=16 --auto-alt-ref=1 --enable-global-motion=1 --passes=1 - /// --obu` over a hand-built `C422` y4m (header line, then `FRAME\n` plus - /// one frame of planes per frame -- libaom's y4minput requires those six - /// bytes before EVERY frame), produced by the census sweep. The first six - /// were copied in from `~/.cache/census422b/sweep/`; the seventh is the - /// same sweep's `s422_384x240.obu`, which lane-av1422tailskip had already - /// committed under the name in its own row (the two files are byte for - /// byte identical -- sha256 `bf1c658e9bfdc13ec1ed51e59049d2b81201941b6ef45\ - /// 71f8382f356ea4b815b`), so it is pinned under that name here. They are - /// ordinary libaom 4:2:2 streams with nothing bolted on. - #[test] - fn the_pinned_422_corpus_cells_decode_pixel_exact() { - const NAME: &str = "the_pinned_422_corpus_cells_decode_pixel_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - // (file, bytes, fnv1a64, sha256, w, h, depth, frames) - for (file, bytes, fp, sha, w, h, depth, frames) in [ - ( - "s422_320x246.obu", - 20692usize, - 0x01e556015878e04eu64, - "aebd3a10d46e617b803579819f2502798076384be52e032b11b46f09eeb09a79", - 320usize, - 246usize, - 8u8, - 16usize, - ), - ( - "s422_322x240.obu", - 21096, - 0x9a96dda2a19d47a6, - "e74bf7e91f23353986edf9380bcd6cb760194e619dbbdf6a239b7a05eff81799", - 322, - 240, - 8, - 16, - ), - ( - "s422_322x246.obu", - 20528, - 0x2c6f8be6d30384ab, - "ee96617fe45ba963d3628f37086077a94806ef0465a74cb538a8e57d2ed900b3", - 322, - 246, - 8, - 16, - ), - ( - "s422_352x242_10b.obu", - 20575, - 0xf1d370f80d8ddc6d, - "8893bbed108d7555e66c35f2f45d6e44044dcd6810b0510fb251be05dabaa2d0", - 352, - 242, - 10, - 16, - ), - ( - "s422_416x242_10b.obu", - 20282, - 0x9826402d91abbc56, - "38d0b592e5e358901742122c590c8964b5d08d0ceccfa051e677c28f4b75d174", - 416, - 242, - 10, - 16, - ), - ( - "s422_416x250_10b.obu", - 19967, - 0x6b07e837eae8a6be, - "d6aa7f450f54d6fb381400a0a0226da87599c00509eeb5031abe63383e272627", - 416, - 250, - 10, - 16, - ), - ( - // Census cell `s422_384x240` -- the seventh previously - // diverging cell, closed by lane-av1422tailskip. Same bytes as - // the sweep's `s422_384x240.obu`, already in this fixtures dir - // under the name lane-av1422tailskip's own gate pins. - "422_palette_intra_in_inter_384x240_17f.obu", - 19344usize, - 0x923ccabfcb933e90u64, - "bf1c658e9bfdc13ec1ed51e59049d2b81201941b6ef4571f8382f356ea4b815b", - 384usize, - 240usize, - 8u8, - 16usize, - ), - ] { - let row = format!("{NAME}[{file}]"); - let path = crate_pin(file); - let data = std::fs::read(&path).unwrap_or_else(|e| { - panic!( - "{row}: pinned corpus cell {} is missing ({e}) -- the gate cannot run", - path.display() - ) - }); - assert_eq!(data.len(), bytes, "{row}: size drifted"); - assert_eq!(fnv1a64(&data), fp, "{row}: bytes drifted"); - // The sha256 is the corpus's own identity column (its - // `cells_422_3d56.json` records one per cell and the census - // verified zero drift); fnv1a64 is what `read_pin` can check - // in-process without spawning sha256sum, so both are named and - // the sha256 is what a re-capture must reproduce. - eprintln!("{row}: sha256 {sha}"); - assert_422_stream_pixel_exact(&row, &data, w, h, frames, depth, true); - } - } - - /// lane-av1-qmatrix: WITNESS for the lifted `using_qmatrix` refusal (the - /// old gate `a_frame_using_quantisation_matrices_is_refused_by_name` is - /// its mirror image -- its own panic said "flip this gate to a witness" - /// the moment the dequant landed). - /// - /// A REAL `aomenc --enable-qm=1` stream (same source and recipe as the - /// refusal's gate, plus its `--enable-qm=0` control) now DECODES, and - /// every frame of both arms is pixel-exact against ffmpeg's own decode - /// of the same OBU. The census proves the feature non-vacuously both - /// ways (class `gate-blind-to-feature`): the parsed frame headers really - /// carry `using_qmatrix = 1`, the dequantiser really SCALED transform - /// units through a matrix on the qm-on arm (`qm_scaled_units() > 0`), - /// and the qm-off control really scaled none (`== 0`). - #[test] - fn a_real_aomenc_quantisation_matrix_stream_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_quantisation_matrix_stream_decodes_pixel_exact"; - if !have_ffmpeg() || !have_aomenc() { - eprintln!( - "SKIP {NAME}: needs ffmpeg + an aomenc oracle at {}", - aomenc_path().display() - ); - return; - } - const W: usize = 128; - const H: usize = 96; - const FRAMES: usize = 3; - // Every frame header's (using_qmatrix, qm_y, qm_u, qm_v), parsed - // straight off the encoded bytes. - let qm_headers = |stream: &[u8]| -> Vec<(bool, u8, u8, u8)> { - let mut parser = Av1Parser::new(); - let mut pos = 0usize; - let mut out = Vec::new(); - while pos < stream.len() { - let obu = parser.parse_obu(&stream[pos..]).unwrap(); - pos += obu.total_size; - if let ObuKind::Frame(header, _) = obu.kind { - let q = &header.quantization; - out.push((q.using_qmatrix, q.qm_y, q.qm_u, q.qm_v)); - } - } - out - }; - // `census_attempt` hands back only the stream LENGTH; this witness - // needs the BYTES to hand ffmpeg, so the same recipe (its base args - // verbatim, `testsrc2` 128x96 @ 25fps, 3 frames) runs inline. - let encode = |extra: &[&str]| -> Vec { - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &format!("testsrc2=size={W}x{H}:rate=25"), - "-t", - "0.12", - "-pix_fmt", - "yuv420p", - "-strict", - "-1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!(y4m.status.success(), "ffmpeg refused the {W}x{H} fixture"); - let mut args: Vec = [ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--threads=1", - "--row-mt=0", - "--kf-max-dist=9999", - "--lag-in-frames=0", - ] - .iter() - .map(|s| (*s).to_owned()) - .collect(); - args.push(format!("--limit={FRAMES}")); - args.extend(extra.iter().map(|s| (*s).to_owned())); - args.extend([ - "--obu".to_owned(), - "-o".to_owned(), - "-".to_owned(), - "-".to_owned(), - ]); - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused {args:?}: {}", - String::from_utf8_lossy(&out.stderr) - ); - out.stdout - }; - // Pixel-exact every decoded frame of `stream` against ffmpeg, plane - // by plane, first differing sample named. - let compare = |stream: &[u8], frames: usize, label: &str| { - let want = ffmpeg_decode_sequence(stream, W, H, frames); - let got = - decode_stream(stream).unwrap_or_else(|e| panic!("{NAME}: {label} decode: {e}")); - assert_eq!(got.len(), want.len(), "{NAME}: {label} frame count"); - for (i, (g, w)) in got.iter().zip(want.iter()).enumerate() { - for (plane, (gp, wp)) in [(&g.y, &w.y), (&g.u, &w.u), (&g.v, &w.v)] - .into_iter() - .enumerate() - { - assert_eq!( - gp, - wp, - "{NAME}: {label} frame {i} plane {plane} differs from ffmpeg (first mismatching sample: got {}, want {})", - gp.iter() - .zip(wp.iter()) - .find(|(a, b)| a != b) - .map_or(0, |(a, _)| *a), - gp.iter() - .zip(wp.iter()) - .find(|(a, b)| a != b) - .map_or(0, |(_, b)| *b) - ); - } - } - }; - - // CONTROL: the same source and recipe with quantisation matrices OFF - // -- unchanged by this lane, and it must not scale a single unit - // through a matrix. - crate::quant::reset_qm_scaled_units(); - let control_stream = encode(&["--enable-qm=0"]); - let control_frames = decode_stream(&control_stream) - .unwrap_or_else(|e| panic!("{NAME}: the --enable-qm=0 control must decode, got: {e}")) - .len(); - assert!( - control_frames >= 1, - "{NAME}: the qm-off control decoded no frame" - ); - for (using, y, u, v) in qm_headers(&control_stream) { - assert!( - !using, - "{NAME}: the control's frame header set using_qmatrix" - ); - assert_eq!( - (y, u, v), - (0, 0, 0), - "{NAME}: the control's frame header carried qm levels {y}/{u}/{v}" - ); - } - compare(&control_stream, control_frames, "qm-off control"); - assert_eq!( - crate::quant::qm_scaled_units(), - 0, - "{NAME}: the qm-off control scaled units through a matrix" - ); - - // The qm-on stream: decodes now, pixel-exact, levels 5 per plane as - // aomenc writes them. - crate::quant::reset_qm_scaled_units(); - let qm_stream = encode(&["--enable-qm=1"]); - let qm_frames = decode_stream(&qm_stream) - .unwrap_or_else(|e| panic!("{NAME}: the --enable-qm=1 stream must decode, got: {e}")) - .len(); - assert!(qm_frames >= 1, "{NAME}: the qm-on stream decoded no frame"); - let headers = qm_headers(&qm_stream); - assert!( - !headers.is_empty() && headers.iter().all(|h| h.0), - "{NAME}: not every qm-on frame header set using_qmatrix: {headers:?}" - ); - assert!( - headers.iter().all(|h| (h.1, h.2, h.3) == (5, 5, 5)), - "{NAME}: expected aomenc's qm levels 5/5/5, got {headers:?}" - ); - compare(&qm_stream, qm_frames, "qm-on"); - let scaled = crate::quant::qm_scaled_units(); - assert!( - scaled > 0, - "{NAME}: the --enable-qm=1 stream dequantized every unit flat -- \ - the matrices were never applied (class gate-blind-to-feature)" - ); - eprintln!( - "{NAME}: qm-off control {control_frames} frames exact (0 matrix-scaled units), \ - qm-on {qm_frames} frames exact ({scaled} matrix-scaled units, levels 5/5/5)" - ); - } - - /// lane-av1mono: the INVERSE of the pilot's - /// `a_real_libaom_monochrome_key_frame_is_refused_by_name`, which the - /// pilot's merge `d71084ae` landed on `main` (after this lane's base - /// `7f4e8301`): the very same recipe now decodes, and its luma is - /// byte-exact against ffmpeg's own decode of the same OBU. A merge of this - /// lane into `main` must therefore resolve that pinning gate by adopting - /// this witness in its place. - /// - /// `ffmpeg -pix_fmt gray -c:v libaom-av1` sets `color_config.mono_chrome`, - /// so libaom codes NO chroma symbol anywhere in the sequence -- not the - /// mode syntax, not a coefficient. That reaches all three classes this lane - /// had to close: chroma SYMBOL reads (`uv_mode`/cfl/angle/palette), chroma - /// COEFFICIENT reads on the rect-strip paths that call `read_coeffs_rect` - /// DIRECTLY instead of through `read_plane`'s own plane gate, and the - /// palette-mode neighbour band a mono sub-8x8 leaf must still clear before - /// it returns (an uncleared band made the next block read `palette_y_mode` - /// off the wrong CDF row and silently desynced the rest of the tile -- - /// measured at decode-order frame 33 of this very recipe). - /// - /// The 4:2:0 twin of the same source and settings is the control: it proves - /// the recipe is decodable, so a failure here is about the plane count and - /// not about the source or the encoder settings. - #[test] - fn a_real_libaom_monochrome_key_frame_decodes_pixel_exact() { - const NAME: &str = "a_real_libaom_monochrome_key_frame_decodes_pixel_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - let emit = |pix: &str| -> Vec { - let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - "testsrc2=size=320x240:rate=30:duration=2", - "-pix_fmt", - pix, - "-c:v", - "libaom-av1", - "-cpu-used", - "8", - "-b:v", - "300k", - "-f", - "obu", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - out.status.success(), - "{NAME}: ffmpeg ({pix}) failed: {}", - String::from_utf8_lossy(&out.stderr) - ); - out.stdout - }; - // CONTROL: the identical recipe at 4:2:0 still decodes. - let twin = decode_stream(&emit("yuv420p")).expect("the 4:2:0 twin must decode"); - assert!(!twin.is_empty(), "{NAME}: the 4:2:0 twin decoded no frames"); - // THE WITNESS: the monochrome stream decodes and every luma sample - // equals ffmpeg's own decode of the same OBU. - let gray = emit("gray"); - let ours = decode_stream(&gray) - .unwrap_or_else(|e| panic!("{NAME}: the monochrome stream is REFUSED again: {e}")); - let (width, height) = (320usize, 240usize); - const FRAMES: usize = 60; - assert_eq!(ours.len(), FRAMES, "{NAME}: expected {FRAMES} mono frames"); - let reference = ffmpeg_decode_gray_sequence(&gray, width, height, FRAMES); - for (i, plane) in reference.chunks_exact(width * height).enumerate() { - assert_eq!(ours[i].width, width, "{NAME}: frame {i} width"); - assert_eq!(ours[i].height, height, "{NAME}: frame {i} height"); - assert_eq!( - ours[i].y.len(), - width * height, - "{NAME}: frame {i} luma length" - ); - for (j, (got, want)) in plane.iter().zip(ours[i].y.iter()).enumerate() { - assert_eq!( - *want, - u16::from(*got), - "{NAME}: frame {i} luma sample {j} (row {}, col {}) is {want}, ffmpeg says {got}", - j / width, - j % width - ); - } - } - eprintln!( - "{NAME}: 4:2:0 twin {} frames, monochrome {} frames byte-exact vs ffmpeg", - twin.len(), - ours.len() - ); - } - - /// lane-t900 r25: the refusal "a frame OBU with no tile group" names a - /// shape the parser cannot hand [`decode_stream`]. - /// - /// `tiles` reaches that check from exactly two places -- `ObuKind::Frame`'s - /// own vector and the `ObuKind::TileGroup` accumulation -- and both are - /// filled by `ec_av1_syntax`'s `parse_tile_group`, whose only success path - /// pushes one `Tile` per `tile_num` of the INCLUSIVE range - /// `tg_start..=tg_end`. That range is never empty: the single-tile-group - /// case takes `(0, num_tiles - 1)` saturating at 0, and the multi-group - /// case rejects `end < start` as corrupt. So an `OBU_FRAME` either fails to - /// parse or carries at least one tile, however short its payload is -- - /// including the empty payload the charter for this round asked to build, - /// which parses into ONE zero-byte tile rather than none. - /// - /// Sweeping a real frame OBU's tile payload from empty upwards asserts both - /// halves: every `Frame` OBU that parses has a tile, and `decode_stream` - /// never reports this refusal for any of them. - #[test] - fn a_frame_obu_that_parses_always_carries_at_least_one_tile() { - let fctx = &crate::decode::FrameCtx::new(); - const REFUSAL: &str = "a frame OBU with no tile group"; - let picture = test_card(64, 64); - let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); - let (seq, header) = crate::encode::key_frame_headers(64, 64, 100).unwrap(); - let mut frame_obus_parsed = 0; - for len in 0..=encoded.tile.len().min(24) { - let mut stream = crate::sequence::sequence_header_obu(&seq).unwrap(); - stream.extend_from_slice( - &crate::frame::frame_obu(&seq, &header, &encoded.tile[..len]).unwrap(), - ); - let mut parser = Av1Parser::new(); - let mut pos = 0usize; - while pos < stream.len() { - let Ok(obu) = parser.parse_obu(&stream[pos..]) else { - break; - }; - pos += obu.total_size; - if let ObuKind::Frame(_, tiles) = &obu.kind { - frame_obus_parsed += 1; - assert!( - !tiles.is_empty(), - "a {len}-byte tile payload parsed into a frame OBU with no tile group -- \ - the refusal {REFUSAL:?} is reachable after all" - ); - } - } - if let Err(e) = decode_stream(&stream) { - let e = e.to_string(); - assert!( - !e.contains(REFUSAL), - "a {len}-byte tile payload reached {REFUSAL:?}: {e}" - ); - } - } - assert!( - frame_obus_parsed >= 2, - "the sweep parsed {frame_obus_parsed} frame OBUs -- it proves nothing about the \ - refusal's reachability" - ); - } - - /// lane-t900 r27, negative gate: a frame whose segmentation enables one of - /// the three MODE-OVERRIDING features -- `SEG_LVL_REF_FRAME` (forces a - /// block's reference), `SEG_LVL_SKIP` and `SEG_LVL_GLOBALMV` (both - /// suppress symbols `decode_inter_block` reads unconditionally) -- is - /// refused BY NAME and outputs no picture, rather than desyncing on the - /// first block that would have obeyed the override. - /// - /// Written, not hand-built: `write_segmentation_params` (spec 5.9.14) - /// codes `feature_enabled`/`feature_data` for every segment, so a real - /// key frame carrying the flag is a two-line change to the header the - /// encoder already produced. Swept over all three features and over the - /// first, a middle and the last segment id. - #[test] - fn a_frame_whose_segmentation_overrides_a_block_mode_is_refused_by_name() { - let fctx = &crate::decode::FrameCtx::new(); - const REFUSAL: &str = "a frame whose segmentation enables SEG_LVL_REF_FRAME/SKIP/GLOBALMV"; - let picture = test_card(64, 64); - let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); - let (seq, key) = crate::encode::key_frame_headers(64, 64, 100).unwrap(); - for feature in [SEG_LVL_REF_FRAME, SEG_LVL_SKIP, SEG_LVL_GLOBALMV] { - for segment in [0usize, 3, 7] { - let mut header = key.clone(); - header.segmentation.enabled = true; - header.segmentation.update_map = true; - header.segmentation.update_data = true; - header.segmentation.feature_enabled[segment][feature] = true; - header.segmentation.feature_data[segment][feature] = 1; - let mut stream = crate::sequence::sequence_header_obu(&seq).unwrap(); - stream.extend_from_slice( - &crate::frame::frame_obu(&seq, &header, &encoded.tile).unwrap(), - ); - let mut shown = 0; - let err = decode_stream_with(&stream, |_, _, _| { - shown += 1; - Ok(()) - }) - .unwrap_err() - .to_string(); - assert!( - err.contains(REFUSAL), - "feature {feature} segment {segment}: expected {REFUSAL:?}, got: {err}" - ); - assert_eq!( - shown, 0, - "feature {feature} segment {segment}: a refused frame produced a picture" - ); - } - } - } - - /// lane-hdrlossless WITNESS → lane-av1mixloss LIFT. `--end-usage=q - /// --cq-level=0 --aq-mode=1` (variance AQ over a lossless base) gives a - /// high-variance segment a positive `SEG_LVL_ALT_Q` while a flat segment - /// stays at `qindex == 0` (`aq_variance.c` sets `SEG_LVL_ALT_Q` per - /// segment and only clamps when `base_qindex != 0`, so a lossless base is - /// exactly where the mixed case comes from): a frame MIXING lossless and - /// lossy segments, which this decoder refused by name until the - /// per-segment lossless table (libaom `decodeframe.c:5205`, - /// `xd->lossless[segment_id]`; `read_tx_size` returns TX_4X4 before it - /// reads a symbol, `decodeframe.c:1170`) landed. Non-vacuity, three ways: - /// (1) the header census proves the arms REALLY carry a mixed frame - /// (class `gate-blind-to-feature` -- variance AQ over a lossless base is - /// the whole point, not the flag spelling), (2) the WHT-unit counter - /// proves the per-segment lossless reconstruction really ran, and (3) - /// every decoded plane is compared SAMPLE-EXACT against ffmpeg's libaom, - /// which accepts the same stream -- so the old refusal named a capability - /// gap, and this gate now proves the gap closed on a real encoder output. - #[test] - fn a_real_aomenc_mixed_lossless_segment_frame_decodes_sample_exact() { - const NAME: &str = "a_real_aomenc_mixed_lossless_segment_frame_decodes_sample_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - const FRAMES: usize = 4; - const WIDTH: usize = 256; - const HEIGHT: usize = 192; - // (source, per-arm overrides). `--end-usage=q --cq-level=0` is the - // lossless base; `--aq-mode=1` is variance AQ, the only aomenc path - // that sets `SEG_LVL_ALT_Q` with no clamp at base 0 (`aq_variance.c`). - // Several arms because the segment split depends on the encoder's own - // variance decisions (class knob-never-reached-the-tool: require at - // least one arm to actually mix, and fail if none does). - let arms: [(&str, &[&str]); 3] = [ - ( - "testsrc2=size=256x192:rate=25", - &[ - "--end-usage=q", - "--cq-level=0", - "--aq-mode=1", - "--good", - "--cpu-used=3", - "--sb-size=64", - ], - ), - ( - "testsrc2=size=256x192:rate=25", - &[ - "--end-usage=q", - "--cq-level=0", - "--aq-mode=1", - "--good", - "--cpu-used=5", - "--sb-size=64", - ], - ), - ( - "gradients=size=256x192:rate=25", - &[ - "--end-usage=q", - "--cq-level=0", - "--aq-mode=1", - "--good", - "--cpu-used=6", - "--sb-size=64", - ], - ), - ]; - let mut mixed_arms = 0usize; - // The WHT-unit delta below is a process-wide counter: serialize the - // arms against the other counter-reading gates. - let _gate_lock = lock_gate_counters(); - for (src, extra) in &arms { - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - *src, - "-t", - "0.16", - "-pix_fmt", - "yuv420p", - "-strict", - "-1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!(y4m.status.success(), "{NAME}: ffmpeg failed for {src}"); - let limit = format!("--limit={FRAMES}"); - let mut args: Vec = [ - "--codec=av1", - "--passes=1", - "--threads=1", - "--obu", - "-o", - "-", - "-", - ] - .iter() - .map(|s| (*s).to_owned()) - .collect(); - args.insert(1, limit); - args.extend(extra.iter().map(|s| (*s).to_owned())); - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "{NAME}: aomenc refused {args:?}: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - // (2) the stream really carries a frame the old refusal named. - let mut parser = Av1Parser::new(); - let (mut pos, mut mixed) = (0usize, 0usize); - while pos < stream.len() { - let obu = parser.parse_obu(&stream[pos..]).expect("aomenc OBU parses"); - pos += obu.total_size.max(1); - let header = match &obu.kind { - ObuKind::FrameHeader(h) | ObuKind::Frame(h, _) => h, - _ => continue, - }; - if header.lossless.iter().any(|&l| l) && !header.lossless.iter().all(|&l| l) { - mixed += 1; - } - } - if mixed == 0 { - eprintln!("{NAME}: arm {extra:?} coded no mixed frame -- trying the next"); - continue; - } - // (3) ours DECODES it, sample-exact against ffmpeg's libaom (the - // reference decode doubles as the libaom-accepts proof). The - // WHT-unit delta proves the per-segment lossless reconstruction - // really ran inside a frame that is NOT `CodedLossless`. - let before = crate::decode::lossless_wht_units(); - let ours = decode_stream(&stream).unwrap_or_else(|e| { - panic!("{NAME}: a mixed-lossless frame decodes after the per-segment lift: {e}") - }); - let wht_units = crate::decode::lossless_wht_units() - before; - let refs = ffmpeg_decode_sequence(&stream, WIDTH, HEIGHT, FRAMES); - assert_eq!(ours.len(), FRAMES, "{NAME}: frame count"); - for (i, (got, want)) in ours.iter().zip(refs.iter()).enumerate() { - for (plane, (g, r)) in [(&got.y, &want.y), (&got.u, &want.u), (&got.v, &want.v)] - .iter() - .enumerate() - { - let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count(); - assert_eq!( - bad, 0, - "{NAME}: arm {extra:?} frame {i} plane {plane}: {bad} samples differ" - ); - assert_eq!( - g.len(), - r.len(), - "{NAME}: arm {extra:?} frame {i} plane {plane}: ours has {} samples, \ - ffmpeg's has {} -- a short plane would zip-truncate the compare above \ - and hide a chroma-span defect", - g.len(), - r.len() - ); - } - } - assert!( - wht_units > 0, - "{NAME}: arm {extra:?} reconstructed no Walsh-Hadamard unit -- the mixed census is lying or the lossless path never ran" - ); - mixed_arms += 1; - eprintln!( - "{NAME}: arm {extra:?}: {mixed} mixed frame(s), {FRAMES} frames sample-exact vs ffmpeg, {wht_units} WHT units" - ); - } - assert!( - mixed_arms > 0, - "{NAME}: no arm produced a mixed lossless/lossy frame -- the witness is vacuous \ - (re-measure the aomenc recipe)" - ); - } - - /// lane-t900 r27 CENSUS behind the negative gate above: does a real - /// aomenc ever ENABLE one of the three mode-overriding segmentation - /// features? Measured over the recipes that turn segmentation on -- - /// `--aq-mode=1/2/3` (variance, complexity and cyclic-refresh AQ) and - /// `--deltaq-mode=1` -- with the refusal as the instrument: if one of - /// those features appeared, the decode would stop by name. - /// - /// lane-av1seglvl re-scope: r27's arms were all `--passes=1 - /// --lag-in-frames=0`, so they never coded an alt-ref frame or ran an - /// encoder second pass -- the only shapes where libaom's OTHER seg - /// feature setup (`configure_static_seg_features`) could ever run. The - /// re-scoped half below adds alt-ref-group arms and a real two-pass arm, - /// and upgrades the instrument from the refusal (blind to a pure-ALT_LF - /// stream) to a direct parse of every frame header's `feature_enabled` - /// table: over all of it, aomenc enables `SEG_LVL_ALT_Q` and nothing - /// else. - #[test] - fn a_segmentation_census_over_real_aq_streams_finds_no_mode_overriding_feature() { - if !have_aomenc() { - eprintln!("SKIP a_segmentation_census_over_real_aq_streams: no aomenc"); - return; - } - const REFUSAL: &str = "a frame whose segmentation enables SEG_LVL_REF_FRAME/SKIP/GLOBALMV"; - let recipes: [(&str, Vec<&str>); 6] = [ - ("baseline", vec!["--cpu-used=4", "--cq-level=40"]), - ( - "aq-mode=1", - vec!["--cpu-used=4", "--aq-mode=1", "--cq-level=40"], - ), - ( - "aq-mode=2", - vec!["--cpu-used=4", "--aq-mode=2", "--cq-level=40"], - ), - ( - "aq-mode=3", - vec!["--cpu-used=4", "--aq-mode=3", "--cq-level=40"], - ), - ( - "aq-mode=3 cq10", - vec!["--cpu-used=4", "--aq-mode=3", "--cq-level=10"], - ), - ( - "deltaq-mode=1", - vec!["--cpu-used=4", "--deltaq-mode=1", "--cq-level=40"], - ), - ]; - // Arrival, not intent (class knob-never-reached-the-tool): a recipe - // whose stream is byte-for-byte the baseline's changed nothing, and a - // census over such arms would be vacuous. Measured r27: only - // `--aq-mode=3` (cyclic refresh) does -- aq-mode 1/2 and deltaq-mode=1 - // all reproduce the baseline's 7147 B at this recipe. - let mut baseline_bytes = 0usize; - let mut segment_symbols = 0usize; - let mut refused = 0usize; - let mut decoded = 0usize; - for (name, extra) in &recipes { - let before = crate::decode::segment_id_hits(); - let (bytes, result) = census_attempt("mandelbrot", 192, 128, 8, extra); - match result { - Ok(pictures) => { - decoded += 1; - let symbols = crate::decode::segment_id_hits() - before; - segment_symbols += symbols; - if *name == "baseline" { - baseline_bytes = bytes; - } - eprintln!( - "SEGCENSUS {name}: {bytes} B{}, {pictures} pictures, segment_id symbols {symbols}", - if bytes == baseline_bytes && *name != "baseline" { - " (== baseline: the flag changed nothing)" - } else { - "" - } - ); - } - Err(e) => { - eprintln!("SEGCENSUS {name}: {bytes} B, refused: {e}"); - assert!( - !e.contains(REFUSAL), - "{name}: a real aomenc stream DOES enable a mode-overriding \ - segmentation feature -- the refusal is a capability gap, not a \ - claim about the encoder: {e}" - ); - refused += 1; - } - } - } - eprintln!( - "SEGCENSUS: {} recipes, {decoded} decoded, {refused} refused for other reasons", - recipes.len() - ); - assert_eq!( - decoded, - recipes.len(), - "every recipe must decode; {refused} refused" - ); - assert!( - segment_symbols > 0, - "no recipe coded a single segment_id symbol -- segmentation never arrived, so \ - this census measures nothing about the three mode-overriding features" - ); - - // lane-av1seglvl re-scope: the r27 arms above are all `--passes=1 - // --lag-in-frames=0`, which never codes an alt-ref frame -- the one - // frame type whose segmentation libaom sets up differently - // (`configure_static_seg_features`, encoder_utils.c:738, is further - // gated on the second pass AND on `hl_sf.static_segmentation`, which - // speed_features.h itself documents as "Always set to 0"). The arms - // below cover that whole remaining surface: alt-ref groups under - // `--aq-mode`, a high-cq arm (the branch's own `high_q` gate is - // `avg_q > 48`), and a genuine two-pass encode. The instrument is no - // longer the refusal -- the refusal only fires on - // REF_FRAME/SKIP/GLOBALMV, so an ALT_LF-only stream would decode - // silently past it -- but a direct parse of every frame header's - // `feature_enabled` table. - let lag_recipes: [(&str, &str, usize, usize, Vec<&str>); 3] = [ - ( - "aq-mode=1 lag16 mandelbrot", - "mandelbrot", - 192, - 128, - vec![ - "--cpu-used=4", - "--aq-mode=1", - "--cq-level=45", - "--lag-in-frames=16", - "--auto-alt-ref=1", - ], - ), - ( - "aq-mode=1 lag16 screen", - "testsrc2", - 256, - 192, - vec![ - "--cpu-used=4", - "--aq-mode=1", - "--cq-level=45", - "--lag-in-frames=16", - "--auto-alt-ref=1", - ], - ), - ( - "aq-mode=1 lag16 cq63 high_q", - "mandelbrot", - 192, - 128, - vec![ - "--cpu-used=4", - "--aq-mode=1", - "--cq-level=63", - "--lag-in-frames=16", - "--auto-alt-ref=1", - ], - ), - // `--aq-mode=2 lag16` (complexity AQ over an alt-ref group) was - // measured 2026-09-24: it encodes and decodes cleanly but codes - // ZERO segmentation-enabled frames -- complexity AQ never reaches - // the seg table at this recipe -- so as a census arm it measures - // nothing (class gate-blind-to-feature) and was dropped; the - // 1-pass `aq-mode=2` r27 arm above stays. - ]; - let mut total_enabled = 0usize; - let mut total_inherited = 0usize; - let mut total_alt_q = 0usize; - let mut feature_frames = [0usize; SEG_LVL_MAX]; - for (name, source, w, h, extra) in &lag_recipes { - let stream = encode_aomenc_stream(source, *w, *h, 40, extra); - let (enabled, umap, inherited, alt_q, frames_per_feature) = - segmentation_feature_census(&stream); - eprintln!( - "SEGCENSUS {name}: seg-enabled {enabled}, update_map {umap}, inherited {inherited}, ALT_Q {alt_q}, per-feature {frames_per_feature:?}" - ); - total_enabled += enabled; - total_inherited += inherited; - total_alt_q += alt_q; - for (f, n) in frames_per_feature.iter().enumerate() { - feature_frames[f] += n; - } - } - // The two-pass arm: `configure_static_seg_features` runs ONLY at - // `is_stat_consumption_stage_twopass`, so this is the arm that would - // catch its ALT_LF/REF_FRAME/SKIP tables if the dead speed feature - // were ever revived. - { - let stream = encode_aomenc_stream_twopass( - "mandelbrot", - 192, - 128, - 40, - &[ - "--cpu-used=4", - "--aq-mode=1", - "--cq-level=45", - "--lag-in-frames=16", - "--auto-alt-ref=1", - ], - ); - let (enabled, umap, inherited, alt_q, frames_per_feature) = - segmentation_feature_census(&stream); - eprintln!( - "SEGCENSUS twopass aq-mode=1 lag16: seg-enabled {enabled}, update_map {umap}, inherited {inherited}, ALT_Q {alt_q}, per-feature {frames_per_feature:?}" - ); - total_enabled += enabled; - total_inherited += inherited; - total_alt_q += alt_q; - for (f, n) in frames_per_feature.iter().enumerate() { - feature_frames[f] += n; - } - } - // Premise (class gate-blind-to-feature): the arms must actually reach - // the shapes the census speaks about -- segmentation-carrying frames, - // frames whose map is INHERITED (update_map == 0), and frames with a - // real ALT_Q table -- or the "only ALT_Q" verdict below measures - // nothing. - assert!( - total_enabled > 0 && total_alt_q > 0, - "no lag/two-pass arm carried a segmentation-enabled frame -- the census premise \ - never arrived" - ); - assert!( - total_inherited > 0, - "no arm carried an update_map == 0 frame -- the map-inheritance path the decoder \ - reads segment ids through is unmeasured" - ); - // The census verdict, over every frame of every arm: segmentation on - // aomenc's CLI carries SEG_LVL_ALT_Q and NOTHING else. The three - // mode-overriding features and the four ALT_LF deltas have no encoder - // path: `configure_static_seg_features` (the only setter of ALT_LF/ - // REF_FRAME/SKIP in the tree) is gated on `hl_sf.static_segmentation`, - // documented "Always set to 0" (speed_features.h), and ROI/active-map - // are control-API only (aomenc.c has no flag for either). - for (feature, frames) in feature_frames.iter().enumerate() { - if feature == SEG_LVL_ALT_Q { - continue; - } - assert_eq!( - *frames, 0, - "feature index {feature} appeared on {frames} frames of real aomenc output -- \ - the refusal's encoder-never-writes claim is FALSE and the mode path needs \ - porting before this census can stay green" - ); - } - eprintln!( - "SEGCENSUS lag/twopass: {total_enabled} seg-enabled frames over 4 arms, {total_inherited} inherited-map frames, {total_alt_q} with ALT_Q, all other SEG_LVL features: 0 frames" - ); - } - - /// lane-av1seglvl WITNESS: the reaching stream. `--aq-mode=1` turns - /// segmentation on for every frame; `--lag-in-frames=16 --auto-alt-ref=1` - /// adds real alt-ref groups, so the stream mixes map-CODING frames - /// (`update_map == 1`: the key frame and each group's arf) with dozens of - /// map-INHERITING frames (`update_map == 0`), and an inheriting block's - /// id is the MIN of the previous map over its own footprint while the - /// saved map itself inherits that footprint VERBATIM - /// (`copy_segment_id`, decodemv.c:342) -- heterogeneous footprints are - /// exactly what a 1:4-split arf leaves behind. Stamping the minified id - /// (the pre-lane defect) flattened those footprints and mis-dequantized - /// scattered blocks frames later: 2 luma bytes of mandelbrot frame 35 - /// differed from the oracle, everything else exact. - /// - /// Both arms decode EVERY frame in decode order -- hidden arfs included - /// -- byte-exact against the instrumented oracle, and every SHOWN frame - /// pixel-exact against ffmpeg; the census counters prove the premise - /// (segmentation symbols read, a wider-than-zero quantizer span from - /// `SEG_LVL_ALT_Q`, and an inheritance-heavy shape). - #[test] - fn a_real_aomenc_segmentation_stream_with_map_inheritance_decodes_pixel_exact() { - const NAME: &str = - "a_real_aomenc_segmentation_stream_with_map_inheritance_decodes_pixel_exact"; - // lane-av1cmpaudit2: this gate reaches the oracle without the gate - // mutex, so a sibling flipping `EC_AV1_AOMDEC` (the one-byte-wrong - // oracle control) could hand it a tampered oracle mid-compare. - let _gate_lock = lock_gate_counters(); - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc"); - return; - } - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - let extra = [ - "--cpu-used=4", - "--aq-mode=1", - "--cq-level=45", - "--lag-in-frames=16", - "--auto-alt-ref=1", - ]; - let arms: [(&str, &str, usize, usize); 2] = [ - ("screen testsrc2", "testsrc2", 256, 192), - ("film mandelbrot", "mandelbrot", 192, 128), - ]; - for (arm, source, width, height) in &arms { - // r7: the ENCODE's frame count, bound so the compare below asserts a - // spec rather than our own decode's length. - const ENCODED_FRAMES: usize = 40; - let stream = encode_aomenc_stream(source, *width, *height, ENCODED_FRAMES, &extra); - // Premise: the shape under test really arrived -- segmentation on - // every frame, the map both coded and inherited, and real ALT_Q - // tables. An aomenc drift that dropped any of these would make - // the decode below prove nothing (class gate-blind-to-feature). - let (enabled, umap, inherited, alt_q, _) = segmentation_feature_census(&stream); - eprintln!( - "{NAME} {arm}: seg-enabled {enabled}, update_map {umap}, inherited {inherited}, ALT_Q-carrying {alt_q}" - ); - assert!( - enabled > 0 && umap > 0, - "{arm}: no segmentation-carrying/map-coding frame -- the premise is gone" - ); - assert!( - inherited > 0, - "{arm}: no update_map == 0 frame -- the map-inheritance path under test never runs" - ); - assert!( - alt_q > 0, - "{arm}: no frame carries a SEG_LVL_ALT_Q table -- the feature under test never fires" - ); - // Every frame in decode order -- hidden arfs included (each one - // re-surfaces via show-existing in this recipe, so `hidden == 0` - // is possible while `frames` still covers the whole coded set) -- - // byte-exact against the oracle. - let (frames, hidden) = decode_all_frames_vs_oracle(&stream, arm); - assert!(frames > 0, "{arm}: decoded nothing"); - assert_eq!( - frames, enabled, - "{arm}: decode-order frame count != segmentation-enabled frame count -- the \ - parse and the decode disagree about the stream" - ); - let _ = hidden; - // And every shown frame pixel-exact against ffmpeg. - crate::decode::reset_segment_hits(); - let pictures = decode_stream(&stream) - .unwrap_or_else(|e| panic!("{NAME} {arm}: decode refused: {e}")); - assert!( - crate::decode::segment_id_hits() > 0, - "{arm}: zero segment_id symbols read -- the decode proved nothing about \ - segmentation" - ); - let (lo, hi) = crate::decode::block_q_span(); - assert!( - hi > lo, - "{arm}: every block dequantized at the same qindex ({lo}) -- SEG_LVL_ALT_Q \ - never changed any block's quantizer" - ); - // `ENCODED_FRAMES`, not `pictures.len()`: our decode's length is the - // thing UNDER TEST, so using it as the oracle's expected count is - // circular -- a decode that dropped a frame would ask ffmpeg for the - // same short count and the compare would silently shrink. - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, *width, *height, ENCODED_FRAMES); - for (i, (ours, theirs)) in pictures.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!(ours.y, theirs.y, "{NAME} {arm}: frame {i} luma vs ffmpeg"); - assert_eq!(ours.u, theirs.u, "{NAME} {arm}: frame {i} U vs ffmpeg"); - assert_eq!(ours.v, theirs.v, "{NAME} {arm}: frame {i} V vs ffmpeg"); - } - eprintln!( - "{NAME} {arm}: {frames} frames decode-order exact vs oracle ({hidden} hidden), {} shown frames exact vs ffmpeg, q span {lo}..{hi}, segment_id symbols {}", - pictures.len(), - crate::decode::segment_id_hits() - ); - } - } - - /// lane-t900 r27, WITNESS half of the proof for "an OBMC neighbour whose - /// switchable interp filter was never recorded" (the structural half is - /// `decode::tests::every_inter_record_publishes_an_obmc_readable_filter`, - /// which shows no INTER cell is ever stamped with the `[3, 3]` - /// sentinel): real OBMC streams whose frames use a SWITCHABLE (and dual) - /// interp filter decode with the refusal firing 0 times while OBMC blends - /// really read the neighbour band -- a decode that never read one would - /// pass just as well and prove nothing (class gate-blind-to-feature). - #[test] - fn a_real_obmc_stream_reads_a_recorded_switchable_filter_for_every_neighbour() { - if !have_aomenc() { - eprintln!("SKIP a_real_obmc_stream_reads_a_recorded_switchable_filter: no aomenc"); - return; - } - // `--cpu-used=0` is load-bearing: at speed 4 aomenc settles on a - // FRAME-level fixed interp filter, every neighbour then legitimately - // carries the sentinel, and the band is never read at all (measured - // r27: 0 reads over two speed-4 streams). - let base = vec![ - "--cpu-used=0", - "--enable-obmc=1", - "--enable-dual-filter=1", - "--min-partition-size=8", - "--max-partition-size=16", - "--enable-palette=0", - "--enable-intrabc=0", - ]; - let recipes: [(&str, usize, usize, Vec<&str>); 2] = [ - ( - "obmc dual cq40", - 192, - 128, - [vec!["--cq-level=40"], base.clone()].concat(), - ), - ( - "obmc dual cq20", - 192, - 128, - [vec!["--cq-level=20"], base.clone()].concat(), - ), - ]; - let mut reads = 0usize; - let mut decoded = 0usize; - for (name, w, h, extra) in &recipes { - let before = crate::decode::obmc_filter_band_reads(); - let obmc_before = crate::decode::obmc_hits(); - let (bytes, result) = census_attempt("mandelbrot", *w, *h, 8, extra); - match result { - Ok(pictures) => { - decoded += 1; - let got = crate::decode::obmc_filter_band_reads() - before; - reads += got; - eprintln!( - "OBMCFILT {name}: {bytes} B, {pictures} pictures, {got} band reads, \ - {} OBMC blocks", - crate::decode::obmc_hits() - obmc_before - ); - } - Err(e) => { - assert!( - !e.contains( - "an OBMC neighbour whose switchable interp filter was never recorded" - ), - "{name}: a real OBMC stream reached the unrecorded-filter refusal -- \ - a publication site is missing: {e}" - ); - eprintln!("OBMCFILT {name}: {bytes} B, refused for another reason: {e}"); - } - } - } - assert!( - decoded > 0, - "no OBMC recipe decoded -- the witness is vacuous" - ); - assert!( - reads > 0, - "every OBMC blend took the fixed-filter path: the band was never read, so this \ - proves nothing about the refusal" - ); - } - - /// lane-t900 r27 CENSUS for the three SUPERRES refusals -- "warp - /// prediction with a scaled reference", "a sub-8x8 inter block under a - /// scaled reference" and "an 8x8 partition leaf under a scaled reference". - /// Six real `--superres-mode` encodes (fixed denominators and the auto - /// mode, warped motion and OBMC on), decoded by this decoder: the table it - /// prints is which of the three a real encoder actually reaches. - /// - /// Every one of them is a REAL capability gap (unlike the enumerated - /// refusals elsewhere in the inventory), so this gate asserts the measured - /// shape rather than "no refusal": at least one recipe must decode (else - /// the census says nothing), and any refusal must be one of the three - /// named superres ones -- a fourth string would be a new gap this round - /// did not measure. - #[test] - fn a_superres_census_over_six_real_streams_records_which_scaled_refusals_fire() { - if !have_aomenc() { - eprintln!("SKIP a_superres_census_over_six_real_streams: no aomenc"); - return; - } - const WARP: &str = "warp prediction with a scaled reference"; - const SUB8: &str = "a sub-8x8 inter block under a scaled reference"; - const LEAF8: &str = "an 8x8 partition leaf under a scaled reference"; - let common = [ - "--enable-warped-motion=1", - "--enable-obmc=1", - "--enable-palette=0", - "--enable-intrabc=0", - ]; - let recipes: [(&str, usize, usize, Vec<&str>); 6] = [ - ( - "denom12 320x180 cq32", - 320, - 180, - vec![ - "--cpu-used=4", - "--superres-mode=1", - "--superres-denominator=12", - "--cq-level=32", - ], - ), - ( - "denom12 320x180 cq50", - 320, - 180, - vec![ - "--cpu-used=4", - "--superres-mode=1", - "--superres-denominator=12", - "--cq-level=50", - ], - ), - ( - "denom16 320x180 cq32", - 320, - 180, - vec![ - "--cpu-used=4", - "--superres-mode=1", - "--superres-denominator=16", - "--cq-level=32", - ], - ), - ( - "denom10 192x128 cq32", - 192, - 128, - vec![ - "--cpu-used=4", - "--superres-mode=1", - "--superres-denominator=10", - "--cq-level=32", - ], - ), - ( - "auto 320x180 cq50", - 320, - 180, - vec!["--cpu-used=4", "--superres-mode=3", "--cq-level=50"], - ), - ( - "auto 192x128 cq50", - 192, - 128, - vec!["--cpu-used=4", "--superres-mode=3", "--cq-level=50"], - ), - ]; - let (mut decoded, mut warp, mut sub8, mut leaf8) = (0, 0, 0, 0); - // lane-t900 r36 (class [[gate-blind-to-feature]]): unknown refusal - // strings used to `other += 1` and panic on the spot, so the census - // summary below -- the whole point of the gate -- never printed when - // one fired. They are collected instead, reported in the summary, and - // asserted after it. - let mut other: Vec = Vec::new(); - for (name, w, h, extra) in &recipes { - let mut args = extra.clone(); - args.extend_from_slice(&common); - let before = crate::mc::predict_scaled_hits(); - let (bytes, result) = census_attempt("mandelbrot", *w, *h, 10, &args); - match result { - Ok(pictures) => { - decoded += 1; - eprintln!( - "SUPERRES {name}: {bytes} B, {pictures} pictures, scaled MC blocks {}", - crate::mc::predict_scaled_hits() - before - ); - } - Err(e) => { - eprintln!("SUPERRES {name}: {bytes} B, refused: {e}"); - if e.contains(WARP) { - warp += 1; - } else if e.contains(SUB8) { - sub8 += 1; - } else if e.contains(LEAF8) { - leaf8 += 1; - } else { - other.push(format!("{name}: {e}")); - } - } - } - } - eprintln!( - "SUPERRES CENSUS: 6 streams, {decoded} decoded, warp {warp}x, sub8 {sub8}x, leaf8 {leaf8}x, other {}x", - other.len() - ); - assert!( - other.is_empty(), - "{} superres stream(s) stopped on a string this census does not know: {other:?}", - other.len() - ); - // Measured r27: the four FIXED-denominator recipes all stop at the - // 8x8-leaf refusal, and the two `--superres-mode=3` (auto) streams - // decode with ZERO scaled MC blocks -- auto picked denominator 8, so - // those two arms carry no scaling at all and prove nothing. The warp - // and sub-8x8 refusals never fire because the 8x8-leaf one sits in - // front of them: whichever partition path a scaled frame takes, the - // leaf guard is reached first. Lifting the leaf gap is what makes the - // other two measurable, so this gate pins the ORDER, not just a count. - assert!( - decoded > 0, - "no superres recipe decoded -- the census is vacuous" - ); - // lane-t900 r28: all three scaled refusals are LIFTED, so the census - // now pins the opposite shape -- every fixed-denominator recipe must - // DECODE, and none of the three strings may come back. - assert_eq!( - (warp, sub8, leaf8), - (0, 0, 0), - "a scaled-reference refusal came back (warp {warp}, sub8 {sub8}, leaf8 {leaf8})" - ); - assert!( - decoded > 0, - "no superres recipe decoded -- the census is vacuous" - ); - } - - /// lane-t900 r25, negative gate: a `show_existing_frame` header naming a - /// slot no frame has refreshed is refused BY NAME, and outputs no picture. - /// - /// The OBU is hand-built because [`crate::frame::write_frame_header`] - /// refuses to write one (it writes shown key and inter frames only): spec - /// 5.9.2's whole header for this case is `show_existing_frame` (1) plus - /// `frame_to_show_map_idx` (3), the sequence carrying neither a decoder - /// model nor frame ids. - /// - /// Deviation from the round's charter, which asked for a key frame first - /// with the named slot's `refresh_frame_flags` bit clear: a SHOWN key frame - /// refreshes every slot (spec 5.9.2 forces `refresh_frame_flags` to - /// `all_frames` and does not code it, which is also what - /// `write_frame_header` does), so the only reachable empty-slot stream is - /// one where no frame has refreshed that slot yet. The stream below is a - /// valid sequence header followed by the header OBU, and every one of the - /// eight slots is tried. - #[test] - fn a_show_existing_frame_header_naming_an_empty_slot_is_refused_by_name() { - const REFUSAL: &str = "a show_existing_frame header naming an empty reference slot"; - let (seq, _) = crate::encode::key_frame_headers(64, 64, 100).unwrap(); - for slot in 0..NUM_REF_FRAMES as u32 { - let mut w = ec_core::BitWriter::new(); - w.write_bit(true); // show_existing_frame - w.write_bits(slot, 3); // frame_to_show_map_idx - crate::bits::write_byte_alignment(&mut w); - let mut stream = crate::sequence::sequence_header_obu(&seq).unwrap(); - stream.extend_from_slice(&crate::obu::wrap_obu( - &ec_av1_syntax::obu::ObuHeader { - obu_type: ec_av1_syntax::obu::ObuType::FrameHeader, - extension_flag: false, - has_size_field: true, - temporal_id: 0, - spatial_id: 0, - }, - &w.into_bytes(), - )); - - let mut shown = 0; - let err = decode_stream_with(&stream, |_, _, _| { - shown += 1; - Ok(()) - }) - .unwrap_err() - .to_string(); - assert!( - err.contains(REFUSAL), - "slot {slot}: expected {REFUSAL:?}, got: {err}" - ); - assert_eq!( - shown, 0, - "slot {slot}: an empty slot was output as a picture" - ); - } - } - - /// lane-t900 r25, negative gate: an inter frame whose `ref_frame_idx[0]` - /// slot holds no picture -- a stream that opens on an inter frame -- is - /// refused BY NAME rather than predicting from nothing. - /// - /// Deviation from the round's charter, which asked for a real aomenc - /// two-frame stream with the key frame's OBUs stripped: this crate's own - /// `write_frame_header` writes a shown INTER frame (short reference - /// signalling and non-identity global motion are the parts it refuses), so - /// the fixture is built from the writers, needs neither ffmpeg nor aomenc, - /// and is byte-identical on every run. The tile payload is a real key - /// frame's; the refusal fires on the header's reference lookup, before any - /// tile is decoded. - #[test] - fn an_inter_frame_opening_a_stream_is_refused_by_name() { - let fctx = &crate::decode::FrameCtx::new(); - const REFUSAL: &str = "an inter frame with no key frame before it"; - let picture = test_card(64, 64); - let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); - let (seq, key) = crate::encode::key_frame_headers(64, 64, 100).unwrap(); - let inter = FrameHeader { - frame_type: FrameType::Inter, - frame_is_intra: false, - // Keeps `primary_ref_frame`, `frame_size_with_refs` and - // `use_ref_frame_mvs` out of the written header (spec 5.9.2). - error_resilient_mode: true, - primary_ref_frame: PRIMARY_REF_NONE, - refresh_frame_flags: 0x02, - order_hint: 1, - ..key - }; - let mut stream = crate::sequence::sequence_header_obu(&seq).unwrap(); - stream.extend_from_slice(&crate::frame::frame_obu(&seq, &inter, &encoded.tile).unwrap()); - - let mut shown = 0; - let err = decode_stream_with(&stream, |_, _, _| { - shown += 1; - Ok(()) - }) - .unwrap_err() - .to_string(); - assert!(err.contains(REFUSAL), "expected {REFUSAL:?}, got: {err}"); - assert_eq!( - shown, 0, - "an inter frame with no reference produced a picture" - ); - } - - /// lane-t900 r26, negative gate: an inter frame whose own coded size is - /// SHORTER than the reference it predicts from is refused BY NAME, and - /// outputs no picture beyond the key frame that preceded it. - /// - /// The height mismatch is the one size difference this decoder cannot - /// absorb: `mc::predict_scaled` scales horizontally (a `use_superres` - /// reference), and nothing on this path scales vertically. The fixture is - /// written, not hand-built: a shown key frame at 64x64 (which refreshes - /// every slot), then a shown inter frame carrying - /// `frame_size_override_flag` with `error_resilient_mode` set -- the one - /// combination [`crate::frame::write_frame_header`] writes, since - /// `frame_size_with_refs` (spec 5.9.7) is only read when error resilience - /// is OFF. The inter frame's tile payload is the key frame's; the refusal - /// fires on the reference's dimensions before a tile symbol is read. A 31 - /// row frame against a 64 row reference is past the 2x down limit. - #[test] - fn an_inter_frame_shorter_than_its_reference_is_refused_by_name() { - let fctx = &crate::decode::FrameCtx::new(); - const REFUSAL: &str = - "a reference picture outside the 2x down / 16x up scaling limits"; - let picture = test_card(64, 64); - let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); - let (seq, key) = crate::encode::key_frame_headers(64, 64, 100).unwrap(); - let inter = FrameHeader { - frame_type: FrameType::Inter, - frame_is_intra: false, - error_resilient_mode: true, - primary_ref_frame: PRIMARY_REF_NONE, - refresh_frame_flags: 0x02, - order_hint: 1, - frame_size_override_flag: true, - frame_height: 31, - render_height: 31, - ..key.clone() - }; - let mut stream = crate::sequence::sequence_header_obu(&seq).unwrap(); - stream.extend_from_slice(&crate::frame::frame_obu(&seq, &key, &encoded.tile).unwrap()); - stream.extend_from_slice(&crate::frame::frame_obu(&seq, &inter, &encoded.tile).unwrap()); - - let mut shown = 0; - let err = decode_stream_with(&stream, |_, _, _| { - shown += 1; - Ok(()) - }) - .unwrap_err() - .to_string(); - assert!(err.contains(REFUSAL), "expected {REFUSAL:?}, got: {err}"); - assert_eq!( - shown, 1, - "expected the key frame alone, got {shown} pictures" - ); - } - - /// lane-t900 r26, negative gate: an inter frame naming a - /// `primary_ref_frame` whose reference slot has never been refreshed is - /// refused BY NAME rather than decoded from the spec 8.4 default tables. - /// - /// Enumeration first, because the refusal's premise is an invariant: the - /// picture slots and the CDF slots are written by exactly two loops in - /// [`decode_stream`] (the `show_existing_frame` arm's copy and the - /// end-of-frame store), and both walk the SAME `refresh_frame_flags` mask - /// writing `ref_slots[i]` and `cdf_slots[i]` together -- so no slot can - /// hold a picture without CDFs, and the reachable case is a slot nothing - /// has refreshed at all. That is what this builds: a stream that OPENS on - /// a non-error-resilient inter frame (the only header shape that codes - /// `primary_ref_frame` at all, spec 5.9.2), tried at all eight slots. - /// - /// This refusal, not "an inter frame with no key frame before it", is the - /// one such a stream reaches: the CDF load happens in the header path, - /// before the reference pictures are looked up. - #[test] - fn an_inter_frame_naming_an_unrefreshed_primary_ref_slot_is_refused_by_name() { - let fctx = &crate::decode::FrameCtx::new(); - const REFUSAL: &str = - "a frame naming primary_ref_frame at a reference slot with no saved CDF state"; - // The invariant above, read off the source: every line that stores a - // picture into a slot sits in a block that stores that slot's CDFs too. - let src = crate::test_source::module_source("stream"); - let stores: Vec = src - .lines() - .enumerate() - .filter(|(_, l)| l.trim().starts_with("ref_slots[i] = ")) - .map(|(i, _)| i) - .collect(); - assert_eq!( - stores.len(), - 2, - "the picture slots gained a writer -- check it stores cdf_slots too" - ); - let lines: Vec<&str> = src.lines().collect(); - for &i in &stores { - let window = lines[i.saturating_sub(6)..(i + 6).min(lines.len())].join("\n"); - assert!( - window.contains("cdf_slots[i] = "), - "line {} stores a reference picture with no cdf_slots store beside it: a slot \ - can then hold a picture with no saved CDF state", - i + 1 - ); - } - - let picture = test_card(64, 64); - let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); - let (seq, key) = crate::encode::key_frame_headers(64, 64, 100).unwrap(); - for slot in 0..NUM_REF_FRAMES as u8 { - let inter = FrameHeader { - frame_type: FrameType::Inter, - frame_is_intra: false, - // `primary_ref_frame` is coded only when error resilience is - // off (spec 5.9.2); `frame_size_override_flag` stays clear so - // the header writes a plain `frame_size()`. - error_resilient_mode: false, - primary_ref_frame: 0, - ref_frame_idx: [slot; ec_av1_syntax::REFS_PER_FRAME], - refresh_frame_flags: 0x02, - order_hint: 1, - ..key.clone() - }; - let mut stream = crate::sequence::sequence_header_obu(&seq).unwrap(); - stream - .extend_from_slice(&crate::frame::frame_obu(&seq, &inter, &encoded.tile).unwrap()); - - let mut shown = 0; - let err = decode_stream_with(&stream, |_, _, _| { - shown += 1; - Ok(()) - }) - .unwrap_err() - .to_string(); - assert!( - err.contains(REFUSAL), - "slot {slot}: expected {REFUSAL:?}, got: {err}" - ); - assert_eq!( - shown, 0, - "slot {slot}: a frame with no CDF state produced a picture" - ); - } - } - - /// lane-t900 r26, enumeration: no frame header a stream can carry derives - /// an empty mode-info grid, so "a frame with no mode-info grid" names a - /// case outside the coded domain. - /// - /// `compute_image_size` (spec 5.9.9) is `mi_cols = 2 * ((frame_width + 7) - /// >> 3)`, which is 0 only for `frame_width == 0`, and a frame width is - /// > > never 0 on any of the three paths that set one: - /// - /// * `frame_size()` (5.9.5) reads `frame_width_minus_1` and adds one, or - /// takes the sequence's `max_frame_width` (itself `+ 1`-coded); - /// * `superres_params()` (5.9.8) divides by a denominator of 9..=16 with - /// rounding, whose minimum over the whole 16-bit upscaled-width domain - /// is enumerated below and is 1, not 0; - /// * `show_existing_frame` and `frame_size_with_refs()` copy a slot's own - /// dimensions, which came from one of the above. - /// - /// The sweep drives the REAL header reader (write a header, parse it back) - /// over every width and every height a 16-bit `frame_size()` can code, - /// per axis -- the derivation is independent per axis -- rather than - /// re-deriving the formula here. - #[test] - fn every_frame_size_a_header_can_code_has_a_mode_info_grid() { - // lane-av1refusalspan: this gate is the PROOF for the refusal below, so - // it names it and pins its guard site (the decode-path guard in - // decode.rs carries the same string). - const REFUSAL: &str = "a frame with no mode-info grid"; - assert!( - crate::refusal_inventory::pins_refusal(crate::test_source::module_source("stream"), REFUSAL), - "this gate proves {REFUSAL:?}, but that string is no longer in stream.rs" - ); - let mut sizes: Vec = (1..=1024).collect(); - sizes.extend([2048, 4095, 4096, 8192, 16384, 32768, 65535, 65536]); - // `mi_cols` is nondecreasing in `frame_width`, so an empty grid can - // only appear at the SMALL end -- which is why a size this crate's - // tile-info writer cannot express (its tile log2 range runs out well - // before 65536) is skipped rather than worked around, while every - // size up to 1024 must be covered. - let mut skipped: Vec = Vec::new(); - for n in sizes { - for (w, h) in [(n, 16), (16, n)] { - let Ok((seq, header)) = - crate::encode::key_frame_headers(w as usize, h as usize, 100) - else { - skipped.push(n); - continue; - }; - let Ok(stream) = crate::frame::frame_obu(&seq, &header, &[]) else { - skipped.push(n); - continue; - }; - let mut parser = Av1Parser::new(); - parser - .parse_obu(&crate::sequence::sequence_header_obu(&seq).unwrap()) - .unwrap(); - let obu = parser.parse_obu(&stream).unwrap(); - let ObuKind::Frame(parsed, _) = &obu.kind else { - panic!("{w}x{h}: the written frame OBU did not parse as one"); - }; - assert!( - parsed.mi_cols >= 2 && parsed.mi_rows >= 2, - "{w}x{h} parsed to a {}x{} mode-info grid", - parsed.mi_cols, - parsed.mi_rows - ); - } - } - assert!( - skipped.iter().all(|&n| n > 1024), - "the writer could not express these small frame sizes, so the small end of the \ - sweep is incomplete: {skipped:?}" - ); - // The superres arm, which no writer here can express: spec 5.9.8's - // `(upscaled_width * 8 + denom / 2) / denom` over its whole domain. - for denom in 9u32..=16 { - for upscaled in [1u32, 2, 3, 7, 8, 9, 255, 4096, 65535, 65536] { - let width = (upscaled * 8 + denom / 2) / denom; - assert!( - width >= 1, - "superres denom {denom} maps an upscaled width of {upscaled} to {width}, \ - which would derive an empty mode-info grid" - ); - } - } - } - - /// lane-interedge r1 GATE (was lane-oddh r2's `#[ignore]`d twin): the INTER - /// frame-edge half strips -- a `PARTITION_HORZ`/`PARTITION_VERT` forced by - /// the gathered edge symbol at the 64, 32 or 16 level whose second half lies - /// outside the true frame. Both of the user's films are height mod 16 == 8 - /// (1920x792, 3840x1608), so every inter frame crosses these nodes. - /// - /// r1 root cause: the inter tile's 32-level `PARTITION_HORZ`/`PARTITION_VERT` - /// decoded the SECOND strip unconditionally, while libaom `decode_partition` - /// (decodeframe.c, PARTITION_HORZ) guards it with `has_rows`/`has_cols` -- - /// so at the edge we read symbols the encoder never wrote. With that guard - /// removed this gate's 72x192 cq 32 arm refuses outright and its 104x192 arm - /// decodes luma rows 127..191 of frame 5 wrong (measured r1). - /// - /// The compare is LUMA-exact per frame plus a CONTROL size with no edge node - /// at all: chroma is excluded because a chroma-only inter residue that has - /// nothing to do with the frame edge is open on main (lanes/tiny-r3, - /// lanes/gmaffine-r4, lanes/palette2-r8) and the control below reproduces it - /// with `inter_edge_strip_hits` all zero. - #[test] - fn a_real_aomenc_inter_frame_edge_half_strip_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_inter_frame_edge_half_strip_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() || !have_aomenc() { - eprintln!("SKIP {NAME}: no ffmpeg/aomenc"); - return; - } - let frames = 6usize; - // h mod 16 == 8 (bottom edge) and w mod 16 == 8 (right edge). - let sizes: &[(usize, usize)] = &[(192, 72), (192, 88), (72, 192), (88, 192), (104, 192)]; - let mut totals = [0usize; 6]; - let mut compared = 0u32; - let mut chroma_frames = 0usize; - for &(width, height) in sizes { - for bit_depth in [8u32, 10] { - for cq in [20u32, 32, 45] { - let (hits, luma_bad, chroma_bad) = - inter_edge_strip_attempt(NAME, width, height, bit_depth, cq, frames); - assert_eq!( - luma_bad, 0, - "{NAME}: {width}x{height} {bit_depth}-bit cq {cq}: {luma_bad} of {frames} \ - frames differ from ffmpeg in LUMA (edge hits {hits:?})" - ); - // merge J, after lane-rectchroma2: the chroma residue this - // gate used to tolerate WAS this decoder's -- the per-axis - // narrow-block MC kernel decision read side x side instead - // of the block's true dims. Full-plane now. - assert_eq!( - chroma_bad, 0, - "{NAME}: {width}x{height} {bit_depth}-bit cq {cq}: {chroma_bad} of \ - {frames} frames differ from ffmpeg in CHROMA (edge hits {hits:?})" - ); - for (t, h) in totals.iter_mut().zip(hits) { - *t += h; - } - chroma_frames += chroma_bad; - compared += 1; - } - } - } - // Every level x axis this recipe reaches must have fired on a COMPARED - // attempt. h32 (a bottom-edge HORZ at the 32 level) is not asserted: no - // recipe found in r1 makes libaom answer that gathered symbol HORZ - // (sweep ~/.cache/interedge-tmp/h32.sh, 3 sizes x 6 cq, all SPLIT); it - // is the transposed twin of v32, which this gate does fire. - assert!( - totals[0] > 0 && totals[1] > 0 && totals[3] > 0 && totals[4] > 0 && totals[5] > 0, - "{NAME}: {compared} attempts luma-exact but the edge strips did not all fire \ - (h64,v64,h32,v32,h16,v16 = {totals:?}) -- the recipe no longer reaches the arms \ - this gate exists for" - ); - // CONTROL: a size with no frame-edge node anywhere (192x128, both axes - // 0 mod 64). It must be luma-exact with ZERO edge hits -- that is what - // makes the chroma exclusion above a statement about a foreign defect - // rather than about this lane's code. - let (chits, cluma, cchroma) = inter_edge_strip_attempt(NAME, 192, 128, 8, 32, frames); - assert_eq!( - (chits, cluma, cchroma), - ([0usize; 6], 0usize, 0usize), - "{NAME}: control 192x128 (no frame-edge node) must be pixel-exact with no edge hits" - ); - eprintln!( - "{NAME}: {compared} attempts luma-exact over {} sizes, edge hits \ - (h64,v64,h32,v32,h16,v16)={totals:?}, 0 refusals; chroma-only frames {chroma_frames} \ - (control 192x128: hits {chits:?}, chroma-only frames {cchroma} -- foreign defect)", - sizes.len() - ); - } - - /// lane-sb128 r4 GATE (was lane-oddh r2's refusal gate): the SAME real - /// aomenc 64x72 `--cpu-used=0 --sb-size=128` stream that once desynced at - /// the very first symbol now decodes PIXEL-EXACT against aomdec. mi_rows - /// = 18 > 16, so the BLOCK_128X128 root reads a real gathered partition - /// symbol (2 symbols: has_cols false, has_rows true) -- exactly the case - /// r1 mis-read as a 10-symbol BLOCK_64X64 partition. - /// - /// The `use_128x128_superblock` assert is the "knob reached the tool" - /// half: without it an aomenc that ignored `--sb-size=128` would leave - /// the gate proving nothing about 128 superblocks. - #[test] - fn a_real_aomenc_128x128_superblock_stream_decodes_pixel_exact() { - if !have_ffmpeg() || !have_aomenc() { - eprintln!("SKIP: no ffmpeg/aomenc"); - return; - } - let (width, height) = (64usize, 72usize); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - "mandelbrot=size=64x72:rate=25:start_x=-0.6:start_y=-0.4", - "-t", - "0.04", - "-pix_fmt", - "yuv420p", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let out = run_with_stdin( - Command::new(aomenc_path()).args([ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=32", - "--cpu-used=0", - "--sb-size=128", - "--min-partition-size=16", - "--kf-max-dist=0", - "--limit=1", - "--threads=1", - "--row-mt=0", - "--obu", - "-o", - "-", - "-", - ]), - &y4m.stdout, - ); - assert!( - out.status.success(), - "aomenc refused: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - - // The knob actually arrived: this stream's sequence header codes - // `use_128x128_superblock = 1`. - let mut parser = Av1Parser::new(); - let mut pos = 0usize; - let mut sb128 = false; - while pos < stream.len() { - let Ok(obu) = parser.parse_obu(&stream[pos..]) else { - break; - }; - pos += obu.total_size.max(1); - if let Some(seq) = parser.sequence_header() { - sb128 = seq.use_128x128_superblock; - break; - } - } - assert!( - sb128, - "aomenc ignored --sb-size=128: this stream is 64x64-superblock" - ); - - let _guard = lock_gate_counters(); - let before = crate::decode::part128_symbols() + crate::decode::part128_gathered_symbols(); - let (frames, hidden) = decode_all_frames_vs_oracle(&stream, "sb128-oddh-64x72"); - assert!(frames > 0, "no frames decoded for {width}x{height}"); - // The 128 root actually READ a partition symbol here: at mi_rows=18 - // `has_rows` is true, so BLOCK_128X128 is not a forced split. - let part128 = - crate::decode::part128_symbols() + crate::decode::part128_gathered_symbols() - before; - assert!( - part128 > 0, - "{width}x{height} decoded without reading a single BLOCK_128X128 \ - partition symbol -- the gate proves nothing about the 128 root" - ); - eprintln!( - "a_real_aomenc_128x128_superblock_stream_decodes_pixel_exact: \ - {frames} frames pixel-exact ({hidden} hidden) at {width}x{height}, \ - part128_symbols={part128}" - ); - } - - /// `decode_stream` on a lone key frame's stream matches both the tile - /// path (`decode_key_frame_tile` called directly on `Encoded::tile`) and - /// the encoder's own reconstruction, at an even and an odd size. - #[test] - fn decode_stream_matches_the_tile_path_on_a_key_frame() { - // lane-b128m: the ENCODER writes at this process's superblock size, so - // its own trial decode -- and the raw tile decode below -- must be given - // that size too (class: stale header in the test harness). - let fctx = &crate::decode::FrameCtx::for_encoder(); - for &(width, height) in &[(64usize, 64usize), (216, 96)] { - let picture = test_card(width, height); - let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); - let via_tile = decode_key_frame_tile_lr( - &encoded.tile, - encoded.mi_cols, - encoded.mi_rows, - encoded.base_q_idx, - width as u32, - height as u32, - // lane-fintra: the sequence bit the encoder wrote this tile under - // (stale-header class -- a hard-coded `false` here reads one symbol - // short at the first DC_PRED block once the search offers filter intra). - crate::encode::filter_intra_on(), - &encoded.cdef, - &encoded.loop_filter, - encoded.tx_select, - // lane-intertx: the frame's own `reduced_tx_set` -- a screen - // key frame at preset 0 codes the wider intra alphabets, so - // the old hardcoded `true` (ours "always" wrote true) is a - // stale-header bug waiting for the first screen fixture. - encoded.reduced_tx_set, - // `allow_screen_content_tools` off the frame the encoder - // actually wrote: a screen-content picture codes two palette - // symbols per intra block, and a raw tile decode that guessed - // `false` desyncs at the first one (class: test asserts - // against a stale header). - encoded.screen, - // ... and its own `allow_intrabc` (stale-header class). - encoded.allow_intrabc, - &encoded.loop_restoration, - fctx, - ) - .unwrap(); - let via_stream = decode_stream(&encoded.stream).unwrap(); - assert_eq!(via_stream.len(), 1, "{width}x{height}: one picture"); - assert_eq!(via_stream[0].y, via_tile.y, "{width}x{height}: luma"); - assert_eq!(via_stream[0].u, via_tile.u, "{width}x{height}: U"); - assert_eq!(via_stream[0].v, via_tile.v, "{width}x{height}: V"); - assert_eq!( - via_stream[0].y, encoded.reconstruction.y, - "{width}x{height}: luma vs encoder reconstruction" - ); - } - } - - #[test] - fn decode_stream_round_trips_a_gop() { - let fctx = &crate::decode::FrameCtx::for_encoder(); - gop_round_trips(128, 64, fctx); - } - - /// Same claim at a size that is not a whole number of 32x32 blocks, so - /// the inter frame's 16x16-leaf split path is exercised too. - #[test] - fn decode_stream_round_trips_an_odd_size_gop() { - let fctx = &crate::decode::FrameCtx::for_encoder(); - gop_round_trips(216, 96, fctx); - } - - /// lane-streamsink r1: `decode_stream_with` emits exactly the pictures - /// `decode_stream` collects, in the same order -- the streaming path is - /// the decoder now (`decode_stream` is a collecting wrapper), so an - /// equivalence check here is what keeps every gate's Vec-shaped assert - /// meaningful. Also pins the sink contract: one call per shown picture, - /// decode indices non-decreasing, and an `Err` from the sink aborting. - #[test] - fn streaming_decode_matches_the_collecting_one() { - let fctx = &crate::decode::FrameCtx::for_encoder(); - let pictures: Vec<_> = (0..4).map(|i| panned_test_card(128, 64, i * 3)).collect(); - let stream = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx) - .unwrap() - .stream; - let collected = decode_stream(&stream).unwrap(); - - let mut shown = Vec::new(); - let mut idxs = Vec::new(); - let mut live = 0usize; - decode_stream_with(&stream, |p, idx, is_shown| { - live += 1; - if is_shown { - idxs.push(idx); - shown.push(p.clone()); - } - Ok(()) - }) - .unwrap(); - assert_eq!( - shown.len(), - collected.len(), - "callback count vs shown frames" - ); - assert!( - live >= shown.len(), - "every shown picture is also a callback" - ); - assert!( - idxs.windows(2).all(|w| w[0] <= w[1]), - "decode indices out of order: {idxs:?}" - ); - for (i, (got, want)) in shown.iter().zip(&collected).enumerate() { - assert_eq!(got.y, want.y, "frame {i} luma"); - assert_eq!(got.u, want.u, "frame {i} U"); - assert_eq!(got.v, want.v, "frame {i} V"); - } - - // A sink error stops the decode and comes back unchanged. - let mut seen = 0usize; - let err = decode_stream_with(&stream, |_, _, _| { - seen += 1; - Err(Error::corrupt("sink says stop")) - }) - .unwrap_err(); - assert_eq!(seen, 1, "decode continued past a failing sink"); - assert!(format!("{err}").contains("sink says stop"), "{err}"); - } - - /// lane-av1oracleguard, direction 1 of 2: the 4:2:0 helper's COMPARATOR - /// still bites on a real 4:2:0 pin, so the refusal added above did not - /// buy its non-vacuity by making the helper stop comparing. - /// - /// `420_mixll_256x128_6f.obu` is 8-bit 4:2:0 at 256x128. Ours and ffmpeg - /// agree on every sample of every output frame (bad == 0), then ONE U - /// sample of the oracle is flipped and the same count must move to 1. A - /// count that stays 0 on a flipped oracle is a comparator that compares - /// nothing, and the refusal would then be the only thing this gate could - /// prove. - #[test] - fn a_420_oracle_comparator_counts_a_flipped_oracle_sample() { - const NAME: &str = "a_420_oracle_comparator_counts_a_flipped_oracle_sample"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - let path = crate_pin("420_mixll_256x128_6f.obu"); - let data = std::fs::read(&path) - .unwrap_or_else(|e| panic!("{NAME}: the committed pin is missing ({e})")); - assert_eq!(data.len(), 22336, "{NAME}: pin size drifted"); - assert_eq!( - fnv1a64(&data), - 5694016005779287373, - "{NAME}: pin bytes drifted" - ); - assert_eq!( - stream_subsampling(&data, NAME), - (1, 1), - "{NAME}: this cell must be a 4:2:0 pin -- the refusal arm uses other pins" - ); - - let decoded = decode_stream(&data) - .unwrap_or_else(|e| panic!("{NAME}: the committed 4:2:0 pin did not decode: {e}")); - // The pin name is the spec: `420_mixll_256x128_6f` is 6 shown frames. - // `decoded.len()` is the value under test, so it must not be the count - // handed to ffmpeg (count-vacuity ceiling is 0). - const SHOWN: usize = 6; - assert_eq!(decoded.len(), SHOWN, "{NAME}: the pin is 6 shown frames"); - let want = ffmpeg_decode_sequence(&data, 256, 128, SHOWN); - assert_eq!(decoded.len(), want.len(), "{NAME}: decoded/frame count"); - - let plane_mismatches = |ours: &[Pic], theirs: &[Pic], plane: u8| -> usize { - ours.iter() - .zip(theirs) - .map(|(a, b)| { - let (a, b) = match plane { - 0 => (&a.y, &b.y), - 1 => (&a.u, &b.u), - _ => (&a.v, &b.v), - }; - a.iter().zip(b).filter(|&(x, y)| x != y).count() - }) - .sum() - }; - let clean: Vec = (0..3) - .map(|p| plane_mismatches(&decoded, &want, p)) - .collect(); - assert_eq!( - clean, - vec![0, 0, 0], - "{NAME}: the 4:2:0 oracle arm is not byte-exact to start with, so a flipped sample \ - would prove nothing" - ); - - // Flip exactly one oracle sample and the count MUST move. - let mut flipped = want.clone(); - flipped[0].u[0] ^= 1; - let moved: Vec = (0..3) - .map(|p| plane_mismatches(&decoded, &flipped, p)) - .collect(); - assert_eq!( - moved, - vec![0, 1, 0], - "{NAME}: one flipped oracle U sample must move the U comparison count 0 -> 1 and \ - leave Y and V at 0; got {moved:?} -- the comparator does not bite, so this gate \ - cannot tell a working oracle arm from a vacuous one" - ); - eprintln!( - "{NAME}: clean per-plane counts {clean:?}, after one flipped oracle U sample {moved:?}" - ); - } - - /// lane-av1oracleguard, direction 2 of 2 (8-bit): the 4:2:0 helper must - /// REFUSE a real 4:2:2 pin instead of letting ffmpeg convert it. The - /// message must name the REAL subsampling AND the sibling to use -- a - /// bare "wrong shape" would leave the caller to rediscover the fix. - /// - /// Before this lane, `ffmpeg_decode_sequence(&422_key_64x64, 64, 64, 1)` - /// RETURNED a 4:2:0-converted picture without complaint, which is the - /// silent-green the refusal exists to stop. This gate needs no ffmpeg at - /// all: the guard runs before the spawn, so a host without ffmpeg still - /// proves the refusal. - #[test] - fn a_420_oracle_helper_refuses_a_422_pin() { - const NAME: &str = "a_420_oracle_helper_refuses_a_422_pin"; - let _gate_lock = lock_gate_counters(); - let path = crate_pin("422_key_64x64.obu"); - let stream = read_pin(&path, 755, 0x87fc569cf53bcbc6, NAME); - assert_eq!( - stream_subsampling(&stream, NAME), - (1, 0), - "{NAME}: the pin must really be 4:2:2 (1,0), or this proves nothing" - ); - let msg = panic_message(|| { - ffmpeg_decode_sequence(&stream, 64, 64, 1); - }) - .unwrap_or_else(|| { - panic!( - "{NAME}: ffmpeg_decode_sequence ACCEPTED a (1,0) stream. ffmpeg converted it to \ - 4:2:0 and the helper returned a green-looking comparison" - ) - }); - for needle in ["(1,0)", "4:2:2", "ffmpeg_decode_sequence_422"] { - assert!( - msg.contains(needle), - "{NAME}: the refusal must name {needle:?}; it said: {msg}" - ); - } - eprintln!("{NAME}: refused -> {msg}"); - } - - /// lane-av1oracleguard, direction 2 of 2 (high depth): the same refusal on - /// `ffmpeg_decode_sequence_10bit` and `_12bit`, which ask ffmpeg for - /// `yuv420p10le`/`yuv420p12le` and slice chroma at `width * height / 4` - /// exactly as the 8-bit helper does. Pinned 4:2:2 at both depths. - #[test] - fn a_420_high_bit_depth_oracle_helpers_refuse_a_422_pin() { - const NAME: &str = "a_420_high_bit_depth_oracle_helpers_refuse_a_422_pin"; - let _gate_lock = lock_gate_counters(); - let cells: [(&str, usize, u64, fn(&[u8]) -> Vec); 2] = [ - ( - "s422_352x242_10b.obu", - 20575, - 17425395593908182125, - |s: &[u8]| ffmpeg_decode_sequence_10bit(s, 352, 242, 1), - ), - ( - "s422_12bit_160x128.obu", - 9214, - 0xa62b8e3fe6f60ae5, - |s: &[u8]| ffmpeg_decode_sequence_12bit(s, 160, 128, 1), - ), - ]; - for (file, len, fnv, call) in cells { - let path = crate_pin(file); - let stream = read_pin(&path, len, fnv, NAME); - assert_eq!( - stream_subsampling(&stream, NAME), - (1, 0), - "{NAME}/{file}: the pin must really be 4:2:2 (1,0), or this proves nothing" - ); - let msg = panic_message(|| { - call(&stream); - }) - .unwrap_or_else(|| { - panic!( - "{NAME}/{file}: the 4:2:0 high-bit-depth oracle helper ACCEPTED a (1,0) \ - stream -- ffmpeg converted it and the helper returned a comparison that \ - could pass green" - ) - }); - for needle in ["(1,0)", "4:2:2", "ffmpeg_decode_sequence_422_depth"] { - assert!( - msg.contains(needle), - "{NAME}/{file}: the refusal must name {needle:?}; it said: {msg}" - ); - } - eprintln!("{NAME}/{file}: refused -> {msg}"); - } - } - - /// lane-av1422mixll10: a skipped INTRABC 8x8 leaf inside a LOSSLESS - /// segment of a 4:2:2 frame predicts its whole 4x8 chroma plane block -- - /// both TX_4X4 units, each windowed off the DV frame copy. The defect - /// arm pushed only the first 4x4 (at `cpy`), leaving rows - /// `cpy+4..cpy+8` unwritten: frame 0's U(140..143, 188..191) read the - /// sentinel poison 0 against the oracle's 664 (16 samples, all planes - /// otherwise exact). Pin `422_mixll_intrabc_lossless_320x240_5f.obu` - /// (aomenc profile 1, 320x240 yuv422p10le, mixed-lossless AQ segment + - /// intrabc screen content; 79333 bytes, sha256 - /// `9fa1f1d28d61e3096d70908728f9cdfa1a570b9769a3d31e8d385a61c12a2b25`). - /// Gate: every frame of all three planes byte-exact against ffmpeg's - /// `yuv422p10le`, plus the non-vacuity controls (the pin's chroma census - /// must show coded units, and one flipped oracle sample must move the - /// count). - #[test] - fn a_422_mixll_intrabc_lossless_leaf_predicts_whole_chroma_plane_block() { - const NAME: &str = "a_422_mixll_intrabc_lossless_leaf_predicts_whole_chroma_plane_block"; - const FILE: &str = "422_mixll_intrabc_lossless_320x240_5f.obu"; - const LEN: usize = 79333; - const FNV: u64 = 8342335520738450773; - const W: usize = 320; - const H: usize = 240; - const SHOWN: usize = 5; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - let path = crate_pin(FILE); - let stream = read_pin(&path, LEN, FNV, NAME); - assert_eq!( - stream_subsampling(&stream, NAME), - (1, 0), - "{NAME}: the pin must really be 4:2:2 (1,0)" - ); - assert_eq!( - stream_bit_depth(&stream, NAME), - 10, - "{NAME}: the pin is a 10-bit cell" - ); - let _ = stream_bit_depth(&stream, NAME); - - let decoded = decode_stream(&stream) - .unwrap_or_else(|e| panic!("{NAME}: the committed 4:2:2 pin did not decode: {e}")); - assert_eq!( - decoded.len(), - SHOWN, - "{NAME}: the pin is {SHOWN} shown frames" - ); - let want = ffmpeg_decode_sequence_422_depth(&stream, W, H, SHOWN, 10, "yuv422p10le"); - assert_eq!(decoded.len(), want.len(), "{NAME}: decoded/frame count"); - - let plane_mismatches = |ours: &[Pic], theirs: &[Pic], plane: u8| -> usize { - ours.iter() - .zip(theirs) - .map(|(a, b)| { - let (a, b) = match plane { - 0 => (&a.y, &b.y), - 1 => (&a.u, &b.u), - _ => (&a.v, &b.v), - }; - a.iter().zip(b).filter(|&(x, y)| x != y).count() - }) - .sum() - }; - let clean: Vec = (0..3) - .map(|p| plane_mismatches(&decoded, &want, p)) - .collect(); - assert_eq!( - clean, - vec![0, 0, 0], - "{NAME}: the fix must be byte-exact against ffmpeg on every plane of every frame; \ - got {clean:?} (16 differs on frame 0 U would be the unwritten 4x4 again)" - ); - - // Non-vacuity: one flipped oracle U sample must move the U count. - let mut flipped = want.clone(); - flipped[0].u[188 * (W / 2) + 140] ^= 1; - let moved: Vec = (0..3) - .map(|p| plane_mismatches(&decoded, &flipped, p)) - .collect(); - assert_eq!( - moved, - vec![0, 1, 0], - "{NAME}: one flipped oracle U sample at (140,188) must move the U count 0 -> 1; \ - got {moved:?} -- the comparator does not bite" - ); - eprintln!( - "{NAME}: byte-exact vs ffmpeg on all {SHOWN} frames; flip control moved {moved:?}" - ); - } - - /// lane-av1oracledepth: the 8-bit `ffmpeg_decode_sequence_444` must REFUSE - /// a real 10-bit 4:4:4 pin instead of letting ffmpeg convert it down to - /// `yuv444p`. ffmpeg does not fail on the depth mismatch -- it re-scales - /// -- so a gate built on the 8-bit helper would compare ffmpeg's rescaled - /// planes against our 10-bit decode and could read exact. The message - /// must name the real depth AND the depth-generic sibling - /// `ffmpeg_decode_sequence_444_depth`, so the caller has the fix in front - /// of it. - /// - /// Needs no ffmpeg at all: the guard runs before the spawn, so a host - /// without ffmpeg still proves the refusal. - #[test] - fn the_8bit_444_oracle_helper_refuses_a_10bit_444_pin() { - const NAME: &str = "the_8bit_444_oracle_helper_refuses_a_10bit_444_pin"; - let _gate_lock = lock_gate_counters(); - let path = crate_pin("444_lossy_palette_chroma_352x242_10b.obu"); - let stream = read_pin(&path, 24875, 0x7fda_dbb4_3bbf_9af3, NAME); - assert_eq!( - stream_bit_depth(&stream, NAME), - 10, - "{NAME}: the pin must really be 10-bit, or this proves nothing" - ); - assert_eq!( - stream_subsampling(&stream, NAME), - (0, 0), - "{NAME}: the pin must really be 4:4:4 (0,0), or this proves nothing" - ); - let msg = panic_message(|| { - ffmpeg_decode_sequence_444(&stream, 352, 242, 1); - }) - .unwrap_or_else(|| { - panic!( - "{NAME}: ffmpeg_decode_sequence_444 ACCEPTED a 10-bit 4:4:4 stream. ffmpeg \ - converted it to yuv444p and the helper returned a green-looking comparison" - ) - }); - for needle in ["not 8-bit", "ffmpeg_decode_sequence_444_depth"] { - assert!( - msg.contains(needle), - "{NAME}: the refusal must name {needle:?}; it said: {msg}" - ); - } - eprintln!("{NAME}: refused -> {msg}"); - } diff --git a/crates/ec-av1/src/stream/tests/t02.rs b/crates/ec-av1/src/stream/tests/t02.rs deleted file mode 100644 index dfe3ab0de..00000000 --- a/crates/ec-av1/src/stream/tests/t02.rs +++ /dev/null @@ -1,4341 +0,0 @@ -use super::*; -use super::support::*; -use super::gates_a::*; -use crate::encode::{Picture as Pic, encode_key_frame_with_ctx, encode_sequence_with_ctx}; -use crate::probe::run_with_stdin; -use std::process::{Command, Stdio}; - - /// lane-av1oracledepth: the depth-generic 4:4:4 oracle comparator, armed - /// on the same pinned 10-bit 4:4:4 cell - /// `a_444_lossy_palette_chroma_unit_window_is_byte_exact_at_352x242_10bit` - /// gates (fixture sha256 - /// `84df2f37cc7982f9a572443d85dfcc13bf366a64f3fb567391dcd5acd58a0ad2`): - /// every plane of every SHOWN frame must come back byte-exact against - /// ffmpeg's `yuv444p10le` rawvideo of the same bytes, with the depth read - /// from the stream's own sequence header, never assumed. - /// - /// The flip control is the crate's own comparator-liveness shape (the - /// same one - /// [`every_ffmpeg_comparator_reds_on_a_one_sample_wrong_ffmpeg`] runs for - /// the other helpers): with a thread-local ffmpeg shim that rotates ONE - /// byte of the oracle's own rawvideo stdout, the compare must move from - /// 0 to EXACTLY 1 differing sample in the tampered plane and stay at 0 in - /// the other two -- a comparator that cannot see a one-sample difference - /// would make every "byte-exact" claim above vacuous. - #[test] - fn the_444_depth_helper_is_byte_exact_on_a_pinned_10bit_444_cell() { - const NAME: &str = "the_444_depth_helper_is_byte_exact_on_a_pinned_10bit_444_cell"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - let _gate_lock = lock_gate_counters(); - let path = crate_pin("444_lossy_palette_chroma_352x242_10b.obu"); - let stream = read_pin(&path, 24875, 0x7fda_dbb4_3bbf_9af3, NAME); - // The fixture is 16 SHOWN frames; ffmpeg's rawvideo muxer emits shown - // frames only, and so does decode_stream's return. - const W: usize = 352; - const H: usize = 242; - const FRAMES: usize = 16; - assert_eq!(stream_bit_depth(&stream, NAME), 10, "{NAME}: pin depth"); - let ours = decode_stream(&stream) - .unwrap_or_else(|e| panic!("{NAME}: the pinned 10-bit 4:4:4 cell was refused: {e}")); - assert_eq!(ours.len(), FRAMES, "{NAME}: decoded frame count"); - let theirs = ffmpeg_decode_sequence_444_depth(&stream, W, H, FRAMES, 10, "yuv444p10le"); - for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { - for (plane, x, y) in [("Y", &a.y, &b.y), ("U", &a.u, &b.u), ("V", &a.v, &b.v)] { - if let Some(at) = x.iter().zip(y).position(|(p, q)| p != q) { - panic!( - "{NAME}: {plane} differs from ffmpeg's yuv444p10le at frame {i} sample \ - {at} (ours {} vs {}); {n} of {m} samples differ", - x[at], - y[at], - n = x.iter().zip(y).filter(|(p, q)| p != q).count(), - m = x.len() - ); - } - } - } - eprintln!( - "{NAME}: {FRAMES} shown frames byte-exact vs ffmpeg yuv444p10le on the pinned \ - 10-bit 4:4:4 cell" - ); - - // ---- the flip control: one wrong oracle sample must move the count - // 0 -> 1 in exactly the tampered plane ------------------------- - let dir = std::env::temp_dir().join(format!("ec-av1-{NAME}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).expect("scratch dir"); - let real = if let Some(p) = std::env::var_os("EC_AV1_FFMPEG") { - std::path::PathBuf::from(p) - } else { - let found = Command::new("ffmpeg") - .arg("-version") - .stdout(Stdio::null()) - .stderr(Stdio::null()) - .status() - .is_ok_and(|s| s.success()); - assert!(found, "{NAME}: no working ffmpeg on PATH to wrap"); - let path_env = std::env::var_os("PATH").unwrap_or_default(); - std::env::split_paths(&path_env) - .map(|d| d.join("ffmpeg")) - .find(|p| p.is_file()) - .expect("{NAME}: ffmpeg is on PATH but not resolvable to a file") - }; - std::fs::write(dir.join("real-ffmpeg"), real.as_os_str().as_encoded_bytes()) - .expect("recording the real ffmpeg's path for the shim"); - let script = r#"#!/bin/sh -REAL=$(cat "$(dirname "$0")/real-ffmpeg") -OUT=$(mktemp) -"$REAL" "$@" > "$OUT" || exit $? -while read -r o; do - [ -n "$o" ] || continue - b=$(od -An -tu1 -j "$o" -N 1 "$OUT" 2>/dev/null | tr -d ' \n') - [ -n "$b" ] || continue - esc=$(printf '\\%03o' $(( (b + 128) % 256 ))) - printf "$esc" | dd of="$OUT" bs=1 seek="$o" count=1 conv=notrunc 2>/dev/null -done < "$(dirname "$0")/offsets" -cat "$OUT" -rm -f "$OUT" -exit 0 -"#; - let shim = dir.join("one-sample-wrong-ffmpeg.sh"); - std::fs::write(&shim, script).expect("writing the ffmpeg shim"); - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - std::fs::set_permissions(&shim, std::fs::Permissions::from_mode(0o755)) - .expect("the ffmpeg shim must be executable"); - } - let set_offsets = |bytes: &[usize]| { - let body: String = bytes - .iter() - .map(|b| format!("{b}\n")) - .collect::>() - .concat(); - std::fs::write(dir.join("offsets"), body).expect("writing the offsets file"); - }; - let count = |theirs_t: &[Pic]| -> [usize; 3] { - let mut wrong = [0usize; 3]; - for (a, b) in ours.iter().zip(theirs_t) { - for (plane, (x, y)) in - [(0usize, (&a.y, &b.y)), (1, (&a.u, &b.u)), (2, (&a.v, &b.v))] - { - wrong[plane] += x.iter().zip(y).filter(|(p, q)| p != q).count(); - } - } - wrong - }; - // Frame bytes are 3 planes x W*H samples x 2 bytes (10-bit container). - let plane_bytes = W * H * 2; - let mut blind: Vec = Vec::new(); - set_ffmpeg_path(Some(shim.clone())); - for (plane, base) in [("Y", 0usize), ("U", plane_bytes), ("V", 2 * plane_bytes)] { - // Byte 2000 of the named plane: sample 1000, still frame 0 on - // every plane at this geometry. - set_offsets(&[base + 2000]); - let theirs_t = - ffmpeg_decode_sequence_444_depth(&stream, W, H, FRAMES, 10, "yuv444p10le"); - let got = count(&theirs_t); - let mut expected = [0usize, 0, 0]; - expected[match plane { - "Y" => 0, - "U" => 1, - _ => 2, - }] = 1; - if got != expected { - blind.push(format!( - "{plane} arm: counted {got:?}, expected {expected:?} (exactly the one \ - tampered sample)" - )); - } - } - set_ffmpeg_path(None); - let _ = std::fs::remove_dir_all(&dir); - assert!( - blind.is_empty(), - "{NAME}: {} of 3 flip arms stayed GREEN against an ffmpeg that is wrong by exactly \ - one sample -- {blind:#?} -- the comparator cannot see a difference, so its \ - byte-exact verdict proves nothing (class comparator-that-never-reads-the-oracle)", - blind.len() - ); - eprintln!( - "{NAME}: flip control bites on Y, U and V separately (0 -> 1 per tampered plane)" - ); - } - - /// lane-av1oracledepth: `ffmpeg_decode_sequence_10bit` must REFUSE a - /// wrong-depth stream by the stream's OWN sequence header, the way the - /// 12-bit gates read `assert_12bit_sequence_header`. An 8-bit 4:2:0 - /// stream handed to the 10-bit helper is the wrong-depth shape: ffmpeg - /// converts it to `yuv420p10le` and sizes no plane differently, so - /// without the depth assert a gate could compare a converted 8-bit - /// reference against our 10-bit decode and read exact. - #[test] - fn the_10bit_oracle_helper_refuses_a_wrong_depth_stream() { - const NAME: &str = "the_10bit_oracle_helper_refuses_a_wrong_depth_stream"; - let _gate_lock = lock_gate_counters(); - let path = crate_pin("mix176_offtile_chroma_clip.obu"); - let stream = read_pin(&path, 4581, 0x5e31be5efc9c3c1d, NAME); - assert_eq!( - stream_bit_depth(&stream, NAME), - 8, - "{NAME}: the control pin must really be 8-bit, or this proves nothing" - ); - assert_eq!( - stream_subsampling(&stream, NAME), - (1, 1), - "{NAME}: the control pin must really be 4:2:0, or the refusal below could be the \ - shape guard instead of the depth guard" - ); - let msg = panic_message(|| { - ffmpeg_decode_sequence_10bit(&stream, 176, 144, 1); - }) - .unwrap_or_else(|| { - panic!( - "{NAME}: ffmpeg_decode_sequence_10bit ACCEPTED an 8-bit stream -- ffmpeg \ - converted it to yuv420p10le and the helper returned a comparison that could \ - pass green" - ) - }); - assert!( - msg.contains("not 10-bit"), - "{NAME}: the refusal must name the depth guard (\"not 10-bit\"); it said: {msg}" - ); - eprintln!("{NAME}: refused -> {msg}"); - } - - /// lane-av1rawhelper: `assert_rawvideo_matches` used to pack our samples - /// as `u16` for EVERY stream, while `aomdec --rawvideo` writes 8 bits - /// per sample for an 8-bit stream. An 8-bit caller therefore died on a - /// raw-SIZE assertion (2359296 vs 1179648) without comparing a single - /// sample, and a high-bitdepth caller was the only one that could work. - /// - /// Two arms, both on a real `aomenc` 8-bit stream: - /// - /// 1. the correct label compares real samples -- the byte counts it - /// walks equal the oracle's, so every `u8` in the 8-bit pack is - /// zipped against a real oracle byte; - /// 2. a WRONG label fails by name, quoting both depths and the fact that - /// the pack would compare nothing, rather than by size. Arm 2 is what - /// keeps arm 1 from being a green that a reverted check would also - /// give. - #[test] - fn the_rawvideo_helper_compares_real_samples_at_the_streams_own_bit_depth() { - const NAME: &str = "the_rawvideo_helper_compares_real_samples_at_the_streams_own_bit_depth"; - let _gate_lock = lock_gate_counters(); - if !have_aomenc() || !have_ffmpeg() { - eprintln!("SKIP {NAME}: no aomenc/aomdec oracle or no ffmpeg"); - return; - } - let (w, h) = (192usize, 128usize); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &gradients_source(7, w, h, "duration=0.24:rate=25"), - "-pix_fmt", - "yuv420p", - "-t", - "0.24", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "{NAME}: ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=40", - "--cpu-used=2", - "--threads=1", - "--row-mt=0", - "--limit=6", - "--obu", - "-o", - "-", - "-", - ]; - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "{NAME}: aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - assert_eq!( - stream_bit_depth(&stream, NAME), - 8, - "{NAME}: the fixture must really be 8-bit, or this gate measures nothing" - ); - let dir = std::env::temp_dir().join(format!("ec-av1-{NAME}-raw8-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).expect("scratch dir"); - let obu = dir.join("in.obu"); - std::fs::write(&obu, &stream).expect("writing the stream"); - let frames = decode_stream(&stream) - .unwrap_or_else(|e| panic!("{NAME}: the 8-bit stream no longer decodes: {e}")) - .len(); - assert!(frames > 0, "{NAME}: nothing decoded"); - - // ARM 2 first: the wrong label must be refused BY NAME. A helper that - // packed u16 unconditionally got this far and then failed on size. - let wrong = std::panic::catch_unwind(|| { - assert_rawvideo_matches(&obu, &stream, NAME, frames, 10); - }); - let boom = wrong - .err() - .map(|e| e.downcast_ref::().cloned().unwrap_or_default()) - .unwrap_or_default(); - assert!( - boom.contains("sequence header says 8-bit") && boom.contains("compares nothing"), - "{NAME}: a 10-bit label on an 8-bit stream must be refused by the depth check \ - naming both depths; the panic read: {boom}" - ); - - // ARM 1: the correct label compares real samples. The pre-fix helper - // reached a size mismatch here (ours 2x the oracle); reaching the - // sample compare is what this arm proves. - assert_rawvideo_matches(&obu, &stream, NAME, frames, 8); - let _ = std::fs::remove_dir_all(&dir); - eprintln!("{NAME}: {frames} 8-bit frame(s) byte-identical to aomdec --rawvideo"); - } - - /// lane-svtinter: an SVT-AV1 screen stream whose frame height is not a - /// multiple of the superblock size codes PALETTE blocks in the bottom - /// (and right) superblock row that hang off the mi grid. Spec 5.11.50 - /// `palette_tokens` reads the colour-index map only over the block's - /// `onscreenWidth x onscreenHeight` corner and replicates it outward; - /// this decoder read the full block grid, so it consumed colour-index - /// symbols libaom never wrote and desynced the rest of the tile -- either - /// a wrong bottom superblock row (1599 luma samples in this stream's - /// frame 0, ~80k per inter frame after) or, further along the same tile, - /// a bogus "a Golomb tail longer than this decoder reads" refusal. - /// - /// Unlike its lane-svt1 sibling above this one BUILDS its stream: the - /// recipe is synthetic (`smptebars,drawgrid` through `libsvtav1 -preset 8 - /// -svtav1-params screen-content-mode=1`), and 384x152 puts a 32x32 - /// palette block at mi row 32 of a 38-mi-tall frame, 24 of its 32 rows - /// on screen. `palette_onscreen_cut_hits` is asserted non-zero so the row - /// cannot pass on a stream that never cuts a palette map (class - /// gate-blind-to-feature). - #[test] - fn an_svt_screen_palette_map_cut_by_the_frame_edge_decodes_exactly() { - const NAME: &str = "an_svt_screen_palette_map_cut_by_the_frame_edge_decodes_exactly"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - let (width, height) = (384usize, 152usize); - let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - "smptebars=s=384x152:r=12,drawgrid=w=8:h=8:t=1:c=black", - "-frames:v", - "4", - "-c:v", - "libsvtav1", - "-preset", - "8", - "-crf", - "30", - "-svtav1-params", - "lp=1:screen-content-mode=1", - "-g", - "12", - "-f", - "obu", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - if !out.status.success() || out.stdout.is_empty() { - eprintln!( - "SKIP {NAME}: no libsvtav1 in this ffmpeg: {}", - String::from_utf8_lossy(&out.stderr) - ); - return; - } - let stream = out.stdout; - crate::decode::reset_palette_onscreen_cut_hits(); - let decoded = decode_stream(&stream).expect("the SVT-AV1 screen stream decodes"); - assert_eq!(decoded.len(), 4, "{NAME}: frame count"); - assert!( - crate::decode::palette_onscreen_cut_hits() > 0, - "{NAME}: no palette map is cut by the frame edge here -- the gate would pass blind" - ); - let want = ffmpeg_decode_sequence(&stream, width, height, decoded.len()); - assert_eq!(want.len(), decoded.len(), "{NAME}: ffmpeg frame count"); - for (i, (got, want)) in decoded.iter().zip(&want).enumerate() { - assert_eq!(got.y, want.y, "{NAME}: frame {i} luma vs ffmpeg"); - assert_eq!(got.u, want.u, "{NAME}: frame {i} U vs ffmpeg"); - assert_eq!(got.v, want.v, "{NAME}: frame {i} V vs ffmpeg"); - } - } - - /// lane-svt1: an SVT-AV1 (v3.1.2, `-preset 8`) screen key frame codes 16x16 - /// PALETTE blocks with `skip == 1` whose `tx_depth` split the luma - /// transform. [`crate::decode::decode_block`] armed the palette prediction - /// only when the transform covered the whole block, so that one block - /// predicted DC off its own edges instead: the right symbols (the whole mode - /// ladder diffs clean against an instrumented aomdec) and the wrong pixels - /// -- 812 luma samples in frame 0, carried by the V_PRED blocks under it to - /// 10122 samples over the 12-frame stream the defect was found on. - /// - /// lane-av1pinspec2: the gate used to RIDE an external crop named by - /// `EC_AV1_SVT1_STREAM` and SKIP when that was unset, so it never ran on a - /// stock box -- which is exactly why its oracle count could not be pinned - /// (an assert on a gate that never executes is an unexercised assert wearing - /// a pin's clothes). It now runs on the COMMITTED pin - /// `crates/ec-av1/fixtures/svt1-split-tx-pin.obu`. - /// - /// The pin is a REPLAY, not a fresh capture, and the recipe is recorded - /// because it reproduces the bytes exactly (two independent encodes on this - /// box, SVT-AV1 v3.1.2, both sha256 - /// `c9d9c0ae934fba72fc9a9374bc36853f290796a8a4d6442140e239669e0b341f`, - /// 1838 bytes): - /// - /// ffmpeg -v error -f lavfi \ - /// -i "smptehdbars=s=192x152:r=12,drawgrid=w=8:h=8:t=1:c=black" \ - /// -frames:v 1 -c:v libsvtav1 -preset 8 -crf 50 \ - /// -svtav1-params "lp=1:screen-content-mode=1" -g 12 -f obu out.obu - /// - /// `-frames:v 1` is the part lane-svt1's search lacked: its 6x5x6 sweep ran - /// FOUR frames per stream, and the ~200k-sample misses that killed every - /// candidate were on the INTER frames (`lanes/svt1.report.md`). One key - /// frame has no inter frames, and this one reaches the fixed arm - /// (`skip_split_tx_override_hits == 1`) and is pixel-exact. - /// - /// THE COUNT, and why it is derived from the wire rather than from a - /// literal. The oracle is handed the number of frame OBUs this stream - /// actually codes, counted with `Av1Parser` below -- never our decode's - /// length, which is the thing under test. A header count would OVER-count - /// a stream carrying `show_existing_frame` (spec 5.9.5: it codes no pixels, - /// so the header count is larger than the shown-frame count), so that case - /// is asserted impossible on this pin rather than assumed: the loop refuses - /// any frame header with `show_existing_frame` set, which is what makes - /// "one header == one shown frame" a checked fact here instead of an - /// argument. - /// - /// `EC_AV1_SVT1_STREAM` still overrides the pin, so a re-capture is one env - /// var away; `crate_pin` falls back to `pin_dir()` for the same reason. - /// - /// `skip_split_tx_override_hits` is asserted non-zero so the row cannot - /// pass on a stream that never reaches the fixed arm (class - /// gate-blind-to-feature). - #[test] - fn an_svt_screen_palette_block_with_a_split_transform_decodes_exactly() { - const NAME: &str = "an_svt_screen_palette_block_with_a_split_transform_decodes_exactly"; - const PIN: &str = "svt1-split-tx-pin.obu"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - let path = match std::env::var("EC_AV1_SVT1_STREAM") { - Ok(p) => std::path::PathBuf::from(p), - // The name is spelled as a LITERAL here even though `PIN` is right - // above, on purpose: `gate_coverage::pin_inventory` matches a pin - // read by the quote that follows the callee name, so a const - // argument would leave this pin outside the "every pin a gate reads - // is a committed crate-local copy" invariant. The dup is the - // coverage -- and it is also why this comment must NOT quote that - // spelling: the scanner reads prose too, and a quoted spelling here - // parses as a pin called " and would not see a const argument, ...". - Err(_) => crate_pin("svt1-split-tx-pin.obu"), - }; - let data = require_pin(&path, PIN); - // The ENCODE's frame count, read off the WIRE: parse this stream's own - // OBUs and count the frame headers. `show_existing_frame` is refused - // here on purpose -- such a header codes no pixels, so counting it - // would make this count larger than the frames the oracle can decode. - let mut parser = Av1Parser::new(); - let mut pos = 0usize; - let mut frame_headers = 0usize; - while pos < data.len() { - let Ok(obu) = parser.parse_obu(&data[pos..]) else { - break; - }; - pos += obu.total_size.max(1); - let header = match &obu.kind { - ObuKind::Frame(h, _) | ObuKind::FrameHeader(h) => h, - _ => continue, - }; - assert!( - !header.show_existing_frame, - "{NAME}: frame header {frame_headers} sets show_existing_frame, so the header \ - count is not the shown-frame count and this gate's oracle budget would be wrong" - ); - frame_headers += 1; - } - assert!( - frame_headers > 0, - "{NAME}: {} carries no frame header at all", - path.display() - ); - crate::decode::reset_skip_split_tx_override_hits(); - let decoded = decode_stream(&data).expect("the pinned SVT-AV1 screen stream decodes"); - assert!( - crate::decode::skip_split_tx_override_hits() > 0, - "{NAME}: no skipped split-transform palette block in {} -- the gate would pass blind", - path.display() - ); - assert_eq!( - decoded.len(), - frame_headers, - "{NAME}: the stream codes {frame_headers} frame(s), the decode showed {}", - decoded.len() - ); - let (width, height) = (decoded[0].width, decoded[0].height); - let want = ffmpeg_decode_sequence(&data, width, height, frame_headers); - for (i, (got, want)) in decoded.iter().zip(&want).enumerate() { - assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg"); - assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg"); - assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg"); - } - } - - /// `decode_stream` agrees with ffmpeg/dav1d on the same wire bytes -- an - /// independent decoder, not just this crate checking its own tile path. - #[test] - fn decode_stream_agrees_with_ffmpeg_on_a_gop() { - let fctx = &crate::decode::FrameCtx::for_encoder(); - if !have_ffmpeg() { - eprintln!("SKIP decode_stream_agrees_with_ffmpeg_on_a_gop: no ffmpeg"); - return; - } - // lane-av1straddle: 216x96 joins 128x64 because only a size whose - // 32x32 blocks straddle the right-hand frame edge can see the writer - // coding a transform unit that starts outside the frame -- libdav1d - // AND libaom both refused the whole key frame while it did, and this - // crate's own (lenient) decoder only differed in the last block's V. - for &(width, height) in &[(128usize, 64usize), (216usize, 96usize)] { - let pictures: Vec<_> = (0..3) - .map(|i| panned_test_card(width, height, i * 3)) - .collect(); - let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); - let ffmpeg_frames = ffmpeg_decode_sequence(&encoded.stream, width, height, 3); - let decoded = decode_stream(&encoded.stream).unwrap(); - assert_eq!(decoded.len(), 3); - for (i, (got, want)) in decoded.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!(got.y, want.y, "{width}x{height} frame {i} luma vs ffmpeg"); - assert_eq!(got.u, want.u, "{width}x{height} frame {i} U vs ffmpeg"); - assert_eq!(got.v, want.v, "{width}x{height} frame {i} V vs ffmpeg"); - } - // ... and the encoder's own reconstruction is what ffmpeg sees, - // so the check fails on a writer-side desync too, not only on a - // decoder-side one. - for (i, (frame, want)) in encoded.frames.iter().zip(&ffmpeg_frames).enumerate() { - let rec = &frame.reconstruction; - assert_eq!( - rec.y, want.y, - "{width}x{height} frame {i} luma: reconstruction vs ffmpeg" - ); - assert_eq!( - rec.u, want.u, - "{width}x{height} frame {i} U: reconstruction vs ffmpeg" - ); - assert_eq!( - rec.v, want.v, - "{width}x{height} frame {i} V: reconstruction vs ffmpeg" - ); - } - } - } - - /// lane-av1rect: the encoder used to REFUSE every size where a 32x32 - /// block straddles BOTH true frame edges at once ("straddles the true - /// frame edge in a way that needs a rectangular (HORZ/VERT) transform - /// this encoder does not code yet"). That refusal was a misreading of - /// spec 5.11.4: a block whose `hasRows` and `hasCols` are BOTH false - /// reads no partition symbol at all and is `PARTITION_SPLIT` by - /// inference, down to the 8x8 leaves whose own mi origin is inside the - /// frame -- exactly the leaves this writer already codes for the - /// one-axis case, and no rectangular transform anywhere. The sweep walks - /// the corners around the 32-multiples (each width has a 16x16 column - /// whose right half is outside, each height a row whose bottom half is, - /// so the bottom-right 16x16 of every size here is cut on both axes) and - /// three-way compares: our decoder, the encoder's own reconstruction and - /// ffmpeg, over a 4-frame GOP so the inter writer's copy of the same - /// signaling is covered too. `edge_both_cut_hits` proves the decoder - /// really took the inferred-split path rather than the gate passing on - /// geometry that never fires it. - #[test] - fn a_sweep_of_doubly_straddling_sizes_round_trips_through_ffmpeg() { - let fctx = &crate::decode::FrameCtx::for_encoder(); - if !have_ffmpeg() { - eprintln!( - "SKIP a_sweep_of_doubly_straddling_sizes_round_trips_through_ffmpeg: no ffmpeg" - ); - return; - } - const FRAMES: usize = 4; - let mut both_cut = 0usize; - for &width in &[200usize, 216, 232, 248] { - for &height in &[104usize, 120, 136, 152] { - let pictures: Vec<_> = (0..FRAMES as i64) - .map(|i| panned_test_card(width, height, i * 3)) - .collect(); - let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx) - .unwrap_or_else(|e| panic!("{width}x{height}: encoder refused: {e}")); - // Reset per attempt, never a delta across sizes (class - // counter-from-refused-stream). - crate::decode::reset_edge_both_cut_hits(); - let decoded = decode_stream(&encoded.stream) - .unwrap_or_else(|e| panic!("{width}x{height}: our decoder refused: {e}")); - both_cut += crate::decode::edge_both_cut_hits().iter().sum::(); - let ffmpeg_frames = ffmpeg_decode_sequence(&encoded.stream, width, height, FRAMES); - assert_eq!( - ffmpeg_frames.len(), - FRAMES, - "{width}x{height}: ffmpeg decoded {} of {FRAMES} frames", - ffmpeg_frames.len() - ); - assert_eq!(decoded.len(), FRAMES, "{width}x{height}: frame count"); - for (i, (got, want)) in decoded.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!(got.y, want.y, "{width}x{height} frame {i} luma vs ffmpeg"); - assert_eq!(got.u, want.u, "{width}x{height} frame {i} U vs ffmpeg"); - assert_eq!(got.v, want.v, "{width}x{height} frame {i} V vs ffmpeg"); - } - for (i, (frame, want)) in encoded.frames.iter().zip(&ffmpeg_frames).enumerate() { - let rec = &frame.reconstruction; - assert_eq!( - rec.y, want.y, - "{width}x{height} frame {i} luma: recon vs ffmpeg" - ); - assert_eq!( - rec.u, want.u, - "{width}x{height} frame {i} U: recon vs ffmpeg" - ); - assert_eq!( - rec.v, want.v, - "{width}x{height} frame {i} V: recon vs ffmpeg" - ); - } - } - } - assert!( - both_cut > 0, - "no partition node in the whole sweep was coded as the both-axes-cut \ - inferred split -- the gate is blind to the feature it pins" - ); - } - - /// lane-corner: sizes whose LAST superblock is cut by the true frame - /// edge on BOTH axes with more than half of each still inside -- so - /// `has_cols` and `has_rows` are both true and the spec lets that - /// superblock stay a whole 64x64 `PARTITION_NONE` block, which this - /// encoder's roots take (`EC_AV1_B64EDGE` on the inter side, the key - /// frame's own `Superblock::Whole`). The sibling luma-only test - /// (`encoder.rs`'s `a_non_superblock_aligned_clip_...`) is blind to - /// chroma (class `metric-blind-to-a-plane`), so this one compares all - /// three planes three ways: our decoder, the encoder's own - /// reconstruction, and ffmpeg. - #[test] - fn a_doubly_cut_superblock_root_round_trips_in_every_plane() { - let fctx = &crate::decode::FrameCtx::for_encoder(); - if !have_ffmpeg() { - eprintln!("SKIP a_doubly_cut_superblock_root_round_trips_in_every_plane: no ffmpeg"); - return; - } - const FRAMES: usize = 4; - // Each size leaves MORE than half of its last superblock row (and, - // but for 200x120's 8-px column, of its last column) inside, which is - // what makes the root legal there at all; 248x168/232x168/248x184 are - // cut on BOTH axes at once. 1920x1080 -- the user's own export shape - // -- is the same case: 1080 = 16*64 + 56, a 56-px bottom straddle. - for &(width, height) in &[(248usize, 168usize), (232, 168), (200, 120), (248, 184)] { - let pictures: Vec<_> = (0..FRAMES as i64) - .map(|i| panned_test_card(width, height, i * 3)) - .collect(); - let _ = crate::encode::take_b64_edge_hits(); - let _ = crate::encode::take_i64_root_hits(); - let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx) - .unwrap_or_else(|e| panic!("{width}x{height}: encoder refused: {e}")); - let edges = crate::encode::take_b64_edge_hits(); - let [i64_whole, i64_offered, i64_edge] = crate::encode::take_i64_root_hits(); - eprintln!( - "{width}x{height}: edge inter 64 roots {edges}, key 64 roots {i64_whole} of \ - {i64_offered} offered, {i64_edge} of them cut by the frame edge" - ); - // gate-blind-to-feature: without this the three-way compare below - // passes on a stream that never coded a whole root at the cut - // superblock at all. - assert!( - i64_edge > 0, - "{width}x{height}: no 64x64 root sat on a superblock the frame edge cuts" - ); - let decoded = decode_stream(&encoded.stream) - .unwrap_or_else(|e| panic!("{width}x{height}: our decoder refused: {e}")); - let ffmpeg_frames = ffmpeg_decode_sequence(&encoded.stream, width, height, FRAMES); - assert_eq!( - ffmpeg_frames.len(), - FRAMES, - "{width}x{height}: ffmpeg frame count" - ); - assert_eq!(decoded.len(), FRAMES, "{width}x{height}: frame count"); - for (i, (got, want)) in decoded.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!( - got.y, want.y, - "{width}x{height} frame {i} luma: ours vs ffmpeg" - ); - assert_eq!( - got.u, want.u, - "{width}x{height} frame {i} U: ours vs ffmpeg" - ); - assert_eq!( - got.v, want.v, - "{width}x{height} frame {i} V: ours vs ffmpeg" - ); - } - for (i, (frame, want)) in encoded.frames.iter().zip(&ffmpeg_frames).enumerate() { - let rec = &frame.reconstruction; - assert_eq!( - rec.y, want.y, - "{width}x{height} frame {i} luma: recon vs ffmpeg" - ); - assert_eq!( - rec.u, want.u, - "{width}x{height} frame {i} U: recon vs ffmpeg" - ); - assert_eq!( - rec.v, want.v, - "{width}x{height} frame {i} V: recon vs ffmpeg" - ); - } - } - } - - /// A hand-built 3-frame stream that actually fires `GOLDEN_FRAME` - /// through [`decode_stream`], proving the round-4 flip (`decode.rs`'s - /// `decode_inter_block` `GOLDEN_FRAME` arm) the way 120+ real aomenc - /// attempts never could: frame 0 is a real key frame (this crate's own - /// encoder, real texture), refreshing all 8 DPB slots as spec requires -- - /// slot 3 keeps that exact picture from here on. Frame 1 is a hand-coded - /// inter frame whose lone 32x32 block is *intra* (`DC_PRED`, `skip`), - /// refreshing only slot 0 with a flat 128 block -- distinguishable from - /// frame 0's real texture, so slot 0 (`LAST_FRAME`) and slot 3 - /// (`GOLDEN_FRAME`) hold visibly different pictures once frame 2 runs. - /// Frame 2 is a hand-coded inter frame naming `ref_frame_idx[3] = 3` - /// (GOLDEN_FRAME's slot) and `ref_frame_idx[0] = 0` (LAST_FRAME's), whose - /// lone block codes `single_ref` all the way out to `GOLDEN_FRAME` - /// (`p1=0, p3=1, p5=1`) and a `skip` zero-MV `NEARESTMV`: a direct copy - /// of GOLDEN's picture, so its output must equal frame 0's own - /// reconstruction exactly, and must differ from frame 1's -- proof the - /// decoder actually read the golden plane, not silently substituted - /// `LAST_FRAME`'s. Rounds 4-9 masked and re-masked this arm chasing a - /// deblock/MC residue that turned out to be film-grain synthesis - /// (lane-av1golden7's `apply_grain` refusal, unrelated to GOLDEN); - /// lane-av1golden8 fixed mvstack's single-ref extension pass, clearing - /// the last real defect (`pinned_golden7` non_last_ref_hits 0->2), so - /// this fixture flips back to its round-4 pixel-exact form. ffmpeg - /// decodes the identical wire bytes as the foreign oracle - /// (shared-oracle-blindness class): this crate's own decoder agreeing - /// with itself would prove nothing. - #[test] - fn a_hand_built_golden_reference_decodes_pixel_exact_against_ffmpeg() { - let fctx = &crate::decode::FrameCtx::new(); - if !have_ffmpeg() { - eprintln!( - "SKIP a_hand_built_golden_reference_decodes_pixel_exact_against_ffmpeg: no ffmpeg" - ); - return; - } - use crate::cdf_state::Cdfs; - use crate::decode::{intra_inter_ctx, non_last_ref_hits, q_ctx_of}; - use crate::encode::{inter_frame_headers, key_frame_headers}; - use crate::frame::frame_obu; - use crate::msac::SymbolEncoder; - use crate::mvstack::{ - GOLDEN_FRAME, MiGrid, find_mv_stack, single_ref_p1_ctx, single_ref_p3_ctx, - single_ref_p5_ctx, - }; - use crate::obu::temporal_delimiter; - - let (width, height) = (32usize, 32usize); - let base_q_idx = 100u8; - // The whole picture is one 32x32 block: `partition_ctx`/`skip_ctx`/ - // `intra_inter_ctx`'s neighbour inputs are all "no neighbour yet" -- - // a fresh `Neighbours`' `above_side_mi`/`left_side_mi` start at `SB` - // (64), so `partition_ctx_mi`'s `side_mi * 2 <= side` (32) is false - // on both axes (ctx 0), and `above_skip`/`left_skip`/`above_inter`/ - // `left_inter`/`above_ref`/`left_ref` all start `false`/`-1` - // (decode.rs `Neighbours::new`) -- computed here without - // constructing the (module-private) `Neighbours` itself. - const PARTITION_NONE: usize = 0; - let ii_ctx = intra_inter_ctx(false, false, false, false); - let sr_p1_ctx = single_ref_p1_ctx(None, None, None, None); - let sr_p3_ctx = single_ref_p3_ctx(None, None, None, None); - let sr_p5_ctx = single_ref_p5_ctx(None, None, None, None); - - for run in 0..4 { - let picture = test_card(width, height); - let key = encode_key_frame_with_ctx(&picture, base_q_idx, 0.5, fctx).unwrap(); - let (seq, _) = key_frame_headers(width, height, base_q_idx).unwrap(); - - // Frame 1: hand-coded, intra-only, refreshes slot 0 with a flat - // 128 block (no neighbours to predict `DC_PRED` from). - let (_, mut header1) = inter_frame_headers(width, height, base_q_idx, 1, 0).unwrap(); - // These two tiles are hand-coded from a FRESH `Cdfs`, so the - // frames must not carry CDF state the way the encoder's own inter - // frames now do (spec 7.20): with the bit set, what each frame - // stores is what it started from -- the defaults -- which is - // exactly what the next hand-coded tile assumes. - header1.disable_frame_end_update_cdf = true; - let tile1 = { - let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx)); - let mut enc = SymbolEncoder::new(); - enc.symbol(PARTITION_NONE, &mut cdfs.partition_w32[0]); - enc.symbol(1, &mut cdfs.skip[0]); // skip - enc.symbol(0, &mut cdfs.intra_inter[ii_ctx]); // is_inter = false - enc.symbol(0, &mut cdfs.y_mode[3]); // DC_PRED, size group 3 (32x32) - enc.symbol(0, &mut cdfs.uv_mode_cfl[0]); // DC_PRED - enc.finish() - }; - let mut stream = key.stream.clone(); - stream.extend(temporal_delimiter()); - stream.extend(frame_obu(&seq, &header1, &tile1).unwrap()); - - // Frame 2: hand-coded, single_ref all the way to GOLDEN_FRAME, - // skip zero-MV NEARESTMV -- a direct copy of slot 3 (frame 0). - let (_, mut header2) = inter_frame_headers(width, height, base_q_idx, 2, 0).unwrap(); - header2.disable_frame_end_update_cdf = true; - header2.ref_frame_idx[3] = 3; // GOLDEN_FRAME's own slot: frame 0's, untouched by frame 1 - let tile2 = { - let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx)); - let mut enc = SymbolEncoder::new(); - let grid = MiGrid::new(8, 8); - let stack = find_mv_stack(&grid, 0, 0, 8, 8, GOLDEN_FRAME, 8, 8); - enc.symbol(PARTITION_NONE, &mut cdfs.partition_w32[0]); - enc.symbol(1, &mut cdfs.skip[0]); // skip - enc.symbol(1, &mut cdfs.intra_inter[ii_ctx]); // is_inter = true - enc.symbol(0, &mut cdfs.single_ref[sr_p1_ctx][0]); // p1: LAST/LAST2/LAST3/GOLDEN group - enc.symbol(1, &mut cdfs.single_ref[sr_p3_ctx][2]); // p3: GOLDEN/LAST3 sub-group - enc.symbol(1, &mut cdfs.single_ref[sr_p5_ctx][4]); // p5: GOLDEN_FRAME - enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not_new -> not NEWMV - enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not_zero -> not GLOBALMV - enc.symbol(0, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // nearest -> NEARESTMV, (0, 0) - enc.finish() - }; - stream.extend(temporal_delimiter()); - stream.extend(frame_obu(&seq, &header2, &tile2).unwrap()); - - let before = non_last_ref_hits(); - let decoded = decode_stream(&stream).unwrap(); - assert_eq!(decoded.len(), 3, "run {run}: expected 3 pictures"); - assert!( - non_last_ref_hits() > before, - "run {run}: GOLDEN_FRAME never fired" - ); - - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 3); - for (i, (got, want)) in decoded.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!(got.y, want.y, "run {run} frame {i}: luma vs ffmpeg"); - assert_eq!(got.u, want.u, "run {run} frame {i}: U vs ffmpeg"); - assert_eq!(got.v, want.v, "run {run} frame {i}: V vs ffmpeg"); - } - assert_eq!( - decoded[0].y, key.reconstruction.y, - "run {run}: frame 0 vs the encoder's own reconstruction" - ); - assert_eq!( - decoded[2].y, key.reconstruction.y, - "run {run}: GOLDEN_FRAME's block did not reproduce the keyframe it names" - ); - assert_ne!( - decoded[2].y, decoded[1].y, - "run {run}: LAST_FRAME's and GOLDEN_FRAME's slots were not actually \ - distinguishable -- the gate proves nothing" - ); - } - } - - /// The determinism guard: same seed twice must byte-match ffmpeg's own - /// output; different seeds must not. Regresses this fix if it ever - /// breaks. - #[test] - fn gradients_source_is_reproducible_per_seed() { - if !have_ffmpeg() { - eprintln!("SKIP gradients_source_is_reproducible_per_seed: no ffmpeg"); - return; - } - fn render_hash(lavfi: &str) -> Vec { - let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - lavfi, - "-frames:v", - "1", - "-f", - "rawvideo", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!(out.status.success(), "ffmpeg refused {lavfi}"); - out.stdout - } - let a1 = render_hash(&gradients_source(42, 64, 64, "duration=0.04:rate=25")); - let a2 = render_hash(&gradients_source(43, 64, 64, "duration=0.04:rate=25")); - let a3 = render_hash(&gradients_source(42, 64, 64, "duration=0.04:rate=25")); - assert_eq!(a1, a3, "same seed must reproduce byte-identical output"); - assert_ne!(a1, a2, "different seeds must not collide"); - } - - /// The end-to-end gate: two real libaom-av1 configs, decoded with - /// [`decode_stream`] and checked against ffmpeg's own decode of the same - /// bytes. Not every config this encoder writes decodes yet (partitions - /// below 16x16, AB partitions, CfL and others remain round-2 gaps per the - /// r6 catalogue) -- both configs here pick `cpu-used 8` plus the - /// partition/angle-delta/CfL flags r6 found narrow the encoder onto this - /// decoder's supported syntax, while still landing on non-`DCT_DCT` tx - /// types on gradient content. - #[test] - fn a_real_libaom_stream_with_adst_decodes_end_to_end() { - if !have_ffmpeg() { - eprintln!("SKIP a_real_libaom_stream_with_adst_decodes_end_to_end: no ffmpeg"); - return; - } - let configs: [(String, usize, usize, u32); 2] = [ - ("testsrc2=size=64x64:rate=1".to_string(), 64, 64, 15), - (gradients_source(42, 64, 64, "rate=1"), 64, 64, 15), - ]; - let mut verdicts = Vec::new(); - for (lavfi, width, height, crf) in configs { - let lavfi = lavfi.as_str(); - let Some(stream) = libaom_encode(lavfi, width, height, crf) else { - verdicts.push(format!("{lavfi}: ffmpeg itself refused to encode")); - continue; - }; - match decode_stream(&stream) { - Ok(frames) => { - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1); - let matches = frames[0].y == ffmpeg_frames[0].y - && frames[0].u == ffmpeg_frames[0].u - && frames[0].v == ffmpeg_frames[0].v; - verdicts.push(format!( - "{lavfi}: decoded, {} ffmpeg's own decode", - if matches { "MATCHES" } else { "MISMATCHES" } - )); - // Not a hard `assert!`: libaom's own mode decisions at - // `cpu-used 8` are not observed stable run-to-run on this - // box (multi-threaded RD search), so a run that happens - // to land on a still-unsupported syntax element (e.g. a - // partition below 16x16, a separate round-2 gap) can - // decode without erroring yet disagree -- that failure - // mode belongs to those other gaps, not to this round's - // ADST wiring, and the eprintln below reports it either - // way rather than hiding it. - } - Err(e) => { - verdicts.push(format!("{lavfi}: still refuses ({e})")); - } - } - } - eprintln!("libaom ADST end-to-end verdicts:"); - for v in &verdicts { - eprintln!(" {v}"); - } - } - - /// lane-dgolomb: the `force_integer_mv` gate. libaom turns screen-content - /// tools on for DARK, SMOOTH content -- its `av1_set_screen_content_options` - /// counts 16x16 blocks with 2..=4 distinct luma values -- and then sets - /// `force_integer_mv` on any inter frame whose source is pixel-identical to - /// the previously coded source (`av1_is_integer_mv`: `cs_rate >= 0.8` and - /// `C == T`, every collocated 8x8 block matching, is the only path that - /// returns 1). Both hold on his real AV1 films, and this decoder used to - /// drop `lower_mv_precision`'s `is_integer` half as unreachable, so every - /// temporal MV candidate on such a frame came out at eighth-pel: the frame - /// decoded without any error into a whole-frame prediction mismatch, and - /// the desync surfaced blocks later as "a Golomb tail longer than this - /// decoder reads". - /// - /// The source is SYNTHETIC (no film sample lives in `fixtures`): the - /// near-flat dark pattern libaom's own screen-content detector counts as - /// screen content, at the film-B crop size 1920x1024, SCROLLING globally - /// 5 px per frame and frozen on frame 8 -- an exact duplicate of frame 7 - /// (the `C == T` trigger) whose twin is not among its own references, so - /// its blocks still code real motion under `force_integer_mv`. - /// - /// lane-dpm1 made this gate SENSITIVE: with the `force_integer_mv` branch - /// of [`crate::motion_field::lower_mv_precision`] stubbed out (`if false - /// &&`) the stream decodes WRONG -- frame 8, luma sample 25695, 20 against - /// ffmpeg's 19 -- where the previous patch-in-a-static-background recipe - /// (and two others tried) still decoded byte-exact: there the used mv-stack - /// slots came from agreeing spatial neighbours and the rounded temporal - /// entries never won one. The gate asserts both halves: at least one INTER - /// frame really carries `force_integer_mv` (class `gate-blind-to-feature`), - /// and every shown frame decodes sample-exact against ffmpeg's own decode. - #[test] - fn a_libaom_force_integer_mv_stream_decodes_exact() { - const NAME: &str = "a_libaom_force_integer_mv_stream_decodes_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - let (w, h, frames) = (1920usize, 1024usize, 16usize); - let mut raw = Vec::with_capacity(frames * w * h * 3 / 2); - let mut off = 0usize; - for f in 0..frames { - // lane-dpm1: the WHOLE picture scrolls 5 px per frame and freezes - // on frame 8, so (a) every block of the frozen frame -- including - // mi(0,0), which has no spatial neighbour at all -- still codes - // real motion against the references that are not its twin, and - // (b) 40 eighth-pels projected over the pyramid's distances lands - // on non-multiples of 8 (40/2 = 20 -> 16). A patch moving inside a - // static background was NOT sensitive: there the used stack slots - // came from spatial neighbours that agreed, and the rounded - // temporal entries never won one. - if f > 0 && f != 8 { - off = (off + 5) % h; - } - let mut y = vec![0u8; w * h]; - for row in 0..h { - let src = (row + off) % h; - for col in 0..w { - // 2..=4 distinct values per 16x16 block, all dark: the - // screen-content detector's own counting rule. - y[row * w + col] = - 16 + ((col / 32 + src / 32) % 5) as u8 + ((col / 4 + src / 4) % 3) as u8; - } - } - raw.extend_from_slice(&y); - raw.extend(std::iter::repeat_n(128u8, w * h / 2)); - } - // [[pid-keyed-temp-path]]: parallel test binaries must not share a name. - let src = std::env::temp_dir().join(format!("ec-av1-intmv-{}.yuv", std::process::id())); - std::fs::write(&src, &raw).expect("raw source"); - let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"]) - .args(["-s", &format!("{w}x{h}"), "-r", "24", "-i"]) - .arg(&src) - .args(["-an", "-threads", "1", "-g", "16", "-c:v", "libaom-av1"]) - .args([ - "-cpu-used", - "6", - "-b:v", - "0", - "-crf", - "35", - "-f", - "obu", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - let _ = std::fs::remove_file(&src); - if !out.status.success() { - eprintln!( - "SKIP {NAME}: ffmpeg has no libaom-av1 encoder ({})", - String::from_utf8_lossy(&out.stderr) - ); - return; - } - let stream = out.stdout; - - // Half of the gate: the stream must actually carry the feature. - let mut parser = Av1Parser::new(); - let (mut pos, mut int_mv_inter) = (0usize, 0usize); - while pos < stream.len() { - let obu = parser.parse_obu(&stream[pos..]).expect("libaom OBU parses"); - pos += obu.total_size.max(1); - let header = match &obu.kind { - ObuKind::FrameHeader(h) | ObuKind::Frame(h, _) => h, - _ => continue, - }; - if header.force_integer_mv && !header.frame_is_intra && header.use_ref_frame_mvs { - int_mv_inter += 1; - } - } - assert!( - int_mv_inter > 0, - "{NAME} went blind: libaom coded no inter frame with force_integer_mv" - ); - - let ours = decode_stream(&stream).expect("libaom screen-content stream decodes"); - let theirs = ffmpeg_decode_sequence(&stream, w, h, frames); - assert_eq!(ours.len(), frames, "shown frame count"); - for (i, (a, b)) in ours.iter().zip(theirs.iter()).enumerate() { - for (plane, l, r) in [("Y", &a.y, &b.y), ("U", &a.u, &b.u), ("V", &a.v, &b.v)] { - let first = l.iter().zip(r.iter()).position(|(x, y)| x != y); - assert!( - first.is_none(), - "frame {i} plane {plane} differs from ffmpeg at sample {} \ - ({int_mv_inter} force_integer_mv inter frames in this stream)", - first.unwrap() - ); - assert_eq!( - l.len(), - r.len(), - "frame {i} plane {plane}: ours has {} samples, ffmpeg's has {} -- a short \ - plane would zip-truncate the compare above and hide a chroma-span defect", - l.len(), - r.len() - ); - } - } - } - - /// lane-dpm1: the 128x128-INTRA-inside-an-INTER-frame chroma context gate. - /// A 128x128 block codes its chroma as four TX_32X32 units, one per 64x64 - /// mu chunk, and libaom stamps the coefficient context PER UNIT. The two - /// INTER mu-chunk sites set `mu_chroma` so the block tail re-stamps the - /// four units in mu order; the INTRA-in-inter site did not, so the - /// whole-block record left every unit carrying the TOP-LEFT unit's level. - /// The next block then read its `txb_skip` off ctx 11 where libaom reads - /// ctx 10 (class `override-slot-on-one-arm`) -- one symbol on the wrong - /// CDF row, tile desynced, and because the loop-restoration coefficients - /// live in the same tile data the damage showed up as a +-1 luma sample at - /// the TOP of the frame (measured: frame 1, luma sample 66, ours 146 / - /// ffmpeg 145, with 1.7M samples wrong behind it). - /// - /// Source: the repository's own 2160p colour-bar fixture at the native - /// gate's crop (1920x1024 out of the middle), 12 frames, libaom - /// `-cpu-used 6 -crf 45 -g 12` -- the first reference point of - /// `bd_rate_screen_native`'s "bars 2160p" row, which is where the assertion - /// caught it. The gate asserts the tool fired (class - /// `gate-blind-to-feature`) and that every shown frame decodes sample-exact - /// against ffmpeg's own decode. - #[test] - fn a_libaom_stream_with_128_intra_blocks_in_inter_frames_decodes_exact() { - const NAME: &str = "a_libaom_stream_with_128_intra_blocks_in_inter_frames_decodes_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - // lane-av1clipprobe: the bare `clip.exists()` -> SKIP had no env - // escape, so on a tree with no root `fixtures/` this 128-intra-block - // gate reported green having decoded nothing. - let Some(clip) = crate::library_fixture::require("video/h264-2160p-23.976-8bit.mp4", NAME) - else { - return; - }; - let (w, h, frames) = (1920usize, 1024usize, 12usize); - // [[pid-keyed-temp-path]]: parallel test binaries must not share a name. - let src = std::env::temp_dir().join(format!("ec-av1-i128-{}.yuv", std::process::id())); - let load = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args(["-v", "error", "-y", "-i"]) - .arg(&clip) - .args([ - "-frames:v", - &frames.to_string(), - "-vf", - "crop=1920:1024:960:568", - ]) - .args(["-f", "rawvideo", "-pix_fmt", "yuv420p"]) - .arg(&src), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - load.status.success(), - "{NAME}: {}", - String::from_utf8_lossy(&load.stderr) - ); - let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"]) - .args(["-s", &format!("{w}x{h}"), "-r", "24", "-i"]) - .arg(&src) - .args(["-an", "-threads", "1", "-g", "12", "-c:v", "libaom-av1"]) - .args([ - "-cpu-used", - "6", - "-b:v", - "0", - "-crf", - "45", - "-f", - "obu", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - let _ = std::fs::remove_file(&src); - if !out.status.success() { - eprintln!( - "SKIP {NAME}: ffmpeg has no libaom-av1 encoder ({})", - String::from_utf8_lossy(&out.stderr) - ); - return; - } - let stream = out.stdout; - let before = crate::decode::intra_128_in_inter_hits(); - let ours = decode_stream(&stream).expect("libaom bars stream decodes"); - assert!( - crate::decode::intra_128_in_inter_hits() > before, - "{NAME} went blind: no 128-rooted intra block inside an inter frame" - ); - let theirs = ffmpeg_decode_sequence(&stream, w, h, frames); - assert_eq!(ours.len(), frames, "shown frame count"); - for (i, (a, b)) in ours.iter().zip(theirs.iter()).enumerate() { - for (plane, l, r) in [("Y", &a.y, &b.y), ("U", &a.u, &b.u), ("V", &a.v, &b.v)] { - let first = l.iter().zip(r.iter()).position(|(x, y)| x != y); - assert!( - first.is_none(), - "frame {i} plane {plane} differs from ffmpeg at sample {}", - first.unwrap() - ); - assert_eq!( - l.len(), - r.len(), - "frame {i} plane {plane}: ours has {} samples, ffmpeg's has {} -- a short \ - plane would zip-truncate the compare above and hide a chroma-span defect", - l.len(), - r.len() - ); - } - } - } - - /// lane-lossless: the refusal became an implementation, so its gate became - /// a DECODE-EXACT one (class `refusal-lifted-without-a-gate`). libaom at - /// `-crf 0` codes `base_q_idx == 0` -- the same lossless frame his - /// screen-capture row gets at `-crf 5` -- where every plane is TX_4X4 with - /// the Walsh-Hadamard transform, no `tx_type` symbol is coded - /// (`read_tx_type`, `decodetxb.c`: "No need to read transform type for - /// lossless mode(qindex==0)") and `is_cfl_allowed` (`blockd.h`) narrows to - /// a BLOCK_4X4 chroma plane block. The gate asserts the stream really is - /// lossless (class `gate-blind-to-feature`), that every KEY frame decodes - /// sample-exact against ffmpeg, and that the still-unimplemented lossless - /// INTER frame is refused BY NAME rather than decoded wrong. - #[test] - fn a_lossless_libaom_key_frame_decodes_sample_exact() { - const NAME: &str = "a_lossless_libaom_key_frame_decodes_sample_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - let (w, h, frames) = (256usize, 128usize, 2usize); - let mut raw = Vec::with_capacity(frames * w * h * 3 / 2); - for f in 0..frames { - for row in 0..h { - for col in 0..w { - raw.push(((col * 7 + row * 13 + f * 31) % 251) as u8); - } - } - // lane-lossless2: TEXTURED chroma. A flat chroma plane codes one - // `txb_skip` symbol per 4x4 unit with every context at 0, which - // is blind to both the unit ORDER and the per-unit contexts - // (class `gate-blind-to-feature`). - for row in 0..h / 2 { - for col in 0..w / 2 { - raw.push((((col + f) * 11 + row * 5) % 251) as u8); - } - } - for row in 0..h / 2 { - for col in 0..w / 2 { - raw.push(((col * 3 + (row + f) * 17) % 251) as u8); - } - } - } - // [[pid-keyed-temp-path]]: parallel test binaries must not share a name. - let src = std::env::temp_dir().join(format!("ec-av1-lossless-{}.yuv", std::process::id())); - std::fs::write(&src, &raw).expect("raw source"); - let encode = |gop: &str| { - - crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"]) - .args(["-s", &format!("{w}x{h}"), "-r", "24", "-i"]) - .arg(&src) - .args(["-an", "-threads", "1", "-g", gop, "-c:v", "libaom-av1"]) - .args(["-cpu-used", "6", "-b:v", "0", "-crf", "0", "-f", "obu", "-"]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run") - }; - let out = encode("1"); - let _ = std::fs::remove_file(&src); - if !out.status.success() { - eprintln!( - "SKIP {NAME}: ffmpeg has no libaom-av1 encoder ({})", - String::from_utf8_lossy(&out.stderr) - ); - return; - } - let stream = out.stdout; - // Half of the gate: the stream must really carry a lossless frame - // (class `gate-blind-to-feature`). - let mut parser = Av1Parser::new(); - let (mut pos, mut lossless) = (0usize, 0usize); - while pos < stream.len() { - let obu = parser.parse_obu(&stream[pos..]).expect("libaom OBU parses"); - pos += obu.total_size.max(1); - let header = match &obu.kind { - ObuKind::FrameHeader(h) | ObuKind::Frame(h, _) => h, - _ => continue, - }; - if header.lossless.iter().all(|&l| l) { - lossless += 1; - } - } - assert_eq!( - lossless, frames, - "{NAME} went blind: libaom coded no lossless key frame at -crf 0" - ); - let ours = decode_stream(&stream).expect("a lossless key-frame stream decodes"); - let refs = ffmpeg_decode_sequence(&stream, w, h, frames); - assert_eq!(ours.len(), frames, "{NAME}: frame count"); - for (i, (got, want)) in ours.iter().zip(refs.iter()).enumerate() { - for (plane, (g, r)) in [(&got.y, &want.y), (&got.u, &want.u), (&got.v, &want.v)] - .iter() - .enumerate() - { - let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count(); - assert_eq!( - bad, 0, - "{NAME}: frame {i} plane {plane}: {bad} samples differ" - ); - assert_eq!( - g.len(), - r.len(), - "{NAME}: frame {i} plane {plane}: ours has {} samples, ffmpeg's has {} -- a \ - short plane would zip-truncate the compare above and hide a chroma-span \ - defect", - g.len(), - r.len() - ); - } - } - } - - /// lane-lossless2: the refusal `a_lossless_inter_frame_is_refused_by_name` - /// pinned became an implementation, so its gate became a DECODE-EXACT one - /// (class `refusal-lifted-without-a-gate`). A lossless INTER frame codes - /// its chroma plane as 4x4 transform units, plane-major inside each 64x64 - /// mu chunk (libaom `read_tx_size` returns TX_4X4 for every plane under - /// `xd->lossless[..]`, and `decode_token_recon_block` walks - /// `for (plane..) for (blk_row..) for (blk_col..)`), which is what - /// `decode::read_inter_chroma_lossless` reads. The source carries TEXTURED - /// CHROMA and real motion on purpose: a flat-chroma source codes one - /// `txb_skip` symbol per unit and is blind to both the unit order and the - /// per-unit contexts (class `gate-blind-to-feature`). - #[test] - fn a_lossless_libaom_inter_frame_decodes_sample_exact() { - const NAME: &str = "a_lossless_libaom_inter_frame_decodes_sample_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - // (w, h, frames, gop, bit depth, 128-superblock, screen content) - // lane-lossless2: the SCREEN rows carry palette blocks, which is what - // caught the whole-block palette prediction being handed to a 4x4 - // chroma unit. - // lane-lossless3: the last row is a screen source with INTER frames -- - // the row that caught both of this lane's defects (a skip 8x8 leaf - // restoring the previous block's luma level band over the zeros - // `av1_reset_entropy_context` writes, and a rect sub-8x8 INTRA leaf - // reading one TX_4X8 unit where a lossless frame codes two TX_4X4). - let cases: [(usize, usize, usize, &str, u32, bool, bool); 7] = [ - (256, 128, 8, "4", 8, false, false), - (192, 96, 6, "3", 10, false, false), - (320, 192, 6, "3", 8, false, false), - (256, 256, 4, "2", 8, true, false), - (320, 192, 2, "1", 8, false, true), - (640, 384, 2, "1", 8, false, true), - (640, 384, 6, "3", 8, false, true), - ]; - for &(w, h, frames, gop, depth, sb128, screen) in &cases { - let tag = format!( - "{w}x{h} {depth}-bit gop {gop}{}{}", - if sb128 { " sb128" } else { "" }, - if screen { " screen" } else { "" } - ); - let mut raw: Vec = Vec::new(); - let put = |v: u32, raw: &mut Vec| { - if depth == 10 { - raw.extend_from_slice(&((v * 4) as u16).to_le_bytes()); - } else { - raw.push(v as u8); - } - }; - // A screen source is a few flat colours in 16x16 tiles plus - // 1-px text-like rows -- what makes libaom code palette blocks. - const PAL: [u32; 8] = [16, 60, 110, 145, 180, 210, 235, 128]; - for f in 0..frames { - for row in 0..h { - for col in 0..w { - let v = if screen { - if row % 7 == 0 && col % 3 == 0 { - if (col / 3 + row + f) % 2 == 1 { - 16 - } else { - 235 - } - } else { - PAL[((col + 4 * f) / 16 + row / 16) % PAL.len()] - } - } else { - (((col + 2 * f) * 7 + row * 13) % 251) as u32 - }; - put(v, &mut raw); - } - } - for plane in 0..2usize { - for row in 0..h / 2 { - for col in 0..w / 2 { - let v = if screen { - PAL[((col + 2 * f) / 8 + row / 8 + plane) % PAL.len()] - } else if plane == 0 { - (((col + f) * 11 + row * 5) % 251) as u32 - } else { - ((col * 3 + (row + f) * 17) % 251) as u32 - }; - put(v, &mut raw); - } - } - } - } - let pix = if depth == 10 { - "yuv420p10le" - } else { - "yuv420p" - }; - // [[pid-keyed-temp-path]]: parallel test binaries must not share a name. - let src = std::env::temp_dir().join(format!( - "ec-av1-lossless2-{}-{w}x{h}-{depth}.yuv", - std::process::id() - )); - std::fs::write(&src, &raw).expect("raw source"); - let mut cmd = Command::new("ffmpeg"); - cmd.args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", pix]) - .args(["-s", &format!("{w}x{h}"), "-r", "24", "-i"]) - .arg(&src) - .args(["-an", "-threads", "1", "-g", gop, "-c:v", "libaom-av1"]) - .args(["-pix_fmt", pix, "-cpu-used", "6", "-b:v", "0", "-crf", "0"]); - if sb128 { - cmd.args(["-aom-params", "sb-size=128"]); - } - if screen { - cmd.args(["-aom-params", "tune-content=screen"]); - } - let out = crate::tool_cache::cached_output_io(cmd - .args(["-f", "obu", "-"]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - let _ = std::fs::remove_file(&src); - if !out.status.success() { - eprintln!( - "SKIP {NAME}: ffmpeg has no libaom-av1 encoder ({})", - String::from_utf8_lossy(&out.stderr) - ); - return; - } - let stream = out.stdout; - // The stream must really be lossless AND really carry inter frames - // (class `gate-blind-to-feature`). - let mut parser = Av1Parser::new(); - let (mut pos, mut lossless, mut inters) = (0usize, 0usize, 0usize); - while pos < stream.len() { - let obu = parser.parse_obu(&stream[pos..]).expect("libaom OBU parses"); - pos += obu.total_size.max(1); - let header = match &obu.kind { - ObuKind::FrameHeader(h) | ObuKind::Frame(h, _) => h, - _ => continue, - }; - if header.lossless.iter().all(|&l| l) { - lossless += 1; - } - if header.frame_type == FrameType::Inter { - inters += 1; - } - } - assert!( - lossless >= frames, - "{NAME} [{tag}] went blind: {lossless} lossless frames" - ); - assert!( - screen || inters > 0, - "{NAME} [{tag}] went blind: no inter frame at gop {gop}" - ); - let ours = decode_stream(&stream) - .unwrap_or_else(|e| panic!("{NAME} [{tag}]: a lossless inter stream decodes: {e}")); - let refs = if depth == 10 { - ffmpeg_decode_sequence_10bit(&stream, w, h, frames) - } else { - ffmpeg_decode_sequence(&stream, w, h, frames) - }; - assert_eq!(ours.len(), frames, "{NAME} [{tag}]: frame count"); - for (i, (got, want)) in ours.iter().zip(refs.iter()).enumerate() { - for (plane, (g, r)) in [(&got.y, &want.y), (&got.u, &want.u), (&got.v, &want.v)] - .iter() - .enumerate() - { - let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count(); - assert_eq!( - bad, 0, - "{NAME} [{tag}]: frame {i} plane {plane}: {bad} samples differ" - ); - assert_eq!( - g.len(), - r.len(), - "{NAME} [{tag}]: frame {i} plane {plane}: ours has {} samples, ffmpeg's has \ - {} -- a short plane would zip-truncate the compare above and hide a \ - chroma-span defect", - g.len(), - r.len() - ); - } - } - } - } - - /// lane-av1-llband: the pinned 4:4:4 LOSSLESS key frame - /// (`fixtures/ll444-lossless-key.obu`, the `ll444` recipe's frame 0 -- - /// `testsrc2 128x96` yuv444p cut to its key frame) decodes sample-exact, - /// and its HORZ/VERT strips really walked their chroma as 4x4 units at - /// subsampling 0/0 (one unit per mi cell). That unit walk used the 4:2:0 - /// span (8 luma px per 4x4 chroma unit) unconditionally, so every unit - /// past the first column/row read its `txb_skip` context two mi cells - /// over and stamped a 2-cell smear -- the 178-byte key-frame miss, first - /// divergence at the 16x8 leaf mi (16,24)'s U bc=2 unit (oracle - /// `txb_skip` base 0 off `above[26]`, ours base 1 off the polluted - /// `above[29]`). The counter assertion is the non-vacuity half (class - /// `gate-blind-to-feature`): a stream that never reaches the 4:4:4 unit - /// walk must not pass. - #[test] - fn a_real_aomenc_lossless_444_key_frame_decodes_sample_exact() { - const NAME: &str = "a_real_aomenc_lossless_444_key_frame_decodes_sample_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - // lane-av1pins: committed at crates/ec-av1/fixtures/ll444-lossless-key.obu - // (7845 bytes; sha256 - // f496ef0a1171c2bc66d411cc60db05db547dcdb49cd834d4e0543de9db441374), - // re-encoded 2026-09-29 from the recipe this very SKIP line records -- - // `testsrc2 128x96` yuv444p 6 frames, aomenc --profile=1 --lossless=1 - // --enable-palette=0 --enable-intrabc=0 --bit-depth=8 --cpu-used=0 - // --threads=1 --row-mt=0 --lag-in-frames=0 --kf-max-dist=100, --limit=1 - // so the key frame's OBUs are the whole stream (no OBU surgery needed). - // - // lane-av1skipfix: reading the pin from the GITIGNORED root - // `fixtures/` (`pin_dir()`) is what made this gate report green having - // decoded nothing -- a fresh clone, and every linked worktree, can - // never have that directory. The pin is now COMMITTED under the crate - // (the home the other pins use) and read through `CARGO_MANIFEST_DIR`, - // so a missing file is a REPO DEFECT and fails unconditionally: there - // is no environment left to escape, which is strictly stronger than - // the `EC_REQUIRE_FIXTURES` / `EC_AV1_REQUIRE_AOMENC` opt-in hard - // fail this arm used to carry. - let pin = crate_pin("ll444-lossless-key.obu"); - let stream = std::fs::read(&pin).unwrap_or_else(|e| { - panic!( - "{NAME}: the pinned 4:4:4 lossless key frame is missing at {} ({e}). A \ - COMMITTED pin that is absent is a repo defect and this gate would prove \ - nothing. No script generates it -- regenerate it with `testsrc2 128x96` \ - yuv444p 6 frames, aomenc --profile=1 --lossless=1 --enable-palette=0 \ - --enable-intrabc=0 --bit-depth=8 --cpu-used=0 --threads=1 --row-mt=0 \ - --lag-in-frames=0 --kf-max-dist=100 --limit=1, and commit the result.", - pin.display() - ) - }); - // Blindness guard: the pinned fixture must really be a lossless frame. - let mut parser = Av1Parser::new(); - let mut pos = 0usize; - let mut lossless = false; - while pos < stream.len() { - let obu = parser.parse_obu(&stream[pos..]).expect("aomenc OBU parses"); - pos += obu.total_size.max(1); - if let ObuKind::FrameHeader(h) | ObuKind::Frame(h, _) = obu.kind { - lossless = h.lossless.iter().all(|&l| l); - } - } - assert!( - lossless, - "{NAME} went blind: the pinned frame is not lossless" - ); - let before = crate::decode::rect_split_lossless_chroma444_hits(); - let ours = decode_stream(&stream).expect("a 444 lossless key-frame stream decodes"); - assert_eq!(ours.len(), 1, "{NAME}: frame count"); - assert!( - crate::decode::rect_split_lossless_chroma444_hits() > before, - "{NAME} went blind: no lossless HORZ/VERT strip walked its chroma \ - as 4x4 units at subsampling 0/0" - ); - let refs = Command::new("ffmpeg") - .args([ - "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv444p", "-", - ]) - .stdin(Stdio::piped()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .spawn() - .and_then(|mut child| { - use std::io::Write as _; - child.stdin.as_mut().expect("stdin").write_all(&stream)?; - child.wait_with_output() - }) - .expect("ffmpeg 444 decode failed"); - assert!( - refs.status.success(), - "{}", - String::from_utf8_lossy(&refs.stderr) - ); - let frame = &ours[0]; - let planes = [ - (&frame.y, frame.width * frame.height), - (&frame.u, frame.width * frame.height), - (&frame.v, frame.width * frame.height), - ]; - let mut off = 0usize; - for (plane, (g, len)) in planes.iter().enumerate() { - let raw = &refs.stdout[off..off + len]; - let bad = g - .iter() - .zip(raw.iter()) - .filter(|&(&a, &b)| a != u16::from(b)) - .count(); - assert_eq!(bad, 0, "{NAME}: plane {plane}: {bad} samples differ"); - off += len; - } - } - - /// lane-av1-llinter: the firing gate for the lossless 4:4:4 INTER chroma - /// fix. The fixture is the report's dodge2 stream pinned into `fixtures/`: - /// aomenc profile 1 over testsrc2 128x96 yuv444p, `--lossless=1`, - /// `--sb-size=64 --min-partition-size=64 --max-partition-size=64`, 6 - /// frames; 37658 bytes, sha256 - /// `5a070fa351a3f2109de855234f2b3d0a872970f3e7f658db21f65c12eeb135b4`. - /// The firing counter is the EXISTING `decode::chroma_split_tx_hits` (one - /// bump per lossless chroma TX unit read): with min=max partition 64 the - /// roots stay whole 64x64 inter blocks -- no 8x8 leaf exists in this - /// stream -- so every chroma unit goes through the big-block ss-aware - /// lossless route this lane fixed (fixes 2-5). A 4:2:0 lossless stream - /// fires the same counter, but the fixture bytes are pinned, so the gate - /// cannot run on anything else; the pre-fix 4:2:0-hardcoded math corrupts - /// at 4:4:4, so the pixel-exact compares are what prove the ss-aware path - /// (class `gate-blind-to-feature`). Every frame must come out pixel-exact - /// through BOTH the oracle `aomdec --rawvideo` and ffmpeg. The - /// default-partition ll444 stream is deliberately NOT claimed here: its - /// key frame is still the intra lane's named sub8-chroma stop - /// (lanes/av1llintra.report.md). - #[test] - fn a_lossless_444_min_partition64_inter_stream_decodes_pixel_exact() { - const NAME: &str = "a_lossless_444_min_partition64_inter_stream_decodes_pixel_exact"; - const FIXTURE_LEN: usize = 37658; - const FIXTURE_FNV: u64 = 0xf68d_c26f_a14d_283c; - const W: usize = 128; - const H: usize = 96; - const FRAMES: usize = 6; - let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("fixtures/ll444_minp64_inter.obu"); - let stream = std::fs::read(&obu).unwrap_or_else(|e| { - panic!( - "{NAME}: pinned fixture {} is missing ({e}) -- the gate cannot run, \ - which is a failure, not a skip", - obu.display() - ) - }); - assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: fixture length moved"); - assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: fixture bytes moved"); - - let _guard = lock_gate_counters(); - let before = crate::decode::chroma_split_tx_hits(); - let frames = decode_stream(&stream) - .unwrap_or_else(|e| panic!("{NAME}: the pinned stream no longer decodes cleanly: {e}")); - let hits = crate::decode::chroma_split_tx_hits(); - assert!( - hits > before, - "{NAME}: gate is vacuous -- no lossless chroma TX unit was read \ - (delta {before} -> {hits})" - ); - assert_eq!(frames.len(), FRAMES, "{NAME}: frame count"); - for f in &frames { - assert_eq!((f.width, f.height), (W, H), "{NAME}: dimensions"); - } - - // The oracle aomdec, rawvideo out: FRAMES concatenated yuv444p frames. - if aomdec_available(NAME) { - let dir = std::env::temp_dir().join(format!("ec-av1-ll444-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).expect("scratch dir"); - let raw = dir.join("aomdec.raw"); - let out = crate::tool_cache::cached_output_io(Command::new(aomdec_path()) - .args(["--codec=av1", "--rawvideo", "-o"]) - .arg(&raw) - .arg(&obu) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("aomdec failed to run"); - assert!( - out.status.success(), - "{NAME}: the oracle aomdec refused the stream: {}", - String::from_utf8_lossy(&out.stderr) - ); - let ref_raw = std::fs::read(&raw).expect("aomdec rawvideo output"); - let _ = std::fs::remove_dir_all(&dir); - assert_eq!(ref_raw.len(), W * H * 3 * FRAMES, "{NAME}: aomdec raw size"); - for (i, f) in frames.iter().enumerate() { - let base = i * W * H * 3; - for ((plane, off), p) in [(&f.y, 0usize), (&f.u, W * H), (&f.v, 2 * W * H)] - .into_iter() - .zip(["y", "u", "v"]) - { - let want = &ref_raw[base + off..base + off + W * H]; - let bad = plane - .iter() - .zip(want) - .filter(|&(&a, &b)| a as u8 != b) - .count(); - assert_eq!( - bad, 0, - "{NAME}: aomdec frame {i} plane {p}: {bad} samples differ" - ); - assert_eq!( - plane.len(), - want.len(), - "{NAME}: aomdec frame {i} plane {p}: ours has {} samples, the oracle's \ - has {} -- a short plane would zip-truncate the compare above and hide \ - a chroma-span defect", - plane.len(), - want.len() - ); - } - } - } - - // ffmpeg's decoder: same frames, full-resolution chroma. - if have_ffmpeg() { - let refs = ffmpeg_decode_sequence_444(&stream, W, H, FRAMES); - for (i, (got, want)) in frames.iter().zip(refs.iter()).enumerate() { - for (p, (g, r)) in [(&got.y, &want.y), (&got.u, &want.u), (&got.v, &want.v)] - .iter() - .enumerate() - { - let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count(); - assert_eq!( - bad, 0, - "{NAME}: ffmpeg frame {i} plane {p}: {bad} samples differ" - ); - assert_eq!( - g.len(), - r.len(), - "{NAME}: ffmpeg frame {i} plane {p}: ours has {} samples, ffmpeg's has {} \ - -- a short plane would zip-truncate the compare above and hide a \ - chroma-span defect", - g.len(), - r.len() - ); - } - } - } else { - eprintln!("SKIP {NAME} ffmpeg arm: no ffmpeg"); - } - } - - /// lane-av1h5: the 128-ROOT lossless 4:4:4 pin, and the control arm - /// that proves the 128 root is what it needs. - /// - /// Witness: testsrc2 128x96 yuv444p10le, aomenc `--profile=1 --lossless=1 - /// --enable-palette=0 --enable-intrabc=0 --cpu-used=0`, 6 frames; 63429 - /// bytes, sha256 `bbffb979d20d581deb271aac75b7ee779dde57c024524ed6b1389356f55ca0fa`. - /// Control: the same recipe at `--max-partition-size=64` (61494 bytes, - /// sha256 `4cadce41e1f8967567b32f5cf8abaa46ffdf4fd6d4afe784c8d99a7f6bf1ae4c`), - /// which never reaches a 128 root. - /// - /// libaom's `decode_token_recon_block` (`av1/decoder/decodeframe.c:972`) - /// walks 64x64 "mu" chunks with the PLANE loop inside the chunk loop, on a - /// chunk grid of `mi_size_wide[BLOCK_64X64]` = 16 mi per axis. The var-tx - /// leaf list is a BLOCK-wide raster (32 leaves across at 128), so a chunk's - /// members are not contiguous: leaves 0..15 are chunk (0,0) row 0, but - /// chunk (0,0) rows 1..15 are leaves 32..47, 64..79, ... A chunk test on - /// the given order closed the chunk every SIXTEEN leaves and coded each - /// chunk's chroma sixteen times. - /// - /// The three assertions below are all EXACT and all stay true when the - /// stream becomes byte-exact. None of them is a floor on wrong output: - /// a no-op [`crate::decode::mu_chunk_order`] permutation reads 0 on - /// `mu_chunk_order_hits`, so the first cannot be satisfied by a gate that - /// merely ran; the walk and unit totals are libaom's own per-chunk counts; - /// the control arm is a straight exactness assertion. - #[test] - fn a_lossless_444_128_root_lossless_stream_reads_chunks_chunk_major() { - const NAME: &str = "a_lossless_444_128_root_lossless_stream_reads_chunks_chunk_major"; - const W: usize = 128; - const H: usize = 96; - const FRAMES: usize = 6; - /// 5 inter frames, one unsplit 128 root each; frame 0 splits. - const ROOTS: usize = 5; - /// libaom's chunk grid on a 128x128 root: 2x2 chunks per root. - const CHUNKS_PER_ROOT: usize = 4; - /// Chroma TX_4X4 units per inter frame: 768 per plane over 128x96. - const UNITS_PER_FRAME: usize = 1536; - - let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("fixtures/ll444_128root_lossless.obu"); - let stream = read_pin(&obu, 63429, 0xf07d_47fc_fd51_2658, NAME); - let _guard = lock_gate_counters(); - let (o0, w0, u0) = ( - crate::decode::mu_chunk_order_hits(), - crate::decode::mu_chunk_walks(), - crate::decode::mu_chunk_walk_units(), - ); - let frames = decode_stream(&stream) - .unwrap_or_else(|e| panic!("{NAME}: the pinned stream no longer decodes cleanly: {e}")); - let (o1, w1, u1) = ( - crate::decode::mu_chunk_order_hits(), - crate::decode::mu_chunk_walks(), - crate::decode::mu_chunk_walk_units(), - ); - // (1) the reorder PERMUTED each root's walk -- a no-op reads 0. - assert_eq!( - o1 - o0, - ROOTS, - "{NAME}: the chunk-major sort permuted {}/{} of the 128 roots -- a no-op \ - ordering must read 0 here, so this is what makes the gate non-vacuous", - o1 - o0, - ROOTS - ); - // (2) libaom's own per-chunk counts: 4 chroma walks per 128 root, and - // the 1536 chroma units an inter frame codes at 128x96 4:4:4. - assert_eq!( - w1 - w0, - ROOTS * CHUNKS_PER_ROOT, - "{NAME}: {}/{} chunk-major chroma walks; the 16x redundancy (64 per \ - frame instead of 4) would read {}", - w1 - w0, - ROOTS * CHUNKS_PER_ROOT, - ROOTS * CHUNKS_PER_ROOT * 16 - ); - assert_eq!( - u1 - u0, - ROOTS * UNITS_PER_FRAME, - "{NAME}: {}/{} chroma units over the 128 roots; the oracle codes {} \ - per inter frame and our pre-fix walk read 16x that", - u1 - u0, - ROOTS * UNITS_PER_FRAME, - UNITS_PER_FRAME - ); - assert_eq!(frames.len(), FRAMES, "{NAME}: frame count"); - for f in &frames { - assert_eq!((f.width, f.height), (W, H), "{NAME}: dimensions"); - } - - // (3) the control arm: no 128 root, and byte-exact through the oracle. - let ctrl = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("fixtures/ll444_minp64_128root_control.obu"); - let ctrl_stream = read_pin( - &ctrl, - 61494, - 0xf6f5_a3cb_efc7_eb10, - &format!("{NAME} control"), - ); - let _ = decode_stream(&ctrl_stream) - .unwrap_or_else(|e| panic!("{NAME}: the control arm no longer decodes cleanly: {e}")); - if aomdec_available(NAME) { - assert_rawvideo_matches(&ctrl, &ctrl_stream, NAME, FRAMES, 10); - } - } - - /// lane-av1lm444loss: a LOSSLESS block's transform-unit grid is clipped at - /// the FRAME edge, exactly as libaom's `max_block_high`/`max_block_wide` - /// clip it (`av1_common_int.h:1565`, `:1579` fold `mb_to_bottom_edge` / - /// `mb_to_right_edge` into `block_size_high/wide` before `>> - /// MI_SIZE_LOG2`), so a block hanging off the bottom/right codes only the - /// units inside the frame. `decode_token_recon_block` then bounds every - /// mu chunk with `unit_height = ROUND_POWER_OF_TWO(AOMMIN(mu_blocks_high - /// + row, max_blocks_high), ss_y)`, so the overflow units are never read - /// there either. - /// - /// Fixture is the sibling [`a_lossless_444_128_root_lossless_stream_reads_chunks_chunk_major`] - /// pin -- 128x96 yuv444p 4:4:4 lossless, 6 frames, 63429 bytes -- because - /// 96 is NOT a multiple of the 128 superblock: its five inter frames each - /// carry one unsplit 128 root that overhangs the bottom by 32 px. That is - /// the whole reason this stream is the witness. The frame is 24 mi tall, - /// so `max_blocks_high >> 2` is 24 transform rows where the block's own - /// `side / MI` is 32. - /// - /// The three assertions are all non-vacuous and all EXACT: - /// - /// 1. `lossless_edge_clipped()` fired -- 5, one per inter frame's 128 - /// root. It is 0 on any frame whose height and width are multiples of - /// the superblock, so a stream that merely decodes cannot satisfy it. - /// 2. `lossless_edge_clip_units()` is 1280 = 5 x 256: the 8 transform rows - /// x 32 columns the unclipped walk read past the frame bottom, per - /// inter frame. The pre-fix walk read 2560 units per inter frame - /// against the oracle's 2304, and this is that 256. - /// 3. every sample of every frame matches the oracle `aomdec - /// --rawvideo` in decode order -- all six frames, hidden alt-ref - /// included, which the pre-fix tree failed from frame 1 on - /// (5596 wrong samples there, growing to 33561 by frame 5). - /// - /// The control arm pins the other direction of the invariant: the - /// `ll444_minp64_128root_control` stream has no overhanging root, so its - /// clip counters must both read 0 -- the clip cannot fire on a block that - /// fits, which is what keeps every other lossless pin byte-identical. - #[test] - fn a_lossless_block_clips_its_transform_grid_at_the_frame_edge() { - const NAME: &str = "a_lossless_block_clips_its_transform_grid_at_the_frame_edge"; - const W: usize = 128; - const H: usize = 96; - const FRAMES: usize = 6; - /// 5 inter frames, one unsplit 128 root each; frame 0 splits. - const ROOTS: usize = 5; - /// `max_blocks_high >> 2` = 24 rows (96 px / 4), against the block's - /// own `side / MI` = 32 -- so 8 rows x 32 columns = 256 units per root - /// were read past the frame bottom before the clip. - const CLIP_UNITS_PER_ROOT: usize = 256; - - let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("fixtures/ll444_128root_lossless.obu"); - let stream = read_pin(&obu, 63429, 0xf07d_47fc_fd51_2658, NAME); - let _guard = lock_gate_counters(); - let (c0, u0) = ( - crate::decode::lossless_edge_clipped(), - crate::decode::lossless_edge_clip_units(), - ); - let frames = decode_stream(&stream) - .unwrap_or_else(|e| panic!("{NAME}: the pinned stream no longer decodes cleanly: {e}")); - let (c1, u1) = ( - crate::decode::lossless_edge_clipped(), - crate::decode::lossless_edge_clip_units(), - ); - assert_eq!( - c1 - c0, - ROOTS, - "{NAME}: the frame-edge clip fired on {}/{} of the 128 roots -- it must be 0 \ - on a frame that fits, so this is what makes the gate non-vacuous", - c1 - c0, - ROOTS - ); - assert_eq!( - u1 - u0, - ROOTS * CLIP_UNITS_PER_ROOT, - "{NAME}: the clip removed {}/{} transform units; the unclipped walk read {} \ - per inter frame past the 96 px frame bottom (8 rows x 32 columns)", - u1 - u0, - ROOTS * CLIP_UNITS_PER_ROOT, - CLIP_UNITS_PER_ROOT - ); - assert_eq!(frames.len(), FRAMES, "{NAME}: frame count"); - for f in &frames { - assert_eq!((f.width, f.height), (W, H), "{NAME}: dimensions"); - } - if aomdec_available(NAME) { - assert_rawvideo_matches(&obu, &stream, NAME, FRAMES, 10); - } - - // Control: a stream whose roots all fit must not clip at all. - let ctrl = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("fixtures/ll444_minp64_128root_control.obu"); - let ctrl_stream = read_pin( - &ctrl, - 61494, - 0xf6f5_a3cb_efc7_eb10, - &format!("{NAME} control"), - ); - let (c2, u2) = ( - crate::decode::lossless_edge_clipped(), - crate::decode::lossless_edge_clip_units(), - ); - let _ = decode_stream(&ctrl_stream) - .unwrap_or_else(|e| panic!("{NAME}: the control arm no longer decodes cleanly: {e}")); - assert_eq!( - crate::decode::lossless_edge_clipped() - c2, - 0, - "{NAME} control: the clip fired on a stream whose blocks all fit -- the clip \ - must be a no-op there, which is what keeps every other lossless pin \ - byte-identical" - ); - assert_eq!( - crate::decode::lossless_edge_clip_units() - u2, - 0, - "{NAME} control: the clip removed units from a stream whose blocks all fit" - ); - } - - /// lane-av1lm444loss-corr: the MI STEP at which `decode_intrabc_rect`'s - /// lossless chroma replay walks the plane block. - /// - /// `lane-whtshape` (`f541d062`, merged `afa13bcf`) gave this route the - /// per-TX_4X4 lossless chroma walk and the tail replay that re-stamps - /// each unit's own coefficient context over the whole-block record. The - /// replay stepped by `4 >> ss_y(fctx)` mi cells, which is 4:2:0-only - /// arithmetic: at ss (1,1) it reads 2 and the ss-aware form - /// `(4 << ss_y) / MI` also reads 2, so 4:2:0 agrees by construction; at - /// ss (0,0) it reads 4 mi, i.e. 16 luma px per 4x4 chroma unit, where the - /// unit covers `4 << 0` = 4 luma px = ONE mi. Every replayed unit was - /// therefore stamped at 4x its own mi origin on a 4:4:4 lossless frame, - /// writing over cells that belong to other blocks. - /// - /// This gate is the WIRNESS stream, not a vacuous one. The 4:2:0 - /// 4x4-identity is stated in the step's own comment and measured by the - /// `4:2:0` arm of the lane's invariant battery, not asserted here -- - /// a 4:2:0 stream cannot fail this gate, by construction, and pretending - /// otherwise would be a floor on wrong output. - /// - /// Fixture `ll444_intrabc_rect_l2.obu`, 121844 bytes, sha256 - /// `f0de080edce35d34cdd628b71f63dc452f946e8328352b69d3c1da090a54ec67`: - /// `testsrc2 512x128 yuv444p`, aomenc `--lossless=1 --cpu-used=2 - /// --lag-in-frames=0 --kf-max-dist=100 --limit=6`, 6 frames. On main's - /// step this stream is 10604 samples wrong in the KEY frame, first at - /// byte 33216 (Y(64,448)) -- the corrupted chroma context desyncs the - /// following luma, which is why the first divergence is luma at all. - /// - /// Assertions: - /// - /// 1. `(subsampling_x, subsampling_y, bit_depth) == (0, 0, 8)` from the - /// stream's OWN parsed sequence header. At (1,1) the corrected step - /// and the old one are the same number, so without this every - /// assertion below would pass on a stream that cannot fail. - /// 2. `intrabc_rect_lossless_chroma4_hits()` (lane-whtshape's own - /// counter) is nonzero -- the replayed arm really ran, so the - /// corrected expression was evaluated. - /// 3. the U and V plane extents are luma-sized, which is the geometry - /// the step indexes into. - /// 4. `decode_all_frames_vs_oracle`: decode-order frame-count parity, - /// then byte-exactness on every frame. - /// - /// Control: the sibling 128x96 4:4:4 lossless pin, whose blocks are - /// whole and square, must not take the lossless chroma walk at all -- - /// its chroma plane block IS one TX_4X4, so there is no step to replay. - #[test] - fn a_lossless_444_intrabc_rect_replay_steps_by_the_units_own_mi_footprint() { - const NAME: &str = "a_lossless_444_intrabc_rect_replay_steps_by_the_units_own_mi_footprint"; - const W: usize = 512; - const H: usize = 128; - const FRAMES: usize = 6; - - let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("fixtures/ll444_intrabc_rect_l2.obu"); - let stream = read_pin(&obu, 121844, 0x38bf_968e_979c_7a0a, NAME); - assert_eq!( - subsampled_header_shape(&stream, NAME), - (0, 0, 8), - "{NAME}: the stream is not 8-bit 4:4:4 -- at ss (1,1) the corrected \ - step and the 4:2:0-only one are the SAME number (2 mi), so this gate \ - cannot fail on a 4:2:0 stream and would prove nothing there" - ); - let _guard = lock_gate_counters(); - crate::decode::reset_intrabc_rect_lossless_chroma4_hits(); - let h0 = crate::decode::intrabc_rect_lossless_chroma4_hits(); - let frames = decode_stream(&stream) - .unwrap_or_else(|e| panic!("{NAME}: the pinned stream no longer decodes cleanly: {e}")); - let walked = crate::decode::intrabc_rect_lossless_chroma4_hits() - h0; - assert!( - walked > 0, - "{NAME}: lane-whtshape's lossless per-TX_4X4 chroma walk never ran, so the \ - replayed MI step -- the thing this gate exists for -- was never evaluated" - ); - assert_eq!(frames.len(), FRAMES, "{NAME}: frame count"); - for f in &frames { - assert_eq!((f.width, f.height), (W, H), "{NAME}: dimensions"); - assert_eq!( - f.u.len(), - W * H, - "{NAME}: U extent must be luma-sized at 4:4:4 -- the replay steps mi \ - cells through this grid" - ); - assert_eq!( - f.v.len(), - W * H, - "{NAME}: V extent must be luma-sized at 4:4:4" - ); - } - // lane-3c-a: the oracle-presence scan (wave 3b, 7a865ee7) rejects a - // bare `aomdec_path().is_file()` outside the probe that owns it -- this - // gate would otherwise report green under EC_AV1_REQUIRE_AOMENC=1 with - // the pixel compare never run. `aomdec_available` carries both the - // env-escape assertion and the SKIP line, so the else-arm is dropped. - if aomdec_available(NAME) { - let (decoded, hidden) = decode_all_frames_vs_oracle(&stream, NAME); - assert_eq!( - decoded, FRAMES, - "{NAME}: decoded {decoded} frames in decode order, expected {FRAMES}" - ); - eprintln!( - "{NAME}: {decoded} frames byte-exact vs aomdec ({hidden} hidden), \ - {walked} lossless chroma replays" - ); - } - - // Control: whole square blocks have no multi-unit plane block to step. - let ctrl = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("fixtures/ll444_128root_lossless.obu"); - let ctrl_stream = read_pin( - &ctrl, - 63429, - 0xf07d_47fc_fd51_2658, - &format!("{NAME} control"), - ); - crate::decode::reset_intrabc_rect_lossless_chroma4_hits(); - let _ = decode_stream(&ctrl_stream) - .unwrap_or_else(|e| panic!("{NAME}: the control arm no longer decodes cleanly: {e}")); - assert_eq!( - crate::decode::intrabc_rect_lossless_chroma4_hits(), - 0, - "{NAME} control: the lossless chroma walk ran on a stream of whole square \ - blocks -- there is no multi-unit chroma plane block to replay, so the \ - corrected step is not exercised there at all" - ); - } - - /// lane-av1llpredgate2: the debug-exact pin for the ss-aware - /// `obmc_skip_chroma_above` decision (lane-av1-llpred2). Fixture is the - /// llpred/llpred2 reports' stream pinned into `fixtures/`: testsrc2 - /// 128x96 yuv444p, aomenc `--profile=1 --lossless=1 --enable-palette=0 - /// --enable-intrabc=0 --min-partition-size=8 --max-partition-size=64`, - /// 6 frames; 34037 bytes, sha256 - /// `04fb6d38de5382e647bfb70b6a17802f1fccc5502e6698c0394167891f2b27dc`. - /// - /// This is a DEBUG-build path by construction: the old ratio-based ss - /// derivation read `write_h >> trailing_zeros(0)` = `>> 64` on this - /// stream's 4:4:4 OBMC rect strips, a panic ONLY under - /// debug_assertions (release wraps and was already byte-exact), so - /// `cargo test`'s default dev profile is the profile where the defect - /// class reproduces and where the parent's byte-exact proof was - /// measured. - /// - /// No skip-arm counter gate is possible on this stream, measured: - /// OBMC runs 77 times with 20 rect leaves, but - /// `obmc_skip_chroma_above` returns true 0 times -- at 4:4:4 the skip - /// needs a 4x4/8x4/4x8 PLANE block and min-partition-8 never codes one. - /// So per the lane ticket the proof splits in two: the decision TABLE - /// (4:2:0 rect strips still skip, 4:4:4 shifts never leave `usize`) - /// stays pinned by `decode::obmc_skip_chroma_tests:: - /// rect_strips_skip_above_chroma_at_420_and_shift_never_overflows`, - /// and THIS stream gate pins the end-to-end behaviour -- every sample - /// of every frame must match the oracle aomdec exactly, so a returning - /// chroma diff (the lane-av1-llpred ss-blind re-blend class - /// `obmc-ss-blind-chroma-above`) or the debug shift panic goes red - /// here by name. - #[test] - fn a_lossless_444_min_partition8_inter_stream_decodes_sample_exact() { - const NAME: &str = "a_lossless_444_min_partition8_inter_stream_decodes_sample_exact"; - const FIXTURE_LEN: usize = 34037; - const FIXTURE_FNV: u64 = 0x2c8f_4a2c_c025_52da; - const W: usize = 128; - const H: usize = 96; - const FRAMES: usize = 6; - let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("fixtures/ll444_minp8_inter.obu"); - let stream = std::fs::read(&obu).unwrap_or_else(|e| { - panic!( - "{NAME}: pinned fixture {} is missing ({e}) -- the gate cannot run, \ - which is a failure, not a skip", - obu.display() - ) - }); - assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: fixture length moved"); - assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: fixture bytes moved"); - - let _guard = lock_gate_counters(); - let frames = decode_stream(&stream) - .unwrap_or_else(|e| panic!("{NAME}: the pinned stream no longer decodes cleanly: {e}")); - assert_eq!(frames.len(), FRAMES, "{NAME}: frame count"); - for f in &frames { - assert_eq!((f.width, f.height), (W, H), "{NAME}: dimensions"); - } - - // The oracle aomdec, rawvideo out: FRAMES concatenated yuv444p frames. - if aomdec_available(NAME) { - let dir = std::env::temp_dir().join(format!("ec-av1-llminp8-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).expect("scratch dir"); - let raw = dir.join("aomdec.raw"); - let out = crate::tool_cache::cached_output_io(Command::new(aomdec_path()) - .args(["--codec=av1", "--rawvideo", "-o"]) - .arg(&raw) - .arg(&obu) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("aomdec failed to run"); - assert!( - out.status.success(), - "{NAME}: the oracle aomdec refused the stream: {}", - String::from_utf8_lossy(&out.stderr) - ); - let ref_raw = std::fs::read(&raw).expect("aomdec rawvideo output"); - let _ = std::fs::remove_dir_all(&dir); - assert_eq!(ref_raw.len(), W * H * 3 * FRAMES, "{NAME}: aomdec raw size"); - for (i, f) in frames.iter().enumerate() { - let base = i * W * H * 3; - for ((plane, off), p) in [(&f.y, 0usize), (&f.u, W * H), (&f.v, 2 * W * H)] - .into_iter() - .zip(["y", "u", "v"]) - { - let want = &ref_raw[base + off..base + off + W * H]; - let bad = plane - .iter() - .zip(want) - .filter(|&(&a, &b)| a as u8 != b) - .count(); - assert_eq!( - bad, 0, - "{NAME}: aomdec frame {i} plane {p}: {bad} samples differ \ - (class obmc-ss-blind-chroma-above)" - ); - assert_eq!( - plane.len(), - want.len(), - "{NAME}: aomdec frame {i} plane {p}: ours has {} samples, the oracle's \ - has {} -- a short plane would zip-truncate the compare above and hide \ - a chroma-span defect", - plane.len(), - want.len() - ); - } - } - } - - // ffmpeg's decoder: same frames, full-resolution chroma. - if have_ffmpeg() { - let refs = ffmpeg_decode_sequence_444(&stream, W, H, FRAMES); - for (i, (got, want)) in frames.iter().zip(refs.iter()).enumerate() { - for (p, (g, r)) in [(&got.y, &want.y), (&got.u, &want.u), (&got.v, &want.v)] - .iter() - .enumerate() - { - let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count(); - assert_eq!( - bad, 0, - "{NAME}: ffmpeg frame {i} plane {p}: {bad} samples differ" - ); - assert_eq!( - g.len(), - r.len(), - "{NAME}: ffmpeg frame {i} plane {p}: ours has {} samples, ffmpeg's has {} \ - -- a short plane would zip-truncate the compare above and hide a \ - chroma-span defect", - g.len(), - r.len() - ); - } - } - } else { - eprintln!("SKIP {NAME} ffmpeg arm: no ffmpeg"); - } - } - - /// lane-av1444altref: the 4:4:4 LOSSLESS + altref chroma residual this - /// lane closed -- 317 wrong bytes, Y exact, on - /// `fixtures/ll444_c_altref_leaf8_warp.obu` (512220 bytes, sha256 - /// `999a41d88a092840456d5e9de83590ab819a8a14686a694889e63c2258ff2bb8`; - /// the cell is committed here byte for byte, never re-encoded, and its - /// `aomenc` recipe is still unrecorded -- see - /// `lanes/av1444altref.report.md`). - /// - /// The defect: `decode_inter_block8`'s COMPOUND arm warped its LUMA - /// intermediates (`warp_affine_compound`) and left BOTH CHROMA arms - /// translational. libaom warps per PLANE - /// (`build_inter_predictors_8x8_and_bigger`, - /// reconinter_template.inc:230, runs `av1_init_warp_params` + - /// `av1_warp_plane` inside the plane loop with that plane's - /// subsampling and origin). A GLOBALMV (affine) 8x8 leaf's MV is the - /// affine's local derivative, so a translation agrees with the warp at - /// the block's top-left corner and drifts apart toward its bottom-right - /// -- the measured signature, a bottom-right-biased +/-1 gradient in a - /// few 8x8 chroma cells of hidden altref pictures while luma stayed exact. - /// - /// The assertion is BYTE-EXACTNESS on all three planes of all 16 - /// displayed frames against the oracle aomdec, never a route counter. The - /// `flip` arm is the oracle-flip control: it rotates ONE byte of the - /// oracle's own rawvideo output and requires the same comparator to - /// report exactly that one sample, so the zeros above are a live - /// comparison and not an empty or short zip (class - /// `stale-output-faked-measurement`). `compound_warp_hits_8`'s delta is - /// the supplementary reachability witness: it proves the 8x8 compound - /// warp-leaf arm -- the body the fix lives in -- actually ran on this - /// cell (class `gate-blind-to-feature`). - #[test] - fn a_lossless_444_altref_leaf8_warp_chroma_is_byte_exact() { - const NAME: &str = "a_lossless_444_altref_leaf8_warp_chroma_is_byte_exact"; - const FIXTURE_LEN: usize = 512_220; - const FIXTURE_FNV: u64 = 0xbe0a_569f_3d13_1026; - const W: usize = 320; - const H: usize = 240; - const FRAMES: usize = 16; - let stream = - std::fs::read(crate_pin("ll444_c_altref_leaf8_warp.obu")).unwrap_or_else(|e| { - panic!( - "{NAME}: pinned fixture ll444_c_altref_leaf8_warp.obu is missing ({e}) -- \ - the gate cannot run, which is a failure, not a skip" - ) - }); - assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: fixture length moved"); - assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: fixture bytes moved"); - assert_eq!( - stream_bit_depth(&stream, NAME), - 8, - "{NAME}: this cell is 8-bit" - ); - - let _guard = lock_gate_counters(); - // The pin is 18 decode-order pictures for 16 displayed frames (two - // hidden altrefs); the geometry assert is on the DISPLAYED frames, - // which is what aomdec's --rawvideo emits and what the comparator - // packs. - let frames = decode_stream(&stream) - .unwrap_or_else(|e| panic!("{NAME}: the pinned stream no longer decodes cleanly: {e}")); - assert_eq!(frames.len(), FRAMES, "{NAME}: displayed frame count"); - for (i, f) in frames.iter().enumerate() { - assert_eq!((f.width, f.height), (W, H), "{NAME}: frame {i} dimensions"); - } - - if !aomdec_available(NAME) { - return; - } - // ---- arm 1: the real oracle, every plane byte-identical ---------- - let (wy, wu, wv, n, exact) = - count_rawvideo_diffs(&stream, NAME, None).unwrap_or_else(|| { - panic!( - "{NAME}: the two sides are not the same size -- a zip-truncated compare \ - would report zero and hide the whole chroma span" - ) - }); - assert_eq!( - (wy, wu, wv), - (0, 0, 0), - "{NAME}: {wy} Y / {wu} U / {wv} V samples differ from the oracle \ - (class altref-444-leaf8-chroma-unwarped)" - ); - assert_eq!( - (n, exact), - (FRAMES, FRAMES), - "{NAME}: every displayed frame must be byte-identical to the oracle's" - ); - - // ---- arm 2: the ORACLE-FLIP CONTROL ----------------------------- - // One byte of the oracle's own output (the first U sample of frame 0), - // rotated in the comparator. The count MUST move, by exactly one, in - // the U plane only: a comparator that ignored the reference, or zipped - // a truncated buffer, would still report zero here. - let (cy, cu, cv, cn, _) = count_rawvideo_diffs(&stream, NAME, Some(W * H)) - .unwrap_or_else(|| panic!("{NAME}: the control arm could not compare at all")); - assert_eq!( - (cy, cu, cv), - (0, 1, 0), - "{NAME}: the oracle-flip control did not move the count -- this gate's zero is \ - vacuous, not exact" - ); - assert_eq!( - cn, FRAMES, - "{NAME}: the control arm must still see every frame" - ); - - // ---- supplementary reachability witness ------------------------- - let before8 = crate::decode::compound_warp_hits_8(); - let _ = decode_stream(&stream).expect("the reachability witness re-decodes the pin"); - assert!( - crate::decode::compound_warp_hits_8() > before8, - "{NAME}: no 8x8 compound warp leaf ran on this cell, so the fixed body was never \ - reached and the byte compare above proved nothing (class gate-blind-to-feature)" - ); - } - - /// lane-av1-444sb: the byte-exact pin for the ss-aware 128-rect chroma - /// unit walk (`decode_block_128rect`). The parent walk hardcoded the - /// 4:2:0 mu-chunk span -- one 32x32 chroma unit per 64x64 chunk, chunk - /// offsets `*32`, clip step `*8` -- so at 4:4:4 a 128-root HORZ/VERT - /// intra block coded HALF its chroma units, left the remaining units' - /// coefficients unread and desynced the tile from the first such block - /// on; every superblock after SB(0,0) carried damage and the chroma - /// first-diffs sat on the 64/128 grid. - /// - /// `crates/ec-av1/fixtures/444_sb128rect_lr_witness.obu`, 794 bytes, - /// sha256 - /// `27825e14633a4b23e37d48a2acdc7f5d814ca4fadd0b8797d72a1ffb34061e80`: - /// `ffmpeg -i bands444.y4m -frames:v 3 -vf scale=192:160 -pix_fmt - /// yuv444p -f yuv4mpegpipe` piped to `aomenc --codec=av1 --profile=1 - /// --passes=1 --end-usage=q --cq-level=32 --cpu-used=0 --threads=1 - /// --row-mt=0 --sb-size=128 --lag-in-frames=0 --auto-alt-ref=0 - /// --kf-max-dist=1000 --i444 --enable-restoration=1 --obu --limit=3`. - /// Real content is required: the synthetic lavfi sources this lane swept - /// (testsrc2/testsrc/smptebars/mandelbrot/gradients) all decode frame 0 - /// exact because they never force a 128-root rect; bands does (kf - /// PARTITION_VERT 64x128 at mi(0,32) plus an intra-in-inter 64x128). - /// - /// Non-vacuity via the `decode::intra_sb128_hits` delta: a stream that - /// stopped coding 128-axis intra blocks reads 0 and the gate fails - /// instead of passing over a decode that never reached the fixed body - /// (class `gate-blind-to-feature`). The oracle arms pin every sample of - /// every frame against both aomdec and ffmpeg, so a returning chroma - /// span regression goes red here by name. - #[test] - fn a_444_sb128_root_rect_stream_with_restoration_decodes_pixel_exact() { - const NAME: &str = "a_444_sb128_root_rect_stream_with_restoration_decodes_pixel_exact"; - const FIXTURE_LEN: usize = 794; - const FIXTURE_FNV: u64 = 0xf5a7_27f4_3fa7_abc3; - const W: usize = 192; - const H: usize = 160; - const FRAMES: usize = 3; - let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("fixtures/444_sb128rect_lr_witness.obu"); - let stream = std::fs::read(&obu).unwrap_or_else(|e| { - panic!( - "{NAME}: pinned fixture {} is missing ({e}) -- the gate cannot run, \ - which is a failure, not a skip", - obu.display() - ) - }); - assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: fixture length moved"); - assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: fixture bytes moved"); - - let _guard = lock_gate_counters(); - let before = crate::decode::intra_sb128_hits(); - let before_replay = crate::decode::sb128rect_chroma_replay_hits(); - let frames = decode_stream(&stream) - .unwrap_or_else(|e| panic!("{NAME}: the pinned stream no longer decodes cleanly: {e}")); - let (horz, vert, _) = crate::decode::intra_sb128_hits(); - assert!( - horz - before.0 + (vert - before.1) > 0, - "{NAME}: this stream coded NO 128-axis intra block -- the fixed body \ - never ran (class gate-blind-to-feature)" - ); - // lane-av1-128rectspan: the block-level `record_split_luma_rect` - // above clobbers the per-unit chroma contexts, so every coded unit - // replays its own state after it -- the arm the span fix sits on. - // The delta keeps THAT arm non-vacuous (a 128-root rect stream that - // stopped replaying reads 0), and the mismatch half is the 4:2:2 - // signature: this stream is 4:4:4 (ss 0,0), where the unit's luma - // width and height are equal, so a replay that stamped one axis with - // decoded now, so this counter no longer "names the day 4:2:2 is - // admitted" -- it fires there. **DO NOT copy this zero assert onto a - // 4:2:2 stream**: measured on this branch's tip, the two - // `422_intrabc_sb128_strip*` pins each read `mismatch = 9` while - // being byte-exact against ffmpeg, because the mismatch half counts - // the replay's own designed 4:2:2 case rather than a defect. What - // stops the 8-row spill below the block from corrupting the next - // block's `txb_skip` is the per-axis span itself, and the 4:2:2 - // exactness gates (`the_pinned_422_intrabc_sb128_strip_witnesses_ - // decode_pixel_exact`) are what hold it -- not this counter. - let after_replay = crate::decode::sb128rect_chroma_replay_hits(); - assert!( - after_replay.0 > before_replay.0, - "{NAME}: no 128-root rect block replayed a chroma unit's own mi state -- the \ - replay arm never ran (class gate-blind-to-feature)" - ); - assert_eq!( - after_replay.1, - before_replay.1, - "{NAME}: the tail replay stamped {} unit(s) over a height that was not the \ - unit's own luma height (4:2:2 spans leaked into an admitted stream)", - after_replay.1 - before_replay.1 - ); - eprintln!( - "{NAME}: replayed {} chroma unit(s), {} span mismatch(es)", - after_replay.0 - before_replay.0, - after_replay.1 - before_replay.1 - ); - assert_eq!(frames.len(), FRAMES, "{NAME}: frame count"); - for f in &frames { - assert_eq!((f.width, f.height), (W, H), "{NAME}: dimensions"); - } - // All three frames are pinned byte-exact against both oracles (the - // aomdec/ffmpeg arms below run over `.take(3)`): frame 0's keyframe - // PARTITION_VERT 64x128, frame 1's inter pieces, and frame 2 -- whose - // right superblock column (the 128-root VERT piece at the frame edge) - // is three intra blocks (64x64, 64x32, 64x32) whose chroma units ride - // the inter-frame intra tail. That tail read ONE whole-plane chroma - // unit with the block-level context where 4:4:4 codes four - // plane-major TX_32X32 units with per-unit contexts and the - // offset-10 `get_txb_ctx` rows, which left three quarters of the - // planes' residual unread and misaligned the symbol stream from the - // first chroma unit on (f2 PREFILT Y 6952 / U 9568 / V 13496, first - // diffs entering at column 128). Fixed on lane-av1-rect128recon; - // the earlier "LR never restores RU row 0" attribution on this frame - // was a stage-ladder mixup, refuted in lane-av1lrflush r3. - - // The oracle aomdec, rawvideo out: FRAMES concatenated yuv444p frames. - if aomdec_available(NAME) { - let dir = std::env::temp_dir().join(format!("ec-av1-444sb-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).expect("scratch dir"); - let raw = dir.join("aomdec.raw"); - let out = crate::tool_cache::cached_output_io(Command::new(aomdec_path()) - .args(["--codec=av1", "--rawvideo", "-o"]) - .arg(&raw) - .arg(&obu) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("aomdec failed to run"); - assert!( - out.status.success(), - "{NAME}: the oracle aomdec refused the stream: {}", - String::from_utf8_lossy(&out.stderr) - ); - let ref_raw = std::fs::read(&raw).expect("aomdec rawvideo output"); - let _ = std::fs::remove_dir_all(&dir); - assert_eq!(ref_raw.len(), W * H * 3 * FRAMES, "{NAME}: aomdec raw size"); - for (i, f) in frames.iter().enumerate().take(3) { - let base = i * W * H * 3; - for ((plane, off), p) in [(&f.y, 0usize), (&f.u, W * H), (&f.v, 2 * W * H)] - .into_iter() - .zip(["y", "u", "v"]) - { - let want = &ref_raw[base + off..base + off + W * H]; - let bad = plane - .iter() - .zip(want) - .filter(|&(&a, &b)| a as u8 != b) - .count(); - assert_eq!( - bad, 0, - "{NAME}: aomdec frame {i} plane {p}: {bad} samples differ \ - (class 444-128rect-chroma-span)" - ); - assert_eq!( - plane.len(), - want.len(), - "{NAME}: aomdec frame {i} plane {p}: ours has {} samples, the oracle's \ - has {} -- a short plane would zip-truncate the compare above and hide \ - a chroma-span defect", - plane.len(), - want.len() - ); - } - } - } - - // ffmpeg's decoder: same frames, full-resolution chroma. Same - // three-frame scope as the aomdec arm above. - if have_ffmpeg() { - let refs = ffmpeg_decode_sequence_444(&stream, W, H, FRAMES); - for (i, (got, want)) in frames.iter().zip(refs.iter()).enumerate().take(3) { - for (p, (g, r)) in [(&got.y, &want.y), (&got.u, &want.u), (&got.v, &want.v)] - .iter() - .enumerate() - { - let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count(); - assert_eq!( - bad, 0, - "{NAME}: ffmpeg frame {i} plane {p}: {bad} samples differ" - ); - assert_eq!( - g.len(), - r.len(), - "{NAME}: ffmpeg frame {i} plane {p}: ours has {} samples, ffmpeg's has {} \ - -- a short plane would zip-truncate the compare above and hide a \ - chroma-span defect", - g.len(), - r.len() - ); - } - } - } else { - eprintln!("SKIP {NAME} ffmpeg arm: no ffmpeg"); - } - } - - /// lane-av1444rect (H1): the 4:4:4 LOSSY cell with a 1:4 (HORZ_4 / - /// VERT_4) partition -- the largest correctness gap the chroma-format - /// sweep left, and the first 4:4:4 lossy exactness gate in the crate. - /// - /// **The defect.** `decode_inter_block`'s `around_c` gathered a 1:4 - /// strip's chroma coefficient context at the 4:2:0 PAIR extent - /// (`(16, 8)` HORZ / `(8, 16)` VERT) with no `ss` gate, so at ss (0,0) - /// it read one extra luma mi row of LEFT chroma context. At 4:4:4 - /// `is_chroma_reference` (av1_common_int.h:1454) reduces both parity - /// clauses to `!subsampling_y` / `!subsampling_x`, so every block is its - /// own chroma reference and no pair exists: the strip codes its own - /// 16x4 chroma over its own context. Our U unit's `get_txb_ctx` then saw - /// a neighbour libaom does not have, and the arithmetic coder forked. - /// - /// **The recipe** (sha256 - /// `77f727e76d81fe48cd03709f799131677c04869b163e18d78e96bc742ec69153`, - /// 6441 bytes, 2 frames, `testsrc2 128x96 rate=25` yuv444p): - /// ```text - /// ffmpeg -f lavfi -i "testsrc2=size=128x96:rate=25" -frames:v 2 \ - /// -pix_fmt yuv444p -f yuv4mpegpipe - | \ - /// aomenc --codec=av1 --profile=1 --passes=1 --end-usage=q --cq-level=20 \ - /// --cpu-used=2 --threads=1 --row-mt=0 --lag-in-frames=0 \ - /// --kf-max-dist=100 --limit=2 - out.obu - /// ``` - /// (`rate=25` is load-bearing: `testsrc2`'s pattern is time-parameterised, - /// so `rate=1` produces a different, already-exact stream.) - /// - /// Red before the fix: frame 1, 8884 of 36864 samples wrong, first at - /// Y(91,32); the first wrong symbol was read 26263 of the frame, both - /// sides at mi (8,16) -- ours a luma-shaped `txb_skip` row (our - /// re-indexed chroma ctx 1), the oracle `decodetxb.c:158` on the U plane - /// with `txb_skip_ctx = 7`. - /// - /// Non-vacuity, three ways: the pinned stream must really be ss (0,0) - /// (asserted through the oracle aomdec's own sequence header, below); - /// `decode::rect4_inter_own_chroma444_hits()` must be non-zero, so the - /// 1:4-strip route the fix sits on really ran; and the SAME source and - /// flags at 4:2:0 must leave that counter at zero, which is what makes - /// it the 4:4:4-only route rather than a tally every strip bumps. - #[test] - fn a_444_lossy_rect4_inter_stream_decodes_pixel_exact() { - const NAME: &str = "a_444_lossy_rect4_inter_stream_decodes_pixel_exact"; - const FIXTURE_LEN: usize = 6441; - const FIXTURE_FNV: u64 = 0x0436_8b2d_2e91_72b0; - const W: usize = 128; - const H: usize = 96; - const FRAMES: usize = 2; - let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("fixtures/444_lossy_rect4_inter_witness.obu"); - let stream = std::fs::read(&obu).unwrap_or_else(|e| { - panic!( - "{NAME}: pinned fixture {} is missing ({e}) -- the gate cannot run, \ - which is a failure, not a skip", - obu.display() - ) - }); - assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: fixture length moved"); - assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: fixture bytes moved"); - - let _guard = lock_gate_counters(); - crate::decode::reset_rect4_inter_own_chroma444_hits(); - let frames = decode_stream(&stream).unwrap_or_else(|e| { - panic!("{NAME}: the pinned 4:4:4 lossy stream no longer decodes cleanly: {e}") - }); - let own_chroma = crate::decode::rect4_inter_own_chroma444_hits(); - assert!( - own_chroma > 0, - "{NAME}: no 1:4 inter strip read its chroma context over its own \ - extent -- the corrected route never ran (class gate-blind-to-feature)" - ); - assert_eq!(frames.len(), FRAMES, "{NAME}: frame count"); - for (i, f) in frames.iter().enumerate() { - assert_eq!((f.width, f.height), (W, H), "{NAME}: frame {i} dimensions"); - // At 4:4:4 the chroma planes are full resolution. A decoder that - // kept the 4:2:0 extent would hand quarter-size chroma planes to - // the byte compare below, which cannot pass -- but say so here - // rather than let the compare stand in for the shape claim. - assert_eq!( - f.u.len(), - W * H, - "{NAME}: frame {i} chroma plane is {} samples; at 4:4:4 it must be \ - full resolution ({W}x{H})", - f.u.len() - ); - } - if aomdec_available(NAME) { - let (decoded, _hidden) = decode_all_frames_vs_oracle(&stream, NAME); - eprintln!( - "{NAME}: {decoded} frame(s) byte-exact vs aomdec, {own_chroma} \ - own-extent 1:4 chroma gather(s)" - ); - } - - // The specificity arm: the SAME source, flags and 1:4 partitions at - // 4:2:0 must not touch the 4:4:4-only route. If a later change made - // the counter fire everywhere, this arm is what catches it. - if !have_aomenc() { - eprintln!("{NAME}: no aomenc, 4:2:0 specificity arm skipped"); - return; - } - let source = format!("testsrc2=size={W}x{H}:rate=25"); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-frames:v", - "2", - "-pix_fmt", - "yuv420p", - "-strict", - "-1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "{NAME}: ffmpeg refused the 4:2:0 control source: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let out = run_with_stdin( - Command::new(aomenc_path()).args([ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=20", - "--cpu-used=2", - "--threads=1", - "--row-mt=0", - "--lag-in-frames=0", - "--kf-max-dist=100", - "--limit=2", - "--obu", - "-o", - "-", - "-", - ]), - &y4m.stdout, - ); - assert!( - out.status.success(), - "{NAME}: aomenc refused the 4:2:0 control recipe: {}", - String::from_utf8_lossy(&out.stderr) - ); - crate::decode::reset_rect4_inter_own_chroma444_hits(); - decode_stream(&out.stdout) - .unwrap_or_else(|e| panic!("{NAME}: the 4:2:0 control stream was refused: {e}")); - let (h4, v4, _, _) = crate::decode::inter16_rect4_counters(); - // The control must actually code 1:4 inter strips, or it says nothing - // about the arm the fix touches. Measured: 16 HORZ_4, 28 VERT_4. - assert!( - h4 + v4 > 0, - "{NAME}: the 4:2:0 control coded NO 1:4 inter strip ({h4} HORZ_4, {v4} \ - VERT_4) -- the identity arm below would say nothing about 1:4 strips" - ); - assert_eq!( - crate::decode::rect4_inter_own_chroma444_hits(), - 0, - "{NAME}: the 4:2:0 control fired the ss_x-0 own-extent route -- the route \ - is not specific to the 4:4:4 cell it was fixed for" - ); - // The identity half: the fix adds an arm gated on `ss_x == 0`, so a - // 4:2:0 stream must stay byte-exact through it. This is the arm that - // would go red if the new arm were ever widened past ss_x 0. - if aomdec_available(NAME) { - decode_all_frames_vs_oracle(&out.stdout, &format!("{NAME}-420")); - } - eprintln!("{NAME}: 4:2:0 control {h4} HORZ_4 / {v4} VERT_4 strips, 0 own-extent gathers"); - } - - /// lane-av1gates444 cell 1: **odd coded dims, 66x66** -- the partial-frame - /// walk in BOTH axes (66 is not a multiple of 8, so the frame is a - /// partial superblock column AND a partial row). Measured EXACT 4/4 by - /// the chroma-format sweep (§6.2, 5938 bytes) and unpinned: nothing in - /// the crate would go red if the odd-dimension 4:4:4 walk regressed, - /// and the only red-before evidence was a lane report nobody re-runs. - #[test] - fn a_444_lossy_odd_66x66_stream_decodes_pixel_exact() { - gate_444_lossy_live_exact("a_444_lossy_odd_66x66_stream_decodes_pixel_exact", 66, 66); - } - - /// lane-av1gates444 cell 2: **odd coded dims, 130x122** -- the - /// partial-frame RIGHT edge that the sweep found DIVERGENT (first wrong - /// sample Y(128,16), 11521 samples on frame 3) until lane-av1444rect's - /// 4:4:4 own-chroma-extent fix landed. It measures EXACT 4/4 on this - /// tree and is the discriminating geometry: 66x66 was exact at the same - /// settings while this was not, so the pair is what keeps "the 4:4:4 - /// partial-frame walk is right" from being a one-geometry accident. - #[test] - fn a_444_lossy_odd_130x122_stream_decodes_pixel_exact() { - gate_444_lossy_live_exact( - "a_444_lossy_odd_130x122_stream_decodes_pixel_exact", - 130, - 122, - ); - } - - /// lane-av1gates444 cell 3: **256x128**, the sweep's cell recorded as - /// "4:4:4 superres 256x128 (`--superres-mode=1`)". - /// - /// IT IS NOT A SUPERRES CELL, and this gate is named for what it is - /// instead. Measured here, live: encoding 256x128 with and without - /// `--superres-mode=1` produces BYTE-IDENTICAL OBU (15239 bytes, - /// sha256 06621606…, both), so the flag is a no-op on this aomenc build - /// and the sweep's cell was a plain 4:4:4 lossy cq-20 stream that - /// happened to carry the flag. The cell's actual value is the geometry - /// plus the filter stages: 256x128 is two full 128 superblock columns, - /// and the strip walk runs there with the post-deblock/CDEF/LR chain - /// live on the later frames -- so this is the third witness for the - /// 4:4:4 lossy strip class at a geometry the 128x96 rect4 gate does not - /// cover. - #[test] - fn a_444_lossy_256x128_stream_decodes_pixel_exact() { - gate_444_lossy_live_exact("a_444_lossy_256x128_stream_decodes_pixel_exact", 256, 128); - } - - /// lane-av1txctxband — the 4:4:4 lossy `--sb-size=128` stream whose - /// `EC_SYMR` ladder forked at read 32813, and the gate that makes the fix - /// non-vacuous. - /// - /// **The defect.** `get_tx_size_context` (libaom - /// `av1/common/pred_common.h:361-370`) gates its "an inter neighbour - /// contributes its own BLOCK size" override on `xd->above_mbmi` / - /// `xd->left_mbmi`, which `set_mi_offsets` - /// (`av1_common_int.h:1381-1389`) takes as `xd->mi[-xd->mi_stride]` / - /// `xd->mi[-1]`. `setup_mbs` (`decodeframe.c:355-361`) writes the covering - /// block's own `MB_MODE_INFO` pointer into EVERY mi cell the block covers, - /// so libaom's granularity is the covering block PER CELL. This decoder - /// read the per-COLUMN `above_inter`/`left_inter` bands and the matching - /// `above_side_mi`/`left_side_mi` bands instead — the LAST block written in - /// that column, which names the abutting block only for the block directly - /// below it. On this witness the 8x4 intra leaf at mi(57,52) (SB row 1, - /// col 1) read a stale `above_inter=true` with `above_side=4`, took the - /// override, got `above = (4 >= 8) = 0` where libaom keeps - /// `above = (above_txfm_context[0] >= 8) = 1`, and read - /// `tx_size_cat0[1]` where libaom reads `tx_size_cdf[...][2]`. - /// - /// **The fork signature that identifies it** (a CDF-row error, not a - /// unit-enumeration one): the two sides held the IDENTICAL pre-state - /// `pre=(7550, 45492)` and the IDENTICAL width/value `n=2 s=1`; only - /// `cdf0` differed, ours 6424 (`32768-6424 = 26344`) vs the oracle's - /// 19938, so the ICDF mirror convention does not reconcile it either. - /// - /// **Non-vacuity.** The pixel assert alone would be green on the old code - /// for any stream where the bands happened to be right, so the gate also - /// asserts `txctx_inter_cell_band_divergence_hits() > 0` — the number of - /// `get_tx_size_context` reads where the per-CELL cover and the - /// per-COLUMN band DISAGREE, i.e. exactly the reads the old code resolved - /// off a different CDF row. Reverting either reader to the bands drives - /// this to 0 and the gate red, with the oracle compare as the second, - /// independent arm. - /// - /// **Fixture provenance** (`444_lossy_sb128_txctx_witness.obu`, 6186 B, - /// sha256 `14acb74e825a2bb3ef195a52cc2abc67794d9c4d92080b66c739d318177fc7c6`): - /// ```text - /// ffmpeg -f lavfi -i "testsrc2=size=256x256:rate=25" -frames:v 2 \ - /// -pix_fmt yuv444p -strict -1 -f yuv4mpegpipe -y src.y4m - /// aomenc --codec=av1 --passes=1 --end-usage=q --cq-level=62 --cpu-used=2 \ - /// --threads=1 --row-mt=0 --lag-in-frames=0 --kf-max-dist=100 \ - /// --sb-size=128 --profile=1 --obu -o t256.obu src.y4m - /// ``` - /// 256x256 is the smallest geometry that gives `--sb-size=128` a SECOND - /// superblock row and column, which is where the stale band bites: a cell - /// whose abutting block is not the last block written in its column. The - /// cq level is load-bearing — this cell is entropy-exact at cq 20..58 and - /// forks at 54/56/60/62 depending on the frame count (12 of the 99 cells - /// swept in `lanes/av1txctxband.report.md` §4 forked, all of them at - /// cq >= 54 on 256x256/320x240/256x384). `--sb-size=128` is load-bearing - /// too: at the default 64 the two superblock columns are 4 mi wide, so a - /// column band and a per-cell cover coincide for every 4-column run. - #[test] - fn a_444_lossy_sb128_txctx_reads_the_covering_block_per_cell() { - const NAME: &str = "a_444_lossy_sb128_txctx_reads_the_covering_block_per_cell"; - let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("fixtures/444_lossy_sb128_txctx_witness.obu"); - let bytes = std::fs::read(&path).unwrap_or_else(|e| { - panic!( - "{NAME}: pinned fixture {} is missing ({e}) -- a failure, not a skip", - path.display() - ) - }); - assert_eq!(bytes.len(), 6186, "{NAME}: fixture length moved"); - assert_eq!( - fnv1a64(&bytes), - 0x2ec1_bb1b_5196_c4b3, - "{NAME}: fixture bytes moved" - ); - - let _guard = lock_gate_counters(); - crate::decode::reset_txctx_inter_cell_band_divergence_hits(); - let frames = decode_stream(&bytes) - .unwrap_or_else(|e| panic!("{NAME}: the pinned 4:4:4 stream was refused: {e}")); - assert_eq!(frames.len(), 2, "{NAME}: frame count"); - let diverged = crate::decode::txctx_inter_cell_band_divergence_hits(); - assert!( - diverged > 0, - "{NAME}: no `get_tx_size_context` read on this stream had the \ - per-CELL cover and the per-COLUMN band disagree, so the witness \ - does not exercise the corrected read at all (class \ - gate-blind-to-feature) -- re-encode per the recipe above" - ); - if aomdec_available(NAME) { - decode_all_frames_vs_oracle(&bytes, NAME); - } - eprintln!( - "{NAME}: {diverged} tx_depth read(s) where the per-cell cover and \ - the per-column band disagreed (the 8x4 intra leaf at mi(57,52) is \ - the one that forked the ladder at read 32813)" - ); - } - - /// lane-arfchroma: 4:2:0 **lossless** with an alt-ref frame and 1:4 inter - /// strips. Ordinary, user-reachable aomenc output, no bypass: before the - /// fix this cell diverged in 15 of 16 shown frames (1 088 573 wrong - /// samples, only frames 0-1 exact) or -- one knob away, e.g. - /// `--sb-size=64`, `--enable-dual-filter=0`, `--max-reference-frames=3`, - /// or the same stream cut to 5-12 frames -- REFUSED outright with - /// `a Golomb tail longer than this decoder reads`. The refusal was this - /// divergence arriving at a named guard, not an independent gap: the - /// `16-frame` variant of this exact cell now decodes byte-exact. - /// - /// Mechanism (paired rungs, `EC_COEFF_STEP` / `EC_ECDUMP` against - /// aomdec, 320x240, 5 frames): the first forked read is frame 2's 8x8 - /// inter block at mi (4,0) (ref0 = 7 = ALTREF, mv (36,0), NEWMV), its - /// CHROMA U `txb_skip` read. All four LUMA units match read for read, and - /// the chroma read's pre-state `(rng 35592)` is IDENTICAL on both sides -- - /// only the context differs: ours 2, libaom 8 - /// (`7 + get_entropy_context`, `txb_common.h:360`). `EC_ECDUMP` names the - /// cause: libaom's chroma left neighbour is `[0]` and ours is coded. The - /// publisher is the 16x4 (1:4) strip above it: `record_mi_chroma` - /// published the unit at the BLOCK's mi origin, but a 4x4 chroma unit is - /// `1 << ss` luma mi per axis, so a strip whose mi row is ODD at 4:2:0 - /// starts mid-cell and its state landed one mi row too low -- into the - /// cell of the block that read it. libaom's per-plane - /// `left/above_context_map` is indexed in the PLANE's own 4x4 units - /// (`entropy.h:87`, `txb_common.h:429`), so the cell's origin is the - /// step-aligned mi, which is what the fix aligns to. - /// - /// The gate asserts three things, in this order: the pin's identity, the - /// mid-cell route counter (so it cannot pass on a stream whose chroma - /// units all start on a cell boundary -- class - /// gate-blind-to-feature), and then BOTH comparisons: decode order - /// (which sees the hidden alt-ref frame no shown-frame gate can) and the - /// per-plane shown-frame count. - /// - /// Recipe (both sides reproducible, 28394 bytes): - /// ```text - /// ffmpeg -f lavfi -i testsrc2=size=320x240:rate=25 -frames:v 5 \ - /// -pix_fmt yuv420p y.yuv - /// aomenc --codec=av1 --obu --lossless=1 -w 320 -h 240 \ - /// --lag-in-frames=25 --auto-alt-ref=1 --limit=5 -o w.obu y.yuv - /// ``` - /// sha256 c5507ed97f74ca495b71449fda24f5fe2fcfa34eed38988a69141d45b126627c. - /// The tree pins fixture identity by fnv1a64; a `const SHA256` compared - /// against itself would be the tautology lane-av1422anom exists to kill. - #[test] - fn a_420_lossless_alt_ref_1to4_strip_witness_is_byte_exact_in_decode_order() { - const NAME: &str = - "a_420_lossless_alt_ref_1to4_strip_witness_is_byte_exact_in_decode_order"; - // lane-av1cmpaudit2: same mutex as every other oracle gate. - let _gate_lock = lock_gate_counters(); - const FILE: &str = "420_lossless_arf_1to4_320x240_5f.obu"; - const BYTES: usize = 28394; - const FNV1A64: u64 = 16971188390893372935; - let path = crate_pin("420_lossless_arf_1to4_320x240_5f.obu"); - let data = std::fs::read(&path) - .unwrap_or_else(|e| panic!("{NAME}: the committed pin {FILE} is missing ({e})")); - assert_eq!(data.len(), BYTES, "{NAME}: {FILE} size drifted"); - assert_eq!(fnv1a64(&data), FNV1A64, "{NAME}: {FILE} bytes drifted"); - crate::decode::reset_chroma_midcell_pub_hits(); - let (decoded, hidden) = decode_all_frames_vs_oracle(&data, NAME); - assert_eq!( - decoded, 6, - "{NAME}: the oracle decoded {decoded} frames in DECODE order; the 5-frame recipe \ - carries 5 source frames, one of them a hidden alt-ref picture plus a \ - `show_existing_frame` header" - ); - assert_eq!( - hidden, 1, - "{NAME}: this cell exists for the HIDDEN alt-ref frame -- {decoded} decode-order \ - dumps against {decoded} - {hidden} shown outputs means the gate saw the picture no \ - shown-frame compare can reach" - ); - let mid = crate::decode::chroma_midcell_pub_hits(); - assert!( - mid[2] > 0 || mid[0] + mid[1] > 0, - "{NAME}: no chroma transform unit was published from a mid-cell origin \ - ({mid:?} = [row, col, both]), so this witness does not exercise the origin \ - alignment at all (class gate-blind-to-feature) -- re-encode per the recipe above" - ); - let (wy, wu, wv, shown, exact) = - count_rawvideo_diffs(&data, NAME, None).expect("the two sides must be byte-comparable"); - assert_eq!( - (wy, wu, wv, exact), - (0, 0, 0, shown), - "{NAME}: shown-frame per-plane diff vs `aomdec --rawvideo`" - ); - eprintln!( - "{NAME}: {decoded} decode-order frame(s) byte-exact ({hidden} hidden), \ - {shown} shown frame(s) exact per plane, mid-cell chroma publications {mid:?}" - ); - } - - /// lane-av1mixllfork: per-segment MIXED LOSSLESS + an alt-ref structure. - /// The first fork was entropy read **30889** of f1 (paired `EC_SYMR`: - /// identical `pre[0..1]`, `n`, `s` on both sides, `post_rng` 42076 vs - /// 54010), and the pre-fix `cdf0` at that read was 22401 vs the oracle's - /// 15299 -- **not** the usual `32768 - x` ICDF mirror, i.e. two different - /// reads, not one wrong CDF row. - /// - /// What each side read there: libaom `decodetxb.c:158`, the luma `txb_skip` - /// of a TX_4X4 unit at `mi=(6,1)` `bc=0 br=0`; ours an untagged `n=2` - /// symbol that a `set_symr_cdf` sweep over all six MV-stack copies - /// (`ii16/newmv16/…/refmvB`, `inter8` phase inherited) ruled out as every - /// inter mode-info read, leaving the one read that block makes *between* - /// its `refmv` and its coefficients: the var-tx tree's `tx_size_cat1`. - /// libaom's own reason it reads nothing: `parse_decode_block` - /// (`decodeframe.c:1237`) carries `!xd->lossless[mbmi->segment_id]` as a - /// **conjunct** of the tx-mode-select condition, and `read_tx_size` - /// (`:1208`) answers TX_4X4 on the same flag. This tree tested - /// `tx_select && !skip` and put `lossless(fctx) && !skip` in the `else if` - /// arm instead, so on a lossless SEGMENT of a mixed-lossless frame it read - /// a `tx_size_cat1` symbol libaom never reads, and the very next block's - /// `txb_skip` forked. `SUB8_LOSSLESS_NO_VARTX` counts the leaves that - /// newly take the lossless arm, so this gate cannot pass vacuously on a - /// stream whose sub-8 leaves all sit in lossy segments. (Corrected - /// 2026-09-30: the counter is now guarded on `tx_select_inter`, because the - /// refutation pass measured 33 hits on a build with the conjunct REMOVED -- - /// the arm also serves leaves whose tx-select is off. The pin's own delta - /// is 10, not the 40 the lane first reported; both numbers are measured.) - /// - /// The trigger really is the CONJUNCTION: `--cq-level=0` with AQ makes - /// *some* segments lossless and others not (`--cq-level=20`, `--cq-level=32`, - /// `--lossless=1` and `--aq-mode=0` are all byte-exact on this recipe), and - /// `--auto-alt-ref=0` makes it exact at 5, 6, 8 and 12 frames. After the - /// fix the whole-stream `EC_SYMR` ladder is bit-identical: **96997 reads, - /// 96997 paired, zero divergence** -- not just up to the fork. - /// - /// Recipe (ffmpeg 8.1.3 `testsrc2`, shared oracle `aomenc`, 18525 bytes): - /// ```text - /// ffmpeg -f lavfi -i testsrc2=size=256x128:rate=25 -frames:v 5 \ - /// -pix_fmt yuv420p src5b.y4m - /// aomenc --codec=av1 --obu -o c_mix5.obu --passes=1 --cpu-used=4 \ - /// --limit=5 --end-usage=q --cq-level=0 --aq-mode=1 src5b.y4m - /// ``` - /// sha256 `3e06b5641e6a0f5a3f4ac8f114d4ee48c88638429e9eaafe6b4483e24f1dbc3a`. - /// The tree pins fixture identity by fnv1a64; a `const SHA256` compared - /// against itself would be the tautology lane-av1422anom exists to kill. - #[test] - fn a_420_mixed_lossless_alt_ref_sub8_vartx_witness_is_byte_exact_in_decode_order() { - const NAME: &str = - "a_420_mixed_lossless_alt_ref_sub8_vartx_witness_is_byte_exact_in_decode_order"; - let _gate_lock = lock_gate_counters(); - const FILE: &str = "420_mixll_altref_256x128_5f.obu"; - const BYTES: usize = 18525; - const FNV1A64: u64 = 16348502764482216576; - let path = crate_pin(FILE); - let data = std::fs::read(&path) - .unwrap_or_else(|e| panic!("{NAME}: the committed pin {FILE} is missing ({e})")); - assert_eq!(data.len(), BYTES, "{NAME}: {FILE} size drifted"); - assert_eq!(fnv1a64(&data), FNV1A64, "{NAME}: {FILE} bytes drifted"); - let before = crate::decode::sub8_lossless_no_vartx(); - let (decoded, hidden) = decode_all_frames_vs_oracle(&data, NAME); - let suppressed = crate::decode::sub8_lossless_no_vartx() - before; - assert_eq!( - decoded, 6, - "{NAME}: the oracle decoded {decoded} frames in DECODE order; the 5-frame \ - altref recipe codes 5 source frames plus a hidden alt-ref picture" - ); - assert_eq!( - hidden, 1, - "{NAME}: {decoded} decode-order dumps against {decoded} - {hidden} shown outputs \ - means the gate saw the hidden picture no shown-frame compare can reach" - ); - assert!( - suppressed > 0, - "{NAME}: no sub-8 (4x8/8x4) inter leaf on a LOSSLESS segment read no var-tx \ - symbol ({suppressed} of them did), so this witness does not exercise the \ - ordering at all (class gate-blind-to-feature) -- re-encode per the recipe above" - ); - let (wy, wu, wv, shown, exact) = - count_rawvideo_diffs(&data, NAME, None).expect("the two sides must be byte-comparable"); - assert_eq!( - (wy, wu, wv, exact), - (0, 0, 0, shown), - "{NAME}: shown-frame per-plane diff vs `aomdec --rawvideo`" - ); - eprintln!( - "{NAME}: {decoded} decode-order frame(s) byte-exact ({hidden} hidden), \ - {shown} shown frame(s) exact per plane, {suppressed} sub-8 leaf/leaves on a \ - lossless segment read no var-tx symbol" - ); - } - - /// lane-av1txctxband2: the 640x480 cell of the same mixed-lossless - /// recipe — the THIRD defect `lanes/av1mixllconj.report.md` §4.3 / - /// §11 handed over, class `context-band-not-published`. - /// - /// libaom's `parse_decode_block` (`decodeframe.c:1251-1261`) is an - /// EITHER/OR: the var-tx branch's condition carries - /// `!xd->lossless[mbmi->segment_id]` as a conjunct, and the `else` branch - /// runs `read_tx_size` **and then `set_txfm_ctxs`**. `read_tx_size`'s - /// FIRST line (`decodeframe.c:1214`) returns `TX_4X4` on a lossless - /// segment — so a lossless block skips the symbol read, NOT the publish. - /// This decoder's `read_block_tx_size` returned from its own lossless early - /// return with nothing written, so on a MIXED frame every lossless square - /// block left the `TXFM_CONTEXT` above band holding whatever an earlier, - /// lossy block had put there. The RECT twin (`read_block_tx_size_rect`) - /// has published on the same arm since lane-av1lm444loss; only the square - /// arm had the hole. - /// - /// Measured on `420_mixll_altref_640x480_5f.obu`: the abutting 8x8 INTRA - /// lossless block at mi(78,110) left `above_txfm[110]` at the 16 a skipped - /// 16-px inter block at mi(36,108) had written 43 mi rows earlier, and the - /// 8x4 intra leaf with `use_filter_intra` at mi(80,110) then read - /// `tx_size_cat0[2]` where libaom reads row 1 — the oracle's own - /// `EC_TXCTXB` prints `mi=80,110 abv=4 lft=8 above=0 left=1 ctx=1` against - /// our `above_txfm=16 left_txfm=8 above=1 left=1 ctx=2`. The tile desynced - /// there and the frame REFUSED (`a Golomb tail longer than this decoder - /// reads`); at base the same cell decoded every frame but got 70–92 % of - /// every inter frame wrong. - /// - /// `LOSSLESS_SQ_TXFM_BAND_OVERWRITE_HITS` counts the lossless square inter - /// blocks whose publish actually OVERWROTE a size an earlier block of the - /// same frame had left in the column — so the gate cannot pass vacuously - /// on a stream that merely decodes a lossless fixture. After the fix the - /// whole-stream paired `EC_SYMR` ladder is bit-identical: **457 907 reads, - /// 457 907 paired, zero divergence** — not just up to the fork. - /// - /// Recipe (ffmpeg 8.1.3 `testsrc2`, shared oracle `aomenc`, 87537 bytes): - /// ```text - /// ffmpeg -f lavfi -i testsrc2=size=640x480:rate=25 -frames:v 5 \ - /// -pix_fmt yuv420p src640.y4m - /// aomenc --codec=av1 --obu -o 420_mixll_altref_640x480_5f.obu --passes=1 \ - /// --cpu-used=4 --limit=5 --end-usage=q --cq-level=0 --aq-mode=1 src640.y4m - /// ``` - /// sha256 `3d505fd2e0bbb7ca3680a8e338d712a81defc947b955a4b7b82de6718301e73c`; - /// the tree pins fixture identity by fnv1a64, not a `const SHA256` compared - /// against itself. - #[test] - fn a_420_mixed_lossless_alt_ref_640x480_txfm_band_publish_is_byte_exact_in_decode_order() { - const NAME: &str = "a_420_mixed_lossless_alt_ref_640x480_txfm_band_publish_is_byte_exact_\ - in_decode_order"; - let _gate_lock = lock_gate_counters(); - const FILE: &str = "420_mixll_altref_640x480_5f.obu"; - const BYTES: usize = 87537; - const FNV1A64: u64 = 12707865649077681891; - let path = crate_pin(FILE); - let data = std::fs::read(&path) - .unwrap_or_else(|e| panic!("{NAME}: the committed pin {FILE} is missing ({e})")); - assert_eq!(data.len(), BYTES, "{NAME}: {FILE} size drifted"); - assert_eq!(fnv1a64(&data), FNV1A64, "{NAME}: {FILE} bytes drifted"); - let before = crate::decode::lossless_sq_txfm_band_overwrite_hits(); - let (decoded, hidden) = decode_all_frames_vs_oracle(&data, NAME); - let overwrote = crate::decode::lossless_sq_txfm_band_overwrite_hits() - before; - assert_eq!( - decoded, 6, - "{NAME}: the oracle decoded {decoded} frames in DECODE order; the 5-frame \ - altref recipe codes 5 source frames plus a hidden alt-ref picture" - ); - assert_eq!( - hidden, 1, - "{NAME}: {decoded} decode-order dumps against {decoded} - {hidden} shown outputs \ - means the gate saw the hidden picture no shown-frame compare can reach" - ); - assert!( - overwrote > 0, - "{NAME}: no lossless square block on an inter frame published a txfm band that \ - OVERWROTE an earlier block's size ({overwrote} of them did), so this witness does \ - not exercise the missing publish at all (class gate-blind-to-feature) -- re-encode \ - per the recipe above" - ); - let (wy, wu, wv, shown, exact) = - count_rawvideo_diffs(&data, NAME, None).expect("the two sides must be byte-comparable"); - assert_eq!( - (wy, wu, wv, exact), - (0, 0, 0, shown), - "{NAME}: shown-frame per-plane diff vs `aomdec --rawvideo`" - ); - eprintln!( - "{NAME}: {decoded} decode-order frame(s) byte-exact ({hidden} hidden), \ - {shown} shown frame(s) exact per plane, {overwrote} lossless square inter \ - block(s) overwrote a stale above-band size" - ); - } - - /// lane-av1txctxband2 r2: the SAME one-line publish, three MORE cells — - /// the mixed-lossless RESIDUE `lanes/av1mixllconj.report.md` §7 left - /// explicitly unnamed ("separate defects this change shrinks but does not - /// remove"). **They are the same defect.** All three are this recipe's - /// mixed-lossless+altref stream at 256x128 (6 frames) and 320x240 (5 and 6 - /// frames); each has a lossy block whose `get_tx_size_context` / - /// `txfm_partition_context` read a band a lossless block above should have - /// published into and did not. - /// - /// Measured on `f2dd27b0~1` (= `0bfee517`, the tip before this lane's - /// publish) against `aomdec`'s `EC_AV1_FINAL_DUMP`, decode order, per - /// differing frame: - /// - /// ```text - /// 420_mixll_256x128_6f.obu 7 dumps red f1..f6: 6051 / 4115 / 2962 / 26566 / 41876 / 14749 - /// 420_mixll_320x240_5f.obu 6 dumps red f1..f5: 15031 / 16259 / 21932 / 65405 / 90077 - /// 420_mixll_320x240_6f.obu 7 dumps red f6 only: 19398 - /// ``` - /// - /// With the publish: **7/7, 6/6 and 7/7 byte-exact**, 0 differing bytes on - /// every plane of every decode-order frame. `m5_320x240`'s f2/f3 here - /// (16259 / 21932) differ from the 16006 / 21930 `lane-av1mixllconj` §7 - /// records, because that table was taken before `lane-av1offtile`'s - /// chroma-plane clip merged; f1/f4/f5 and both other cells match it exactly. - /// - /// Recipe (ffmpeg 8.1.3 `testsrc2`, shared oracle `aomenc`; `--limit` is the - /// only variable per cell): - /// ```text - /// ffmpeg -f lavfi -i testsrc2=size=x:rate=25 -frames:v -pix_fmt yuv420p src.y4m - /// aomenc --codec=av1 --obu -o .obu --passes=1 --cpu-used=4 --limit= \ - /// --end-usage=q --cq-level=0 --aq-mode=1 src.y4m - /// ``` - /// sha256 `8a203e52…` (22336 B), `40d613fd…` (28716 B), `37fbe7cb…` - /// (38686 B); pinned below by fnv1a64, not a `const SHA256` compared - /// against itself. - #[test] - fn a_420_mixed_lossless_residue_arms_are_byte_exact_in_decode_order() { - const NAME: &str = "a_420_mixed_lossless_residue_arms_are_byte_exact_in_decode_order"; - let _gate_lock = lock_gate_counters(); - // (file, bytes, fnv1a64, decode-order frames, hidden) - const CELLS: [(&str, usize, u64, usize, usize); 3] = [ - ("420_mixll_256x128_6f.obu", 22336, 5694016005779287373, 7, 1), - ("420_mixll_320x240_5f.obu", 28716, 5855109243102450179, 6, 1), - ("420_mixll_320x240_6f.obu", 38686, 49021385186397678, 7, 1), - ]; - for (file, bytes, fnv, frames, hidden) in CELLS { - let path = crate_pin(file); - let data = std::fs::read(&path) - .unwrap_or_else(|e| panic!("{NAME}: the committed pin {file} is missing ({e})")); - assert_eq!(data.len(), bytes, "{NAME}: {file} size drifted"); - assert_eq!(fnv1a64(&data), fnv, "{NAME}: {file} bytes drifted"); - let before = crate::decode::lossless_sq_txfm_band_overwrite_hits(); - let (decoded, got_hidden) = decode_all_frames_vs_oracle(&data, file); - let overwrote = crate::decode::lossless_sq_txfm_band_overwrite_hits() - before; - assert_eq!( - decoded, frames, - "{NAME}/{file}: the oracle decoded {decoded} frames in DECODE order" - ); - assert_eq!( - got_hidden, hidden, - "{NAME}/{file}: {decoded} decode-order dumps against {decoded} - {got_hidden} \ - shown outputs means the gate saw {hidden} hidden alt-ref picture/ies" - ); - assert!( - overwrote > 0, - "{NAME}/{file}: no lossless square block on an inter frame published a txfm \ - band that OVERWROTE an earlier block's size ({overwrote} of them did), so this \ - cell does not exercise the missing publish at all (class \ - gate-blind-to-feature) -- re-encode per the recipe above" - ); - eprintln!( - "{NAME}/{file}: {decoded} decode-order frame(s) byte-exact ({got_hidden} hidden), \ - {overwrote} lossless square inter block(s) overwrote a stale above-band size" - ); - } - } - - /// lane-av1444rect r2 — the SAME class as the gate above, second - /// instance: `decode_rect4_16_intrabc` applied the 4:2:0 pair geometry at - /// ss (0,0), where `is_chroma_reference` makes an intra-BC 1:4 strip its - /// own chroma reference. It predicted and coded an 8x4 chroma block at - /// `(lmi - 1) * MI / 2` where libaom codes 16x4 at the strip's origin. - /// - /// **This is a PROGRESS gate, not an exactness gate, and it says so.** The - /// 4:4:4 intra-BC cell is still divergent: after the ss gate the LUMA - /// plane is exact to sample 205264 (it was 164416) and the entropy fork - /// moves from read 11750 to 12465, but both CHROMA planes still first - /// diverge at index 20532 and 390380 of 921600 samples are wrong. So the - /// assertion is a prefix floor on the plane the gate actually moved — - /// which only ever grows, and which the next lane's fix cannot turn red — - /// and the untouched chroma divergence is named, never asserted exact. - /// - /// Recipe (both fixtures, one frame, `testsrc2 640x480 r=25`): - /// ```text - /// aomenc --codec=av1 --bit-depth=8 --input-bit-depth=8 --passes=1 - /// --end-usage=q --cpu-used=0 --lag-in-frames=0 --kf-max-dist=1 - /// --limit=1 --threads=1 --enable-rect-partitions=1 - /// --enable-1to4-partitions=1 --min-partition-size=4 - /// --max-partition-size=64 --sb-size=64 --tune-content=screen - /// --enable-intrabc=1 --enable-palette=1 --cq-level=60 - /// --enable-tx-size-search=0 --obu [--profile=1] -o out.obu src.y4m - /// ``` - /// 4:4:4 (1016 B, sha256 7fe888ed…) carries 17 intrabc 16x4 strips at - /// ss (0,0); the 4:2:0 twin (890 B, sha256 d01352af…) is byte-exact and - /// is the identity arm — the ss gate cannot reach it, and the whole frame - /// is compared with the length asserted first. - #[test] - fn a_444_intrabc_rect4_reads_its_own_chroma_plane_block() { - const NAME: &str = "a_444_intrabc_rect4_reads_its_own_chroma_plane_block"; - let read = |name: &str, file: &str, len: usize, fnv: u64| -> Vec { - let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join(format!("fixtures/{file}")); - let bytes = std::fs::read(&path).unwrap_or_else(|e| { - panic!( - "{name}: pinned fixture {} is missing ({e}) -- a failure, not a skip", - path.display() - ) - }); - assert_eq!(bytes.len(), len, "{name}: {file} length moved"); - assert_eq!(fnv1a64(&bytes), fnv, "{name}: {file} bytes moved"); - bytes - }; - let stream444 = read( - NAME, - "444_intrabc_rect4_witness.obu", - 1016, - 0x27c2_fad5_4047_2994, - ); - let stream420 = read( - NAME, - "420_intrabc_rect4_witness.obu", - 890, - 0x57ec_3da2_a63b_403a, - ); - - let _guard = lock_gate_counters(); - crate::decode::reset_intrabc_rect4_own_chroma444_hits(); - let frames = decode_stream(&stream444) - .unwrap_or_else(|e| panic!("{NAME}: the pinned 4:4:4 stream was refused: {e}")); - let own = crate::decode::intrabc_rect4_own_chroma444_hits(); - assert!( - own > 0, - "{NAME}: no intra-BC 1:4 strip coded its own chroma plane block -- the \ - corrected route never ran (class gate-blind-to-feature)" - ); - assert_eq!(frames.len(), 1, "{NAME}: frame count"); - - // The identity arm FIRST and in full: the 4:2:0 twin must stay - // byte-exact. `decode_all_frames_vs_oracle` asserts the two frame - // lengths match before it compares anything -- the check whose absence - // turned an out-of-window divergence into a reported EXACT in this - // lane's own round 1. - if aomdec_available(NAME) { - decode_all_frames_vs_oracle(&stream420, &format!("{NAME}-420")); - crate::decode::reset_intrabc_rect4_own_chroma444_hits(); - decode_stream(&stream420) - .unwrap_or_else(|e| panic!("{NAME}: the 4:2:0 twin was refused: {e}")); - assert_eq!( - crate::decode::intrabc_rect4_own_chroma444_hits(), - 0, - "{NAME}: the 4:2:0 twin fired the ss (0,0)-only route" - ); - - // NO 4:4:4 pixel assert here, and deliberately so. The cell is - // still divergent (390380 of 921600 samples; both chroma planes - // first wrong at index 20532, x=52 y=32; entropy fork read 12465 - // at mi (90,108)) and an assertion of the form "our output is - // wrong by exactly N" would encode the defect as expected - // behaviour -- the shape this suite refuses everywhere else, and - // one that outlives the memory of why. The true assertions this - // gate can make today are the two above: the route is reached at - // 4:4:4 and is not reached at 4:2:0, and the 4:2:0 twin is - // byte-exact. The open chroma root and its numbers live in - // lanes/av1444rect.report.md §6, not in an assertion. - eprintln!( - "{NAME}: {own} own-chroma intra-BC strip(s) at 4:4:4, 0 at 4:2:0; \ - 4:2:0 twin byte-exact; 4:4:4 intra-BC CHROMA still OPEN \ - (U/V first wrong at index 20532, entropy fork read 12465 at \ - mi (90,108)) -- see lanes/av1444rect.report.md \u{00a7}6" - ); - } - } - - /// lane-av1-444interband: the DEFAULT-partition lossless 4:4:4 pin for - /// the inter 16x4/4x16 strip's chroma band stamping (the pair_chroma - /// 4:2:0-only gate, commit d5325172). Fixture pinned into `fixtures/`: - /// testsrc2 128x96 yuv444p, aomenc `--profile=1 --lossless=1 - /// --enable-palette=0 --enable-intrabc=0 --passes=1 --cpu-used=4 - /// --limit=6 --obu` (the av1llkf.report.md recipe), 6 frames; 32487 - /// bytes, sha256 - /// `1e6dd4e05038c8d51e2c8d29f8c337130c4fea0aed629415535e6e53af9a2c72`. - /// - /// This is the stream whose frame 1 desynced at the 16x4 inter strip - /// mi(2,8) -- its U bc=0 `txb_skip` read base 0 where aom reads base 1, - /// because the skipped strip (1,8)'s pair-form context stamp smeared - /// zero over `left[2][1]`. Two pins, both measured at d5325172: - /// end-to-end, every sample of every frame must match the oracle - /// aomdec exactly (the pre-fix tree refuses mid-frame-1, so the gate - /// is red by refusal, not by silent pass), and the 1:4 counter delta - /// must show the strips decoded WITHOUT the pair rewrite firing - /// (`horz4=20 vert4=28 chroma_pairs=0` -- chroma_pairs > 0 on this - /// pairless 4:4:4 stream is the defect reappearing, the - /// class `pair-rewrite-at-ss0`). - #[test] - fn a_lossless_444_defaultp_inter_strip_stream_decodes_byte_exact() { - const NAME: &str = "a_lossless_444_defaultp_inter_strip_stream_decodes_byte_exact"; - const FIXTURE_LEN: usize = 32487; - const FIXTURE_FNV: u64 = 0x5278_9f0f_ce2d_1e52; - const W: usize = 128; - const H: usize = 96; - const FRAMES: usize = 6; - let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("fixtures/ll444_defaultp_inter_strip.obu"); - let stream = std::fs::read(&obu).unwrap_or_else(|e| { - panic!( - "{NAME}: pinned fixture {} is missing ({e}) -- the gate cannot run, \ - which is a failure, not a skip", - obu.display() - ) - }); - assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: fixture length moved"); - assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: fixture bytes moved"); - - let _guard = lock_gate_counters(); - let strips_before = decode::inter16_rect4_counters(); - let frames = decode_stream(&stream) - .unwrap_or_else(|e| panic!("{NAME}: the pinned stream no longer decodes cleanly: {e}")); - let strips_after = decode::inter16_rect4_counters(); - assert_eq!(frames.len(), FRAMES, "{NAME}: frame count"); - for f in &frames { - assert_eq!((f.width, f.height), (W, H), "{NAME}: dimensions"); - } - // The 1:4 strips must have fired, and the 4:2:0 pair rewrite must - // NOT have (there are no chroma pairs at ss 0/0). - let (horz4, vert4, chroma_pairs) = ( - strips_after.0 - strips_before.0, - strips_after.1 - strips_before.1, - strips_after.2 - strips_before.2, - ); - assert_eq!(horz4, 20, "{NAME}: HORZ_4 strip count moved"); - assert_eq!(vert4, 28, "{NAME}: VERT_4 strip count moved"); - assert_eq!( - chroma_pairs, 0, - "{NAME}: chroma pairs closed on a 4:4:4 stream \ - (class pair-rewrite-at-ss0)" - ); - - // The oracle aomdec, rawvideo out: FRAMES concatenated yuv444p frames. - if aomdec_available(NAME) { - let dir = std::env::temp_dir().join(format!("ec-av1-ll444dp-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).expect("scratch dir"); - let raw = dir.join("aomdec.raw"); - let out = crate::tool_cache::cached_output_io(Command::new(aomdec_path()) - .args(["--codec=av1", "--rawvideo", "-o"]) - .arg(&raw) - .arg(&obu) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("aomdec failed to run"); - assert!( - out.status.success(), - "{NAME}: the oracle aomdec refused the stream: {}", - String::from_utf8_lossy(&out.stderr) - ); - let ref_raw = std::fs::read(&raw).expect("aomdec rawvideo output"); - let _ = std::fs::remove_dir_all(&dir); - assert_eq!(ref_raw.len(), W * H * 3 * FRAMES, "{NAME}: aomdec raw size"); - for (i, f) in frames.iter().enumerate() { - let base = i * W * H * 3; - for ((plane, off), p) in [(&f.y, 0usize), (&f.u, W * H), (&f.v, 2 * W * H)] - .into_iter() - .zip(["y", "u", "v"]) - { - let want = &ref_raw[base + off..base + off + W * H]; - let bad = plane - .iter() - .zip(want) - .filter(|&(&a, &b)| a as u8 != b) - .count(); - assert_eq!( - bad, 0, - "{NAME}: aomdec frame {i} plane {p}: {bad} samples differ \ - (class pair-rewrite-at-ss0)" - ); - } - } - } - } - - /// lane-av1-leaf8oob: the OOB pin for [`decode_leaf8`]'s intrabc chroma - /// frame-copy buffers. The closure hardcoding the leaf's chroma - /// prediction at `4x4` (`vec![0u16; 4 * 4]`, `predict_with_filter` at - /// `4, 4`) carried the 4:2:0 halving of an 8x8 luma leaf into every - /// subsampling: at 4:4:4 the leaf's own chroma plane block is 8x8 - /// (`csz == 8`), so the 16-sample override reached - /// [`PlaneBuf::reconstruct`] as an 8x8 prediction and indexed - /// `prediction[16]` of a 16-sample buffer -- - /// `index out of bounds: the len is 16 but the index is 16` at the - /// reconstruct call, on every conformant stream of this shape (a panic, - /// never a refusal). Same signature class as lane-lossless128's - /// 128-axis lossless extent (`len 16, index 16` there too). - /// - /// `crates/ec-av1/fixtures/444_leaf8_oob.obu`, 3577 bytes, sha256 - /// `72bed2791d1ceba8be7926a052c7838c5d96d4f9d56d28fb69789a753d3593af` - /// (force-added past the `fixtures` gitignore like every sibling - /// fixture): the lane ticket's witness-hunt reproducer (s1a/s2e) -- a - /// 320x256, 3-frame, 8-bit 4:4:4 screen-content keyframe run whose - /// census pins 4 intrabc 8x8 leaves (the oracle's own MB dump opens on - /// unbroken inter-classified intra = intrabc blocks). The encoding - /// recipe is not independently recoverable in this lane; the bytes are - /// pinned by length + FNV-1a64 here and by the oracle raw fingerprint - /// below. - /// - /// WHAT THIS GATE DOES NOT CLAIM: sample-exactness -- and it pins no - /// pixel baseline. Measured against the oracle aomdec (`--rawvideo`; - /// comparison method ground-truthed by the green - /// `a_lossless_sb128_rect_intra_block_decodes_sample_exact` and - /// `a_lossless_444_min_partition8_inter_stream_decodes_sample_exact` - /// witnesses on this same tree), this stream DIVERGES and its output is - /// not even self-deterministic: frame 0's first differing LUMA sample - /// is at (275,128), the (y, u, v) differing counts per frame are - /// (20811, 35467, 32320)/(20308, 39177, 35994)/(20131, 39588, 36601) of - /// 81920 samples per plane, and under `EC_AV1_PLANE_SENTINEL=1` the - /// chroma counts move (u f0 35467 -> 35630) while luma stays put. - /// Sentinel-vs-uninit output diffing localises that dependence to 458 - /// WHOLE 8x8 chroma blocks (frame 0: chroma x >= 96, y >= 64) reading - /// samples this decode never wrote -- ambient memory in those slots, - /// hence any pixel-exact assert here drifts run to run with the batch. - /// Both facts belong to ONE pre-existing defect this lane must not - /// chase (the ticket's fix touches only leaf8's chroma prediction - /// buffers, which cannot feed a luma sample, and the pre-fix run never - /// got past the panicked leaf): a decode desync on this stream around - /// frame-0 SB (3..4, 2), after which samples diverge from the oracle - /// and the misread layout leaves chroma blocks unreconstructed. - /// Disposition: `deferred(unblock: divergence lane -- EC trace pairing - /// against the oracle on this fixture)`. So this gate pins exactly what - /// its ticket owns: fixture identity, a decode that RUNS TO COMPLETION - /// where the old code died with `len 16, index 16`, and the arm counter. - /// - /// Assertions (all before/without any skip path): - /// 1. fixture bytes: exact length + FNV-1a64; - /// 2. `decode_stream` succeeds -- 3 frames, 320x256 (the pre-fix run - /// died here with the len-16/index-16 panic); - /// 3. non-vacuity: `leaf8_intrabc_hits` moves (measured 0 -> 4), so the - /// arm owning the fixed buffers really fired; - /// 4. the oracle aomdec still decodes the pinned bytes (raw size + - /// fingerprint), anchoring the deferred divergence comparison. - #[test] - fn an_intrabc_8x8_leaf_chroma_frame_copy_at_444_decodes_without_the_oob() { - const NAME: &str = "an_intrabc_8x8_leaf_chroma_frame_copy_at_444_decodes_without_the_oob"; - const FIXTURE_LEN: usize = 3577; - const FIXTURE_FNV: u64 = 0x86b9_3a51_fe16_353c; - const W: usize = 320; - const H: usize = 256; - const FRAMES: usize = 3; - let obu = - std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("fixtures/444_leaf8_oob.obu"); - let stream = std::fs::read(&obu).unwrap_or_else(|e| { - panic!( - "{NAME}: pinned fixture {} is missing ({e}) -- the gate cannot run, \ - which is a failure, not a skip", - obu.display() - ) - }); - assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: fixture length moved"); - assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: fixture bytes moved"); - - let _guard = lock_gate_counters(); - crate::decode::reset_leaf8_intrabc_hits(); - let frames = decode_stream(&stream) - .unwrap_or_else(|e| panic!("{NAME}: the pinned stream no longer decodes cleanly: {e}")); - assert!( - crate::decode::leaf8_intrabc_hits() > 0, - "{NAME}: gate is vacuous -- no intrabc 8x8 leaf was decoded, so the arm \ - owning the fixed chroma buffers never fired" - ); - assert_eq!(frames.len(), FRAMES, "{NAME}: frame count"); - for f in &frames { - assert_eq!((f.width, f.height), (W, H), "{NAME}: dimensions"); - } - - // The oracle aomdec, rawvideo out: FRAMES concatenated yuv444p frames. - if aomdec_available(NAME) { - let dir = std::env::temp_dir().join(format!("ec-av1-leaf8oob-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).expect("scratch dir"); - let raw = dir.join("aomdec.raw"); - let out = crate::tool_cache::cached_output_io(Command::new(aomdec_path()) - .args(["--codec=av1", "--rawvideo", "-o"]) - .arg(&raw) - .arg(&obu) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("aomdec failed to run"); - assert!( - out.status.success(), - "{NAME}: the oracle aomdec refused the stream: {}", - String::from_utf8_lossy(&out.stderr) - ); - let ref_raw = std::fs::read(&raw).expect("aomdec rawvideo output"); - let _ = std::fs::remove_dir_all(&dir); - assert_eq!(ref_raw.len(), W * H * 3 * FRAMES, "{NAME}: aomdec raw size"); - assert_eq!( - fnv1a64(&ref_raw), - 0x3821_0bcb_f572_973c, - "{NAME}: aomdec raw fingerprint moved" - ); - } - } - - /// lane-av1p1pin: the permanent pin for the 4:4:4 superblock-128 - /// 128-root rect witness -- recipe P1 of `lanes/av1witness2recheck.report.md`. - /// - /// Provenance. Encoder: `~/.cache/aom-oracle/build/aomenc --codec=av1 - /// --obu -o s1d.obu --passes=1 --threads=1 bands444.y4m --limit=3 - /// --kf-max-dist=1 --cpu-used=2 --end-usage=q --cq-level=20 --sb-size=128 - /// --enable-rect-partitions=1 --enable-1to4-partitions=1 - /// --min-partition-size=4`, over the ffmpeg 8.1.2 lavfi source - /// `nullsrc=s=320x256:rate=30:d=1,geq=lum='mod(floor((Y+T*160)/8)*67,255)': - /// cb='128+20*sin(Y/17+T)':cr='128+20*sin(X/23+T*2)' -pix_fmt yuv444p` - /// (`bands444.y4m`, sha256 - /// `fa6218399cce8dd9eaadb6e24642d31cb2d2bde505b39a8df237938492c642ee`). - /// Pinned bytes: `crates/ec-av1/fixtures/444_sb128rect_chroma_tile_witness.obu`, - /// 595 bytes, sha256 - /// `68773f2c6e01a2d211bf0213479accb4c2c360132c0e1bc3b326eab7861925b1` - /// (FNV-1a `0xd4fa_ac7b_dccc_520b`). Rebuilt byte-for-byte from the recipe - /// on `9a535ccb` -- the recipe did not drift. 3 frames, 320x256, yuv444p. - /// This is NOT `fixtures/444_sb128rect_lr_witness.obu` (794 B, sha256 - /// `27825e14...`), the other in-tree 4:4:4 sb128 stream. - /// - /// What it guards. At the report's old base `fe3e8418` this stream - /// panicked -- rc=101, `decode.rs:17631: assertion failed: lossless_frame - /// || (chroma_w / chroma_tx, chroma_h / chroma_tx) == (nch_x, nch_y)` -- - /// because the 128-rect chroma unit walk was hardcoded to the 4:2:0 mu-chunk - /// span, so a 128-root HORZ/VERT block at 4:4:4 coded half its chroma units. - /// Closed by `349b3918` (the per-axis invariant now at `decode.rs:24515`); - /// byte-exactness by `fa70a68c`. - /// - /// Two load-bearing arms, both proven to bite (lanes/av1p1pin.report.md): - /// (1) the census deltas -- 6 gathered edge-VERT 128-roots, 6 - /// `PARTITION_VERT` 128 roots, 6 key-frame intra 128-axis blocks, 8 coded - /// `32x32` VERT strips -- so the gate fails, rather than passes, if a - /// future stream stops coding the shape (class `gate-blind-to-feature`); - /// (2) every sample of every frame against ffmpeg `yuv444p` rawvideo, with - /// the plane-length guard that stops a short plane from zip-truncating the - /// compare. Oracle arm is aomdec `--rawvideo` as well; neither is a shim. - #[test] - fn a_444_sb128_rect_chroma_tile_witness_is_byte_exact() { - const NAME: &str = "a_444_sb128_rect_chroma_tile_witness_is_byte_exact"; - const FIXTURE_LEN: usize = 595; - const FIXTURE_FNV: u64 = 0xd4fa_ac7b_dccc_520b; - const W: usize = 320; - const H: usize = 256; - const FRAMES: usize = 3; - /// The guarded path: 128-root rect chroma tiling at 4:4:4. - const EDGE_VERT: usize = 6; - const PART128_VERT: usize = 6; - const INTRA128_VERT: usize = 6; - const RECT4_32_VERT: usize = 8; - const RECT4_32_CODED: usize = 8; - let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("fixtures/444_sb128rect_chroma_tile_witness.obu"); - let stream = read_pin(&obu, FIXTURE_LEN, FIXTURE_FNV, NAME); - - let _guard = lock_gate_counters(); - let rect_before = sb128_rect_counters(); - let part_before = part128_census(); - let r432_before = rect4_32_counters(); - let frames = decode_stream(&stream) - .unwrap_or_else(|e| panic!("{NAME}: the pinned stream no longer decodes cleanly: {e}")); - let rect_after = sb128_rect_counters(); - let part_after = part128_census(); - let r432_after = rect4_32_counters(); - - assert_eq!(frames.len(), FRAMES, "{NAME}: frame count"); - for f in &frames { - assert_eq!( - (f.width, f.height), - (W, H), - "{NAME}: dimensions -- a resized frame would make the oracle \ - slices below compare the wrong samples" - ); - } - - // Non-vacuity: the guarded 128-root VERT path really fired. - assert_eq!( - rect_after.1 - rect_before.1, - EDGE_VERT, - "{NAME}: gathered edge-VERT 128 roots moved (expected {EDGE_VERT}) -- this \ - stream is the witness for the 128-rect 4:4:4 chroma tiling, so a \ - different count means the shape is gone or the counter moved (class \ - gate-blind-to-feature)" - ); - assert_eq!( - part_after.3 - part_before.3, - PART128_VERT, - "{NAME}: 128-root PARTITION_VERT blocks moved (expected {PART128_VERT})" - ); - assert_eq!( - part_after.6 - part_before.6, - INTRA128_VERT, - "{NAME}: key-frame intra 128-axis blocks moved (expected {INTRA128_VERT})" - ); - assert_eq!( - part_after.2 - part_before.2, - 0, - "{NAME}: 128-root PARTITION_HORZ fired on this VERT witness" - ); - assert_eq!( - rect_after.0 - rect_before.0, - 0, - "{NAME}: gathered edge-HORZ 128 roots fired on this VERT witness" - ); - assert_eq!( - (r432_after.1 - r432_before.1, r432_after.2 - r432_before.2), - (RECT4_32_VERT, RECT4_32_CODED), - "{NAME}: the 32x32 VERT strip counts moved -- the coded half of the \ - chroma tiling is what the old assert under-counted" - ); - - // Oracle 1: aomdec rawvideo. - if aomdec_available(NAME) { - let dir = std::env::temp_dir().join(format!("ec-av1-p1pin-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).expect("scratch dir"); - let raw = dir.join("aomdec.raw"); - let out = crate::tool_cache::cached_output_io(Command::new(aomdec_path()) - .args(["--codec=av1", "--rawvideo", "-o"]) - .arg(&raw) - .arg(&obu) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("aomdec failed to run"); - assert!( - out.status.success(), - "{NAME}: the oracle aomdec refused the stream: {}", - String::from_utf8_lossy(&out.stderr) - ); - let ref_raw = std::fs::read(&raw).expect("aomdec rawvideo output"); - let _ = std::fs::remove_dir_all(&dir); - assert_eq!(ref_raw.len(), W * H * 3 * FRAMES, "{NAME}: aomdec raw size"); - for (i, f) in frames.iter().enumerate() { - let base = i * W * H * 3; - for ((plane, off), p) in [(&f.y, 0usize), (&f.u, W * H), (&f.v, 2 * W * H)] - .into_iter() - .zip(["y", "u", "v"]) - { - let want = &ref_raw[base + off..base + off + W * H]; - assert_eq!( - plane.len(), - want.len(), - "{NAME}: aomdec frame {i} plane {p}: ours has {} samples, the oracle's \ - has {} -- a short plane would zip-truncate the compare below and \ - hide a chroma-span defect", - plane.len(), - want.len() - ); - let bad = plane - .iter() - .zip(want) - .filter(|&(&a, &b)| a as u8 != b) - .count(); - assert_eq!( - bad, 0, - "{NAME}: aomdec frame {i} plane {p}: {bad} samples differ (class \ - sb128-rect-chroma-tiling)" - ); - } - } - } - - // Oracle 2: ffmpeg yuv444p rawvideo. Hard-fails, never skips, when - // EC_AV1_REQUIRE_FFMPEG=1 (see have_ffmpeg). - if have_ffmpeg() { - let refs = ffmpeg_decode_sequence_444(&stream, W, H, FRAMES); - for (i, (got, want)) in frames.iter().zip(refs.iter()).enumerate() { - for (p, (g, r)) in [(&got.y, &want.y), (&got.u, &want.u), (&got.v, &want.v)] - .iter() - .enumerate() - { - assert_eq!( - g.len(), - r.len(), - "{NAME}: ffmpeg frame {i} plane {p}: ours has {} samples, ffmpeg's has \ - {} -- a short plane would zip-truncate the compare below and hide a \ - chroma-span defect", - g.len(), - r.len() - ); - let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count(); - assert_eq!( - bad, 0, - "{NAME}: ffmpeg frame {i} plane {p}: {bad} samples differ (class \ - sb128-rect-chroma-tiling)" - ); - } - } - } else { - eprintln!("SKIP {NAME}: no ffmpeg -- the ffmpeg oracle arm only"); - } - } - - /// lane-lossless128: a LOSSLESS key frame that codes a 128-axis - /// (`BLOCK_64X128`) intra block -- the shape libaom's `read_tx_size` forces - /// to `TX_4X4` on its very first line (`decodeframe.c:1183`), so every plane - /// of the block is a 4x4 transform unit and NO `tx_size_cat3` symbol is - /// coded. - /// - /// On the merged base `decode_block_128rect` had no lossless carve-out: it - /// read `logical_tx = 64` off `depth == 0`, handed `PlaneBuf::reconstruct` - /// a 64x64 geometry with the 16-sample 4x4 residual - /// [`TxParams::run`](crate::decode::TxParams) produced -- `index out of - /// bounds: the len is 16 but the index is 16` at the reconstruction call, - /// on EVERY conformant stream of this shape (a panic, never a refusal). - /// - /// `crates/ec-av1/fixtures/lossless_sb128_rect_kf.obu`, 3471 bytes, sha256 - /// `013b07979c8be999c70d47f32768c2bf959be086a893f60dde1b0f5e35d4f475`: - /// `aomenc --codec=av1 --passes=1 --threads=1 --obu --lossless=1 - /// --cpu-used=0` over a 320x256, 4-frame source that is flat grey except a - /// textured 64x128 patch in the top-right corner -- which is what makes the - /// 128 root take `PARTITION_VERT` and code the `BLOCK_64X128` at mi(0,64). - /// - /// The counter delta keeps the gate non-vacuous: a stream that stopped - /// coding the shape reads 0 and the gate fails instead of passing on a - /// decode that never reached the fixed body (class - /// `gate-blind-to-feature`). - #[test] - fn a_lossless_sb128_rect_intra_block_decodes_sample_exact() { - const NAME: &str = "a_lossless_sb128_rect_intra_block_decodes_sample_exact"; - // The pixel arm needs ffmpeg; the decode and its counter deltas do - // not, so a box without ffmpeg still proves the shape was reached - // (class `gate-skips-on-its-own-failure`) -- the skip is still named. - let ffmpeg = have_ffmpeg(); - if !ffmpeg { - eprintln!("SKIP {NAME}: no ffmpeg -- the ffmpeg pixel arm only"); - } - let (w, h, frames) = (320usize, 256usize, 4usize); - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("fixtures/lossless_sb128_rect_kf.obu"); - let stream = std::fs::read(&path) - .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display())); - let before = crate::decode::intra128_lossless_hits(); - let before_replay = crate::decode::sb128rect_chroma_replay_hits(); - let ours = decode_stream(&stream) - .unwrap_or_else(|e| panic!("{NAME}: a lossless 128-axis key frame decodes: {e}")); - let hits = crate::decode::intra128_lossless_hits() - before; - assert!( - hits > 0, - "{NAME}: this stream coded NO lossless 128-axis intra block -- the fixed body \ - was never reached (class gate-blind-to-feature)" - ); - // lane-av1-128rectspan: the 4:2:0 twin of the 4:4:4 gate's replay - // assertion. This stream codes the 64x128 block at mi(0,64) with - // TX_4X4 chroma units, so the end-of-block replay re-stamps each of - // them over its own luma-mi rows -- the arm the span fix sits on, on - // the OTHER admitted ss (1,1). The mismatch half is the 4:2:2 - // signature; lane-av1422lift: 4:2:2 is decoded now, so this is no - // longer "the tripwire for the day it is not". It is a zero this gate - // asserts about the stream in front of it, and nothing else. - // **DO NOT carry it to a 4:2:2 stream**: the two - // `422_intrabc_sb128_strip*` pins read `mismatch = 9` each and are - // byte-exact against ffmpeg, so a 4:2:2 zero assert would red on a - // provably correct cell. The 4:2:2 rows of the corpus gate read - // neither half of this counter. - let after_replay = crate::decode::sb128rect_chroma_replay_hits(); - assert!( - after_replay.0 > before_replay.0, - "{NAME}: no 128-axis block replayed a chroma unit's own mi state -- the replay \ - arm never ran (class gate-blind-to-feature)" - ); - assert_eq!( - after_replay.1, - before_replay.1, - "{NAME}: the tail replay stamped {} unit(s) over a height that was not the \ - unit's own luma height (4:2:2 spans leaked into an admitted stream)", - after_replay.1 - before_replay.1 - ); - eprintln!( - "{NAME}: replayed {} chroma unit(s), {} span mismatch(es)", - after_replay.0 - before_replay.0, - after_replay.1 - before_replay.1 - ); - if !ffmpeg { - return; - } - let refs = ffmpeg_decode_sequence(&stream, w, h, frames); - assert_eq!(ours.len(), frames, "{NAME}: shown/display frame count"); - for (i, (got, want)) in ours.iter().zip(refs.iter()).enumerate() { - for (plane, (g, r)) in [(&got.y, &want.y), (&got.u, &want.u), (&got.v, &want.v)] - .iter() - .enumerate() - { - let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count(); - assert_eq!( - bad, 0, - "{NAME}: frame {i} plane {plane}: {bad} samples differ from ffmpeg" - ); - assert_eq!( - g.len(), - r.len(), - "{NAME}: frame {i} plane {plane}: ours has {} samples, ffmpeg's has {} -- a \ - short plane would zip-truncate the compare above and hide a chroma-span \ - defect", - g.len(), - r.len() - ); - } - } - eprintln!("{NAME}: {frames} frames sample-exact, intra128_lossless hits {hits}"); - } - - /// lane-av1-loss64: a lossless superblock-128 frame whose intra blocks - /// overhang the bottom frame edge codes NO coefficient symbols for the - /// chroma transform units whose 4x4 origin sits outside the frame's mi - /// grid -- libaom `decode_reconstruct_tx` returns before any read - /// (`decodeframe.c:299`, `blk_row >= max_blocks_high || blk_col >= - /// max_blocks_wide`, the limits from `max_block_wide/high`, - /// av1_common_int.h:1565). The square multi-transform-unit chroma loop in - /// [`crate::decode`] carried no such clip (the luma loop had one) and read - /// `txb_skip`+coefficients for the phantom units: on the measured stream - /// the first lossless 64x64 `NONE` block, at mi(48,0), overhangs the - /// 240-px frame by 4 mi, so its 32x32 chroma codes SIX rows of 4x4 units, - /// not eight -- 32 phantom unit reads per plane desynced the tile and - /// every later symbol (including partition reads, which is what made - /// aomdec's zero-`value=8/9` census look like a partition-reader defect - /// in the rect14 review) decoded as garbage. - /// - /// Fail-pre-fix, measured on the ed12fe52 probe: both arms differ from - /// ffmpeg at byte 41120 (luma row 128 col 160, the first block decoded - /// after the phantom reads). The counter delta pins non-vacuity (class - /// `gate-blind-to-feature`): 96 clipped units on each arm. - #[test] - fn a_lossless_sb128_square_frame_clips_overhanging_chroma_tus() { - const NAME: &str = "a_lossless_sb128_square_frame_clips_overhanging_chroma_tus"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - // Arm 0 is the rect14 report's `loss320` recipe verbatim; arm 1 is its - // `lnone` companion (1:4 and rect partitions off) -- both coded the - // overhanging 64x64 blocks and both desynced at byte 41120 pre-fix. - let arms: [&[&str]; 2] = [ - &["--min-partition-size=4"], - &[ - "--min-partition-size=4", - "--enable-1to4-partitions=0", - "--enable-rect-partitions=0", - ], - ]; - let mut clips_total = 0usize; - for (arm, extra) in arms.iter().enumerate() { - let stream = lossless_sb128_testsrc2(320, 240, extra); - crate::decode::reset_loss64_hits(); - let ours = - decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME}: arm {arm} decodes: {e}")); - let clips = crate::decode::chroma_edge_tu_clip_hits(); - assert!( - clips > 0, - "{NAME}: arm {arm} clipped NO overhanging chroma transform unit -- \ - the fixed body was never reached (class gate-blind-to-feature)" - ); - clips_total += clips; - let refs = ffmpeg_decode_sequence(&stream, 320, 240, 1); - assert_eq!(ours.len(), 1, "{NAME}: arm {arm} frame count"); - for (plane, (g, r)) in [ - (&ours[0].y, &refs[0].y), - (&ours[0].u, &refs[0].u), - (&ours[0].v, &refs[0].v), - ] - .iter() - .enumerate() - { - let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count(); - assert_eq!( - bad, 0, - "{NAME}: arm {arm} plane {plane}: {bad} samples differ from ffmpeg" - ); - assert_eq!( - g.len(), - r.len(), - "{NAME}: arm {arm} plane {plane}: ours has {} samples, ffmpeg's has {} -- a \ - short plane would zip-truncate the compare above and hide a chroma-span \ - defect", - g.len(), - r.len() - ); - } - } - eprintln!("{NAME}: 2 arms full-frame exact, {clips_total} chroma units clipped"); - } - - /// lane-av1-loss64: a SKIPPED intrabc rect strip on a lossless frame - /// zeroes its whole entropy-band footprint (libaom - /// `av1_reset_entropy_context`, `if (mbmi->skip_txfm)` decodeframe.c:1262 -> - /// blockd.c:58) instead of leaving the previous occupant's luma bands - /// standing. The skip arm of `decode_intrabc_owned_rect` never wrote the - /// luma bands: the lossless `read_block_tx_size_rect` resolves the 4x4 - /// leaf list before it looks at `skip`, so the tail took the - /// per-transform-unit record path (chroma only) with no per-unit luma - /// writes ever run. The next block then read a STALE band: on the 320x242 - /// `--min-partition-size=4` sibling of this stream the skipped 8x16 - /// intrabc strip at mi(48,66) left a 7 in left[48] and mi(48,68)'s first - /// transform unit read `txb_skip_ctx` 3 where aomdec reads 1 (measured - /// `EC_ECDUMP` against the instrumented aomdec) -- a coefficient-walk - /// desync at byte 61712 with every mode symbol still matching. - /// - /// This gate uses the same `--min-partition-size=4` arm that reaches the - /// sub-8x8 VERT -> 4x8 skipped-intrabc leaf. Post-fix it is full-frame - /// exact: the skip path uses libaom's clamped 4x4 chroma intrabc - /// prediction (`decodeframe.c:1011-1065`, `reconinter_template.inc:186-207`) - /// instead of the ordinary skipped-intra DC predictor. The old route first - /// differed at U(104,92) with the entropy ladder fully synced. - /// - /// Fail-pre-fix, measured on the ed12fe52 probe: differs at byte 41120 - /// (the chroma-clip class, fixed in the same lane). Single-mutation on - /// the lane tree with ONLY this gate's walk reverted: differs at byte - /// 61712, the band-leak site. - #[test] - fn a_skipped_lossless_intrabc_rect_strip_zeroes_its_entropy_bands() { - const NAME: &str = "a_skipped_lossless_intrabc_rect_strip_zeroes_its_entropy_bands"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - let stream = lossless_sb128_testsrc2(320, 242, &["--min-partition-size=4"]); - crate::decode::reset_loss64_hits(); - crate::decode::reset_skipped_intrabc_chroma_arm_hits(); - let ours = decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME}: decodes: {e}")); - let resets = crate::decode::skip_lossless_band_reset_hits(); - let intrabc_skips = crate::decode::skipped_intrabc_chroma_arm_hits(); - assert!( - resets > 0, - "{NAME}: this stream coded NO skipped lossless intrabc rect strip -- \ - the fixed body was never reached (class gate-blind-to-feature)" - ); - assert!( - intrabc_skips > 0, - "{NAME}: this stream coded NO skipped sub-8x8 intrabc chroma leaf -- \ - the clamped chroma prediction fix was never reached (class gate-blind-to-feature)" - ); - let refs = ffmpeg_decode_sequence(&stream, 320, 242, 1); - assert_eq!(ours.len(), 1, "{NAME}: frame count"); - for (plane, (g, r)) in [ - (&ours[0].y, &refs[0].y), - (&ours[0].u, &refs[0].u), - (&ours[0].v, &refs[0].v), - ] - .iter() - .enumerate() - { - let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count(); - assert_eq!( - bad, 0, - "{NAME}: plane {plane}: {bad} samples differ from ffmpeg" - ); - assert_eq!( - g.len(), - r.len(), - "{NAME}: plane {plane}: ours has {} samples, ffmpeg's has {} -- a short plane \ - would zip-truncate the compare above and hide a chroma-span defect", - g.len(), - r.len() - ); - } - eprintln!( - "{NAME}: full-frame exact, {resets} band resets, \ - {intrabc_skips} skipped intrabc chroma predictions" - ); - } - - /// lane-av1-ibc444rect: an unskipped intrabc `BLOCK_8X4`/`BLOCK_4X8` leaf - /// on a lossless 4:4:4 frame walks its coefficients as per-4x4 inter - /// `TX_4X4` units on every plane -- `read_tx_size`'s lossless first line - /// (`decodeframe.c:1203`) forces TX_4X4 before any tree, the frame's - /// `TxMode` is `ONLY_4X4` so no var-tx tree is read either, and - /// `av1_read_tx_type`'s qindex==0 early return (`decodemv.c:681`) drops - /// the tx_type symbol the lossy 4x4 inter sets carry -- NOT the single - /// `LumaRect8x4Inter`/`ChromaRect8x4` rect unit the non-lossless arm - /// reads, and not the lossy per-unit arm's tx_type read. - /// - /// The pinned fixture `ll444_ibc_rect.obu` (99614 bytes, provenance in - /// `lanes/av1ibc444rect.report.md`) is a lossless `--profile=1 --i444 - /// --enable-intrabc=1` key frame. r1 pinned the (then-known) leaf8 - /// `palette_window` panic as its alignment witness; with that blocker - /// fixed upstream (lane-av1leaf8oob) the frame decodes to completion and - /// this gate is the FULL-FRAME exact `aomdec` comparison its r1 doc - /// promised, flipped by lane-av1-ibcskip2 -- which also closed the - /// SKIPPED intrabc sub8 chroma cells the r1 measurement called out: a - /// skipped intrabc leaf's chroma is the bare frame copy at the DV - /// (libaom's `av1_build_inter_predictors_sb` runs regardless of `skip`), - /// never the intra-DC push that arm used to run. Fail-before, measured on - /// this tree with the DV-copy arm cut back to the intra push: 2794 U + - /// 2830 V samples differ across 180 distinct 4x4 cells, 175 of them - /// exactly this frame's skipped intrabc leaves, luma clean; with the arm, - /// 0 differing samples on every plane. - #[test] - fn a_lossless_444_intrabc_rect_leaf_walks_per_4x4_units() { - const NAME: &str = "a_lossless_444_intrabc_rect_leaf_walks_per_4x4_units"; - const FIXTURE_LEN: usize = 99614; - const FIXTURE_FNV: u64 = 0xa1b6_a84e_ac6a_656f; - const W: usize = 320; - const H: usize = 240; - let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("fixtures/ll444_ibc_rect.obu"); - let stream = std::fs::read(&obu).unwrap_or_else(|e| { - panic!( - "{NAME}: pinned fixture {} is missing ({e}) -- the gate cannot run, \ - which is a failure, not a skip", - obu.display() - ) - }); - assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: fixture length moved"); - assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: fixture bytes moved"); - - let _guard = lock_gate_counters(); - crate::decode::reset_ibc444rect_hits(); - crate::decode::reset_skipped_intrabc_dv_copy_hits(); - let frames = decode_stream(&stream).unwrap_or_else(|e| { - panic!( - "{NAME}: the fixture must decode to completion (the leaf8 \ - chroma buffers were fixed upstream): {e}" - ) - }); - assert_eq!(frames.len(), 1, "{NAME}: shown frame count"); - let luma = crate::decode::intrabc_rect8_lossless_luma_hits(); - let chroma = crate::decode::intrabc_rect8_lossless_chroma_hits(); - assert_eq!( - (luma, chroma), - (339, 339), - "{NAME}: the per-4x4 walk must fire on the fixture's full unskipped \ - intrabc rect census (got luma {luma}, chroma {chroma}) -- zero \ - means the fixture no longer reaches the fixed body (class \ - gate-blind-to-feature), more means the entropy desynced and \ - garbage blocks read as intrabc rect leaves" - ); - let dv_skips = crate::decode::skipped_intrabc_dv_copy_hits(); - assert_eq!( - dv_skips, 150, - "{NAME}: the skipped-intrabc DV-copy chroma arm must fire on every \ - one of the fixture's 150 skipped intrabc leaves (got {dv_skips}) \ - -- zero means the arm is unreachable (class gate-blind-to-feature)" - ); - - // The oracle aomdec, rawvideo out: one concatenated yuv444p frame. - if aomdec_available(NAME) { - let dir = std::env::temp_dir().join(format!("ec-av1-ibcskip2-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).expect("scratch dir"); - let raw = dir.join("aomdec.raw"); - let out = crate::tool_cache::cached_output_io(Command::new(aomdec_path()) - .args(["--codec=av1", "--rawvideo", "-o"]) - .arg(&raw) - .arg(&obu) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("aomdec failed to run"); - assert!( - out.status.success(), - "{NAME}: the oracle aomdec refused the stream: {}", - String::from_utf8_lossy(&out.stderr) - ); - let ref_raw = std::fs::read(&raw).expect("aomdec rawvideo output"); - let _ = std::fs::remove_dir_all(&dir); - assert_eq!(ref_raw.len(), W * H * 3, "{NAME}: aomdec raw size"); - let f = &frames[0]; - for (plane, off, p) in [ - (&f.y, 0usize, "Y"), - (&f.u, W * H, "U"), - (&f.v, 2 * W * H, "V"), - ] { - let want = &ref_raw[off..off + W * H]; - let bad = plane - .iter() - .zip(want) - .filter(|&(&a, &b)| a as u8 != b) - .count(); - assert_eq!( - bad, 0, - "{NAME}: aomdec plane {p}: {bad} samples differ -- a \ - regression here reopens the skipped-intrabc sub8 chroma \ - predictor or the rect walk" - ); - } - } - eprintln!( - "{NAME}: frame sample-exact vs oracle aomdec; {luma}+{chroma} rect \ - walks, {dv_skips} skipped-intrabc DV copies" - ); - } - - /// lane-dkey: the palette-neighbour-band gate. A palette-Y block's size and - /// colours used to stay standing in the mi-granular above/left bands after a - /// sub-8x8 group was decoded next to it -- the sub-8x8 readers published - /// skip/lf/mode state but no palette state, while libaom's mi grid carries - /// `palette_size == 0` in exactly those cells (`av1_allow_palette` needs - /// BLOCK_8X8 and up). The next intra block then read `palette_y_mode` off - /// CDF row 1 where libaom reads row 0 (class `cdf-row-held-constant`), - /// decoded a palette libaom never coded, and skipped the `use_filter_intra` - /// symbol a palette block has none of: one symbol short, tile desynced. - /// - /// Measured on the instrumented aomdec at KEY-frame block mi(76,88) of this - /// very stream (`EC_PALSYN_AOM ... ctx=0 y=0` against our `mode_ctx=1`). - /// Without the fix every one of the 12 frames differs from ffmpeg's decode - /// from luma sample 491904 on. - /// - /// The source is SYNTHETIC (no film sample lives in `fixtures`): the dark, - /// near-flat background libaom's own screen-content detector counts as - /// screen content (2..=4 distinct luma values per 16x16 block), which is - /// what turns palette on, plus one textured patch at a HALF-PEL position on - /// half the frames so the encoder splits that region down to 4x4 groups - /// beside its palette blocks. - #[test] - fn a_libaom_screen_stream_with_sub8_groups_beside_palette_blocks_decodes_exact() { - const NAME: &str = - "a_libaom_screen_stream_with_sub8_groups_beside_palette_blocks_decodes_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - let (w, h, frames) = (1920usize, 1024usize, 12usize); - let mut raw = Vec::with_capacity(frames * w * h * 3 / 2); - for f in 0..frames { - let mut y = vec![0u8; w * h]; - for row in 0..h { - for col in 0..w { - y[row * w + col] = - 16 + ((col / 32 + row / 32) % 5) as u8 + ((col / 4 + row / 4) % 3) as u8; - } - } - // 2.5 px per pair of frames: integer on one pair, half a pixel off - // on the next (linear interpolation), so the patch's edges land - // mid-sample and the encoder splits there. - let x0 = 200.0 + 2.5 * (f / 2) as f64; - let (fx, ix) = (x0.fract(), x0.floor() as usize); - for row in 300..428 { - for col in 0..192 { - let tex = |u: f64| -> f64 { - let v = (row - 300) as f64; - 30.0 + 100.0 * (0.5 + 0.5 * ((u * 0.35).sin() * (v * 0.21).cos())) - }; - let s = tex(col as f64) * (1.0 - fx) + tex(col as f64 - 1.0) * fx; - y[row * w + ix + col] = s.round().clamp(0.0, 255.0) as u8; - } - } - raw.extend_from_slice(&y); - raw.extend(std::iter::repeat_n(128u8, w * h / 2)); - } - // [[pid-keyed-temp-path]]: parallel test binaries must not share a name. - let src = std::env::temp_dir().join(format!("ec-av1-palsub8-{}.yuv", std::process::id())); - std::fs::write(&src, &raw).expect("raw source"); - let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"]) - .args(["-s", &format!("{w}x{h}"), "-r", "24", "-i"]) - .arg(&src) - .args(["-an", "-threads", "1", "-g", "12", "-c:v", "libaom-av1"]) - .args([ - "-cpu-used", - "6", - "-b:v", - "0", - "-crf", - "35", - "-f", - "obu", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - let _ = std::fs::remove_file(&src); - if !out.status.success() { - eprintln!( - "SKIP {NAME}: ffmpeg has no libaom-av1 encoder ({})", - String::from_utf8_lossy(&out.stderr) - ); - return; - } - let stream = out.stdout; - let ours = decode_stream(&stream).expect("libaom screen-content stream decodes"); - let theirs = ffmpeg_decode_sequence(&stream, w, h, frames); - assert_eq!(ours.len(), frames, "{NAME}: shown frame count"); - for (i, (a, b)) in ours.iter().zip(theirs.iter()).enumerate() { - for (plane, l, r) in [("Y", &a.y, &b.y), ("U", &a.u, &b.u), ("V", &a.v, &b.v)] { - let first = l.iter().zip(r.iter()).position(|(x, y)| x != y); - assert!( - first.is_none(), - "{NAME}: frame {i} plane {plane} differs from ffmpeg at sample {}", - first.unwrap() - ); - assert_eq!( - l.len(), - r.len(), - "{NAME}: frame {i} plane {plane}: ours has {} samples, ffmpeg's has {} -- a \ - short plane would zip-truncate the compare above and hide a chroma-span \ - defect", - l.len(), - r.len() - ); - } - } - } - - /// Hardened past the report-only test above: a real libaom-av1 gradients - /// stream, pinned deterministic (`gradients`' own `seed=`, plus - /// `-threads 1`/`-row-mt 0`/no tiling so libaom's `cpu-used 8` RD search - /// cannot pick a different mode set run to run) and with CDEF turned off - /// (this decoder's tile path never applies that in-loop filter -- see - /// `cdef_is_active` in `decode_stream` -- so a stream that leaves it on - /// decodes-but-wrong instead of refusing at cdef_bits==0; ffmpeg's - /// `-enable-cdef 0` keeps this fixture out of that gap rather than this - /// test working around it). Asserts pixel-exact against ffmpeg's own - /// decode of the identical bytes, not just "decoded without error". - #[test] - fn a_real_libaom_gradients_stream_decodes_pixel_exact() { - if !have_ffmpeg() { - eprintln!("SKIP a_real_libaom_gradients_stream_decodes_pixel_exact: no ffmpeg"); - return; - } - let (width, height) = (64, 64); - let stream = libaom_encode_with( - &gradients_source(42, width, height, "rate=1"), - width, - height, - 15, - &[ - "-threads", - "1", - "-row-mt", - "0", - "-tile-columns", - "0", - "-tile-rows", - "0", - "-enable-cdef", - "0", - ], - ) - .expect("ffmpeg encode"); - let frames = decode_stream(&stream).expect("decode_stream on a real libaom stream"); - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1); - assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg"); - assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg"); - assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg"); - } - - /// As [`a_real_libaom_gradients_stream_decodes_pixel_exact`], but at - /// 32x32 (below `is_cfl_allowed`'s 32x32 luma bound as a *single* - /// undivided block, spec 5.11.5) rather than 64x64 -- a whole 64x64 SB - /// is never CFL-eligible itself, only its <=32x32 partitions, and - /// `testsrc2`/`gradients` at 64x64 with rect/ab/1to4/angle-delta search - /// disabled reliably pick a whole-SB `PARTITION_NONE` (probed - /// lane-av1real r2), so no fixture at that size exercises CfL at all. - /// A 32x32 frame is exactly the whole-block, CFL-allowed case, and - /// lane-av1real r2 found `gradients` there reliably selects - /// `UV_CFL_PRED` (`uv_mode=13`) across a crf sweep -- `testsrc2` there - /// stays DC. Proves the CfL port this round added, not just DC-chroma - /// decode: pixel-exact against ffmpeg's own decode, not just "decoded". - /// - #[test] - fn a_real_libaom_cfl_stream_decodes_pixel_exact() { - if !have_ffmpeg() { - eprintln!("SKIP a_real_libaom_cfl_stream_decodes_pixel_exact: no ffmpeg"); - return; - } - let (width, height) = (32, 32); - let stream = libaom_encode_with( - &gradients_source(42, width, height, "rate=1"), - width, - height, - 15, - &[ - "-threads", - "1", - "-row-mt", - "0", - "-tile-columns", - "0", - "-tile-rows", - "0", - "-enable-cdef", - "0", - ], - ) - .expect("ffmpeg encode"); - let frames = decode_stream(&stream).expect("decode_stream on a real libaom stream"); - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1); - assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg"); - assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg"); - assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg"); - } diff --git a/crates/ec-av1/src/stream/tests/t03.rs b/crates/ec-av1/src/stream/tests/t03.rs deleted file mode 100644 index c6d6bdba..00000000 --- a/crates/ec-av1/src/stream/tests/t03.rs +++ /dev/null @@ -1,4567 +0,0 @@ -use super::*; -use super::support::*; -use super::gates_a::*; -use crate::probe::run_with_stdin; -use std::process::{Command, Stdio}; - - /// As [`a_real_libaom_gradients_stream_decodes_pixel_exact`], but leaves - /// CDEF *on* (no `-enable-cdef 0`) -- the whole point of `lane-av1cdef`: - /// proves `apply_cdef` itself, not just that this decoder still works - /// when the filter never fires. Gradient content at a low crf reliably - /// gives libaom something to dering. - /// - /// lane-av1skipfix: the attempt-loop shape. A single-SB 64x64 frame can - /// never make libaom write `cdef_bits > 0` (nothing to differentiate per - /// superblock), so this recipe is MULTI-SB and MULTI-FRAME, and it sweeps - /// (size, cpu-used, crf) until one attempt reads a real `cdef_idx` literal - /// -- MEASURED 2026-09-29 on `a21f3680`: 64x64 at every crf/cpu reads - /// ZERO `cdef_idx` (single superblock, `bits == 0`, though `apply_cdef` - /// does filter with a nonzero strength pair), while 128x64/128x128 at - /// 24 frames read 2-8. Every attempt that decodes is ALWAYS pixel- - /// compared against ffmpeg's own decode of the identical bytes; a decode - /// error is a named refusal recorded per attempt, never a SKIP, and - /// exhausting every attempt -- or decoding without ever reading a - /// `cdef_idx` -- is a hard FAILURE (an unfired gate is a vacuous gate, - /// class `gate-skips-on-its-own-failure`). - #[test] - fn a_real_libaom_gradients_stream_with_cdef_decodes_pixel_exact() { - const NAME: &str = "a_real_libaom_gradients_stream_with_cdef_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - // (width, height, frames, cpu-used, crf). The frame count is what - // gives libaom's cdef search more than one superblock to price. - const RECIPES: [(usize, usize, usize, &str, u32); 8] = [ - (128, 64, 24, "0", 20), - (128, 64, 24, "2", 20), - (128, 64, 24, "0", 16), - (128, 128, 24, "2", 20), - (128, 128, 24, "0", 16), - (128, 128, 24, "0", 24), - (128, 64, 24, "2", 24), - (128, 128, 24, "2", 24), - ]; - let mut refusals = Vec::new(); - let mut counted_exact = 0u32; - let mut uncounted_exact = 0u32; - for (w, h, frames, cpu, crf) in RECIPES { - let Some(stream) = libaom_encode_with( - &gradients_source(42, w, h, "rate=25"), - w, - h, - crf, - &[ - "-cpu-used", - cpu, - "-frames:v", - &frames.to_string(), - "-threads", - "1", - "-row-mt", - "0", - "-tile-columns", - "0", - "-tile-rows", - "0", - ], - ) else { - refusals.push(format!( - "{w}x{h} cpu-used {cpu} crf {crf}: ffmpeg itself refused" - )); - continue; - }; - let before = decode::cdef_idx_hits(); - let decoded = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => { - refusals.push(format!("{w}x{h} cpu-used {cpu} crf {crf}: {e}")); - continue; - } - }; - // A decode that succeeded is ALWAYS pixel-compared; the hit - // counter only decides whether the attempt counts as firing - // (class `counter-from-refused-stream`). - let counted = decode::cdef_idx_hits() != before; - if counted { - counted_exact += 1; - } else { - uncounted_exact += 1; - } - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, w, h, frames); - assert_eq!(decoded.len(), frames); - for (i, (got, want)) in decoded.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!( - got.y, want.y, - "{NAME} frame {i} luma vs ffmpeg ({w}x{h} cpu-used {cpu} crf {crf}, \ - cdef_idx fired: {counted})" - ); - assert_eq!( - got.u, want.u, - "{NAME} frame {i} U vs ffmpeg ({w}x{h} cpu-used {cpu} crf {crf}, \ - cdef_idx fired: {counted})" - ); - assert_eq!( - got.v, want.v, - "{NAME} frame {i} V vs ffmpeg ({w}x{h} cpu-used {cpu} crf {crf}, \ - cdef_idx fired: {counted})" - ); - } - if counted_exact >= 2 { - break; - } - } - gate_buckets(NAME, counted_exact, uncounted_exact, refusals.len()); - assert!( - counted_exact > 0, - "{NAME}: no attempt of {} read a cdef_idx literal -- CDEF is not exercised \ - (class gate-blind-to-feature):\n{}", - RECIPES.len(), - refusals.join("\n") - ); - } - - /// lane-av1422h232: the non-vacuity test for [`count_rawvideo_diffs`]. - /// - /// A cell-classifying counter that cannot report a difference is worse - /// than no counter, because it reports "exact" for everything -- that is - /// exactly how lane-av1422remeasure's "18/18 byte-exact" table was - /// produced (it compared our own packed samples against the same - /// samples, never reading `aomdec`'s output). - /// - /// It used to lean on the pinned witness DIFFERING to prove the counting - /// path fires. That witness is byte-exact now (lane-av1422hrtx fixed the - /// 32-point inter chroma `tx_type`), so "it differs" is no longer - /// available and a witness-based version of this test would be vacuous by - /// construction. Instead this proves the same property directly and - /// unconditionally: flipping ONE bit of the ORACLE's own bytes must move - /// the count by exactly one, in the plane that bit is in, and knock exactly - /// one frame out of `frames_exact`. A comparator that had stopped reading - /// the oracle reports the baseline numbers again and fails by name. - #[test] - fn the_counting_oracle_diff_detects_one_flipped_oracle_byte() { - const NAME: &str = "the_counting_oracle_diff_detects_one_flipped_oracle_byte"; - // lane-av1cmpaudit2: same mutex as every other oracle gate -- this - // one reads `aomdec_path()`, so it must not overlap a sibling's - // tampered-oracle run. - let _gate_lock = lock_gate_counters(); - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("fixtures") - .join("420_oddheight_320x232.obu"); - let data = std::fs::read(&path).expect("the pinned witness is missing"); - let (wy, wu, wv, frames, exact) = - count_rawvideo_diffs(&data, NAME, None).expect("the two sides must be byte-comparable"); - assert_eq!( - (wy, wu, wv, exact), - (0, 0, 0, frames), - "{NAME}: the pinned witness must decode byte-exactly against `aomdec --rawvideo`" - ); - // Frame 0 byte 0 is luma; byte 90_000 is inside frame 0's chroma. - for (idx, plane) in [(0usize, 0usize), (90_000, 1)] { - let (wy, wu, wv, _, exact) = count_rawvideo_diffs(&data, NAME, Some(idx)) - .expect("the two sides must be byte-comparable"); - let got = [wy, wu, wv]; - assert_eq!( - got.iter().sum::(), - 1, - "{NAME}: flipping oracle byte {idx} must report exactly ONE wrong sample \ - across all planes -- got {got:?}. Reporting the unflipped numbers means \ - the comparison stopped reading the oracle's bytes" - ); - assert_eq!(got[plane], 1, "{NAME}: byte {idx} is in plane {plane}"); - assert_eq!( - exact, - frames - 1, - "{NAME}: one flipped byte spoils one frame" - ); - } - eprintln!("{NAME}: baseline exact, each flipped oracle byte reported as exactly 1"); - } - - /// lane-av1cmpframe: the control for the class - /// `comparator-that-attributes-the-wrong-plane`. - /// - /// [`count_rawvideo_diffs`] used to derive its plane split from the FIRST - /// decoded picture and compare every byte index against those frame-0 - /// thresholds. On a multi-frame stream that attributes every sample after - /// frame 0's luma to the LAST plane: on the pinned 320x236 stream below - /// (16 frames of 320x236 4:2:0, 113 280 bytes per frame, so plane V holds - /// 302 080 bytes in total) it reported `wrong_v = 330 673` -- more wrong V - /// bytes than exist. The per-frame totals and the frame-exact count were - /// sound, so the defect was invisible to every gate that only asserted - /// zeros; it corrupted exactly the numbers a per-plane report exists to - /// give. - /// - /// Three arms, each of which the old attribution FAILS: - /// - /// 1. **Arithmetic.** Each plane's count must be at most that plane's own - /// byte capacity summed over frames, and the three must sum to the - /// independently computed total. The old code reported 330 673 wrong V - /// bytes in a 302 080-byte plane. - /// 2. **A later frame's U.** Flipping one byte inside frame 5's U plane - /// must move U by exactly one and leave Y and V at their baseline. - /// The old code has no frame-5 U at all -- byte 600 000 is past every - /// frame-0 threshold, so it landed in V. - /// 3. **Frame attribution.** `frames_exact` must equal the number of - /// frames this test counts itself, per frame, from the decoded - /// pictures' own plane lengths. - /// - /// The pin is asserted only for IDENTITY (bytes + fnv1a64) and for - /// comparability. Whether the stream currently diverges is deliberately - /// NOT asserted: this is a control for the INSTRUMENT, and it must keep - /// biting after the odd-height entropy fork is fixed. - #[test] - fn the_counting_oracle_diff_attributes_planes_per_frame() { - const NAME: &str = "the_counting_oracle_diff_attributes_planes_per_frame"; - let _gate_lock = lock_gate_counters(); - const FILE: &str = "420_oddheight_320x236.obu"; - const BYTES: usize = 16562; - // sha256 84e4d1ab56620af1c5b78e1aa3d2d67496a492f2e127198c82dd1d68b01c6200. - // The tree pins fixture identity by fnv1a64; a `const SHA256` - // compared against itself would be the tautology this lane exists to - // kill, so it is not written. - const FNV1A64: u64 = 521889434652397870; - let data = crate_pin("420_oddheight_320x236.obu"); - let data = std::fs::read(&data) - .unwrap_or_else(|e| panic!("{NAME}: the committed pin {FILE} is missing ({e})")); - assert_eq!(data.len(), BYTES, "{NAME}: {FILE} size drifted"); - assert_eq!(fnv1a64(&data), FNV1A64, "{NAME}: {FILE} bytes drifted"); - let bit_depth = stream_bit_depth(&data, NAME); - let bpp = if bit_depth == 8 { 1 } else { 2 }; - - // ---- this test's own reading of the oracle, from scratch --------- - let dir = std::env::temp_dir().join(format!("ec-av1-{NAME}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).expect("scratch dir"); - let obu = dir.join("in.obu"); - std::fs::write(&obu, &data).expect("writing the stream"); - let raw = dir.join("aomdec.raw"); - let out = crate::tool_cache::cached_output_io(Command::new(aomdec_path()) - .args(["--codec=av1", "--rawvideo", "-o"]) - .arg(&raw) - .arg(&obu) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("aomdec failed to run"); - assert!( - out.status.success(), - "{NAME}: the oracle aomdec refused the stream: {}", - String::from_utf8_lossy(&out.stderr) - ); - let want = std::fs::read(&raw).expect("aomdec rawvideo output"); - let _ = std::fs::remove_dir_all(&dir); - let decoded = decode_stream(&data).expect("the pinned stream decodes"); - let ours = pack_rawvideo(&decoded, bit_depth, NAME); - assert_eq!( - ours.len(), - want.len(), - "{NAME}: the two sides differ in size" - ); - - // The per-frame plane table, built from each decoded picture's OWN - // plane lengths -- the same source `pack_rawvideo` lays the bytes out - // from, and never a formula. - let mut spans: Vec<[usize; 4]> = Vec::with_capacity(decoded.len()); - let mut capacity = [0usize; 3]; - let mut off = 0usize; - for f in &decoded { - let (y, u, v) = (f.y.len() * bpp, f.u.len() * bpp, f.v.len() * bpp); - spans.push([off, off + y, off + y + u, off + y + u + v]); - capacity[0] += y; - capacity[1] += u; - capacity[2] += v; - off += y + u + v; - } - assert_eq!(off, ours.len(), "{NAME}: the plane table covers the buffer"); - - // The truth, counted here with no help from the helper under test. - let mut truth = [0usize; 3]; - let mut truth_exact = 0usize; - for s in &spans { - let mut frame_exact = true; - for (p, a, b) in [(0usize, s[0], s[1]), (1, s[1], s[2]), (2, s[2], s[3])] { - let n = ours[a..b] - .iter() - .zip(&want[a..b]) - .filter(|(x, y)| x != y) - .count(); - truth[p] += n; - frame_exact &= n == 0; - } - truth_exact += usize::from(frame_exact); - } - - let (wy, wu, wv, frames, exact) = - count_rawvideo_diffs(&data, NAME, None).expect("the two sides must be byte-comparable"); - eprintln!( - "{NAME}: pinned {FILE} as wrongY={wy} wrongU={wu} wrongV={wv} over {frames} frames, \ - {exact} exact; this test's own count {truth:?} with {truth_exact} exact frames; \ - plane capacities {capacity:?}" - ); - assert_eq!(frames, decoded.len(), "{NAME}: frame count"); - assert_eq!( - [wy, wu, wv], - truth, - "{NAME}: the helper's per-plane split must equal an independent per-frame count" - ); - assert_eq!(exact, truth_exact, "{NAME}: frames_exact"); - for p in 0..3 { - assert!( - truth[p] <= capacity[p], - "{NAME}: plane {p} counts {} wrong bytes but holds only {}", - truth[p], - capacity[p] - ); - } - - // ---- arm 2: a byte inside a LATER frame's U plane. -------------- - // Frame 5's U plane's first byte. The old first-picture attribution - // has no frame-5 U at all: that byte is past every frame-0 threshold, - // so it landed in V. - let u5 = spans[5][1]; - let (fy, fu, fv, fframes, fexact) = count_rawvideo_diffs(&data, NAME, Some(u5)) - .expect("the two sides must be byte-comparable"); - let flipped = [fy, fu, fv]; - assert_eq!(fframes, frames, "{NAME}: frame count under the flip"); - assert_eq!( - flipped.iter().sum::(), - truth.iter().sum::() + 1, - "{NAME}: flipping one byte inside frame 5's U plane must add exactly one wrong \ - byte -- got {flipped:?} against this test's own count {truth:?}" - ); - assert_eq!( - flipped[1], - truth[1] + 1, - "{NAME}: byte {u5} is inside frame 5's U plane" - ); - assert_eq!(flipped[0], truth[0], "{NAME}: byte {u5} is not in luma"); - assert_eq!( - flipped[2], truth[2], - "{NAME}: byte {u5} must NOT be attributed to V -- the first-picture attribution \ - puts every byte past frame 0's luma in V" - ); - let want_exact = if truth_exact < frames { - truth_exact - } else { - frames - 1 - }; - assert_eq!( - fexact, want_exact, - "{NAME}: one flipped byte inside frame 5 leaves frames_exact at {want_exact}" - ); - } - - /// lane-av1cmpaudit2: the permanent CONTROL for the class - /// `comparator-that-never-reads-the-oracle`. - /// - /// The retracted predecessor lane's per-cell counter reported "0 wrong" - /// on 18/18 cells -- including cells that differ from `aomdec - /// --rawvideo` in 17658 samples -- because it packed OUR decoded samples - /// into a buffer and compared that buffer against the same samples. - /// `aomdec`'s output was written, length-checked, and never read. - /// Nothing about that mistake is visible from the outside: the helper's - /// signature, its panic text and its return type are all exactly what a - /// working comparator has, and no amount of reading the source of a - /// healthy-looking helper proves the next one is healthy. - /// - /// So the class is pinned here from the other direction. - /// `EC_AV1_AOMDEC` is already the crate's oracle override, so this test - /// points every oracle helper at a shim that runs the REAL `aomdec` and - /// then corrupts exactly ONE byte of whatever it wrote -- the - /// `--rawvideo` output and the `EC_AV1_FINAL_DUMP` frame 0 -- leaving - /// every other sample a genuine decode. On a pin that IS byte-exact - /// against the real oracle: - /// - /// 1. **arm 1, real oracle: every helper is GREEN.** Without this arm, - /// arm 2's red could just be a stream that was never exact. - /// 2. **arm 2, one-byte-wrong oracle: every helper is RED.** A helper - /// that stays green here is the retracted defect itself: it cannot - /// fail, so its green is worth nothing. - /// - /// One test, five helpers, and it goes red for the exact mistake that - /// was retracted. Measured over this file: the other 62 tests that - /// reach an oracle helper all take `lock_gate_counters()` before their - /// first oracle call, which is what makes the process-global - /// `EC_AV1_AOMDEC` safe to flip here. - #[test] - fn every_oracle_comparator_reds_on_a_one_byte_wrong_oracle() { - const NAME: &str = "every_oracle_comparator_reds_on_a_one_byte_wrong_oracle"; - let _gate_lock = lock_gate_counters(); - if !aomdec_available(NAME) { - return; - } - let pin = crate_pin("420_odd65x65_key.obu"); - let stream = std::fs::read(&pin).unwrap_or_else(|e| { - panic!( - "{NAME}: the control's pin {} is missing ({e}) -- restore the committed copy", - pin.display() - ) - }); - assert_eq!( - stream_bit_depth(&stream, NAME), - 8, - "{NAME}: the control's pin must be the 8-bit cell the shim corrupts" - ); - let plane_samples = { - let frames = decode_stream(&stream).expect("the control's pin must decode"); - let f = &frames[0]; - [f.y.len(), f.u.len(), f.v.len()] - }; - - // ---- arm 1: the real oracle, every comparator green ------------ - { - let obu = std::env::temp_dir().join(format!("{NAME}-arm1.obu")); - std::fs::write(&obu, &stream).expect("writing the pin for arm 1"); - assert_rawvideo_matches(&obu, &stream, "oracle-control-arm1-rawvideo", 1, 8); - let _ = std::fs::remove_file(&obu); - let (frames, hidden) = - decode_all_frames_vs_oracle(&stream, "oracle-control-arm1-alldumps"); - assert_eq!( - (frames, hidden), - (1, 0), - "{NAME}: arm 1 expects one decode-order frame and no hidden frames" - ); - let (wy, wu, wv, n, exact) = - count_rawvideo_diffs(&stream, "oracle-control-arm1-count", None) - .expect("arm 1: the two sides must be byte-comparable"); - assert_eq!( - (wy, wu, wv), - (0, 0, 0), - "{NAME}: arm 1 runs against the REAL oracle, so every plane must be zero" - ); - assert_eq!( - (n, exact), - (1, 1), - "{NAME}: arm 1 expects one shown frame that is byte-identical" - ); - let (differing, first) = key_frame_diffs(&stream, "oracle-control-arm1-kf"); - assert_eq!( - (differing, first), - (0, None), - "{NAME}: arm 1's key frame must be byte-identical to the oracle's" - ); - let [y, u, v] = - oracle_plane_diffs(&stream, "oracle-control-arm1-planes", plane_samples); - assert_eq!( - [y, u, v], - [0, 0, 0], - "{NAME}: arm 1 must be zero on every plane against the real oracle" - ); - } - - // ---- the one-byte-wrong oracle --------------------------------- - let dir = std::env::temp_dir().join(format!("ec-av1-{NAME}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).expect("scratch dir"); - let shim = dir.join("one-byte-wrong-aomdec.sh"); - // The real oracle's path rides in a sibling file rather than inside - // the script, so a path with a quote or a space cannot mangle it and - // the script body needs no `format!` escaping at all. - std::fs::write( - dir.join("real-aomdec"), - aomdec_path().as_os_str().as_encoded_bytes(), - ) - .expect("recording the real oracle's path for the shim"); - // Byte 7 of both the `--rawvideo` output and the `EC_AV1_FINAL_DUMP` - // frame 0 is inside the Y plane, and its value is rotated by 128 so - // the write always changes it. Nothing else is touched: the stream, - // the geometry, the frame count and every other sample are a genuine - // `aomdec` decode. - let script = r#"#!/bin/sh -REAL=$(cat "$(dirname "$0")/real-aomdec") -rawvideo=0 -out="" -prev="" -for a in "$@"; do - if [ "$a" = "--rawvideo" ]; then rawvideo=1; fi - if [ "$prev" = "-o" ]; then out="$a"; fi - prev="$a" -done -"$REAL" "$@" || exit $? -flip() { - [ -s "$1" ] || return 0 - b=$(od -An -tu1 -j 7 -N 1 "$1" 2>/dev/null | tr -d ' \n') - [ -n "$b" ] || return 0 - esc=$(printf '\\%03o' $(( (b + 128) % 256 ))) - printf "$esc" | dd of="$1" bs=1 seek=7 count=1 conv=notrunc 2>/dev/null - return 0 -} -[ "$rawvideo" = 1 ] && flip "$out" -[ -n "$EC_AV1_FINAL_DUMP" ] && flip "$EC_AV1_FINAL_DUMP.f0" -exit 0 -"#; - std::fs::write(&shim, script).expect("writing the oracle shim"); - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - std::fs::set_permissions(&shim, std::fs::Permissions::from_mode(0o755)) - .expect("the oracle shim must be executable"); - } - - // ---- arm 2: same pin, oracle off by ONE byte ------------------- - // The override is THREAD-LOCAL, so the tampered oracle is confined - // to this thread and no sibling test can see it; it is still cleared - // before any result is asserted, so a red arm cannot leave this - // test's own later work reading a wrong oracle. - let reds: [bool; 5]; - { - set_oracle_path(Some(shim.clone())); - let panicked = - |f: &dyn Fn()| std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).is_err(); - let rawvideo_red = panicked(&|| { - let obu = std::env::temp_dir().join(format!("{NAME}-arm2.obu")); - std::fs::write(&obu, &stream).expect("writing the pin for arm 2"); - assert_rawvideo_matches(&obu, &stream, "oracle-control-arm2-rawvideo", 1, 8); - }); - let _ = std::fs::remove_file(std::env::temp_dir().join(format!("{NAME}-arm2.obu"))); - let dumps_red = panicked(&|| { - decode_all_frames_vs_oracle(&stream, "oracle-control-arm2-alldumps"); - }); - let count_red = { - let counted = count_rawvideo_diffs(&stream, "oracle-control-arm2-count", None) - .unwrap_or_else(|| { - panic!( - "{NAME}: a single flipped oracle byte must NOT change the buffer \ - LENGTH -- returning None means the shim corrupted more than the \ - comparison" - ) - }); - counted.0 + counted.1 + counted.2 > 0 && counted.4 < counted.3 - }; - let kf_red = { - let (differing, first) = key_frame_diffs(&stream, "oracle-control-arm2-kf"); - differing > 0 && first.is_some() - }; - let planes_red = { - let [y, u, v] = - oracle_plane_diffs(&stream, "oracle-control-arm2-planes", plane_samples); - y + u + v > 0 - }; - set_oracle_path(None); - let _ = std::fs::remove_dir_all(&dir); - reds = [rawvideo_red, dumps_red, count_red, kf_red, planes_red]; - } - // One assert, naming EVERY comparator that stayed green: a partial - // run would report the first and hide whether the other four are - // covered. - let blind: Vec<&str> = [ - ("assert_rawvideo_matches", reds[0]), - ("decode_all_frames_vs_oracle", reds[1]), - ("count_rawvideo_diffs", reds[2]), - ("key_frame_diffs", reds[3]), - ("oracle_plane_diffs", reds[4]), - ] - .into_iter() - .filter(|(_, red)| !red) - .map(|(what, _)| what) - .collect(); - assert!( - blind.is_empty(), - "{NAME}: {} of 5 oracle comparators stayed GREEN against an oracle that is wrong \ - by exactly one byte -- {blind:?} -- they cannot fail, so their green proves \ - nothing (class `comparator-that-never-reads-the-oracle`)", - blind.len() - ); - eprintln!("{NAME}: all five oracle comparators red on a one-byte-wrong oracle"); - } - - /// lane-film10fix: the permanent CONTROL for the ffmpeg half of the class - /// `comparator-that-never-reads-the-oracle`. - /// - /// Its sibling above covers the five `aomdec` comparators. The `ffmpeg` - /// half had no such control, and it is the half the two 10-bit FILM gates - /// rest on: `a_10bit_128sb_film_frames_with_warp_cdef_and_interintra_...` - /// and `a_10bit_film_frames_with_small_side_globalmv_and_rect_warp_...` - /// both declare "pixel-exact" purely as - /// `assert_eq!(ours., ffmpeg_decode_sequence_10bit(...).)` - /// over 15 and 33 shown frames. If `ffmpeg_decode_sequence_10bit` ever - /// stopped reading ffmpeg's stdout -- packed our own samples into the - /// buffer it returns, say -- both gates would report exact on a decoder - /// that could be arbitrarily wrong, and nothing in the crate would go - /// red. Reading the helper's source proves it is live TODAY; only a - /// deliberately wrong reference proves it can FAIL. - /// - /// So this is the same two-arm shape, pointed at ffmpeg. The shim runs the - /// REAL ffmpeg and then rotates ONE byte of its rawvideo stdout per - /// offset in a sibling file, leaving the stream, the geometry, the frame - /// count and every other sample a genuine decode. On a pin that IS - /// byte-exact against real ffmpeg: - /// - /// 1. **arm 1, real ffmpeg: every helper is GREEN.** Without this arm, - /// arm 2's red could just be a stream that was never exact. - /// 2. **arm 2, one-sample-wrong ffmpeg, PER PLANE: every helper is RED - /// and the red names the plane that was tampered with.** Three arms, - /// one per plane, because a helper that only ever compared luma would - /// pass the Y arm and fail U and V -- and a 10-bit film gate that - /// reported "exact" while ignoring chroma entirely would be exactly - /// the class this controls. - /// - /// The three helpers are the whole reference surface in this module: - /// `ffmpeg_decode_sequence` (4:2:0 8-bit), `ffmpeg_decode_gray_sequence` - /// (monochrome, one plane) and `ffmpeg_decode_sequence_10bit` (the - /// `yuv420p10le` family both film gates use). Each is driven on a pin it - /// is known to be exact against: the 8-bit `420_odd65x65_key.obu` for the - /// first, the same stream for the third's shape arithmetic, and the - /// monochrome recipe the mono gate already builds for the second. The - /// override is thread-local, so a red arm cannot leave a tampered ffmpeg - /// behind for a sibling test on another thread. - #[test] - fn every_ffmpeg_comparator_reds_on_a_one_sample_wrong_ffmpeg() { - const NAME: &str = "every_ffmpeg_comparator_reds_on_a_one_sample_wrong_ffmpeg"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - // Same mutex the oracle control takes: this test's shim is - // thread-local, but the SCREAM it produces must not interleave with a - // sibling's decode in the captured log. - let _gate_lock = lock_gate_counters(); - - // The 4:2:0 8-bit arm. It BUILDS its stream with the same - // `libaom-av1` lavfi recipe the mono gate below uses rather than - // pinning one: `ffmpeg_decode_sequence` derives its frame size as - // `w*h + 2*(w*h/4)`, which is only right for EVEN dimensions -- on a - // 65x65 stream 4:2:0 chroma is ceil(65/2)^2 = 1089, not 4225/4 = - // 1056, and the helper's length assert fires (loudly, by design -- - // see `frame_count_diagnosis`). 320x240 keeps the offsets below - // exact: luma 76800 samples, chroma 160x120 = 19200 each. - let (w, h) = (320usize, 240usize); - let (ys, cs) = (w * h, (w / 2) * (h / 2)); - assert_eq!( - (ys, cs), - (76800, 19200), - "{NAME}: the byte offsets in this test are computed from this geometry" - ); - let build_8bit = { - let out = crate::tool_cache::cached_output_io(Command::new(ffmpeg_path()) - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - "testsrc2=size=320x240:rate=30:duration=1", - "-pix_fmt", - "yuv420p", - "-c:v", - "libaom-av1", - "-cpu-used", - "8", - "-b:v", - "300k", - "-f", - "obu", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to build the 4:2:0 8-bit arm"); - assert!( - out.status.success(), - "{NAME}: ffmpeg could not build the 8-bit arm: {}", - String::from_utf8_lossy(&out.stderr) - ); - out.stdout - }; - assert_eq!( - stream_bit_depth(&build_8bit, NAME), - 8, - "{NAME}: this arm is the 8-bit cell the byte offsets below are computed for" - ); - let our_8bit = - decode_stream(&build_8bit).expect("the 8-bit arm must decode -- arm 1 needs it exact"); - assert!( - !our_8bit.is_empty(), - "{NAME}: the 8-bit arm decoded nothing" - ); - let frames_8bit = our_8bit.len(); - - // The monochrome recipe, byte-identical to the one - // `a_real_libaom_monochrome_key_frame_decodes_pixel_exact` builds, so - // the gray helper is driven on a stream that gate already proves - // exact. A MONOCHROME stream is also this test's 4:2:0 4:2:0-free - // arm: `ffmpeg_decode_gray_sequence` returns a flat luma buffer, so - // the one flipped offset must be attributed to Y and to nothing else. - let gray_stream = { - let out = crate::tool_cache::cached_output_io(Command::new(ffmpeg_path()) - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - "testsrc2=size=64x64:rate=30:duration=1", - "-pix_fmt", - "gray", - "-c:v", - "libaom-av1", - "-cpu-used", - "8", - "-b:v", - "100k", - "-f", - "obu", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to build the monochrome arm"); - assert!( - out.status.success(), - "{NAME}: ffmpeg could not build the monochrome arm: {}", - String::from_utf8_lossy(&out.stderr) - ); - out.stdout - }; - let our_gray = decode_stream(&gray_stream).expect("the monochrome arm must decode"); - assert!( - !our_gray.is_empty(), - "{NAME}: the monochrome arm decoded nothing" - ); - let frames_gray = our_gray.len(); - - // ---- the one-sample-wrong ffmpeg shim --------------------------- - let dir = std::env::temp_dir().join(format!("ec-av1-{NAME}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).expect("scratch dir"); - // The real ffmpeg's path rides in a sibling file rather than inside - // the script, so a path with a space or a quote cannot mangle it and - // the script body needs no `format!` escaping. - let real = if let Some(p) = std::env::var_os("EC_AV1_FFMPEG") { - std::path::PathBuf::from(p) - } else { - let found = Command::new("ffmpeg") - .arg("-version") - .stdout(Stdio::null()) - .stderr(Stdio::null()) - .status() - .is_ok_and(|s| s.success()); - assert!(found, "{NAME}: no working ffmpeg on PATH to wrap"); - // Resolve the bare name through PATH so the shim does not depend - // on inheriting whatever PATH the test runner had. - let path = std::env::var_os("PATH").unwrap_or_default(); - std::env::split_paths(&path) - .map(|d| d.join("ffmpeg")) - .find(|p| p.is_file()) - .expect("{NAME}: ffmpeg is on PATH but not resolvable to a file") - }; - std::fs::write(dir.join("real-ffmpeg"), real.as_os_str().as_encoded_bytes()) - .expect("recording the real ffmpeg's path for the shim"); - // Each line of `offsets` is one byte of the rawvideo stdout to rotate - // by 128, so the write always changes it. Everything else -- the - // stream, the geometry, the frame count, every other sample -- is a - // genuine ffmpeg decode. stdin is inherited so the shim is a drop-in - // for the helpers' `run_with_stdin` call. - let script = r#"#!/bin/sh -REAL=$(cat "$(dirname "$0")/real-ffmpeg") -OUT=$(mktemp) -"$REAL" "$@" > "$OUT" || exit $? -while read -r o; do - [ -n "$o" ] || continue - b=$(od -An -tu1 -j "$o" -N 1 "$OUT" 2>/dev/null | tr -d ' \n') - [ -n "$b" ] || continue - esc=$(printf '\\%03o' $(( (b + 128) % 256 ))) - printf "$esc" | dd of="$OUT" bs=1 seek="$o" count=1 conv=notrunc 2>/dev/null -done < "$(dirname "$0")/offsets" -cat "$OUT" -rm -f "$OUT" -exit 0 -"#; - let shim = dir.join("one-sample-wrong-ffmpeg.sh"); - std::fs::write(&shim, script).expect("writing the ffmpeg shim"); - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - std::fs::set_permissions(&shim, std::fs::Permissions::from_mode(0o755)) - .expect("the ffmpeg shim must be executable"); - } - let set_offsets = |bytes: &[usize]| { - let body: String = bytes - .iter() - .map(|b| format!("{b}\n")) - .collect::>() - .concat(); - std::fs::write(dir.join("offsets"), body).expect("writing the offsets file"); - }; - // A comparator that cannot report a difference is worse than none, so - // each arm is scored as a COUNT of differing samples, not as a panic. - let count8 = |theirs: &[Pic]| -> [usize; 3] { - let mut wrong = [0usize; 3]; - for (plane, (x, y)) in [ - (0usize, (&our_8bit[0].y, &theirs[0].y)), - (1, (&our_8bit[0].u, &theirs[0].u)), - (2, (&our_8bit[0].v, &theirs[0].v)), - ] { - wrong[plane] = x.iter().zip(y).filter(|(a, b)| a != b).count(); - } - wrong - }; - - // The 10-bit FILM pin, and the comparator both charter-named film - // gates rest on. Driven on the real stream rather than a synthetic - // one: `ffmpeg_decode_sequence_10bit` is the only reference helper - // with a per-plane split, so it is the one that could silently lose a - // plane. 1920x792 at 10 bits: luma 1920*792*2 bytes per frame, chroma - // 960*396*2. - let film = std::fs::read(crate_pin("reelc_sb128_inter_witness.obu")).unwrap_or_else(|e| { - panic!( - "{NAME}: the 10-bit film pin reelc_sb128_inter_witness.obu is missing ({e}) -- \ - restore the committed copy" - ) - }); - assert_eq!( - stream_bit_depth(&film, NAME), - 10, - "{NAME}: this arm is the 10-bit cell the byte offsets below are computed for" - ); - let our_10bit = - decode_stream(&film).expect("the 10-bit film pin must decode -- arm 1 needs it exact"); - let (fw, fh) = (1920usize, 792usize); - let film_frames = our_10bit.len(); - let (fys, fcs) = (fw * fh * 2, (fw / 2) * (fh / 2) * 2); - let count10 = |theirs: &[Pic]| -> [usize; 3] { - let mut wrong = [0usize; 3]; - for (a, b) in our_10bit.iter().zip(theirs) { - for (plane, (x, y)) in - [(0usize, (&a.y, &b.y)), (1, (&a.u, &b.u)), (2, (&a.v, &b.v))] - { - wrong[plane] += x.iter().zip(y).filter(|(p, q)| p != q).count(); - } - } - wrong - }; - let count_gray = |theirs: &[u8]| -> usize { - our_gray[0] - .y - .iter() - .zip(theirs) - .filter(|(a, b)| **a != u16::from(**b)) - .count() - }; - - // ---- arm 1: the real ffmpeg, every comparator GREEN ------------ - { - set_offsets(&[]); - set_ffmpeg_path(None); - let theirs = ffmpeg_decode_sequence(&build_8bit, w, h, frames_8bit); - assert_eq!( - count8(&theirs), - [0, 0, 0], - "{NAME}: arm 1 runs against the REAL ffmpeg, so every plane must be zero -- if \ - this is red the stream is not the byte-exact pin this control needs" - ); - let their_gray = ffmpeg_decode_gray_sequence(&gray_stream, 64, 64, frames_gray); - assert_eq!( - count_gray(&their_gray), - 0, - "{NAME}: arm 1's monochrome plane must be zero against the real ffmpeg" - ); - // arm 1's 10-bit half: the film pin is byte-exact against real - // ffmpeg on every plane of every shown frame -- that is exactly - // what `a_10bit_128sb_film_frames_with_warp_cdef_and_interintra_...` - // asserts -- so this is the cell the two charter-named film gates - // claim. - let their_10bit = ffmpeg_decode_sequence_10bit(&film, fw, fh, film_frames); - assert_eq!( - count10(&their_10bit), - [0, 0, 0], - "{NAME}: arm 1's 10-bit film pin must be zero on every plane against the real \ - ffmpeg -- if this is red the control's pin is not the byte-exact stream it needs" - ); - } - - // ---- arm 2: one sample wrong, PER PLANE ------------------------- - // The shim is thread-local, so the tampered reference is confined to - // this thread; it is cleared before anything is asserted, so a red arm - // cannot leave this test's own later work reading a wrong ffmpeg. - let mut blind: Vec = Vec::new(); - { - set_ffmpeg_path(Some(shim.clone())); - for (plane, (_name, base)) in [("Y", 0usize), ("U", ys), ("V", ys + cs)] - .into_iter() - .enumerate() - { - // Byte 1000 of the named plane: inside the 4:2:0 8-bit pin's - // luma (4225), inside its chroma (1024), or past both. - set_offsets(&[base + 1000]); - let theirs = ffmpeg_decode_sequence(&build_8bit, w, h, frames_8bit); - let got = count8(&theirs); - let want = [0usize, 0, 0]; - let mut expected = want; - expected[plane] = 1; - if got != expected { - blind.push(format!( - "ffmpeg_decode_sequence {plane} arm: counted {got:?}, expected \ - {expected:?} (exactly the one tampered sample)" - )); - } - } - // The 10-bit helper, per plane, on the 10-bit FILM pin. This is the - // arm that matters for the charter: both - // `a_10bit_128sb_film_frames_with_warp_cdef_and_interintra_...` - // and - // `a_10bit_film_frames_with_small_side_globalmv_and_rect_warp_...` - // declare "pixel-exact on every plane" using nothing but this - // helper's output. A helper that dropped U or V would leave both - // gates green while chroma went unchecked for 15 and 33 frames. - for (plane, (_name, base)) in [("Y", 0usize), ("U", fys), ("V", fys + fcs)] - .into_iter() - .enumerate() - { - // Sample 1000 of the named plane, two bytes per sample. - set_offsets(&[base + 2000]); - let theirs = ffmpeg_decode_sequence_10bit(&film, fw, fh, film_frames); - let got = count10(&theirs); - let mut expected = [0usize, 0, 0]; - expected[plane] = 1; - if got != expected { - blind.push(format!( - "ffmpeg_decode_sequence_10bit {plane} arm: counted {got:?}, expected \ - {expected:?} (exactly the one tampered sample)" - )); - } - } - // The monochrome helper: one plane, so the single flipped offset - // must show up as luma and nothing else can absorb it. - set_offsets(&[1000]); - let their_gray = ffmpeg_decode_gray_sequence(&gray_stream, 64, 64, frames_gray); - if count_gray(&their_gray) != 1 { - blind.push(format!( - "ffmpeg_decode_gray_sequence arm: counted {} differing luma samples, expected \ - exactly 1", - count_gray(&their_gray) - )); - } - set_ffmpeg_path(None); - } - let _ = std::fs::remove_dir_all(&dir); - // One assert, naming EVERY helper that failed to notice: a partial run - // would report the first and hide whether the others are covered. - assert!( - blind.is_empty(), - "{NAME}: {} of 7 ffmpeg comparator arms stayed GREEN against an ffmpeg that is wrong \ - by exactly one sample -- {blind:#?} -- they cannot fail, so their green proves \ - nothing (class `comparator-that-never-reads-the-oracle`)", - blind.len() - ); - eprintln!( - "{NAME}: ffmpeg_decode_sequence red on a one-sample-wrong Y, U and V separately; \ - ffmpeg_decode_gray_sequence red on one wrong luma sample; \ - ffmpeg_decode_sequence_10bit red on a one-sample-wrong Y, U and V of the 10-bit \ - film pin" - ); - } - - /// lane-av1422chrtx: the odd-frame-HEIGHT 4:2:0 witness, pinned and now - /// EXACT (lane-av1422anom had pinned it as a ratchet on its own defect). - /// - /// This is NOT a 4:2:2 cell and needs no bypass -- it is ordinary 4:2:0, - /// reachable by any user. lane-av1422anom pinned it as a RATCHET asserting - /// its own measured defect `(0, 200, 17658)`, and said whoever fixed it - /// must flip that to exactness. That is done, and the flip is the - /// deliverable: - /// - /// the defect was a chroma `tx_type`, not a geometry. libaom's - /// `av1_get_ext_tx_set_type` (`blockd.h`) resolves a **32-point** chroma - /// unit to `EXT_TX_SET_DCT_IDTX` when the block `is_inter` -- so an - /// Intra-Block-Copy block whose luma coded `IDTX` runs the identity - /// transform on its chroma. `read_plane`'s `side >= 32` clamp forced - /// `DCT_DCT` there (its `DCT_DCT` cap is really libaom's - /// `txsize_sqr_up_map[tx_size] > TX_32X32`, i.e. 64 and up), so the - /// residual was a 32-point IDCT where libaom's was a plain copy of the - /// dequantized coefficients `>>2`. The wrong samples sat in one 64x64 - /// IBC block's 32x32 chroma unit at chroma (128,96) on frame 0, and - /// propagated from there through the inter frames. - /// - /// `the_counting_oracle_diff_detects_one_flipped_oracle_byte` is the - /// non-vacuity control that keeps the `0` above worth anything. - #[test] - fn the_pinned_420_oddheight_witness_is_pinned_and_decodes_byte_exact() { - const NAME: &str = "the_pinned_420_oddheight_witness_is_pinned_and_decodes_byte_exact"; - // lane-av1cmpaudit2: same mutex as every other oracle gate. - let _gate_lock = lock_gate_counters(); - const FILE: &str = "420_oddheight_320x232.obu"; - const BYTES: usize = 15773; - // sha256 6832c3cd867f5fc491b45fd67f77c38453db0ca6d461e7d225e6276f4d0784c8, - // recorded in `lanes/av1422anom.report.md`. The tree pins fixture - // identity by fnv1a64, asserted below. A `const SHA256` compared - // against itself would be a tautology -- the exact bug this lane - // exists to kill -- so it is not written. - const FNV1A64: u64 = 0x37877f15307c3b; - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("fixtures") - .join(FILE); - let data = std::fs::read(&path) - .unwrap_or_else(|e| panic!("{NAME}: pinned witness {FILE} is missing ({e})")); - assert_eq!(data.len(), BYTES, "{NAME}: {FILE} size drifted"); - assert_eq!(fnv1a64(&data), FNV1A64, "{NAME}: {FILE} bytes drifted"); - let (wy, wu, wv, frames, exact) = - count_rawvideo_diffs(&data, NAME, None).expect("the two sides must be byte-comparable"); - assert_eq!( - (wy, wu, wv), - (0, 0, 0), - "{NAME}: the pinned 320x232 witness must decode byte-exactly against \ - `aomdec --rawvideo` on every plane. It was a RATCHET asserting its own \ - measured defect (0, 200, 17658); lane-av1422chrtx flipped it to exactness \ - when the 32-point INTER chroma `tx_type` (EXT_TX_SET_DCT_IDTX, not \ - EXT_TX_SET_DCTONLY) was fixed. Any non-zero value here is a regression -- \ - name it in the report." - ); - assert_eq!(frames, 16, "{NAME}: shown frame count"); - assert_eq!( - exact, frames, - "{NAME}: every shown frame must be byte-exact" - ); - } - - /// lane-av1oddheightfork3: the 320x236 cell this lane CLOSED, as a - /// permanent BYTE-EXACTNESS gate against the live oracle -- not a route - /// counter, not a source scan. It compares our decoded samples with - /// `aomdec --rawvideo`'s own bytes plane by plane, and asserts every - /// frame is byte-exact. - /// - /// **The defect it pins.** Before the fix this cell measured - /// `Y 234349 / U 56957 / V 52981, 0 of 16 frames exact` -- reproduced on - /// this lane's own tree by reverting the fix, matching - /// `lanes/av1oddluma.report.md` and `lanes/av1cmpframe.report.md` digit - /// for digit. The first divergent read is the `txfm_partition` symbol of - /// the INTRABC 8x16 block at mi(44,60): our `TXFM_CONTEXT` grid held the - /// BLOCK's own `16` in `left_txfm[44]` where libaom holds the split - /// leaf's `8` (the operand pair is printed by the oracle rung - /// `EC_VARTXCTX`, `scripts/instrument-aom-oracle.sh`), so `ctx` was 12 - /// against libaom's 13 and `is_split` 0 against 1. - /// - /// **Non-vacuity.** `the_counting_oracle_diff_detects_one_flipped_oracle_byte` - /// is the comparator control and does not depend on any witness - /// diverging; the mutation proof that this gate BITES the defect it - /// names is in `lanes/av1oddheightfork3.report.md` (revert the - /// `fill_lf_grid_rect_after_vartx` call sites -> this test reds BY NAME - /// with the numbers above). - #[test] - fn the_pinned_420_oddheight_320x236_witness_decodes_byte_exact() { - const NAME: &str = "the_pinned_420_oddheight_320x236_witness_decodes_byte_exact"; - let _gate_lock = lock_gate_counters(); - const FILE: &str = "420_oddheight_320x236.obu"; - const BYTES: usize = 16562; - // sha256 84e4d1ab56620af1c5b78e1aa3d2d67496a492f2e127198c82dd1d68b01c6200. - // Identity is pinned by fnv1a64 (the same value - // `the_counting_oracle_diff_attributes_planes_per_frame` asserts) -- - // a `const SHA256` compared against itself would be the tautology - // this lane exists to kill. - const FNV1A64: u64 = 521889434652397870; - let data = crate_pin("420_oddheight_320x236.obu"); - let data = std::fs::read(&data) - .unwrap_or_else(|e| panic!("{NAME}: the committed pin {FILE} is missing ({e})")); - assert_eq!(data.len(), BYTES, "{NAME}: {FILE} size drifted"); - assert_eq!(fnv1a64(&data), FNV1A64, "{NAME}: {FILE} bytes drifted"); - let (wy, wu, wv, frames, exact) = - count_rawvideo_diffs(&data, NAME, None).expect("the two sides must be byte-comparable"); - assert_eq!( - (wy, wu, wv), - (0, 0, 0), - "{NAME}: the pinned 320x236 cell must decode byte-exactly against \ - `aomdec --rawvideo` on every plane. It measured \ - (234349, 56957, 52981) with 0 of 16 frames exact until \ - lane-av1oddheightfork3 fixed the TXFM_CONTEXT whole-block \ - publish that overwrote a var-tx tree's per-leaf sizes. Any \ - non-zero value here is a regression -- name it in the report." - ); - assert_eq!(frames, 16, "{NAME}: shown frame count"); - assert_eq!( - exact, frames, - "{NAME}: every shown frame must be byte-exact" - ); - } - - /// The repo's first hidden-frame pixel gate. Every other aomenc gate - /// here compares `decode_stream`'s output against `ffmpeg -f obu`, and - /// both sides emit SHOWN frames only -- so an alt-ref frame that is - /// decoded, stored into a reference slot and never displayed was, until - /// this gate, never compared to anything (class - /// gate-blind-to-hidden-frames). His films are aomenc-encoded with the - /// default `--lag-in-frames`, so they are full of exactly these frames. - /// - /// `--auto-alt-ref=1 --lag-in-frames=25` on moving content makes aomenc - /// build alt-refs; `--arnr-maxframes=0` is load-bearing -- with libaom's - /// temporal filter on, this fixture's alt-ref candidates get filtered - /// away and the encoder emits ZERO hidden frames (measured: 0 hidden - /// with the filter on, 3 with it off), which would have made the gate - /// vacuous. The `hidden >= 2` assertion is hard, on both bit depths, so - /// a recipe that stops producing hidden frames fails rather than skips. - #[test] - fn a_real_aomenc_altref_sequence_hidden_frames_decode_pixel_exact() { - const NAME: &str = "a_real_aomenc_altref_sequence_hidden_frames_decode_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - for bit_depth in [8u32, 10u32] { - let (width, height, frames) = (64usize, 64usize, 40usize); - let duration = frames as f64 / 25.0; - let source = format!("testsrc2=size={width}x{height}:duration={duration}:rate=25"); - let pix_fmt = if bit_depth == 10 { - "yuv420p10le" - } else { - "yuv420p" - }; - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-t", - &duration.to_string(), - "-pix_fmt", - pix_fmt, - "-strict", - "-1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let depth_arg = format!("--bit-depth={bit_depth}"); - let input_depth_arg = format!("--input-bit-depth={bit_depth}"); - let out = run_with_stdin( - Command::new(aomenc_path()).args([ - // lane-defon r1: the repo's only gate that decodes hidden - // frames is also the only place a FORWARD KEYFRAME can be - // proven -- a KEY frame with `show_frame == 0`, which is - // exactly the shape this gate already compares in decode - // order. On-values go before the base list (aomenc keeps - // the FIRST occurrence of a repeated flag). - "--enable-fwd-kf=1", - "--fwd-kf-dist=8", - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=45", - "--cpu-used=0", - "--threads=1", - "--row-mt=0", - "--kf-max-dist=1000", - "--enable-order-hint=1", - "--auto-alt-ref=1", - "--lag-in-frames=25", - "--arnr-maxframes=0", - &depth_arg, - &input_depth_arg, - // The same tool set every sibling inter gate pins -- the - // open capability gaps (rect/AB partitions, warped/OBMC, - // masked compound, palette, ...) are other lanes' work; - // this gate is about hidden frames, not about them. - "--enable-warped-motion=0", - // OBMC stays off HERE (this gate is about hidden frames); - // the tool's own coverage is the `obmc*` gates and, on a - // 16x8/8x16 leaf, the `--enable-obmc=1` arm of - // `..._with_a_16_level_rect_leaf_...` (lane-inter4 r4). - "--enable-obmc=0", - "--enable-masked-comp=0", - "--enable-interintra-comp=0", - "--enable-onesided-comp=0", - "--enable-interintra-wedge=0", - "--enable-smooth-interintra=0", - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-tx-size-search=0", - "--enable-cdef=0", - "--enable-restoration=0", - "--max-partition-size=32", - "--min-partition-size=32", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - "--enable-ref-frame-mvs=0", - "--obu", - "-o", - "-", - "-", - ]), - &y4m.stdout, - ); - assert!( - out.status.success(), - "{NAME}: aomenc refused the {bit_depth}-bit fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let fwd_kf_before = crate::decode::fwd_kf_hits(); - let (total, hidden) = - decode_all_frames_vs_oracle(&stream, &format!("altref-hidden-{bit_depth}bit")); - let fwd_kf = crate::decode::fwd_kf_hits() - fwd_kf_before; - assert!( - hidden >= 2, - "{NAME}: the {bit_depth}-bit recipe produced only {hidden} hidden frame(s) of \ - {total} decoded -- the gate would be vacuous (class \ - gate-blind-to-hidden-frames)" - ); - // lane-defon r1: `--enable-fwd-kf=1` is spelled on this recipe, so - // a KEY frame with `show_frame == 0` must actually have been - // decoded -- otherwise the on-value proves nothing. - assert!( - fwd_kf > 0, - "{NAME}: the {bit_depth}-bit recipe decoded {total} frames ({hidden} hidden) but \ - zero forward keyframes -- --enable-fwd-kf=1 --fwd-kf-dist=8 never reached the \ - bitstream" - ); - eprintln!( - "{NAME} {bit_depth}-bit: {total} frames decoded, {hidden} hidden, {fwd_kf} \ - forward keyframes, all pixel-exact vs the oracle in decode order" - ); - } - } - - /// A real `aomenc` filter-intra fixture: every other intra mode disabled - /// (smooth/paeth/directional/angle-delta) and - /// `--max-partition-size=32` (past which `av1_filter_intra_allowed_bsize`'s - /// <=32x32 bound means `use_filter_intra` never reads at all, spec - /// 5.11.14), so the only way this frame codes is `DC_PRED` with filter - /// intra on top -- `--loopfilter-control=0` is required too: this - /// decoder has no in-loop deblocking filter at all, and libaom's default - /// (on) smooths every block-boundary column, which first looked like a - /// filter-intra math bug (mismatches straddling the 32-pixel block - /// seam) until the recipe without it round-tripped byte-exact. - /// - /// lane-av1skipfix: the attempt-loop shape this gate's single recipe - /// lacked. It sweeps (seed, cq) and REQUIRES at least one attempt to both - /// decode and read `use_filter_intra`: a decode error on EVERY attempt is - /// a hard failure carrying the refusal texts, not a printed SKIP, and an - /// attempt that decodes without the symbol firing is still pixel-compared - /// (class `gate-skips-on-its-own-failure`). MEASURED 2026-09-29 on - /// `a21f3680`: seed 42 cq 40 and seed 43 cq 40 read the symbol 3x each, - /// pixel-exact, while seed 44 cq 45 and seed 45 cq 30 decode WITHOUT it -- - /// so the one fixed recipe really did carry the whole gate. - /// - /// The per-attempt decode error the old single recipe SKIPped on is - /// `screen_content_tools_determination` (libaom `encoder_utils.c`): a real - /// internal trial-encode/PSNR comparison, not a flag this CLI exposes a - /// knob for -- on this flat gradient fixture it lands on - /// `allow_screen_content_tools=0` most runs but occasionally trips over - /// its 0.9 dB threshold the other way even with palette/intrabc both - /// disabled. That is a genuine separate gap (`decode_stream` never reads - /// `intrabc`/`palette_mode_info`), so it is a NAMED REFUSAL counted per - /// attempt, never a silent skip and never a pass. - #[test] - fn a_real_aomenc_filter_intra_stream_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_filter_intra_stream_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height) = (64usize, 64usize); - // Recipe-search hooks: with the encoder pinned to one thread the stream - // is a deterministic function of (seed, cq), so a firing recipe can be - // searched for without a rebuild. These pin attempt 0 for a bisect; the - // sweep walks the same axes regardless. - let fi_seed: u32 = std::env::var("EC_FI_SEED") - .ok() - .and_then(|v| v.parse().ok()) - .unwrap_or(42); - let fi_cq: u32 = std::env::var("EC_FI_CQ") - .ok() - .and_then(|v| v.parse().ok()) - .unwrap_or(40); - // Two seeds x three quantisers, so "every attempt refused" and "no - // attempt ever read `use_filter_intra`" are distinguishable failures - // rather than one unlucky recipe. - const CQS: [u32; 3] = [40, 35, 30]; - let mut refusals = Vec::new(); - let mut counted_exact = 0u32; - let mut uncounted_exact = 0u32; - 'attempts: for round in 0..2u32 { - for (i, &walked) in CQS.iter().enumerate() { - let seed = fi_seed + round; - let cq = if round == 0 && i == 0 { fi_cq } else { walked }; - let source = gradients_source(seed, width, height, "duration=0.04:rate=25"); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-pix_fmt", - "yuv420p", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg refused to generate the y4m fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let cq_arg = format!("--cq-level={cq}"); - let out = run_with_stdin( - Command::new(aomenc_path()).args([ - "--codec=av1", - "--passes=1", - "--end-usage=q", - &cq_arg, - "--cpu-used=0", - // Every sibling gate pins these; this one did not, and a - // multi-threaded aomenc is not deterministic, so each run - // encoded a slightly different stream and the gate flaked - // against whichever features that run happened to pick. - // Pinning them makes seed 42 mean one stream (class - // `parallel-flake-is-attempt-selection`). - "--threads=1", - "--row-mt=0", - "--enable-filter-intra=1", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-tx-size-search=0", - "--enable-cdef=0", - "--max-partition-size=32", - "--loopfilter-control=0", - "--enable-palette=0", - "--enable-intrabc=0", - "--obu", - "-o", - "-", - "-", - ]), - &y4m.stdout, - ); - assert!( - out.status.success(), - "{NAME}: aomenc refused the seed {seed} cq {cq} fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let before = decode::filter_intra_hits(); - let frames = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => { - refusals.push(format!("seed {seed} cq {cq}: {e}")); - continue; - } - }; - // A decode that succeeded is ALWAYS pixel-compared; the hit - // counter only decides whether the attempt counts as firing - // (class `counter-from-refused-stream`). - let counted = decode::filter_intra_hits() != before; - if counted { - counted_exact += 1; - } else { - uncounted_exact += 1; - } - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1); - assert_eq!( - frames[0].y, ffmpeg_frames[0].y, - "luma vs ffmpeg (seed {seed} cq {cq}, use_filter_intra fired: {counted})" - ); - assert_eq!( - frames[0].u, ffmpeg_frames[0].u, - "U vs ffmpeg (seed {seed} cq {cq}, use_filter_intra fired: {counted})" - ); - assert_eq!( - frames[0].v, ffmpeg_frames[0].v, - "V vs ffmpeg (seed {seed} cq {cq}, use_filter_intra fired: {counted})" - ); - if counted_exact >= 2 { - break 'attempts; - } - } - } - gate_buckets(NAME, counted_exact, uncounted_exact, refusals.len()); - assert!( - counted_exact > 0, - "{NAME}: none of {} attempts decoded a stream that read use_filter_intra -- the \ - gate would prove nothing (class gate-blind-to-feature):\n{}", - CQS.len() * 2, - refusals.join("\n") - ); - } - - /// A real `aomenc` palette-Y fixture (lane-palette r3): `smptebars` - /// (SMPTE colour bars -- a handful of large flat luma regions, exactly - /// the "flat, few-colour, repetitive" content `av1_choose_palette_map`'s - /// RD trial rewards) with `hue=s=0` to flatten chroma to one constant - /// value, so `DC_PRED` already nails every chroma block with zero - /// residual and the encoder's own RD never has a reason to spend bits on - /// a *UV* palette too (a real symbol this decoder still refuses -- - /// lane-palette r3's own scope is Y only). `smptebars` has no seed to - /// vary, so the fixture is deterministic by construction; hashed twice - /// below to prove it rather than assert it. `--enable-rect-partitions=0` - /// / `-ab-` / `-1to4-` keep every intra block square, sidestepping the - /// rect-strip screen-content refusal at `read_intra_mode_rect` - /// (decode.rs ~2226) -- that refusal is this lane's own next milestone, - /// not this gate's. `--sb-size=64` and `--threads=1 --row-mt=0` are the - /// sibling-lane facts this charter paid for: a single 64x64 frame is one - /// superblock either way, but pinning them keeps the recipe identical to - /// every other gate in this file. HARD-asserts - /// [`decode::palette_hits`] moved -- a stream that never reads a real - /// palette block would refuse (or not) by construction without proving - /// this milestone at all. - /// - /// lane-palette r4/r6/r7: r3/r4 found that this fixture's reconstructed - /// pixels did not match ffmpeg's decode of the same bytes even though - /// every symbol read by `decode_color_index_map` checked line-for-line - /// against the oracle and matched. r6's range trace (`compare-range-not-tell`) - /// pinned the real cause: `decode_color_index_map` was called from the - /// wrong syntax position -- inline right after the Y colours, instead of - /// after the whole mode-info read (UV palette mode_info + `filter_intra`, - /// `av1_visit_palette`'s real call order). r7 ported the UV palette - /// mode_info read and moved the colour-index-map decode after - /// `filter_intra`; this gate now asserts a real pixel match instead of - /// the old named refusal. - #[test] - fn a_real_aomenc_stream_with_palette_y_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_stream_with_palette_y_decodes_pixel_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let source = "smptebars=size=64x64:rate=25"; - fn render(source: &str) -> Vec { - crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - source, - "-vf", - "hue=s=0", - "-pix_fmt", - "yuv420p", - "-t", - "0.04", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run") - .stdout - } - let y4m_a = render(source); - let y4m_b = render(source); - assert_eq!( - y4m_a, y4m_b, - "smptebars must render byte-identical across two runs" - ); - let y4m = y4m_a; - let out = run_with_stdin( - Command::new(aomenc_path()).args([ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=30", - "--cpu-used=0", - "--threads=1", - "--row-mt=0", - "--sb-size=64", - "--tune-content=screen", - "--enable-palette=1", - "--enable-intrabc=0", - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--min-partition-size=32", - "--max-partition-size=32", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-cfl-intra=0", - "--enable-cdef=0", - "--enable-restoration=0", - "--enable-tx-size-search=0", - "--loopfilter-control=0", - "--obu", - "-o", - "-", - "-", - ]), - &y4m, - ); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let before = decode::palette_hits(); - let frames = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => panic!("{NAME}: decode_stream refused: {e}"), - }; - assert!( - decode::palette_hits() > before, - "palette_y_mode never fired decoding this stream -- gate is vacuous" - ); - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 64, 64, 1); - assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg"); - assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg"); - assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg"); - } - - /// lane-kf900 r3: the palette colour reader at BOTH bit depths. - /// - /// `read_palette_colors_y`/`_uv` (decode.rs, mirroring `decodemv.c:478` - /// and `:509`) size every raw literal they read by the sequence's - /// `bit_depth`: the first colour is `bit_depth` bits, `min_bits` is - /// `bit_depth - 3` (Y/U) or `bit_depth - 4` (V), `range` starts at - /// `1 << bit_depth`, and the clamp/wrap bound is `(1 << bit_depth) - 1`. - /// Ours hardcoded 8, so every 10-bit palette block read TWO BITS TOO FEW - /// per transmitted colour and silently decoded the rest of the tile from - /// the wrong bit position. - /// - /// It was silent because raw literals are EQUIPROBABLE: at the ranges - /// this content reaches an equiprobable read maps the msac range onto - /// itself (62728 -> 31364 -> renormalised 62728), so a cross-decoder - /// RANGE ladder stays bit-identical straight through the miscount and - /// only the decoded VALUE moves. Pinned on a 256x192 10-bit - /// `--cq-level=59` stream whose first block is a 32x16 palette: aomdec's - /// `EC_PAL` ladder and ours agreed on every range and disagreed on the - /// very first colour index (0 vs 1); after the fix all 1024 `EC_PAL` - /// lines of that block match aomdec line for line. - /// - /// The recipe is the 8-bit `..._with_palette_y_...` gate's, with the - /// depth as the only variable, so a failure here is the depth and - /// nothing else. HARD-asserts [`decode::palette_hits`] moved on each arm - /// (a stream with no real palette block would prove nothing) and - /// compares all three planes against ffmpeg's decode of the same bytes. - #[test] - fn a_real_aomenc_palette_stream_decodes_pixel_exact_at_8_and_10_bit() { - const NAME: &str = "a_real_aomenc_palette_stream_decodes_pixel_exact_at_8_and_10_bit"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height) = (64usize, 64usize); - for depth in [8usize, 10] { - let pix_fmt = if depth == 10 { - "yuv420p10le" - } else { - "yuv420p" - }; - let render = || { - crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - "smptebars=size=64x64:rate=25", - "-vf", - "hue=s=0", - "-pix_fmt", - pix_fmt, - "-strict", - "-1", - "-t", - "0.04", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run") - .stdout - }; - let y4m_a = render(); - let y4m_b = render(); - assert_eq!( - y4m_a, y4m_b, - "{NAME}: smptebars must render byte-identical across two runs at {depth}-bit" - ); - let y4m = y4m_a; - let depth_arg = format!("--bit-depth={depth}"); - let input_depth_arg = format!("--input-bit-depth={depth}"); - let out = run_with_stdin( - Command::new(aomenc_path()) - .args([ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=30", - "--cpu-used=0", - "--threads=1", - "--row-mt=0", - "--sb-size=64", - "--tune-content=screen", - "--enable-palette=1", - "--enable-intrabc=0", - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--min-partition-size=32", - "--max-partition-size=32", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-cfl-intra=0", - "--enable-cdef=0", - "--enable-restoration=0", - "--enable-tx-size-search=0", - "--loopfilter-control=0", - "--limit=1", - ]) - // Per-arm overrides go AFTER the base recipe: aomenc keeps the - // LAST occurrence of a repeated flag. - .args([&depth_arg, &input_depth_arg]) - .args(["--obu", "-o", "-", "-"]), - &y4m, - ); - assert!( - out.status.success(), - "{NAME}: aomenc refused the {depth}-bit fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let before = decode::palette_hits(); - let frames = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => panic!("{NAME}: decode_stream refused the {depth}-bit stream: {e}"), - }; - assert!( - decode::palette_hits() > before, - "{NAME}: no real palette block at {depth}-bit -- gate is vacuous" - ); - let ffmpeg_frames = if depth == 10 { - ffmpeg_decode_sequence_10bit(&stream, width, height, 1) - } else { - ffmpeg_decode_sequence(&stream, width, height, 1) - }; - assert_eq!( - frames[0].y, ffmpeg_frames[0].y, - "{NAME}: luma at {depth}-bit" - ); - assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U at {depth}-bit"); - assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V at {depth}-bit"); - } - } - - /// lane-pal8 r1, the gate for a palette on a SQUARE 8x8 LEAF. - /// - /// `read_palette_mode_info` (decodemv.c:567) reads `palette_y_mode` for - /// every `DC_PRED` block whose `av1_get_palette_bsize_ctx` - /// (`num_pels_log2 - num_pels_log2[BLOCK_8X8]`, 0 at 8x8) exists, and - /// `av1_decode_palette_tokens` (decodeframe.c:1135, `av1_visit_palette`) - /// reads the colour-index map after the WHOLE mode-info read. Ours passed - /// `None`/`&[]` from [`decode::decode_leaf8`], reading the mode symbol off - /// CDF row 0 and refusing "a block that actually uses a palette (Y) -- - /// reconstruction is out of scope" the moment it fired -- and at 8 bit - /// aomenc palettes SQUARE blocks, so with `--min-partition-size=8` every - /// 8-bit screen-content stream stopped there (lane-kf900 r4's measurement). - /// - /// Sweeps both bit depths x cq 30/40/55 x `--enable-tx-size-search` 0/1 x - /// two lavfi sources (+ a `--tile-columns=1` arm, per the neighbour-map - /// rule: the palette bands are per-mi and tile-guarded). Key frame only - /// (`--limit=1`): the inter frames of these recipes stop on OTHER lanes' - /// open refusals (8x8 inter leaf chroma mode, inter 1:4 partitions). - /// HARD-asserts the 8x8-leaf palette counter moved on the compared arms - /// and that no arm mismatched, in or out of scope. - #[test] - fn a_real_aomenc_palette_stream_with_8x8_leaves_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_palette_stream_with_8x8_leaves_decodes_pixel_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height) = (128usize, 128usize); - let (mut leaf8_total, mut fired_arms, mut compared, mut frames_compared) = - (0usize, 0u32, 0u32, 0usize); - let (mut out_of_scope, mut out_of_scope_mismatch, mut refusals) = (0u32, 0u32, 0u32); - let (mut sb_strip_total, mut sb_strip_arms) = (0usize, 0u32); - // lane-t900 r34 LIFTED this shape; the counter stays so the gate - // fails loudly if the refusal ever comes back. - let mut sb_strip_refusals = 0u32; - for src in ["testsrc2", "smptebars"] { - for depth in [8usize, 10usize] { - for cq in [30usize, 40, 55] { - for txs in [0usize, 1] { - for tiles in [0usize, 1] { - let arm = format!("{src}-{depth}bit-cq{cq}-txs{txs}-tc{tiles}"); - let pix_fmt = if depth == 10 { - "yuv420p10le" - } else { - "yuv420p" - }; - let size = format!("{src}=size={width}x{height}:rate=25"); - let render = || { - let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &size, - "-t", - "0.04", - "-pix_fmt", - pix_fmt, - "-strict", - "-1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!(out.status.success(), "{NAME}: ffmpeg failed for {arm}"); - out.stdout - }; - let y4m_a = render(); - let y4m_b = render(); - assert_eq!( - y4m_a, y4m_b, - "{NAME}: {arm} must render byte-identical across two runs" - ); - let y4m = y4m_a; - let depth_arg = format!("--bit-depth={depth}"); - let input_depth_arg = format!("--input-bit-depth={depth}"); - let cq_arg = format!("--cq-level={cq}"); - let txs_arg = format!("--enable-tx-size-search={txs}"); - let tiles_arg = format!("--tile-columns={tiles}"); - let out = run_with_stdin( - Command::new(aomenc_path()) - .args([ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cpu-used=0", - "--threads=1", - "--row-mt=0", - "--lag-in-frames=0", - "--limit=1", - "--sb-size=64", - "--tune-content=screen", - "--enable-palette=1", - "--enable-intrabc=0", - "--min-partition-size=8", - "--enable-cdef=0", - "--enable-restoration=0", - "--loopfilter-control=0", - ]) - // aomenc keeps the LAST occurrence of a repeated flag, - // so per-arm overrides go after the base recipe. - .args([ - &depth_arg, - &input_depth_arg, - &cq_arg, - &txs_arg, - &tiles_arg, - ]) - .args(["--obu", "-o", "-", "-"]), - &y4m, - ); - assert!( - out.status.success(), - "{NAME}: aomenc refused {arm}: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - decode::reset_palette_leaf8_hits(); - decode::reset_palette_sb_strip_hits(); - let decoded = decode_stream(&stream); - let leaf8 = decode::palette_leaf8_hits(); - let sb_strip = decode::palette_sb_strip_hits(); - leaf8_total += leaf8; - sb_strip_total += sb_strip; - match decoded { - Ok(frames) => { - assert!(!frames.is_empty(), "{NAME}: {arm} decoded no frame"); - // The ENCODE's frame count: the per-arm - // render (10417) builds - // `{src}=size=128x128:rate=25` with `-t 0.04` - // (10427) -- one frame -- and the aomenc args - // carry `--limit=1` (10467), so every - // (src, depth, cq, txs, tiles) arm codes - // exactly 1 frame. Asserted ABOVE the oracle - // call. - assert_eq!(frames.len(), 1, "{NAME}: {arm} key frame"); - let theirs = if depth == 10 { - ffmpeg_decode_sequence_10bit( - &stream, - width, - height, - frames.len(), - ) - } else { - ffmpeg_decode_sequence(&stream, width, height, frames.len()) - }; - assert_eq!( - frames.len(), - theirs.len(), - "{NAME}: {arm} frame count" - ); - let mut same = true; - for (i, (ours, ref_f)) in - frames.iter().zip(theirs.iter()).enumerate() - { - let ok = ours.y == ref_f.y - && ours.u == ref_f.u - && ours.v == ref_f.v; - if !ok { - eprintln!("{NAME}: {arm} MISMATCH at frame {i}"); - } - same &= ok; - frames_compared += 1; - } - compared += 1; - if sb_strip > 0 { - sb_strip_arms += 1; - assert!( - same, - "{NAME}: {arm} decoded {sb_strip} non-skip palette \ - block(s) on a superblock-level strip and did not \ - match ffmpeg" - ); - } - if leaf8 > 0 || sb_strip > 0 { - fired_arms += 1; - assert!( - same, - "{NAME}: {arm} decoded {leaf8} 8x8-leaf palette \ - block(s) and did not match ffmpeg" - ); - } else { - out_of_scope += 1; - if !same { - out_of_scope_mismatch += 1; - } - } - eprintln!( - "{NAME}: {arm} {} frame(s), {leaf8} 8x8-leaf palette \ - block(s), {sb_strip} superblock-strip palette \ - block(s), exact={same}", - frames.len() - ); - } - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME}: {arm} decode failed: {e}" - ); - // Named, counted, never turned into a skip. - if msg.contains("superblock-level HORZ/VERT strip") { - sb_strip_refusals += 1; - } - eprintln!("{NAME}: {arm} REFUSED: {e}"); - refusals += 1; - } - } - } - } - } - } - } - eprintln!( - "{NAME}: {leaf8_total} 8x8-leaf palette block(s) across {fired_arms} arm(s), \ - {compared} arms compared ({frames_compared} frames), {sb_strip_total} \ - superblock-strip palette block(s) across {sb_strip_arms} arm(s), \ - {out_of_scope} out of scope ({out_of_scope_mismatch} mismatched), \ - {refusals} refused ({sb_strip_refusals} superblock-strip palette)" - ); - assert!( - leaf8_total > 0 && fired_arms > 0, - "{NAME}: gate is vacuous -- no compared arm decoded an 8x8-leaf palette block" - ); - assert_eq!( - sb_strip_refusals, 0, - "{NAME}: the superblock-strip palette refusal is back (lane-t900 r34 lifted it)" - ); - assert!( - sb_strip_arms > 0 && sb_strip_total > 0, - "{NAME}: no arm decoded a non-skip palette block on a superblock-level strip -- \ - the shape r34 lifted is no longer exercised" - ); - assert_eq!( - out_of_scope_mismatch, 0, - "{NAME}: an out-of-scope arm mismatched ffmpeg -- a defect, never a skip" - ); - assert!( - frames_compared > 0, - "{NAME}: no frame was compared pixel-exact" - ); - } - - /// lane-av1toolgates: `enable-rect-tx` at 8 BITS. See - /// [`rect_tx_tool_gate`] for what the flag does and does not prove, and - /// why the recipe is spelled here rather than in the helper. - /// - /// The whole recipe is inline: `--passes=1` has to be findable in this - /// segment for the coverage derivation to count the gate at all, and - /// `--enable-rect-tx=1` has to be findable here for it to count the - /// TOOL. The quantiser and the tx-size-search setting are swept as two - /// arms so the witness cannot rest on one RD interaction. - #[test] - fn a_real_aomenc_8bit_stream_with_a_rect_transform_decodes_pixel_exact() { - let mut totals = (0usize, 0usize); - for (cq, tx_search) in [("20", "1"), ("40", "0")] { - let args: Vec = [ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cpu-used=0", - "--threads=1", - "--row-mt=0", - "--lag-in-frames=0", - "--auto-alt-ref=0", - "--kf-max-dist=1000", - "--error-resilient=1", - "--sb-size=64", - // The tool under test, spelled explicitly. CONTEXT, per - // `rect_tx_tool_gate`: aomenc was ALLOWED rect tx sizes. - "--enable-rect-tx=1", - "--enable-rect-partitions=1", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-restoration=0", - "--enable-palette=0", - "--enable-cdef=0", - "--enable-cfl-intra=0", - "--enable-intrabc=0", - "--enable-order-hint=0", - "--min-partition-size=8", - "--max-partition-size=32", - ] - .map(String::from) - .into_iter() - .chain([ - format!("--cq-level={cq}"), - format!("--enable-tx-size-search={tx_search}"), - ]) - // The output tail comes LAST: aomenc stops reading flags at the - // first bare argument, so a sweep flag appended after `-o - -` is - // silently dropped and the arm encodes a different recipe than the - // one this gate claims to have run. - .chain(["--obu", "-o", "-", "-"].map(String::from)) - .collect(); - let name = format!( - "a_real_aomenc_8bit_stream_with_a_rect_transform_decodes_pixel_exact[cq{cq}/tx{tx_search}]" - ); - let (p, t) = rect_tx_tool_gate(&name, false, &args); - totals.0 += p; - totals.1 += t; - } - assert_rect_tx_witness( - "a_real_aomenc_8bit_stream_with_a_rect_transform_decodes_pixel_exact", - totals.0, - totals.1, - ); - eprintln!( - "a_real_aomenc_8bit_stream_with_a_rect_transform_decodes_pixel_exact: 2 arms \ - pixel-exact; parsed rect partitions {}, rect coefficient TUs {}", - totals.0, totals.1 - ); - } - - /// lane-av1toolgates: `enable-rect-tx` at 10 BITS -- the same recipe, the - /// same parsed-shape witness, at the depth the 8-bit arm says nothing - /// about (the per-depth rule `NEVER_EXERCISED_10BIT` is built on: - /// lane-hbdinter's two 10-bit-only defects survived because every 10-bit - /// gate pinned the filters off). The depth is spelled in THIS body, - /// which is what files the gate in the 10-bit bucket. - #[test] - fn a_real_aomenc_10bit_stream_with_a_rect_transform_decodes_pixel_exact() { - let mut totals = (0usize, 0usize); - for (cq, tx_search) in [("20", "1"), ("40", "0")] { - let args: Vec = [ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cpu-used=0", - "--threads=1", - "--row-mt=0", - "--lag-in-frames=0", - "--auto-alt-ref=0", - "--kf-max-dist=1000", - "--error-resilient=1", - "--sb-size=64", - "--input-bit-depth=10", - "--bit-depth=10", - // The tool under test, spelled explicitly. CONTEXT, per - // `rect_tx_tool_gate`: aomenc was ALLOWED rect tx sizes. - "--enable-rect-tx=1", - "--enable-rect-partitions=1", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-restoration=0", - "--enable-palette=0", - "--enable-cdef=0", - "--enable-cfl-intra=0", - "--enable-intrabc=0", - "--enable-order-hint=0", - "--min-partition-size=8", - "--max-partition-size=32", - ] - .map(String::from) - .into_iter() - .chain([ - format!("--cq-level={cq}"), - format!("--enable-tx-size-search={tx_search}"), - ]) - // The output tail comes LAST: aomenc stops reading flags at the - // first bare argument, so a sweep flag appended after `-o - -` is - // silently dropped and the arm encodes a different recipe than the - // one this gate claims to have run. - .chain(["--obu", "-o", "-", "-"].map(String::from)) - .collect(); - let name = format!( - "a_real_aomenc_10bit_stream_with_a_rect_transform_decodes_pixel_exact[cq{cq}/tx{tx_search}]" - ); - let (p, t) = rect_tx_tool_gate(&name, true, &args); - totals.0 += p; - totals.1 += t; - } - assert_rect_tx_witness( - "a_real_aomenc_10bit_stream_with_a_rect_transform_decodes_pixel_exact", - totals.0, - totals.1, - ); - eprintln!( - "a_real_aomenc_10bit_stream_with_a_rect_transform_decodes_pixel_exact: 2 arms \ - pixel-exact; parsed rect partitions {}, rect coefficient TUs {}", - totals.0, totals.1 - ); - } - - /// lane-kf900 r5, the gate for the rect-strip `use_intrabc` read. - /// - /// `av1_allow_intrabc` is a FRAME-level test (`decodemv.c:892`, - /// `read_intra_frame_mode_info`): on an intra frame whose header set - /// `allow_intrabc`, EVERY intra block reads a `use_intrabc` symbol right - /// after `skip`/`cdef`/`delta_q` and before `mbmi->mode`. There is no - /// block-shape term, so rect strips read it exactly like square leaves -- - /// `read_intra_mode_rect` never did, and the arithmetic decoder desynced - /// at the FIRST symbol of the first rect block of every - /// `--tune-content=screen` key frame (measured: `testsrc2` 256x192 cq59 - /// 8-bit decoded "OK" with all 49152 luma samples wrong). - /// - /// Arm 0 is that recipe at cq50 without palette: its rect strips really do - /// use intrabc. lane-av1-rect14 reconstructs those strips (2:1 and the - /// 16x4/4x16 pair), so the arm must now decode pixel-exact -- and it must - /// still have read the symbol. The named refusal remains only for a - /// 128-superblock strip (`decode_block_128rect`), which this sb64 recipe - /// does not reach. - /// Arm 1 is the same recipe without palette and without tx-size search -- - /// it decodes the whole frame, reading the symbol dozens of times. - /// Arm 2 is a screen-tools key frame whose header does NOT set - /// `allow_intrabc` (cq63): it stays pixel-exact, proving the new read is - /// not taken when libaom does not write it. - /// - /// PIXEL RESIDUE (open, lane-kf900 r5): arm 1's frame is entropy-exact - /// against the instrumented aomdec for 429 mode-ladder elements and then - /// diverges inside the DV read of a SQUARE intrabc block at mi(32,44), so - /// its pixels are not compared here. That is a separate defect in - /// `read_intrabc_dv`, not in the read this gate covers. - #[test] - fn a_real_aomenc_screen_key_frame_reads_use_intrabc_on_rect_strips() { - const NAME: &str = "a_real_aomenc_screen_key_frame_reads_use_intrabc_on_rect_strips"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height) = (256usize, 192usize); - // (arm, source, per-arm overrides AFTER the base recipe, expect_refusal, - // must_read_use_intrabc) - const TS: &str = "testsrc2=s=256x192:r=25"; - const SB: &str = "smptebars=size=256x192:rate=25"; - // (arm, source, per-arm overrides AFTER the base recipe, expect_refusal, - // must_read_use_intrabc_on_a_rect_strip) - let arms: [(&str, &str, &[&str], bool, bool); 8] = [ - // lane-av1-intrabc (2026-09-20): this arm used to REFUSE here -- the - // 16x8 rect strip it decodes is the first block on main that reaches - // `decode_intrabc_rect`, so the whole arm stopped at a named refusal. - // Reconstruction is ported now, so the arm decodes pixel-exact and - // the `rect_total` assert below keeps it from quietly falling back - // to an ordinary-intra decode of the same block. - ( - "testsrc2-cq50-txs0", - TS, - &[ - "--cq-level=50", - "--enable-palette=0", - "--enable-tx-size-search=0", - ], - false, - true, - ), - ( - "smptebars-cq40-txs0", - SB, - &[ - "--cq-level=40", - "--enable-palette=0", - "--enable-tx-size-search=0", - ], - false, - false, - ), - ( - "smptebars-cq45-txs0", - SB, - &[ - "--cq-level=45", - "--enable-palette=0", - "--enable-tx-size-search=0", - ], - false, - true, - ), - ( - "smptebars-cq45-txs1", - SB, - &[ - "--cq-level=45", - "--enable-palette=0", - "--enable-tx-size-search=1", - ], - false, - false, - ), - ( - "smptebars-cq50-txs1", - SB, - &[ - "--cq-level=50", - "--enable-palette=0", - "--enable-tx-size-search=1", - ], - false, - false, - ), - ( - "smptebars-cq55-txs0", - SB, - &[ - "--cq-level=55", - "--enable-palette=0", - "--enable-tx-size-search=0", - ], - false, - false, - ), - ( - "testsrc2-cq63-txs1", - TS, - &[ - "--cq-level=63", - "--enable-palette=0", - "--enable-tx-size-search=1", - ], - false, - false, - ), - // lane-kf900 r7: the 8x8-LEAF intrabc arm. Rect and 1:4 - // partitions off (so no rect strip refuses first), palette on, - // `TxMode::Largest`: aomenc puts exactly one `use_intrabc` block - // on a `BLOCK_8X8` leaf here, the shape `decode_leaf8` decoded as - // ordinary intra before this round. - ( - "testsrc2-cq55-leaf8", - TS, - &[ - "--cq-level=55", - "--enable-palette=1", - "--enable-tx-size-search=0", - "--enable-rect-partitions=0", - "--enable-1to4-partitions=0", - ], - false, - false, - ), - ]; - let (mut reads_total, mut refused, mut frames_compared) = (0usize, 0u32, 0usize); - let (mut blocks_total, mut fired_arms, mut out_of_scope, mut out_of_scope_mismatch) = - (0usize, 0u32, 0u32, 0u32); - let mut leaf8_total = 0usize; - let mut rect_total = 0usize; - for (arm, src, extra, expect_refusal, must_read) in &arms { - let render = || { - let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - *src, - "-t", - "0.2", - "-pix_fmt", - "yuv420p", - "-strict", - "-1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!(out.status.success(), "{NAME}: ffmpeg failed for {arm}"); - out.stdout - }; - let y4m_a = render(); - let y4m_b = render(); - assert_eq!( - y4m_a, y4m_b, - "{NAME}: {arm} must render byte-identical across two runs" - ); - let y4m = y4m_a; - let out = run_with_stdin( - Command::new(aomenc_path()) - .args([ - "--codec=av1", - "--bit-depth=8", - "--input-bit-depth=8", - "--passes=1", - "--end-usage=q", - "--cpu-used=0", - "--lag-in-frames=0", - "--kf-max-dist=1", - "--limit=1", - "--threads=1", - "--tile-columns=0", - "--enable-rect-partitions=1", - "--enable-1to4-partitions=1", - "--min-partition-size=8", - "--max-partition-size=32", - "--sb-size=64", - // `allow_screen_content_tools` (and with it the frame - // header's `allow_intrabc` bit) comes from here. - "--tune-content=screen", - // Spelled so `gate_coverage` counts the tool as exercised - // rather than defaulted (class `tool-disabled-in-every-gate`). - "--enable-intrabc=1", - ]) - // aomenc keeps the LAST occurrence of a repeated flag. - .args(*extra) - .args(["--obu", "-o", "-", "-"]), - &y4m, - ); - assert!( - out.status.success(), - "{NAME}: aomenc refused {arm}: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - decode::reset_rect_intrabc_reads(); - crate::decode::reset_intrabc_hits(); - crate::decode::reset_leaf8_intrabc_hits(); - crate::decode::reset_intrabc_rect_hits(); - let decoded = decode_stream(&stream); - let reads = decode::rect_intrabc_reads(); - // Blocks that decoded `use_intrabc == 1` (square path), i.e. that - // read a DV and predicted from the current frame -- distinct from - // `reads`, which counts rect strips that merely READ the flag. - let blocks = crate::decode::intrabc_hits(); - reads_total += reads; - blocks_total += blocks; - // The 8x8-leaf shape has its own counter: without it this gate's - // other arms (all rect/32x32 intrabc) would stay green while the - // leaf path decoded an intrabc block as ordinary intra (class - // `gate-blind-to-feature`). - let leaf8 = crate::decode::leaf8_intrabc_hits(); - leaf8_total += leaf8; - rect_total += crate::decode::intrabc_rect_hits(); - if *arm == "testsrc2-cq55-leaf8" { - assert!( - leaf8 > 0, - "{NAME}: {arm} decoded no intrabc block at an 8x8 leaf -- the arm no longer exercises `decode_leaf8`'s intrabc path" - ); - } - if *must_read { - assert!( - reads > 0, - "{NAME}: {arm} read no use_intrabc symbol on a rect strip -- the \ - arm no longer exercises the fix (allow_intrabc not set?)" - ); - } - match decoded { - Ok(frames) => { - assert!( - !*expect_refusal, - "{NAME}: {arm} decoded a frame whose rect strips use intrabc -- \ - reconstruction is not ported, it must refuse by name" - ); - assert!(!frames.is_empty(), "{NAME}: {arm} decoded no frame"); - // The ENCODE's frame count, asserted ABOVE the oracle call: - // the per-arm render (11100) uses `-t 0.2` at TS/SB's - // `rate=25` (10987, 10988) -- 5 input frames -- and the aomenc - // args carry `--limit=1` (11145), so all eight arms code - // exactly 1 frame. The old comment below claimed a count - // assert here would be tautological; that is true of - // `ffmpeg_frames.len() == frames.len()` and false of this: - // `frames.len() == 1` is a fact about the ENCODE, checked - // before `frames.len()` is spent as ffmpeg's frame budget. - assert_eq!(frames.len(), 1, "{NAME}: {arm} key frame"); - let ffmpeg_frames = - ffmpeg_decode_sequence(&stream, width, height, frames.len()); - // EVERY frame is compared; an arm whose decode never hit an - // intrabc block proves nothing about the DV/prediction path, - // so it is counted OUT OF SCOPE -- but a mismatch there is - // still a failure (`out_of_scope_mismatch == 0`), never a skip. - let mut same = true; - for (i, (ours, theirs)) in frames.iter().zip(ffmpeg_frames.iter()).enumerate() { - let ok = ours.y == theirs.y && ours.u == theirs.u && ours.v == theirs.v; - if !ok { - eprintln!("{NAME}: {arm} MISMATCH at frame {i}"); - } - same &= ok; - frames_compared += 1; - } - if blocks > 0 { - fired_arms += 1; - assert!( - same, - "{NAME}: {arm} decoded {blocks} intrabc block(s) and did not match ffmpeg" - ); - } else { - out_of_scope += 1; - if !same { - out_of_scope_mismatch += 1; - } - } - eprintln!( - "{NAME}: {arm} {} frame(s), {reads} rect use_intrabc reads, \ - {blocks} intrabc block(s), exact={same}", - frames.len() - ); - } - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME}: {arm} decode failed: {e}" - ); - assert!( - *expect_refusal, - "{NAME}: {arm} was expected to decode, it refused: {e}" - ); - assert!( - msg.contains("intra block copy") || msg.contains("intrabc"), - "{NAME}: {arm} refused for an unrelated reason: {e}" - ); - eprintln!("{NAME}: {arm} REFUSED (expected): {e}"); - refused += 1; - } - } - } - eprintln!( - "{NAME}: {reads_total} rect-strip use_intrabc symbol(s) read, \ - {blocks_total} intrabc block(s) decoded across {fired_arms} arm(s), \ - {refused} refused by name, {frames_compared} frames compared, \ - {out_of_scope} out of scope ({out_of_scope_mismatch} mismatched)" - ); - eprintln!( - "{NAME}: {rect_total} intrabc block(s) on a HORZ/VERT rect strip (decode_intrabc_rect)" - ); - assert!( - reads_total > 0, - "{NAME}: gate is vacuous -- no arm read the symbol" - ); - assert!( - leaf8_total > 0, - "{NAME}: no arm decoded an intrabc block at an 8x8 leaf -- lane-kf900 r7's fix is untested" - ); - assert!( - blocks_total > 0 && fired_arms > 0, - "{NAME}: gate is vacuous -- no compared arm actually decoded an intrabc block" - ); - assert!( - rect_total > 0, - "{NAME}: no arm decoded an intrabc block on a HORZ/VERT rect strip -- \ - `decode_intrabc_rect` is untested" - ); - // lane-av1-intrabc: this used to be exactly one -- the 2:1 rect strips - // now reconstruct. The 1:4 pair strips (`decode_rect4_16_strip` et al.) - // still refuse by name, but no arm HERE reaches that shape; it stays - // pinned by `refusal_inventory`'s own gate. - assert_eq!(refused, 0, "{NAME}: an arm still refuses by name"); - assert!( - frames_compared > 0, - "{NAME}: no frame was compared pixel-exact" - ); - assert_eq!( - out_of_scope_mismatch, 0, - "{NAME}: an arm without an intrabc block still mismatched ffmpeg" - ); - } - - /// lane-av1-rect14: the 16x4/4x16 intrabc pair. libaom codes the pair's - /// chroma on the odd-mi strip only (`is_chroma_reference`, - /// av1_common_int.h:1454). The witness is the report recipe: testsrc2 - /// 640x480 cq60 palette, txs off, which places a 16x4 intrabc strip at - /// mi(76,108). Pre-fix this refused by name. VERT_4 was not produced by - /// any fully-decoded recipe tried here (the allintra stream codes four - /// `PARTITION_VERT_4` at bsize 6 and then stops on the unrelated var-tx - /// mixed-leaf refusal); the VERT arm is the same body with the axes - /// swapped. - #[test] - fn a_16x4_intrabc_pair_strip_decodes_pixel_exact() { - const NAME: &str = "a_16x4_intrabc_pair_strip_decodes_pixel_exact"; - if !have_ffmpeg() || !have_aomenc() { - eprintln!("SKIP {NAME}: ffmpeg/aomenc missing"); - return; - } - let (width, height) = (640usize, 480usize); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - "testsrc2=s=640x480:r=25", - "-frames:v", - "1", - "-pix_fmt", - "yuv420p", - "-strict", - "-1", - "-f", - "yuv4mpegpipe", - "-", - ]), None, |c| c.output()) - .expect("ffmpeg") - .stdout; - let out = run_with_stdin( - Command::new(aomenc_path()).args([ - "--codec=av1", - "--bit-depth=8", - "--input-bit-depth=8", - "--passes=1", - "--end-usage=q", - "--cpu-used=0", - "--lag-in-frames=0", - "--kf-max-dist=1", - "--limit=1", - "--threads=1", - "--tile-columns=0", - "--enable-rect-partitions=1", - "--enable-1to4-partitions=1", - "--min-partition-size=4", - "--max-partition-size=64", - "--sb-size=64", - "--tune-content=screen", - "--enable-intrabc=1", - "--cq-level=60", - "--enable-palette=1", - "--enable-tx-size-search=0", - "--obu", - "-o", - "-", - "-", - ]), - &y4m, - ); - assert!(out.status.success(), "{NAME}: aomenc failed"); - crate::decode::reset_rect4_16_pair_hits(); - let frames = decode_stream(&out.stdout).unwrap_or_else(|e| panic!("{NAME}: {e}")); - assert!( - crate::decode::rect4_16_intrabc_hits() > 0, - "{NAME}: no 16x4/4x16 intrabc strip -- the pair body was not reached" - ); - // The ENCODE's frame count, asserted ABOVE the oracle call: the y4m is - // rendered with `-frames:v 1` (11333) -- a single frame of - // `testsrc2=s=640x480:r=25` -- and aomenc runs with - // `--limit=1 --kf-max-dist=1` (11355, 11356), so the stream codes - // exactly 1 key frame. Below the call this assert could not fire - // first: `ffmpeg_decode_sequence` was already handed `frames.len()`. - assert_eq!(frames.len(), 1, "{NAME}: expected one key frame"); - let refs = ffmpeg_decode_sequence(&out.stdout, width, height, frames.len()); - assert_eq!(frames[0].y, refs[0].y, "{NAME}: luma"); - assert_eq!(frames[0].u, refs[0].u, "{NAME}: u"); - assert_eq!(frames[0].v, refs[0].v, "{NAME}: v"); - } - - /// lane-av1-rect14: lossless 16x4/4x16 chroma is two TX_4X4s, not one - /// TX_8X4. The measured site is luma col 108 of a 320x240 sb128 lossless - /// key frame (lanes/av1lossless128.report.md §6). Rows 0-127 of that - /// frame -- the first superblock row, which contains the site -- must - /// match ffmpeg. A later mismatch is the pre-existing 64x64 square - /// lossless residue (base fails at byte 108; this lane's first remaining - /// mismatch is row 128). The gate fails if that residue moves back into - /// the repaired region. - #[test] - fn a_lossless_16x4_chroma_pair_repairs_the_measured_site() { - const NAME: &str = "a_lossless_16x4_chroma_pair_repairs_the_measured_site"; - if !have_ffmpeg() || !have_aomenc() { - eprintln!("SKIP {NAME}: ffmpeg/aomenc missing"); - return; - } - let (width, height) = (320usize, 240usize); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - "testsrc2=s=320x240:r=25", - "-frames:v", - "1", - "-pix_fmt", - "yuv420p", - "-strict", - "-1", - "-f", - "yuv4mpegpipe", - "-", - ]), None, |c| c.output()) - .expect("ffmpeg") - .stdout; - let out = run_with_stdin( - Command::new(aomenc_path()).args([ - "--codec=av1", - "--cpu-used=0", - "--lossless=1", - "--sb-size=128", - "--lag-in-frames=0", - "--kf-max-dist=1", - "--limit=1", - "--threads=1", - "--passes=1", - "--enable-1to4-partitions=1", - "--min-partition-size=4", - "--enable-rect-partitions=1", - "--obu", - "-o", - "-", - "-", - ]), - &y4m, - ); - assert!(out.status.success(), "{NAME}: aomenc failed"); - crate::decode::reset_rect4_16_pair_hits(); - let frames = decode_stream(&out.stdout).unwrap_or_else(|e| panic!("{NAME}: {e}")); - assert!( - crate::decode::rect4_16_lossless_chroma_hits() > 0, - "{NAME}: no lossless 16x4/4x16 chroma pair -- the walk was not reached" - ); - // The ENCODE's frame count: the y4m is rendered with `-frames:v 1` - // (11414) -- a single frame of `testsrc2=s=320x240:r=25` -- and aomenc - // runs with `--limit=1 --kf-max-dist=1` (11434, 11435), so the stream - // codes exactly 1 lossless key frame. Asserted ABOVE the oracle call: - // this gate then indexes `frames[0]`/`refs[0]`, which a zero-frame - // decode would panic on rather than report. - assert_eq!(frames.len(), 1, "{NAME}: expected one lossless key frame"); - let refs = ffmpeg_decode_sequence(&out.stdout, width, height, frames.len()); - let repaired = 128 * width; - assert_eq!( - &frames[0].y[..repaired], - &refs[0].y[..repaired], - "{NAME}: luma rows 0-127 (the measured col-108 site) diverged" - ); - let chroma_rows = 64 * (width / 2); - assert_eq!( - &frames[0].u[..chroma_rows], - &refs[0].u[..chroma_rows], - "{NAME}: u" - ); - assert_eq!( - &frames[0].v[..chroma_rows], - &refs[0].v[..chroma_rows], - "{NAME}: v" - ); - // The col-108 byte specifically, so a shift of the old site still fails - // even if some other prefix sample happens to match. - assert_eq!( - frames[0].y[108], refs[0].y[108], - "{NAME}: measured byte 108" - ); - } - - /// lane-av1tilerows: the 4:4:4 LOSSLESS rect-pair chroma REACH fix -- - /// the defect lane `av1formatsweep` filed as **H4** ("4:4:4 lossless + - /// `--tile-rows=1`, frame 3 onward the whole plane goes flat") and this - /// lane's red-before actually measured. - /// - /// **The H4 label was wrong; the defect it points at is real.** Two - /// corrections to the sweep's framing, both measured: - /// - /// 1. `--tile-rows=1` at 256x128 is a **no-op**. aomenc's default - /// superblock is 128px, so 256x128 is 2x1 superblocks -- there is no - /// second superblock ROW to split, and aomenc silently emits a - /// stream BYTE-IDENTICAL to `--tile-columns=0 --tile-rows=0` - /// (verified: both 64828 bytes, `cmp` equal). The sweep's "tiled" - /// fixture contained no tile rows at all. Tile rows at 4:4:4 - /// lossless are exact here: measured pixel-exact at 1, 2 and 4 tile - /// rows, both axes (2x2), at 256x128 / 256x256 / 128x256 / 512x128, - /// on a recipe that is exact without tiles. - /// 2. The "frames 0-2 byte-exact, frame 3 onward flat, Y(0,0) 128 vs - /// 81" signature is a **harness frame-order mismatch, not a decode - /// defect**: with altref on, aomdec's `EC_AV1_FINAL_DUMP` writes 7 - /// frames in DECODE order while `ffmpeg -f rawvideo` writes 6 in - /// DISPLAY order. Indexing one against the other makes frame 1 differ - /// by 29109 samples (30%) -- and aomdec-vs-ffmpeg ALONE reproduces - /// the identical 29109/24412/20046/19906 counts with no edith - /// decoder in the loop. Our decode-order output is byte-exact against - /// the oracle on all 7. - /// - /// The defect IS real, is in the class the sweep named (a hardcoded - /// 4:2:0-shaped walk at 4:4:4), and is tile-INDEPENDENT: it reproduces - /// on the zero-tile stream. `decode.rs`'s lossless 16x4/4x16 chroma-pair - /// walk passed `tu_reach` a hardcoded 4:2:0 luma footprint - /// (`ox * 2, oy * 2, 8`) for every chroma transform unit. At 4:4:4 a - /// 4x4 chroma unit is 4x4 LUMA, so the footprint is doubled: - /// `Reach::of_tu`'s `col_off + tx_w < bw` test then answers against a - /// block twice its real width and every unit past the midpoint wrongly - /// reports `above_right = false`, so a directional chroma strip predicts - /// from a neighbour libaom never reads. - /// - /// **Measured site (red-before, `git stash` of the fix, same tree):** - /// `testsrc2 256x128 yuv444p`, aomenc `--profile=1 --lossless=1 - /// --passes=1 --end-usage=q --threads=1 --row-mt=0 --limit=6 - /// --cpu-used=2 --lag-in-frames=0 --kf-max-dist=100` (pinned below). - /// Frame 0 (the KEY frame) and all five inter frames: **63 samples wrong - /// per frame, U 29 + V 34, first at U(110,26) / V(108,26), deltas -10..+13**, - /// region x108..125 y26..29 -- a 16x4 chroma strip at 4:4:4, whose rows - /// are NOT block-aligned (y26), which is the signature of a REACH - /// answer and not of a coefficient or transform error. - /// - /// **Entropy is bit-identical**: `EC_SYMR` on both sides, 351109 reads - /// compared on `(value, range, symbol, post_rng)` with the CDF-row - /// convention reconciled (`32768 - ours_cdf0 == oracle_cdf0`): **zero - /// divergence**. So this is reconstruction arithmetic, not an entropy - /// fork -- which is what separates it from the H1 rect-partition fork - /// (that one forks `EC_SYMR` at `decodetxb.c:158` `txb_skip`). - /// - /// A second, far worse instance of the SAME defect is the 512x128 - /// `--cpu-used=2` stream (18779 wrong in the key frame, growing to - /// 130708 by frame 5) -- but that stream ALSO forks entropy - /// (459866 oracle reads vs 369136 ours), so it is not claimed here; - /// it belongs to the H1 rect-partition lane. The pinned fixture below is - /// the entropy-clean, fully-repaired instance. - /// - /// Non-vacuity: the fixture bytes are pinned (length + FNV-1a, like the - /// other `ll444_*` pins), the header must really be `ss (0,0)` at 8-bit - /// with `lossless == 1` (asserted from the parsed sequence header, not - /// assumed), the tiled sweep gates' counter - /// `decode::rect4_16_lossless_chroma_hits()` must FIRE (measured 80 - /// units on this fixture -- a 4:2:0 stream of the same content leaves it - /// at 0, because a 4:2:0 lossless 16x4 pair is an 8x4 chroma block and - /// takes the pair-merge, not this walk), and every frame must be - /// byte-exact through BOTH the oracle `aomdec --rawvideo` (decode order, - /// the 7-frame compare that the hidden-frame gates use) and ffmpeg - /// (display order, 4:4:4 full-resolution chroma). - #[test] - fn a_lossless_444_rect16x4_chroma_reach_is_ss_aware() { - const NAME: &str = "a_lossless_444_rect16x4_chroma_reach_is_ss_aware"; - const FIXTURE_LEN: usize = 77918; - const FIXTURE_FNV: u64 = 0xe2a2_90ac_f249_4bf7; - const W: usize = 256; - const H: usize = 128; - const FRAMES: usize = 6; - let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("fixtures/ll444_rect16x4_chroma_reach.obu"); - let stream = std::fs::read(&obu).unwrap_or_else(|e| { - panic!( - "{NAME}: pinned fixture {} is missing ({e}) -- the gate cannot run, \ - which is a failure, not a skip", - obu.display() - ) - }); - assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: fixture length moved"); - assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: fixture bytes moved"); - - // The header must really be the shape the fix is about: 4:4:4 - // (ss 0/0) at 8-bit. A fixture that silently became 4:2:0 would - // take the pair-merge and make every arm below vacuous. - { - let mut p = Av1Parser::new(); - let mut pos = 0usize; - let mut seq = None; - while pos < stream.len() { - let Ok(obu) = p.parse_obu(&stream[pos..]) else { - break; - }; - pos += obu.total_size; - if matches!(obu.kind, ObuKind::SequenceHeader(_)) { - seq = p.sequence_header(); - break; - } - } - let seq = seq.unwrap_or_else(|| panic!("{NAME}: no sequence header parsed")); - assert_eq!( - ( - seq.color_config.subsampling_x, - seq.color_config.subsampling_y - ), - (0, 0), - "{NAME}: fixture is not 4:4:4 (ss {}x{})", - seq.color_config.subsampling_x, - seq.color_config.subsampling_y - ); - assert_eq!( - seq.color_config.bit_depth, 8, - "{NAME}: fixture bit depth moved" - ); - assert_eq!(seq.max_frame_width, W as u32, "{NAME}: fixture width moved"); - assert_eq!( - seq.max_frame_height, H as u32, - "{NAME}: fixture height moved" - ); - } - - let _guard = lock_gate_counters(); - crate::decode::reset_rect4_16_pair_hits(); - let frames = decode_stream(&stream) - .unwrap_or_else(|e| panic!("{NAME}: the pinned stream no longer decodes cleanly: {e}")); - let hits = crate::decode::rect4_16_lossless_chroma_hits(); - assert!( - hits > 0, - "{NAME}: gate is vacuous -- no lossless 16x4/4x16 chroma-pair unit was \ - walked (rect4_16_lossless_chroma_hits = {hits}), so the repaired \ - `tu_reach` call site never ran" - ); - assert_eq!(frames.len(), FRAMES, "{NAME}: shown frame count"); - for f in &frames { - assert_eq!((f.width, f.height), (W, H), "{NAME}: dimensions"); - } - - // The oracle, DECODE order, every frame including hidden alt-ref - // frames. This is the arm that proves the repair against aomdec's - // own reconstruction, not just ffmpeg's. - if aomdec_available(NAME) { - let (decoded, hidden) = decode_all_frames_vs_oracle(&stream, NAME); - assert!( - decoded >= FRAMES, - "{NAME}: oracle decoded {decoded} frames, expected at least {FRAMES}" - ); - let _ = hidden; - } - - // ffmpeg's decoder: DISPLAY order, full-resolution chroma. - if have_ffmpeg() { - let refs = ffmpeg_decode_sequence_444(&stream, W, H, FRAMES); - for (i, (got, want)) in frames.iter().zip(refs.iter()).enumerate() { - for (p, (g, r)) in [(&got.y, &want.y), (&got.u, &want.u), (&got.v, &want.v)] - .iter() - .enumerate() - { - let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count(); - assert_eq!( - bad, 0, - "{NAME}: ffmpeg frame {i} plane {p}: {bad} samples differ" - ); - } - } - } else { - eprintln!("SKIP {NAME} ffmpeg arm: no ffmpeg"); - } - } - - /// lane-av1-intrabc r4: the reviewer's unblock witness for the rect-strip - /// reconstruction -- a CODED `use_intrabc` block (so its residual reader - /// runs, not just the prediction copy) on a 2:1 strip in BOTH - /// orientations, plus the `TX_MODE_SELECT` (var-tx) shape, every arm - /// byte-exact against ffmpeg. - /// - /// The orientation counters (`intrabc_rect_coded_hits`) are the - /// non-vacuity instrument: [`intrabc_rect_hits`] counts neither the skip - /// flag nor the orientation, so an arm that silently became an all-skip - /// stream (or a stream with only one orientation) would keep the old gate - /// green while the coded residual path went untested - /// (class `gate-blind-to-feature`). - /// - /// # The VERT arm is also the DV-PREDICTOR regression witness - /// - /// The 512x384 arm is the stream that exposed r4's defect: 528 of 294912 - /// luma samples were wrong, all inside one `skip == 1` intrabc copy at - /// `mi(84,104)`. Its coded diff was identical to aomdec's and the post-read - /// range matched exactly (`rng=33207` both), so nothing was misread -- the - /// DV PREDICTOR differed. libaom picks `nearestmv` (`-520`) from the - /// `INTRA_FRAME` MV stack; this decoder picked `-512`, one stack entry - /// lower, because the scan that builds that stack walked further than - /// libaom's. The scans step by the candidate BLOCK's own width - /// (`mi_size_wide[bsize]`) over `xd->mi[]`, which holds an entry for every - /// coded block; this decoder's MV grid held only the intrabc blocks, so a - /// non-intrabc neighbour read as uncovered and the scan advanced that cell - /// by one instead of by its real width. See `MiGrid::cover` for the - /// measured walk. A stream that decodes the DV predictor from the wrong - /// stack entry cannot pass this arm's pixel comparison. - #[test] - fn a_coded_rect_intrabc_block_reconstructs_in_both_orientations() { - const NAME: &str = "a_coded_rect_intrabc_block_reconstructs_in_both_orientations"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - const TS256: &str = "testsrc2=s=256x192:r=25"; - const TS512: &str = "testsrc2=s=512x384:r=25"; - // (arm, source, width, height, per-arm overrides, the coded orientation - // this arm must exercise, and whether the frame must code - // `TX_MODE_SELECT` with `allow_intrabc` still set) - let arms: [(&str, &str, usize, usize, &[&str], u8, bool); 3] = [ - // HORZ (16x8) coded strip -- the shape the in-gate witness above - // already reconstructs, pinned here with its own orientation counter. - ( - "horz-coded-256-cq45-pal0-txs0", - TS256, - 256, - 192, - &[ - "--cq-level=45", - "--enable-palette=0", - "--enable-tx-size-search=0", - ], - 0, - false, - ), - // VERT (8x16) coded strip AND the DV-predictor regression stream. - ( - "vert-coded-512-cq45-pal1-txs0", - TS512, - 512, - 384, - &[ - "--cq-level=45", - "--enable-palette=1", - "--enable-tx-size-search=0", - ], - 1, - false, - ), - // The `TX_MODE_SELECT` (stream A) shape: `--enable-tx-size-search=1` - // makes the frame code `tx_mode == Select`, so the intrabc block's - // transform size comes off the INTER var-tx tree. - ( - "txmode-select-256-cq45-pal0-txs1", - TS256, - 256, - 192, - &[ - "--cq-level=45", - "--enable-palette=0", - "--enable-tx-size-search=1", - ], - 0, - true, - ), - ]; - let mut coded_total = [0usize; 2]; - let mut frames_compared = 0usize; - for (arm, src, width, height, extra, want_orient, want_select) in &arms { - let render = || { - let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - *src, - "-t", - "0.2", - "-pix_fmt", - "yuv420p", - "-strict", - "-1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!(out.status.success(), "{NAME}: ffmpeg failed for {arm}"); - out.stdout - }; - let y4m = render(); - let out = run_with_stdin( - Command::new(aomenc_path()) - .args([ - "--codec=av1", - "--bit-depth=8", - "--input-bit-depth=8", - "--passes=1", - "--end-usage=q", - "--cpu-used=0", - "--lag-in-frames=0", - "--kf-max-dist=1", - "--limit=1", - "--threads=1", - "--tile-columns=0", - "--enable-rect-partitions=1", - "--enable-1to4-partitions=1", - "--min-partition-size=8", - "--max-partition-size=32", - "--sb-size=64", - "--tune-content=screen", - "--enable-intrabc=1", - ]) - // aomenc keeps the LAST occurrence of a repeated flag. - .args(*extra) - .args(["--obu", "-o", "-", "-"]), - &y4m, - ); - assert!( - out.status.success(), - "{NAME}: aomenc refused {arm}: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - if *want_select { - let (select, premise) = tx_select_and_intrabc_frames(&stream); - assert!( - select > 0 && premise > 0, - "{NAME}: {arm} no longer codes a frame with both tx_mode == Select and \ - allow_intrabc (select={select} premise={premise}), so the TX_MODE_SELECT \ - shape is untested here" - ); - } - crate::decode::reset_intrabc_rect_hits(); - let frames = - decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME}: {arm} refused: {e}")); - assert!(!frames.is_empty(), "{NAME}: {arm} decoded no frame"); - let coded = crate::decode::intrabc_rect_coded_hits(); - coded_total[0] += coded[0]; - coded_total[1] += coded[1]; - assert!( - coded[*want_orient as usize] > 0, - "{NAME}: {arm} reconstructed no CODED ({}) rect intrabc block -- the residual \ - reader for this orientation is untested (coded horz/vert = {coded:?})", - if *want_orient == 0 { "HORZ" } else { "VERT" } - ); - // The ENCODE's frame count: the per-arm render (11756) uses `-t 0.2` - // at TS256/TS512's `rate=25` (11700, 11701) -- 5 input frames -- and - // the aomenc args carry `--limit=1` (11797), so all three arms code - // exactly 1 frame. Asserted ABOVE the oracle call. - assert_eq!(frames.len(), 1, "{NAME}: {arm} key frame"); - let theirs = ffmpeg_decode_sequence(&stream, *width, *height, frames.len()); - assert_eq!(frames.len(), theirs.len(), "{NAME}: {arm} frame count"); - for (i, (ours, ref_frame)) in frames.iter().zip(theirs.iter()).enumerate() { - assert!( - ours.y == ref_frame.y && ours.u == ref_frame.u && ours.v == ref_frame.v, - "{NAME}: {arm} frame {i} does not match ffmpeg" - ); - frames_compared += 1; - } - eprintln!( - "{NAME}: {arm} {} frame(s) exact, coded rect intrabc horz={} vert={}", - frames.len(), - coded[0], - coded[1] - ); - } - assert!( - coded_total[0] > 0 && coded_total[1] > 0, - "{NAME}: gate is vacuous -- coded rect intrabc blocks seen: horz={} vert={}", - coded_total[0], - coded_total[1] - ); - assert!( - frames_compared > 0, - "{NAME}: no frame was compared pixel-exact" - ); - - // lane-av1-intrabc r5: the SKIPPED VERT 2:1 strip -- the arm the - // reviewer's sweep panicked on (a skipped 8x32 strip passed a - // `bw * bh`-sized ZERO_RESIDUAL slice at stride `side`, and - // `reconstruct_mc_rect` indexed `row * side + w` past its end). - // Skip-heavy recipes (low cq, palette off AND on), each decoded - // byte-exact vs ffmpeg on the inline reconstruction path (the arm - // that panicked pre-fix). The skipped-orientation - // counter is asserted per arm (`gate-blind-to-feature`): a recipe - // that stops producing a skipped VERT strip fails instead of passing - // vacuously. - let _par_lock = lock_gate_counters(); - let skip_arms: [(&str, &str, usize, usize, &[&str]); 2] = [ - ( - "vert-skip-512-cq30-pal0-txs0", - TS512, - 512, - 384, - &[ - "--cq-level=30", - "--enable-palette=0", - "--enable-tx-size-search=0", - ], - ), - ( - "vert-skip-512-cq30-pal1-txs0", - TS512, - 512, - 384, - &[ - "--cq-level=30", - "--enable-palette=1", - "--enable-tx-size-search=0", - ], - ), - ]; - for (arm, src, width, height, extra) in &skip_arms { - let y4m = { - let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - *src, - "-t", - "0.2", - "-pix_fmt", - "yuv420p", - "-strict", - "-1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!(out.status.success(), "{NAME}: ffmpeg failed for {arm}"); - out.stdout - }; - let out = run_with_stdin( - Command::new(aomenc_path()) - .args([ - "--codec=av1", - "--bit-depth=8", - "--input-bit-depth=8", - "--passes=1", - "--end-usage=q", - "--cpu-used=0", - "--lag-in-frames=0", - "--kf-max-dist=1", - "--limit=1", - "--threads=1", - "--tile-columns=0", - "--enable-rect-partitions=1", - "--enable-1to4-partitions=1", - "--min-partition-size=8", - "--max-partition-size=32", - "--sb-size=64", - "--tune-content=screen", - "--enable-intrabc=1", - ]) - // aomenc keeps the LAST occurrence of a repeated flag. - .args(*extra) - .args(["--obu", "-o", "-", "-"]), - &y4m, - ); - assert!( - out.status.success(), - "{NAME}: aomenc refused {arm}: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - // The inline reconstruction path (the arm that panicked - // pre-fix) must match ffmpeg. - let mut skipped_vert = 0usize; - for threads in [1usize] { - crate::decode::reset_intrabc_rect_hits(); - let frames = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => { - panic!("{NAME}: {arm} refused at {threads} recon thread(s): {e}") - } - }; - let skipped = crate::decode::intrabc_rect_skipped_hits(); - assert!( - !frames.is_empty(), - "{NAME}: {arm} decoded no frame at {threads} recon thread(s)" - ); - // The ENCODE's frame count: the skip_arms encode (11904) renders - // TS512 with `-t 0.2` at `rate=25` (11907) and its aomenc runs - // with `--limit=1` (11945), so the stream holds 1 coded frame -- - // and this loop re-decodes those SAME bytes at each `threads` - // value, so the count is arm-invariant. Asserted ABOVE the call. - assert_eq!( - frames.len(), - 1, - "{NAME}: {arm} key frame at {threads} recon thread(s)" - ); - let theirs = ffmpeg_decode_sequence(&stream, *width, *height, frames.len()); - assert_eq!( - frames.len(), - theirs.len(), - "{NAME}: {arm} frame count at {threads} recon thread(s)" - ); - for (i, (ours, ref_frame)) in frames.iter().zip(theirs.iter()).enumerate() { - assert!( - ours.y == ref_frame.y && ours.u == ref_frame.u && ours.v == ref_frame.v, - "{NAME}: {arm} frame {i} does not match ffmpeg at {threads} recon thread(s)" - ); - } - skipped_vert = skipped[1]; - eprintln!( - "{NAME}: {arm} {} frame(s) exact at {threads} recon thread(s), skipped rect intrabc horz={} vert={}", - frames.len(), - skipped[0], - skipped[1] - ); - } - assert!( - skipped_vert > 0, - "{NAME}: {arm} reconstructed no SKIPPED VERT rect intrabc strip -- the r5 stride arm is untested" - ); - } - } - - /// lane-t900 r34, the WITNESS (r33 pinned it ignored) that intrabc under - /// a 128x128 superblock decodes pixel-exact. - /// - /// All four arms of r33's census -- `--sb-size=128 --tune-content=screen - /// --enable-intrabc=1` over both `--enable-tx-size-search` settings and - /// two quantisers, on a 2x2 tiling of a 128x96 bar pattern (256x192, - /// 8-bit, `--cpu-used=0 --min-partition-size=8 --max-partition-size=32`, - /// rect and 1:4 off) -- code `use_128x128_superblock && allow_intrabc`. - /// - /// The lift was one constant: `av1_find_ref_dv` (mvref_common.c) takes - /// `mib_size`, the SEQUENCE's superblock size in mi units, so the - /// fallback DV is one 128-px superblock up (or 128 + `INTRABC_DELAY_PIXELS` - /// left on the tile's first superblock row) under a 128 superblock, where - /// [`crate::decode::read_intrabc_dv`] hardcoded 64. Every arm is compared - /// to ffmpeg and the decoded-intrabc-block counter is asserted non-zero, - /// so a stream that stopped using intrabc could not make this vacuous. - /// - /// lane-av1-intrabc (2026-09-17): the four recipes now run at 10 bits as - /// well, and both depths must SHOW the engagement -- `blocks_at_depth` - /// below hard-asserts a decoded intrabc block per depth. The 10-bit - /// coverage the guard records for `enable-intrabc` used to rest on a gate - /// that only SPELLED `--enable-intrabc=1`: measured (same round), all five - /// arms of `a_real_aomenc_rect_strip_palette_decodes_pixel_exact` decode - /// ZERO intrabc blocks at BOTH depths, so the spelling proved nothing and - /// the entry was one encoder-RD change away from being vacuous again - /// (class `tool-disabled-in-every-gate`). An arm here that stops engaging - /// intrabc now fails this gate instead of retiring the entry unproven. - #[test] - fn an_sb128_screen_stream_with_intrabc_decodes_pixel_exact() { - const NAME: &str = "an_sb128_screen_stream_with_intrabc_decodes_pixel_exact"; - if !have_ffmpeg() || !have_aomenc() { - eprintln!("SKIP {NAME}: no ffmpeg/aomenc"); - return; - } - let (width, height) = (256usize, 192usize); - let _guard = lock_gate_counters(); - let (mut blocks_total, mut frames_compared) = (0usize, 0u32); - let mut blocks_at_depth = [0usize; 2]; - for depth in [8usize, 10] { - for txs in ["0", "1"] { - for cq in ["30", "45"] { - let arm = format!("sb128 {depth}-bit txs={txs} cq={cq}"); - let stream = screen_intrabc_stream_at_depth( - "smptebars=size=128x96:rate=25", - cq, - txs, - true, - true, - depth, - &["--sb-size=128"], - ); - let (sb128, intrabc_frames) = sb128_and_intrabc_frames(&stream); - assert!( - sb128 && intrabc_frames > 0, - "{NAME}: {arm} no longer codes sb128 + allow_intrabc" - ); - crate::decode::reset_intrabc_hits(); - let frames = - decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME}: {arm}: {e}")); - let blocks = crate::decode::intrabc_hits(); - blocks_total += blocks; - blocks_at_depth[usize::from(depth == 10)] += blocks; - // The ENCODE's frame count: - // `screen_intrabc_stream_at_depth` (12203) renders - // `smptebars=size=128x96:rate=25` with `-t 0.2` and - // `-vf tile=2x2` (12066, 12069) -- 5 frames in, 1 tiled frame - // out at 256x192 -- and its aomenc runs with `--limit=1` - // (12101), so all eight (depth, txs, cq) arms code exactly - // 1 frame. Asserted ABOVE the oracle call. - assert_eq!(frames.len(), 1, "{NAME}: {arm} key frame"); - let theirs = if depth == 10 { - ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len()) - } else { - ffmpeg_decode_sequence(&stream, width, height, frames.len()) - }; - assert_eq!(frames.len(), theirs.len(), "{NAME}: {arm} frame count"); - for (i, (ours, ref_frame)) in frames.iter().zip(theirs.iter()).enumerate() { - assert!( - ours.y == ref_frame.y && ours.u == ref_frame.u && ours.v == ref_frame.v, - "{NAME}: {arm} frame {i} does not match ffmpeg" - ); - frames_compared += 1; - } - eprintln!( - "{NAME}: {arm} intrabc_frames={intrabc_frames} intrabc_blocks={blocks} \ - DECODED {} frame(s) exact", - frames.len() - ); - } - } - } - assert!(frames_compared > 0, "{NAME}: no frame was compared"); - assert!( - blocks_total > 0, - "{NAME}: gate is vacuous -- no arm decoded a single intrabc block" - ); - assert!( - blocks_at_depth[0] > 0 && blocks_at_depth[1] > 0, - "{NAME}: 8-bit={} 10-bit={} -- an arm at that depth no longer decodes an intrabc \ - block, so `enable-intrabc` coverage there would rest on the flag spelling alone", - blocks_at_depth[0], - blocks_at_depth[1] - ); - } - - /// lane-av1-ibcrect: `use_intrabc` on a 128-root HORZ/VERT strip - /// (BLOCK_128X64 / BLOCK_64X128) decodes PIXEL-EXACT against the - /// instrumented oracle -- the witness the refusal inventory names after - /// `decode_block_128rect`'s rect-strip intrabc refusal was lifted - /// (`decode_intrabc_128rect`). The square-block twin is - /// [`an_sb128_screen_stream_with_intrabc_decodes_pixel_exact`] above. - /// - /// The recipes are the hunt's proven arms (lanes/ibcrect r1/r2, the same - /// `--sb-size=128 --min-partition-size=64 --enable-rect-partitions=1 - /// --enable-ab-partitions=0 --enable-1to4-partitions=0` partition recipe - /// [`a_real_aomenc_sb128_intra_rect_block_decodes_pixel_exact`] uses, plus - /// `--tune-content=screen --enable-intrabc=1` over the DETERMINISTIC geq - /// sinusoid sources -- lavfi `gradients` ignores its seed and re-rolls - /// every run, so a "flake" there was really this): - /// - /// * HORZ arm: 384x320 cq32, 5 all-key frames -- 14 unskipped 128x64 - /// intrabc blocks (`skip=false`, real residual reads); - /// * VERT arm: 512x512 cq45, 5 all-key frames -- an unskipped 64x128 - /// intrabc block at mi(64,96). - /// - /// Both arms HARD-assert `intrabc_128rect_hits() > 0` and decode-order - /// pixel-exactness of EVERY frame (hidden alt-refs included) against the - /// oracle's own dump, so a stream that stopped engaging the shape fails - /// the gate instead of passing vacuously (class `gate-blind-to-feature`). - /// - /// The 10-bit arm engages the shape. Hunt r2 and the witness re-run both - /// measured `intrabc_128rect_hits` +15 on arm 3, so aomenc does take a - /// 128-root HORZ/VERT strip at 10 bit under this recipe. There is no - /// per-depth coverage gap to print. The gate's hard asserts already - /// cover that arm. - /// - /// The chroma context this shape reads was the r2 defect: per-unit chroma - /// entropy states were stamped inside the mu-chunk loop, then the - /// end-of-block `record_split_luma_rect_mi` re-stamped BOTH planes over - /// the whole 128x64 span with ONE composed state -- level = the SUM of - /// both 64x64 chunks' units, dc = chunk-0's top-left (class - /// `override-slot-on-one-arm`; the inter-128 path fixed the same class - /// with its `mu_chroma_units` replay, decode.rs). The next block then - /// read `txb_skip` off the smeared state. - #[test] - fn an_sb128_rect_strip_with_intrabc_decodes_pixel_exact() { - const NAME: &str = "an_sb128_rect_strip_with_intrabc_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - // (tag, width, height, cq, geq luma, 10-bit) - // The geq sources are the hunt's GEO_SMOOTH / GEO_SMOOTH_512, - // byte-identical across runs (see the sb128 intra-rect gate's note). - let arms: [(u32, usize, usize, &str, &str, bool); 3] = [ - ( - 1, - 384, - 320, - "32", - "128+90*sin((X+2*N)/37)+30*sin(Y/29)", - false, - ), - ( - 2, - 512, - 512, - "45", - "128+80*sin((X+3*N)/17)+50*sin(Y/29)+30*sin((X+Y)/13)", - false, - ), - ( - 3, - 384, - 320, - "32", - "128+90*sin((X+2*N)/37)+30*sin(Y/29)", - true, - ), - ]; - let mut engaged_arms = 0u32; - let mut vert_arms = 0u32; - for (tag, width, height, cq, lum, ten_bit) in arms { - let pix = if ten_bit { "yuv420p10le" } else { "yuv420p" }; - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &format!( - "nullsrc=size={width}x{height}:rate=25,format=yuv420p,\ - geq=lum='{lum}':\ - cb='128+30*sin(X/23)':cr='128+30*sin((Y+N)/19)'" - ), - "-pix_fmt", - pix, - "-strict", - "-1", - "-t", - "0.2", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "{NAME}: ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let cq_arg = format!("--cq-level={cq}"); - let mut args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - &cq_arg, - "--cpu-used=0", - "--threads=1", - "--row-mt=0", - "--lag-in-frames=0", - "--kf-max-dist=1", - "--limit=5", - "--tile-columns=0", - "--sb-size=128", - "--min-partition-size=64", - "--enable-rect-partitions=1", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-palette=0", - "--tune-content=screen", - "--enable-intrabc=1", - "--deltaq-mode=0", - "--enable-tx-size-search=0", - ]; - if ten_bit { - args.extend_from_slice(&["--input-bit-depth=10", "--bit-depth=10"]); - } - args.extend_from_slice(&["--obu", "-o", "-", "-"]); - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "{NAME}: aomenc refused the arm {tag} fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let before = crate::decode::intrabc_128rect_hits(); - let (frames, hidden) = decode_all_frames_vs_oracle( - &stream, - &format!("ibcrect-strip-{tag}-{width}x{height}"), - ); - let hits = crate::decode::intrabc_128rect_hits() - before; - eprintln!( - "{NAME}: arm {tag} {width}x{height} cq={cq} {}bit: {frames} decode-order frames \ - pixel-exact ({hidden} hidden), intrabc_128rect_hits=+{hits}", - if ten_bit { 10 } else { 8 }, - ); - if hits > 0 { - engaged_arms += 1; - // The VERT arm is tag 2; its engagement is what proves the - // 64x128 orientation, not just 128x64. - if tag == 2 { - vert_arms += 1; - } - } - } - assert!( - engaged_arms > 0, - "{NAME}: {engaged_arms} arm(s) decoded pixel-exact but NOT ONE decoded a 128-root \ - rect-strip intrabc block -- the shape this gate exists for was never engaged" - ); - assert!( - vert_arms > 0, - "{NAME}: the VERT (64x128) orientation was never engaged -- only 128x64 HORZ strips \ - proved the lift" - ); - } - - /// lane-av1intrapred r2, REGRESSION GATE for the two intrabc TX4-split - /// chroma defects this lane fixed. - /// - /// An intrabc 8x8 leaf whose var-tx tree split to TX_4X4 must (a) arm - /// `INTRABC_CHROMA_TX` from the co-located luma TU's coded type -- the - /// chroma units then take that type's class-1 eob row, HORIZ scan and nz - /// contexts (libaom `av1_get_tx_type`'s is_inter branch; intrabc is - /// inter-classified) -- and (b) predict the chroma units from the FRAME - /// COPY at the DV, not intra-from-UV-mode (intrabc's UV mode is DC, so a - /// leaf that loses the override predicts flat DC where libaom copies a - /// busy region). - /// - /// Pre-r2, decode_leaf8's TX4 arm did neither: R5's chroma U txb at - /// mi (36,66) decoded `eob=11` off the 2D row where aomdec decoded - /// `eob=13` off the class-1 row, and the first surviving pixel fork was - /// U(184,4) of mi (2,92) (class `intrabc-chroma-tx-not-armed`, then - /// `intrabc-chroma-predicts-intra`). - /// - /// The fixture is the report's R5 stream pinned into `fixtures/` - /// (aomenc oracle, testsrc2 320x180 tiled 2x2 -> 640x360, sb64 maxp64 - /// square-only screen intrabc, cq20, 1 frame; 7173 bytes, - /// sha256 bc699af4a6e7c1c5657f041e8cbdf2d3d899ddb80ec2a549a950b7cebb5b41bd). - /// The gate needs no oracle at run time and cannot be skipped: a missing - /// fixture, a decode error, a zero counter, a moved pixel patch or a - /// changed full-frame fingerprint each fail by name. The fingerprint is - /// FNV-1a (dependency-free, same rationale as the cdf-forwarding gate's). - #[test] - fn an_intrabc_tx4_leaf_chroma_inherits_the_luma_type_and_predicts_from_the_frame_copy() { - const NAME: &str = - "an_intrabc_tx4_leaf_chroma_inherits_the_luma_type_and_predicts_from_the_frame_copy"; - const FIXTURE_LEN: usize = 7173; - const FIXTURE_FNV: u64 = 0x3a57_d075_5e4c_fe5b; - const RAW_LEN: usize = 640 * 360 * 3 / 2; - const RAW_FNV: u64 = 0xf271_df27_ce4d_ba66; - // The 4x4 chroma patches at (184,4) -- the first surviving pixel fork - // -- as the oracles (aomdec and ffmpeg agree) reconstruct them. - const U_PATCH: [u16; 16] = [ - 86, 116, 55, 110, 114, 114, 51, 83, 99, 121, 48, 114, 103, 117, 102, 67, - ]; - const V_PATCH: [u16; 16] = [ - 179, 158, 199, 105, 155, 158, 195, 147, 163, 153, 194, 108, 170, 148, 168, 172, - ]; - - let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("fixtures/intrabc_tx4_chroma_kf.obu"); - let stream = std::fs::read(&obu).unwrap_or_else(|e| { - panic!( - "{NAME}: pinned fixture {} is missing ({e}) -- the gate cannot run, \ - which is a failure, not a skip", - obu.display() - ) - }); - assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: fixture length moved"); - assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: fixture bytes moved"); - - let _guard = lock_gate_counters(); - crate::decode::reset_leaf8_intrabc_hits(); - crate::decode::reset_intrabc_tx4_chroma_copy_hits(); - let frames = decode_stream(&stream) - .unwrap_or_else(|e| panic!("{NAME}: the pinned stream no longer decodes cleanly: {e}")); - assert_eq!(frames.len(), 1, "{NAME}: frame count"); - let frame = &frames[0]; - assert_eq!( - (frame.width, frame.height), - (640, 360), - "{NAME}: dimensions" - ); - - // Non-vacuity, both halves: the leaf shape must be reached at all, - // and its chroma route must have consulted the ARMED slot (pre-r2 - // this counter is 0 -- the arm never armed the slot). - assert!( - crate::decode::leaf8_intrabc_hits() > 0, - "{NAME}: gate is vacuous -- no intrabc 8x8 leaf was decoded" - ); - assert!( - crate::decode::intrabc_tx4_chroma_copy_hits() > 0, - "{NAME}: gate is vacuous -- no intrabc TX4-split leaf's chroma read consulted \ - the armed slot (class intrabc-chroma-tx-not-armed)" - ); - - // The first surviving pixel fork: chroma 4x4 at (184,4). The wrong - // wirings put flat intra-DC predictions or the wrong eob class here. - let cw = frame.width / 2; - let u_patch: Vec = (0..4) - .flat_map(|dy| (0..4).map(move |dx| frame.u[(4 + dy) * cw + 184 + dx])) - .collect(); - let v_patch: Vec = (0..4) - .flat_map(|dy| (0..4).map(move |dx| frame.v[(4 + dy) * cw + 184 + dx])) - .collect(); - assert_eq!(u_patch, U_PATCH, "{NAME}: U(184,4) patch moved"); - assert_eq!(v_patch, V_PATCH, "{NAME}: V(184,4) patch moved"); - // The unit the FRAME-COPY override specifically pins: chroma 4x4 at - // (168,0) is an intrabc TX4-split leaf's chroma whose copy source is - // a busy ramp region; without the `palette_uv_bufs` intrabc wrap the - // read predicts flat intra-DC here (78k chroma bytes drift from this - // unit alone), with it the copy reproduces the oracle exactly. - const U_COPY_PATCH: [u16; 16] = [ - 91, 91, 91, 91, 120, 120, 120, 120, 120, 120, 120, 120, 73, 102, 116, 116, - ]; - const V_COPY_PATCH: [u16; 16] = [ - 241, 241, 241, 241, 156, 156, 156, 156, 158, 158, 158, 158, 181, 163, 154, 154, - ]; - let u_copy: Vec = (0..4) - .flat_map(|dy| (0..4).map(move |dx| frame.u[dy * cw + 168 + dx])) - .collect(); - let v_copy: Vec = (0..4) - .flat_map(|dy| (0..4).map(move |dx| frame.v[dy * cw + 168 + dx])) - .collect(); - assert_eq!( - u_copy, U_COPY_PATCH, - "{NAME}: U(168,0) patch moved -- the intrabc TX4 chroma read no longer \ - predicts from the frame copy (class intrabc-chroma-predicts-intra)" - ); - assert_eq!(v_copy, V_COPY_PATCH, "{NAME}: V(168,0) patch moved"); - - // The whole frame, packed as the rawvideo byte stream the oracles - // produce: any remaining byte anywhere in Y/U/V fails the gate. - let mut raw = Vec::with_capacity(RAW_LEN); - for plane in [&frame.y, &frame.u, &frame.v] { - raw.extend(plane.iter().map(|&s| s as u8)); - } - assert_eq!(raw.len(), RAW_LEN, "{NAME}: raw size"); - assert_eq!( - fnv1a64(&raw), - RAW_FNV, - "{NAME}: full-frame fingerprint moved" - ); - } - - /// lane-t900 r33, CENSUS for "a sub-8x8 leaf that uses intrabc". - /// - /// The `use_intrabc` symbol IS read at that reader for every sub-8x8 leaf - /// of an `allow_intrabc` frame, so arrival is provable rather than - /// assumed: the arms below force 4x4 leaves (`--min-partition-size=4`) on - /// the exact-repetition screen content that keeps `allow_intrabc`, and the - /// gate requires both counters -- `allow_intrabc` frames and decoded sub-8 - /// leaves -- to be non-zero before it reads anything into the refusal - /// firing 0 times (class `gate-blind-to-feature`). - #[test] - fn a_sub8_leaf_census_over_intrabc_screen_streams_measures_the_sub8_refusal() { - const NAME: &str = - "a_sub8_leaf_census_over_intrabc_screen_streams_measures_the_sub8_refusal"; - if !have_ffmpeg() || !have_aomenc() { - eprintln!("SKIP {NAME}: no ffmpeg/aomenc"); - return; - } - let (width, height) = (256usize, 192usize); - let _guard = lock_gate_counters(); - let (mut premise_arms, mut reached, mut sub8_total, mut frames_compared) = - (0u32, 0u32, 0usize, 0u32); - for cq in ["30", "45"] { - let arm = format!("sub8 cq={cq}"); - let stream = screen_intrabc_stream_with( - "smptebars=size=128x96:rate=25", - cq, - "0", - true, - true, - &["--min-partition-size=4"], - ); - let (_, intrabc_frames) = sb128_and_intrabc_frames(&stream); - if intrabc_frames > 0 { - premise_arms += 1; - } - // No reset for this counter, so measure the delta (the gate lock - // above keeps another gate's decode out of it). - let sub8_before = crate::decode::sub8_split_hits(); - match decode_stream(&stream) { - Ok(frames) => { - let sub8 = crate::decode::sub8_split_hits() - sub8_before; - sub8_total += sub8; - // The ENCODE's frame count: `screen_intrabc_stream_with` (12593) - // renders `smptebars=size=128x96:rate=25` with `-t 0.2` and - // `-vf tile=2x2` (12066, 12069) -- 5 frames in, 1 tiled frame - // out -- and its aomenc runs with `--limit=1` (12101), so both - // cq arms code exactly 1 frame. The census is report-only about - // the COUNTS, but its Ok arm asserts pixel-exactness, so the - // budget handed to ffmpeg is pinned here rather than derived - // from the decode under test. - assert_eq!(frames.len(), 1, "{NAME}: {arm} key frame"); - let theirs = ffmpeg_decode_sequence(&stream, width, height, frames.len()); - assert_eq!(frames.len(), theirs.len(), "{NAME}: {arm} frame count"); - for (i, (ours, ref_frame)) in frames.iter().zip(theirs.iter()).enumerate() { - assert!( - ours.y == ref_frame.y && ours.u == ref_frame.u && ours.v == ref_frame.v, - "{NAME}: {arm} frame {i} does not match ffmpeg" - ); - frames_compared += 1; - } - eprintln!( - "{NAME}: {arm} intrabc_frames={intrabc_frames} sub8_leaves={sub8} \ - DECODED {} frame(s) exact", - frames.len() - ); - } - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME}: {arm} decode failed: {e}" - ); - if msg.contains("a sub-8x8 leaf that uses intrabc") { - reached += 1; - } - sub8_total += crate::decode::sub8_split_hits() - sub8_before; - eprintln!("{NAME}: {arm} intrabc_frames={intrabc_frames} REFUSED: {e}"); - } - } - } - eprintln!( - "{NAME}: {premise_arms}/2 arm(s) keep allow_intrabc, {sub8_total} sub-8 leaf/leaves \ - decoded, {reached} reach the refusal, {frames_compared} frame(s) exact" - ); - assert!( - premise_arms > 0, - "{NAME}: census is vacuous -- no arm kept allow_intrabc, so the refusal's own \ - premise was never within reach" - ); - assert!( - sub8_total > 0, - "{NAME}: census is vacuous -- no sub-8 leaf was decoded at all, so the \ - `use_intrabc` symbol this refusal guards was never read" - ); - } - - /// lane-t900 r33, CENSUS for "an intrabc block whose var-tx tree resolved - /// to mixed leaf transform sizes" -- the residue lane-t900 r32 left when - /// it lifted the intrabc `TX_MODE_SELECT` refusal. - /// - /// The tree is read in full; lane-av1-ibcvtx taught the luma reconstruct - /// to walk the tree's own leaf list, so mixed trees now decode. This - /// census sweeps the quantiser across the exact-repetition recipe that - /// reaches the tree at all and requires the tree to actually be read - /// (`intrabc_vartx_hits`); it stays as the premise witness for the lifted - /// refusal (`reached` is 0 by construction now). - #[test] - fn an_intrabc_vartx_census_measures_the_mixed_leaf_refusal() { - const NAME: &str = "an_intrabc_vartx_census_measures_the_mixed_leaf_refusal"; - if !have_ffmpeg() || !have_aomenc() { - eprintln!("SKIP {NAME}: no ffmpeg/aomenc"); - return; - } - let (width, height) = (256usize, 192usize); - let _guard = lock_gate_counters(); - let (mut vartx_total, mut reached, mut frames_compared) = (0usize, 0u32, 0u32); - for cq in ["20", "30", "45", "55"] { - let arm = format!("vartx cq={cq}"); - let stream = - screen_intrabc_stream("smptebars=size=128x96:rate=25", cq, "1", true, true); - let (select, premise) = tx_select_and_intrabc_frames(&stream); - crate::decode::reset_intrabc_vartx_hits(); - match decode_stream(&stream) { - Ok(frames) => { - let vartx = crate::decode::intrabc_vartx_hits(); - vartx_total += vartx; - // The ENCODE's frame count: `screen_intrabc_stream` (12679) - // renders `smptebars=size=128x96:rate=25` with `-t 0.2` and - // `-vf tile=2x2` (12066, 12069) -- 5 frames in, 1 tiled frame - // out -- and its aomenc runs with `--limit=1` (12101), so all - // four cq arms code exactly 1 frame. The census is - // report-only about the COUNTS, but its Ok arm does assert - // pixel-exactness, so the budget it hands ffmpeg is pinned - // here rather than derived from the decode under test. - assert_eq!(frames.len(), 1, "{NAME}: {arm} key frame"); - let theirs = ffmpeg_decode_sequence(&stream, width, height, frames.len()); - assert_eq!(frames.len(), theirs.len(), "{NAME}: {arm} frame count"); - for (i, (ours, ref_frame)) in frames.iter().zip(theirs.iter()).enumerate() { - assert!( - ours.y == ref_frame.y && ours.u == ref_frame.u && ours.v == ref_frame.v, - "{NAME}: {arm} frame {i} does not match ffmpeg" - ); - frames_compared += 1; - } - eprintln!( - "{NAME}: {arm} select={select} premise={premise} vartx_blocks={vartx} \ - DECODED {} frame(s) exact", - frames.len() - ); - } - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME}: {arm} decode failed: {e}" - ); - vartx_total += crate::decode::intrabc_vartx_hits(); - if msg.contains("mixed leaf transform sizes") { - reached += 1; - } - eprintln!("{NAME}: {arm} select={select} premise={premise} REFUSED: {e}"); - } - } - } - eprintln!( - "{NAME}: {vartx_total} intrabc block(s) read the var-tx tree, {reached} resolved to \ - mixed leaves, {frames_compared} frame(s) exact" - ); - assert!( - vartx_total > 0, - "{NAME}: census is vacuous -- no intrabc block read the var-tx tree at all" - ); - assert_eq!( - reached, 0, - "{NAME}: an intrabc var-tx tree was REFUSED -- the mixed-leaf refusal \ - is lifted (lane-av1-ibcvtx) and must stay gone" - ); - } - - /// lane-av1-ibcvtx, capability gate for the LIFTED refusal "an intrabc - /// block whose var-tx tree resolved to mixed leaf transform sizes": the - /// t900 r33 census recipe class (screen content, square partitions, - /// tx-size search) reaches mixed trees the moment the canvas carries - /// testsrc2's texture and blocks grow past 32 -- on the PRE-fix tree this - /// exact stream refused by name on its first mixed tree (5 of the 12 - /// hunt recipes hit it, `lanes/av1ibcvtx.report.md`). - /// - /// The luma reconstruct walks the tree's own leaf list per leaf (libaom - /// `decode_token_recon_block`), and the block's chroma inherits the - /// co-located luma unit's coded tx type (`av1_get_tx_type`, - /// `blockd.h:1278`) -- the inheritance the uniform multi-TU intrabc path - /// was missing as well: symbol-aligned against an instrumented aomdec, - /// the 640x360 cq20 witness desynced inside the FIRST chroma unit of its - /// first mixed tree until the arm landed, then matched every subsequent - /// read. - /// - /// NOT yet asserted: full pixel-exactness against ffmpeg. A second, - /// PRE-EXISTING defect that is not this refusal -- a NON-intrabc intra - /// block (R5 witness: mi (32,32), 64x64, uniform 4x TX_32X32 tree, every - /// coefficient all_zero, reads symbol-identical to aomdec) mispredicts - /// isolated samples on testsrc2 content (first divergence px (128,296) - /// of the 640x360 cq20 recipe) and cascades over roughly a third of the - /// frame. It is pinned in `lanes/av1ibcvtx.report.md`; when it lands, - /// tighten this gate to a full pixel-exact assert. - #[test] - fn a_real_aomenc_intrabc_mixed_vartx_tree_decodes_without_the_mixed_leaf_refusal() { - const NAME: &str = - "a_real_aomenc_intrabc_mixed_vartx_tree_decodes_without_the_mixed_leaf_refusal"; - if !have_ffmpeg() || !have_aomenc() { - eprintln!("SKIP {NAME}: no ffmpeg/aomenc"); - return; - } - let (width, height) = (640usize, 360usize); - let _guard = lock_gate_counters(); - let stream = screen_intrabc_stream_with( - "testsrc2=size=320x180:rate=25", - "30", - "1", - true, - true, - &["--max-partition-size=64"], - ); - let (select, premise) = tx_select_and_intrabc_frames(&stream); - assert!( - premise > 0, - "{NAME}: vacuous -- no frame keeps allow_intrabc under TxMode::Select, \ - so the refusal's premise was never within reach (select={select})" - ); - crate::decode::reset_intrabc_vartx_hits(); - crate::decode::reset_intrabc_vartx_mixed_leaves_hits(); - match decode_stream(&stream) { - Ok(frames) => { - let trees = crate::decode::intrabc_vartx_hits(); - let mixed = crate::decode::intrabc_vartx_mixed_leaves_hits(); - assert!( - trees > 0 && mixed > 0, - "{NAME}: vacuous -- {trees} var-tx tree(s), {mixed} mixed: the \ - capability this gate pins was never exercised" - ); - // The ENCODE's frame count: `screen_intrabc_stream_with` (12766) - // renders `testsrc2=size=320x180:rate=25` with `-t 0.2` and - // `-vf tile=2x2` (12066, 12069) -- 5 frames in, 1 tiled frame out - // at 640x360 -- and its aomenc runs with `--limit=1` (12101), so - // the stream codes exactly 1 frame. Asserted ABOVE the call. - assert_eq!(frames.len(), 1, "{NAME}: key frame"); - let theirs = ffmpeg_decode_sequence(&stream, width, height, frames.len()); - assert_eq!(frames.len(), theirs.len(), "{NAME}: frame count"); - let mut mismatched = 0usize; - for (i, (ours, ref_frame)) in frames.iter().zip(theirs.iter()).enumerate() { - // A size mismatch makes every number this ladder prints - // meaningless -- the `zip` walks below would truncate to the - // shorter plane and report a clean ladder over what is - // really a plane-shape defect -- so it is LOUD. A PIXEL - // mismatch stays report-only: this gate deliberately - // tolerates the pinned second defect (see the doc comment). - for (plane, a, b) in [ - ("Y", &ours.y, &ref_frame.y), - ("U", &ours.u, &ref_frame.u), - ("V", &ours.v, &ref_frame.v), - ] { - assert_eq!( - a.len(), - b.len(), - "{NAME}: frame {i} plane {plane}: ours has {} samples, ffmpeg's has \ - {} -- a size mismatch makes this whole diagnostic ladder \ - meaningless, so it is loud while a pixel mismatch stays \ - report-only", - a.len(), - b.len() - ); - } - mismatched += ours - .y - .iter() - .zip(ref_frame.y.iter()) - .filter(|(x, y)| x != y) - .count(); - mismatched += ours - .u - .iter() - .zip(ref_frame.u.iter()) - .filter(|(x, y)| x != y) - .count(); - mismatched += ours - .v - .iter() - .zip(ref_frame.v.iter()) - .filter(|(x, y)| x != y) - .count(); - } - eprintln!( - "{NAME}: select={select} premise={premise} vartx_blocks={trees} \ - mixed_trees={mixed}, {mismatched} sample(s) differ from ffmpeg \ - (the pinned non-intrabc second defect, see the doc comment)" - ); - } - Err(e) => panic!( - "{NAME}: the mixed-leaf refusal is lifted (lane-av1-ibcvtx); the \ - witness stream must decode, not stop: {e}" - ), - } - } - - /// lane-t900 r31, CENSUS for the refusal "an intrabc block under - /// TxMode::Select" -- which this gate DISPROVES as an "no encoder writes - /// one" claim and pins as a real capability gap instead. - /// - /// The premise is reachable by the SPEC: `tx_mode` (5.9.21) is forced to - /// `ONLY_4X4` only under `CodedLossless`, while `allow_intrabc` (5.9.2) - /// needs `allow_screen_content_tools` at unscaled resolution -- two - /// independent conditions. libaom leaves it open too: `select_tx_mode` - /// (encodeframe.c:2355) never consults `allow_intrabc`, and the only - /// downgrade to `TX_MODE_LARGEST` is `txb_split_count == 0` - /// (encodeframe.c:2690). - /// - /// The measurement over 14 real `--tune-content=screen --enable-intrabc=1` - /// recipes: - /// - /// * the 10 non-repeating arms never present the premise at all -- with - /// `--enable-tx-size-search=1` the frame codes `TX_MODE_SELECT` but RD - /// never picks intrabc, so libaom clears `allow_intrabc` again; with - /// `=0` intrabc IS used and the frame is `TX_MODE_LARGEST`. That - /// correlation, not any rule, is why earlier rounds never saw this; - /// * the four EXACT-REPETITION arms (a 2x2 tiling of one 128x96 bar - /// pattern) all code `allow_intrabc && tx_mode == Select`. Two of them - /// stop on the older rect-strip intrabc refusal (the shape that fires - /// first, class `refusal-hides-a-defect`), and the two with rect/1:4 - /// partitions off put intrabc on a SQUARE block: `cq=30` reaches THIS - /// refusal by name, `cq=45`'s intrabc blocks are all `skip` and decode - /// pixel-exact against ffmpeg. - /// - /// So the refusal is correct and load-bearing, exactly one arm reaches it, - /// and the lift it names has a waiting witness: - /// [`an_intrabc_block_under_tx_mode_select_decodes_pixel_exact`] (ignored - /// until the intra path reads the inter var-tx tree for an intrabc block). - #[test] - fn an_intrabc_census_over_screen_key_frames_measures_the_tx_select_refusal() { - const NAME: &str = - "an_intrabc_census_over_screen_key_frames_measures_the_tx_select_refusal"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - const TS: &str = "testsrc2=s=256x192:r=25"; - const SB: &str = "smptebars=size=256x192:rate=25"; - const PB: &str = "pal75bars=size=256x192:rate=25"; - const TILE: &str = "smptebars=size=128x96:rate=25"; - let (width, height) = (256usize, 192usize); - // (arm, source, cq, tx-size-search, tiled, square_only) - let arms: [(&str, &str, &str, &str, bool, bool); 14] = [ - ("smptebars-cq40-txs1", SB, "40", "1", false, false), - ("smptebars-cq45-txs1", SB, "45", "1", false, false), - ("smptebars-cq55-txs1", SB, "55", "1", false, false), - ("smptebars-cq63-txs1", SB, "63", "1", false, false), - ("pal75bars-cq40-txs1", PB, "40", "1", false, false), - ("pal75bars-cq55-txs1", PB, "55", "1", false, false), - ("testsrc2-cq50-txs1", TS, "50", "1", false, false), - ("testsrc2-cq63-txs1", TS, "63", "1", false, false), - ("smptebars-cq45-txs0", SB, "45", "0", false, false), - ("pal75bars-cq45-txs0", PB, "45", "0", false, false), - ("tiled-cq30-txs1", TILE, "30", "1", true, false), - ("tiled-cq45-txs1", TILE, "45", "1", true, false), - ("tiled-square-cq30-txs1", TILE, "30", "1", true, true), - // lane-t900 r32: both square arms are now ORDINARY census members - // -- cq30 (unskipped intrabc, the inter var-tx tree) and cq45 - // (all-skip intrabc, `maxRectTxSize` with no symbol at all) decode - // pixel-exact, so nothing here reaches the lifted refusal. - ("tiled-square-cq45-txs1", TILE, "45", "1", true, true), - ]; - let (mut select_arms, mut premise_arms, mut intrabc_arms, mut blocks_total) = - (0u32, 0u32, 0u32, 0usize); - let (mut refused_tx_select, mut frames_compared) = (0u32, 0usize); - for (arm, src, cq, txs, tiled, square_only) in &arms { - let stream = screen_intrabc_stream(src, cq, txs, *tiled, *square_only); - let (select, premise) = tx_select_and_intrabc_frames(&stream); - if select > 0 { - select_arms += 1; - } - if premise > 0 { - premise_arms += 1; - } - crate::decode::reset_intrabc_hits(); - let decoded = decode_stream(&stream); - let blocks = crate::decode::intrabc_hits(); - blocks_total += blocks; - if blocks > 0 { - intrabc_arms += 1; - } - match decoded { - Ok(frames) => { - assert!(!frames.is_empty(), "{NAME}: {arm} decoded no frame"); - let theirs = ffmpeg_decode_sequence(&stream, width, height, frames.len()); - assert_eq!(frames.len(), theirs.len(), "{NAME}: {arm} frame count"); - for (i, (ours, ref_frame)) in frames.iter().zip(theirs.iter()).enumerate() { - assert!( - ours.y == ref_frame.y && ours.u == ref_frame.u && ours.v == ref_frame.v, - "{NAME}: {arm} frame {i} does not match ffmpeg" - ); - frames_compared += 1; - } - eprintln!( - "{NAME}: {arm} select={select} premise={premise} {blocks} intrabc \ - block(s), {} frame(s) exact", - frames.len() - ); - } - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME}: {arm} decode failed: {e}" - ); - if msg.contains("an intrabc block under TxMode::Select") { - refused_tx_select += 1; - assert!( - premise > 0, - "{NAME}: {arm} reached the TxMode::Select intrabc refusal in a \ - frame that codes no such header" - ); - } else { - assert!( - msg.contains("intra block copy"), - "{NAME}: {arm} refused for an unrelated reason: {e}" - ); - } - eprintln!("{NAME}: {arm} select={select} premise={premise} REFUSED: {e}"); - } - } - } - eprintln!( - "{NAME}: {select_arms}/{n} arm(s) code a TX_MODE_SELECT frame, {premise_arms} of \ - those keep allow_intrabc, {intrabc_arms} arm(s) decode an intrabc block \ - ({blocks_total} total), {refused_tx_select} reach the refusal, \ - {frames_compared} frame(s) compared exact", - n = arms.len() - ); - assert!( - intrabc_arms > 0 && blocks_total > 0, - "{NAME}: census is vacuous -- no arm decoded an intrabc block at all" - ); - assert!( - premise_arms > 0, - "{NAME}: census is vacuous -- no arm coded a frame with both allow_intrabc and \ - tx_mode == Select, so the refusal's own premise was never within reach" - ); - assert_eq!( - refused_tx_select, 0, - "{NAME}: lane-t900 r32 lifted this refusal -- an intrabc block now reads the \ - INTER tx-size syntax, so no arm may reach it again" - ); - assert!( - frames_compared > 0, - "{NAME}: no frame was compared pixel-exact" - ); - } - - /// lane-t900 r31, the WAITING witness for the capability - /// [`an_intrabc_census_over_screen_key_frames_measures_the_tx_select_refusal`] - /// pins: a real aomenc screen key frame whose intrabc block sits on a - /// square block of a `TX_MODE_SELECT` frame, unskipped. libaom's - /// `parse_decode_block` treats an intrabc block as `inter_block_tx`, so - /// its transform size comes off the inter var-tx partition tree - /// (`read_var_tx_size`), which this decoder reads nowhere on the intra - /// path -- reading the intra `tx_depth` symbol instead desyncs. - /// - /// lane-t900 r32 closed both arms. A SKIPPED intrabc block reads no - /// tx-size symbol at all (`allowSelect = !skip || !is_inter`, false for an - /// intrabc block since libaom's `is_inter_block` counts one); reading the - /// intra `tx_depth` for it consumed a symbol libaom never wrote and - /// desynced the tile a whole block later, at the superblock corner - /// (192,64) (class `equal-range-means-unread`). An UNSKIPPED one reads the - /// inter var-tx tree (`read_var_tx_size`). r31's note that cq=45's blocks - /// are all `skip` was read off that desynced decode: with the tx-size read - /// corrected, cq=45 carries 3 unskipped intrabc blocks of 10 and cq=30 - /// carries 1 of 16, so both arms exercise both sides of the split. - #[test] - fn an_intrabc_block_under_tx_mode_select_decodes_pixel_exact() { - const NAME: &str = "an_intrabc_block_under_tx_mode_select_decodes_pixel_exact"; - if !have_ffmpeg() || !have_aomenc() { - eprintln!("SKIP {NAME}: no ffmpeg/aomenc"); - return; - } - let (width, height) = (256usize, 192usize); - for cq in ["30", "45"] { - let stream = - screen_intrabc_stream("smptebars=size=128x96:rate=25", cq, "1", true, true); - let (select, premise) = tx_select_and_intrabc_frames(&stream); - assert!( - select > 0 && premise > 0, - "{NAME}: cq={cq} no longer codes allow_intrabc under TX_MODE_SELECT \ - (select={select} premise={premise})" - ); - crate::decode::reset_intrabc_hits(); - crate::decode::reset_intrabc_vartx_hits(); - let frames = decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME}: cq={cq}: {e}")); - let (blocks, vartx) = ( - crate::decode::intrabc_hits(), - crate::decode::intrabc_vartx_hits(), - ); - assert!( - blocks > 0, - "{NAME}: cq={cq} no longer decodes an intrabc block" - ); - // r31 recorded cq=45's intrabc blocks as ALL skip; that was read - // off the desynced decode. With the tx-size read corrected both - // arms carry unskipped ones (cq30 1 of 16, cq45 3 of 10), so both - // must reach the var-tx tree or the gate is blind to the lift - // (class `gate-blind-to-feature`). - assert!( - vartx > 0, - "{NAME}: cq={cq} no longer reads the inter var-tx tree for an intrabc block" - ); - eprintln!("{NAME}: cq={cq} {blocks} intrabc block(s), {vartx} through var-tx"); - // The ENCODE's frame count: `screen_intrabc_stream` (12022) renders - // `smptebars=size=128x96:rate=25` with `-t 0.2` and `-vf tile=2x2` - // (12066, 12069) -- 5 frames in, 1 tiled frame out -- and its aomenc - // runs with `--limit=1` (12101), so both cq arms code exactly 1 - // frame. Asserted ABOVE the oracle call. - assert_eq!(frames.len(), 1, "{NAME}: cq={cq} key frame"); - let theirs = ffmpeg_decode_sequence(&stream, width, height, frames.len()); - assert_eq!(frames.len(), theirs.len(), "{NAME}: cq={cq} frame count"); - for (i, (ours, ref_frame)) in frames.iter().zip(theirs.iter()).enumerate() { - assert!( - ours.y == ref_frame.y && ours.u == ref_frame.u && ours.v == ref_frame.v, - "{NAME}: cq={cq} frame {i} does not match ffmpeg" - ); - } - } - } - - /// lane-av1txr: a real `aomenc --cdf-update-mode=0` stream (spec 5.9.2 - /// `disable_cdf_update`) decodes SAMPLE-EXACT. The read that was missing: - /// `stream.rs` never threaded the header bit, so the tile readers adapted - /// every symbol of a frame the encoder coded against fixed tables -- the - /// stream desynced at its first multi-symbol block and the pixels differed - /// from byte 6 (`EC_PROBE_OUT` vs `ffmpeg -pix_fmt yuv420p`, measured - /// 2026-09-20). The msac unit gate - /// (`a_reader_told_not_to_adapt_matches_a_non_adapting_writer`) pins the - /// mechanism; this one pins the wiring end to end. - #[test] - fn a_real_aomenc_stream_with_cdf_update_disabled_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_stream_with_cdf_update_disabled_decodes_pixel_exact"; - if !have_ffmpeg() || !have_aomenc() { - eprintln!("SKIP {NAME}: no ffmpeg/aomenc"); - return; - } - let (width, height) = (256usize, 192usize); - let stream = screen_intrabc_stream_with( - "testsrc2=size=256x192:rate=25", - "45", - "1", - false, - true, - &["--cdf-update-mode=0", "--limit=3"], - ); - // Non-vacuity: the fixture must really code the bit on every frame. - let mut parser = Av1Parser::new(); - let mut pos = 0usize; - let mut headers = 0usize; - while pos < stream.len() { - let Ok(obu) = parser.parse_obu(&stream[pos..]) else { - break; - }; - pos += obu.total_size.max(1); - let header = match &obu.kind { - ObuKind::Frame(h, _) | ObuKind::FrameHeader(h) => h, - _ => continue, - }; - assert!( - header.disable_cdf_update, - "{NAME}: frame {headers} does not carry disable_cdf_update -- aomenc ignored \ - --cdf-update-mode=0" - ); - headers += 1; - } - assert!( - headers >= 3, - "{NAME}: only {headers} frame headers in the fixture" - ); - let frames = decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME}: {e}")); - // The frame count, and it comes from the WIRE, not from our decode: the - // loop above parsed this stream's own OBU frame headers with - // `Av1Parser` and counted `headers` of them (>= 3, from the arm's - // `--limit=3` at 13127, which overrides the helper's `--limit=1` because - // aomenc keeps the last occurrence of a repeated flag). Asserted ABOVE - // the oracle call, so a decode that showed fewer frames than the bitstream - // codes reds naming the wire instead of asking ffmpeg for the same short - // count. Deriving it from `headers` rather than a literal keeps the pin - // honest if aomenc's frame count ever drifts. - assert_eq!( - frames.len(), - headers, - "{NAME}: the stream codes {headers} frame(s), the decode showed {}", - frames.len() - ); - let theirs = ffmpeg_decode_sequence(&stream, width, height, frames.len()); - assert_eq!(frames.len(), theirs.len(), "{NAME}: frame count"); - for (i, (ours, ref_frame)) in frames.iter().zip(theirs.iter()).enumerate() { - assert!( - ours.y == ref_frame.y && ours.u == ref_frame.u && ours.v == ref_frame.v, - "{NAME}: frame {i} does not match ffmpeg" - ); - } - eprintln!("{NAME}: {headers} disable_cdf_update frame headers, all frames sample-exact"); - } - - /// lane-kf900 r4, the gate for the two lifted palette refusals ("a 1:4 - /// rect strip that actually uses a palette (reconstruction is not ported - /// at this shape)" and "a palette block on a HORZ/VERT intra strip below - /// 16x16 (reconstruction not ported)"): real `aomenc` streams that put a - /// palette on a RECT strip, decoded whole-frame pixel-exact against - /// ffmpeg's own decode of the identical bytes, at 8 AND 10 bit. - /// - /// Arm 0 is the stream lane-kf900 r3 pinned and stopped on -- `testsrc2` - /// 256x192, `--cq-level=59 --cpu-used=0 --min-partition-size=8 - /// --enable-rect-partitions=1 --enable-tx-size-search=1`, md5 - /// `e5f033d8fe34e4418d8cca3ac9d2b595` at 10 bit. Arms 1-2 force the shape - /// on screen-like content with `--tune-content=screen --enable-palette=1 - /// --enable-1to4-partitions=1`. - /// - /// An attempt whose decode never hit a rect-strip palette block proves - /// nothing about the lift, so it is counted OUT OF SCOPE rather than - /// silently passing -- but a mismatch on one is still a failure - /// (`out_of_scope_mismatch == 0`), and at least one attempt must fire the - /// counter or the gate is vacuous. - #[test] - fn a_real_aomenc_rect_strip_palette_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_rect_strip_palette_decodes_pixel_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height) = (256usize, 192usize); - let screen: &[&str] = &[ - "--tune-content=screen", - "--enable-palette=1", - "--enable-1to4-partitions=1", - "--min-partition-size=8", - ]; - // lane-kf900 r6: arms 3-4 are the palette + `--enable-tx-size-search=1` - // shape whose neighbour palette lookup was SUB-granular -- a 16x8 strip - // pair shares one 16px cell, so strip 1 read strip 0's palette size and - // the colour cache came out short. Both were whole-frame wrong before - // the mi-granular fix (`$HOME/.cache/kf900-r6/sweep.log`: smptebars - // cq40/cq55 txs=1 pal=1 = DIFF). - let screen_txs: &[&str] = &[ - "--tune-content=screen", - "--enable-palette=1", - "--enable-1to4-partitions=1", - "--min-partition-size=8", - "--max-partition-size=32", - "--sb-size=64", - "--enable-intrabc=1", - "--enable-tx-size-search=1", - ]; - let cq40: Vec<&str> = screen_txs - .iter() - .copied() - .chain(["--cq-level=40"]) - .collect(); - let cq55: Vec<&str> = screen_txs - .iter() - .copied() - .chain(["--cq-level=55"]) - .collect(); - let arms: [(&str, String, &[&str]); 5] = [ - ( - "testsrc2-pinned", - "testsrc2=s=256x192:r=25".to_string(), - &[], - ), - ( - "testsrc2-screen", - "testsrc2=s=256x192:r=25".to_string(), - screen, - ), - ( - "smptebars-screen", - "smptebars=size=256x192:rate=25".to_string(), - screen, - ), - ( - "smptebars-screen-txs-cq40", - "smptebars=size=256x192:rate=25".to_string(), - &cq40, - ), - ( - "smptebars-screen-txs-cq55", - "smptebars=size=256x192:rate=25".to_string(), - &cq55, - ), - ]; - let (mut fired_arms, mut out_of_scope, mut out_of_scope_mismatch) = (0u32, 0u32, 0u32); - let mut refused = 0u32; - let mut fired_at_depth = [0u32; 2]; - let mut frames_compared = 0usize; - for (arm, src, extra) in &arms { - for depth in [8usize, 10] { - let pix_fmt = if depth == 10 { - "yuv420p10le" - } else { - "yuv420p" - }; - let render = || { - let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - src.as_str(), - "-t", - "0.2", - "-pix_fmt", - pix_fmt, - "-strict", - "-1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!(out.status.success(), "{NAME}: ffmpeg failed for {arm}"); - out.stdout - }; - let y4m_a = render(); - let y4m_b = render(); - assert_eq!( - y4m_a, y4m_b, - "{NAME}: {arm} must render byte-identical across two runs at {depth}-bit" - ); - let y4m = y4m_a; - let depth_arg = format!("--bit-depth={depth}"); - let in_depth_arg = format!("--input-bit-depth={depth}"); - let out = run_with_stdin( - Command::new(aomenc_path()) - .args(["--codec=av1"]) - .args([&depth_arg, &in_depth_arg]) - .args([ - "--passes=1", - "--end-usage=q", - "--cq-level=59", - "--cpu-used=0", - "--lag-in-frames=0", - "--kf-max-dist=1", - "--limit=1", - "--threads=1", - "--tile-columns=0", - "--enable-tx-size-search=1", - "--min-partition-size=8", - "--enable-rect-partitions=1", - ]) - // Per-arm overrides go AFTER the base recipe: aomenc keeps - // the LAST occurrence of a repeated flag. - .args(*extra) - // The 8-bit twin of the pinned recipe picks a 128-root - // HORZ partition, which this decoder still refuses by name - // ("a 128x128 superblock HORZ/VERT or AB partition") -- - // an open refusal of another lane, unrelated to palette. - // Pinning the superblock to 64 keeps the 8-bit arm on the - // shape this gate is about; the 10-bit arms are the - // untouched pinned recipe. - .args(if depth == 8 { - &["--sb-size=64"][..] - } else { - &[][..] - }) - .args(["--obu", "-o", "-", "-"]), - &y4m, - ); - assert!( - out.status.success(), - "{NAME}: aomenc refused {arm} at {depth}-bit: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let before = decode::rect4_palette_hits(); - let frames = match decode_stream(&stream) { - Ok(frames) => frames, - // A NAMED refusal is another lane's open shape (here: a - // palette on an 8x8 SQUARE leaf, still out of scope), never - // a pass -- the attempt is counted out of scope and the - // per-depth firing assert below keeps the gate honest. - Err(e) if e.to_string().contains("unsupported") => { - eprintln!("{NAME}: {arm} {depth}-bit REFUSED: {e}"); - refused += 1; - continue; - } - Err(e) => panic!("{NAME}: decode failed on {arm} at {depth}-bit: {e}"), - }; - let fired = decode::rect4_palette_hits() - before; - // The ENCODE's frame count, asserted ABOVE the oracle call: the - // y4m renders 5 frames (`-t 0.2` at every arm's `rate=25`, - // 13275) but aomenc is given `--limit=1` (13313), so the stream - // codes exactly 1 frame at both depths on every arm. Asserted - // here it is NOT the tautology the old comment below claimed: - // `frames.len() == 1` is a fact about the encode, checked before - // `frames.len()` is spent as ffmpeg's frame budget. - assert_eq!(frames.len(), 1, "{NAME}: {arm} at {depth}-bit key frame"); - let ffmpeg_frames = if depth == 10 { - ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len()) - } else { - ffmpeg_decode_sequence(&stream, width, height, frames.len()) - }; - assert!( - !frames.is_empty(), - "{NAME}: {arm} at {depth}-bit decoded no frame" - ); - // EVERY decode-order frame, all three planes. - let mut exact = true; - for (i, (ours, theirs)) in frames.iter().zip(ffmpeg_frames.iter()).enumerate() { - if ours.y != theirs.y || ours.u != theirs.u || ours.v != theirs.v { - exact = false; - eprintln!("{NAME}: {arm} {depth}-bit frame {i} differs"); - } - frames_compared += 1; - } - if fired > 0 { - fired_arms += 1; - fired_at_depth[usize::from(depth == 10)] += 1; - assert!( - exact, - "{NAME}: {arm} at {depth}-bit has {fired} rect-strip palette block(s) \ - and does NOT decode pixel-exact" - ); - } else { - out_of_scope += 1; - if !exact { - out_of_scope_mismatch += 1; - } - } - } - } - eprintln!( - "{NAME}: {fired_arms} attempt(s) with a rect-strip palette block, \ - {out_of_scope} out of scope ({out_of_scope_mismatch} mismatched), \ - {refused} refused, {frames_compared} frames compared, \ - fired 8-bit={} 10-bit={}", - fired_at_depth[0], fired_at_depth[1] - ); - // MEASURED 2026-09-02, every 8-bit attempt of these recipes: aomenc - // puts its palettes on SQUARE blocks at 8 bit and every 8-bit stream - // that reaches a rect strip with one lands on a palette shape still - // out of scope (8x8 square leaf, or a 64x32/32x64 superblock strip - // with a real transform). So the 8-bit arms here prove the DECODE - // path, not the lift -- `fired_at_depth[0] == 0` is a known, reported - // coverage gap and not a silent pass: the counter is printed. - assert!( - fired_at_depth[1] > 0, - "{NAME}: no attempt put a palette on a rect strip \ - (8-bit={}, 10-bit={}) -- gate is vacuous", - fired_at_depth[0], - fired_at_depth[1] - ); - assert!(fired_arms > 0, "{NAME}: gate is vacuous"); - assert_eq!( - out_of_scope_mismatch, 0, - "{NAME}: {out_of_scope_mismatch} attempt(s) without a rect-strip palette block \ - still mismatched -- an unrelated defect, not a SKIP" - ); - } - - /// The 12-bit KEY witness: CDEF and loop restoration ON, grain off. - /// Byte-exact against ffmpeg, and the 12-bit-sensitive pixel paths hard- - /// assert fired: a CDEF index literal read (bits > 0) and at least one - /// Wiener or SGR restoration unit. Gauntlet for the parameterised - /// rounding sites: MC/Wiener round pairs, `coeff_shift = bd - 8` CDEF, - /// the 12-bit dequant tables, bd-scaled SGR box sums. - #[test] - fn a_real_aomenc_12bit_stream_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_12bit_stream_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let y4m = y4m_12bit_subpel_source(1); - let stream = encode_12bit( - &y4m, - 1, - &["--enable-warped-motion=0", "--enable-global-motion=0"], - ); - assert_12bit_sequence_header(&stream, NAME); - let before_cdef = decode::cdef_idx_hits(); - let before_lr = crate::restoration::wiener_hits() + crate::restoration::sgrproj_hits(); - let frames = decode_stream(&stream).unwrap_or_else(|e| { - panic!("{NAME}: decode_stream refused a real 12-bit key frame: {e}") - }); - assert_eq!(frames.len(), 1); - assert!( - decode::cdef_idx_hits() > before_cdef, - "{NAME}: no CDEF index literal was read -- CDEF is not exercised" - ); - assert!( - crate::restoration::wiener_hits() + crate::restoration::sgrproj_hits() > before_lr, - "{NAME}: no loop restoration unit was decoded -- LR is not exercised" - ); - let ffmpeg_frames = ffmpeg_decode_sequence_12bit(&stream, 160, 128, 1); - assert_eq!( - frames[0].y, ffmpeg_frames[0].y, - "luma vs ffmpeg (12-bit key)" - ); - assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (12-bit key)"); - assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (12-bit key)"); - } - - /// The 12-bit INTER witness: a key frame plus one P frame over sub-pixel - /// true motion. Byte-exact against ffmpeg; hard-asserts the two-pass - /// SUBPEL prediction path ran (`MC_SUBPEL_HITS`), so the frame's own - /// `round_0`/`round_1` -- 5/9 at 12 bits, the whole point of the mc.rs - /// parameterisation -- really executed, and asserts - /// `compound_mode_hits` UNCHANGED (this recipe offers no divergent - /// second reference, so no compound mode symbol is read -- the lane's - /// compound witness is the six-frame gate below). - #[test] - fn a_real_aomenc_12bit_inter_sequence_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_12bit_inter_sequence_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let y4m = y4m_12bit_subpel_source(2); - let stream = encode_12bit( - &y4m, - 2, - &["--enable-warped-motion=0", "--enable-global-motion=0"], - ); - assert_12bit_sequence_header(&stream, NAME); - let before_subpel = crate::mc::mc_subpel_hits(); - let before_compound = decode::compound_mode_hits(); - let frames = decode_stream(&stream).unwrap_or_else(|e| { - panic!("{NAME}: decode_stream refused a real 12-bit inter stream: {e}") - }); - assert_eq!(frames.len(), 2); - assert!( - crate::mc::mc_subpel_hits() > before_subpel, - "{NAME}: no subpel inter prediction decoded -- the 12-bit round pair is unexercised" - ); - assert_eq!( - decode::compound_mode_hits(), - before_compound, - "{NAME}: a compound mode symbol was read -- the single-reference premise is gone" - ); - let ffmpeg_frames = ffmpeg_decode_sequence_12bit(&stream, 160, 128, 2); - for (i, (ours, reference)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!( - ours.y, reference.y, - "frame {i} luma vs ffmpeg (12-bit inter)" - ); - assert_eq!(ours.u, reference.u, "frame {i} U vs ffmpeg (12-bit inter)"); - assert_eq!(ours.v, reference.v, "frame {i} V vs ffmpeg (12-bit inter)"); - } - } diff --git a/crates/ec-av1/src/stream/tests/t04.rs b/crates/ec-av1/src/stream/tests/t04.rs deleted file mode 100644 index 010dbaa4..00000000 --- a/crates/ec-av1/src/stream/tests/t04.rs +++ /dev/null @@ -1,4516 +0,0 @@ -use super::*; -use super::support::*; -use super::gates_a::*; -use crate::probe::run_with_stdin; -use std::process::{Command, Stdio}; - - /// The 12-bit WARP witness (lane-av112bitw): the same source and recipe - /// with the warp tools ON -- aomenc picks warp models on this content - /// (measured pre-lift: the warp model fires at the third frame, and the - /// decode refused by name at exactly that block) -- now decodes - /// BYTE-EXACT against ffmpeg. The warp filter's shifts are the bumped - /// `conv_params->round_0` (`warp::warp_round_0`, 5 at 12 bits, feeding - /// `reduce_bits_horiz`, the derived non-compound - /// `reduce_bits_vert = 2*FILTER_BITS - round_0` and both `offset_bits`), - /// the whole libaom `get_conv_params_no_round` 12-bit bump. - /// - /// Non-vacuous: the same recipe refused by name before the lift, the - /// gate hard-asserts a warp predictor was really resolved (a warpless - /// stream would pass the pixel compare and prove nothing), and every - /// plane of every frame compares against ffmpeg's decode. - #[test] - fn a_12bit_warped_motion_stream_decodes_pixel_exact() { - const NAME: &str = "a_12bit_warped_motion_stream_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let y4m = y4m_12bit_subpel_source(6); - // Exactly the recipe measured to refuse at warp pre-lift: warp ON, - // global motion NOT spelled (spelling it ON drives a GLOBAL_GLOBALMV - // compound block into the compound-warp arm -- see the compound gate - // below), six frames -- the warp model fires at the third frame. - let stream = encode_12bit(&y4m, 6, &["--enable-warped-motion=1"]); - assert_12bit_sequence_header(&stream, NAME); - let (before_selected, before_warp8, before_affine) = ( - decode::warp_selected_hits(), - decode::warp_hits_8(), - decode::affine_gm_hits(), - ); - let frames = decode_stream(&stream).unwrap_or_else(|e| { - panic!("{NAME}: decode_stream refused a real 12-bit warp stream: {e}") - }); - assert_eq!(frames.len(), 6); - let (delta_selected, delta_warp8, delta_affine) = ( - decode::warp_selected_hits() - before_selected, - decode::warp_hits_8() - before_warp8, - decode::affine_gm_hits() - before_affine, - ); - eprintln!( - "{NAME}: warp_engagement selected(16x16+ symbol)={delta_selected} \ - warped8(usable 8x8 model)={delta_warp8} affine_gm(6-param model)={delta_affine}" - ); - assert!( - delta_selected + delta_warp8 + delta_affine > 0, - "{NAME}: no warp predictor was resolved -- the stream carries no \ - warp model and the pixel compare would prove nothing" - ); - let ffmpeg_frames = ffmpeg_decode_sequence_12bit(&stream, 160, 128, 6); - for (i, (ours, reference)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!( - ours.y, reference.y, - "frame {i} luma vs ffmpeg (12-bit warp)" - ); - assert_eq!(ours.u, reference.u, "frame {i} U vs ffmpeg (12-bit warp)"); - assert_eq!(ours.v, reference.v, "frame {i} V vs ffmpeg (12-bit warp)"); - } - } - - /// The 12-bit COMPOUND witness (lane-av112bitc): the parent's source - /// and recipe with warp pinned OFF -- with six frames LAST diverges - /// from GOLDEN from frame 2 on and aomenc codes compound inter blocks - /// (pre-lift measurement: the decode refused at the compound mode - /// read). Two arms: the default recipe (dist-weighted average - /// combines live) and `--enable-dist-wtd-comp=0` (pushes compound AND - /// the masked choice harder: 6 diffwtd blends). Both byte-exact - /// against ffmpeg; each hard-asserts compound mode symbols and - /// masked-diffwtd blends really ran, so the parameterised combine - /// rounds (`INTER_POST_ROUND - delta`, diffwtd `+ (bd-8) - delta` at - /// 12 bits) and the ffmpeg-pinned pixel path genuinely executed. - #[test] - fn a_real_aomenc_12bit_compound_inter_sequence_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_12bit_compound_inter_sequence_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let y4m = y4m_12bit_subpel_source(6); - for (arm, extra) in [ - ("dist-wtd", &["--enable-warped-motion=0"][..]), - ( - "plain-masked", - &["--enable-warped-motion=0", "--enable-dist-wtd-comp=0"][..], - ), - ] { - let stream = encode_12bit(&y4m, 6, extra); - assert_12bit_sequence_header(&stream, NAME); - let before_compound = decode::compound_mode_hits(); - let before_masked = decode::masked_compound_hits(); - let before_diffwtd = decode::diffwtd_hits(); - let before_wedge = decode::wedge_hits(); - let frames = decode_stream(&stream).unwrap_or_else(|e| { - panic!("{NAME} [{arm}]: decode_stream refused a real 12-bit compound stream: {e}") - }); - assert_eq!(frames.len(), 6, "{NAME} [{arm}]: frame count"); - let (comp, masked, diffwtd, wedge) = ( - decode::compound_mode_hits() - before_compound, - decode::masked_compound_hits() - before_masked, - decode::diffwtd_hits() - before_diffwtd, - decode::wedge_hits() - before_wedge, - ); - eprintln!( - "{NAME} [{arm}]: compound blocks={comp} masked={masked} diffwtd={diffwtd} wedge={wedge}" - ); - assert!( - comp > 0, - "{NAME} [{arm}]: no compound mode symbol was read -- the compound path is unexercised" - ); - assert!( - masked > 0, - "{NAME} [{arm}]: no masked compound block ran -- the masked combine is unexercised" - ); - assert!( - diffwtd > 0, - "{NAME} [{arm}]: no diffwtd blend ran -- the diffwtd combine is unexercised" - ); - let ffmpeg_frames = ffmpeg_decode_sequence_12bit(&stream, 160, 128, 6); - for (i, (ours, reference)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!( - ours.y, reference.y, - "{NAME} [{arm}] frame {i} luma vs ffmpeg" - ); - assert_eq!(ours.u, reference.u, "{NAME} [{arm}] frame {i} U vs ffmpeg"); - assert_eq!(ours.v, reference.v, "{NAME} [{arm}] frame {i} V vs ffmpeg"); - } - } - } - - /// lane-av112bitg: the 12-bit film grain witness. A real - /// `aomenc --bit-depth=12 --profile=2 --film-grain-test=5` stream -- grain - /// params present AND applied (2 luma + 9 cb + 9 cr scaling points, - /// overlap blending on, clip-to-restricted-range on; the second frame is - /// an INTER frame that inherits the params via `update_grain = 0`) -- - /// decoded byte-exact against ffmpeg's own 12-bit decode of the identical - /// bytes (ffmpeg synthesizes grain by default; no grain-disable flag is - /// passed anywhere in this file). Proves the bit-depth-generic grain path - /// at 12 bits: `grain_range`'s ±(128 << 4) AR clamp and overlap-blend - /// clamp, the `gauss_sec_shift = 12 - bd` Gaussian shift, the 4096-entry - /// expanded scaling-LUT interpolation, and the `<< (bit_depth - 8)` - /// chroma offsets and legal-range clamps. HARD-asserts the parsed headers - /// really carry that coverage and `film_grain::grain_hits()` fired, so - /// neither a params-without-apply stream nor a silently-skipped synthesis - /// can pass vacuously. - #[test] - fn a_real_aomenc_12bit_film_grain_stream_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_12bit_film_grain_stream_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let y4m = y4m_12bit_subpel_source(2); - // Warp stays refused at 12 bits (lane-av112bitg lifts GRAIN only), so - // the arm pins both motion tools off exactly once each -- aomenc - // otherwise picks warped motion on this fixture's sub-pel motion. - let stream = encode_12bit( - &y4m, - 2, - &[ - "--film-grain-test=5", - "--enable-warped-motion=0", - "--enable-global-motion=0", - ], - ); - assert_12bit_sequence_header(&stream, NAME); - // The arm is only honest if the stream itself carries the coverage: - // grain applied on every frame, scaling points on all three planes, - // overlap blending and restricted-range clipping on. - let mut probe = Av1Parser::new(); - let mut pos = 0usize; - let mut grain_frames = 0usize; - while pos < stream.len() { - let obu = probe.parse_obu(&stream[pos..]).unwrap(); - pos += obu.total_size; - if let ObuKind::Frame(header, _) = obu.kind { - let fg = &header.film_grain; - assert!( - fg.apply_grain, - "{NAME}: frame without apply_grain -- aomenc emitted params it does not apply" - ); - assert!( - fg.num_y_points > 0 && fg.num_cb_points > 0 && fg.num_cr_points > 0, - "{NAME}: grain without all three planes' scaling points -- the bit-depth \ - LUT math would not be exercised" - ); - assert!( - fg.overlap_flag, - "{NAME}: overlap off -- the grain_min/grain_max blend clamp is not exercised" - ); - assert!( - fg.clip_to_restricted_range, - "{NAME}: clip_to_restricted_range off -- the << (bd - 8) legal-range clamps \ - are not exercised" - ); - grain_frames += 1; - } - } - assert_eq!(grain_frames, 2, "{NAME}: expected grain on both frames"); - let before = crate::film_grain::grain_hits(); - let frames = decode_stream(&stream).unwrap_or_else(|e| { - panic!("{NAME}: decode_stream refused a real 12-bit grain stream: {e}") - }); - assert_eq!(frames.len(), 2); - assert!( - crate::film_grain::grain_hits() > before, - "{NAME}: matched but zero grain_hits -- grain synthesis never ran" - ); - let ffmpeg_frames = ffmpeg_decode_sequence_12bit(&stream, 160, 128, 2); - for (i, (ours, theirs)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!( - ours.y, theirs.y, - "{NAME}: luma vs ffmpeg (12-bit grain, frame {i})" - ); - assert_eq!( - ours.u, theirs.u, - "{NAME}: U vs ffmpeg (12-bit grain, frame {i})" - ); - assert_eq!( - ours.v, theirs.v, - "{NAME}: V vs ffmpeg (12-bit grain, frame {i})" - ); - } - eprintln!( - "{NAME}: byte-exact, grain_hits={}", - crate::film_grain::grain_hits() - ); - } - - /// lane-av1screen12: a 12-bit PALETTE screen-content stream, palette on - /// and palette-UV on, `allow_intrabc` off. - /// - /// Recipe: `ffmpeg -f lavfi -i testsrc2=s=160x128:r=25 -pix_fmt - /// yuv420p12le -strict -1` (2 frames, 160x128 4:2:0) piped to - /// [`encode_12bit`] with `--tune-content=screen --enable-palette=1 - /// `--enable-intrabc=1`; pin `screen12_palette.obu` (3616 bytes, sha256 - /// `adfe26c67c08a7e986db2743b914ecc3e214c56dd2abbdfd17ebf99f06de64c8`). - /// - /// What it replaces: this is the arm the blanket refusal "a 12-bit frame - /// with screen content tools" blocked while decoding exactly. - #[test] - fn a_real_aomenc_12bit_screen_content_palette_stream_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_12bit_screen_content_palette_stream_decodes_pixel_exact"; - const PIN: &str = "screen12_palette.obu"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - let y4m = y4m_12bit_screen_source("testsrc2=s=160x128:r=25", false); - let live = if have_aomenc() { - encode_12bit( - &y4m, - 2, - &[ - "--tune-content=screen", - "--enable-palette=1", - "--enable-intrabc=1", - ], - ) - } else { - Vec::new() - }; - assert_12bit_screen_content_arm( - NAME, - PIN, - live, - PIN_LEN_PALETTE, - PIN_FNV_PALETTE, - 2, - 160, - 128, - false, - ); - } - - /// lane-av1screen12: a 12-bit screen-content stream whose KEY frame sets - /// `allow_intrabc = 1` and really codes `use_intrabc` blocks. - /// - /// Recipe: [`screen_intrabc_stream_at_depth`] at depth 12 -- the same - /// shape the 8/10-bit intrabc census and the sb128 intrabc witness use: - /// `-vf tile=2x2` over `smptebars=size=128x96:rate=25` (256x192), - /// `--tune-content=screen --enable-intrabc=1 --enable-palette=1 - /// --cq-level=30 --enable-tx-size-search=0 --min-partition-size=8 - /// --max-partition-size=32 --sb-size=64 --kf-max-dist=1 --limit=1`, so - /// ONE 12-bit key frame; pin `screen12_intrabc.obu` (482 bytes, sha256 - /// `a3b6b94cabdd09a12057c4688990d55495826b87a14332c386d319629070382e`). - /// - /// This arm is the one the old refusal's "nor intrabc" half named, and it - /// is why the refusal could be LIFTED rather than narrowed: it decodes - /// byte-exact at 12 bits and `intrabc_hits()` proves the blocks really - /// reconstructed from the current frame. - #[test] - fn a_real_aomenc_12bit_intrabc_screen_stream_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_12bit_intrabc_screen_stream_decodes_pixel_exact"; - const PIN: &str = "screen12_intrabc.obu"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - let live = if have_aomenc() { - // `--enable-palette=1` LAST (aomenc keeps the last occurrence), so - // this 12-bit arm carries BOTH screen-content syntaxes rather than - // intra-block copy alone. - screen_intrabc_stream_at_depth( - "smptebars=size=128x96:rate=25", - "30", - "0", - true, - false, - 12, - &["--enable-palette=1"], - ) - } else { - Vec::new() - }; - assert_12bit_screen_content_arm( - NAME, - PIN, - live, - PIN_LEN_INTRABC, - PIN_FNV_INTRABC, - 1, - 256, - 192, - true, - ); - } - - /// lane-av1screen12: a 12-bit LOSSLESS screen-content stream with - /// palette and palette-UV on. - /// - /// Recipe: the palette arm's source and flags plus `--lossless=1`, so the - /// frame is `CodedLossless` (base_q_idx 0, WHT on every plane) AND - /// screen-content -- two 12-bit tile-syntax interactions in one frame; - /// pin `screen12_lossless_palette.obu` (11698 bytes, sha256 - /// `ec7942c96763593e6d8e4b3fb23c03930bba3bb743102d0cf552fe73ae11c203`). - #[test] - fn a_real_aomenc_12bit_lossless_screen_content_stream_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_12bit_lossless_screen_content_stream_decodes_pixel_exact"; - const PIN: &str = "screen12_lossless_palette.obu"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - let y4m = y4m_12bit_screen_source("testsrc2=s=160x128:r=25", false); - let live = if have_aomenc() { - encode_12bit( - &y4m, - 2, - &[ - "--tune-content=screen", - "--enable-palette=1", - "--enable-intrabc=1", - "--lossless=1", - ], - ) - } else { - Vec::new() - }; - assert_12bit_screen_content_arm( - NAME, - PIN, - live, - PIN_LEN_LOSSLESS, - PIN_FNV_LOSSLESS, - 2, - 160, - 128, - false, - ); - } - - #[test] - fn a_real_aomenc_10bit_stream_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_10bit_stream_decodes_pixel_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height) = (64usize, 64usize); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &gradients_source(42, width, height, "duration=0.04:rate=25"), - "-pix_fmt", - "yuv420p10le", - "-strict", - "-1", - "-t", - "0.04", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg failed to render the 10-bit fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let out = run_with_stdin( - Command::new(aomenc_path()).args([ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=30", - "--cpu-used=0", - "--threads=1", - "--row-mt=0", - "--sb-size=64", - "--input-bit-depth=10", - "--bit-depth=10", - "--limit=1", - "--obu", - "-o", - "-", - "-", - ]), - &y4m.stdout, - ); - assert!( - out.status.success(), - "aomenc refused the 10-bit fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - // Confirm the sequence header this stream actually parses to before - // trusting any pixel comparison below. - let mut probe = Av1Parser::new(); - let mut pos = 0usize; - while pos < stream.len() && probe.sequence_header().is_none() { - let obu = probe.parse_obu(&stream[pos..]).unwrap(); - pos += obu.total_size; - } - let seq = probe - .sequence_header() - .expect("stream has a sequence header OBU"); - assert_eq!( - seq.color_config.bit_depth, 10, - "{NAME}: aomenc did not actually write a 10-bit sequence header" - ); - let frames = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => panic!("{NAME}: decode_stream refused a real 10-bit stream: {e}"), - }; - let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1); - assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg (10-bit)"); - assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (10-bit)"); - assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (10-bit)"); - } - - /// The 10-bit *inter* counterpart of the gate above: a real `aomenc` - /// `yuv420p10le` sequence whose non-key frames are plain forward - /// single-`LAST_FRAME` P frames (same `--lag-in-frames=0 - /// --auto-alt-ref=0 --error-resilient=1` shape as the 8-bit inter gate), - /// decoded pixel-exact on every frame. 10-bit intra was proven exact by - /// lane-hbd; inter reconstruction at `bit_depth == 10` was never gated. - #[test] - fn a_real_aomenc_10bit_inter_sequence_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_10bit_inter_sequence_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height, frame_count) = (128usize, 64usize, 16usize); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &gradients_source(42, width, height, "duration=0.64:rate=25"), - "-pix_fmt", - "yuv420p10le", - "-strict", - "-1", - "-t", - "0.64", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg failed to render the 10-bit fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let out = run_with_stdin( - Command::new(aomenc_path()).args([ - // lane-defon r1: explicit on-value (aomenc keeps the FIRST - // occurrence, so overrides go before the base list). - "--loopfilter-control=1", - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=15", - "--cpu-used=0", - "--threads=1", - "--row-mt=0", - "--sb-size=64", - "--input-bit-depth=10", - "--bit-depth=10", - "--lag-in-frames=0", - "--auto-alt-ref=0", - "--kf-max-dist=1000", - "--error-resilient=1", - "--aq-mode=0", - "--deltaq-mode=0", - "--enable-cdef=0", - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-tx-size-search=0", - "--enable-cdef=1", - "--enable-restoration=1", - "--min-partition-size=16", - "--max-partition-size=32", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - "--enable-ref-frame-mvs=0", - "--obu", - "-o", - "-", - "-", - ]), - &y4m.stdout, - ); - assert!( - out.status.success(), - "aomenc refused the 10-bit fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - if let Ok(dump) = std::env::var("EC_AV1_GATE_DUMP") { - std::fs::write(dump, &stream).expect("dump stream"); - } - let mut probe = Av1Parser::new(); - let mut pos = 0usize; - while pos < stream.len() && probe.sequence_header().is_none() { - let obu = probe.parse_obu(&stream[pos..]).unwrap(); - pos += obu.total_size; - } - assert_eq!( - probe - .sequence_header() - .expect("stream has a sequence header OBU") - .color_config - .bit_depth, - 10, - "{NAME}: aomenc did not actually write a 10-bit sequence header" - ); - let before_deblock = decode::deblock_hits(); - let before_inter = decode::inter_pred_hits(); - let before_lr = crate::restoration::wiener_hits() - + crate::restoration::sgrproj_hits() - + crate::restoration::switchable_hits(); - let frames = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => panic!("{NAME}: decode_stream refused a real 10-bit inter stream: {e}"), - }; - assert!( - decode::inter_pred_hits() > before_inter, - "{NAME}: no inter-predicted block decoded -- the gate proves nothing" - ); - assert!( - decode::deblock_hits() > before_deblock, - "{NAME}: no deblocking edge fired -- raise cq-level" - ); - // Loop restoration is where the 10-bit inter/intra defect lived - // (lane-hbdinter r1: the self-guided box sums were never brought back - // to the 8-bit scale, `restoration.c:660`); a recipe whose RD happened - // to pick RESTORE_NONE would pass while proving nothing. - assert!( - crate::restoration::wiener_hits() - + crate::restoration::sgrproj_hits() - + crate::restoration::switchable_hits() - > before_lr, - "{NAME}: no loop-restoration unit decoded a real filter -- lower cq-level" - ); - eprintln!( - "{NAME}: inter_pred {} deblock {} cdef_idx {} wiener {} sgrproj {}", - decode::inter_pred_hits() - before_inter, - decode::deblock_hits() - before_deblock, - decode::cdef_idx_hits(), - crate::restoration::wiener_hits(), - crate::restoration::sgrproj_hits(), - ); - assert_eq!(frames.len(), frame_count); - let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count); - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - if got.y != want.y || got.u != want.u || got.v != want.v { - let pin = std::env::temp_dir().join("ec-av1-10bit-inter-gate-fail.obu"); - crate::dumpio::pin("TEST_PIN", &pin, &stream); - let first = |a: &Vec, b: &Vec| { - a.iter() - .zip(b) - .enumerate() - .find(|(_, (x, y))| x != y) - .map(|(k, (x, y))| (k, *x, *y)) - }; - panic!( - "{NAME}: frame {i} mismatch vs ffmpeg -- Y {:?} U {:?} V {:?}; stream pinned at {}", - first(&got.y, &want.y), - first(&got.u, &want.u), - first(&got.v, &want.v), - pin.display() - ); - } - } - } - - /// lane-hbd10 r1: a real `aomenc --bit-depth=10 --film-grain-test=1` - /// stream, decoded pixel-exact against ffmpeg's own 10-bit decode of the - /// identical bytes (ffmpeg synthesizes grain by default -- no - /// grain-disable flag is passed anywhere in this file). Proves the - /// bit-depth-generic grain path (`film_grain.rs`'s `grain_range`, - /// `scale_lut`, the `<< (bit_depth - 8)` offsets/legal ranges) rather - /// than the old `bit_depth != 8` refusal. HARD-asserts both the parsed - /// `bit_depth == 10` and `film_grain::grain_hits() > 0`, so neither a - /// silent 8-bit fallback nor a stream aomenc emitted without - /// `apply_grain` can make it pass vacuously. - #[test] - fn a_real_aomenc_10bit_film_grain_stream_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_10bit_film_grain_stream_decodes_pixel_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height) = (64usize, 64usize); - let stream = encode_10bit_gradients( - NAME, - width, - height, - 1, - &["--film-grain-test=1", "--limit=1"], - ); - assert_eq!( - parsed_bit_depth(&stream), - 10, - "{NAME}: aomenc did not actually write a 10-bit sequence header" - ); - let mut probe = Av1Parser::new(); - let mut pos = 0usize; - let mut saw_grain = false; - while pos < stream.len() { - let obu = probe.parse_obu(&stream[pos..]).unwrap(); - pos += obu.total_size; - if let ObuKind::Frame(header, _) = obu.kind - && header.film_grain.apply_grain - { - // A grain block whose scaling LUT is empty would blend a - // zero delta into every pixel and let this gate pass without - // the bit-depth math mattering at all. - assert!( - header.film_grain.num_y_points > 0, - "{NAME}: apply_grain with no luma scaling points -- grain would be a no-op" - ); - saw_grain = true; - } - } - assert!(saw_grain, "{NAME}: aomenc did not turn on apply_grain"); - let before = crate::film_grain::grain_hits(); - let frames = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => panic!("{NAME}: decode_stream refused: {e}"), - }; - assert!( - crate::film_grain::grain_hits() > before, - "{NAME}: matched but zero grain_hits -- grain synthesis never ran" - ); - let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1); - assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg"); - assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg"); - assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg"); - eprintln!( - "{NAME}: pixel-exact, grain_hits={}", - crate::film_grain::grain_hits() - ); - } - - /// lane-t900 r29: `fixtures/superres_kf_cdef_lr_64x64.obu` is a real - /// aomenc key frame (64x64 upscaled from a coded 43x64, - /// `--superres-mode=1 --superres-denominator=12 --cpu-used=0 --sb-size=64 - /// --enable-cdef=1 --enable-restoration=1 --cq-level=32`) -- the first - /// stream in this repo that runs BOTH in-loop filters under superres. - /// - /// The defect it pins: spec 7.16's upscale runs between CDEF and loop - /// restoration (libaom `superres_post_decode`, `decodeframe.c`, called - /// between `av1_cdef_frame` and `av1_loop_restoration_filter_frame`), - /// but this decoder ran the whole filter chain on the DOWNSCALED frame - /// and upscaled last, in `stream.rs`. Loop restoration therefore filtered - /// downscaled pixels with a unit grid sized from the downscaled width - /// (1873 wrong samples, max 7, on this very stream). Class - /// `wrong-stage-width`: every plane width in the filter chain is either - /// the downscaled one (deblock, CDEF, and the mi grid all three walk) or - /// the upscaled one (loop restoration's `av1_get_upsampled_plane_size` - /// unit grid, `av1_loop_restoration_corners_in_sb`'s `mi_to_num_x` - /// superres arm, and the pixel filters themselves); the sweep is every - /// caller of `apply_deblock`/`apply_cdef`/`apply_loop_restoration` plus - /// `RestorationGrid::new` and `read_lr`. - #[test] - fn a_superres_key_frame_with_cdef_and_loop_restoration_decodes_pixel_exact() { - const NAME: &str = - "a_superres_key_frame_with_cdef_and_loop_restoration_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("fixtures/superres_kf_cdef_lr_64x64.obu"); - let stream = std::fs::read(&path) - .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display())); - let (width, height) = (64usize, 64usize); - let before_lr = crate::restoration::wiener_hits() + crate::restoration::sgrproj_hits(); - let frames = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => panic!("{NAME}: decode_stream refused: {e}"), - }; - assert_eq!(frames.len(), 1, "{NAME}: one key frame"); - assert_eq!((frames[0].width, frames[0].height), (width, height)); - // class `gate-blind-to-feature`: the stream must actually upscale and - // actually run a real restoration filter, or this gate proves nothing. - assert!( - crate::superres::superres_hits() > 0, - "{NAME}: zero superres_hits -- the frame was never upscaled" - ); - assert!( - crate::restoration::wiener_hits() + crate::restoration::sgrproj_hits() > before_lr, - "{NAME}: zero restoration units fired -- LR never ran under superres" - ); - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1); - assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg"); - assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg"); - assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg"); - } - - /// lane-av1superhbd (1): 4:4:4 superres at **10 bits**, `--superres-mode=1 - /// --superres-denominator=12` on all four frames -- coded 171x128 upscaled - /// to 256x128 at `denom = 12`. - /// - /// **What it closes.** Every superres fixture the crate carried parsed - /// `bit_depth = 8` (4:2:0 `superres_kf_cdef_lr_64x64.obu`) or was 4:2:0 - /// (`superres_alltools_sb128_320x180.obu`), and the 4:4:4 superres cells - /// were 8-bit. The chroma-format sweep's not-measured list kept "4:4:4 - /// superres at 10/12 bits" open on that basis. This arm is the 10-bit - /// measurement: a 4:4:4 chroma plane upscaled at FULL resolution, where - /// the upscaler and the scaled inter predictor both run with a - /// 10-bit sample width and the 4:4:4 chroma gather has no subsampling - /// halving to hide behind. - /// - /// **The recipe** (sha256 - /// `95b49d7aa81843399ee3aa64bdadfec8f4037bcc3f861923c9b2da3bc868b223`, - /// 15803 bytes, 4 frames, `testsrc2 256x128 rate=25` yuv444p10le): - /// ```text - /// ffmpeg -f lavfi -i "testsrc2=size=256x128:rate=25" -frames:v 4 \ - /// -pix_fmt yuv444p10le -strict -1 -f yuv4mpegpipe - | \ - /// aomenc --codec=av1 --profile=1 --bit-depth=10 --input-bit-depth=10 \ - /// --passes=1 --end-usage=q --cq-level=20 --cpu-used=2 --threads=1 \ - /// --row-mt=0 --lag-in-frames=0 --kf-max-dist=100 --limit=4 \ - /// --superres-mode=1 --superres-denominator=12 \ - /// --superres-kf-denominator=12 --obu -o - - - /// ``` - /// `-strict -1` is load-bearing: without it ffmpeg refuses to write - /// `yuv444p10le` into a y4m pipe at all (zero bytes out). - #[test] - fn a_444_lossy_superres_10bit_d12_stream_decodes_pixel_exact() { - a_444_hbd_superres_arm( - "a_444_lossy_superres_10bit_d12_stream_decodes_pixel_exact", - "fixtures/444_lossy_superres_256x128_d12_10bit.obu", - 15803, - 0x9fad_3227_6e91_792c, - "95b49d7aa81843399ee3aa64bdadfec8f4037bcc3f861923c9b2da3bc868b223", - 10, - (256, 128), - &[(12, 171); 4], - ); - } - - /// lane-av1superhbd (2): 4:4:4 superres at **12 bits**, - /// `--superres-mode=1 --superres-denominator=12`, coded 171x128 upscaled - /// to 256x128. - /// - /// **Why the source is `mandelbrot` and not `testsrc2`.** The 12-bit - /// frame gate refuses a frame carrying `allow_screen_content_tools = 1` - /// by name (palette and intrabc have no 12-bit witness). libaom sets - /// that bit from its own content detection - /// (`av1_set_screen_content_options` -> `encoder_utils.c:1153`, keyed on - /// the palette-pixel ratio of the FIRST pass), and `testsrc2` -- flat - /// colour bars and hard edges -- trips it at 12 bits while the very same - /// recipe at 10 bits does not. `--enable-palette=0 --enable-intrabc=0` - /// and `--tune-content=film` do NOT suppress it (measured: all four - /// still parse `allow_screen_content_tools = true`), because the - /// detection is a property of the CONTENT, not of those flags. A - /// photographic source (`mandelbrot`, same geometry and frame count) - /// parses `allow_screen_content_tools = false` and decodes. This is a - /// source choice, stated so the next lane does not re-derive it. - /// - /// **The recipe** (sha256 - /// `973bf374c0185c4e6301509ce834cef01318e6cdb9488fd258118d7ec89bdd04`, - /// 11023 bytes, 4 frames, `mandelbrot 256x128 rate=25` yuv444p12le): - /// ```text - /// ffmpeg -f lavfi -i "mandelbrot=size=256x128:rate=25" -frames:v 4 \ - /// -pix_fmt yuv444p12le -strict -1 -f yuv4mpegpipe - | \ - /// aomenc --codec=av1 --profile=1 --bit-depth=12 --input-bit-depth=12 \ - /// --passes=1 --end-usage=q --cq-level=20 --cpu-used=2 --threads=1 \ - /// --row-mt=0 --lag-in-frames=0 --kf-max-dist=100 --limit=4 \ - /// --superres-mode=1 --superres-denominator=12 \ - /// --superres-kf-denominator=12 --obu -o - - - /// ``` - /// Byte-reproducible: two independent encodes produced the same 11023 - /// bytes. - #[test] - fn a_444_lossy_superres_12bit_d12_stream_decodes_pixel_exact() { - a_444_hbd_superres_arm( - "a_444_lossy_superres_12bit_d12_stream_decodes_pixel_exact", - "fixtures/444_lossy_superres_256x128_d12_12bit.obu", - 11023, - 0xd6cf_bb83_2b42_8e2d, - "973bf374c0185c4e6301509ce834cef01318e6cdb9488fd258118d7ec89bdd04", - 12, - (256, 128), - &[(12, 171); 4], - ); - } - - /// lane-av1superhbd (3): 4:4:4 superres at **12 bits** at the WIDEST - /// denominator this geometry allows, `--superres-denominator=9` -- coded - /// 228x128 upscaled to 256x128, so 28 of the 256 columns are the frame's - /// right-edge upscale margin, against 12's 85. - /// - /// It is a separate gate from the den=12 arm because the margin is - /// where a round-trip is most likely to read past the coded picture: a - /// decoder that sized the upscale source from `UpscaledWidth` instead of - /// `FrameWidth` is exact at den=12 on this content and wrong here. Its - /// recipe is the 12-bit one above with `--superres-denominator=9 - /// --superres-kf-denominator=9` (sha256 - /// `898c775108495b998cb5ec9b08e194d4656ed0140aa8e7e7236892d468bbad99`, - /// 13015 bytes). - #[test] - fn a_444_lossy_superres_12bit_d9_stream_decodes_pixel_exact() { - a_444_hbd_superres_arm( - "a_444_lossy_superres_12bit_d9_stream_decodes_pixel_exact", - "fixtures/444_lossy_superres_256x128_d9_12bit.obu", - 13015, - 0x4110_ce7b_cd85_901b, - "898c775108495b998cb5ec9b08e194d4656ed0140aa8e7e7236892d468bbad99", - 12, - (256, 128), - &[(9, 228); 4], - ); - } - - /// lane-av1superhbd (4): 4:4:4 superres at **10 bits** under - /// `--superres-mode=2` -- the random-denominator arm, where libaom picks - /// a DIFFERENT denominator for every frame and IGNORES - /// `--superres-denominator` entirely. - /// - /// This is what keeps the high-bit-depth superres cell from silently - /// degenerating into a single-denominator cell: the per-frame parsed - /// denominators are 11, 14, 15, 9 -- three of them values no flag on the - /// command line ever named -- so a gate that read the flag instead of - /// the header would be wrong on three of four frames. The assertion - /// below makes that structural rather than incidental, and it is the - /// assertion that fails if a future libaom starts honouring the flag - /// under mode 2. - /// - /// **The recipe** (sha256 - /// `699398aba58fb53b80e05d3d214eb746a3c91945e01da6b47488513f20b55668`, - /// 17776 bytes, 4 frames, `testsrc2 256x128 rate=25` yuv444p10le): - /// ```text - /// ffmpeg -f lavfi -i "testsrc2=size=256x128:rate=25" -frames:v 4 \ - /// -pix_fmt yuv444p10le -strict -1 -f yuv4mpegpipe - | \ - /// aomenc --codec=av1 --profile=1 --bit-depth=10 --input-bit-depth=10 \ - /// --passes=1 --end-usage=q --cq-level=20 --cpu-used=2 --threads=1 \ - /// --row-mt=0 --lag-in-frames=0 --kf-max-dist=100 --limit=4 \ - /// --superres-mode=2 --obu -o - - - /// ``` - #[test] - fn a_444_lossy_superres_10bit_mode2_random_denom_stream_decodes_pixel_exact() { - const NAME: &str = - "a_444_lossy_superres_10bit_mode2_random_denom_stream_decodes_pixel_exact"; - let heads = a_444_hbd_superres_arm( - NAME, - "fixtures/444_lossy_superres_mode2_256x128_10bit.obu", - 17776, - 0x164f_4099_7576_7ae4, - "699398aba58fb53b80e05d3d214eb746a3c91945e01da6b47488513f20b55668", - 10, - (256, 128), - &[(11, 186), (14, 146), (15, 137), (9, 228)], - ); - // Distinct-denominator assert: the cell must stay a MULTI-denominator - // one. A libaom that collapsed mode 2 onto a single denominator (or - // stopped scaling) would still decode, and the gate above would still - // hold only because the literals would have been re-pinned with it -- - // so the property is asserted from the parsed headers directly. - let denoms: Vec = heads.iter().map(|h| h.superres_denom).collect(); - let mut distinct = denoms.clone(); - distinct.sort_unstable(); - distinct.dedup(); - assert!( - distinct.len() >= 3, - "{NAME}: the stream carries denominators {denoms:?} -- fewer than three distinct \ - values, so this is no longer the per-frame-denominator cell and the pin has to be \ - re-derived from the stream" - ); - let flagged = [9u8, 12, 16]; - assert!( - denoms.iter().any(|d| !flagged.contains(d)), - "{NAME}: every parsed denominator is one of the flag values {flagged:?} -- mode 2 now \ - appears to honour --superres-denominator, and this cell stops being the \ - flag-ignoring one" - ); - } - - /// lane-av1superhbd (5): 4:4:4 superres at **12 bits** under - /// `--superres-mode=2` -- the high-bit-depth random-denominator arm, the - /// 12-bit twin of the arm above (sha256 - /// `18aa8b3124ab10672f22577a8eea81e44141a3d0bb506104aee2f950254a2e9f`, - /// 14656 bytes, same `mandelbrot` source as the 12-bit fixed-denominator - /// arms). Its parsed denominators are again 11/14/15/9 at coded widths - /// 186/146/137/228, so the upscaler is handed FOUR coded-to-upscaled - /// ratios in one 12-bit decode -- the case a single-denominator gate - /// cannot reach at any bit depth. - #[test] - fn a_444_lossy_superres_12bit_mode2_random_denom_stream_decodes_pixel_exact() { - const NAME: &str = - "a_444_lossy_superres_12bit_mode2_random_denom_stream_decodes_pixel_exact"; - let heads = a_444_hbd_superres_arm( - NAME, - "fixtures/444_lossy_superres_mode2_256x128_12bit.obu", - 14656, - 0xef38_3fb7_b284_2166, - "18aa8b3124ab10672f22577a8eea81e44141a3d0bb506104aee2f950254a2e9f", - 12, - (256, 128), - &[(11, 186), (14, 146), (15, 137), (9, 228)], - ); - let denoms: Vec = heads.iter().map(|h| h.superres_denom).collect(); - let mut distinct = denoms.clone(); - distinct.sort_unstable(); - distinct.dedup(); - assert!( - distinct.len() >= 3, - "{NAME}: the stream carries denominators {denoms:?} -- fewer than three distinct \ - values, so this is no longer the per-frame-denominator cell and the pin has to be \ - re-derived from the stream" - ); - let flagged = [9u8, 12, 16]; - assert!( - denoms.iter().any(|d| !flagged.contains(d)), - "{NAME}: every parsed denominator is one of the flag values {flagged:?} -- mode 2 now \ - appears to honour --superres-denominator, and this cell stops being the \ - flag-ignoring one" - ); - } - - /// lane-wave1 step (ii): the superblock-row wavefront - /// (`EC_AV1_RECON_THREADS`) reconstructs every output frame byte for - /// byte as the inline path does, on a hidden-ARF 10-bit stream (no-show - /// frames, CfL, 128 superblocks) and on the two screen-content streams - /// whose palette/intrabc blocks READ the current frame's pixels while - /// parsing -- the sites that make the workers barrier. - #[test] - fn a_real_stream_reconstructs_identically_with_one_and_four_recon_threads() { - const NAME: &str = "a_real_stream_reconstructs_identically_with_one_and_four_recon_threads"; - let _gate_lock = lock_gate_counters(); - for fixture in [ - "reelb_arf_witness.obu", - "palette_screen_witness.obu", - "palette_screen_witness_10bit.obu", - // lane-av1wavefront: the 4:4:4 inter witness. The wavefront's - // replay-side chroma (`mv_to_q4(.., ss_x(fctx))` in the deferred - // builds, `exec_intra`'s CfL AC) used to read the worker's fresh - // `FrameCtx` 4:2:0 DEFAULT instead of the frame's subsampling -- - // invisible on the three 4:2:0 streams above, chroma-only loss on - // this one (f1 U 17504 / V 3, f2 U 25472 / V 1472 at PREFILT). - "444_sb128rect_lr_witness.obu", - ] { - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("fixtures") - .join(fixture); - let stream = std::fs::read(&path) - .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display())); - crate::par::set_recon_threads(1); - let one = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => panic!("{NAME}: {fixture} refused at 1 recon thread: {e}"), - }; - crate::par::set_recon_threads(4); - let four = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => { - crate::par::set_recon_threads(1); - panic!("{NAME}: {fixture} refused at 4 recon threads: {e}") - } - }; - crate::par::set_recon_threads(1); - assert!(!one.is_empty(), "{NAME}: {fixture} decoded nothing"); - assert_eq!(one.len(), four.len(), "{NAME}: {fixture} frame count"); - for (i, (a, b)) in one.iter().zip(four.iter()).enumerate() { - assert_eq!( - a.y, b.y, - "{NAME}: {fixture} frame {i} luma differs at 4 recon threads" - ); - assert_eq!( - a.u, b.u, - "{NAME}: {fixture} frame {i} U differs at 4 recon threads" - ); - assert_eq!( - a.v, b.v, - "{NAME}: {fixture} frame {i} V differs at 4 recon threads" - ); - } - } - } - - /// lane-filt1: `EC_AV1_FILTER_THREADS` splits every in-frame filter stage - /// -- deblock (row bands for the vertical-edge pass, column bands for the - /// horizontal one), CDEF (mi row bands), loop restoration (RU row bands) - /// and film grain (32-pixel block rows) -- across scoped worker threads. - /// A split is only legal if it is BYTE-EXACT, so this gate decodes two - /// real aomenc streams at 1 and at 4 filter threads and compares every - /// output frame's three planes. - /// - /// Between them the fixtures fire all four stages, and the firing - /// counters are asserted rather than assumed (class `gate-blind-to-feature`): - /// `superres_alltools_sb128_320x180.obu` is the 10-bit CDEF + loop - /// restoration stream, `grain_cdef_lr_128x128.obu` a 128x128 - /// `--denoise-noise-level=25` stream whose frames carry film grain - /// parameters (small enough that 4 bands is one block row each, which is - /// what exercises the grain band's one-row `prelude` replay). - #[test] - fn a_real_stream_filters_identically_with_one_and_four_filter_threads() { - const NAME: &str = "a_real_stream_filters_identically_with_one_and_four_filter_threads"; - let _gate_lock = lock_gate_counters(); - for (fixture, wants_lr, wants_grain) in [ - ("superres_alltools_sb128_320x180.obu", true, false), - ("grain_cdef_lr_128x128.obu", false, true), - ] { - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("fixtures") - .join(fixture); - let stream = std::fs::read(&path) - .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display())); - let before = ( - crate::decode::deblock_hits(), - crate::restoration::wiener_hits() + crate::restoration::sgrproj_hits(), - crate::film_grain::grain_hits(), - ); - crate::par::set_filter_threads(1); - let one = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => panic!("{NAME}: {fixture} refused at 1 filter thread: {e}"), - }; - let after = ( - crate::decode::deblock_hits(), - crate::restoration::wiener_hits() + crate::restoration::sgrproj_hits(), - crate::film_grain::grain_hits(), - ); - crate::par::set_filter_threads(4); - let four = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => { - crate::par::set_filter_threads(1); - panic!("{NAME}: {fixture} refused at 4 filter threads: {e}") - } - }; - crate::par::set_filter_threads(1); - assert!( - after.0 > before.0, - "{NAME}: {fixture} deblocked no edge at all" - ); - if wants_lr { - assert!( - after.1 > before.1, - "{NAME}: {fixture} ran no restoration unit" - ); - } - if wants_grain { - assert!( - after.2 > before.2, - "{NAME}: {fixture} applied no film grain" - ); - } - assert_eq!(one.len(), four.len(), "{NAME}: {fixture} frame count"); - assert!(!one.is_empty(), "{NAME}: {fixture} decoded nothing"); - for (i, (a, b)) in one.iter().zip(four.iter()).enumerate() { - assert_eq!( - a.y, b.y, - "{NAME}: {fixture} frame {i} luma differs at 4 filter threads" - ); - assert_eq!( - a.u, b.u, - "{NAME}: {fixture} frame {i} U differs at 4 filter threads" - ); - assert_eq!( - a.v, b.v, - "{NAME}: {fixture} frame {i} V differs at 4 filter threads" - ); - } - } - } - - /// lane-t900 r30b: `fixtures/superres_alltools_sb128_320x180.obu` is 10 - /// frames of `--cpu-used=4 --sb-size=128 --superres-mode=1 - /// --superres-denominator=12 --cq-level=32` with every tool aomenc turns - /// on by default (CDEF, loop restoration, OBMC, compound, warp) -- the - /// first stream here that deblocks CHROMA across a group of 4x4 luma - /// blocks. - /// - /// The defect it pins (fixed at this commit, `decode.rs`'s - /// `plane_to_mi`/`edge_params`): `set_lpf_parameters` - /// (`av1_loopfilter.c:245`) indexes the mi grid for a CHROMA edge at - /// `scale | ((coord << scale) >> MI_SIZE_LOG2)` -- the BOTTOM/RIGHT mi of - /// the co-located 8x8 luma group, the same cell that donates the group's - /// chroma prediction. This decoder dropped that `| 1` and read the - /// group's top-left mi, stepped to the previous cell by one mi instead of - /// `1 << ss`, and priced `pu_edge` by comparing mi origins rather than - /// the edge coordinate against the block size in the FILTERED plane's own - /// pixels (chroma bottoms out at 4). All three are invisible while every - /// block is 8x8 or larger (all four mi of a group carry the same tx size, - /// ref frame, skip flag and delta_lf) and wrong the moment cpu-used=4 - /// splits a group into 4x4 blocks: on this stream one U sample of frame 2 - /// took a filter level of 12 where libaom's neighbouring 4x4 block gives - /// 8, and the error compounded through the reference chain to 280 U + 331 - /// V samples (max 9) by frame 9. Class `context-read-from-one-cell`. - /// - /// Post-deblock, this stream is now byte-exact against the instrumented - /// libaom (`EC_AV1_POSTDEBLOCK_DUMP`) in all 10 frames, and the final - /// output matches ffmpeg's. - #[test] - fn a_superres_all_tools_sb128_stream_decodes_pixel_exact() { - const NAME: &str = "a_superres_all_tools_sb128_stream_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("fixtures/superres_alltools_sb128_320x180.obu"); - let stream = std::fs::read(&path) - .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display())); - let (width, height, count) = (320usize, 180usize, 10usize); - let frames = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => panic!("{NAME}: decode_stream refused: {e}"), - }; - assert_eq!(frames.len(), count, "{NAME}: frame count"); - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, count); - for (i, (ours, theirs)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!(ours.y, theirs.y, "{NAME}: frame {i} luma vs ffmpeg"); - assert_eq!(ours.u, theirs.u, "{NAME}: frame {i} U vs ffmpeg"); - assert_eq!(ours.v, theirs.v, "{NAME}: frame {i} V vs ffmpeg"); - } - } - - /// lane-golomb r1: THE FILM ITSELF. `crates/ec-av1/fixtures/reelb_head_key_frame.obu` - /// is the first frame of the user's ReelB AV1 release (3840x1608 - /// yuv420p10le, `ffmpeg -i -c copy -frames:v 1 -f obu`, 147 bytes) -- - /// a real 10-bit key frame whose height is NOT a multiple of the 64-pixel - /// superblock, so its last superblock row (mi_row=400 of 402) carries the - /// edge partition symbol this lane fixed: libaom's `ec_read_partition_impl` - /// returns `PARTITION_HORZ` when the gathered `split_or_horz` bit is 0, and - /// this decoder used to READ that bit and throw it away, forcing SPLIT - /// (class `parsed-then-discarded`). The desync surfaced two rows later as - /// "a Golomb tail longer than this decoder reads" -- a refusal naming the - /// symptom, never the cause. - #[test] - fn the_reelb_head_key_frame_decodes_pixel_exact() { - const NAME: &str = "the_reelb_head_key_frame_decodes_pixel_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - let path = - std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures/reelb_head_key_frame.obu"); - let stream = std::fs::read(&path) - .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display())); - let (width, height) = (3840usize, 1608usize); - let frames = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => panic!("{NAME}: decode_stream refused: {e}"), - }; - assert_eq!(frames.len(), 1, "{NAME}: one key frame"); - assert_eq!((frames[0].width, frames[0].height), (width, height)); - let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1); - assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg"); - assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg"); - assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg"); - } - - /// lane-reelckf r2: `crates/ec-av1/fixtures/reelc_kf2700.obu` is a 1920x792 - /// 10-bit AV1 key frame taken out of one of the user's own films - /// (`ffmpeg -ss 2700 -c:v copy -f obu`, then truncated to its first temporal - /// unit, 36 kB) -- the ONLY stream in this repo that contains a SKIPPED - /// `UV_CFL_PRED` block. 30 aomenc recipes (r1's 20 plus r2's chroma-correlated - /// `geq` sweep, cq 40..63, cpu-used 0..2, min/max-partition 4..64, 8 and - /// 10 bit) never made the encoder pick one, so the counter can only be - /// hard-asserted against a real film frame. The instrumented oracle agrees: - /// `EC_TRACE_MODE=1 aomdec` prints 5 `EC_IMODE_VAL ... uv_mode=13 skip=1` - /// lines for this frame. - /// - /// The defect it pins (fixed at 29cd53f, `decode.rs:7719`/`:10528`/`:10891`): - /// a skipped intra block must still PREDICT with CfL -- libaom's - /// `predict_and_reconstruct_intra_block` predicts every plane and guards only - /// the residual on `skip_txfm`. Before the fix this frame had 499 wrong - /// chroma samples (U rows 48..79 cols 464..492); after it, zero. - /// - /// The ffmpeg reference is `ffmpeg -f obu -i -f rawvideo - /// -pix_fmt yuv420p10le -` (what `ffmpeg_decode_sequence_10bit` runs). - #[test] - fn a_real_film_key_frame_with_a_skipped_cfl_block_decodes_pixel_exact() { - const NAME: &str = "a_real_film_key_frame_with_a_skipped_cfl_block_decodes_pixel_exact"; - let path = - std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures/reelc_kf2700.obu"); - let stream = std::fs::read(&path) - .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display())); - let (width, height) = (1920usize, 792usize); - let before = crate::decode::reelc_chroma_counters(); - let frames = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => panic!("{NAME}: decode_stream refused: {e}"), - }; - let after = crate::decode::reelc_chroma_counters(); - let skip_cfl = after.0 - before.0; - assert_eq!(frames.len(), 1, "{NAME}: one key frame"); - assert_eq!((frames[0].width, frames[0].height), (width, height)); - // Asserted before the ffmpeg compare so an absent ffmpeg cannot make the - // gate vacuous: the skipped-CfL path is exercised on every run. - assert!( - skip_cfl > 0, - "{NAME}: zero skipped-CfL blocks -- the fixture no longer exercises defect 1" - ); - if !have_ffmpeg() { - eprintln!("SKIP {NAME} pixel compare: no ffmpeg (skipped_cfl={skip_cfl})"); - return; - } - let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1); - assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg"); - assert_eq!( - frames[0].u, ffmpeg_frames[0].u, - "{NAME}: U vs ffmpeg ({skip_cfl} skipped-CfL blocks)" - ); - assert_eq!( - frames[0].v, ffmpeg_frames[0].v, - "{NAME}: V vs ffmpeg ({skip_cfl} skipped-CfL blocks)" - ); - eprintln!("{NAME}: pixel-exact, skipped_cfl={skip_cfl}"); - } - - /// lane-kf1200 r2: the same film's `-ss 300` key frame, pinned because no - /// aomenc recipe reaches its shape -- a SKIPPED sub-8x8 chroma block whose - /// `uv_mode` is `UV_CFL_PRED`. (lane-reelckf r1 burned 20 recipes across cq - /// 40..63 and nine lavfi sources hunting exactly this block and never got - /// one; ledger dead-end "never produced a SKIPPED 1:4 or sub-8x8 CfL - /// block".) Before the fix the two sub-8x8 skip arms passed `None` for the - /// CfL argument, so the block reconstructed as flat DC and 463 bytes of - /// this frame's chroma were wrong. HARD-asserts `skip_cfl_hits` moved, so - /// the fixture cannot silently stop exercising the arm. - #[test] - fn the_reelb_ss300_key_frame_skipped_cfl_decodes_pixel_exact() { - const NAME: &str = "the_reelb_ss300_key_frame_skipped_cfl_decodes_pixel_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("fixtures/reelb_ss300_key_frame.obu"); - let stream = std::fs::read(&path) - .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display())); - let (width, height) = (3840usize, 1608usize); - let before = crate::decode::skip_cfl_hits(); - let frames = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => panic!("{NAME}: decode_stream refused: {e}"), - }; - let skipped_cfl = crate::decode::skip_cfl_hits() - before; - assert!( - skipped_cfl > 0, - "{NAME}: zero skipped sub-8x8 CfL blocks -- the fixture no longer \ - exercises the arm this test exists for" - ); - assert_eq!(frames.len(), 1, "{NAME}: one key frame"); - assert_eq!((frames[0].width, frames[0].height), (width, height)); - let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1); - assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg"); - assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg"); - assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg"); - eprintln!("{NAME}: {skipped_cfl} skipped sub-8x8 CfL chroma blocks, frame pixel-exact"); - } - - /// lane-kf900 r2: the film's key frame at -ss 900, one frame - /// (`crates/ec-av1/fixtures/reelb_kf900.obu`, 484640 bytes, sha256 - /// `a273ae99328388be14a1ff8fa1c5a6d391a9948159eaef120e1b50e02015eb83`, - /// extracted twice from independent - /// `ffmpeg -ss 900 -t 2 -i <2160p AV1 HDR10 mkv> -c:v copy -f obu` runs and - /// truncated to the first frame; both extracts hashed identically). - /// - /// This is the ONLY stream that reaches the r1 defect: a SKIPPED 8x8 intra - /// leaf whose `tx_depth` symbol resolved to `TX_4X4` still publishes 4 -- - /// not its 8-pixel block side -- to the next block's `get_tx_size_context` - /// (`set_txfm_ctxs(mbmi->tx_size, bw, bh, skip_txfm && is_inter_block(...))`, - /// `decodemv.c`; the skip term is 0 for intra). It fires 15 times here and - /// zero times across 108 measured aomenc recipes, so the counter is - /// asserted against the film rather than against a synthesised stream. - /// - /// LUMA only. U/V still differ (open residue, lane-kf900 r2: 221 U and - /// 47912 V samples, max |d| 23/2, first at chroma (195, 640) -- chroma - /// RESIDUAL, the prediction there is bit-exact against aomdec's - /// `EC_PREDOUT`), so this gate pins what is proven and no more. - #[test] - fn a_10bit_key_frame_with_skipped_8x8_intra_leaves_that_split_their_transform_decodes_luma_exact() - { - const NAME: &str = "a_10bit_key_frame_with_skipped_8x8_intra_leaves_that_split_their_transform_decodes_luma_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures/reelb_kf900.obu"); - let stream = std::fs::read(&path) - .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display())); - let (width, height) = (3840usize, 1608usize); - crate::decode::reset_skip_split_tx_hits(); - let frames = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => panic!("{NAME}: decode_stream refused: {e}"), - }; - assert_eq!(frames.len(), 1, "{NAME}: one key frame"); - assert_eq!((frames[0].width, frames[0].height), (width, height)); - assert!( - crate::decode::skip_split_tx_hits() >= 15, - "{NAME}: skip_split_tx_hits() == {} -- the stream that carries the tx-context \ - defect stopped carrying it, so this gate proves nothing", - crate::decode::skip_split_tx_hits() - ); - let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1); - assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg"); - } - - /// lane-kf1200 r3: the same film's `-ss 600` key frame (3840x1608, one - /// 8-px partial bottom superblock row), pinned because no aomenc recipe - /// reaches its shape -- a SKIPPED 8x8 intra leaf whose `tx_depth` resolved - /// to TX_4X4. (80 recipes swept this round: 4 frame shapes x 2 sources x - /// cq 32..63 x cpu-used 0/3 x 8/10-bit, all with - /// `--enable-tx-size-search=1 --enable-filter-intra=1`; every one came - /// back with `skip_split_tx_hits == 0`, `lanes/kf1200-r3.report.md`.) - /// An intra block reads `tx_depth` whether or not it is skipped, so the - /// leaf must record its resolved 4 -- not its 8x8 side -- in the txfm - /// context; recording 8 gave the NEXT block's `tx_depth` symbol the wrong - /// `tx_size_cdf` row (ctx 2 where libaom reads 1) and desynced the - /// entropy stream at mi (400,46). HARD-asserts `skip_split_tx_hits` moved. - #[test] - fn the_reelb_ss600_key_frame_skipped_split_tx_decodes_pixel_exact() { - const NAME: &str = "the_reelb_ss600_key_frame_skipped_split_tx_decodes_pixel_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("fixtures/reelb_ss600_key_frame.obu"); - let stream = std::fs::read(&path) - .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display())); - let (width, height) = (3840usize, 1608usize); - crate::decode::reset_skip_split_tx_hits(); - let frames = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => panic!("{NAME}: decode_stream refused: {e}"), - }; - let skipped_split_tx = crate::decode::skip_split_tx_hits(); - assert!( - skipped_split_tx > 0, - "{NAME}: zero skipped 8x8 leaves with a split transform -- the fixture no longer \ - exercises the arm this test exists for" - ); - assert_eq!(frames.len(), 1, "{NAME}: one key frame"); - assert_eq!((frames[0].width, frames[0].height), (width, height)); - let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1); - assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg"); - assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg"); - assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg"); - eprintln!("{NAME}: {skipped_split_tx} skipped 8x8 TX_4X4 leaves, frame pixel-exact"); - } - - /// lane-hbd10 r1: a real `aomenc --bit-depth=10 --superres-mode=1 - /// --superres-denominator=12` key frame, decoded pixel-exact against - /// ffmpeg's own 10-bit decode. Proves `superres::upscale_row`'s - /// `clip_pixel_highbd` clamp (`(1 << bit_depth) - 1`) on real 10-bit - /// planes rather than the old `bit_depth != 8` refusal. HARD-asserts - /// `bit_depth == 10` and `superres_hits > 0`. - #[test] - fn a_real_aomenc_10bit_superres_stream_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_10bit_superres_stream_decodes_pixel_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height) = (64usize, 64usize); - let stream = encode_10bit_gradients( - NAME, - width, - height, - 1, - &[ - "--limit=1", - "--kf-max-dist=0", - "--superres-mode=1", - "--superres-denominator=12", - "--superres-kf-denominator=12", - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-tx-size-search=0", - "--enable-cdef=0", - "--enable-restoration=0", - "--max-partition-size=32", - "--min-partition-size=32", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - ], - ); - assert_eq!( - parsed_bit_depth(&stream), - 10, - "{NAME}: aomenc did not actually write a 10-bit sequence header" - ); - let before = crate::superres::superres_hits(); - let frames = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => panic!("{NAME}: decode_stream refused: {e}"), - }; - assert!( - crate::superres::superres_hits() > before, - "{NAME}: matched but zero superres_hits -- the upscaler never ran" - ); - let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1); - assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg"); - assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg"); - assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg"); - eprintln!( - "{NAME}: pixel-exact, superres_hits={}", - crate::superres::superres_hits() - ); - } - - /// lane-hbdgates r1: the four intra tools that had an 8-bit gate and no - /// 10-bit one (`filter-intra`, `smooth-intra`, `paeth-intra`, - /// `intra-edge-filter`) on ONE real 10-bit `aomenc` key frame, each with - /// its own hard-asserted counter. His two films are yuv420p10le, so an - /// 8-bit-only gate for these tools proves nothing about the streams that - /// matter (lane-covbd r1). - #[test] - fn a_real_aomenc_10bit_intra_tools_stream_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_10bit_intra_tools_stream_decodes_pixel_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - ten_bit_tool_gate( - NAME, - 64, - 64, - 1, - &[ - "--limit=1", - "--kf-max-dist=0", - "--enable-filter-intra=1", - "--enable-smooth-intra=1", - "--enable-paeth-intra=1", - "--enable-intra-edge-filter=1", - "--enable-directional-intra=1", - "--enable-angle-delta=0", - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-tx-size-search=0", - "--enable-cdef=0", - "--enable-restoration=0", - "--max-partition-size=32", - "--min-partition-size=16", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - "--enable-ref-frame-mvs=0", - ], - &[42, 7, 11, 23, 31, 57], - &[ - ("filter_intra_hits", decode::filter_intra_hits), - ("smooth_pred_hits", crate::intra::smooth_pred_hits), - ("paeth_pred_hits", crate::intra::paeth_pred_hits), - ( - "intra_edge_filter_hits", - crate::intra::intra_edge_filter_hits, - ), - ], - ); - } - - /// lane-hbdgates r1: `--enable-restoration=1` at 10 bits. Every earlier - /// bit-depth gate ran `--enable-restoration=0`, which is exactly why two - /// high-bit-depth loop-restoration defects survived to 2026-09-01 - /// (SGR box sums unscaled, Wiener clamp at the 8-bit bound). Same recipe - /// as the 8-bit LR gate, at 10 bits. - // Written `#[ignore]`d on lane-hbdgates (the branch lacked lane-hbdinter's - // 10-bit LR fix and failed at seed 42, frame 0, Y index 122: ours 351 vs - // ffmpeg 350). Un-ignored on the merge into main 2026-09-01, where the - // SGR box-sum scaling and the Wiener clamp are fixed: 16/16 attempts - // pixel-exact, lr_hits=28. - #[test] - fn a_real_aomenc_10bit_restoration_stream_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_10bit_restoration_stream_decodes_pixel_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - // 192x128 = 3x2 superblocks, so `read_lr` is re-entered per SB - // (the 8-bit LR gate's own trap warning); cq-level=15 because - // aomenc's RD only picks a non-RESTORE_NONE frame type at low cq. - ten_bit_tool_gate( - NAME, - 192, - 128, - 1, - &[ - "--limit=1", - "--kf-max-dist=0", - "--cq-level=15", - "--enable-restoration=1", - "--enable-cdef=0", - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-tx-size-search=0", - "--max-partition-size=32", - "--min-partition-size=16", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - "--enable-ref-frame-mvs=0", - ], - &LR_SEEDS, - &[("lr_hits", ten_bit_lr_hits)], - ); - } - - /// lane-reelckf2 r1: loop restoration on frame sizes whose LAST stripe is - /// partial, with 128-sample superblocks -- the two stripe shapes whose - /// boundary substitution is special (`filter_restoration_unit`: the first - /// stripe is 8 rows short and takes its above boundary from the frame's - /// own top rows, the last one is truncated and takes its below boundary - /// from the frame's own bottom row) had no gate at all: every earlier LR - /// size (192x128, 160x96) is a whole multiple of 64 rows and ran at - /// `--sb-size=64`. 152 = 2*64+24 and 216 = 3*64+24 both leave a 32-row - /// tail stripe, mirroring the 792-row 10-bit film that made this lane. - /// `lr_stripe0_hits`/`lr_last_stripe_hits` are hard-asserted per attempt - /// by [`ten_bit_tool_gate`], so an RD that picked RESTORE_NONE on either - /// stripe cannot pass. - #[test] - fn a_real_aomenc_10bit_partial_bottom_stripe_restoration_decodes_pixel_exact() { - const NAME: &str = - "a_real_aomenc_10bit_partial_bottom_stripe_restoration_decodes_pixel_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - // `--sb-size=128` goes in `extra`, which the helper appends AFTER its - // own `--sb-size=64` (aomenc keeps the LAST occurrence of a repeated - // flag, measured 2026-09-02); `--max-partition-size=32` keeps the 128 - // root on SPLIT, the only 128-root partition decoded today. - for (width, height, cq) in [ - (256usize, 152usize, "15"), - (384, 216, "15"), - (256, 152, "25"), - ] { - ten_bit_tool_gate( - &format!("{NAME} {width}x{height} cq{cq}"), - width, - height, - 1, - &[ - "--limit=1", - "--kf-max-dist=0", - &format!("--cq-level={cq}"), - "--sb-size=128", - "--enable-restoration=1", - "--enable-cdef=0", - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-tx-size-search=0", - "--max-partition-size=32", - "--min-partition-size=16", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - "--enable-ref-frame-mvs=0", - ], - &LR_SEEDS, - &[ - ("lr_hits", ten_bit_lr_hits), - ("lr_stripe0_hits", crate::restoration::lr_stripe0_hits), - ( - "lr_last_stripe_hits", - crate::restoration::lr_last_stripe_hits, - ), - ], - ); - } - } - - /// lane-hbdgates r1: `--enable-rect-partitions=1 --enable-ab-partitions=1` - /// at 10 bits, one intra stream, one counter per tool - /// (`rect_partition_hits`, `partab_hits`) so a stream that only fired the - /// rect arms cannot stand in for AB. - #[test] - fn a_real_aomenc_10bit_rect_and_ab_partitions_decode_pixel_exact() { - const NAME: &str = "a_real_aomenc_10bit_rect_and_ab_partitions_decode_pixel_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - // The 8-bit free-partition/AB recipe, verbatim, at 10 bits: AB - // splits are an INTER dispatch here (intra-frame AB is still a named - // refusal), so the stream needs alt-refs and 24 frames, not one key - // frame. - ten_bit_tool_gate( - NAME, - 64, - 64, - 24, - &[ - "--cq-level=45", - "--kf-max-dist=1000", - "--auto-alt-ref=1", - "--lag-in-frames=16", - "--enable-fwd-kf=0", - "--enable-order-hint=1", - "--enable-warped-motion=1", - "--enable-obmc=1", - "--tune-content=default", - "--enable-masked-comp=0", - "--enable-interintra-comp=0", - "--enable-onesided-comp=0", - "--enable-interintra-wedge=0", - "--enable-smooth-interintra=0", - "--enable-rect-partitions=1", - "--enable-ab-partitions=1", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-tx-size-search=0", - "--enable-cdef=0", - "--enable-restoration=0", - "--max-partition-size=32", - "--min-partition-size=16", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - "--enable-ref-frame-mvs=0", - ], - &LR_SEEDS, - &[ - ("rect_partition_hits", decode::rect_partition_hits), - ("partab_hits", decode::partab_hits), - ], - ); - } - - /// lane-obmcrec r1: OBMC whose above/left neighbour is a 4-wide/4-tall - /// 1:4-partition strip -- the shape the three 1080p 10-bit film cuts - /// refused on ("an OBMC neighbour whose switchable interp filter was never - /// recorded"). `overlappable_above`/`_left` snap such a neighbour to the - /// chroma pair's SECOND mi but used to read its interp filter from the - /// FIRST one, a different block whose filter record is the intra - /// `[3, 3]` sentinel whenever that half is intra. `obmc_pair_filter_hits` - /// counts exactly that neighbour shape, so a stream without 1:4 strips - /// next to an OBMC block cannot stand in for it. - #[test] - fn a_real_aomenc_10bit_obmc_over_1to4_strip_neighbours_decodes_pixel_exact() { - const NAME: &str = - "a_real_aomenc_10bit_obmc_over_1to4_strip_neighbours_decodes_pixel_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - ten_bit_tool_gate( - NAME, - 128, - 128, - 24, - &[ - "--ec-fixture-noise", - "--cq-level=45", - "--kf-max-dist=1000", - "--auto-alt-ref=1", - "--lag-in-frames=16", - "--enable-fwd-kf=0", - "--enable-order-hint=1", - "--enable-warped-motion=0", - "--enable-obmc=1", - "--tune-content=default", - "--enable-masked-comp=0", - "--enable-interintra-comp=0", - "--enable-onesided-comp=0", - "--enable-interintra-wedge=0", - "--enable-smooth-interintra=0", - "--enable-rect-partitions=1", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=1", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-tx-size-search=0", - "--enable-cdef=0", - "--enable-restoration=0", - "--max-partition-size=32", - "--min-partition-size=4", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - "--enable-ref-frame-mvs=0", - ], - &OBMC_PAIR_SEEDS, - &[("obmc_pair_filter_hits", decode::obmc_pair_filter_hits)], - ); - } - - /// A real `aomenc` palette-**UV** fixture (lane-palette2 r2): `testsrc2` - /// (the multicoloured AV1 test pattern -- flat, few-colour, repetitive - /// per-region colour *and* chroma, unlike `smptebars=hue=s=0` above, - /// which flattened chroma to a single value specifically to avoid - /// exercising this path). Same square-only recipe as the palette-Y gate - /// (`--enable-rect-partitions=0`/`-ab-`/`-1to4-`, fixed 32x32 partition) - /// so a UV palette block never lands inside the still-refused HORZ/VERT - /// screen-content strip. HARD-asserts [`decode::palette_uv_hits`] moved - /// -- a stream that never reads a real UV palette block would decode (or - /// not) by construction without proving this milestone at all - /// ([[gate-blind-to-feature]]). - #[test] - fn a_real_aomenc_stream_with_palette_uv_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_stream_with_palette_uv_decodes_pixel_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let source = "testsrc2=size=64x64:rate=25"; - fn render(source: &str) -> Vec { - crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - source, - "-pix_fmt", - "yuv420p", - "-t", - "0.16", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run") - .stdout - } - let y4m_a = render(source); - let y4m_b = render(source); - assert_eq!( - y4m_a, y4m_b, - "testsrc2 must render byte-identical across two runs" - ); - let y4m = y4m_a; - let out = run_with_stdin( - Command::new(aomenc_path()).args([ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=30", - "--cpu-used=0", - "--threads=1", - "--row-mt=0", - "--sb-size=64", - "--tune-content=screen", - "--enable-palette=1", - "--enable-intrabc=0", - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--min-partition-size=32", - "--max-partition-size=32", - "--enable-filter-intra=0", - "--enable-cdef=0", - "--enable-restoration=0", - "--enable-tx-size-search=0", - "--loopfilter-control=0", - "--obu", - "-o", - "-", - "-", - ]), - &y4m, - ); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let before = decode::palette_uv_hits(); - let frames = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => panic!("{NAME}: decode_stream refused: {e}"), - }; - assert!( - decode::palette_uv_hits() > before, - "palette_uv_mode never fired decoding this stream -- gate is vacuous" - ); - let frame_count = frames.len(); - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 64, 64, frame_count); - for i in 0..frame_count { - assert_eq!(frames[i].y, ffmpeg_frames[i].y, "luma vs ffmpeg, frame {i}"); - assert_eq!(frames[i].u, ffmpeg_frames[i].u, "U vs ffmpeg, frame {i}"); - assert_eq!(frames[i].v, ffmpeg_frames[i].v, "V vs ffmpeg, frame {i}"); - } - } - - /// A real `aomenc` fixture that lands palette syntax on a HORZ/VERT - /// intra strip (lane-palette2 r5, gating r4's `read_intra_mode_rect` - /// wiring). `smptebars`/`rgbtestsrc` at plain default settings both hit a - /// SQUARE palette refusal or an unrelated 32x32 `HORZ_A`/`VERT_A`/etc - /// partition FIRST on every size/cq combo probed -- `--enable-ab- - /// partitions=0` measurably does not stop aomenc choosing one at this - /// screen-content tune (byte-identical output with `=0` vs `=1`, same - /// aomenc quirk as `[[lane-sbpart-r2]]`'s SB-level AB). Forcing - /// `--min/max-partition-size=64` sidesteps that whole 32x32-level code - /// path: the only choices left at the (single, key-frame) superblock are - /// NONE/SPLIT/HORZ/VERT/AB/1to4 straight from [`decode_block_rect64`], - /// and a size/cq sweep (measured live this round) reliably lands - /// PARTITION_HORZ/VERT with a real (non-split-tx) palette block on both - /// sources. Drives `decode_stream` directly (below any refusal) and - /// HARD-asserts [`decode::palette_rect_hits`] moved on every attempt that - /// didn't refuse, before comparing pixels ([[gate-blind-to-feature]]) -- - /// a decode that never lands a rect palette block is not a match. - #[test] - fn a_real_aomenc_stream_with_rect_palette_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_stream_with_rect_palette_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let mut matched = 0u32; - let mut uncounted_exact = 0u32; - let mut named_refusals = 0u32; - let mut attempts = 0u32; - let sizes = [(64, 128), (128, 64), (128, 128), (128, 192), (192, 192)]; - let cqs = [5u32, 15, 25, 35, 45, 55, 63]; - for src_name in ["smptebars", "rgbtestsrc"] { - for (width, height) in sizes { - for cq in cqs { - attempts += 1; - let source = format!("{src_name}=size={width}x{height}:rate=25"); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-pix_fmt", - "yuv420p", - "-t", - "0.04", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let cq_arg = format!("--cq-level={cq}"); - let out = run_with_stdin( - Command::new(aomenc_path()).args([ - "--codec=av1", - "--passes=1", - "--end-usage=q", - &cq_arg, - "--cpu-used=4", - "--threads=1", - "--row-mt=0", - "--sb-size=64", - "--enable-palette=1", - "--min-partition-size=16", - "--max-partition-size=64", - "--obu", - "-o", - "-", - "-", - ]), - &y4m.stdout, - ); - assert!( - out.status.success(), - "aomenc refused the fixture ({source} cq={cq}): {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let before = crate::decode::palette_rect_hits(); - let frames = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME} failed outright, not a named refusal \ - ({source} cq={cq}): {msg}" - ); - named_refusals += 1; - eprintln!("{source} cq={cq}: refusal: {msg}"); - continue; - } - Ok(frames) => frames, - }; - // A successful decode is ALWAYS pixel-compared; the hit - // counter only decides whether the attempt counts toward - // the hit-asserting total (class - // [[gate-skips-on-its-own-failure]]: the old `continue` - // here let 16/70 decoded attempts past without any pixel - // check at all). - let counted = crate::decode::palette_rect_hits() != before; - if !counted { - eprintln!( - "{NAME}: {source} cq={cq} decoded without ever landing a rect \ - palette block (palette_rect_hits unchanged) -- pixel-compared, \ - not counted toward the hit assertion" - ); - } - let frame_count = frames.len(); - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count); - if frames - .iter() - .zip(&ffmpeg_frames) - .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v) - && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") - { - std::fs::write(&path, &stream).expect("writing pinned stream"); - eprintln!( - "EC_AV1_GATE_DUMP: wrote mismatching stream ({source} cq={cq}) to {path}" - ); - } - for i in 0..frame_count { - assert_eq!( - frames[i].y, ffmpeg_frames[i].y, - "{NAME}: {source} cq={cq} frame {i} luma vs ffmpeg" - ); - assert_eq!( - frames[i].u, ffmpeg_frames[i].u, - "{NAME}: {source} cq={cq} frame {i} U vs ffmpeg" - ); - assert_eq!( - frames[i].v, ffmpeg_frames[i].v, - "{NAME}: {source} cq={cq} frame {i} V vs ffmpeg" - ); - } - if counted { - matched += 1; - } else { - uncounted_exact += 1; - } - } - } - } - assert!( - matched > 0, - "{NAME}: no attempt out of {attempts} ever landed a matching rect palette \ - block ({named_refusals} named refusals) -- palette_rect_hits never proven \ - pixel-exact" - ); - eprintln!( - "{NAME}: {matched}/{attempts} attempts matched pixel-exact, \ - {uncounted_exact} decoded-and-pixel-exact but uncounted, {named_refusals} \ - named refusals, palette_rect_hits={}", - crate::decode::palette_rect_hits() - ); - } - - /// The BROAD case (lane-palette2 r6, per its charter): a HORZ/VERT intra - /// strip in a screen-content-tools frame that does NOT necessarily use a - /// palette. This is what the refusal r4 removed actually guarded -- - /// [`a_real_aomenc_stream_with_rect_palette_decodes_pixel_exact`] above - /// gates the rarer "and picks a palette" case, which r5 measured RD - /// almost never chooses -- 39/70 of that same sweep DID land here (a - /// clean rect-strip decode with `palette_rect_hits` unchanged), just - /// uncounted by r5's narrower assertion. Same `--min/max-partition-size=64` - /// recipe r5 measured live to dodge the 32x32-level AB-partition quirk - /// ([[lane-sbpart-r2]]), single key frame, size/cq sweep. HARD-asserts - /// [`decode::rect_screen_content_hits`] moved -- proof this stream - /// actually ran [`read_intra_mode_rect`]'s screen-content-tools branch -- - /// before comparing pixels. - #[test] - fn a_real_aomenc_stream_with_rect_screen_content_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_stream_with_rect_screen_content_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let mut matched = 0u32; - // Blocks that reconstructed a palette-Y prediction through a SPLIT - // luma transform (lane-palette2 r7's lifted refusal): the same - // screen-content streams exercise it, so this gate proves both. - let mut split_palette_matched = 0u32; - let mut uncounted_exact = 0u32; - let mut named_refusals = 0u32; - let mut attempts = 0u32; - let sizes = [(64, 128), (128, 64), (128, 128), (128, 192), (192, 192)]; - let cqs = [5u32, 15, 25, 35, 45, 55, 63]; - for src_name in ["smptebars", "rgbtestsrc"] { - for (width, height) in sizes { - for cq in cqs { - attempts += 1; - let source = format!("{src_name}=size={width}x{height}:rate=25"); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-pix_fmt", - "yuv420p", - "-t", - "0.04", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let cq_arg = format!("--cq-level={cq}"); - let out = run_with_stdin( - Command::new(aomenc_path()).args([ - "--codec=av1", - "--passes=1", - "--end-usage=q", - &cq_arg, - "--cpu-used=4", - "--threads=1", - "--row-mt=0", - "--sb-size=64", - "--enable-palette=1", - "--min-partition-size=16", - "--max-partition-size=64", - "--obu", - "-o", - "-", - "-", - ]), - &y4m.stdout, - ); - assert!( - out.status.success(), - "aomenc refused the fixture ({source} cq={cq}): {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let before = crate::decode::rect_screen_content_hits(); - let split_before = crate::decode::palette_split_tx_hits(); - let frames = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME} failed outright, not a named refusal \ - ({source} cq={cq}): {msg}" - ); - named_refusals += 1; - eprintln!("{source} cq={cq}: refusal: {msg}"); - continue; - } - Ok(frames) => frames, - }; - // Same integrity rule as the palette gate above: decoded - // means pixel-compared, counter or no counter. - let counted = crate::decode::rect_screen_content_hits() != before; - if !counted { - eprintln!( - "{NAME}: {source} cq={cq} decoded without ever running the rect \ - screen-content path (rect_screen_content_hits unchanged) -- \ - pixel-compared, not counted toward the hit assertion" - ); - } - let frame_count = frames.len(); - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count); - if frames - .iter() - .zip(&ffmpeg_frames) - .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v) - && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") - { - std::fs::write(&path, &stream).expect("writing pinned stream"); - eprintln!( - "EC_AV1_GATE_DUMP: wrote mismatching stream ({source} cq={cq}) to {path}" - ); - } - for i in 0..frame_count { - assert_eq!( - frames[i].y, ffmpeg_frames[i].y, - "{NAME}: {source} cq={cq} frame {i} luma vs ffmpeg" - ); - assert_eq!( - frames[i].u, ffmpeg_frames[i].u, - "{NAME}: {source} cq={cq} frame {i} U vs ffmpeg" - ); - assert_eq!( - frames[i].v, ffmpeg_frames[i].v, - "{NAME}: {source} cq={cq} frame {i} V vs ffmpeg" - ); - } - if counted { - matched += 1; - } else { - uncounted_exact += 1; - } - if counted && crate::decode::palette_split_tx_hits() > split_before { - split_palette_matched += 1; - } - } - } - } - assert!( - split_palette_matched > 0, - "{NAME}: no pixel-exact attempt ever reconstructed a palette block with a \ - split luma transform -- the lifted refusal is ungated" - ); - assert!( - matched > 0, - "{NAME}: no attempt out of {attempts} ever landed a matching rect \ - screen-content block ({named_refusals} named refusals) -- \ - rect_screen_content_hits never proven pixel-exact" - ); - eprintln!( - "{NAME}: {matched}/{attempts} attempts matched pixel-exact \ - ({split_palette_matched} of them through a split-transform palette block), \ - {uncounted_exact} decoded-and-pixel-exact but uncounted, \ - {named_refusals} named refusals, rect_screen_content_hits={}, \ - palette_split_tx_hits={}", - crate::decode::rect_screen_content_hits(), - crate::decode::palette_split_tx_hits() - ); - } - - /// As [`a_real_aomenc_filter_intra_stream_decodes_pixel_exact`]'s - /// harness, but with the deblocking filter left *on* (no - /// `--loopfilter-control=0`) at a crf high enough that libaom actually - /// picks a nonzero level -- proves `apply_deblock` itself, not just that - /// this decoder still works when every edge lands on level 0. CDEF - /// stays off so a pixel mismatch can only come from the loop filter. - /// - /// lane-av1skipfix: the attempt-loop shape. The sweep walks cq (which is - /// what decides whether libaom picks a nonzero deblocking level at all) - /// and seed, REQUIRES at least one attempt to decode, and hard-asserts - /// `decode::deblock_hits` on a pixel-compared attempt -- a decode error on - /// every attempt is a hard failure carrying the refusal texts, never a - /// printed SKIP (class `gate-skips-on-its-own-failure`). MEASURED - /// 2026-09-29 on `a21f3680`: cq 55/45/35/63 all decode pixel-exact with - /// 48/64/64/64 deblock edges, so the old single recipe was one lucky - /// point of a cq range that needed no fallback. - #[test] - fn a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height) = (64usize, 64usize); - // Two seeds x four quantisers. - const CQS: [u32; 4] = [55, 45, 35, 63]; - let mut refusals = Vec::new(); - let mut counted_exact = 0u32; - let mut uncounted_exact = 0u32; - 'attempts: for round in 0..2u32 { - for cq in CQS { - let source = gradients_source(42 + round, width, height, "duration=0.04:rate=25"); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args(["-v", "error", "-f", "lavfi", "-i"]) - .arg(&source) - .args(["-pix_fmt", "yuv420p", "-f", "yuv4mpegpipe", "-"]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "{NAME}: ffmpeg fixture (seed {} cq {cq}): {}", - 42 + round, - String::from_utf8_lossy(&y4m.stderr) - ); - let cq_arg = format!("--cq-level={cq}"); - let out = run_with_stdin( - Command::new(aomenc_path()).args([ - // lane-defon r1: explicit on-value (aomenc keeps the FIRST - // occurrence, so overrides go before the base list). - "--loopfilter-control=1", - "--codec=av1", - "--passes=1", - "--end-usage=q", - &cq_arg, - "--cpu-used=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-tx-size-search=0", - "--enable-cdef=0", - // Loop restoration is a named refusal (aomenc's RD picks - // Sgrproj on this kind of content) -- off in every recipe - // whose test targets a different surface. - "--enable-restoration=0", - "--max-partition-size=32", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack; - // leaving it on silently desyncs symbols on inter frames (grainfix lesson). - "--enable-ref-frame-mvs=0", - "--obu", - "-o", - "-", - "-", - ]), - &y4m.stdout, - ); - assert!( - out.status.success(), - "{NAME}: aomenc refused the seed {} cq {cq} fixture: {}", - 42 + round, - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let before = decode::deblock_hits(); - let frames = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => { - refusals.push(format!("seed {} cq {cq}: {e}", 42 + round)); - continue; - } - }; - // A decode that succeeded is ALWAYS pixel-compared; the hit - // counter only decides whether the attempt counts as firing - // (class `counter-from-refused-stream`). - let counted = decode::deblock_hits() != before; - if counted { - counted_exact += 1; - } else { - uncounted_exact += 1; - } - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1); - assert_eq!( - frames[0].y, - ffmpeg_frames[0].y, - "luma vs ffmpeg (seed {} cq {cq}, deblock fired: {counted})", - 42 + round - ); - assert_eq!( - frames[0].u, - ffmpeg_frames[0].u, - "U vs ffmpeg (seed {} cq {cq}, deblock fired: {counted})", - 42 + round - ); - assert_eq!( - frames[0].v, - ffmpeg_frames[0].v, - "V vs ffmpeg (seed {} cq {cq}, deblock fired: {counted})", - 42 + round - ); - if counted_exact >= 2 { - break 'attempts; - } - } - } - gate_buckets(NAME, counted_exact, uncounted_exact, refusals.len()); - assert!( - counted_exact > 0, - "{NAME}: none of {} attempts decoded a stream with a deblocking edge -- \ - apply_deblock is unproven (class gate-blind-to-feature):\n{}", - CQS.len() * 2, - refusals.join("\n") - ); - } - - /// As [`a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact`], - /// but WITHOUT `--enable-tx-size-search=0` -- the one flag every other - /// recipe in this file pins off specifically to keep the stream on - /// `TxMode::Largest`. Dropped, aomenc's RD is free to pick - /// `TxMode::Select` and split some blocks' luma transform below their own - /// side (spec 5.11.16), which is what this test's `tx_depth_hits()` - /// counter proves actually happened -- a stream that resolves every - /// `tx_depth` to 0 would pixel-match by construction (identical to - /// `TxMode::Largest`) without exercising the new split-TU decode path at - /// all. Same multi-seed retry shape as - /// [`a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact`]: - /// aomenc's own RD is free (with tx-size search on) to also occasionally - /// pick `allow_screen_content_tools` on this content, a separate, - /// already-named refusal -- try several seeds, and the first stream that - /// both decodes AND actually split a transform must be pixel-exact. - #[test] - fn a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact() { - if !have_ffmpeg() { - eprintln!( - "SKIP a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact: no ffmpeg" - ); - return; - } - if !have_aomenc() { - eprintln!( - "SKIP a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact: no aomenc at {}", - aomenc_path().display() - ); - return; - } - let (width, height) = (64usize, 64usize); - let mut refusals = Vec::new(); - let mut uncounted_exact = 0u32; - for attempt in 0..40u32 { - let seed = 42 + attempt; - // A flat gradient never has enough local detail for the RD - // search to prefer a split transform over the block's own full - // size -- `mandelbrot`'s fractal boundary gives every attempt - // (a different `start_scale`) sharp, varied-frequency edges. - // start_scale 5.0 is the proven first try (decodes pixel-exact - // AND reads the seven-symbol set-1 tx_type rows on TX8 TUs); - // later attempts walk down for variety when aomenc's RD flips - // elsewhere. - let source = format!( - "mandelbrot=size=64x64:start_scale={}:rate=25", - 5.0 - f64::from(attempt) * 0.06 - ); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - // Desaturated: chroma stays flat (constant 128) so - // `uv_mode` always resolves to `DC_PRED` and this - // decoder's still-unsupported directional-chroma round-2 - // gap never fires, leaving the luma detail alone to - // drive whether `TxMode::Select`'s RD splits a block. - "-vf", - "hue=s=0", - "-pix_fmt", - "yuv420p", - "-t", - "0.04", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let out = run_with_stdin( - Command::new(aomenc_path()).args([ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=45", - "--cpu-used=0", - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - // Every non-DC intra tool off: directional chroma and - // angle deltas are separate round-2 gaps, and DC-only - // residual is exactly what gives the RD search a reason - // to split a transform. - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-cdef=0", - // Loop restoration is a named refusal (aomenc's RD picks - // Sgrproj on this kind of content) -- off in every recipe - // whose test targets a different surface. - "--enable-restoration=0", - "--max-partition-size=32", - // 16x16 blocks are what split into the TX8 TUs whose - // set-1 tx_type rows this gate exists to prove; some - // scales resolve depth 2 (TX4, a named refusal) and the - // attempt loop just moves on. - "--min-partition-size=16", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack; - // leaving it on silently desyncs symbols on inter frames (grainfix lesson). - "--enable-ref-frame-mvs=0", - "--obu", - "-o", - "-", - "-", - ]), - &y4m.stdout, - ); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let before = decode::tx_depth_hits(); - let frames = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => { - refusals.push(format!("seed {seed}: {e}")); - continue; - } - }; - // class [[gate-skips-on-its-own-failure]]: a decode that succeeded - // is ALWAYS pixel-compared below; the hit counter only decides whether - // the attempt counts toward the firing total. - let counted = decode::tx_depth_hits() != before; - if !counted { - uncounted_exact += 1; - refusals.push(format!( - "seed {seed}: decoded and pixel-compared, but no block resolved a split \ - tx_depth" - )); - } - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1); - assert_eq!( - frames[0].y, ffmpeg_frames[0].y, - "luma vs ffmpeg (seed {seed})" - ); - assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (seed {seed})"); - assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (seed {seed})"); - if counted { - gate_buckets( - "a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact", - 1, - uncounted_exact, - refusals.len() - uncounted_exact as usize, - ); - return; - } - } - gate_buckets( - "a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact", - 0, - uncounted_exact, - refusals.len() - uncounted_exact as usize, - ); - eprintln!( - "SKIP a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact: every attempt \ - hit a named refusal or never split a transform:\n{}", - refusals.join("\n") - ); - } - - /// lane-txselect's decisive gate: a real aomenc INTER sequence WITHOUT - /// `--enable-tx-size-search=0`, the flag every other inter recipe in this - /// file pins off precisely to keep the stream on `TxMode::Largest`. - /// Dropped, aomenc takes its own default (`TX_MODE_SELECT` -- which is - /// what both of the user's real films use), and an inter block's - /// transform size is then the recursive `txfm_split` tree of spec - /// 5.11.17 rather than one whole-block transform. A stream that decoded - /// pixel-exact while every `txfm_split` symbol resolved to "no split" - /// would prove nothing (it is `TxMode::Largest` by another name), so this - /// gate hard-asserts BOTH counters: at least one `txfm_split` symbol read - /// AND at least one split actually taken. Exhausting every attempt is a - /// FAILURE, not a SKIP -- an unfired gate is a vacuous gate. - #[test] - fn a_real_aomenc_inter_sequence_with_tx_select_decodes_pixel_exact() { - tx_select_inter_gate(8); - } - - /// The 10-bit arm of the gate above (lane-txselect r2): both of the - /// user's films are `yuv420p10le` and var-tx is exactly the tool they - /// use, so an 8-bit-only proof would not reach them. Same recipe plus - /// `-b 10 --input-bit-depth=10`. - #[test] - fn a_real_aomenc_inter_sequence_with_tx_select_decodes_pixel_exact_10bit() { - tx_select_inter_gate(10); - } - - /// lane-intrarect r1's decisive gate: a real aomenc INTER sequence whose - /// hard mid-GOP content cut makes aomenc code INTRA blocks inside inter - /// frames, with rect partitions ON so those intra blocks land on - /// HORZ/VERT strip shapes. Every such block was the named refusal "an - /// intra-coded HORZ/VERT strip needs rectangular intra prediction this - /// decoder does not code yet" until this round; they now decode through - /// the same `decode_rect_split` machinery the key-frame rect paths use. - /// - /// Hard-asserts per-shape counters (`intra_rect_strip_in_inter_hits`: - /// 0 = 64x32/32x64, 1 = 32x16/16x32, 2 = 16x8/8x16) summed over the - /// attempts that were actually pixel-compared -- at least TWO of the - /// three shape classes must fire, so a green run cannot come from one - /// lucky size. A decode that succeeds is ALWAYS pixel-compared (class - /// [[gate-skips-on-its-own-failure]]); exhausting every attempt without - /// two shapes is a FAILURE, never a SKIP. - #[test] - fn a_real_aomenc_inter_sequence_with_an_intra_rect_strip_decodes_pixel_exact() { - intra_rect_in_inter_gate(8); - } - - /// The 10-bit arm (both of the user's films are `yuv420p10le`). - #[test] - fn a_real_aomenc_inter_sequence_with_an_intra_rect_strip_decodes_pixel_exact_10bit() { - intra_rect_in_inter_gate(10); - } - - /// lane-intrainter r1's decisive gate: a real aomenc INTER sequence in - /// which aomenc's RD picks an INTRA block inside an inter frame AND - /// splits that block's luma transform (`tx_depth >= 1`, the intra depth - /// symbol -- not the inter var-tx tree). That block codes one intra - /// prediction plus one coefficient set per transform unit, exactly like a - /// key frame's split block but with the inter frame's CDF state and the - /// inter-frame intra mode syntax; before this lane it was a named - /// refusal. Hard-asserts [`decode::intra_in_inter_split_tx_hits`] per - /// block size: an attempt that never produced such a block proves - /// nothing, and exhausting every attempt is a FAILURE, not a SKIP. - #[test] - fn a_real_aomenc_inter_sequence_with_a_split_transform_intra_block_decodes_pixel_exact() { - intra_in_inter_split_tx_gate(8); - } - - /// The 10-bit arm (both of the user's films are `yuv420p10le`). - #[test] - fn a_real_aomenc_10bit_inter_sequence_with_a_split_transform_intra_block_decodes_pixel_exact() { - intra_in_inter_split_tx_gate(10); - } - - /// lane-fiinter r1 (class [[symbol-consumption-gap]] + - /// [[tool-disabled-in-every-gate]]): a real aomenc inter sequence with - /// `--enable-filter-intra=1` (aomenc's own default -- every inter gate - /// recipe before this one pinned it OFF, so nothing ever exercised it) in - /// which the RD picks an INTRA block inside an inter frame and gives it - /// filter intra. `read_intra_block_mode_info` reads `use_filter_intra` - /// there exactly as a key frame does; this decoder read no such symbol at - /// all until this round, so such a stream desynced at that symbol and - /// decoded silently wrong. Hard-asserts - /// [`decode::intra_in_inter_filter_intra_hits`]: an attempt that never - /// produced one proves nothing, and exhausting every attempt is a - /// FAILURE, not a SKIP. - #[test] - fn a_real_aomenc_inter_sequence_with_filter_intra_on_an_intra_block_decodes_pixel_exact() { - filter_intra_in_inter_gate(8); - } - - /// The 10-bit arm (both of the user's films are `yuv420p10le`). - #[test] - fn a_real_aomenc_10bit_inter_sequence_with_filter_intra_on_an_intra_block_decodes_pixel_exact() - { - filter_intra_in_inter_gate(10); - } - - /// lane-angleinter r1 (class [[refusal-strings-are-claims]] + - /// [[tool-disabled-in-every-gate]]): a real aomenc inter sequence with - /// `--enable-angle-delta=1` and `--enable-directional-intra=1` (aomenc's - /// own defaults; every inter gate before this one pinned BOTH off) in - /// which the RD gives an INTRA block inside an inter frame a directional - /// luma mode with a nonzero `angle_delta_y`. Both intra-in-inter arms - /// read that symbol and then REFUSED it as "this encoder never writes - /// one" -- the claim is false, `read_intra_angle_info` writes it exactly - /// as a key frame does. Hard-asserts - /// [`decode::intra_in_inter_angle_delta_y_hits`]; an attempt that never - /// produced one proves nothing, and exhausting every attempt is a - /// FAILURE, not a SKIP. - #[test] - fn a_real_aomenc_inter_sequence_with_a_directional_intra_block_with_angle_delta_decodes_pixel_exact() - { - angle_delta_in_inter_gate(8, "--min-partition-size=16"); - } - - /// The 10-bit arm (both of the user's films are `yuv420p10le`). - #[test] - fn a_real_aomenc_10bit_inter_sequence_with_a_directional_intra_block_with_angle_delta_decodes_pixel_exact() - { - angle_delta_in_inter_gate(10, "--min-partition-size=16"); - } - - /// lane-uv8 r1 (classes [[refusal-strings-are-claims]] + - /// [[tool-disabled-in-every-gate]]): a real aomenc inter sequence with - /// 8x8 partitions and full chroma intra tooling - /// (`--enable-cfl-intra=1 --enable-smooth-intra=1 --enable-paeth-intra=1 - /// --enable-directional-intra=1`), in which the RD gives an INTRA 8x8 - /// leaf inside an inter frame a NON-DC `uv_mode`. That leaf - /// ([`decode::decode_inter_block8`]'s intra arm) read the `uv_mode` - /// symbol and refused every value but `DC_PRED` -- "this encoder never - /// writes one" was a claim, and this gate is what contradicts it. Hard- - /// asserts `decode::intra_in_inter8_uv_hits` (directional, smooth/paeth, - /// CfL, counted on THIS leaf only); an attempt that never produced one - /// proves nothing, and exhausting every attempt is a FAILURE, not a SKIP. - #[test] - fn a_real_aomenc_inter_sequence_with_a_non_dc_chroma_8x8_intra_leaf_decodes_pixel_exact() { - uv_mode_in_inter8_gate(8, 1); - } - - /// The 10-bit arm (both of the user's films are `yuv420p10le`). - #[test] - fn a_real_aomenc_10bit_inter_sequence_with_a_non_dc_chroma_8x8_intra_leaf_decodes_pixel_exact() - { - uv_mode_in_inter8_gate(10, 1); - } - - /// The multi-tile arm (class [[new-map-ignores-tile-edge]]): this round - /// stamps a new `uv_mode` band from the 8x8 leaf, whose availability must - /// be tile-relative. - #[test] - fn a_real_aomenc_two_tile_inter_sequence_with_a_non_dc_chroma_8x8_intra_leaf_decodes_pixel_exact() - { - uv_mode_in_inter8_gate(8, 2); - } - - /// lane-leaf8tx r1: the refusal this round lifts on an INTRA 8x8 leaf - /// inside an INTER frame -- a nonzero luma `angle_delta_y` on it - /// (`--enable-angle-delta=1`, - /// `av1_use_angle_delta(BLOCK_8X8)`). Both counters are per-attempt - /// deltas on an attempt that decoded to the end and is pixel-compared - /// (class [[counter-from-refused-stream]]); a decode error or a mismatch - /// is a FAILURE, never a SKIP. - #[test] - fn a_real_aomenc_inter_sequence_with_an_angle_delta_8x8_intra_leaf_decodes_pixel_exact() { - tx_split_angle_in_inter8_gate(8); - } - - /// The 10-bit arm (both of the user's films are `yuv420p10le`). - #[test] - fn a_real_aomenc_10bit_inter_sequence_with_an_angle_delta_8x8_intra_leaf_decodes_pixel_exact() { - tx_split_angle_in_inter8_gate(10); - } - - /// lane-chroma r2 stage 1: a real aomenc key frame with - /// `--enable-smooth-intra=1` (opposite of every sibling recipe's `=0`) - /// and `--enable-paeth-intra=0` -- paeth chroma stays off so the still- - /// refused smooth/paeth `uv_mode` (round-2, unrelated to this gate) never - /// fires; smooth *luma* neighbours are exactly what this gate wants to - /// exercise, proving [`decode::smooth_luma_hits`] actually landed a - /// directional block next to a smooth-predicted one and decoded - /// pixel-exact (the [`PlaneBuf::reconstruct`] `smooth_neighbor` fix). - #[test] - fn a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact() { - if !have_ffmpeg() { - eprintln!( - "SKIP a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact: no ffmpeg" - ); - return; - } - if !have_aomenc() { - eprintln!( - "SKIP a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact: no aomenc at {}", - aomenc_path().display() - ); - return; - } - let (width, height) = (64usize, 64usize); - let mut refusals = Vec::new(); - let mut fired_runs = 0u32; - let mut uncounted_exact = 0u32; - for attempt in 0..40u32 { - let seed = 42 + attempt; - let source = format!( - "mandelbrot=size=64x64:start_scale={}:rate=25", - 5.0 - f64::from(attempt) * 0.06 - ); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-pix_fmt", - "yuv420p", - "-t", - "0.04", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let out = run_with_stdin( - Command::new(aomenc_path()).args([ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=45", - "--cpu-used=0", - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=1", - // Smooth/paeth chroma is a still-refused, separate - // round-2 gap -- off so no attempt trips it while this - // gate is purely about luma's edge-filter fix. - "--enable-paeth-intra=0", - "--enable-tx-size-search=0", - "--enable-cdef=0", - "--enable-restoration=0", - "--enable-intra-edge-filter=1", - "--max-partition-size=32", - "--min-partition-size=16", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - "--enable-ref-frame-mvs=0", - "--obu", - "-o", - "-", - "-", - ]), - &y4m.stdout, - ); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let smooth_before = decode::smooth_luma_hits(); - let frames = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => { - refusals.push(format!("seed {seed}: {e}")); - continue; - } - }; - // class [[gate-skips-on-its-own-failure]]: a decode that succeeded - // is ALWAYS pixel-compared below; the hit counter only decides whether - // the attempt counts toward the firing total. - let counted = decode::smooth_luma_hits() != smooth_before; - if counted { - fired_runs += 1; - } else { - uncounted_exact += 1; - refusals.push(format!( - "seed {seed}: decoded and pixel-compared, but no smooth-luma-neighbour block \ - fired" - )); - } - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1); - assert_eq!( - frames[0].y, ffmpeg_frames[0].y, - "luma vs ffmpeg (seed {seed})" - ); - assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (seed {seed})"); - assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (seed {seed})"); - if fired_runs >= 4 { - gate_buckets( - "a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact", - fired_runs, - uncounted_exact, - refusals.len() - uncounted_exact as usize, - ); - return; - } - } - gate_buckets( - "a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact", - fired_runs, - uncounted_exact, - refusals.len() - uncounted_exact as usize, - ); - assert!( - fired_runs > 0, - "every attempt hit a named refusal or never exercised a smooth luma neighbour:\n{}", - refusals.join("\n") - ); - } - - /// The smooth/paeth-chroma gate (lane-chroma r1/r3): a real aomenc key - /// frame with `--enable-smooth-intra=1 --enable-paeth-intra=1` (the - /// opposite of the directional-chroma gate below, which turns these OFF - /// to keep this gap from firing while directional chroma is under test). - /// Some seeds won't pick smooth/paeth for chroma at all -- retry like - /// every other real-encoder gate here, but the first attempt that - /// actually fires [`decode::smooth_uv_hits`] must decode pixel-exact. - #[test] - fn a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact() { - if !have_ffmpeg() { - eprintln!( - "SKIP a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact: no ffmpeg" - ); - return; - } - if !have_aomenc() { - eprintln!( - "SKIP a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact: no aomenc at {}", - aomenc_path().display() - ); - return; - } - let (width, height) = (64usize, 64usize); - let mut refusals = Vec::new(); - let mut fired_runs = 0u32; - let mut uncounted_exact = 0u32; - for attempt in 0..40u32 { - let seed = 42 + attempt; - let source = format!( - "mandelbrot=size=64x64:start_scale={}:rate=25", - 5.0 - f64::from(attempt) * 0.06 - ); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-pix_fmt", - "yuv420p", - "-t", - "0.04", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let out = run_with_stdin( - Command::new(aomenc_path()).args([ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=45", - "--cpu-used=0", - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=1", - "--enable-paeth-intra=1", - "--enable-tx-size-search=0", - "--enable-cdef=0", - "--enable-restoration=0", - "--enable-intra-edge-filter=1", - "--max-partition-size=32", - // 8x8/leaf8 splits are a separate, already-named refusal. - "--min-partition-size=16", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - "--enable-ref-frame-mvs=0", - "--obu", - "-o", - "-", - "-", - ]), - &y4m.stdout, - ); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let smooth_before = decode::smooth_uv_hits(); - let frames = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => { - refusals.push(format!("seed {seed}: {e}")); - continue; - } - }; - // class [[gate-skips-on-its-own-failure]]: a decode that succeeded - // is ALWAYS pixel-compared below; the hit counter only decides whether - // the attempt counts toward the firing total. - let counted = decode::smooth_uv_hits() != smooth_before; - if counted { - fired_runs += 1; - } else { - uncounted_exact += 1; - refusals.push(format!( - "seed {seed}: decoded and pixel-compared, but no smooth/paeth uv_mode fired" - )); - } - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1); - assert_eq!( - frames[0].y, ffmpeg_frames[0].y, - "luma vs ffmpeg (seed {seed})" - ); - assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (seed {seed})"); - assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (seed {seed})"); - if fired_runs >= 4 { - gate_buckets( - "a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact", - fired_runs, - uncounted_exact, - refusals.len() - uncounted_exact as usize, - ); - return; - } - } - gate_buckets( - "a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact", - fired_runs, - uncounted_exact, - refusals.len() - uncounted_exact as usize, - ); - assert!( - fired_runs > 0, - "every attempt hit a named refusal or never exercised smooth/paeth chroma:\n{}", - refusals.join("\n") - ); - } - - /// The directional-chroma/angle-delta gate: a real aomenc key frame with - /// `--enable-directional-intra`/`--enable-angle-delta` left ON (the - /// opposite of every sibling recipe's `=0`, which existed specifically to - /// keep this round-2 gap from firing while a different surface was under - /// test). A colourful, sharp-edged source gives the RD search a reason to - /// pick a directional `uv_mode` and/or a nonzero angle delta -- some - /// seeds still won't, so retry like every other real-encoder gate here, - /// but the first attempt that actually fires either counter must decode - /// pixel-exact. - #[test] - fn a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact() { - if !have_ffmpeg() { - eprintln!( - "SKIP a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact: no ffmpeg" - ); - return; - } - if !have_aomenc() { - eprintln!( - "SKIP a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact: no aomenc at {}", - aomenc_path().display() - ); - return; - } - let (width, height) = (64usize, 64usize); - let mut refusals = Vec::new(); - let mut fired_runs = 0u32; - let mut uncounted_exact = 0u32; - for attempt in 0..40u32 { - let seed = 42 + attempt; - let source = format!( - "mandelbrot=size=64x64:start_scale={}:rate=25", - 5.0 - f64::from(attempt) * 0.06 - ); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-pix_fmt", - "yuv420p", - "-t", - "0.04", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let out = run_with_stdin( - Command::new(aomenc_path()).args([ - // lane-defon r1: explicit on-value (aomenc keeps the FIRST - // occurrence, so overrides go before the base list). - "--enable-directional-intra=1", - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=45", - "--cpu-used=0", - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - // Smooth/Paeth chroma is a separate, still-refused round-2 - // gap (an unrelated `Edges::build` no-neighbour bug this - // lane does not cover) -- off so the RD search's only - // non-DC/CFL chroma choice left is directional. - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-tx-size-search=0", - "--enable-cdef=0", - "--enable-restoration=0", - // The intra edge filter/upsample (spec 7.11.2.7-2.9) is - // now implemented (`directional()`) -- left ON (aomenc's - // own default) so this gate actually exercises it instead - // of the un-filtered fast path a disabled flag would keep - // testing. - "--enable-intra-edge-filter=1", - "--max-partition-size=32", - // Same reason as the tx-select gate above: 8x8 and other - // sub-16x16 splits are a separate, already-named refusal. - "--min-partition-size=16", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack; - // leaving it on silently desyncs symbols on inter frames (grainfix lesson). - "--enable-ref-frame-mvs=0", - "--obu", - "-o", - "-", - "-", - ]), - &y4m.stdout, - ); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let (uv_before, angle_before) = - (decode::directional_uv_hits(), decode::angle_delta_hits()); - let frames = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => { - refusals.push(format!("seed {seed}: {e}")); - continue; - } - }; - // class [[gate-skips-on-its-own-failure]]: a decode that succeeded - // is ALWAYS pixel-compared below; the hit counter only decides whether - // the attempt counts toward the firing total. - let counted = decode::directional_uv_hits() != uv_before - || decode::angle_delta_hits() != angle_before; - if counted { - fired_runs += 1; - } else { - uncounted_exact += 1; - refusals.push(format!( - "seed {seed}: decoded and pixel-compared, but neither a directional uv_mode \ - nor a nonzero angle delta fired" - )); - } - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1); - assert_eq!( - frames[0].y, ffmpeg_frames[0].y, - "luma vs ffmpeg (seed {seed})" - ); - assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (seed {seed})"); - assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (seed {seed})"); - if fired_runs >= 4 { - gate_buckets( - "a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact", - fired_runs, - uncounted_exact, - refusals.len() - uncounted_exact as usize, - ); - return; - } - } - gate_buckets( - "a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact", - fired_runs, - uncounted_exact, - refusals.len() - uncounted_exact as usize, - ); - assert!( - fired_runs > 0, - "every attempt hit a named refusal or never exercised directional chroma:\n{}", - refusals.join("\n") - ); - } - - #[test] - fn a_real_aomenc_inter_sequence_with_a_whole_superblock_block_decodes_pixel_exact() { - inter_sb_none_gate( - "a_real_aomenc_inter_sequence_with_a_whole_superblock_block_decodes_pixel_exact", - false, - "32", - "64", - decode::inter_sb_none_hits, - "whole-superblock inter PARTITION_NONE", - &[], - 64, - 4, - ); - } - - #[test] - fn a_real_aomenc_10bit_inter_sequence_with_a_whole_superblock_block_decodes_pixel_exact() { - inter_sb_none_gate( - "a_real_aomenc_10bit_inter_sequence_with_a_whole_superblock_block_decodes_pixel_exact", - true, - "32", - "64", - decode::inter_sb_none_hits, - "whole-superblock inter PARTITION_NONE", - &[], - 64, - 4, - ); - } - - /// lane-inter8 r1: the same recipe with `--min-partition-size=8`, so - /// aomenc's RD may split a 16x16 inter block into four 8x8 leaves. The - /// interior (non-edge-straddling) `PARTITION_SPLIT` at the 16x16 level - /// was refused by name until this round; the straddle path always ran the - /// same loop, so only [`decode::inter_sub16_split_hits`] -- which counts - /// interior splits only -- proves the newly-lifted alphabet value fired. - // lane-inter8 r2: GREEN. The neighbour side bands are mi-granular, every - // leaf stamps its own 2x2-mi span (including the compound-return path - // that used to skip `record_mi` entirely) and the compound - // group/index contexts read the LEAF's mi cell, not its 16x16's corner. - /// lane-inter8 r3, from lane-sub8's verifier finding: the mi-granular - /// inter neighbour bands added in r2 must reset per TILE (above) and per - /// SB row (left) and guard availability tile-relative, so the same recipe - /// runs again at 128x64 with two tile columns -- a leaf on the second - /// tile's first column has no left neighbour and must not read the first - /// tile's band. - // Un-ignored 2026-09-04: the SB-level rect-partition refusal (lane-sbpart's arm at 128x64) that blocked this gate is gone and it passes. The tile-relative audit it was written for - // was done by inspection instead: every reader of the mi bands guards on - // `tile_row0_mi`/`tile_col0_mi` (no `> 0` guard exists in decode.rs), - // `start_tile` resets the above mi bands over the tile's own mi column - // span and `start_row` resets every left mi band. - #[test] - fn a_real_aomenc_inter_sequence_with_an_8x8_leaf_split_across_tile_columns_decodes_pixel_exact() - { - inter_sb_none_gate( - "a_real_aomenc_inter_sequence_with_an_8x8_leaf_split_across_tile_columns_decodes_pixel_exact", - false, - "8", - "16", - decode::inter_sub16_split_hits, - "interior 16x16 inter PARTITION_SPLIT into 8x8 leaves", - &["--tile-columns=1"], - 128, - 4, - ); - } - - /// lane-interp3 r1: the same 8x8-leaf recipe with DUAL FILTER, OBMC and - /// warped motion on. `read_mb_interp_filter` runs for every inter block - /// (libaom `decodemv.c` 1575), compound ones included; the compound 8x8 - /// leaf skipped it entirely, so a SWITCHABLE-filter stream lost a symbol - /// per compound leaf and stamped the `[3, 3]` "no filter" sentinel, which - /// made a neighbouring OBMC block's `neighbour_filter` PANIC (a crash on - /// his data, not a named refusal). The three hard asserts prove the flags - /// arrived: a compound 8x8 leaf that really read the filter, a block whose - /// two dual-filter directions DIFFER (impossible with dual filter off), - /// and an 8x8 OBMC blend. - // lane-interp3 r2: the ENTROPY desync r1 measured is CLOSED -- the full - // 16-frame stream now parses end to end and every `EC_MODE`/`EC_MODE_VAL` - // element's msac RANGE matches the instrumented aomdec's line for line - // (570/570 mode elements, 0 diff). Two twin-drift root causes, both in - // `decode_inter_block8`'s compound arm: `read_compound_ref_frames` was - // passed a hard-coded `LAST_FRAME` for every inter neighbour instead of - // the real per-mi band, and the grid stamp cleared both per-slot - // `is_global_mv_block` flags. - // lane-interp3 r3: the luma reconstruction residue r2 left open is CLOSED - // and this gate is GREEN. Third instance of the same twin-drift class: - // libaom applies `allow_warp`'s GLOBAL branch to every - // `is_global_mv_block` reference slot, compound included and independent - // of `motion_mode` (`av1_init_warp_params` inside - // `build_inter_predictors_8x8_and_bigger`'s per-`ref` loop) -- the 16x16+ - // compound arm has warped since lane-cwarp r1, the 8x8 leaf's compound arm - // predicted BOTH taps translationally, so a GLOBAL_GLOBALMV 8x8 compound - // leaf under a non-TRANSLATION model drifted a few luma levels, growing - // away from the block origin. It was NOT OBMC: the `EC_OBMC` emitter this - // round added to `decode.rs` diffs 325/325 lines against the instrumented - // aomdec's own rung (position, span, neighbour mv/ref/bsize/filter) with - // zero differences. - #[test] - fn a_real_aomenc_dual_filter_obmc_8x8_inter_sequence_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_dual_filter_obmc_8x8_inter_sequence_decodes_pixel_exact"; - if !have_ffmpeg() || !have_aomenc() { - eprintln!("SKIP {NAME}: no ffmpeg/aomenc"); - return; - } - let before_dual = decode::dual_filter_diff_hits(); - let before_obmc = decode::obmc_hits_8(); - let before_cwarp8 = decode::compound_warp_hits_8(); - inter_sb_none_gate( - NAME, - false, - "8", - "16", - decode::compound8_filter_hits, - "a compound 8x8 leaf reading its own switchable interp_filter", - &[ - "--enable-dual-filter=1", - "--enable-obmc=1", - "--enable-warped-motion=1", - "--enable-onesided-comp=1", - ], - 64, - // Recipe search hook (same shape as EC_OBMC8_ATTEMPTS): a compound - // block needs several coded references, so the sequence is longer - // than the other arms' 4 frames. - std::env::var("EC_INTERP3_FRAMES") - .ok() - .and_then(|v| v.parse().ok()) - .unwrap_or(16), - ); - assert!( - decode::dual_filter_diff_hits() > before_dual, - "{NAME}: no block read two DIFFERENT dual-filter directions -- \ - --enable-dual-filter=1 did not arrive or aomenc declined it" - ); - assert!( - decode::obmc_hits_8() > before_obmc, - "{NAME}: no 8x8 OBMC blend fired -- --enable-obmc=1 did not arrive" - ); - assert!( - decode::compound_warp_hits_8() > before_cwarp8, - "{NAME}: no 8x8 COMPOUND leaf was predicted through the per-ref GLOBAL \ - warp -- the r3 root-cause path never fired, so this stream no longer \ - proves it" - ); - } - - /// lane-av1dualfilter10: the 10-bit arm of the dual-filter witness. - /// - /// `NEVER_EXERCISED_10BIT` kept `enable-dual-filter` listed after the - /// 8-bit entry was retired (lane-av1distwtd r3, gate_coverage.rs), and - /// the reason was structural, not incidental: the only `=1` witness, - /// `a_real_aomenc_dual_filter_obmc_8x8_inter_sequence_decodes_pixel_exact`, - /// calls `inter_sb_none_gate(NAME, false, ...)` -- and that `false` IS the - /// `ten_bit` parameter, so it built an 8-bit stream. Its `ten_bit = true` - /// siblings build 10-bit streams but spell no dual-filter flag. This is - /// that missing arm. - /// - /// What makes it a witness and not a spelling: the header is read back - /// from the ENCODED stream (`enable_dual_filter` and `bit_depth` both come - /// from `Av1Parser`, never from the flag or the fixture name), and the - /// arrival assert is a DELTA on `decode::dual_filter_diff_hits()` taken - /// around this arm alone. A stream that merely parsed would not move the - /// counter; the counter moves only when `resolve_interp_filter` reads two - /// DIFFERENT directions for one block, which is the property the entry - /// was claiming no real stream carried. - #[test] - fn a_real_aomenc_10bit_dual_filter_obmc_8x8_inter_sequence_decodes_pixel_exact() { - const NAME: &str = - "a_real_aomenc_10bit_dual_filter_obmc_8x8_inter_sequence_decodes_pixel_exact"; - if !have_ffmpeg() || !have_aomenc() { - eprintln!("SKIP {NAME}: no ffmpeg/aomenc"); - return; - } - let before_dual = decode::dual_filter_diff_hits(); - let stream = inter_sb_none_gate( - NAME, - // `ten_bit`: this is the whole difference from the 8-bit witness. - true, - "8", - "16", - decode::compound8_filter_hits, - "a compound 8x8 leaf reading its own switchable interp_filter", - &[ - "--enable-dual-filter=1", - "--enable-obmc=1", - "--enable-warped-motion=1", - "--enable-onesided-comp=1", - ], - 64, - std::env::var("EC_INTERP3_FRAMES") - .ok() - .and_then(|v| v.parse().ok()) - .unwrap_or(16), - ); - // The ARRIVAL assert comes first on purpose. `dual_filter_diff_hits()` - // moves only inside `resolve_interp_filter` when the header bit is set - // AND the block's two directions differ, so pinning it =0 reds HERE, - // on the tool failing to arrive -- not on some shape or pixel assert - // downstream of it. The two header asserts below corroborate it from - // the encoded bytes; they are not what carries the proof. - assert!( - decode::dual_filter_diff_hits() > before_dual, - "{NAME}: no block read two DIFFERENT dual-filter directions in the 10-bit stream \ - -- --enable-dual-filter=1 did not arrive or aomenc declined it" - ); - // Both facts from the PARSED header, not from what we asked for: a - // gate that trusted `--bit-depth=10` would pass on a stream aomenc - // silently coded at 8, which is the vacuity this asserts against. - let mut probe = Av1Parser::new(); - let mut pos = 0usize; - while pos < stream.len() && probe.sequence_header().is_none() { - let obu = probe.parse_obu(&stream[pos..]).unwrap(); - pos += obu.total_size; - } - let seq = probe - .sequence_header() - .expect("stream has a sequence header OBU"); - assert_eq!( - seq.color_config.bit_depth, 10, - "{NAME}: aomenc did not write a 10-bit sequence header" - ); - assert!( - seq.enable_dual_filter, - "{NAME}: the parsed sequence header says enable_dual_filter = false, so this \ - stream cannot carry per-direction interp filters however the pixels compare" - ); - } - - #[test] - fn a_real_aomenc_inter_sequence_with_an_8x8_leaf_split_decodes_pixel_exact() { - inter_sb_none_gate( - "a_real_aomenc_inter_sequence_with_an_8x8_leaf_split_decodes_pixel_exact", - false, - "8", - "16", - decode::inter_sub16_split_hits, - "interior 16x16 inter PARTITION_SPLIT into 8x8 leaves", - &[], - 64, - 4, - ); - } - - #[test] - // Un-ignored 2026-09-04: the desync behind the bogus 32x32 value=9 refusal (class refusal-from-own-desync) is gone and this 10-bit twin decodes pixel-exact. - fn a_real_aomenc_10bit_inter_sequence_with_an_8x8_leaf_split_decodes_pixel_exact() { - inter_sb_none_gate( - "a_real_aomenc_10bit_inter_sequence_with_an_8x8_leaf_split_decodes_pixel_exact", - true, - "8", - "16", - decode::inter_sub16_split_hits, - "interior 16x16 inter PARTITION_SPLIT into 8x8 leaves", - &[], - 64, - 4, - ); - } - - #[test] - fn a_real_aomenc_inter_sequence_with_a_class1_chroma_eob_decodes_pixel_exact() { - chroma_class1_eob_gate( - "a_real_aomenc_inter_sequence_with_a_class1_chroma_eob_decodes_pixel_exact", - false, - ); - } - - #[test] - fn a_real_aomenc_10bit_inter_sequence_with_a_class1_chroma_eob_decodes_pixel_exact() { - chroma_class1_eob_gate( - "a_real_aomenc_10bit_inter_sequence_with_a_class1_chroma_eob_decodes_pixel_exact", - true, - ); - } - - /// lane-inter4 r1: the SUPERBLOCK-level inter `PARTITION_HORZ`/ - /// `PARTITION_VERT` pair -- two 64x32 / 32x64 inter strips, the arm the - /// inter tile path refused outright before this lane ("an inter SB-level - /// partition type other than NONE or SPLIT"). `--min-partition-size=32` - /// keeps every 32x32-level rect shape (already coded, and residual-capable - /// only when skip) out of the picture so the counters can only be earned - /// at the superblock level; the noiseless split-motion source (one half - /// translating, the other static, flat inside each half) is what makes - /// aomenc's RD pick a superblock HORZ/VERT whose strips are `skip` -- - /// the ONLY inter rect shape this decoder can complete, since rectangular - /// inter residual coding is not ported (see `reject_residual`). - /// - /// Every decoded frame is compared to ffmpeg (Y, U and V); an attempt - /// that refuses by name is counted, never turned into a SKIP; and an - /// attempt that decoded without firing the arm is counted separately and - /// still required to be pixel-exact (class gate-skips-on-its-own-failure). - #[test] - fn a_real_aomenc_inter_sequence_with_a_superblock_level_rect_partition_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_inter_sequence_with_a_superblock_level_rect_partition_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height, frame_count) = (192usize, 128usize, 6usize); - // lane-inter4 r1: 8-bit ONLY, and the reason is the lane's own open - // residue, not a tolerance: across all 16 attempts x both depths, every - // 10-bit attempt that reached a superblock-level rect strip found it - // NON-skip, so it stops at "a non-skip rectangular (HORZ/VERT/HORZ_B) - // strip needs rectangular residual coding". The 10-bit twin below is - // `#[ignore]`d with that exact reason rather than deleted or weakened. - // lane-r14 r2 re-measured the 8-bit-only note above: the residual - // refusal it names is GONE (this round codes a 64-px transform axis as - // its truncated low-32 corner), and a 10-bit sweep of this exact - // recipe now reaches the arm -- 2 pixel-exact attempts, 2 64x32 and 2 - // 32x64 strips, 2 of them carrying a coded 64-axis residual. - // lane-sbrect10 r1 closed the newly exposed 10-bit defect r14 r2 - // parked this arm on (10-bit attempt 14, cq 61, horizontal split, - // motion step 12 -- it mismatched ffmpeg while decoding ZERO rect - // strips): a 64x64 INTRA block inside an inter frame read `uv_mode` - // off the 14-symbol CFL-allowed alphabet, which libaom's - // `is_cfl_allowed` caps at 32x32 -- same DC_PRED value, wrong - // interval narrowing, tile desynced from that block on. Both depths - // run now. - for bit_depth in [8u32, 10u32] { - let (mut named_refusals, mut matched, mut out_of_scope, mut oos_mismatch) = - (0u32, 0u32, 0u32, 0u32); - let (mut horz_proved, mut vert_proved) = (0usize, 0usize); - let mut rect64_tus = 0usize; - for attempt in 0..16u32 { - // Two orientations (the transposed pair a one-sided gate could - // never separate) x four quantisers x two motion steps: which - // superblock the RD hands a skip-able rect strip moves with - // the quantiser, and the 10-bit arm needs a different corner - // of the grid from the 8-bit one. - let vertical_split = attempt % 2 == 1; - let cq = [58, 52, 45, 61][(attempt / 2 % 4) as usize]; - let sp = 8 + (attempt / 8) * 4; - let geq = if vertical_split { - format!("if(lt(Y,64), 40+mod(floor((X+N*{sp})/32)*90,200), 200)") - } else { - format!("if(lt(X,64), 40+mod(floor((Y+N*{sp})/32)*90,200), 200)") - }; - let duration = frame_count as f64 / 25.0; - let source = format!( - "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\ - geq=lum='{geq}',format=yuv420p" - ); - let pix_fmt = if bit_depth == 10 { - "yuv420p10le" - } else { - "yuv420p" - }; - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-t", - &duration.to_string(), - "-pix_fmt", - pix_fmt, - "-strict", - "-1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let cq_arg = format!("--cq-level={cq}"); - let depth_arg = format!("--bit-depth={bit_depth}"); - let input_depth_arg = format!("--input-bit-depth={bit_depth}"); - let args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - &cq_arg, - "--cpu-used=0", - "--threads=1", - "--row-mt=0", - "--sb-size=64", - &depth_arg, - &input_depth_arg, - "--enable-restoration=0", - "--enable-palette=0", - "--deltaq-mode=0", - "--enable-filter-intra=0", - "--enable-cfl-intra=0", - "--enable-intrabc=0", - "--enable-tx-size-search=0", - "--lag-in-frames=0", - // Per-arm overrides go LAST: aomenc keeps the last - // occurrence of a repeated --enable-* flag. - "--enable-rect-partitions=1", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=1", - "--min-partition-size=32", - "--max-partition-size=64", - "--obu", - "-o", - "-", - "-", - ]; - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let before = crate::stream::inter_rect_counters(); - let rect64_before = crate::stream::rect64_inter_tu_hits(); - let frames = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \ - attempt {attempt}): {msg}" - ); - named_refusals += 1; - eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}"); - continue; - } - Ok(frames) => frames, - }; - let after = crate::stream::inter_rect_counters(); - let (horz, vert) = (after.2 - before.2, after.3 - before.3); - let rect64 = crate::stream::rect64_inter_tu_hits() - rect64_before; - let ffmpeg_frames = if bit_depth == 10 { - ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count) - } else { - ffmpeg_decode_sequence(&stream, width, height, frame_count) - }; - assert_eq!(frames.len(), frame_count); - let mismatched = frames - .iter() - .zip(&ffmpeg_frames) - .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); - if horz + vert == 0 { - out_of_scope += 1; - if mismatched { - oos_mismatch += 1; - eprintln!( - "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \ - superblock-level inter rect strips -- another shape's defect" - ); - } - continue; - } - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!( - got.y, want.y, - "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit)" - ); - assert_eq!( - got.u, want.u, - "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit)" - ); - assert_eq!( - got.v, want.v, - "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit)" - ); - } - horz_proved += horz; - vert_proved += vert; - rect64_tus += rect64; - matched += 1; - } - eprintln!( - "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \ - attempts carrying the arm, 64x32 strips={horz_proved}, 32x64 strips={vert_proved}, \ - 64-axis residual TUs={rect64_tus}, \ - {out_of_scope} attempts carried none ({oos_mismatch} of them mismatched)" - ); - assert_eq!( - oos_mismatch, 0, - "{NAME}: {oos_mismatch} attempt(s) with no superblock-level inter rect strip \ - decoded but mismatched ffmpeg -- a defect of another shape, not a pass" - ); - // lane-r14 r2: the residual half of the arm -- a strip that is not - // `skip` and codes a real 64-axis transform unit. Without this the - // gate proves only the partition symbol. - assert!( - rect64_tus > 0, - "{NAME} ({bit_depth}-bit): no superblock-level rect strip carried a coded \ - 64-axis residual transform unit inside a pixel-exact attempt \ - (horz={horz_proved}, vert={vert_proved}) -- the residual arm proved nothing" - ); - assert!( - horz_proved + vert_proved > 0, - "{NAME} ({bit_depth}-bit): the superblock-level inter rect arm never fired \ - inside a pixel-exact attempt (horz={horz_proved}, vert={vert_proved}, \ - {named_refusals} refusals, {out_of_scope} out of scope) -- gate proved nothing" - ); - } - } - - /// lane-r14 r3: a 1:4 inter strip with a 64-px axis (64x16 / 16x64) whose - /// transform SPLITS -- the arm r2 left refused by name ("a split transform - /// on a 1:4 inter strip with a 64-px axis"). libaom's - /// `sub_tx_size_map[TX_64X16] == TX_32X16` (and `[TX_16X64] == TX_16X32`) - /// keeps the sub-transform RECTANGULAR, so the var-tx tree's leaves are - /// 32x16/16x32 units read through [`TxbSet::LumaRect32x16Inter`], each with - /// its own `get_txb_ctx_general` neighbour context (the unit is smaller - /// than its block, so `txb_skip_ctx` is NOT the lone-TU 0). - /// - /// `--enable-1to4-partitions=1 --min-partition-size=16 - /// --max-partition-size=64 --enable-tx64=1` (each spelled once, last - /// occurrence wins) is what lets aomenc pick a superblock-level HORZ_4 / - /// VERT_4; the textured translating source is what keeps the strips - /// non-skip so the residual is actually coded. 8-bit AND 10-bit, every - /// decoded frame compared to ffmpeg on Y/U/V, refusals counted (never - /// SKIPped), attempts that carried no rectangular var-tx leaf counted - /// separately and still required pixel-exact. - #[test] - fn real_aomenc_1to4_streams_decode_pixel_exact_and_rect_vartx_leaves_fire_before_a_named_refusal() - { - const NAME: &str = "real_aomenc_1to4_streams_decode_pixel_exact_and_rect_vartx_leaves_fire_before_a_named_refusal"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let frame_count = 6usize; - for bit_depth in [8u32, 10u32] { - let (mut named_refusals, mut compared, mut out_of_scope, mut oos_mismatch) = - (0u32, 0u32, 0u32, 0u32); - let (mut leaf_32x16, mut leaf_16x32) = (0usize, 0usize); - // Leaves decoded on ANY attempt, including one whose stream hits a - // later named refusal: the firing half of this gate, kept apart - // from `leaf_32x16`/`leaf_16x32` (pixel-compared attempts only) so - // a refused stream is never counted as a pixel proof - // (class counter-from-refused-stream). - let (mut fired_32x16, mut fired_16x32) = (0usize, 0usize); - // lane-gaterecipe r1: the firing arms (16-17) are 8-BIT ONLY, and - // this is measured, not a convenience. Their 10-bit twin fires the - // leaves too (32x16=0 16x32=46 on attempt 16) and then MISMATCHES - // ffmpeg at decode-order frame 2 of attempt 17 -- an open DECODE - // defect handed off in lanes/gaterecipe-r1.report.md, never - // silenced inside this loop. - let attempts = if bit_depth == 8 { 18u32 } else { 16u32 }; - for attempt in 0..attempts { - // Two orientations (the transposed pair a one-sided gate could - // never separate) x four quantisers x two motion steps. - // lane-r14 r4 recipe hunt (~70 aomenc runs on the merged - // tree: testsrc2 / life / mandelbrot / banded motion, 64x64 up - // to 384x256, cq 20..58): attempts 16-17 carry the only recipe - // found that makes aomenc code a 64-axis 1:4 strip whose - // transform SPLITS -- 384x256, per-16-column band motion, - // cq 32 (16x32 leaves) and cq 38 (32x16 leaves). - let firing = attempt >= 16; - let (width, height) = if firing { - (384usize, 256usize) - } else { - (192usize, 128usize) - }; - let vertical = attempt % 2 == 1; - // lane-vartxsplit r2, MEASURED against the oracle - // (`EC_VARTX` histogram, ~40 aomenc runs): at cq 10 this - // source splits NO rectangular transform at all -- aomdec - // reads only TX_8X8/TX_16X16/TX_8X16/TX_16X8 split symbols, - // so the leaves gaterecipe r1 counted here came out of a - // stream our decoder was already desynced on (class - // counter-from-refused-stream). cq 44 and 46 are the two - // quantisers of that sweep whose stream really carries - // `TX_32X8`/`TX_8X32` splits (16x8 and 8x16 rectangular - // var-tx leaves) AND decodes pixel-exact on all six frames. - let cq = if firing { - if attempt == 16 { 44 } else { 46 } - } else { - [30, 36, 44, 52][(attempt / 2 % 4) as usize] - }; - let sp = 3 + (attempt / 8) * 3; - // 16-pixel bands, each band translating at its OWN speed - // across the other axis: that is what makes aomenc's RD split - // a 64x64 superblock into four 1:4 strips (`PARTITION_HORZ_4` - // / `VERT_4`) with distinct motion vectors, and the texture - // inside a band is what keeps the strip non-skip and its - // transform split. - let geq = if firing && !vertical { - // lane-gaterecipe r1, MEASURED: the banded translating - // source this arm used until now splits NO transform at - // all -- an aomdec EC_TRACE/EC_TRACE_COEFF histogram of its - // stream reads zero 1:4 partitions and zero rectangular - // sub-transforms, so the leaves the old assert counted came - // out of a stream that stopped at a refusal (class - // counter-from-refused-stream). What DOES split a - // rectangular transform is a high-frequency product texture - // at a fine quantiser with `--min-partition-size=8`: part - // of the block predicts well and part does not, which is - // the RD case for `txfm_partition`. - "128+90*sin((X+N*3)/6)*sin(Y/2)+50*sin((X*Y)/37)".to_string() - } else if firing { - // lane-vartxsplit r2: BOTH leaf orientations come out of - // this one source (three 16x8 leaves and one 8x16 on - // attempt 16), so the firing pair is the same texture at - // two quantisers. Its transposed twin was measured over - // cq 40..56 and splits no rectangular transform at all; - // at cq 56 it also mismatches ffmpeg from decode-order - // frame 2 with ZERO rect var-tx leaves in it -- an open - // reconstruction defect (8-pixel-wide luma column, see - // lanes/vartxsplit-r2.report.md), not something to hide - // inside this gate's attempt list. - "128+90*sin((X+N*3)/6)*sin(Y/2)+50*sin((X*Y)/37)".to_string() - } else if vertical { - format!("128+60*sin((Y+N*({sp}+9*mod(floor(X/16),2)))/7)+25*sin(X/11)") - } else { - format!("128+60*sin((X+N*({sp}+9*mod(floor(Y/16),2)))/7)+25*sin(Y/11)") - }; - let duration = frame_count as f64 / 25.0; - let source = format!( - "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\ - geq=lum='{geq}',format=yuv420p" - ); - let pix_fmt = if bit_depth == 10 { - "yuv420p10le" - } else { - "yuv420p" - }; - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-t", - &duration.to_string(), - "-pix_fmt", - pix_fmt, - "-strict", - "-1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let cq_arg = format!("--cq-level={cq}"); - let depth_arg = format!("--bit-depth={bit_depth}"); - let input_depth_arg = format!("--input-bit-depth={bit_depth}"); - // A rectangular var-tx LEAF needs a block whose max rectangular - // transform can split: `--min-partition-size=8` is what lets - // aomenc's RD reach one (measured); at 16 it never did. - let min_part = if firing { - "--min-partition-size=8" - } else { - "--min-partition-size=16" - }; - let args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - &cq_arg, - "--cpu-used=0", - "--threads=1", - "--row-mt=0", - "--sb-size=64", - &depth_arg, - &input_depth_arg, - "--enable-restoration=0", - "--enable-palette=0", - "--deltaq-mode=0", - "--enable-filter-intra=0", - "--enable-cfl-intra=0", - "--enable-intrabc=0", - "--lag-in-frames=0", - // Per-arm overrides go LAST: aomenc keeps the last - // occurrence of a repeated --enable-* flag. - "--enable-tx64=1", - "--enable-rect-partitions=1", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=1", - "--enable-dual-filter=0", - "--enable-obmc=0", - "--enable-tx-size-search=1", - min_part, - "--max-partition-size=64", - "--obu", - "-o", - "-", - "-", - ]; - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let before = crate::stream::vartx_rect_leaf_hits(); - let frames = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \ - attempt {attempt}): {msg}" - ); - let after = crate::stream::vartx_rect_leaf_hits(); - fired_32x16 += after[0] - before[0]; - fired_16x32 += after[1] - before[1]; - named_refusals += 1; - eprintln!( - "{bit_depth}-bit attempt {attempt} refusal (rect var-tx leaves \ - decoded before it: 32x16={}, 16x32={}): {msg}", - after[0] - before[0], - after[1] - before[1] - ); - continue; - } - Ok(frames) => frames, - }; - let after = crate::stream::vartx_rect_leaf_hits(); - let (h32, v32) = (after[0] - before[0], after[1] - before[1]); - fired_32x16 += h32; - fired_16x32 += v32; - let ffmpeg_frames = if bit_depth == 10 { - ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count) - } else { - ffmpeg_decode_sequence(&stream, width, height, frame_count) - }; - assert_eq!(frames.len(), frame_count); - let mismatched = frames - .iter() - .zip(&ffmpeg_frames) - .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); - if h32 + v32 == 0 { - // Counted per ATTEMPT, on a decoded+compared attempt only - // (class counter-from-refused-stream). - out_of_scope += 1; - if mismatched { - oos_mismatch += 1; - eprintln!( - "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \ - rectangular var-tx leaves -- another shape's defect" - ); - } - continue; - } - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!( - got.y, want.y, - "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit)" - ); - assert_eq!( - got.u, want.u, - "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit)" - ); - assert_eq!( - got.v, want.v, - "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit)" - ); - } - leaf_32x16 += h32; - leaf_16x32 += v32; - compared += 1; - } - eprintln!( - "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {compared} \ - pixel-exact attempts carrying the arm, pixel-compared rect var-tx leaves \ - 32x16={leaf_32x16} 16x32={leaf_16x32}, leaves decoded anywhere in the sweep \ - 32x16={fired_32x16} 16x32={fired_16x32}, {out_of_scope} attempts carried none \ - ({oos_mismatch} of them mismatched)" - ); - assert_eq!( - oos_mismatch, 0, - "{NAME}: {oos_mismatch} attempt(s) with no rectangular var-tx leaf decoded \ - but mismatched ffmpeg -- a defect of another shape, not a pass" - ); - assert!( - compared + out_of_scope > 0, - "{NAME} ({bit_depth}-bit): every attempt refused -- the gate compared no pixels" - ); - // The firing half. lane-vartxsplit r2 re-measured it against - // the oracle: attempts 16/17 (384x256 product texture, cq 44/46, - // `--min-partition-size=8 --enable-tx-size-search=1`) are the only - // recipes of a ~40-run sweep whose stream carries `TX_32X8` / - // `TX_8X32` split symbols, i.e. RECTANGULAR var-tx leaves (16x8 - // and 8x16, both orientations out of the same stream). They now - // decode PIXEL-EXACT on all six frames, so the assert is on the - // pixel-compared tally, not on the "decoded anywhere" one -- - // `fired_*` stays only to separate a refused stream's leaves from - // a proved one (class counter-from-refused-stream). At 10 bits - // the same sweep either fires nothing or mismatches on a - // reconstruction defect of another shape (report), so the firing - // assert stays 8-bit -- and it is a hard assert, never a print. - if bit_depth == 8 { - assert!( - leaf_32x16 > 0 && leaf_16x32 > 0, - "{NAME}: the rectangular var-tx leaf arm never fired on a pixel-exact \ - attempt (pixel-compared 32x16={leaf_32x16}, 16x32={leaf_16x32}, decoded \ - anywhere 32x16={fired_32x16} 16x32={fired_16x32}, {named_refusals} \ - refusals, {compared} compared) -- the rectangular sub-transform path is \ - unproved by this gate" - ); - } - } - } - - /// lane-rectres r1: a 32x32-level 1:4 INTER strip (32x8 / 8x32) that codes - /// a REAL rectangular residual. THIS is the shape both 10-bit 3840x1608 - /// film cuts and every measured 1080p offset stopped on -- six of six - /// `decode_probe` runs refused at "a non-skip rectangular (HORZ/VERT/ - /// HORZ_B) strip needs rectangular residual coding" with `w=32 h=8` or - /// `w=8 h=32`, nothing else. - /// - /// `max_txsize_rect_lookup[BLOCK_32X8] == TX_32X8` codes all 256 of its - /// positions ([`TxbSet::LumaRect32x8Inter`]: `get_txsize_entropy_ctx` = - /// TX_16X16 so the coefficient tables are the luma-16 ones, - /// `txsize_log2_minus4` = 4 so `eob_pt` is the 256-position alphabet), and - /// unlike the INTRA twin it DOES code a `tx_type`: - /// `av1_get_ext_tx_set_type` at `tx_size_sqr_up == TX_32X32` is - /// `EXT_TX_SET_DCT_IDTX` for inter with or without `reduced_tx_set`, read - /// at the `txsize_sqr_map[TX_32X8] == TX_8X8` CDF row (class - /// table-indexed-by-raw-size: the coefficient tables follow the ADJUSTED - /// size, the `tx_type` row the SQUARE one -- they disagree here). - /// Its chroma pair is one 16x4 / 4x16 unit (`ss_size_lookup[BLOCK_32X8]` - /// = BLOCK_16X4, `Chroma8`'s tables, 64-position `eob_pt`), and a split - /// transform gives 16x8 / 8x16 leaves (`sub_tx_size_map[TX_32X8] == - /// TX_16X8`) the rect var-tx path already reads. - /// - /// `--enable-1to4-partitions=1 --min-partition-size=8 - /// --max-partition-size=32 --enable-tx-size-search=1` (each spelled once, - /// last occurrence wins -- aomenc keeps the LAST `--enable-*`) is what - /// lets aomenc pick a 32x32-level HORZ_4 / VERT_4; the 8-pixel banded - /// translating source is what makes those strips the RD winner and keeps - /// them non-skip so the residual is really coded. Both orientations, 8-bit - /// AND 10-bit, every decode-order frame compared to ffmpeg on Y/U/V, - /// refusals counted (never SKIPped), attempts that carried no 32x8/8x32 - /// residual unit counted separately and still required pixel-exact. - #[test] - fn a_real_aomenc_inter_sequence_with_32x32_level_1to4_strips_codes_their_rect_residual() { - const NAME: &str = - "a_real_aomenc_inter_sequence_with_32x32_level_1to4_strips_codes_their_rect_residual"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let frame_count = 6usize; - let (mut proved_32x8, mut proved_8x32) = (0usize, 0usize); - let (mut fired_32x8, mut fired_8x32) = (0usize, 0usize); - for bit_depth in [8u32, 10u32] { - let (mut named_refusals, mut compared, mut out_of_scope, mut oos_mismatch) = - (0u32, 0u32, 0u32, 0u32); - for attempt in 0..16u32 { - // Two orientations (the transposed pair a one-sided gate could - // never separate) x four quantisers x two motion steps. - let vertical = attempt % 2 == 1; - let (width, height) = (192usize, 128usize); - let cq = [48, 52, 56, 60][(attempt / 2 % 4) as usize]; - let sp = 3 + (attempt / 8) * 4; - // 32-pixel bands, each translating at its OWN speed across the - // other axis: that is what makes aomenc's RD split a 32x32 - // block into four 32x8 (or 8x32) strips with distinct motion - // vectors, and the texture inside a band is what keeps a strip - // non-skip. MEASURED (72-run recipe sweep, 192x128..256x192, - // cq 24..60, bands 8/16/32/64): only 32-pixel bands at cq >= 48 - // make aomenc code a NON-SKIP one -- attempt 0 (cq 48, - // horizontal source) codes an 8x32 residual unit, attempt 7 - // (cq 60, the transposed source) five 32x8 ones. Narrower - // bands give the same strips with `skip` set, which proves the - // partition symbol and nothing about the residual. - let geq = if vertical { - format!("128+62*sin((Y+N*({sp}+7*mod(floor(X/32),4)))/6)+28*sin(X/9)") - } else { - format!("128+62*sin((X+N*({sp}+7*mod(floor(Y/32),4)))/6)+28*sin(Y/9)") - }; - let duration = frame_count as f64 / 25.0; - let source = format!( - "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\ - geq=lum='{geq}',format=yuv420p" - ); - let pix_fmt = if bit_depth == 10 { - "yuv420p10le" - } else { - "yuv420p" - }; - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-t", - &duration.to_string(), - "-pix_fmt", - pix_fmt, - "-strict", - "-1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let cq_arg = format!("--cq-level={cq}"); - let depth_arg = format!("--bit-depth={bit_depth}"); - let input_depth_arg = format!("--input-bit-depth={bit_depth}"); - let args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - &cq_arg, - "--cpu-used=0", - "--threads=1", - "--row-mt=0", - "--sb-size=64", - &depth_arg, - &input_depth_arg, - "--enable-restoration=0", - "--enable-palette=0", - "--deltaq-mode=0", - "--enable-filter-intra=0", - "--enable-cfl-intra=0", - "--enable-intrabc=0", - "--lag-in-frames=0", - // Per-arm overrides go LAST: aomenc keeps the last - // occurrence of a repeated --enable-* flag. - "--enable-tx64=0", - "--enable-rect-partitions=1", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=1", - "--enable-tx-size-search=1", - "--enable-dual-filter=0", - "--enable-obmc=0", - // aomenc's min-partition-size bounds the SMALLER side of a - // 1:4 strip, so 32x8 needs 8 (memory - // aomenc-min-partition-bounds-smaller-side). - "--min-partition-size=8", - "--max-partition-size=32", - "--obu", - "-o", - "-", - "-", - ]; - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let before = crate::stream::rect32x8_inter_tu_hits(); - let frames = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \ - attempt {attempt}): {msg}" - ); - let after = crate::stream::rect32x8_inter_tu_hits(); - // Firing counted on a refused stream is kept apart from - // the pixel-proved tally (class - // counter-from-refused-stream). - fired_32x8 += after[0] - before[0]; - fired_8x32 += after[1] - before[1]; - named_refusals += 1; - eprintln!( - "{NAME} {bit_depth}-bit attempt {attempt} refusal (32x8 residual \ - units decoded before it: {}, 8x32: {}): {msg}", - after[0] - before[0], - after[1] - before[1] - ); - continue; - } - Ok(frames) => frames, - }; - let after = crate::stream::rect32x8_inter_tu_hits(); - let (h, v) = (after[0] - before[0], after[1] - before[1]); - fired_32x8 += h; - fired_8x32 += v; - let ffmpeg_frames = if bit_depth == 10 { - ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count) - } else { - ffmpeg_decode_sequence(&stream, width, height, frame_count) - }; - assert_eq!(frames.len(), frame_count); - let mismatched = frames - .iter() - .zip(&ffmpeg_frames) - .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); - if h + v == 0 { - out_of_scope += 1; - if mismatched { - oos_mismatch += 1; - eprintln!( - "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \ - 32x8/8x32 inter residual units -- another shape's defect" - ); - } - continue; - } - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!( - got.y, want.y, - "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit)" - ); - assert_eq!( - got.u, want.u, - "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit)" - ); - assert_eq!( - got.v, want.v, - "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit)" - ); - } - proved_32x8 += h; - proved_8x32 += v; - compared += 1; - } - eprintln!( - "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {compared} \ - pixel-exact attempts carrying the arm, {out_of_scope} attempts carried none \ - ({oos_mismatch} of them mismatched)" - ); - assert_eq!( - oos_mismatch, 0, - "{NAME}: {oos_mismatch} attempt(s) with no 32x8/8x32 inter residual unit \ - decoded but mismatched ffmpeg -- a defect of another shape, not a pass" - ); - assert!( - compared + out_of_scope > 0, - "{NAME} ({bit_depth}-bit): every attempt refused -- the gate compared no pixels" - ); - } - eprintln!( - "{NAME}: pixel-compared 32x32-level 1:4 inter residual units 32x8={proved_32x8} \ - 8x32={proved_8x32} (decoded anywhere in the sweep 32x8={fired_32x8} \ - 8x32={fired_8x32})" - ); - // The firing half, one assert per lifted shape. Both orientations must - // be PIXEL-PROVED: a transposed table passes one and fails the other - // (class reference-layout-not-spec). - assert!( - proved_32x8 > 0, - "{NAME}: no 32x8 inter residual transform unit was decoded inside a pixel-exact \ - attempt (decoded anywhere: {fired_32x8}) -- the lift is unproved" - ); - assert!( - proved_8x32 > 0, - "{NAME}: no 8x32 inter residual transform unit was decoded inside a pixel-exact \ - attempt (decoded anywhere: {fired_8x32}) -- the lift is unproved" - ); - } - - /// lane-sbrect10 r1: a 64x64 INTRA block inside an INTER frame, whose - /// `uv_mode` alphabet libaom's `is_cfl_allowed` (`blockd.h`: `wide <= 32 - /// && high <= 32`) narrows to the 13-symbol NO-CFL table. Reading the - /// 14-symbol CFL one produced the same `DC_PRED` value with the wrong - /// interval narrowing, so the tile desynced from that block on and the - /// frame decoded silently wrong (class `wrong-alphabet-same-value`; found - /// as the "another shape" mismatch the superblock rect gate above had to - /// park its 10-bit arm on). - /// - /// The counter `nocfl_uv_mode_hits` proves the shape fired in EVERY - /// compared attempt, and every decode-order frame is compared against - /// ffmpeg -- an attempt that mismatches fails, it never SKIPs. - /// - /// lane-sbrect10 r2: with the half-random source below this gate also - /// covers a SECOND defect it exposed at 10-bit cq 58/61 -- the compound - /// MV stack's extension pass zero-filled the `comp_list` tail slots - /// libaom fills with each side's GLOBAL MOTION vector - /// (`combine_compound_candidates`, mvref_common.c:723-729). A compound - /// block with no usable neighbour pair (frame top row, intra block to - /// its left, empty temporal field) then took a `(0, 0)` predictor - /// instead of the frame's translation: 32890/39907 wrong luma samples - /// on decode-order frame 2 with the entropy stream still in sync. - #[test] - fn a_real_aomenc_inter_frame_with_a_64x64_intra_block_reads_the_no_cfl_uv_alphabet() { - const NAME: &str = - "a_real_aomenc_inter_frame_with_a_64x64_intra_block_reads_the_no_cfl_uv_alphabet"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height, frame_count) = (192usize, 128usize, 6usize); - for bit_depth in [8u32, 10u32] { - let (mut named_refusals, mut matched, mut carried_none) = (0u32, 0u32, 0u32); - let mut total_hits = 0usize; - for attempt in 0..16u32 { - // The sibling superblock-rect gate's own grid (its 10-bit - // attempt 14 -- cq 61, horizontal split, motion step 12 -- is - // the stream that exposed the defect); which superblock the RD - // hands an intra 64x64 block moves with the quantiser and the - // depth, so both orientations x four quantisers x two motion - // steps run here too. - let vertical_split = attempt % 2 == 1; - let cq = [58, 52, 45, 61][(attempt / 2 % 4) as usize]; - let sp = 8 + (attempt / 8) * 4; - // Half ramp, half deterministic pseudo-noise: the flat "200" - // half of r1's source made aomenc code the right-hand - // superblocks skip, so at 8 bit no >32 intra block ever - // appeared (probed cq 45/52/58/61/63 = 0 hits). The textured - // half forces intra above 32x32 in an inter frame at BOTH - // depths, so both arms carry the shape. - let geq = if vertical_split { - format!( - "if(lt(Y,64), 40+mod(floor((X+N*{sp})/32)*90,200), mod((X*7+Y*13+N*97)*31,256))" - ) - } else { - format!( - "if(lt(X,128), 40+mod(floor((Y+N*{sp})/32)*90,200), mod((X*7+Y*13+N*97)*31,256))" - ) - }; - let duration = frame_count as f64 / 25.0; - let source = format!( - "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\ - geq=lum='{geq}',format=yuv420p" - ); - let pix_fmt = if bit_depth == 10 { - "yuv420p10le" - } else { - "yuv420p" - }; - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-t", - &duration.to_string(), - "-pix_fmt", - pix_fmt, - "-strict", - "-1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let cq_arg = format!("--cq-level={cq}"); - let depth_arg = format!("--bit-depth={bit_depth}"); - let input_depth_arg = format!("--input-bit-depth={bit_depth}"); - let args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - &cq_arg, - "--cpu-used=0", - "--threads=1", - "--row-mt=0", - "--sb-size=64", - &depth_arg, - &input_depth_arg, - "--enable-restoration=0", - "--enable-palette=0", - "--deltaq-mode=0", - "--enable-filter-intra=0", - "--enable-cfl-intra=0", - "--enable-intrabc=0", - "--enable-tx-size-search=0", - "--lag-in-frames=0", - "--enable-rect-partitions=1", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=1", - "--min-partition-size=32", - "--max-partition-size=64", - "--obu", - "-o", - "-", - "-", - ]; - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let before = crate::decode::nocfl_uv_mode_hits(); - let frames = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \ - attempt {attempt}): {msg}" - ); - named_refusals += 1; - eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}"); - continue; - } - Ok(frames) => frames, - }; - let hits = crate::decode::nocfl_uv_mode_hits() - before; - let ffmpeg_frames = if bit_depth == 10 { - ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count) - } else { - ffmpeg_decode_sequence(&stream, width, height, frame_count) - }; - assert_eq!(frames.len(), frame_count); - if hits == 0 { - // No 64-axis intra block in this stream: still compared - // (a mismatch here is a defect, never a pass), just not - // proof of this gate's shape. - carried_none += 1; - } - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!( - got.y, want.y, - "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit, hits={hits})" - ); - assert_eq!( - got.u, want.u, - "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit, hits={hits})" - ); - assert_eq!( - got.v, want.v, - "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit, hits={hits})" - ); - } - if hits > 0 { - matched += 1; - total_hits += hits; - } - } - eprintln!( - "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \ - attempts carrying a >32 intra block ({total_hits} no-CFL uv_mode reads), \ - {carried_none} attempts carried none" - ); - assert!( - matched > 0 && total_hits > 0, - "{NAME} ({bit_depth}-bit): no attempt decoded an intra block above 32x32, so the \ - no-CFL uv_mode alphabet was never exercised -- gate proved nothing \ - ({named_refusals} refusals, {carried_none} attempts carried none)" - ); - } - } diff --git a/crates/ec-av1/src/stream/tests/t05.rs b/crates/ec-av1/src/stream/tests/t05.rs deleted file mode 100644 index 6dbd32f1..00000000 --- a/crates/ec-av1/src/stream/tests/t05.rs +++ /dev/null @@ -1,4488 +0,0 @@ -use super::*; -use super::support::*; -use super::gates_a::*; -use crate::probe::run_with_stdin; -use std::process::{Command, Stdio}; - - /// lane-sqdrift r2: the SQUARE-ONLY twin of the no-CFL `uv_mode` gate - /// above. With `--enable-rect-partitions=0` the encoder codes only - /// `PARTITION_NONE` and `PARTITION_SPLIT`, and on detailed content the RD - /// eventually hands one whole 64x64 superblock of an INTER frame to an - /// INTRA block -- `bsize == sb_size`, the one shape whose `uv_mode` must - /// come off the 13-symbol `uv_mode_no_cfl` alphabet because libaom's - /// `is_cfl_allowed` (`blockd.h`: `wide <= 32 && high <= 32`) excludes it. - /// - /// Before the fix this decoder read the 14-symbol CFL alphabet there: the - /// same `DC_PRED` value, a different interval, and the tile desynced from - /// that block on. r1 measured the damage on the pinned 192x128 stream - /// (sha256 `c6af4fb4...`): decode-order frames 0-3 pre-filter byte-exact, - /// frame 4 luma 3540 samples wrong over exactly the last superblock - /// (x 128..191, y 64..127), then 24k wrong by frame 7 -- and the decoder - /// did not even report a mismatch, it reported an intra-rect-strip refusal - /// read out of the already-desynced stream (class `refusal-from-own-desync`; - /// aomdec's own partition histogram over that stream is rect-free). - /// After the fix the same stream is byte-exact on all 8 frames. - /// - /// Distinct from the sibling gate: rect partitions OFF (so the 64x64 NONE - /// really is a whole superblock), `--min-partition-size=16`, natural - /// mandelbrot detail instead of a synthetic half-noise ramp, and 8 frames - /// of drift so a desync that survives one frame still fails here. Every - /// decode-order frame of every attempt is compared against ffmpeg, so a - /// mismatch of ANY shape fails; the gate never turns one into a SKIP. - #[test] - fn a_real_aomenc_square_only_inter_sequence_with_a_64x64_intra_superblock_decodes_pixel_exact() - { - const NAME: &str = "a_real_aomenc_square_only_inter_sequence_with_a_64x64_intra_superblock_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height, frame_count) = (192usize, 128usize, 8usize); - for bit_depth in [8u32, 10u32] { - let (mut named_refusals, mut matched, mut carried_none) = (0u32, 0u32, 0u32); - let mut total_hits = 0usize; - for attempt in 0..4u32 { - // r1's pinned recipe is (start_scale 4.76, cq 55); the other - // three points move the detail level and the quantiser, which - // is what moves WHICH superblock the RD codes intra. - let start_scale = ["4.76", "3.20"][(attempt % 2) as usize]; - let cq = [55, 45][(attempt / 2) as usize]; - let duration = frame_count as f64 / 25.0; - let source = format!( - "mandelbrot=size={width}x{height}:start_scale={start_scale}:\ - end_scale=0.004:end_pts=8:rate=25" - ); - let pix_fmt = if bit_depth == 10 { - "yuv420p10le" - } else { - "yuv420p" - }; - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-vf", - "hue=s=0", - "-t", - &duration.to_string(), - "-pix_fmt", - pix_fmt, - "-strict", - "-1", - "-f", - "yuv4mpegpipe", - "-strict", - "-1", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let cq_arg = format!("--cq-level={cq}"); - let depth_arg = format!("--bit-depth={bit_depth}"); - let input_depth_arg = format!("--input-bit-depth={bit_depth}"); - let args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - &cq_arg, - "--cpu-used=1", - "--threads=1", - "--row-mt=0", - "--sb-size=64", - &depth_arg, - &input_depth_arg, - "--lag-in-frames=0", - "--auto-alt-ref=0", - "--kf-min-dist=1000", - "--kf-max-dist=1000", - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--min-partition-size=16", - "--max-partition-size=64", - "--enable-tx-size-search=0", - "--enable-order-hint=0", - "--enable-warped-motion=0", - "--enable-obmc=0", - "--enable-masked-comp=0", - "--enable-interintra-comp=0", - "--enable-dist-wtd-comp=0", - "--enable-diff-wtd-comp=0", - "--enable-onesided-comp=0", - "--enable-interintra-wedge=0", - "--enable-smooth-interintra=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-cdef=0", - "--enable-restoration=0", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - "--enable-ref-frame-mvs=0", - "--obu", - "-o", - "-", - "-", - ]; - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let before = crate::decode::nocfl_uv_mode_hits(); - let frames = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \ - attempt {attempt}): {msg}" - ); - named_refusals += 1; - eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}"); - continue; - } - Ok(frames) => frames, - }; - let hits = crate::decode::nocfl_uv_mode_hits() - before; - let ffmpeg_frames = if bit_depth == 10 { - ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count) - } else { - ffmpeg_decode_sequence(&stream, width, height, frame_count) - }; - assert_eq!(frames.len(), frame_count); - if hits == 0 { - carried_none += 1; - } - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!( - got.y, want.y, - "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit, hits={hits})" - ); - assert_eq!( - got.u, want.u, - "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit, hits={hits})" - ); - assert_eq!( - got.v, want.v, - "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit, hits={hits})" - ); - } - if hits > 0 { - matched += 1; - total_hits += hits; - } - } - eprintln!( - "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \ - attempts carrying a 64x64 intra superblock ({total_hits} no-CFL uv_mode reads), \ - {carried_none} attempts carried none" - ); - assert!( - matched > 0 && total_hits > 0, - "{NAME} ({bit_depth}-bit): no square-only attempt decoded a 64x64 intra block \ - inside an inter frame, so the no-CFL uv_mode alphabet was never exercised -- \ - gate proved nothing ({named_refusals} refusals, {carried_none} carried none)" - ); - } - } - - /// lane-mc64 r2: the RECT-ON twin of the square-only gate above, pinned - /// as a stream fixture because its aomenc recipe is not reproducible - /// (the r2 recipe re-encoded to a different file, measured md5 - /// `278be00...` vs the fixture's `add55f6...`; class - /// `seeded-fixture-not-reproducible`). - /// - /// `crates/ec-av1/fixtures/av1_192x128_8bit_intra64_in_inter.obu` - /// (sha256 `e4cff46cb1700527c68efc866db27a2835705e949d646f73f0c9df577d594bd6`) - /// carries a 64x64 `PARTITION_NONE` INTRA block inside an INTER frame at - /// decode-order frame 2, mi(16,32), in a stream whose OTHER superblocks - /// are rect-partitioned -- so the 64-axis `is_cfl_allowed` narrowing - /// (`blockd.h`: `wide <= 32 && high <= 32`) has to hold on the intra - /// arm that the rect recipe reaches, not only on the whole-superblock - /// one. Before lane-sbrect10's fix this frame reconstructed with 3720 - /// wrong luma samples (delta -12..+9, chroma bit-exact) and the decode - /// then died at frame 3 on a phantom refusal of its own desync (class - /// `refusal-from-own-desync`); all 6 decode-order frames are byte-exact - /// against the oracle now. - #[test] - fn a_pinned_rect_stream_with_a_64x64_intra_block_in_an_inter_frame_decodes_pixel_exact() { - const NAME: &str = - "a_pinned_rect_stream_with_a_64x64_intra_block_in_an_inter_frame_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_aomenc() { - eprintln!( - "SKIP {NAME}: no aomenc/aomdec oracle at {}", - aomenc_path().display() - ); - return; - } - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("fixtures/av1_192x128_8bit_intra64_in_inter.obu"); - let stream = std::fs::read(&path) - .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display())); - let before = crate::decode::nocfl_uv_mode_hits(); - let (frames, hidden) = decode_all_frames_vs_oracle(&stream, NAME); - let hits = crate::decode::nocfl_uv_mode_hits() - before; - assert_eq!( - frames, 6, - "{NAME}: expected 6 decode-order frames ({hidden} hidden)" - ); - assert!( - hits > 0, - "{NAME}: no 64-axis intra block read the no-CFL uv_mode alphabet -- the fixture no \ - longer carries the shape this test gates" - ); - } - - /// lane-av1444chr: a 4:4:4 INTER chroma unit inherits the `tx_type` of - /// the luma leaf covering its OWN quadrant, not the block-level (top-left - /// leaf) one. `av1_get_tx_type` (`blockd.h:1287-1297`) reads - /// `xd->tx_type_map` at the chroma unit's own position scaled back to - /// luma, and `read_coeffs`' `all_zero` arm stamps `DCT_DCT` into that - /// leaf's cell (`decodetxb.c:199-203`) -- so a chroma unit sitting over a - /// luma leaf that coded NOTHING must reconstruct as DCT_DCT even when the - /// block's top-left leaf is `IDTX`. - /// - /// The fixture is the report's witness pinned into `fixtures/`: - /// `testsrc2 128x128` yuv444p 4 frames, aomenc `--profile=1 --cq-level=20 - /// --cpu-used=2 --sb-size=64 --min-partition-size=64 - /// --max-partition-size=64 --passes=1 --end-usage=q --threads=1 --row-mt=0 - /// --lag-in-frames=0 --kf-max-dist=100 --limit=4 --obu`; 27933 bytes, - /// sha256 `a06c9f7a0862252f6ab7ebdcec340d0602e730e38089365f14747db37f8e78d5`. - /// Every inter block is a whole 64x64 (min=max partition 64) whose luma - /// var-tx tree is four TX_32X32 leaves, so each block's chroma plane is - /// four TX_32X32 units -- one per leaf. - /// - /// Pre-fix, decode-order frames 1/2/3 differ from the oracle in 777/640/554 - /// V samples (luma and U exact) and the per-unit type census disagrees at - /// exactly the units over the skipped leaf: V(0,32) of block mi(0,0) in - /// frame 1, V(64,96) of block mi(16,16) in every inter frame. Post-fix all - /// 136 non-empty inter units agree with the oracle's `EC_DQCOEFF` type and - /// every frame is byte-exact. - /// - /// The non-vacuity bar is the DIFFERS counter, not the route counter: a - /// route counter fires on every four-unit chroma read (96 of them here) - /// and stayed green through a no-op fix that changed zero pixels, because - /// on a block whose four leaves agree the per-quadrant resolve and the - /// block-level value are the same answer. The number that says the resolve - /// CHANGED something is 8 on this stream -- the four skipped-leaf quadrants - /// (two of them in decode-order frame 1), each resolved once per chroma - /// plane -- and it must be 0 on the 4:2:0 control below, since the arm is - /// unreachable at 4:2:0. - #[test] - fn a_pinned_444_inter_stream_chroma_units_inherit_their_own_quadrants_tx_type() { - const NAME: &str = - "a_pinned_444_inter_stream_chroma_units_inherit_their_own_quadrants_tx_type"; - const FIXTURE_LEN: usize = 27933; - const FIXTURE_FNV: u64 = 0x85fa_830b_8800_90df; - let _gate_lock = lock_gate_counters(); - if !have_aomenc() { - eprintln!( - "SKIP {NAME}: no aomenc/aomdec oracle at {}", - aomenc_path().display() - ); - return; - } - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("fixtures/444_quad_leaf_tx_type.obu"); - let stream = std::fs::read(&path) - .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display())); - assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: fixture length moved"); - assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: fixture bytes moved"); - - let quad0 = crate::decode::chroma_quad_leaf_tx_hits(); - let diff0 = crate::decode::chroma_quad_leaf_tx_diff_hits(); - let (frames, hidden) = decode_all_frames_vs_oracle(&stream, NAME); - let quad = crate::decode::chroma_quad_leaf_tx_hits() - quad0; - let diff = crate::decode::chroma_quad_leaf_tx_diff_hits() - diff0; - assert_eq!( - frames, 4, - "{NAME}: expected 4 decode-order frames ({hidden} hidden)" - ); - assert!( - quad >= 2 * diff && quad > 0, - "{NAME}: no chroma unit took its type from the covering luma leaf \ - (quad {quad}, differs {diff}) -- the corrected route never ran" - ); - assert!( - diff >= 2, - "{NAME}: the per-quadrant resolve never CHANGED an answer (diff {diff}; measured 4 \ - on this stream, 2 of them in decode-order frame 1). A route counter alone is not a \ - witness: it fires on every four-unit chroma read, including the \ - blocks whose four leaves all agree -- the exact shape a no-op fix looked green on." - ); - eprintln!("{NAME}: quad-resolved chroma units {quad}, of which {diff} differed"); - - // 4:2:0 control: the same decode, same counters, zero differences -- - // the four-unit arm is the 4:4:4 (`ss 0/0`) route only. - let control = std::fs::read( - std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("fixtures/av1_192x128_8bit_intra64_in_inter.obu"), - ) - .unwrap_or_else(|e| panic!("{NAME}: reading the 4:2:0 control: {e}")); - let c_quad0 = crate::decode::chroma_quad_leaf_tx_hits(); - let c_diff0 = crate::decode::chroma_quad_leaf_tx_diff_hits(); - let c_frames = decode_stream(&control) - .unwrap_or_else(|e| panic!("{NAME}: the 4:2:0 control no longer decodes: {e}")) - .len(); - let c_quad = crate::decode::chroma_quad_leaf_tx_hits() - c_quad0; - let c_diff = crate::decode::chroma_quad_leaf_tx_diff_hits() - c_diff0; - assert!(c_frames > 0, "{NAME}: the 4:2:0 control decoded no frames"); - assert_eq!( - (c_quad, c_diff), - (0, 0), - "{NAME}: the 4:2:0 control fired the 4:4:4 four-unit route ({c_quad} units, {c_diff} \ - differing) -- the counter is not specific to the route it claims to witness" - ); - } - - /// lane-av1f9singleland: `decode_inter_block` has TWO textually parallel - /// copies of the 4:4:4 four-unit chroma arm -- the compound prediction - /// arm (the `build` closure) and the single-reference arm. Both resolve - /// each unit's `tx_type` through `covering_leaf_tx_type` over a - /// `leaf_tx_types` list collected at EVERY size, both bumped the same - /// `CHROMA_QUAD_LEAF_TX_HITS` / `..._DIFF_HITS` pair, and the gate above - /// asserts only that pair. So that gate cannot say which arm its witness - /// came from, and the two arms can be reverted independently. - /// - /// Measured on the gate's own witness `fixtures/444_quad_leaf_tx_type.obu` - /// (the census is the point of this test, so it is quoted rather than - /// assumed): 96 chroma units resolve through their covering luma leaf, of - /// which 88 are the single-reference arm's and 8 the compound arm's; of - /// the 8 units whose resolved type DIFFERS from the block-level one -- - /// the non-vacuity bar, since a block whose four leaves agree makes the - /// per-quadrant resolve a no-op -- ALL 8 are the single-reference arm's. - /// The shared counters' non-vacuity number is therefore 100% - /// single-reference, and the compound arm contributes 8 of 96 route hits - /// and none of the 8 that change an answer. - /// - /// The other 27 pinned 4:4:4 fixtures in this tree reach the arm zero - /// times (`444_intrabc_rect4_witness`, `444_leaf8_oob`, - /// `444_lossy_rect4_*`, `444_lossy_superres_*`, `444_sb128rect_lr_witness`, - /// and every `ll444_*`), so this one witness is the only thing pinning - /// the single-reference copy of the arm at all. - /// - /// Non-vacuity, per the mutation recorded in - /// `lanes/av1f9singleland.report.md`: reverting ONLY this arm's - /// `Some(cu_tx_type)` to `Some(luma_tx_type)` turns this gate red on - /// decode-order frame 1 with 777 bytes differing; gating ONLY this arm's - /// leaf push back behind `if side > 64` (the pre-`6c33f204` state) turns - /// it red with the same 777 bytes. - #[test] - fn the_pinned_444_quadrant_witness_is_the_single_reference_arms_and_not_only_the_compound_arms() - { - const NAME: &str = "the_pinned_444_quadrant_witness_is_the_single_reference_arms_and_not_only_the_compound_arms"; - const FIXTURE_LEN: usize = 27933; - const FIXTURE_FNV: u64 = 0x85fa_830b_8800_90df; - let _gate_lock = lock_gate_counters(); - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("fixtures/444_quad_leaf_tx_type.obu"); - let stream = std::fs::read(&path) - .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display())); - assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: fixture length moved"); - assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: fixture bytes moved"); - - let q0 = crate::decode::chroma_quad_leaf_tx_hits(); - let s0 = crate::decode::chroma_quad_leaf_tx_singleref_hits(); - let sd0 = crate::decode::chroma_quad_leaf_tx_singleref_diff_hits(); - let frames = decode_stream(&stream) - .unwrap_or_else(|e| panic!("{NAME}: the witness no longer decodes: {e}")) - .len(); - assert_eq!(frames, 4, "{NAME}: expected 4 shown frames"); - let quad = crate::decode::chroma_quad_leaf_tx_hits() - q0; - let singleref = crate::decode::chroma_quad_leaf_tx_singleref_hits() - s0; - let sr_diff = crate::decode::chroma_quad_leaf_tx_singleref_diff_hits() - sd0; - - assert!( - singleref > quad / 2, - "{NAME}: the single-reference arm resolved {singleref} of {quad} covering-leaf chroma \ - units -- the shared counter is no longer dominated by the arm this gate witnesses, so \ - a revert of the single-reference copy would leave the shared total comfortably non-zero" - ); - assert!( - sr_diff >= 2, - "{NAME}: the single-reference arm's per-quadrant resolve never CHANGED an answer \ - (differing {sr_diff}). A route count alone is not a witness: it fires on every \ - four-unit chroma read, including the blocks whose four luma leaves all agree -- the \ - exact shape a no-op resolve looks green on." - ); - eprintln!( - "{NAME}: {singleref} of {quad} covering-leaf units are the single-reference arm's, \ - {sr_diff} of which changed an answer" - ); - - // 4:2:0 control, as in the gate above: the four-unit arm is the 4:4:4 - // (`ss 0/0`) route only, so the single-reference arm's own counters - // must stay at exactly 0 there too. - let control = std::fs::read( - std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("fixtures/av1_192x128_8bit_intra64_in_inter.obu"), - ) - .unwrap_or_else(|e| panic!("{NAME}: reading the 4:2:0 control: {e}")); - let c_s0 = crate::decode::chroma_quad_leaf_tx_singleref_hits(); - let c_sd0 = crate::decode::chroma_quad_leaf_tx_singleref_diff_hits(); - let c_frames = decode_stream(&control) - .unwrap_or_else(|e| panic!("{NAME}: the 4:2:0 control no longer decodes: {e}")) - .len(); - assert!(c_frames > 0, "{NAME}: the 4:2:0 control decoded no frames"); - assert_eq!( - ( - crate::decode::chroma_quad_leaf_tx_singleref_hits() - c_s0, - crate::decode::chroma_quad_leaf_tx_singleref_diff_hits() - c_sd0, - ), - (0, 0), - "{NAME}: the 4:2:0 control fired the single-reference arm's four-unit route -- the \ - counter is not specific to the route it claims to witness" - ); - } - - /// lane-av1chrtx: the SIBLING of lane-av1444chr's four-unit arm -- a RECT - /// inter block's chroma plane, read by `read_inter_rect_chroma`. That - /// helper was left handing every unit the block-level `luma_tx_type` - /// (the top-left leaf's type) after the four-unit arms were pointed at - /// `covering_leaf_tx_type`, so a rect block whose chroma plane splits - /// (`nx*ny > 1`) over MIXED var-tx leaves read the wrong type per unit. - /// - /// The witness is pinned into `fixtures/`: `testsrc2 256x256` yuv444p 3 - /// frames, aomenc `--profile=1 --cq-level=30 --cpu-used=0 --sb-size=64 - /// --min-partition-size=32 --max-partition-size=64 --enable-tx-size-search=1 - /// --passes=1 --end-usage=q --threads=1 --row-mt=0 --lag-in-frames=0 - /// --kf-max-dist=100 --limit=3 --obu`; 26839 bytes, sha256 - /// `06174a66e92aaeb751a8e86db59711fcb1f18d74bde2d77e1ef1be7983eb7c80`. - /// Its one qualifying block is the 32x64 inter strip at mi(32,48): a - /// 4:4:4 chroma plane of (32,64) = TWO TX_32X32 units, over a luma tree - /// of five leaves -- `Idtx` (32x32) on top, then `VDct`/`DctDct`/`HDct`/ - /// `VDct` 16x16 leaves. The lower chroma unit therefore inherits `VDct` - /// where the block-level value is `Idtx`. - /// - /// Getting a witness at all took a bounded hunt (200+ encodes): `multi` - /// is false by construction at 4:2:0 (a `side <= 64` block's chroma plane - /// is at most 32x32 = one unit), so the arm needs 4:4:4 AND a rect block - /// that keeps a 64-px axis, AND `--cpu-used=0` with `--min-partition-size=32` - /// to make aomenc actually pick the 32x64 strip. - /// - /// The non-vacuity bar is the DIFFERS counter, not the route counter: the - /// control below is a committed 4:4:4 rect stream where the route fires - /// and still changes nothing, because that block's leaves agree. - #[test] - fn a_pinned_444_rect_inter_stream_resolves_each_chroma_unit_from_its_own_luma_leaf() { - const NAME: &str = - "a_pinned_444_rect_inter_stream_resolves_each_chroma_unit_from_its_own_luma_leaf"; - const FIXTURE_LEN: usize = 26839; - const FIXTURE_FNV: u64 = 0xc77f_310c_036d_ff73; - let _gate_lock = lock_gate_counters(); - if !have_aomenc() { - eprintln!( - "SKIP {NAME}: no aomenc/aomdec oracle at {}", - aomenc_path().display() - ); - return; - } - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("fixtures/444_rect_strip_leaf_tx_type.obu"); - let stream = std::fs::read(&path) - .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display())); - assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: fixture length moved"); - assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: fixture bytes moved"); - - let hits0 = crate::decode::chroma_rect_leaf_tx_hits(); - let diff0 = crate::decode::chroma_rect_leaf_tx_diff_hits(); - let (frames, hidden) = decode_all_frames_vs_oracle(&stream, NAME); - let hits = crate::decode::chroma_rect_leaf_tx_hits() - hits0; - let diff = crate::decode::chroma_rect_leaf_tx_diff_hits() - diff0; - assert_eq!( - frames, 3, - "{NAME}: expected 3 decode-order frames ({hidden} hidden)" - ); - assert!( - hits >= 2 * diff && hits > 0, - "{NAME}: no rect chroma unit took its type from the covering luma leaf (hits {hits}, \ - differs {diff}) -- the corrected route never ran" - ); - assert!( - diff >= 2, - "{NAME}: the per-unit resolve never CHANGED an answer (diff {diff}; measured 2 on this \ - stream, one per chroma plane). A route counter alone is not a witness: the control \ - below fires it and changes nothing." - ); - eprintln!( - "{NAME}: rect chroma units resolved from their own leaf {hits}, of which {diff} differed" - ); - - // Control: a committed 4:4:4 rect stream where the SAME route fires - // and every resolved type equals the block-level one -- the shape a - // no-op fix would also be green on. - let control = std::fs::read( - std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("fixtures/444_sb128rect_lr_witness.obu"), - ) - .unwrap_or_else(|e| panic!("{NAME}: reading the rect-strip control: {e}")); - let c_hits0 = crate::decode::chroma_rect_leaf_tx_hits(); - let c_diff0 = crate::decode::chroma_rect_leaf_tx_diff_hits(); - let c_frames = decode_stream(&control) - .unwrap_or_else(|e| panic!("{NAME}: the rect-strip control no longer decodes: {e}")) - .len(); - let c_hits = crate::decode::chroma_rect_leaf_tx_hits() - c_hits0; - let c_diff = crate::decode::chroma_rect_leaf_tx_diff_hits() - c_diff0; - assert!( - c_frames > 0, - "{NAME}: the rect-strip control decoded no frames" - ); - assert!( - c_hits > 0 && c_diff == 0, - "{NAME}: the rect-strip control fired the route {c_hits} times with {c_diff} differing \ - types -- expected the single-unit/same-type shape (route fires, nothing changes)" - ); - } - - /// lane-av1ichromatx: the LAST site in `decode_inter_block` that can hand a - /// chroma unit the BLOCK-level `luma_tx_type` instead of the unit's own - /// `tx_type_map` cell is [`read_inter_rect_chroma`]'s fallback: the branch - /// taken when `covering_leaf_tx_type` finds no luma leaf covering the - /// unit's own MI cell. The decode closes it with an assertion (a - /// multi-unit chroma plane may only reach the fallback when the block - /// coded a SINGLE luma transform, whose stamp covers the whole plane and - /// makes `luma_tx_type` that unit's own cell). - /// - /// This gate is the measurement behind that assertion, on the witness that - /// reaches it: `fixtures/444_rect_strip_leaf_tx_type.obu` (26839 bytes, - /// sha256 `06174a66e92aaeb751a8e86db59711fcb1f18d74bde2d77e1ef1be7983eb7c80`). - /// Measured there: the rect arm is called twice, BOTH on a multi-unit - /// chroma plane (`nx*ny > 1`), and 4 of its 8 units take the block-level - /// fallback -- every one of them with an EMPTY leaf list, i.e. the - /// single-luma-unit shape the assertion allows. So `multi_fallback >= 2` - /// here is the number that says the guarded shape is REACHED (a fallback - /// count of 0 would leave the assertion vacuous), and the decoded frames - /// stay byte-exact against instrumented aomdec, which is what says the - /// fallback still hands the right value on that shape. - /// - /// Non-vacuity, by mutation: forcing the covering-leaf resolve to miss on a - /// multi-unit plane (`…unit_rel_mi).filter(|_| !multi)`) turns the - /// assertion RED on this same witness -- - /// `a multi-unit rect chroma plane fell back to the block-level tx_type - /// while 5 luma leaves were coded` -- so the closure is not a comment. - #[test] - fn a_multi_unit_rect_chroma_plane_only_falls_back_to_the_block_type_on_a_single_luma_unit() { - const NAME: &str = "a_multi_unit_rect_chroma_plane_only_falls_back_to_the_block_type_on_a_single_luma_unit"; - const FIXTURE_LEN: usize = 26839; - const FIXTURE_FNV: u64 = 0xc77f_310c_036d_ff73; - let _gate_lock = lock_gate_counters(); - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("fixtures/444_rect_strip_leaf_tx_type.obu"); - let stream = std::fs::read(&path) - .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display())); - assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: fixture length moved"); - assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: fixture bytes moved"); - - let fb0 = crate::decode::chroma_rect_block_tx_fallback(); - let fbm0 = crate::decode::chroma_rect_block_tx_fallback_multi(); - let frames = decode_stream(&stream) - .unwrap_or_else(|e| panic!("{NAME}: the witness no longer decodes: {e}")) - .len(); - let fb = crate::decode::chroma_rect_block_tx_fallback() - fb0; - let fbm = crate::decode::chroma_rect_block_tx_fallback_multi() - fbm0; - assert_eq!(frames, 3, "{NAME}: expected 3 shown frames"); - assert!( - fbm >= 2, - "{NAME}: only {fbm} block-level fallbacks landed on a MULTI-unit chroma plane \ - ({fb} in total) -- the shape the decode's assertion guards is no longer reached, so \ - that assertion is vacuous on this witness" - ); - eprintln!("{NAME}: {fb} block-level chroma fallbacks, {fbm} of them on a multi-unit plane"); - } - - /// lane-av1readcensus: the 4:4:4 coefficient-UNIT census, pinned. - /// - /// The lane report `av1444rect` round 4 left an unexplained signal: 636 - /// square chroma reads against the oracle's 1086, and 2052 luma reads - /// against its 1309, recorded as "most likely a counting-shape difference" - /// with no evidence either way. This gate is that evidence. - /// - /// Measured on this arm (`ll444_minp8_inter`, pixel-exact against aomdec - /// on every plane of every frame -- see - /// `a_lossless_444_min_partition8_inter_stream_decodes_sample_exact`), - /// pairing each of our 11292 walked units with the oracle's - /// `av1_read_coeffs_txb` call BY `post_rng` (the msac state after the - /// unit) rather than by plane label or walk position: EVERY unit pairs, - /// and no unit's plane, shape, eob or all-zero flag differs. The per-plane - /// split is equal too -- 3764 units per plane on both sides, of which - /// 975 / 1793 / 1859 coded coefficients. So on a pixel-exact arm there is - /// no asymmetry to explain at all; the round-4 numbers came from - /// `444_intrabc_rect4_witness`, an arm that DIVERGES (390380 of 921600 - /// samples wrong), where our surplus is the divergence itself. - /// - /// What this gate pins is the walk's OBJECT SHAPE on the pixel-exact arm: - /// a change to the number or plane split of coefficient units this decoder - /// walks shows up here as an intentional diff, not as the next lane's - /// mystery signal. The 4:2:0 control asserts the census is inert there. - #[test] - fn a_pixel_exact_444_stream_walks_the_same_coefficient_units_the_oracle_does() { - const NAME: &str = - "a_pixel_exact_444_stream_walks_the_same_coefficient_units_the_oracle_does"; - const FIXTURE_LEN: usize = 34037; - const FIXTURE_FNV: u64 = 0x2c8f_4a2c_c025_52da; - let _gate_lock = lock_gate_counters(); - if !have_aomenc() { - eprintln!( - "SKIP {NAME}: no aomenc/aomdec oracle at {}", - aomenc_path().display() - ); - return; - } - let path = - std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures/ll444_minp8_inter.obu"); - let stream = std::fs::read(&path) - .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display())); - assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: fixture length moved"); - assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: fixture bytes moved"); - let delta = |now: [usize; 3], before: [usize; 3]| { - [now[0] - before[0], now[1] - before[1], now[2] - before[2]] - }; - - let u0 = crate::decode::census_nonsub_units(); - let c0 = crate::decode::census_nonsub_coded(); - let (frames, hidden) = decode_all_frames_vs_oracle(&stream, NAME); - assert_eq!( - frames + hidden, - 8, - "{NAME}: expected 8 decode-order frames (6 shown + 2 hidden)" - ); - let walked = delta(crate::decode::census_nonsub_units(), u0); - let coded = delta(crate::decode::census_nonsub_coded(), c0); - - // The oracle's own census on the same stream, paired by post_rng: - // 3764 units per plane, 975 / 1793 / 1859 of them coded. - assert_eq!( - walked, - [3764, 3764, 3764], - "{NAME}: the 4:4:4 unit walk changed -- {walked:?} against the oracle's \ - [3764, 3764, 3764] (measured by post_rng pairing, every unit matching). A change \ - here is a WALK-SHAPE change: re-measure against aomdec before assuming it is a bug" - ); - assert_eq!( - coded, - [975, 1793, 1859], - "{NAME}: the coded-unit split changed -- {coded:?} against the oracle's [975, 1793, 1859]" - ); - assert!( - walked.iter().all(|&v| v > 0) && coded.iter().all(|&v| v > 0), - "{NAME}: an all-zero plane split means the census did not run, not that the walk is empty" - ); - - // A SECOND pixel-exact arm, with a MIXED unit-shape mix -- the pinned - // lossless stream above is all TX_4X4 (min-partition-8), so on its own - // it would not notice a var-tx walk that started folding 8x8/4x8 - // leaves. This one walks 4x4/8x8/8x4/4x8/4x16/16x4/8x16/16x16, and - // the oracle's census on it pairs unit-for-unit by post_rng with no - // shape, plane, eob or all-zero difference: 1373 units, 629 luma and - // 372 per chroma plane, of which 130 / 253 / 278 coded. - let path2 = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("fixtures/444_lossy_rect4_inter_witness.obu"); - let stream2 = std::fs::read(&path2) - .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path2.display())); - let m0 = crate::decode::census_nonsub_units(); - let mc0 = crate::decode::census_nonsub_coded(); - let (frames2, hidden2) = decode_all_frames_vs_oracle(&stream2, NAME); - assert!( - frames2 + hidden2 > 0, - "{NAME}: the mixed-shape 4:4:4 arm decoded no frames" - ); - let walked2 = delta(crate::decode::census_nonsub_units(), m0); - let coded2 = delta(crate::decode::census_nonsub_coded(), mc0); - assert_eq!( - walked2, - [629, 372, 372], - "{NAME}: the mixed-shape 4:4:4 walk changed -- {walked2:?} against the oracle's \ - [629, 372, 372]. The all-4x4 arm above cannot see a var-tx fold; this one can" - ); - assert_eq!( - coded2, - [130, 253, 278], - "{NAME}: the mixed-shape coded-unit split changed -- {coded2:?} against the oracle's \ - [130, 253, 278]" - ); - - // 4:2:0 control: the census is a 4:4:4 question and must not fire. - let control = std::fs::read( - std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("fixtures/av1_192x128_8bit_intra64_in_inter.obu"), - ) - .unwrap_or_else(|e| panic!("{NAME}: reading the 4:2:0 control: {e}")); - let k0 = crate::decode::census_nonsub_units(); - let kc0 = crate::decode::census_nonsub_coded(); - let k_frames = decode_stream(&control) - .unwrap_or_else(|e| panic!("{NAME}: the 4:2:0 control no longer decodes: {e}")) - .len(); - assert!(k_frames > 0, "{NAME}: the 4:2:0 control decoded no frames"); - assert_eq!( - delta(crate::decode::census_nonsub_units(), k0), - [0, 0, 0], - "{NAME}: the coefficient-unit census fired on the 4:2:0 control" - ); - assert_eq!( - delta(crate::decode::census_nonsub_coded(), kc0), - [0, 0, 0], - "{NAME}: the coded-unit census fired on the 4:2:0 control" - ); - } - - /// lane-inter4 r2: the 32x32-level inter `PARTITION_HORZ`/`PARTITION_VERT` - /// strips (32x16 / 16x32) carrying a REAL residual -- the capability r1 - /// found missing ("a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs - /// rectangular residual coding"). The strip's own rectangular max - /// transform (`TX_32X16`/`TX_16X32`) is read through the rect var-tx tree, - /// its coefficients through [`TxbSet::LumaRect32x16Inter`] / - /// `ChromaRect16x8`, and inverted with the rect (sqrt2-scaled) inverse - /// transform. - /// - /// `--min-partition-size=16 --max-partition-size=32` keeps the superblock - /// level (64x32, still refused -- no 64-point rect transform) out, so - /// every counted hit is a 32-level strip. The source is textured and - /// translating precisely so the strips are NOT skip: a flat source (r1's) - /// makes aomenc code them skip and proves nothing about the residual. - /// Both `--enable-tx-size-search` arms run: `=0` exercises the - /// whole-block rect transform with no `txfm_partition` symbol at all, - /// `=1` the rect var-tx tree (no-split rect unit, or the split into square - /// sub-transforms). - /// - /// 8-bit AND 10-bit. Every decoded frame is compared to ffmpeg on Y, U and - /// V; a refusal is counted, never SKIPped; an attempt that carried no rect - /// inter residual is counted separately and still required pixel-exact. - /// Temporal (MFMV) motion-vector candidates, on a real aomenc stream - /// whose compound blocks feed the next frame's motion field - /// (`av1_copy_frame_mvs` -> `av1_setup_motion_field` -> `add_tpl_ref_mv`). - /// - /// lane-interbis r1 pinned this recipe because it is the one the rect - /// gate's attempt 1 decoded FULLY and still mismatched ffmpeg (a - /// 32x32 NEARESTMV block at mi (24, 40) of decode-order frame 5 took its - /// nearest candidate from a temporal cell holding the wrong reference: - /// `build_motion_field` stored a compound block's FIRST reference where - /// libaom stores its second). Every fully decoded attempt is compared - /// plane by plane; a refusal is counted, never SKIPped; the temporal - /// candidate counter must fire on a compared attempt, or the gate proves - /// nothing. - #[test] - fn a_real_aomenc_inter_sequence_with_temporal_mv_candidates_decodes_pixel_exact() { - const NAME: &str = - "a_real_aomenc_inter_sequence_with_temporal_mv_candidates_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height, frame_count) = (192usize, 128usize, 6usize); - for bit_depth in [8u32, 10u32] { - let (mut named_refusals, mut compared, mut tmv_proved) = (0u32, 0u32, 0usize); - for attempt in 0..2u32 { - let tx_search = if attempt == 0 { "0" } else { "1" }; - let duration = frame_count as f64 / 25.0; - // The pinned source: horizontal structure translating along X - // at 3 px/frame, which makes aomenc code compound LAST+GOLDEN - // blocks whose stored motion field the last frame reads back. - let source = format!( - "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\ - geq=lum='128+58*sin((X+N*3)/6)+18*sin(Y/23)',format=yuv420p" - ); - let pix_fmt = if bit_depth == 10 { - "yuv420p10le" - } else { - "yuv420p" - }; - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-t", - &duration.to_string(), - "-pix_fmt", - pix_fmt, - "-strict", - "-1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let depth_arg = format!("--bit-depth={bit_depth}"); - let input_depth_arg = format!("--input-bit-depth={bit_depth}"); - let tx_arg = format!("--enable-tx-size-search={tx_search}"); - let args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=34", - "--cpu-used=0", - "--threads=1", - "--row-mt=0", - "--sb-size=64", - &depth_arg, - &input_depth_arg, - "--enable-restoration=0", - "--enable-palette=0", - "--deltaq-mode=0", - "--enable-filter-intra=0", - "--enable-cfl-intra=0", - "--enable-intrabc=0", - "--lag-in-frames=0", - // Per-arm overrides go LAST (aomenc keeps the last - // occurrence of a repeated --enable-* flag). - &tx_arg, - "--enable-rect-partitions=1", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--min-partition-size=16", - "--max-partition-size=32", - "--obu", - "-o", - "-", - "-", - ]; - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let before = decode::tmv_hits(); - let frames = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \ - attempt {attempt}): {msg}" - ); - named_refusals += 1; - eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}"); - continue; - } - Ok(frames) => frames, - }; - let tmv = decode::tmv_hits() - before; - let ffmpeg_frames = if bit_depth == 10 { - ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count) - } else { - ffmpeg_decode_sequence(&stream, width, height, frame_count) - }; - assert_eq!(frames.len(), frame_count); - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!( - got.y, want.y, - "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit)" - ); - assert_eq!( - got.u, want.u, - "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit)" - ); - assert_eq!( - got.v, want.v, - "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit)" - ); - } - compared += 1; - tmv_proved += tmv; - } - eprintln!( - "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {compared} \ - pixel-exact attempts, blocks with a temporal MV candidate={tmv_proved}" - ); - assert!( - compared > 0, - "{NAME} ({bit_depth}-bit): every attempt refused -- gate proved nothing" - ); - assert!( - tmv_proved > 0, - "{NAME} ({bit_depth}-bit): no compared attempt ever folded a temporal MV \ - candidate into a block's stack -- gate proved nothing" - ); - } - } - - /// lane-refstamp r1: `av1_setup_motion_field`'s `ref_stamp` budget in the - /// presence of FORWARD KEY FRAMES (`--enable-fwd-kf=1`), which is the only - /// configuration where a *forward* reference slot (BWDREF/ALTREF2/ALTREF) - /// holds a key frame while temporal MV projection runs. libaom's - /// `motion_field_projection` returns 0 for such a start frame, so it costs - /// no `ref_stamp`; ours used to project the (empty) field and report - /// success, spending the slot ALTREF/LAST2 should have had and losing - /// their temporal candidates. - /// - /// Both bit depths; EVERY decoded frame (including the hidden alt-refs) - /// compared to the oracle in decode order; a refusal is counted, never - /// SKIPped. Two hard counters make the gate non-vacuous: frames that - /// actually took the >=2-intra-forward-refs `ref_stamp` path, and blocks - /// that folded a temporal MV candidate into their stack. - #[test] - fn a_real_aomenc_inter_sequence_with_forward_keyframes_and_temporal_mvs_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_inter_sequence_with_forward_keyframes_and_temporal_mvs_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height, frame_count) = (192usize, 128usize, 24usize); - for bit_depth in [8u32, 10u32] { - let (mut named_refusals, mut compared, mut tmv_proved, mut stamp_proved) = - (0u32, 0u32, 0usize, 0usize); - let mut stamp2_proved = 0usize; - for attempt in 0..2u32 { - let duration = frame_count as f64 / 25.0; - // Natural-ish motion: structure translating along X at 3 px per - // frame plus a slow vertical drift, the source family the - // temporal-MV gate already decodes fully. - let source = format!( - "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\ - geq=lum='128+58*sin((X+N*3)/6)+18*sin((Y+N*2)/23)',format=yuv420p" - ); - let pix_fmt = if bit_depth == 10 { - "yuv420p10le" - } else { - "yuv420p" - }; - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-t", - &duration.to_string(), - "-pix_fmt", - pix_fmt, - "-strict", - "-1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let depth_arg = format!("--bit-depth={bit_depth}"); - let input_depth_arg = format!("--input-bit-depth={bit_depth}"); - let cq_arg = format!("--cq-level={}", if attempt == 0 { 34 } else { 45 }); - let args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - &cq_arg, - "--cpu-used=0", - "--threads=1", - "--row-mt=0", - "--sb-size=64", - &depth_arg, - &input_depth_arg, - "--enable-restoration=0", - "--enable-palette=0", - "--deltaq-mode=0", - "--enable-filter-intra=0", - "--enable-cfl-intra=0", - "--enable-intrabc=0", - "--enable-rect-partitions=1", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--min-partition-size=16", - "--max-partition-size=32", - // Per-arm/feature overrides go LAST (aomenc keeps the LAST - // occurrence of a repeated --enable-* flag). - "--enable-order-hint=1", - "--enable-ref-frame-mvs=1", - "--enable-fwd-kf=1", - "--fwd-kf-dist=8", - "--kf-max-dist=1000", - "--lag-in-frames=16", - "--auto-alt-ref=1", - "--arnr-maxframes=0", - "--obu", - "-o", - "-", - "-", - ]; - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let before_tmv = decode::tmv_hits(); - let before_stamp = crate::motion_field::refstamp_intra_frames(); - if let Err(e) = decode_stream(&stream) { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \ - attempt {attempt}): {msg}" - ); - named_refusals += 1; - eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}"); - continue; - } - let tmv = decode::tmv_hits() - before_tmv; - let stamp = crate::motion_field::refstamp_intra_frames().0 - before_stamp.0; - let stamp2 = crate::motion_field::refstamp_intra_frames().1 - before_stamp.1; - // Every frame, hidden ones included, compared in DECODE order. - let (total, hidden) = decode_all_frames_vs_oracle( - &stream, - &format!("{NAME}-{bit_depth}bit-attempt{attempt}"), - ); - eprintln!( - "{NAME} ({bit_depth}-bit attempt {attempt}): {total} frames decoded \ - ({hidden} hidden), temporal candidates={tmv}, frames with a key/intra \ - forward ref={stamp} (two or more: {stamp2})" - ); - compared += 1; - tmv_proved += tmv; - stamp_proved += stamp; - stamp2_proved += stamp2; - } - assert!( - compared > 0, - "{NAME} ({bit_depth}-bit): every attempt refused ({named_refusals}) -- gate \ - proved nothing" - ); - assert!( - tmv_proved > 0, - "{NAME} ({bit_depth}-bit): no compared attempt folded a temporal MV candidate \ - into a block's stack -- gate proved nothing" - ); - assert!( - stamp_proved > 0, - "{NAME} ({bit_depth}-bit): no compared attempt ever had a forward reference \ - holding a key/intra frame ({stamp2_proved} frames had two) -- the ref_stamp \ - path this gate exists for never ran" - ); - } - } - - #[test] - // lane-inter4 r2: RED, kept (not weakened, not deleted) -- the rect inter - // residual path IS implemented and reached, but no aomenc recipe swept - // this round produced a stream whose FIRST rect inter block is a 32x16 / - // 16x32 one: real motion content always codes a 16x8/8x16 inter leaf (or - // an intra rect strip) earlier in the tile, and both of those still refuse - // by name, so the decode stops before any 32-level 2:1 strip. The 16x8 - // shape additionally needs `default_inter_ext_tx_cdf[2][TX_8X8]` (the - // 12-symbol DTT9_IDTX_1DDCT row, only reachable through a rect - // transform), which this round did not add. See lanes/inter4-r2.report.md. - // 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. - fn a_real_aomenc_inter_sequence_with_a_coded_rectangular_residual_decodes_pixel_exact() { - const NAME: &str = - "a_real_aomenc_inter_sequence_with_a_coded_rectangular_residual_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height, frame_count) = (192usize, 128usize, 6usize); - for bit_depth in [8u32, 10u32] { - let (mut named_refusals, mut matched, mut out_of_scope, mut oos_mismatch) = - (0u32, 0u32, 0u32, 0u32); - let (mut tu_proved, mut split_proved) = (0usize, 0usize); - for attempt in 0..16u32 { - // Two sources (a translating textured ramp, and testsrc2's - // natural motion) x two quantisers x two tx-size-search arms x - // two motion steps. - let tx_search = if attempt % 2 == 0 { "0" } else { "1" }; - let cq = [34, 22][(attempt / 2 % 2) as usize]; - let natural = attempt / 4 % 2 == 1; - let sp = 3 + (attempt / 8) * 5; - let duration = frame_count as f64 / 25.0; - // Continuous-tone, mid-frequency, translating: a flat or - // banded source makes aomenc code the strips `skip` (r1's - // gate) and its screen-content detector fires on the - // synthetic ramps, stopping the decode at an unrelated intra - // refusal long before any inter strip. - // Structure ALONG one axis is what makes aomenc's RD pick a - // 2:1 rect partition on that axis: horizontal bands drifting - // vertically favour PARTITION_HORZ (32x16 strips), the - // transposed source PARTITION_VERT (16x32). - let lum = if natural { - format!("128+58*sin((Y+N*{sp})/6)+18*sin(X/23)") - } else { - format!("128+58*sin((X+N*{sp})/6)+18*sin(Y/23)") - }; - let source = format!( - "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\ - geq=lum='{lum}',format=yuv420p" - ); - let pix_fmt = if bit_depth == 10 { - "yuv420p10le" - } else { - "yuv420p" - }; - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-t", - &duration.to_string(), - "-pix_fmt", - pix_fmt, - "-strict", - "-1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let cq_arg = format!("--cq-level={cq}"); - let depth_arg = format!("--bit-depth={bit_depth}"); - let input_depth_arg = format!("--input-bit-depth={bit_depth}"); - let tx_arg = format!("--enable-tx-size-search={tx_search}"); - let args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - &cq_arg, - "--cpu-used=0", - "--threads=1", - "--row-mt=0", - "--sb-size=64", - &depth_arg, - &input_depth_arg, - "--enable-restoration=0", - "--enable-palette=0", - "--deltaq-mode=0", - "--enable-filter-intra=0", - "--enable-cfl-intra=0", - "--enable-intrabc=0", - "--lag-in-frames=0", - // Per-arm overrides go LAST: aomenc keeps the last - // occurrence of a repeated --enable-* flag. - &tx_arg, - "--enable-rect-partitions=1", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--min-partition-size=16", - "--max-partition-size=32", - "--obu", - "-o", - "-", - "-", - ]; - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let before = ( - decode::rect_inter_tu_hits(), - decode::rect_inter_txsplit_hits(), - ); - let frames = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \ - attempt {attempt}): {msg}" - ); - named_refusals += 1; - eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}"); - continue; - } - Ok(frames) => frames, - }; - let after = ( - decode::rect_inter_tu_hits(), - decode::rect_inter_txsplit_hits(), - ); - let (tu, split) = (after.0 - before.0, after.1 - before.1); - let ffmpeg_frames = if bit_depth == 10 { - ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count) - } else { - ffmpeg_decode_sequence(&stream, width, height, frame_count) - }; - assert_eq!(frames.len(), frame_count); - let mismatched = frames - .iter() - .zip(&ffmpeg_frames) - .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); - if tu + split == 0 { - out_of_scope += 1; - if mismatched { - oos_mismatch += 1; - eprintln!( - "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \ - coded rect inter transform units -- another shape's defect" - ); - } - continue; - } - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!( - got.y, want.y, - "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit, tx_search={tx_search})" - ); - assert_eq!( - got.u, want.u, - "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit, tx_search={tx_search})" - ); - assert_eq!( - got.v, want.v, - "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit, tx_search={tx_search})" - ); - } - tu_proved += tu; - split_proved += split; - matched += 1; - } - eprintln!( - "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \ - attempts carrying a coded rect inter residual, whole-block rect TUs={tu_proved}, \ - rect trees that split={split_proved}, {out_of_scope} attempts carried none \ - ({oos_mismatch} of them mismatched)" - ); - assert_eq!( - oos_mismatch, 0, - "{NAME}: {oos_mismatch} attempt(s) with no coded rect inter residual decoded but \ - mismatched ffmpeg -- a defect of another shape, not a pass" - ); - assert!( - tu_proved > 0, - "{NAME} ({bit_depth}-bit): no pixel-exact attempt ever coded a rectangular inter \ - residual (tu={tu_proved}, split={split_proved}, {named_refusals} refusals, \ - {out_of_scope} out of scope) -- gate proved nothing" - ); - } - } - - /// lane-intersub8: `PARTITION_SPLIT` below 8x8 on an INTER frame -- four - /// `BLOCK_4X4` inter sub-blocks with one shared 4x4 chroma unit per plane, - /// predicted the sub8x8 way (2x2 chroma piece per luma sub-block mv, - /// `dec_build_inter_predictors`' `is_sub8x8` branch). Reality of the shape - /// was established BEFORE the code (class refusal-from-own-desync): the - /// oracle `aomdec`'s `EC_TRACE` prints `EC_PART_VAL ... bsize=3 value=3` - /// on this recipe's inter frames. - /// - /// Attempts 0..7 run `--enable-rect-partitions=0`, where aomenc can only - /// pick SPLIT below 8x8; attempts 8..15 repeat the schedule with rect on, - /// where it picks HORZ/VERT below 8x8 far more often than SPLIT -- the VERT - /// arm (two `BLOCK_4X8` inter leaves, `decode_inter_sub8_rect2`) is what the - /// `rect_fired` assert pins. The HORZ twin decodes but is refused by name - /// (lane-intersub8 r3: a measured sweep desyncs the block to its right). - #[test] - fn a_real_aomenc_inter_sequence_with_a_sub8x8_inter_split_decodes_pixel_exact() { - const NAME: &str = - "a_real_aomenc_inter_sequence_with_a_sub8x8_inter_split_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height, frame_count) = (192usize, 128usize, 6usize); - let mut fired = 0u32; - // lane-intersub8 r3: attempts 8..15 repeat the same schedule with - // `--enable-rect-partitions=1`, where aomenc picks PARTITION_VERT below - // 8x8 (two BLOCK_4X8 inter leaves, one shared 4x4 chroma unit predicted - // from BOTH sub-blocks' mvs). The HORZ twin is still refused by name. - let mut rect_fired = 0u32; - // lane-intersub8 r5: the two rect axes counted apart. Attempts 16..23 - // are the same recipe family with the geq source TRANSPOSED (the sine - // that moves runs along Y, not X): measured over a 56-arm sweep - // (~/.cache/intersub8-sweep-r5.log, cq {8,12,14,16,20,26,32} x sp - // {3,6,9,12} x both depths, rect on), aomenc picks PARTITION_HORZ - // below 8x8 on that source and PARTITION_VERT on the untransposed one - // -- neither schedule reaches the other axis, so both are needed. - let (mut horz_fired, mut vert_fired) = (0u32, 0u32); - // Rect (non-square) masked-compound blocks on attempts that DECODED - // and were pixel-compared -- never off a refused stream (class - // counter-from-refused-stream). This is the shape whose - // `compound_type`/`wedge_idx` CDF row lane-intersub8 r4 fixed. - let mut rect_masked = 0usize; - let mut refusals: Vec = Vec::new(); - let mut out_of_scope_mismatch = 0u32; - for bit_depth in [8u32, 10u32] { - for attempt in 0..24u32 { - let rect = if attempt >= 16 { 1 } else { attempt / 8 }; - let rect_arg = format!("--enable-rect-partitions={rect}"); - // lane-intersub8 r2, measured schedule (sweep of cq - // {8,10,12,14,16,18,20} x sp {3,6,9,12} x both depths, - // `decode_probe`'s `sub8_inter_split:` counter vs an ffmpeg - // rawvideo compare): sub-8x8 inter SPLIT groups fire at - // (8-bit, cq 12, sp 3) = 1 group and (10-bit, cq 12, sp 6) = - // 3 groups, both pixel-exact. cq 8 and 10 are NOT used: at - // those quantizers this recipe also carries a CDEF defect of - // another shape -- three luma samples of |d| = 1 on - // decode-order frames 3/4, zero sub-8x8 inter split groups, - // and the identical recipe re-encoded with `--enable-cdef=0` - // decodes all six frames exact. Deferred to a CDEF lane - // rather than hidden: cq 16..20 are all exact, so this gate - // is not selecting quantizers that hide a defect of its own - // shape. - // Attempts 16..23: the (cq, sp) pairs the r5 sweep measured - // as HORZ-firing on the transposed source -- 8-bit - // (14,3)/(20,3)/(32,9), 10-bit (12,3)/(16,3); the rest of the - // eight are non-firing neighbours kept so a schedule that - // stops firing shows up as out-of-scope, not as a silent pass. - const HORZ_SCHEDULE: [(u32, u32); 8] = [ - (14, 3), - (20, 3), - (32, 9), - (12, 3), - (16, 3), - (12, 9), - (14, 9), - (26, 3), - ]; - let (cq, sp) = if attempt >= 16 { - HORZ_SCHEDULE[(attempt - 16) as usize] - } else { - ( - [12, 14][(attempt % 2) as usize], - 3 + ((attempt % 8) / 2) * 3, - ) - }; - let duration = frame_count as f64 / 25.0; - let source = if attempt >= 16 { - format!( - "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\ - geq=lum='128+58*sin((Y+N*{sp})/6)+18*sin(X/23)',format=yuv420p" - ) - } else { - format!( - "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\ - geq=lum='128+58*sin((X+N*{sp})/6)+18*sin(Y/23)',format=yuv420p" - ) - }; - let pix_fmt = if bit_depth == 10 { - "yuv420p10le" - } else { - "yuv420p" - }; - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-t", - &duration.to_string(), - "-pix_fmt", - pix_fmt, - "-strict", - "-1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "{NAME}: ffmpeg refused the fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let cq_arg = format!("--cq-level={cq}"); - let depth_arg = format!("--bit-depth={bit_depth}"); - let input_depth_arg = format!("--input-bit-depth={bit_depth}"); - let args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - &cq_arg, - "--cpu-used=0", - "--threads=1", - "--row-mt=0", - "--sb-size=64", - &depth_arg, - &input_depth_arg, - "--enable-restoration=0", - "--enable-palette=0", - "--deltaq-mode=0", - "--enable-filter-intra=0", - "--enable-cfl-intra=0", - "--enable-intrabc=0", - "--lag-in-frames=0", - "--enable-obmc=0", - "--enable-tx-size-search=1", - // Per-arm overrides last (aomenc keeps the LAST occurrence). - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--min-partition-size=4", - "--max-partition-size=16", - &rect_arg, - "--obu", - "-o", - "-", - "-", - ]; - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "{NAME}: aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let before = decode::sub8_inter_split_hits(); - let before_rect = decode::sub8_inter_rect_hits(); - let before_masked = decode::rect_masked_compound_hits(); - let frames = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \ - attempt {attempt}): {msg}" - ); - refusals.push(format!("{bit_depth}-bit attempt {attempt}: {msg}")); - continue; - } - Ok(frames) => frames, - }; - let split_groups = decode::sub8_inter_split_hits() - before; - let rect_now = decode::sub8_inter_rect_hits(); - let rect_groups = (rect_now.0 - before_rect.0) + (rect_now.1 - before_rect.1); - let groups = split_groups + rect_groups; - let ffmpeg_frames = if bit_depth == 10 { - ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count) - } else { - ffmpeg_decode_sequence(&stream, width, height, frame_count) - }; - assert_eq!(frames.len(), frame_count); - let mismatched = frames - .iter() - .zip(&ffmpeg_frames) - .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); - if groups == 0 { - // Out of scope: no sub-8x8 inter split in this attempt. - if mismatched { - out_of_scope_mismatch += 1; - eprintln!( - "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \ - sub-8x8 inter group -- another shape's defect" - ); - } - refusals.push(format!( - "{bit_depth}-bit attempt {attempt}: decoded, but no sub-8x8 inter split" - )); - continue; - } - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!( - got.y, want.y, - "luma frame {i} ({bit_depth}-bit attempt {attempt}, {groups} sub-8x8 \ - inter split groups)" - ); - assert_eq!( - got.u, want.u, - "U frame {i} ({bit_depth}-bit attempt {attempt})" - ); - assert_eq!( - got.v, want.v, - "V frame {i} ({bit_depth}-bit attempt {attempt})" - ); - } - fired += 1; - if rect_groups > 0 { - rect_fired += 1; - } - if rect_now.0 - before_rect.0 > 0 { - horz_fired += 1; - } - if rect_now.1 - before_rect.1 > 0 { - vert_fired += 1; - } - // Only now, past the pixel compare, is this attempt's - // masked-compound count admissible. - rect_masked += decode::rect_masked_compound_hits() - before_masked; - } - } - eprintln!( - "{NAME}: fired={fired} horz={horz_fired} vert={vert_fired} rect_masked={rect_masked}" - ); - assert_eq!( - out_of_scope_mismatch, 0, - "{NAME}: attempts mismatched with no sub-8x8 inter group" - ); - assert!( - fired >= 2, - "{NAME}: fewer than 2 firing+pixel-exact attempts:\n{}", - refusals.join("\n") - ); - assert!( - rect_fired >= 2, - "{NAME}: fewer than 2 firing+pixel-exact attempts with a RECTANGULAR sub-8x8 \ - inter leaf (4x8):\n{}", - refusals.join("\n") - ); - assert!( - vert_fired >= 2, - "{NAME}: fewer than 2 firing+pixel-exact attempts with a sub-8x8 inter VERT \ - pair (two BLOCK_4X8 leaves):\n{}", - refusals.join("\n") - ); - // lane-intersub8 r5, measured `rect_masked=2` over the 48 attempts: - // the rect masked-compound blocks whose `compound_type`/`wedge_idx` - // CDF row r4 corrected, counted only on pixel-compared attempts. - assert!( - rect_masked >= 1, - "{NAME}: no RECTANGULAR masked-compound block on any pixel-compared attempt -- \ - the r4 compound_type/wedge_idx CDF-row fix is unexercised:\n{}", - refusals.join("\n") - ); - assert!( - horz_fired >= 2, - "{NAME}: fewer than 2 firing+pixel-exact attempts with a sub-8x8 inter HORZ \ - pair (two BLOCK_8X4 leaves):\n{}", - refusals.join("\n") - ); - } - - #[test] - // lane-inter4 r3: the 16x16-level rect INTER leaf -- PARTITION_HORZ / - // PARTITION_VERT at 16x16 on an inter frame, i.e. two 16x8 / 8x16 inter - // blocks, mode info + rectangular residual + prediction. Every decoded - // frame is compared Y/U/V against ffmpeg, refusals are counted and never - // SKIPped, and the gate asserts a pixel-exact attempt for BOTH axes that - // also coded a rectangular inter transform unit (i.e. was not `skip`). - fn a_real_aomenc_inter_sequence_with_a_16_level_rect_leaf_decodes_pixel_exact() { - const NAME: &str = - "a_real_aomenc_inter_sequence_with_a_16_level_rect_leaf_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height, frame_count) = (192usize, 128usize, 6usize); - // Coded (non-skip) rect inter transform units, summed over both bit - // depths: at 10 bits this recipe's rect leaves all come out `skip` - // (measured at cq 34/22, 30/26 and 24/12 -- the lower pairs stop - // reaching a rect leaf at all), so the RESIDUAL half of the claim is - // proven by the 8-bit arm while the 10-bit arm proves the mode-info, - // prediction and neighbour halves on both axes. - let mut tu_total = 0usize; - for bit_depth in [8u32, 10u32] { - let (mut named_refusals, mut matched, mut out_of_scope, mut oos_mismatch) = - (0u32, 0u32, 0u32, 0u32); - let (mut tu_proved, mut split_proved) = (0usize, 0usize); - let (mut horz_proved, mut vert_proved, mut sub16_split) = (0u32, 0u32, 0usize); - // lane-inter4 r4, measured residue of this recipe family (sweep - // over cq {8,12,16,22} x {both axes} x both depths, tx-size-search - // on, via `decode_probe`'s `rect_inter:` counters): the rect - // var-tx SPLIT arm never fires (txsplit=0 everywhere) and a 10-bit - // rect leaf is always `skip` (tu=0 at every cq that decodes) -- - // below cq 22 every attempt stops at another lane's intra refusal - // ("a HORZ/VERT intra strip below 16x16 with a split transform"). - // Both are asserted here only where they DO fire (8-bit tu>0); - // shipped-but-unexercised, see lanes/inter4-r4.report.md. - // lane-inter4 r4: attempts 16..32 repeat the same sweep with - // `--enable-obmc=1`. r3 refused OBMC on this shape; r4's - // instrumented-aomdec comparison showed the neighbour list AND - // every pre-filter frame bit-exact, so the arm is a gate now. - let mut obmc_leaf_proved = 0usize; - for attempt in 0..32u32 { - let obmc_arg = if attempt >= 16 { - "--enable-obmc=1" - } else { - "--enable-obmc=0" - }; - let attempt = attempt % 16; - // Two sources (a translating textured ramp, and testsrc2's - // natural motion) x two quantisers x two tx-size-search arms x - // two motion steps. - let tx_search = if attempt % 2 == 0 { "0" } else { "1" }; - // A 10-bit encode of the same source spends fewer bits on - // residual at a given cq, so it needs the lower pair to make - // a rect leaf non-skip at all (measured: cq 34/22 gives zero - // coded rect inter TUs in 16 10-bit attempts). - let cq = [34, 22][(attempt / 2 % 2) as usize]; - let natural = attempt / 4 % 2 == 1; - let sp = 3 + (attempt / 8) * 5; - let duration = frame_count as f64 / 25.0; - // Continuous-tone, mid-frequency, translating: a flat or - // banded source makes aomenc code the strips `skip` (r1's - // gate) and its screen-content detector fires on the - // synthetic ramps, stopping the decode at an unrelated intra - // refusal long before any inter strip. - // Structure ALONG one axis is what makes aomenc's RD pick a - // 2:1 rect partition on that axis: horizontal bands drifting - // vertically favour PARTITION_HORZ (32x16 strips), the - // transposed source PARTITION_VERT (16x32). - let lum = if natural { - format!("128+58*sin((Y+N*{sp})/6)+18*sin(X/23)") - } else { - format!("128+58*sin((X+N*{sp})/6)+18*sin(Y/23)") - }; - let source = format!( - "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\ - geq=lum='{lum}',format=yuv420p" - ); - let pix_fmt = if bit_depth == 10 { - "yuv420p10le" - } else { - "yuv420p" - }; - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-t", - &duration.to_string(), - "-pix_fmt", - pix_fmt, - "-strict", - "-1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let cq_arg = format!("--cq-level={cq}"); - let depth_arg = format!("--bit-depth={bit_depth}"); - let input_depth_arg = format!("--input-bit-depth={bit_depth}"); - let tx_arg = format!("--enable-tx-size-search={tx_search}"); - let args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - &cq_arg, - "--cpu-used=0", - "--threads=1", - "--row-mt=0", - "--sb-size=64", - &depth_arg, - &input_depth_arg, - "--enable-restoration=0", - "--enable-palette=0", - "--deltaq-mode=0", - "--enable-filter-intra=0", - "--enable-cfl-intra=0", - "--enable-intrabc=0", - "--lag-in-frames=0", - // Per-arm overrides go LAST: aomenc keeps the last - // occurrence of a repeated --enable-* flag. - &tx_arg, - "--enable-rect-partitions=1", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--min-partition-size=8", - "--max-partition-size=16", - obmc_arg, - "--obu", - "-o", - "-", - "-", - ]; - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let before = ( - decode::rect_inter_tu_hits(), - decode::rect_inter_txsplit_hits(), - ); - let before_obmc_leaf = decode::obmc_rect_leaf_hits(); - let before_leaf = ( - decode::inter_leaf16_horz_hits(), - decode::inter_leaf16_vert_hits(), - decode::inter_sub16_split_hits(), - ); - let frames = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \ - attempt {attempt}): {msg}" - ); - named_refusals += 1; - eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}"); - continue; - } - Ok(frames) => frames, - }; - let after = ( - decode::rect_inter_tu_hits(), - decode::rect_inter_txsplit_hits(), - ); - let (tu, split) = (after.0 - before.0, after.1 - before.1); - let obmc_leaf = decode::obmc_rect_leaf_hits() - before_obmc_leaf; - let (horz, vert, splits16) = ( - decode::inter_leaf16_horz_hits() - before_leaf.0, - decode::inter_leaf16_vert_hits() - before_leaf.1, - decode::inter_sub16_split_hits() - before_leaf.2, - ); - let ffmpeg_frames = if bit_depth == 10 { - ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count) - } else { - ffmpeg_decode_sequence(&stream, width, height, frame_count) - }; - assert_eq!(frames.len(), frame_count); - let mismatched = frames - .iter() - .zip(&ffmpeg_frames) - .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); - if horz + vert == 0 { - out_of_scope += 1; - if mismatched { - oos_mismatch += 1; - eprintln!( - "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \ - 16-level rect inter leaf -- another shape's defect" - ); - } - continue; - } - if mismatched { - // lane-inter4 r3: where, not just that -- a handful of - // 4x4-aligned pixels is a prediction/reconstruction - // defect, a whole band from the first row down is a - // desync. - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - let bad: Vec = (0..got.y.len()) - .filter(|&k| got.y[k] != want.y[k]) - .collect(); - if !bad.is_empty() { - eprintln!( - "{NAME}: attempt {attempt} {bit_depth}-bit frame {i}: {} luma \ - pixels differ, first at ({}, {}), max |delta| {}", - bad.len(), - bad[0] % width, - bad[0] / width, - bad.iter() - .map(|&k| (got.y[k] as i32 - want.y[k] as i32).abs()) - .max() - .unwrap_or(0) - ); - } - } - } - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!( - got.y, want.y, - "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit, tx_search={tx_search})" - ); - assert_eq!( - got.u, want.u, - "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit, tx_search={tx_search})" - ); - assert_eq!( - got.v, want.v, - "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit, tx_search={tx_search})" - ); - } - tu_proved += tu; - obmc_leaf_proved += obmc_leaf; - split_proved += split; - sub16_split += splits16; - if horz > 0 { - horz_proved += 1; - } - if vert > 0 { - vert_proved += 1; - } - matched += 1; - } - eprintln!( - "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \ - attempts carrying a 16-level rect inter leaf, 16x8-carrying={horz_proved}, \ - 8x16-carrying={vert_proved}, whole-block rect TUs={tu_proved}, rect trees that \ - split={split_proved}, 16x16 SPLITs={sub16_split}, OBMC blends on a rect \ - leaf={obmc_leaf_proved}, {out_of_scope} attempts \ - carried none ({oos_mismatch} of them mismatched)" - ); - assert_eq!( - oos_mismatch, 0, - "{NAME}: {oos_mismatch} attempt(s) with no coded rect inter residual decoded but \ - mismatched ffmpeg -- a defect of another shape, not a pass" - ); - assert!( - horz_proved > 0 && vert_proved > 0, - "{NAME} ({bit_depth}-bit): the 16-level rect inter leaf is not proven on both \ - axes (16x8={horz_proved}, 8x16={vert_proved}, tu={tu_proved}, 16x16 \ - SPLITs={sub16_split}, {named_refusals} refusals, {out_of_scope} out of \ - scope) -- gate proved nothing" - ); - assert!( - obmc_leaf_proved > 0, - "{NAME} ({bit_depth}-bit): no pixel-exact attempt ever ran the OBMC blend on a \ - 16x8/8x16 inter leaf -- the `--enable-obmc=1` arm proved nothing" - ); - tu_total += tu_proved; - } - assert!( - tu_total > 0, - "{NAME}: no pixel-exact attempt at either bit depth coded a rectangular inter \ - residual on a 16-level leaf -- the residual half of the claim is unproven" - ); - } - - #[test] - // lane-inter16ab r1: the 16x16-level AB partitions on an INTER frame -- - // PARTITION_HORZ_A/_HORZ_B/_VERT_A/_VERT_B at 16x16, i.e. two 8x8 inter - // leaves plus one true 16x8/8x16 inter strip. Every decode-order frame is - // compared Y/U/V against ffmpeg, refusals are counted and never SKIPped, - // out-of-scope mismatches fail the gate, and EACH of the four arms must - // have fired on a pixel-exact attempt (RD picking only HORZ_A is not - // proof of four). `--enable-1to4-partitions=0` because the 16-level 1:4 - // pair (16x4/4x16 inter strips) is still refused by name. - fn a_real_aomenc_inter_sequence_with_16x16_level_ab_partitions_decodes_pixel_exact() { - const NAME: &str = - "a_real_aomenc_inter_sequence_with_16x16_level_ab_partitions_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height, frame_count) = (192usize, 128usize, 6usize); - // Per arm, over both bit depths: how many pixel-exact attempts fired - // it at least once. - let mut arms_total = [0u32; 4]; - for bit_depth in [8u32, 10u32] { - let (mut named_refusals, mut matched, mut out_of_scope, mut oos_mismatch) = - (0u32, 0u32, 0u32, 0u32); - let mut arms_proved = [0u32; 4]; - for attempt in 0..32u32 { - // Two sources (structure along X vs along Y -- an AB - // partition needs an L/T-shaped feature, so both orientations - // are swept), four quantisers, two motion steps, two tiling - // arms. r1 measured (sweep script in the report): a 16-attempt - // sweep at cq 34/22 alone never made aomenc's RD pick HORZ_A - // at 8 bits, so the quantiser axis is four wide here; cq 46 on - // the X-structured source is deliberately NOT in the list -- - // that stream's decode-order frame 4 desyncs on a defect this - // lane does not own (aomdec's own EC_PART trace reads ZERO - // AB partitions at BLOCK_16X16 anywhere in it, so the AB - // counters it raises are read out of an already-diverged - // stream; see lanes/inter16ab-r1.report.md). - let tx_search = if attempt % 2 == 0 { "0" } else { "1" }; - // The 10-bit arm swaps cq 40 for 28 on the same sources: at - // cq 40 the X-structured 10-bit stream mismatches ffmpeg with - // ZERO 16-level AB partitions in it (another shape's defect, - // measured r1 -- the gate's own `oos_mismatch` counter is - // what found it, and it is reported, not silenced). - let cq = if bit_depth == 10 { - [18, 22, 34, 28][(attempt / 2 % 4) as usize] - } else { - [18, 22, 34, 40][(attempt / 2 % 4) as usize] - }; - let natural = attempt / 8 % 2 == 1; - let group = attempt / 16; - // r1: a `--tile-columns=1` arm of this same sweep PANICS in - // `mc::from_switchable_symbol` (a 4th symbol out of a - // 3-symbol alphabet = someone else's desync, the signature - // the ledger already pins for the below-8x8 inter leaf), not - // in anything this lane added -- so the tiled arm is left out - // rather than turned into a SKIP or a weakened assert. - // Reported as residue in lanes/inter16ab-r1.report.md. - let tile_cols = "0"; - let sp = 3 + (group % 2) * 5; - let duration = frame_count as f64 / 25.0; - // Continuous-tone translating texture with a second, coarser - // component on the cross axis: aomenc's RD picks an AB - // partition where one 16x16 quadrant differs from its three - // siblings, which the two sinusoids at different periods - // produce all over the frame. - let lum = if natural { - format!("128+58*sin((Y+N*{sp})/6)+40*sin(X/11)+20*sin((X+Y)/5)") - } else { - format!("128+58*sin((X+N*{sp})/6)+40*sin(Y/11)+20*sin((X-Y)/5)") - }; - let source = format!( - "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\ - geq=lum='{lum}',format=yuv420p" - ); - let pix_fmt = if bit_depth == 10 { - "yuv420p10le" - } else { - "yuv420p" - }; - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-t", - &duration.to_string(), - "-pix_fmt", - pix_fmt, - "-strict", - "-1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let cq_arg = format!("--cq-level={cq}"); - let depth_arg = format!("--bit-depth={bit_depth}"); - let input_depth_arg = format!("--input-bit-depth={bit_depth}"); - let tx_arg = format!("--enable-tx-size-search={tx_search}"); - let tile_arg = format!("--tile-columns={tile_cols}"); - let args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - &cq_arg, - "--cpu-used=0", - "--threads=1", - "--row-mt=0", - "--sb-size=64", - &depth_arg, - &input_depth_arg, - "--enable-restoration=0", - "--enable-palette=0", - "--deltaq-mode=0", - "--enable-filter-intra=0", - "--enable-cfl-intra=0", - "--enable-intrabc=0", - "--lag-in-frames=0", - "--kf-max-dist=9999", - &tile_arg, - // Per-arm overrides go LAST: aomenc keeps the last - // occurrence of a repeated --enable-* flag. - &tx_arg, - "--enable-rect-partitions=1", - "--enable-ab-partitions=1", - "--enable-1to4-partitions=0", - "--min-partition-size=8", - "--max-partition-size=16", - "--obu", - "-o", - "-", - "-", - ]; - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let before = decode::ab16_inter_hits_by_arm(); - let frames = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \ - attempt {attempt}): {msg}" - ); - named_refusals += 1; - eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}"); - continue; - } - Ok(frames) => frames, - }; - let after = decode::ab16_inter_hits_by_arm(); - let fired: Vec = (0..4).map(|a| after[a] - before[a]).collect(); - let ffmpeg_frames = if bit_depth == 10 { - ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count) - } else { - ffmpeg_decode_sequence(&stream, width, height, frame_count) - }; - assert_eq!(frames.len(), frame_count); - let mismatched = frames - .iter() - .zip(&ffmpeg_frames) - .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); - if fired.iter().sum::() == 0 { - out_of_scope += 1; - if mismatched { - oos_mismatch += 1; - eprintln!( - "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \ - 16-level inter AB partition -- another shape's defect" - ); - } - continue; - } - if mismatched { - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - let bad: Vec = (0..got.y.len()) - .filter(|&k| got.y[k] != want.y[k]) - .collect(); - if !bad.is_empty() { - eprintln!( - "{NAME}: attempt {attempt} {bit_depth}-bit frame {i}: {} luma \ - pixels differ, first at ({}, {}), max |delta| {}", - bad.len(), - bad[0] % width, - bad[0] / width, - bad.iter() - .map(|&k| (got.y[k] as i32 - want.y[k] as i32).abs()) - .max() - .unwrap_or(0) - ); - } - } - } - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!( - got.y, want.y, - "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit, arms {fired:?})" - ); - assert_eq!( - got.u, want.u, - "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit, arms {fired:?})" - ); - assert_eq!( - got.v, want.v, - "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit, arms {fired:?})" - ); - } - for a in 0..4 { - if fired[a] > 0 { - arms_proved[a] += 1; - arms_total[a] += 1; - } - } - matched += 1; - } - eprintln!( - "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \ - attempts carrying a 16-level inter AB partition, per-arm attempts \ - HORZ_A/HORZ_B/VERT_A/VERT_B={arms_proved:?}, {out_of_scope} attempts carried \ - none ({oos_mismatch} of them mismatched)" - ); - assert_eq!( - oos_mismatch, 0, - "{NAME}: {oos_mismatch} attempt(s) with no 16-level inter AB partition decoded \ - but mismatched ffmpeg -- a defect of another shape, not a pass" - ); - } - assert!( - arms_total.iter().all(|&n| n > 0), - "{NAME}: not every 16-level inter AB arm fired on a pixel-exact attempt \ - (HORZ_A/HORZ_B/VERT_A/VERT_B={arms_total:?}) -- the unfired arm(s) are unproven" - ); - } - - #[test] - // lane-inter16ab r2: the 16x16-level 1:4 partitions on an INTER frame -- - // PARTITION_HORZ_A/_HORZ_B/_VERT_A/_VERT_B at 16x16, i.e. two 8x8 inter - // leaves plus one true 16x8/8x16 inter strip. Every decode-order frame is - // compared Y/U/V against ffmpeg, refusals are counted and never SKIPped, - // out-of-scope mismatches fail the gate, and EACH of the four arms must - // have fired on a pixel-exact attempt (RD picking only HORZ_A is not - // proof of four). `--min-partition-size=4` is what lets aomenc's RD reach - // `PARTITION_HORZ_4`/`_VERT_4` at BLOCK_16X16 (16x4 / 4x16 inter strips); - // the last two counters are the chroma half of the claim -- the odd - // strip's `is_chroma_reference` pair and the pairs whose chroma was built - // from two different strips' motion vectors - // (`build_inter_predictors_sub8x8`). - fn a_real_aomenc_inter_sequence_with_16x16_level_1to4_partitions_decodes_pixel_exact() { - const NAME: &str = - "a_real_aomenc_inter_sequence_with_16x16_level_1to4_partitions_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height, frame_count) = (192usize, 128usize, 6usize); - // Per arm, over both bit depths: how many pixel-exact attempts fired - // it at least once. - let mut arms_total = [0u32; 5]; - // lane-inter16ab r5: attempts refused on "a non-skip rectangular - // (HORZ/VERT/HORZ_B) strip needs rectangular residual coding". - let mut rect_residual_refusals = 0u32; - for bit_depth in [8u32, 10u32] { - let (mut named_refusals, mut matched, mut out_of_scope, mut oos_mismatch) = - (0u32, 0u32, 0u32, 0u32); - let mut arms_proved = [0u32; 5]; - // lane-inter16ab r4: a 4-recipe widening (fine `sin(X/3)` stripes - // at cq 8..14, both depths) was measured and REMOVED again -- every - // extra 1:4 partition it produced is in the KEY frame, and this - // gate's arms count INTER-frame strips. Frame-aware histogram - // script + table in lanes/inter16ab-r4.report.md; the only recipe - // in the whole sweep with an inter-frame `PARTITION_VERT_4` is - // attempt 1's, which refuses on the rect wedge-interintra mask. - for attempt in 0..32u32 { - // Two sources (structure along X vs along Y -- an AB - // partition needs an L/T-shaped feature, so both orientations - // are swept), four quantisers, two motion steps, two tiling - // arms. r1 measured (sweep script in the report): a 16-attempt - // sweep at cq 34/22 alone never made aomenc's RD pick HORZ_A - // at 8 bits, so the quantiser axis is four wide here; cq 46 on - // the X-structured source is deliberately NOT in the list -- - // that stream's decode-order frame 4 desyncs on a defect this - // lane does not own (aomdec's own EC_PART trace reads ZERO - // AB partitions at BLOCK_16X16 anywhere in it, so the AB - // counters it raises are read out of an already-diverged - // stream; see lanes/inter16ab-r1.report.md). - let tx_search = if attempt % 2 == 0 { "0" } else { "1" }; - // The 10-bit arm swaps cq 40 for 28 on the same sources: at - // cq 40 the X-structured 10-bit stream mismatches ffmpeg with - // ZERO 16-level AB partitions in it (another shape's defect, - // measured r1 -- the gate's own `oos_mismatch` counter is - // what found it, and it is reported, not silenced). - let cq = if bit_depth == 10 { - [18, 22, 34, 28][(attempt / 2 % 4) as usize] - } else { - [18, 22, 34, 40][(attempt / 2 % 4) as usize] - }; - let natural = attempt / 8 % 2 == 1; - let group = attempt / 16; - // r1: a `--tile-columns=1` arm of this same sweep PANICS in - // `mc::from_switchable_symbol` (a 4th symbol out of a - // 3-symbol alphabet = someone else's desync, the signature - // the ledger already pins for the below-8x8 inter leaf), not - // in anything this lane added -- so the tiled arm is left out - // rather than turned into a SKIP or a weakened assert. - // Reported as residue in lanes/inter16ab-r1.report.md. - let tile_cols = "0"; - let sp = 3 + (group % 2) * 5; - let duration = frame_count as f64 / 25.0; - // Continuous-tone translating texture with a second, coarser - // component on the cross axis: aomenc's RD picks an AB - // partition where one 16x16 quadrant differs from its three - // siblings, which the two sinusoids at different periods - // produce all over the frame. - let lum = if natural { - format!("128+58*sin((Y+N*{sp})/6)+40*sin(X/11)+20*sin((X+Y)/5)") - } else { - format!("128+58*sin((X+N*{sp})/6)+40*sin(Y/11)+20*sin((X-Y)/5)") - }; - let source = format!( - "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\ - geq=lum='{lum}',format=yuv420p" - ); - let pix_fmt = if bit_depth == 10 { - "yuv420p10le" - } else { - "yuv420p" - }; - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-t", - &duration.to_string(), - "-pix_fmt", - pix_fmt, - "-strict", - "-1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let cq_arg = format!("--cq-level={cq}"); - let depth_arg = format!("--bit-depth={bit_depth}"); - let input_depth_arg = format!("--input-bit-depth={bit_depth}"); - let tx_arg = format!("--enable-tx-size-search={tx_search}"); - let tile_arg = format!("--tile-columns={tile_cols}"); - let args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - &cq_arg, - "--cpu-used=0", - "--threads=1", - "--row-mt=0", - "--sb-size=64", - &depth_arg, - &input_depth_arg, - "--enable-restoration=0", - "--enable-palette=0", - "--deltaq-mode=0", - "--enable-filter-intra=0", - "--enable-cfl-intra=0", - "--enable-intrabc=0", - "--lag-in-frames=0", - "--kf-max-dist=9999", - &tile_arg, - // Per-arm overrides go LAST: aomenc keeps the last - // occurrence of a repeated --enable-* flag. - &tx_arg, - "--enable-rect-partitions=1", - "--enable-ab-partitions=1", - "--enable-1to4-partitions=1", - "--min-partition-size=4", - "--max-partition-size=16", - "--obu", - "-o", - "-", - "-", - ]; - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let before = decode::inter16_rect4_counters(); - let leaf4_before = crate::stream::vartx_rect_leaf4_hits(); - let frames = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \ - attempt {attempt}): {msg}" - ); - // lane-inter16ab r5: attempt 1 is the ONLY recipe in - // r4's 100+ stream frame-aware sweep with an - // inter-frame PARTITION_VERT_4. In r4 it refused on - // the rect wedge codebook (lifted this round); it now - // walks further and stops on rect RESIDUAL coding, a - // refusal this lane does not own -- tracked so the - // VERT_4 / split-tx arms can name their blocker - // instead of silently reading 0. - if msg.contains("needs rectangular residual coding") { - rect_residual_refusals += 1; - } - named_refusals += 1; - eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}"); - continue; - } - Ok(frames) => frames, - }; - let after = decode::inter16_rect4_counters(); - let leaf4_after = crate::stream::vartx_rect_leaf4_hits(); - // [16x4 strips, 4x16 strips, chroma pairs closed, chroma - // pairs built from two strips' motion vectors]. - let fired = [ - after.0 - before.0, - after.1 - before.1, - after.2 - before.2, - after.3 - before.3, - // lane-inter16ab r4: the SPLIT-transform arm -- - // `sub_tx_size_map[TX_16X4] == TX_8X4`, so a 1:4 strip - // that splits its transform codes 8x4/4x8 RECTANGULAR - // var-tx leaves (`--enable-tx-size-search=1`). - (leaf4_after[0] - leaf4_before[0]) + (leaf4_after[1] - leaf4_before[1]), - ]; - let ffmpeg_frames = if bit_depth == 10 { - ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count) - } else { - ffmpeg_decode_sequence(&stream, width, height, frame_count) - }; - assert_eq!(frames.len(), frame_count); - let mismatched = frames - .iter() - .zip(&ffmpeg_frames) - .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); - if fired[0] + fired[1] == 0 { - out_of_scope += 1; - if mismatched { - oos_mismatch += 1; - eprintln!( - "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \ - 16-level inter AB partition -- another shape's defect" - ); - } - continue; - } - if mismatched { - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - let bad: Vec = (0..got.y.len()) - .filter(|&k| got.y[k] != want.y[k]) - .collect(); - if !bad.is_empty() { - eprintln!( - "{NAME}: attempt {attempt} {bit_depth}-bit frame {i}: {} luma \ - pixels differ, first at ({}, {}), max |delta| {}", - bad.len(), - bad[0] % width, - bad[0] / width, - bad.iter() - .map(|&k| (got.y[k] as i32 - want.y[k] as i32).abs()) - .max() - .unwrap_or(0) - ); - } - } - } - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!( - got.y, want.y, - "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit, arms {fired:?})" - ); - assert_eq!( - got.u, want.u, - "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit, arms {fired:?})" - ); - assert_eq!( - got.v, want.v, - "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit, arms {fired:?})" - ); - } - for a in 0..5 { - if fired[a] > 0 { - arms_proved[a] += 1; - arms_total[a] += 1; - } - } - matched += 1; - } - eprintln!( - "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \ - attempts carrying a 16-level inter 1:4 partition, per-arm attempts \ - HORZ_4/VERT_4/chroma-pair/sub8x8-chroma/split-tx-8x4={arms_proved:?}, {out_of_scope} attempts carried \ - none ({oos_mismatch} of them mismatched)" - ); - assert_eq!( - oos_mismatch, 0, - "{NAME}: {oos_mismatch} attempt(s) with no 16-level inter 1:4 partition decoded \ - but mismatched ffmpeg -- a defect of another shape, not a pass" - ); - } - // lane-t900 r36 (class [[gate-blind-to-feature]]): this counter was - // incremented and never read. What it was there to prove is that the - // VERT_4 / split-tx arms' blocker is still the rect-residual refusal. - // It no longer is: `decode.rs`'s "a non-skip rectangular - // (HORZ/VERT/HORZ_B) strip needs rectangular residual coding" still - // exists but is narrowed (lane-rectres + lane-inter4 + - // lane-intrarect), and this sweep now reaches it ZERO times at either - // depth -- attempt 1, the one recipe r5 recorded stopping there, - // decodes. So the counter is reported and pinned at 0: a non-zero - // reading means the refusal came back for this shape. - eprintln!("{NAME}: rect-residual refusals over both depths: {rect_residual_refusals}"); - assert_eq!( - rect_residual_refusals, 0, - "{NAME}: {rect_residual_refusals} attempt(s) stopped on \"a non-skip rectangular \ - (HORZ/VERT/HORZ_B) strip needs rectangular residual coding\" -- that refusal was \ - lifted for this shape and must not block the VERT_4 / split-tx arms again" - ); - // Arms 1/3/4 (HORZ_4, the odd-strip `is_chroma_reference` pair, the - // `build_inter_predictors_sub8x8` two-mv chroma build) are proven - // outright. - for (a, what) in [ - (0usize, "HORZ_4 16x4 strips"), - (2, "odd-strip chroma pairs"), - (3, "sub8x8 two-mv chroma pairs"), - ] { - assert!( - arms_total[a] > 0, - "{NAME}: arm {a} ({what}) never fired on a pixel-exact attempt \ - (HORZ_4/VERT_4/chroma-pairs/sub8x8-chroma-pairs/split-tx-8x4={arms_total:?})" - ); - } - // lane-inter16ab r5, MEASURED reason for the other two arms: the only - // recipe in r4's 100+ stream frame-aware sweep carrying an - // inter-frame `PARTITION_VERT_4` is attempt 1, and in r4 it refused on - // the rect wedge-interintra codebook. That refusal is LIFTED this - // round -- the stream now walks past it and stops on "a non-skip - // rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual - // coding", a refusal this lane does not own. VERT_4 (and with it the - // split-transform 8x4 leaf it feeds) is blocked on THAT, and the gate - // asserts exactly that -- if rect residual coding lands and the arms - // still read 0, or the blocker changes, this fails. - assert!( - arms_total[1] > 0, - "{NAME}: the VERT_4 arm read 0 \ - (HORZ_4/VERT_4/chroma-pairs/sub8x8-chroma-pairs/split-tx-8x4={arms_total:?})" - ); - // lane-gaterecipe r1 -- the split-transform arm (index 4) is NOT - // asserted, and this is the measured reason, not a weakening. Its old - // escape hatch was "some attempt refused on rectangular residual - // coding"; lane-rectres lifted that refusal, so the hatch closed and - // the arm read 0. A ~40-recipe sweep (192x128 and 384x256, cq 8..50, - // min-partition-size 4/8/16, both source orientations; script and - // table in lanes/gaterecipe-r1.report.md) shows NO 192x128 recipe of - // this shape ever makes aomenc split a 16x4/4x16 strip's transform -- - // an aomdec EC_TRACE_COEFF histogram of those streams carries whole - // TX_16X4/TX_4X16 units and no sub-transform. The one recipe that DOES - // split it (384x256 product texture, cq 10, --min-partition-size=8) - // was RE-MEASURED by lane-vartxsplit r2 on the merged tree: that - // stream now decodes PIXEL-EXACT on all six frames and fires ZERO - // rectangular var-tx leaves of any size -- the "6 split-tx 8x4 leaves" - // were counted out of an already-desynced decode (the desync is what - // lane-sub8x4 fixed). r2 also swept THIS gate's own source family at - // cq 46/56/63 (12 streams, both orientations, both motion steps, - // --min-partition-size=4 --enable-tx-size-search=1): zero - // TX_16X4/TX_4X16 split symbols in aomdec's EC_VARTX histogram, all 12 - // pixel-exact. What does split a 16x4/4x16 transform is the product - // texture at --min-partition-size=4 (140 + 238 splits at cq 44), and - // every such stream either stops at a refusal our own desync raises or - // mismatches ffmpeg from decode-order frame 1 -- an open defect handed - // off in lanes/vartxsplit-r2.report.md. So the arm stays - // reported-unproven instead of asserted on a stream nobody has decoded - // exactly. - eprintln!( - "{NAME}: split-tx-8x4 arm unproven (arms {arms_total:?}) -- no recipe of this \ - sweep produces a split 16x4/4x16 transform; see lanes/gaterecipe-r1.report.md" - ); - } - - #[test] - // Un-ignored 2026-09-04: the intra 16x4/4x16-in-inter refusal this recipe stopped at is gone and every arm now decodes pixel-exact. - // lane-intra16x4 r1: an INTRA-coded 16x4 / 4x16 strip inside an INTER - // frame's 16x16-level 1:4 partition -- the wall all six of his film cuts - // stopped at once lane-rectres landed. The shape's chroma is the pair's: - // `is_chroma_reference` (av1_common_int.h:1454) is false on the even - // strips (which read no `uv_mode` and code no chroma at all) and the odd - // one codes ONE 8x4 (4x8) chroma unit at the pair's origin -- and when the - // pair mixes an intra and an inter strip, the chroma is predicted per the - // strip that CARRIES it, which is exactly what routing the intra strip - // through the key frame's own proven per-strip body - // (`decode_rect4_16_strip`) gives. - // - // Recipes found by a 24 + 24 run sweep (three sources x cq 16..63 x two - // sizes, `~/.cache/intra16x4-tmp/sweep*.sh`): aomenc only picks an INTRA - // 1:4 strip on an inter frame at HIGH cq over content its MC cannot - // predict -- a per-frame-random bright bar sweeping the frame (HORZ_4 - // strips) and a `X*Y` product sinusoid under temporal noise (VERT_4). - // Both sources hash identically twice (report). - fn a_real_aomenc_inter_sequence_with_intra_16x4_strips_in_1to4_partitions_decodes_pixel_exact() - { - const NAME: &str = "a_real_aomenc_inter_sequence_with_intra_16x4_strips_in_1to4_partitions_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let frame_count = 6usize; - // (source kind, cq, width, height) -- the four recipes of the 48-run - // sweep (`~/.cache/intra16x4-tmp/sweep*.sh`, table in the report) that - // reach an INTRA 1:4 strip on an inter frame. `bar` is a per-frame - // random bright bar sweeping the frame (its MC failure is what makes - // aomenc's RD pick intra at 16x4), `prod` an `X*Y` product sinusoid - // under temporal noise; `_v` transposes the structure so the RD picks - // PARTITION_VERT_4. - // lane-intra16x4 r2: the last field is `--min-partition-size` -- the - // `bar_h` recipe (a horizontal bar sweeping DOWN the frame) at - // `--min-partition-size=8` is the one recipe of the r2 96-run sweep - // (`~/.cache/intra16x4-tmp/sweep_r2.sh`) that fires intra 16x4 strips - // WITHOUT also carrying the sub-8x8 intra block another lane refuses, - // so it is the arm that can be pixel-compared at all. - const RECIPES: [(&str, u32, usize, usize, u32); 5] = [ - ("noise", 60, 128, 128, 4), - ("bar", 60, 192, 128, 4), - ("prod_v", 56, 128, 128, 4), - ("prod", 56, 160, 128, 4), - ("bar_h", 63, 192, 128, 8), - ]; - // [16x4 intra strips, 4x16 intra strips, of which chroma-reference]: - // how many pixel-exact attempts fired each, over both bit depths. - let mut arms_total = [0u32; 3]; - // Attempts that refused on the sub-8x8 intra block inside an inter - // frame -- a DIFFERENT lane's shape, and the measured blocker of every - // VERT_4-carrying recipe in the sweep. - let mut sub8_intra_refusals = 0u32; - // Every failure the sweep sees, asserted ONCE at the end. - let mut failures: Vec = Vec::new(); - // Per bit depth: attempts that decoded at all, and attempts that fired an - // intra 1:4 strip AND compared pixel-exact. - let mut decoded_per_depth = [0u32; 2]; - let mut fired_exact_per_depth = [0u32; 2]; - for (depth_idx, bit_depth) in [8u32, 10u32].into_iter().enumerate() { - let (mut named_refusals, mut matched, mut out_of_scope, mut oos_mismatch) = - (0u32, 0u32, 0u32, 0u32); - let mut arms_proved = [0u32; 3]; - for attempt in 0..RECIPES.len() as u32 { - let (kind, cq, width, height, min_part) = RECIPES[attempt as usize]; - let duration = frame_count as f64 / 25.0; - // Both sources are deterministic (two identical y4m hashes, - // report): `random()` here is geq's own indexed PRNG and the - // noise filter carries an explicit `all_seed`. - let (lum, noise) = match kind { - "noise" => ( - "128+58*sin((X+N*3)/6)+40*sin(Y/11)".to_string(), - ",noise=alls=40:allf=t+u:all_seed=7", - ), - "bar" => ( - format!( - "if(lt(mod(X+N*37,{width}),24),random(N*100+X+Y)*255,128+50*sin(Y/7))" - ), - "", - ), - "bar_h" => ( - format!( - "if(lt(mod(Y+N*37,{height}),24),random(N*100+X+Y)*255,128+50*sin(X/7))" - ), - "", - ), - "prod_v" => ( - "128+60*sin((X*Y+N*97)/13)+50*sin((Y+N*11)/5)".to_string(), - ",noise=alls=25:allf=t:all_seed=11", - ), - _ => ( - "128+60*sin((X*Y+N*97)/13)+50*sin((X+N*11)/5)".to_string(), - ",noise=alls=25:allf=t:all_seed=11", - ), - }; - let source = format!( - "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\ - geq=lum='{lum}',format=yuv420p{noise}" - ); - let pix_fmt = if bit_depth == 10 { - "yuv420p10le" - } else { - "yuv420p" - }; - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-t", - &duration.to_string(), - "-pix_fmt", - pix_fmt, - "-strict", - "-1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let cq_arg = format!("--cq-level={cq}"); - let min_part_arg = format!("--min-partition-size={min_part}"); - let depth_arg = format!("--bit-depth={bit_depth}"); - let input_depth_arg = format!("--input-bit-depth={bit_depth}"); - let args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - &cq_arg, - "--cpu-used=0", - "--threads=1", - "--row-mt=0", - "--sb-size=64", - &depth_arg, - &input_depth_arg, - "--enable-restoration=0", - "--enable-palette=0", - "--deltaq-mode=0", - "--enable-filter-intra=0", - "--enable-cfl-intra=0", - "--enable-intrabc=0", - "--lag-in-frames=0", - "--kf-max-dist=9999", - "--tile-columns=0", - // Per-arm overrides go LAST (aomenc keeps the last - // occurrence of a repeated --enable-* flag). - "--enable-tx-size-search=1", - "--enable-rect-partitions=1", - "--enable-ab-partitions=1", - "--enable-1to4-partitions=1", - "--enable-intra-edge-filter=1", - &min_part_arg, - "--max-partition-size=16", - "--obu", - "-o", - "-", - "-", - ]; - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let before = crate::stream::intra16x4_in_inter_hits(); - let frames = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - // lane-intra16x4 r3: the ONLY refusals the 120-run sweep - // (`~/.cache/intra16x4-tmp/sweep_r3.sh`, table in the - // report) reaches over these recipes -- each another - // lane's shape. A refusal outside this list is a new wall - // and fails the gate rather than being counted. - const MEASURED_REFUSALS: [&str; 3] = [ - "an intra 8x4/4x8 block inside an inter frame's sub-8x8 HORZ/VERT partition", - "an intra 4x4 block inside an inter frame's sub-8x8 split", - "an OBMC neighbour whose switchable interp filter was never recorded", - ]; - if !MEASURED_REFUSALS.iter().any(|r| msg.contains(r)) { - failures.push(format!( - "{bit_depth}-bit attempt {attempt}: refusal outside the measured \ - list: {msg}" - )); - continue; - } - if msg.contains("sub-8x8") { - sub8_intra_refusals += 1; - } - named_refusals += 1; - eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}"); - continue; - } - Ok(frames) => frames, - }; - decoded_per_depth[depth_idx] += 1; - let after = crate::stream::intra16x4_in_inter_hits(); - let fired = [ - (after.0 - before.0) as u32, - (after.1 - before.1) as u32, - (after.2 - before.2) as u32, - ]; - let ffmpeg_frames = if bit_depth == 10 { - ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count) - } else { - ffmpeg_decode_sequence(&stream, width, height, frame_count) - }; - assert_eq!(frames.len(), frame_count); - let mismatched = frames - .iter() - .zip(&ffmpeg_frames) - .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); - if fired[0] + fired[1] == 0 { - out_of_scope += 1; - if mismatched { - oos_mismatch += 1; - eprintln!( - "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \ - intra 1:4 strip -- another shape's defect" - ); - } - continue; - } - if mismatched { - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - let bad: Vec = (0..got.y.len()) - .filter(|&k| got.y[k] != want.y[k]) - .collect(); - if !bad.is_empty() { - eprintln!( - "{NAME}: attempt {attempt} {bit_depth}-bit frame {i}: {} luma \ - pixels differ, first at ({}, {}), max |delta| {}", - bad.len(), - bad[0] % width, - bad[0] / width, - bad.iter() - .map(|&k| (got.y[k] as i32 - want.y[k] as i32).abs()) - .max() - .unwrap_or(0) - ); - } - } - } - // lane-intra16x4 r3: continue-and-sweep -- a mismatching attempt is - // RECORDED and the sweep goes on, so one arm's defect can no longer - // hide every later arm (r2's attempt 0 panicked before arm 4 ran). - // The end-of-sweep assert below fails on any recorded mismatch. - if mismatched { - failures.push(format!( - "{bit_depth}-bit attempt {attempt} (arms {fired:?}) mismatched ffmpeg" - )); - continue; - } - for a in 0..3 { - if fired[a] > 0 { - arms_proved[a] += 1; - arms_total[a] += 1; - } - } - matched += 1; - fired_exact_per_depth[depth_idx] += 1; - } - eprintln!( - "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \ - attempts carrying an intra 1:4 strip, per-arm attempts \ - 16x4/4x16/chroma-reference={arms_proved:?}, {out_of_scope} attempts carried none \ - ({oos_mismatch} of them mismatched)" - ); - if oos_mismatch > 0 { - failures.push(format!( - "{bit_depth}-bit: {oos_mismatch} attempt(s) with no intra 1:4 strip decoded \ - but mismatched ffmpeg -- another shape's defect, not a pass" - )); - } - } - assert!( - failures.is_empty(), - "{NAME}: {} sweep failure(s): {failures:#?}", - failures.len() - ); - // The counter must have fired on a pixel-exact attempt at every bit depth - // the sweep actually decoded at. - for (depth_idx, bit_depth) in [8u32, 10u32].into_iter().enumerate() { - assert!( - decoded_per_depth[depth_idx] == 0 || fired_exact_per_depth[depth_idx] > 0, - "{NAME}: {bit_depth}-bit decoded {} attempt(s) but none of them fired an intra \ - 1:4 strip on a pixel-exact compare", - decoded_per_depth[depth_idx] - ); - } - // MEASURED (48-run sweep, report table): every recipe that makes - // aomenc pick an intra PARTITION_VERT_4 strip ALSO contains an intra - // 8x4/4x8 or 4x4 block inside a sub-8x8 partition, a refusal this lane - // does not own -- so the 4x16 orientation is blocked on THAT and the - // gate asserts exactly that. If the sub-8x8 lane lands and this arm - // still reads 0, or the blocker changes, this fails. - assert!( - arms_total[1] > 0 || sub8_intra_refusals > 0, - "{NAME}: the 4x16 (PARTITION_VERT_4) arm read 0 \ - (16x4/4x16/chroma-reference={arms_total:?}) and NO attempt refused on the sub-8x8 \ - intra block -- its documented blocker is gone, so a zero arm is now unexplained" - ); - for (a, what) in [ - (0usize, "intra 16x4 strips (PARTITION_HORZ_4)"), - ( - 2, - "chroma-reference (odd) intra strips carrying the pair's 8x4/4x8 chroma", - ), - ] { - assert!( - arms_total[a] > 0, - "{NAME}: arm {a} ({what}) never fired on a pixel-exact attempt \ - (16x4/4x16/chroma-reference={arms_total:?}) -- unproven" - ); - } - } - - #[test] - // lane-sbab r1: the SUPERBLOCK-level (64x64) AB partitions on an INTER - // frame -- PARTITION_HORZ_A/_HORZ_B/_VERT_A/_VERT_B at 64x64, i.e. two - // 32x32 inter squares plus one true 64x32/32x64 inter strip, decoded in - // libaom `decode_partition`'s visit order. Every decode-order frame is - // compared Y/U/V against ffmpeg, refusals are counted and never SKIPped, - // out-of-scope mismatches fail the gate, and EACH of the four arms must - // have fired on a pixel-exact attempt (RD picking only HORZ_A is not - // proof of four). `--min-partition-size=32` keeps every AB piece at or - // above 32x32, `--max-partition-size=64` puts the AB symbol at the SB - // root, and `--enable-1to4-partitions=0` because the 64-level 1:4 pair is - // a different lane's shape. - fn a_real_aomenc_inter_sequence_with_superblock_level_ab_partitions_decodes_pixel_exact() { - const NAME: &str = - "a_real_aomenc_inter_sequence_with_superblock_level_ab_partitions_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height, frame_count) = (256usize, 192usize, 6usize); - // Per arm, over both bit depths: how many pixel-exact attempts fired - // it at least once. - let mut arms_total = [0u32; 4]; - for bit_depth in [8u32, 10u32] { - let (mut named_refusals, mut matched, mut out_of_scope, mut oos_mismatch) = - (0u32, 0u32, 0u32, 0u32); - let mut arms_proved = [0u32; 4]; - for attempt in 0..20u32 { - // Axes measured live by the r1 sweep - // (~/.cache/sbab-tmp/sweep.sh, table in the report): two - // motion steps x two source orientations x five quantisers x - // a single-tile and a two-tile-column arm. All four arms - // appear in that table at both depths; no single (sp, shape, - // cq) point carries more than three of them, which is why the - // sweep is this wide. - let cq = [18, 26, 34, 45, 55][(attempt % 5) as usize]; - let natural = attempt / 5 % 2 == 1; - let sp = if attempt / 10 % 2 == 0 { 3 } else { 8 }; - // r1: a `--tile-columns=1` twin of these 20 attempts was run - // and is deliberately NOT in the gate -- its streams PANIC in - // `mc::from_switchable_symbol` (a 4th symbol out of a - // 3-symbol alphabet), the exact signature lane-inter16ab r1 - // recorded for its own tiled arm and which the ledger pins to - // the below-8x8 inter leaf, not to anything this lane - // touches. Recorded as open residue in - // lanes/sbab-r1.report.md rather than turned into a SKIP or a - // weakened assert. - let tile_cols = "0"; - let duration = frame_count as f64 / 25.0; - // Long-period continuous tone: the 64-level AB partitions - // need the L/T-shaped feature to span 32 px, so the sinusoid - // periods here are ~3x the 16-level gate's. - let lum = if natural { - format!("128+58*sin((Y+N*{sp})/17)+40*sin(X/29)+20*sin((X+Y)/13)") - } else { - format!("128+58*sin((X+N*{sp})/17)+40*sin(Y/29)+20*sin((X-Y)/13)") - }; - let source = format!( - "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\ - geq=lum='{lum}',format=yuv420p" - ); - let pix_fmt = if bit_depth == 10 { - "yuv420p10le" - } else { - "yuv420p" - }; - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-t", - &duration.to_string(), - "-pix_fmt", - pix_fmt, - "-strict", - "-1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let cq_arg = format!("--cq-level={cq}"); - let depth_arg = format!("--bit-depth={bit_depth}"); - let input_depth_arg = format!("--input-bit-depth={bit_depth}"); - let tile_arg = format!("--tile-columns={tile_cols}"); - let args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - &cq_arg, - "--cpu-used=0", - "--threads=1", - "--row-mt=0", - "--sb-size=64", - &depth_arg, - &input_depth_arg, - "--enable-restoration=0", - "--enable-palette=0", - "--deltaq-mode=0", - "--enable-filter-intra=0", - "--enable-cfl-intra=0", - "--enable-intrabc=0", - "--lag-in-frames=0", - "--kf-max-dist=9999", - &tile_arg, - // Per-arm overrides go LAST: aomenc keeps the last - // occurrence of a repeated --enable-* flag. - "--enable-rect-partitions=1", - "--enable-ab-partitions=1", - "--enable-1to4-partitions=0", - "--min-partition-size=32", - "--max-partition-size=64", - "--obu", - "-o", - "-", - "-", - ]; - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let before = decode::sb_ab_inter_hits_by_arm(); - let frames = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \ - attempt {attempt}): {msg}" - ); - named_refusals += 1; - eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}"); - continue; - } - Ok(frames) => frames, - }; - let after = decode::sb_ab_inter_hits_by_arm(); - let fired: Vec = (0..4).map(|a| after[a] - before[a]).collect(); - let ffmpeg_frames = if bit_depth == 10 { - ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count) - } else { - ffmpeg_decode_sequence(&stream, width, height, frame_count) - }; - assert_eq!(frames.len(), frame_count); - let mismatched = frames - .iter() - .zip(&ffmpeg_frames) - .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); - if fired.iter().sum::() == 0 { - out_of_scope += 1; - if mismatched { - oos_mismatch += 1; - eprintln!( - "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \ - 64-level inter AB partition -- another shape's defect" - ); - } - continue; - } - if mismatched { - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - let bad: Vec = (0..got.y.len()) - .filter(|&k| got.y[k] != want.y[k]) - .collect(); - if !bad.is_empty() { - eprintln!( - "{NAME}: attempt {attempt} {bit_depth}-bit frame {i}: {} luma \ - pixels differ, first at ({}, {}), max |delta| {}", - bad.len(), - bad[0] % width, - bad[0] / width, - bad.iter() - .map(|&k| (got.y[k] as i32 - want.y[k] as i32).abs()) - .max() - .unwrap_or(0) - ); - } - } - } - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!( - got.y, want.y, - "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit, arms {fired:?})" - ); - assert_eq!( - got.u, want.u, - "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit, arms {fired:?})" - ); - assert_eq!( - got.v, want.v, - "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit, arms {fired:?})" - ); - } - for a in 0..4 { - if fired[a] > 0 { - arms_proved[a] += 1; - arms_total[a] += 1; - } - } - matched += 1; - } - eprintln!( - "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \ - attempts carrying a 64-level inter AB partition, per-arm attempts \ - HORZ_A/HORZ_B/VERT_A/VERT_B={arms_proved:?}, {out_of_scope} attempts carried \ - none ({oos_mismatch} of them mismatched)" - ); - assert_eq!( - oos_mismatch, 0, - "{NAME}: {oos_mismatch} attempt(s) with no 64-level inter AB partition decoded \ - but mismatched ffmpeg -- a defect of another shape, not a pass" - ); - } - assert!( - arms_total.iter().all(|&n| n > 0), - "{NAME}: not every 64-level inter AB arm fired on a pixel-exact attempt \ - (HORZ_A/HORZ_B/VERT_A/VERT_B={arms_total:?}) -- the unfired arm(s) are unproven" - ); - } - - /// The inter-frame twin of - /// [`a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact`]: - /// deblocking left *on* at a crf high enough that libaom picks a nonzero - /// level, CDEF off, so a pixel mismatch can only come from the loop - /// filter -- and over a real 4-frame INTER sequence, not one key frame. - /// - /// lane-av1skipfix: the attempt-loop shape. The sweep walks cq and seed, - /// REQUIRES at least one attempt to decode, and hard-asserts - /// `decode::deblock_hits` on a pixel-compared attempt; a decode error on - /// every attempt is a hard failure carrying the refusal texts, never a - /// printed SKIP (class `gate-skips-on-its-own-failure`). MEASURED - /// 2026-09-29 on `a21f3680`: cq 55/45/35/63 all decode 4 frames - /// pixel-exact with 208/224/160/208 deblock edges. - #[test] - fn a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height, frame_count) = (64usize, 64usize, 4usize); - // Two seeds x four quantisers. - const CQS: [u32; 4] = [55, 45, 35, 63]; - let mut refusals = Vec::new(); - let mut counted_exact = 0u32; - let mut uncounted_exact = 0u32; - 'attempts: for round in 0..2u32 { - for cq in CQS { - let source = gradients_source(42 + round, width, height, "duration=0.16:rate=25"); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args(["-v", "error", "-f", "lavfi", "-i"]) - .arg(&source) - .args(["-pix_fmt", "yuv420p", "-f", "yuv4mpegpipe", "-"]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "{NAME}: ffmpeg fixture (seed {} cq {cq}): {}", - 42 + round, - String::from_utf8_lossy(&y4m.stderr) - ); - let cq_arg = format!("--cq-level={cq}"); - let out = run_with_stdin( - Command::new(aomenc_path()).args([ - // lane-defon r1: explicit on-value (aomenc keeps the FIRST - // occurrence, so overrides go before the base list). - "--loopfilter-control=1", - "--codec=av1", - "--passes=1", - "--end-usage=q", - &cq_arg, - "--cpu-used=0", - "--lag-in-frames=0", - "--auto-alt-ref=0", - "--kf-max-dist=1000", - // Forces `primary_ref_frame = PRIMARY_REF_NONE` on every - // frame (spec 5.9.2): without it a real encoder's inter - // frame loads its initial CDF state from the previous - // frame's *adapted* tables (spec 7.20's `load_cdfs`), which - // this decoder never does -- it always starts each frame's - // `Cdfs` from the spec defaults (`decode.rs`'s - // `Cdfs::new(q_ctx)`, called fresh per frame in - // `decode_stream`). Without this flag the inter frame's - // very first symbol desyncs immediately (traced 2026-08-27: - // no coefficient trace at all before the tile's first - // partition read comes back an out-of-alphabet value). A - // real decoder needs cross-frame CDF forwarding to handle - // that stream; this fixture sidesteps it the same way a - // real broadcast/low-latency encode legitimately can. - "--error-resilient=1", - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-tx-size-search=0", - "--enable-cdef=0", - // Loop restoration is a named refusal (aomenc's RD picks - // Sgrproj on this kind of content) -- off in every recipe - // whose test targets a different surface. - "--enable-restoration=0", - "--max-partition-size=32", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack; - // leaving it on silently desyncs symbols on inter frames (grainfix lesson). - "--enable-ref-frame-mvs=0", - "--obu", - "-o", - "-", - "-", - ]), - &y4m.stdout, - ); - assert!( - out.status.success(), - "{NAME}: aomenc refused the seed {} cq {cq} fixture: {}", - 42 + round, - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - if let Ok(dump) = std::env::var("EC_AV1_GATE_DUMP") { - std::fs::write(dump, &stream).expect("dump stream"); - } - let before = decode::deblock_hits(); - let frames = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => { - refusals.push(format!("seed {} cq {cq}: {e}", 42 + round)); - continue; - } - }; - // A decode that succeeded is ALWAYS pixel-compared; the hit - // counter only decides whether the attempt counts as firing - // (class `counter-from-refused-stream`). - let counted = decode::deblock_hits() != before; - if counted { - counted_exact += 1; - } else { - uncounted_exact += 1; - } - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count); - assert_eq!(frames.len(), frame_count); - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - // gradients' colors ignore its seed, so this gate encodes fresh - // content every run -- a mismatch here may never reproduce. - // Self-pin the stream before panicking so the failure is - // bisectable (replay: EC_AV1_PIN on scratch_isolate_pinned_mismatch). - let ok = got.y == want.y && got.u == want.u && got.v == want.v; - if !ok { - let pin = std::env::temp_dir().join(format!( - "ec-av1-deblocking-gate-fail-s{}-cq{cq}.obu", - 42 + round - )); - crate::dumpio::pin("TEST_PIN", &pin, &stream); - panic!( - "frame {i} mismatch vs ffmpeg (seed {} cq {cq}, deblock fired: \ - {counted}) -- stream pinned at {}", - 42 + round, - pin.display() - ); - } - } - if counted_exact >= 2 { - break 'attempts; - } - } - } - gate_buckets(NAME, counted_exact, uncounted_exact, refusals.len()); - assert!( - counted_exact > 0, - "{NAME}: none of {} attempts decoded a sequence with a deblocking edge -- \ - apply_deblock is unproven (class gate-blind-to-feature):\n{}", - CQS.len() * 2, - refusals.join("\n") - ); - } - - /// The decisive cross-frame CDF forwarding test: identical to - /// [`a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact`] - /// except it drops `--error-resilient=1`, so aomenc codes every inter - /// frame's `primary_ref_frame` at its default (not `PRIMARY_REF_NONE`) - /// and expects the decoder to resume from the previous frame's *adapted* - /// CDF state (spec 7.20 `load_cdfs`). Without cross-frame forwarding, - /// frame 1's very first tile symbol desyncs (an out-of-alphabet - /// partition read); with it, every frame decodes pixel-exact. - #[test] - fn a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact() { - if !have_ffmpeg() { - eprintln!( - "SKIP a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact: no ffmpeg" - ); - return; - } - if !have_aomenc() { - eprintln!( - "SKIP a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact: no aomenc at {}", - aomenc_path().display() - ); - return; - } - let (width, height, frame_count) = (64usize, 64usize, 4usize); - // The fixture's content varies run to run (lavfi gradients ignores its - // seed option for the c0..c7 colors -- they default to "random"), so: - // most encodes of this recipe trip one of the decoder's NAMED round-2 - // refusals (a reference other than LAST_FRAME, a sub-16 partition -- - // genuine coverage gaps, separately documented), and only some produce - // a stream fully inside this decoder's declared support. So: attempt - // several seeds, and the first stream that DECODES must be pixel-exact - // -- that assertion is what guards the forwarded-CDF state (a wrong - // table decodes plausible-but-wrong pixels; the counter-reset bug this - // gate caught did exactly that). Exhausting every attempt on named - // refusals skips loudly, listing them. - let mut refusals = Vec::new(); - for attempt in 0..8u32 { - let seed = 42 + attempt; - let source = gradients_source(seed, 64, 64, "duration=0.16:rate=25"); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-pix_fmt", - "yuv420p", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - // lane-cdfflake: hard length check on the y4m fixture itself -- - // a truncated/racing ffmpeg write would otherwise surface as a - // downstream pixel mismatch indistinguishable from a real decode - // defect. y4m frames are `FRAME\n` (6 bytes) + raw 4:2:0 payload; - // find the header/frame-data boundary at the first `FRAME` marker - // rather than parsing the header fields (duration/rate can move - // the header text length without moving the frame math). - let marker_at = y4m - .stdout - .windows(5) - .position(|w| w == b"FRAME") - .expect("y4m stream missing FRAME marker"); - let frame_420_bytes = width * height * 3 / 2; - assert_eq!( - y4m.stdout.len(), - marker_at + frame_count * (6 + frame_420_bytes), - "y4m fixture length mismatch (seed {seed})" - ); - let y4m_hash = fnv1a64(&y4m.stdout); - let out = run_with_stdin( - Command::new(aomenc_path()).args([ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=55", - "--cpu-used=0", - "--lag-in-frames=0", - "--auto-alt-ref=0", - "--kf-max-dist=1000", - // `--threads=1` (not the default): a multithreaded RD search - // makes aomenc's screen-content-tools heuristic race (seen - // flaky under `cargo test`'s own parallelism -- the same - // fixture, same seed, occasionally sets - // `allow_screen_content_tools`, a round-2 gap unrelated to - // CDF forwarding), so pin it to one thread for a - // deterministic header. - "--threads=1", - "--row-mt=0", - // `--enable-order-hint=0` kills BWDREF/ALTREF entirely (no - // order hints -> no bidirectional distance weighting) and, - // combined with `--auto-alt-ref=0`/`--lag-in-frames=0` - // above, leaves aomenc's RD search only LAST_FRAME/ - // LAST2_FRAME/LAST3_FRAME/GOLDEN_FRAME to pick from -- - // GOLDEN itself needs no order hint (it is the keyframe's - // fixed slot, not a distance-weighted reference), so this - // does not suppress GOLDEN selection the way the sibling - // CDF-forwarding gate's own comment worried about; it just - // narrows the pool this gate needs GOLDEN to win out of. - "--enable-order-hint=0", - "--enable-warped-motion=0", - "--enable-obmc=0", - "--enable-masked-comp=0", - "--enable-interintra-comp=0", - "--enable-dist-wtd-comp=0", - "--enable-diff-wtd-comp=0", - "--enable-onesided-comp=0", - "--enable-interintra-wedge=0", - "--enable-smooth-interintra=0", - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-tx-size-search=0", - "--enable-cdef=0", - // Loop restoration is a named refusal (aomenc's RD picks - // Sgrproj on this kind of content) -- off in every recipe - // whose test targets a different surface. - "--enable-restoration=0", - "--max-partition-size=32", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack; - // leaving it on silently desyncs symbols on inter frames (grainfix lesson). - "--enable-ref-frame-mvs=0", - "--obu", - "-o", - "-", - "-", - ]), - &y4m.stdout, - ); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let stream_hash = fnv1a64(&stream); - // A named `unsupported` refusal is a documented coverage gap (each - // one carries its own test debt elsewhere), not a forwarding verdict - // -- try the next seed. Any stream that DECODES must be pixel-exact, - // and any non-refusal error is a hard failure. - let frames = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "cross-frame CDF forwarding failed outright (seed {seed}): {msg}" - ); - refusals.push(format!("seed {seed}: {msg}")); - continue; - } - Ok(frames) => frames, - }; - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count); - assert_eq!(frames.len(), frame_count); - // lane-cdfflake: reconstruct ffmpeg's raw reference bytes (the - // three per-frame slices are contiguous chunks of the raw - // `-f rawvideo` output ffmpeg_decode_sequence sliced, so - // concatenating them back is bit-for-bit the same bytes ffmpeg - // actually produced -- no second ffmpeg invocation needed). - let ffmpeg_raw: Vec = ffmpeg_frames - .iter() - .flat_map(|p| p.y.iter().chain(&p.u).chain(&p.v).map(|&v| v as u8)) - .collect(); - let ffmpeg_raw_hash = fnv1a64(&ffmpeg_raw); - eprintln!( - "cdfflake attempt seed={seed}: y4m_hash={y4m_hash:016x} \ - stream_hash={stream_hash:016x} ffmpeg_raw_hash={ffmpeg_raw_hash:016x}" - ); - // lane-av1golden3: pin the exact raw stream on the first mismatch - // so a flaky-looking gate failure becomes a deterministic, static - // fixture to bisect against -- env-gated, no cost on a normal run. - let mismatched = frames - .iter() - .zip(&ffmpeg_frames) - .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); - if mismatched { - if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") { - std::fs::write(&path, &stream).expect("writing pinned stream"); - eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}"); - } - // lane-cdfflake: unconditional pin on mismatch -- the aomenc - // stream AND ffmpeg's raw reference bytes, so a flake caught - // under load names the liar (stream bytes differ from a - // clean rerun -> subprocess instability; reference bytes - // differ -> ffmpeg instability; both stable -> real decode - // defect) without relying on the env var being set. - // The pin goes to `fixtures/`, which outlives the session: an - // earlier version wrote to a session scratchpad, so once tmpfs - // reaped it a real mismatch aborted on the write instead of - // reporting itself. A failed write must not mask the asserts - // below either, so it warns rather than panicking -- lane-av1pinloud - // routed it through `pin_reporting` rather than bare `fs::write`, - // so the warning now carries on-disk-vs-owed byte counts: a - // truncated pin was as silent here as anywhere else, and this - // is the one site where dying on the write is wrong. - let sp = pin_dir(); - let stream_pin = sp.join(format!("cdfflake-stream-seed{seed}.bin")); - let ref_pin = sp.join(format!("cdfflake-ffmpeg-raw-seed{seed}.bin")); - for (path, bytes) in [(&stream_pin, &stream), (&ref_pin, &ffmpeg_raw)] { - if let Err(line) = crate::dumpio::pin_reporting("TEST_PIN", path, bytes) { - eprintln!("cdfflake: {line}"); - } - } - eprintln!( - "cdfflake MISMATCH seed={seed}: pinned stream + ffmpeg reference to {}", - sp.display() - ); - } - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})"); - assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})"); - assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})"); - } - return; - } - eprintln!( - "SKIP a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact: every \ - attempt hit a named refusal:\n{}", - refusals.join("\n") - ); - } - - /// lane-av1golden3: reproduces the pinned mismatch bytes captured by - /// `EC_AV1_GATE_DUMP=$SP/golden3-pin.obu` off - /// [`a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact`] - /// (seed 47, frame 1 U). Deterministic and static -- no aomenc/ffmpeg - /// re-encode involved, only re-decodes fixed bytes on disk. What changed - /// under lane-av1pinslive is that the gate is LIVE: the bytes are committed - /// at `crates/ec-av1/fixtures/golden3-pin.obu` instead of a scratchpad that - /// tmpfs reaps, so it runs in the ordinary suite on any runner that has - /// ffmpeg (guarded by `have_ffmpeg()`, so `EC_AV1_REQUIRE_FFMPEG=1` turns - /// its absence into a hard failure rather than a silent skip). It costs - /// ~0.15 s, touches no process-global, and reads no counter -- none of the - /// conditions that make this crate ignore its other manual gates. - /// - /// The original capture (2026-08-28, `bec27414`) is NOT reproducible: it - /// predates `5ae053d3` "route all 20 gradients gate fixtures through - /// seed-derived colours", so `gradients_source` still left c4..c7 to - /// ffmpeg's `random` default then. This is a FRESH capture from the same - /// recipe family at seed 42, which IS byte-reproducible now: the command is - /// in `lanes/av1pins.report.md`, and the stream's FNV-1a-64 - /// (`89c4089148d51c04`; 159 bytes; sha256 - /// `11c9d5331cffa6614c8265ad5fa685d5ce9155db8439949b48ec4a652ace95cf`) is - /// the `stream_hash` the live - /// `a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact` - /// prints for that seed -- which is what proves the recipe is that gate's. - #[test] - fn pinned_golden3_stream_decodes_pixel_exact() { - let path = std::env::var("EC_AV1_GATE_DUMP_PIN") - .map(std::path::PathBuf::from) - .unwrap_or_else(|_| crate_pin("golden3-pin.obu")); - let Ok(stream) = std::fs::read(&path) else { - eprintln!( - "SKIP pinned_golden3_stream_decodes_pixel_exact: no pinned bytes at {} \ - -- the committed copy is crates/ec-av1/fixtures/golden3-pin.obu", - path.display() - ); - return; - }; - if !have_ffmpeg() { - eprintln!("SKIP pinned_golden3_stream_decodes_pixel_exact: no ffmpeg"); - return; - } - let frames = decode_stream(&stream).expect("pinned stream must decode"); - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 64, 64, 4); - assert_eq!( - frames.len(), - ffmpeg_frames.len(), - "pinned stream decoded {} frames, ffmpeg {} -- a length mismatch would \ - make the zip below compare a mis-paired set", - frames.len(), - ffmpeg_frames.len() - ); - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (pinned)"); - assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (pinned)"); - assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (pinned)"); - } - eprintln!( - "pinned_golden3_stream_decodes_pixel_exact: {} frame(s) byte-exact vs ffmpeg \ - from {}", - frames.len(), - path.display() - ); - } - - /// lane-av1golden4: reproduces the pinned mismatch bytes captured by - /// `EC_AV1_GATE_DUMP=$SP/golden4-pin.obu` off - /// [`a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact`] - /// (seed 43, frame 3 luma) the round the GOLDEN mask lifted. Deterministic - /// and static. - /// - /// LIVE since lane-av1pinslive r3: the bytes are committed at - /// `crates/ec-av1/fixtures/golden4-pin.obu` (137 bytes; sha256 - /// `1754023e44e46edaebc2c05065bf1c65db1a41354577cbf71c0e8ebe737ae14a`, - /// recovered byte-for-byte from the runner library), so the old - /// "reads a pinned fixture path outside the repo" reason is false. Costs - /// ~0.10 s, touches no process-global, reads `non_last_ref_hits` for - /// diagnostic output only (never asserted), and calls no aomenc. - #[test] - fn pinned_golden4_stream_decodes_pixel_exact() { - use crate::decode::non_last_ref_hits; - let path = std::env::var("EC_AV1_GATE_DUMP_PIN") - .map(std::path::PathBuf::from) - .unwrap_or_else(|_| crate_pin("golden4-pin.obu")); - let stream = require_pin(&path, "golden4-pin.obu"); - if !have_ffmpeg() { - eprintln!("SKIP pinned_golden4_stream_decodes_pixel_exact: no ffmpeg"); - return; - } - let before = non_last_ref_hits(); - let frames = decode_stream(&stream).expect("pinned stream must decode"); - eprintln!( - "non_last_ref_hits before={before} after={}", - non_last_ref_hits() - ); - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 64, 64, 4); - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (pinned)"); - assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (pinned)"); - assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (pinned)"); - } - } - - /// lane-av1golden7 round 9: pins the residual GOLDEN_FRAME MC bug found - /// by the forwarding gate once film grain is out of the way (1/20 real - /// aomenc streams, frame 3 luma, apply_grain=false, `non_last_ref_hits` - /// delta=2). `GOLDEN_FRAME` refuses by name until this decodes exact. - /// - /// LIVE since lane-av1pinslive r3. The old shape was the worst of the - /// class: a `concat!(env!("CARGO_MANIFEST_DIR"), "/../../fixtures/...")` - /// literal, which points at the GITIGNORED root and can therefore never be - /// satisfied by a committed pin, combined with a bare `.expect()`. The - /// bytes are now committed at - /// `crates/ec-av1/fixtures/golden7-forwarding-mismatch.obu` (152 bytes; - /// sha256 `81b3bf657a85e95085287b30d97dee93ba5aea0ed1db1e1f4fcd19a06afc17be`, - /// recovered byte-for-byte from the runner library). - #[test] - fn pinned_golden7_stream_decodes_pixel_exact() { - use crate::decode::non_last_ref_hits; - let path = std::env::var("EC_AV1_GATE_DUMP_PIN") - .map(std::path::PathBuf::from) - .unwrap_or_else(|_| crate_pin("golden7-forwarding-mismatch.obu")); - let stream = require_pin(&path, "golden7-forwarding-mismatch.obu"); - if !have_ffmpeg() { - eprintln!("SKIP pinned_golden7_stream_decodes_pixel_exact: no ffmpeg"); - return; - } - let before = non_last_ref_hits(); - let frames = decode_stream(&stream).expect("pinned stream must decode"); - eprintln!( - "non_last_ref_hits before={before} after={}", - non_last_ref_hits() - ); - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 64, 64, 4); - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (pinned)"); - assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (pinned)"); - assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (pinned)"); - } - } - - /// lane-av1refs's decisive single-non-LAST-reference gate: identical - /// recipe to - /// [`a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact`] - /// except `--enable-order-hint=0` is DROPPED (that flag's own comment on - /// the sibling test names it as exactly what suppresses aomenc's RD from - /// ever picking `GOLDEN_FRAME`) and the sequence runs 8 frames, not 4 -- - /// more chances for the RD search to reach past the first GOP's initial - /// key frame. `--auto-alt-ref=0` stays: this decoder only supports - /// `LAST_FRAME`/`GOLDEN_FRAME` so far, and alt-ref/backward references - /// are still a named refusal, not this gate's target. A stream that - /// decodes without firing [`decode::non_last_ref_hits`] is not a - /// coverage win for this round -- SKIP it as a genuine, named miss - /// rather than pass silently on untested ground. - #[test] - fn a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact() { - if !have_ffmpeg() { - eprintln!( - "SKIP a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact: no ffmpeg" - ); - return; - } - if !have_aomenc() { - eprintln!( - "SKIP a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact: no aomenc at {}", - aomenc_path().display() - ); - return; - } - let (width, height, frame_count) = (64usize, 64usize, 8usize); - let mut refusals = Vec::new(); - let mut never_fired = 0u32; - // aomenc's own RD search is nondeterministic run-to-run even at - // `--threads=1` (confirmed live: identical CLI args, identical - // input, two different output byte streams) -- so beyond varying - // the fixture's seed, each attempt is its own independent coin - // flip against every named refusal below. 120 attempts (not 40) - // to give that coin flip enough tries to land on a stream this - // decoder both accepts and that fires GOLDEN_FRAME. `duration=0.32` - // at `rate=25` (not `0.24`) matches every sibling gate's own - // frame-count fixture exactly -- a shorter duration here once - // produced a frame-0 (keyframe, no reference at all) luma mismatch - // against ffmpeg, i.e. a source-frame-count rounding artifact of - // this recipe's own choosing, not a decoder bug. - for attempt in 0..120u32 { - let seed = 42 + attempt % 40; - let source = gradients_source(seed, 64, 64, "duration=0.32:rate=25"); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-pix_fmt", - "yuv420p", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let out = run_with_stdin( - Command::new(aomenc_path()).args([ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=55", - "--cpu-used=0", - "--lag-in-frames=0", - "--auto-alt-ref=0", - "--kf-max-dist=1000", - "--threads=1", - "--row-mt=0", - // Narrows the RD search's reference alphabet toward - // LAST_FRAME/GOLDEN_FRAME -- without this, aomenc's RD is - // just as likely to pick LAST2/LAST3/BWDREF/ALTREF2/ - // ALTREF (this decoder's already-documented, still-open - // refusals), starving this gate of the one reference it - // targets. - "--max-reference-frames=3", - "--reduced-reference-set=1", - "--enable-warped-motion=0", - "--enable-obmc=0", - "--enable-masked-comp=0", - "--enable-interintra-comp=0", - "--enable-dist-wtd-comp=0", - "--enable-diff-wtd-comp=0", - "--enable-onesided-comp=0", - "--enable-interintra-wedge=0", - "--enable-smooth-interintra=0", - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-tx-size-search=0", - "--enable-cdef=0", - "--enable-restoration=0", - // `min == max == 32` forces PARTITION_NONE for every - // 32x32 block, not just biases toward it -- with - // `--min-partition-size=16` alone aomenc's exhaustive - // `cpu-used=0` RD search still occasionally read HORZ/ - // VERT/SPLIT partitions below 32x32 despite - // `--enable-rect-partitions=0`/`--enable-ab-partitions=0`/ - // `--enable-1to4-partitions=0` all being off (two - // separate, already-documented round-2 gaps: "a - // partition below 16x16", "a partition type this encoder - // never writes"), starving this gate's already-narrow - // seed pool. Locking both bounds to 32 removes any - // partition-depth choice from the search entirely, so - // this gate can isolate GOLDEN_FRAME selection alone. - "--max-partition-size=32", - "--min-partition-size=32", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack; - // leaving it on silently desyncs symbols on inter frames (grainfix lesson). - "--enable-ref-frame-mvs=0", - // `--tune-content=film` was dropped: on this box it - // makes aomenc emit `apply_grain` almost every attempt - // (lane-av1golden8 round 10 measurement, live: 120/120 - // real attempts hit a named refusal, 0 ever fired - // GOLDEN_FRAME -- mostly `apply_grain`, dominated by its - // own recipe flag) -- film grain synthesis has its own - // dedicated refusal test and must not starve this gate - // of the GOLDEN_FRAME draws it exists to prove. Default - // content tuning still occasionally flips - // `allow_screen_content_tools` on for this synthetic - // gradient content (a separate, already-documented open - // refusal), which the 120-attempt coin flip below - // tolerates the same way. - "--obu", - "-o", - "-", - "-", - ]), - &y4m.stdout, - ); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let before = decode::non_last_ref_hits(); - let frames = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "a golden-reference stream failed outright (seed {seed}): {msg}" - ); - refusals.push(format!("seed {seed}: {msg}")); - continue; - } - Ok(frames) => frames, - }; - // class [[gate-skips-on-its-own-failure]]: a decode that succeeded - // is ALWAYS pixel-compared below; the hit counter only decides whether - // the attempt counts toward the firing total. - // This seed's RD search may never have picked GOLDEN_FRAME -- a - // genuine miss, not a refusal, and not a reason to skip the pixels. - let counted = decode::non_last_ref_hits() != before; - if !counted { - never_fired += 1; - } - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count); - assert_eq!(frames.len(), frame_count); - // Same pin-on-mismatch pattern as the CDF forwarding gate above: - // env-gated, no cost on a normal run. - let mismatched = frames - .iter() - .zip(&ffmpeg_frames) - .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); - if mismatched - && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") { - std::fs::write(&path, &stream).expect("writing pinned stream"); - eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}"); - } - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})"); - assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})"); - assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})"); - } - if counted { - eprintln!( - "FIRING seed {seed}: non_last_ref_hits advanced by {}", - decode::non_last_ref_hits() - before - ); - gate_buckets( - "a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact", - 1, - never_fired, - refusals.len(), - ); - return; - } - } - gate_buckets( - "a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact", - 0, - never_fired, - refusals.len(), - ); - eprintln!( - "SKIP a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact: \ - {never_fired} attempts decoded but never fired GOLDEN_FRAME, and every other \ - attempt hit a named refusal:\n{}", - refusals.join("\n") - ); - } - - /// lane-av1comp: proves `reference_select`/`comp_mode` are actually read - /// off a real bitstream rather than only unit-tested in isolation -- - /// `--auto-alt-ref=1 --lag-in-frames=16` gives aomenc a backward - /// reference to pick `COMPOUND_REFERENCE` with, `--enable-order-hint=1` - /// is required for it to ever consider compound at all. Three - /// acceptable outcomes: (a) a stream where `reference_select` never - /// actually drove a block to `COMPOUND_REFERENCE` decodes bit-exact end - /// to end (proving the per-block `comp_mode` read did not desync the - /// single-ref blocks around it); (b) a stream that does fire compound - /// is refused by name with [`decode::comp_mode_hits`] having advanced - /// (proving `comp_mode`/`read_compound_ref_frames` consumed the right - /// symbols before refusing, rather than desyncing and refusing for an - /// unrelated reason) -- masked/wedge compound (`comp_group_idx == 1`) - /// and a partition below 16x16 (a real, separately tracked capability - /// gap) are the two refusal arms this can still legitimately name; (c) - /// r13 wired plain `COMPOUND_AVERAGE` MC for real, so as of r15 a - /// stream that fires compound may also decode fully -- accepted only - /// when every output frame is pixel-exact against ffmpeg. - #[test] - fn a_real_aomenc_stream_with_reference_select_reads_comp_mode_correctly() { - const NAME: &str = "a_real_aomenc_stream_with_reference_select_reads_comp_mode_correctly"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height, frame_count) = (64usize, 64usize, 20usize); - let mut refusals = Vec::new(); - let mut never_fired = 0u32; - for attempt in 0..60u32 { - let seed = 42 + attempt % 40; - let duration = frame_count as f64 / 25.0; - let source = - gradients_source(seed, width, height, &format!("duration={duration}:rate=25")); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-pix_fmt", - "yuv420p", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=45", - "--cpu-used=0", - "--kf-max-dist=1000", - "--threads=1", - "--row-mt=0", - "--auto-alt-ref=1", - "--lag-in-frames=16", - "--enable-order-hint=1", - "--enable-warped-motion=0", - "--enable-obmc=0", - "--enable-masked-comp=0", - "--enable-interintra-comp=0", - "--enable-onesided-comp=0", - "--enable-interintra-wedge=0", - "--enable-smooth-interintra=0", - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-tx-size-search=0", - "--enable-cdef=0", - "--enable-restoration=0", - "--max-partition-size=32", - "--min-partition-size=32", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - "--enable-ref-frame-mvs=0", - "--obu", - "-o", - "-", - "-", - ]; - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let before = decode::comp_mode_hits(); - match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - let fired = decode::comp_mode_hits() > before; - assert!( - msg.contains("unsupported"), - "{NAME} failed outright (seed {seed}): {msg}" - ); - if fired { - // `comp_mode` firing does not stop the block walk -- - // a later, unrelated block in the same tile can - // still hit any other named refusal this decoder - // carries. A partition below 16x16 is a real, open - // capability gap tracked on its own (not a - // COMPOUND_REFERENCE defect); accept it here too - // rather than fail a compound-specific gate on a - // partition-search coincidence. lane-av1blend r7: - // re-swept the wide gate with the plain-average - // blend unmasked (r6/r7's ref_ctx fix alone) and it - // still mismatches on real streams beyond that one - // bug -- re-masked comp_group_idx == 0 too, so this - // stays a legal named refusal. - assert!( - msg.contains("COMPOUND_REFERENCE") || msg.contains("a partition"), - "{NAME}: comp_mode fired (seed {seed}) but the refusal \ - was for something else: {msg}" - ); - let advanced = decode::comp_mode_hits() - before; - eprintln!( - "{NAME} FIRING seed {seed}: comp_mode hits advanced by \ - {advanced}, refused by name as expected: {msg}" - ); - return; - } - refusals.push(format!("seed {seed}: {msg}")); - continue; - } - Ok(frames) => { - // class [[gate-skips-on-its-own-failure]]: a decode that - // succeeded is ALWAYS pixel-compared below; the hit counter - // only decides whether the attempt counts as firing. - let counted = decode::comp_mode_hits() != before; - if !counted { - never_fired += 1; - } - // Outcome (c): plain COMPOUND_AVERAGE decoded fully -- - // non-negotiable pixel exactness, no tolerance. - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count); - assert_eq!(frames.len(), frame_count); - let mismatched = frames - .iter() - .zip(&ffmpeg_frames) - .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); - if mismatched { - let pin = - std::env::temp_dir().join("ec-av1-reference-select-gate-fail.obu"); - crate::dumpio::pin("TEST_PIN", &pin, &stream); - if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") { - crate::dumpio::pin("EC_AV1_GATE_DUMP", &path, &stream); - eprintln!( - "EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}" - ); - } - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!( - got.y, - want.y, - "{NAME} frame {i} luma vs ffmpeg (seed {seed}) -- stream pinned at {}", - pin.display() - ); - assert_eq!( - got.u, - want.u, - "{NAME} frame {i} U vs ffmpeg (seed {seed}) -- stream pinned at {}", - pin.display() - ); - assert_eq!( - got.v, - want.v, - "{NAME} frame {i} V vs ffmpeg (seed {seed}) -- stream pinned at {}", - pin.display() - ); - } - } else { - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!( - got.y, want.y, - "{NAME} frame {i} luma vs ffmpeg (seed {seed})" - ); - assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})"); - assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})"); - } - } - // lane-hidden r2 (class gate-blind-to-hidden-frames): the same - // stream again, comparing EVERY decode-order frame -- the hidden - // (show_frame == 0) alt-ref frames the ffmpeg compare above - // cannot see, because both sides of it emit shown frames only. - let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME); - eprintln!( - "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \ - {hidden_n} hidden, all pixel-exact vs the oracle" - ); - // lane-hidden r2 SECOND ARM (the recipe above is untouched): - // libaom's temporal alt-ref filter absorbs this recipe's hidden - // frames, so the compare above is vacuous -- re-encode the same - // fixture with --arnr-maxframes=0 and compare THOSE. - if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) - { - eprintln!( - "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \ - decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle" - ); - } - if counted { - eprintln!( - "{NAME} FIRING seed {seed}: comp_mode hits advanced by {}, decoded \ - fully and pixel-exact", - decode::comp_mode_hits() - before - ); - gate_buckets(NAME, 1, never_fired, refusals.len()); - return; - } - } - } - } - gate_buckets(NAME, 0, never_fired, refusals.len()); - eprintln!( - "SKIP {NAME}: {never_fired} attempts decoded fully (reference_select never drove a \ - block to COMPOUND_REFERENCE) and every other attempt hit a named refusal that never \ - reached comp_mode:\n{}", - refusals.join("\n") - ); - } - - /// lane-av1comp round 14's decisive gate for `skip_mode`: same - /// pin-on-mismatch pattern as [`a_real_aomenc_single_ref_gate`], proving - /// [`decode::skip_mode_hits`] actually advanced (a real block picked - /// `skip_mode`, not just that the frame header bit was set) and that the - /// resulting forced-compound `NEAREST_NEARESTMV` decode is still - /// pixel-exact against ffmpeg. `--auto-alt-ref=1 --lag-in-frames=16 - /// --enable-fwd-kf=0` (backward references) plus - /// `--enable-ref-frame-mvs=0` (unimplemented temporal MV projection, - /// same as every other gate here) is aomenc's own requirement for - /// `skip_mode_present` to ever be considered at all (spec 5.9.22 needs - /// both a forward and a backward reference candidate). - #[test] - fn a_real_aomenc_stream_with_compound_references_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_stream_with_compound_references_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height, frame_count) = (64usize, 64usize, 24usize); - let mut refusals = Vec::new(); - let mut never_fired = 0u32; - for attempt in 0..80u32 { - let seed = 42 + attempt % 40; - let duration = frame_count as f64 / 25.0; - let source = - gradients_source(seed, width, height, &format!("duration={duration}:rate=25")); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-pix_fmt", - "yuv420p", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=45", - "--cpu-used=0", - "--kf-max-dist=1000", - "--threads=1", - "--row-mt=0", - "--auto-alt-ref=1", - "--lag-in-frames=16", - "--enable-fwd-kf=0", - "--enable-order-hint=1", - "--enable-warped-motion=0", - "--enable-obmc=0", - "--enable-masked-comp=0", - "--enable-interintra-comp=0", - "--enable-onesided-comp=0", - "--enable-interintra-wedge=0", - "--enable-smooth-interintra=0", - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-tx-size-search=0", - "--enable-cdef=0", - "--enable-restoration=0", - "--max-partition-size=32", - "--min-partition-size=32", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - "--enable-ref-frame-mvs=0", - "--obu", - "-o", - "-", - "-", - ]; - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let before = decode::skip_mode_hits(); - let frames = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME} failed outright (seed {seed}): {msg}" - ); - refusals.push(format!("seed {seed}: {msg}")); - continue; - } - Ok(frames) => frames, - }; - // class [[gate-skips-on-its-own-failure]]: a decode that succeeded - // is ALWAYS pixel-compared below; the hit counter only decides whether - // the attempt counts toward the firing total. - let counted = decode::skip_mode_hits() != before; - if !counted { - never_fired += 1; - } - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count); - assert_eq!(frames.len(), frame_count); - let mismatched = frames - .iter() - .zip(&ffmpeg_frames) - .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); - if mismatched { - let pin = std::env::temp_dir().join("ec-av1-compound-refs-gate-fail.obu"); - crate::dumpio::pin("TEST_PIN", &pin, &stream); - if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") { - crate::dumpio::pin("EC_AV1_GATE_DUMP", &path, &stream); - eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}"); - } - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!( - got.y, - want.y, - "{NAME} frame {i} luma vs ffmpeg (seed {seed}) -- stream pinned at {}", - pin.display() - ); - assert_eq!( - got.u, - want.u, - "{NAME} frame {i} U vs ffmpeg (seed {seed}) -- stream pinned at {}", - pin.display() - ); - assert_eq!( - got.v, - want.v, - "{NAME} frame {i} V vs ffmpeg (seed {seed}) -- stream pinned at {}", - pin.display() - ); - } - } - // lane-hidden r2 (class gate-blind-to-hidden-frames): the same - // stream again, comparing EVERY decode-order frame -- the hidden - // (show_frame == 0) alt-ref frames the ffmpeg compare above - // cannot see, because both sides of it emit shown frames only. - let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME); - eprintln!( - "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \ - {hidden_n} hidden, all pixel-exact vs the oracle" - ); - // lane-hidden r2 SECOND ARM (the recipe above is untouched): - // libaom's temporal alt-ref filter absorbs this recipe's hidden - // frames, so the compare above is vacuous -- re-encode the same - // fixture with --arnr-maxframes=0 and compare THOSE. - if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) { - eprintln!( - "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \ - decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle" - ); - } - if counted { - eprintln!( - "{NAME} FIRING seed {seed}: skip_mode hits advanced by {}", - decode::skip_mode_hits() - before - ); - gate_buckets(NAME, 1, never_fired, refusals.len()); - return; - } - } - gate_buckets(NAME, 0, never_fired, refusals.len()); - eprintln!( - "SKIP {NAME}: {never_fired} attempts decoded but never fired skip_mode, and every \ - other attempt hit a named refusal:\n{}", - refusals.join("\n") - ); - } - - /// lane-motionmode round 1: `--enable-obmc=1 --enable-warped-motion=0` - /// on the base recipe (`--auto-alt-ref=1 --lag-in-frames=16 - /// --enable-fwd-kf=0 --enable-ref-frame-mvs=0`) -- pixel-exact against - /// ffmpeg, gated on [`decode::obmc_hits`] actually advancing (a real - /// block picked `OBMC_CAUSAL`, not just that the header bit was set). - /// Structure copied from - /// `a_real_aomenc_stream_with_compound_references_decodes_pixel_exact`: - /// a seed sweep with a named-refusal escape hatch and an - /// `EC_AV1_GATE_DUMP` pin on mismatch. - #[test] - fn a_real_aomenc_stream_with_obmc_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_stream_with_obmc_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height, frame_count) = (64usize, 64usize, 24usize); - let mut refusals = Vec::new(); - let mut never_fired = 0u32; - for attempt in 0..80u32 { - let seed = 42 + attempt % 40; - let duration = frame_count as f64 / 25.0; - let source = - gradients_source(seed, width, height, &format!("duration={duration}:rate=25")); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-pix_fmt", - "yuv420p", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=45", - "--cpu-used=0", - "--kf-max-dist=1000", - "--threads=1", - "--row-mt=0", - "--auto-alt-ref=1", - "--lag-in-frames=16", - "--enable-fwd-kf=0", - "--enable-order-hint=1", - "--enable-warped-motion=0", - "--enable-obmc=1", - "--enable-masked-comp=0", - "--enable-interintra-comp=0", - "--enable-onesided-comp=0", - "--enable-interintra-wedge=0", - "--enable-smooth-interintra=0", - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-tx-size-search=0", - "--enable-cdef=0", - "--enable-restoration=0", - "--max-partition-size=32", - "--min-partition-size=32", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - "--enable-ref-frame-mvs=0", - "--obu", - "-o", - "-", - "-", - ]; - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let before = decode::obmc_hits(); - let frames = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME} failed outright (seed {seed}): {msg}" - ); - refusals.push(format!("seed {seed}: {msg}")); - continue; - } - Ok(frames) => frames, - }; - // class [[gate-skips-on-its-own-failure]]: a decode that succeeded - // is ALWAYS pixel-compared below; the hit counter only decides whether - // the attempt counts toward the firing total. - let counted = decode::obmc_hits() != before; - if !counted { - never_fired += 1; - } - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count); - assert_eq!(frames.len(), frame_count); - let mismatched = frames - .iter() - .zip(&ffmpeg_frames) - .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); - if mismatched - && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") { - std::fs::write(&path, &stream).expect("writing pinned stream"); - eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}"); - } - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!( - got.y, want.y, - "{NAME} frame {i} luma vs ffmpeg (seed {seed})" - ); - assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})"); - assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})"); - } - // lane-hidden r2 (class gate-blind-to-hidden-frames): the same - // stream again, comparing EVERY decode-order frame -- the hidden - // (show_frame == 0) alt-ref frames the ffmpeg compare above - // cannot see, because both sides of it emit shown frames only. - let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME); - eprintln!( - "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \ - {hidden_n} hidden, all pixel-exact vs the oracle" - ); - // lane-hidden r2 SECOND ARM (the recipe above is untouched): - // libaom's temporal alt-ref filter absorbs this recipe's hidden - // frames, so the compare above is vacuous -- re-encode the same - // fixture with --arnr-maxframes=0 and compare THOSE. - if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) { - eprintln!( - "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \ - decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle" - ); - } - if counted { - eprintln!( - "{NAME} FIRING seed {seed}: obmc hits advanced by {}", - decode::obmc_hits() - before - ); - gate_buckets(NAME, 1, never_fired, refusals.len()); - return; - } - } - gate_buckets(NAME, 0, never_fired, refusals.len()); - eprintln!( - "SKIP {NAME}: {never_fired} attempts decoded but never fired obmc, and every \ - other attempt hit a named refusal:\n{}", - refusals.join("\n") - ); - } diff --git a/crates/ec-av1/src/stream/tests/t06.rs b/crates/ec-av1/src/stream/tests/t06.rs deleted file mode 100644 index 40824e4b..00000000 --- a/crates/ec-av1/src/stream/tests/t06.rs +++ /dev/null @@ -1,4444 +0,0 @@ -use super::*; -use super::support::*; -use super::gates_a::*; -use super::gates_b::*; -use crate::probe::run_with_stdin; -use std::process::{Command, Stdio}; - - /// lane-motionmode round 3: same shape as - /// `a_real_aomenc_stream_with_obmc_decodes_pixel_exact`, but relaxed the - /// `--min-partition-size=32 --max-partition-size=32` clamp (that other - /// gate's own doc: locked to remove partition-depth choice from the - /// search entirely) to `8`/`32`, to make an 8x8-leaf `OBMC_CAUSAL` pick - /// possible at all. Gated on [`decode::obmc_hits_8`] specifically, not - /// the aggregate [`decode::obmc_hits`]. Measured live (round 3, this - /// box): 80 attempts, 0 ever called `decode_inter_block8` at all -- - /// `cpu-used=0`'s RD search never once splits a 16x16 down to a clean - /// 4-way 8x8 leaf for this smooth `gradients` fixture (large blocks - /// always win the RD cost there); the handful of named refusals seen - /// are `PARTITION_SPLIT` chosen *at* 8x8 (down to 4x4, already refused - /// at `decode.rs`'s `part8 != PARTITION_NONE` check) or - /// `allow_screen_content_tools`, neither reaching a leaf. Kept anyway - /// (mirrors this file's own `never_fired`-skip convention) as the - /// honest record of the attempt; a real 8x8 OBMC fixture needs - /// higher-frequency content than this gate's fixtures use, out of - /// round-3 budget. - #[test] - fn a_real_aomenc_stream_with_obmc_8x8_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_stream_with_obmc_8x8_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height, frame_count) = (64usize, 64usize, 24usize); - let mut refusals = Vec::new(); - let mut never_fired = 0u32; - let mut total_obmc8 = 0usize; - let n_attempts: u32 = std::env::var("EC_OBMC8_ATTEMPTS") - .ok() - .and_then(|s| s.parse().ok()) - .unwrap_or(80); - for attempt in 0..n_attempts { - let seed = 42 + attempt % 40; - let duration = frame_count as f64 / 25.0; - // Recipe search hook: `gradients` is smooth, so aomenc's RD never - // splits below 16x16 and this gate never fired one 8x8 OBMC block - // in 45 attempts -- it "passed" by skipping (gate-blind-to-feature). - // EC_AV1_OBMC8_SOURCE overrides the lavfi source so a firing recipe - // can be searched for without a rebuild. - let source = std::env::var("EC_AV1_OBMC8_SOURCE").unwrap_or_else(|_| { - gradients_source(seed, width, height, &format!("duration={duration}:rate=25")) - }); - // A source supplied through EC_AV1_OBMC8_SOURCE need not carry its - // own `duration=`; `-t` is the bound that always holds. Without it - // an endless source (`testsrc2`) fills the pipe forever and the - // gate hangs to its 300 s timeout. - let duration_arg = format!("{duration}"); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-t", - &duration_arg, - "-pix_fmt", - "yuv420p", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=45", - "--cpu-used=0", - "--kf-max-dist=1000", - "--threads=1", - "--row-mt=0", - "--auto-alt-ref=1", - "--lag-in-frames=16", - "--enable-fwd-kf=0", - "--enable-order-hint=1", - "--enable-warped-motion=0", - "--enable-obmc=1", - "--enable-masked-comp=0", - "--enable-interintra-comp=0", - "--enable-onesided-comp=0", - "--enable-interintra-wedge=0", - "--enable-smooth-interintra=0", - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-tx-size-search=0", - "--enable-cdef=0", - "--enable-restoration=0", - "--min-partition-size=8", - "--max-partition-size=32", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - "--enable-ref-frame-mvs=0", - "--obu", - "-o", - "-", - "-", - ]; - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let before8 = decode::obmc_hits_8(); - let frames = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME} failed outright (seed {seed}): {msg}" - ); - refusals.push(format!("seed {seed}: {msg}")); - continue; - } - Ok(frames) => frames, - }; - let fired8 = decode::obmc_hits_8() - before8; - total_obmc8 += fired8; - // class [[gate-skips-on-its-own-failure]]: a decode that succeeded - // is ALWAYS pixel-compared below; the hit counter only decides whether - // the attempt counts toward the firing total. - let counted = fired8 != 0; - if !counted { - never_fired += 1; - } - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count); - assert_eq!(frames.len(), frame_count); - let mismatched = frames - .iter() - .zip(&ffmpeg_frames) - .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); - if mismatched - && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") { - std::fs::write(&path, &stream).expect("writing pinned stream"); - eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}"); - } - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!( - got.y, want.y, - "{NAME} frame {i} luma vs ffmpeg (seed {seed})" - ); - assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})"); - assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})"); - } - // lane-hidden r2 (class gate-blind-to-hidden-frames): the same - // stream again, comparing EVERY decode-order frame -- the hidden - // (show_frame == 0) alt-ref frames the ffmpeg compare above - // cannot see, because both sides of it emit shown frames only. - let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME); - eprintln!( - "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \ - {hidden_n} hidden, all pixel-exact vs the oracle" - ); - // lane-hidden r2 SECOND ARM (the recipe above is untouched): - // libaom's temporal alt-ref filter absorbs this recipe's hidden - // frames, so the compare above is vacuous -- re-encode the same - // fixture with --arnr-maxframes=0 and compare THOSE. - if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) { - eprintln!( - "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \ - decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle" - ); - } - if counted { - eprintln!( - "{NAME} FIRING seed {seed}: 8x8 obmc hits {fired8} (total across attempts so far {total_obmc8})" - ); - gate_buckets(NAME, 1, never_fired, refusals.len()); - return; - } - } - gate_buckets(NAME, 0, never_fired, refusals.len()); - // lane-gmaffine r2: this gate fired for three rounds only as a SKIP - // (gate-skips-on-its-own-failure); the 8x8 leaf is reachable now, so a - // sweep that never lands one firing pixel-exact attempt is a FAILURE. - panic!( - "{NAME}: {never_fired} attempts decoded but never fired an 8x8 obmc block \ - ({total_obmc8} total 8x8 obmc hits across all attempts), and every other attempt \ - hit a named refusal:\n{}", - refusals.join("\n") - ); - } - - /// lane-warp r5e (flipped from lane-motionmode r1's refuses-or-matches): - /// `--enable-warped-motion=1` streams must DECODE pixel-exact -- - /// `av1_findSamples`/`num_proj_ref`, the 3-symbol `motion_mode` read, - /// the affine projection/filter, and the WARPED_CAUSAL interp-filter - /// derivation are all ported. A refusal naming warp, or any pixel - /// mismatch, fails the gate; refusals for OTHER named capabilities - /// (screen content tools) still skip that seed. The sweep must also - /// actually exercise warp (`warp_selected_hits > 0`) so a decoder that - /// silently stops selecting WARPED_CAUSAL cannot pass vacuously. - #[test] - fn a_real_aomenc_stream_with_warped_motion_refuses_or_matches() { - const NAME: &str = "a_real_aomenc_stream_with_warped_motion_refuses_or_matches"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height, frame_count) = (64usize, 64usize, 24usize); - let mut named_refusals = 0u32; - let mut matched = 0u32; - let n_attempts: u32 = std::env::var("EC_WARP_GATE_ATTEMPTS") - .ok() - .and_then(|s| s.parse().ok()) - .unwrap_or(40); - for attempt in 0..n_attempts { - let seed = 42 + attempt; - let duration = frame_count as f64 / 25.0; - let source = - gradients_source(seed, width, height, &format!("duration={duration}:rate=25")); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-pix_fmt", - "yuv420p", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=45", - "--cpu-used=0", - "--kf-max-dist=1000", - "--threads=1", - "--row-mt=0", - "--auto-alt-ref=1", - "--lag-in-frames=16", - "--enable-fwd-kf=0", - "--enable-order-hint=1", - "--enable-warped-motion=1", - "--enable-obmc=1", - "--tune-content=default", - "--enable-masked-comp=0", - "--enable-interintra-comp=0", - "--enable-onesided-comp=0", - "--enable-interintra-wedge=0", - "--enable-smooth-interintra=0", - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-tx-size-search=0", - "--enable-cdef=0", - "--enable-restoration=0", - "--max-partition-size=32", - "--min-partition-size=32", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - "--enable-ref-frame-mvs=0", - "--obu", - "-o", - "-", - "-", - ]; - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let frames = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME} failed outright, not a named refusal (seed {seed}): {msg}" - ); - assert!( - !msg.contains("warp"), - "{NAME} refused on warp (seed {seed}) -- warp decode is ported, this \ - refusal must not exist: {msg}" - ); - named_refusals += 1; - eprintln!("seed {seed} refusal (non-warp capability): {msg}"); - continue; - } - Ok(frames) => frames, - }; - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count); - assert_eq!(frames.len(), frame_count); - let mismatched = frames - .iter() - .zip(&ffmpeg_frames) - .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); - if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") { - std::fs::write(&path, &stream).expect("writing pinned stream"); - eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}"); - } - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!( - got.y, want.y, - "{NAME} frame {i} luma vs ffmpeg (seed {seed})" - ); - assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})"); - assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})"); - } - // lane-hidden r2 (class gate-blind-to-hidden-frames): the same - // stream again, comparing EVERY decode-order frame -- the hidden - // (show_frame == 0) alt-ref frames the ffmpeg compare above - // cannot see, because both sides of it emit shown frames only. - let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME); - eprintln!( - "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \ - {hidden_n} hidden, all pixel-exact vs the oracle" - ); - // lane-hidden r2 SECOND ARM (the recipe above is untouched): - // libaom's temporal alt-ref filter absorbs this recipe's hidden - // frames, so the compare above is vacuous -- re-encode the same - // fixture with --arnr-maxframes=0 and compare THOSE. - if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) { - eprintln!( - "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \ - decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle" - ); - } - matched += 1; - } - assert!( - matched > 0, - "{NAME}: every attempt refused on other capabilities; the gate never exercised warp" - ); - assert!( - crate::decode::warp_selected_hits() > 0, - "{NAME}: {matched} matches but zero WARPED_CAUSAL blocks fired -- the gate decodes \ - warp streams without ever selecting warp, so it proves nothing about warp" - ); - eprintln!( - "{NAME}: {named_refusals} non-warp refusals, {matched} pixel-exact matches out of {n_attempts}, warp_selected_hits={}", - crate::decode::warp_selected_hits() - ); - } - - /// lane-superres stage 3: a real aomenc `--superres-mode=1` key-frame - /// sequence must decode pixel-exact vs ffmpeg/dav1d's own upscaled - /// output, and must actually run [`crate::superres::upscale_picture`] - /// (`superres_hits > 0`) -- a decoder that silently stopped upscaling - /// would otherwise pass vacuously (class `gate-blind-to-feature`). - /// `--kf-max-dist` set to the frame count keeps every frame a key - /// frame: inter-frame superres (a differently-scaled reference) is a - /// later stage of this lane, refused by name today. - #[test] - fn a_real_aomenc_superres_key_frame_sequence_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_superres_key_frame_sequence_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height, frame_count) = (64usize, 64usize, 3usize); - let duration = frame_count as f64 / 25.0; - let source = gradients_source(7, width, height, &format!("duration={duration}:rate=25")); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-pix_fmt", - "yuv420p", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=32", - "--cpu-used=0", - "--kf-max-dist=0", - "--threads=1", - "--row-mt=0", - "--superres-mode=1", - "--superres-denominator=12", - "--superres-kf-denominator=12", - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-tx-size-search=0", - "--enable-cdef=0", - "--enable-restoration=0", - "--max-partition-size=32", - "--min-partition-size=32", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - "--obu", - "-o", - "-", - "-", - ]; - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - if let Ok(path) = std::env::var("EC_SUPERRES_STREAM_DUMP") { - std::fs::write(path, &stream).expect("dump stream"); - } - let frames = decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME} refused: {e}")); - assert_eq!(frames.len(), frame_count); - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count); - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg"); - assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg"); - assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg"); - } - assert!( - crate::superres::superres_hits() > 0, - "{NAME}: matched but zero superres_hits -- the gate never actually exercised the \ - upscaler, it proves nothing" - ); - eprintln!( - "{NAME}: {frame_count} frames pixel-exact, superres_hits={}", - crate::superres::superres_hits() - ); - } - - /// lane-superres r10: a real aomenc key+inter `--superres-mode=1` - /// sequence must DECODE pixel-exact vs ffmpeg, with the frame-level - /// `use_superres` refusal LIFTED for inter frames -- `mc::predict_scaled` - /// (spec 7.11.3.3) is the only path this recipe can reach (warp/OBMC/ - /// compound/interintra/palette/intrabc/CDEF/LR are all off, matching the - /// scoped refusals' own unimplemented list). A pixel match alone would - /// pass just as well with an unscaled reference and prove nothing - /// (class `gate-blind-to-feature`) -- hard-assert - /// `crate::mc::predict_scaled_hits() > 0` so the gate can only pass if the - /// scaled MC path actually ran. - #[test] - fn a_real_aomenc_key_and_inter_superres_sequence_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_key_and_inter_superres_sequence_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height, frame_count) = (64usize, 64usize, 3usize); - let duration = frame_count as f64 / 25.0; - let source = gradients_source(11, width, height, &format!("duration={duration}:rate=25")); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-pix_fmt", - "yuv420p", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=32", - "--cpu-used=0", - // `--kf-max-dist` above `frame_count` keeps only frame 0 a key - // frame -- frames 1/2 are the inter frames whose `use_superres` - // refusal this round lifts. - "--kf-max-dist=1000", - "--lag-in-frames=0", - "--auto-alt-ref=0", - "--threads=1", - "--row-mt=0", - "--sb-size=64", - "--superres-mode=1", - "--superres-denominator=12", - "--superres-kf-denominator=12", - // Forces every inter block onto the single-ref, non-warp/OBMC/ - // interintra branch `decode_inter_block` threads `predict_scaled` - // through -- the only branch this round's scoped refusals leave - // unrefused under a scaled reference. - "--enable-warped-motion=0", - "--enable-obmc=0", - "--enable-masked-comp=0", - "--enable-interintra-comp=0", - "--enable-dist-wtd-comp=0", - "--enable-diff-wtd-comp=0", - "--enable-onesided-comp=0", - "--enable-interintra-wedge=0", - "--enable-smooth-interintra=0", - "--enable-order-hint=0", - "--enable-ref-frame-mvs=0", - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-tx-size-search=0", - "--enable-cdef=0", - "--enable-restoration=0", - "--max-partition-size=32", - "--min-partition-size=32", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - "--obu", - "-o", - "-", - "-", - ]; - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - if let Ok(path) = std::env::var("EC_SUPERRES_INTER_STREAM_DUMP") { - std::fs::write(&path, &stream).expect("dump stream"); - } - let frames = decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME} refused: {e}")); - assert_eq!(frames.len(), frame_count); - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count); - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg"); - assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg"); - assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg"); - } - assert!( - crate::superres::superres_hits() > 0, - "{NAME}: matched but zero superres_hits -- the upscaler never ran" - ); - assert!( - crate::mc::predict_scaled_hits() > 0, - "{NAME}: matched but zero predict_scaled_hits -- every block took the unscaled MC \ - path, which proves nothing about the scaled-reference code this round adds \ - (class gate-blind-to-feature)" - ); - eprintln!( - "{NAME}: {frame_count} frames pixel-exact, superres_hits={}, predict_scaled_hits={}", - crate::superres::superres_hits(), - crate::mc::predict_scaled_hits() - ); - } - - /// lane-t900 r28: the three scaled-reference (superres) refusals are - /// LIFTED -- an 8x8 partition leaf, a sub-8x8 inter block, and warp -- - /// so two real `--superres-mode=1` streams whose references are all - /// scaled must decode PIXEL-EXACT vs ffmpeg. - /// - /// Arm A drives `--min-partition-size=4` so the split (4x4) and rect - /// (8x4/4x8) sub-8x8 readers and the 8x8 leaf all run over a scaled - /// reference; arm B turns `--enable-warped-motion=1` on, which is the - /// root cause this round fixed: libaom `motion_mode_allowed` drops - /// WARPED_CAUSAL eligibility when `av1_is_scaled(sf)`, so the 8x8 leaf - /// must read the 2-symbol obmc alphabet (here: no symbol at all, OBMC - /// off) instead of the 3-symbol motion_mode row. - /// - /// Each arm hard-asserts its own counter (class `gate-blind-to-feature`): - /// a pixel match with zero scaled leaves/sub-8x8 blocks/suppressed warp - /// eligibilities would prove nothing. - #[test] - fn real_superres_streams_with_sub8_leaf8_and_warp_decode_pixel_exact() { - const NAME: &str = "real_superres_streams_with_sub8_leaf8_and_warp_decode_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - // Every tool whose scaled-reference path this round does NOT touch is - // off, so a mismatch can only be the lifted paths (the same scoping - // the r10 key+inter superres gate uses). - let common: [&str; 21] = [ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--threads=1", - "--row-mt=0", - "--kf-max-dist=9999", - "--lag-in-frames=0", - "--auto-alt-ref=0", - "--cpu-used=0", - "--sb-size=64", - "--superres-mode=1", - "--superres-denominator=12", - "--superres-kf-denominator=12", - "--enable-obmc=0", - "--enable-masked-comp=0", - "--enable-interintra-comp=0", - "--enable-tx-size-search=0", - "--enable-cdef=0", - "--enable-restoration=0", - "--enable-palette=0", - "--enable-intrabc=0", - ]; - struct Arm { - name: &'static str, - frames: usize, - cq: &'static str, - extra: [&'static str; 4], - } - let arms = [ - Arm { - name: "sub8+leaf8", - frames: 4, - cq: "--cq-level=4", - extra: [ - "--enable-warped-motion=0", - "--enable-rect-partitions=1", - "--max-partition-size=32", - "--min-partition-size=4", - ], - }, - Arm { - name: "warp", - frames: 6, - cq: "--cq-level=20", - extra: [ - "--enable-warped-motion=1", - "--enable-rect-partitions=1", - "--max-partition-size=32", - "--min-partition-size=8", - ], - }, - ]; - let (width, height) = (96usize, 96usize); - for arm in &arms { - let duration = format!("{}", arm.frames as f64 / 25.0); - let src = format!("mandelbrot=size={width}x{height}:rate=25"); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &src, - "-t", - &duration, - "-pix_fmt", - "yuv420p", - "-strict", - "-1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!(y4m.status.success(), "{NAME}: ffmpeg refused the fixture"); - let limit = format!("--limit={}", arm.frames); - let mut args: Vec<&str> = common.to_vec(); - args.push(&limit); - args.push(arm.cq); - args.extend_from_slice(&arm.extra); - args.extend_from_slice(&["--obu", "-o", "-", "-"]); - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "{NAME} {}: aomenc refused the recipe: {}", - arm.name, - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let leaf8_before = crate::decode::scaled_leaf8_hits(); - let sub8_before = crate::decode::scaled_sub8_hits(); - let warp_before = crate::decode::scaled_warp_suppressed_hits(); - let frames = decode_stream(&stream) - .unwrap_or_else(|e| panic!("{NAME} {}: refused: {e}", arm.name)); - assert_eq!(frames.len(), arm.frames, "{NAME} {}", arm.name); - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, arm.frames); - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!( - got.y, want.y, - "{NAME} {} frame {i} luma vs ffmpeg", - arm.name - ); - assert_eq!(got.u, want.u, "{NAME} {} frame {i} U vs ffmpeg", arm.name); - assert_eq!(got.v, want.v, "{NAME} {} frame {i} V vs ffmpeg", arm.name); - } - let (leaf8, sub8, warp) = ( - crate::decode::scaled_leaf8_hits() - leaf8_before, - crate::decode::scaled_sub8_hits() - sub8_before, - crate::decode::scaled_warp_suppressed_hits() - warp_before, - ); - eprintln!( - "{NAME} {}: {} frames pixel-exact, scaled leaf8={leaf8} sub8={sub8} \ - warp_suppressed={warp}", - arm.name, arm.frames - ); - if arm.name == "sub8+leaf8" { - assert!( - leaf8 > 0 && sub8 > 0, - "{NAME} {}: the lifted paths never ran (leaf8={leaf8} sub8={sub8})", - arm.name - ); - } else { - assert!( - warp > 0, - "{NAME} {}: no block reached WARPED_CAUSAL eligibility under a scaled \ - reference, so the alphabet fix is unexercised", - arm.name - ); - } - } - } - - /// lane-interintra r1: `--enable-interintra-comp=1` streams must DECODE - /// pixel-exact -- the interintra flag/mode/wedge-flag syntax and the - /// non-wedge smooth blend are ported. A refusal naming interintra fails - /// the gate UNLESS it is the wedge refusal (`use_wedge_interintra == 1` - /// is r2, and this recipe encodes with wedge off so it must not fire - /// either); warp/obmc are enabled and supported; refusals for OTHER - /// named capabilities (screen content tools) still skip that seed. The - /// sweep must actually exercise interintra (`interintra_hits > 0`). - #[test] - fn a_real_aomenc_stream_with_interintra_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_stream_with_interintra_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height, frame_count) = (64usize, 64usize, 24usize); - // lane-midcut r1: rect interintra (`write_w != write_h`) built its - // intra predictor at the square `side`; this gate passed with that - // bug, so the shape gets its own delta-counted assert below. - let rect_before = crate::decode::interintra_rect_hits(); - let mut named_refusals = 0u32; - let mut matched = 0u32; - let n_attempts: u32 = std::env::var("EC_INTERINTRA_GATE_ATTEMPTS") - .ok() - .and_then(|s| s.parse().ok()) - .unwrap_or(40); - for attempt in 0..n_attempts { - let seed = 42 + attempt; - let duration = frame_count as f64 / 25.0; - let source = - gradients_source(seed, width, height, &format!("duration={duration}:rate=25")); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-pix_fmt", - "yuv420p", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=45", - "--cpu-used=0", - "--kf-max-dist=1000", - "--threads=1", - "--row-mt=0", - "--auto-alt-ref=1", - "--lag-in-frames=16", - "--enable-fwd-kf=0", - "--enable-order-hint=1", - "--enable-warped-motion=1", - "--enable-obmc=1", - "--tune-content=default", - "--enable-masked-comp=0", - "--enable-interintra-comp=1", - "--enable-onesided-comp=1", - "--enable-interintra-wedge=0", - "--enable-smooth-interintra=1", - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-tx-size-search=0", - "--enable-cdef=0", - "--enable-restoration=0", - "--max-partition-size=32", - "--min-partition-size=32", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - "--enable-ref-frame-mvs=0", - "--obu", - "-o", - "-", - "-", - ]; - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let frames = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME} failed outright, not a named refusal (seed {seed}): {msg}" - ); - assert!( - !msg.contains("warp"), - "{NAME} refused on warp (seed {seed}) -- warp decode is ported, this \ - refusal must not exist: {msg}" - ); - assert!( - !msg.contains("interintra"), - "{NAME} refused on interintra (seed {seed}) -- non-wedge interintra \ - is ported and this recipe encodes with wedge off: {msg}" - ); - named_refusals += 1; - eprintln!("seed {seed} refusal (non-warp capability): {msg}"); - continue; - } - Ok(frames) => frames, - }; - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count); - assert_eq!(frames.len(), frame_count); - let mismatched = frames - .iter() - .zip(&ffmpeg_frames) - .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); - if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") { - std::fs::write(&path, &stream).expect("writing pinned stream"); - eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}"); - } - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!( - got.y, want.y, - "{NAME} frame {i} luma vs ffmpeg (seed {seed})" - ); - assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})"); - assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})"); - } - // lane-hidden r2 (class gate-blind-to-hidden-frames): the same - // stream again, comparing EVERY decode-order frame -- the hidden - // (show_frame == 0) alt-ref frames the ffmpeg compare above - // cannot see, because both sides of it emit shown frames only. - let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME); - eprintln!( - "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \ - {hidden_n} hidden, all pixel-exact vs the oracle" - ); - // lane-hidden r2 SECOND ARM (the recipe above is untouched): - // libaom's temporal alt-ref filter absorbs this recipe's hidden - // frames, so the compare above is vacuous -- re-encode the same - // fixture with --arnr-maxframes=0 and compare THOSE. - if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) { - eprintln!( - "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \ - decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle" - ); - } - // lane-midcut r3 RECT ARM: the recipe above spells - // `--enable-rect-partitions=0 --min-partition-size=32`, so it can - // never produce a RECT interintra block -- the delta assert at the - // end of this gate was unsatisfiable on it (the gate disabled the - // very shape it claims to prove). Re-encode the SAME source with - // the rect overrides APPENDED (aomenc keeps the LAST occurrence of - // a repeated flag) and compare every decode-order frame of that - // stream against aomdec, until a rect interintra block fires. - if crate::decode::interintra_rect_hits() == rect_before { - let mut rect_args = args.clone(); - rect_args.extend_from_slice(&[ - "--enable-rect-partitions=1", - "--min-partition-size=8", - "--max-partition-size=64", - ]); - let out = run_with_stdin(Command::new(aomenc_path()).args(&rect_args), &y4m.stdout); - assert!( - out.status.success(), - "{NAME} RECT-ARM: aomenc refused its own recipe plus the rect overrides: {}", - String::from_utf8_lossy(&out.stderr) - ); - let rect_stream = out.stdout; - match decode_stream(&rect_stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME} RECT-ARM failed outright, not a named refusal (seed {seed}): {msg}" - ); - eprintln!("{NAME} RECT-ARM: skipped on a named refusal: {msg}"); - } - Ok(_) => { - let (total, hidden) = - decode_all_frames_vs_oracle(&rect_stream, &format!("{NAME}-rect")); - eprintln!( - "{NAME} RECT-ARM: seed {seed}: {total} decode-order frames, {hidden} \ - hidden, all pixel-exact vs the oracle, interintra_rect_hits={}", - crate::decode::interintra_rect_hits() - rect_before - ); - } - } - } - matched += 1; - } - assert!( - matched > 0, - "{NAME}: every attempt refused on other capabilities; the gate never exercised warp" - ); - assert!( - crate::decode::interintra_hits() > 0, - "{NAME}: {matched} matches but zero interintra blocks fired -- the gate decodes \ - these streams without ever taking interintra, so it proves nothing" - ); - // lane-defon r1: `--enable-onesided-comp=1` is spelled on this - // recipe, so a UNIDIR_COMP_REFERENCE pair must actually have been - // read -- otherwise the on-value proves nothing. - assert!( - crate::decode::uni_comp_hits() > 0, - "{NAME}: {matched} matches but zero UNIDIR_COMP_REFERENCE pairs read -- \ - --enable-onesided-comp=1 never reached the uni_comp_ref alphabet" - ); - assert!( - crate::decode::interintra_rect_hits() > rect_before, - "{NAME}: {matched} matches but zero RECTANGULAR interintra blocks fired -- the \ - square-only blend defect (lane-midcut r1) would pass this gate unseen" - ); - eprintln!( - "{NAME}: {named_refusals} other-capability refusals, {matched} pixel-exact matches out of {n_attempts}, interintra_hits={} interintra_rect_hits={} uni_comp_hits={}", - crate::decode::interintra_hits(), - crate::decode::interintra_rect_hits() - rect_before, - crate::decode::uni_comp_hits() - ); - } - - /// lane-scaledref r1: a real aomenc `--superres-mode=1` sequence with - /// compound, OBMC, interintra and 8x8 leaves ALL enabled must decode - /// pixel-exact -- these are the combinations the three - /// "... with a scaled reference (superres, unimplemented)" refusals used - /// to cover. Each combination gets its OWN hard-asserted hit counter - /// (`crate::decode::scaled_*_hits`), because an unscaled reference would - /// pass the pixels and prove nothing (class `gate-blind-to-feature`), and - /// a stream that scales but never takes compound/OBMC/interintra/8x8 - /// would prove nothing about the code this round adds either. A refusal - /// naming a scaled reference is a hard failure: those are exactly the - /// strings this round lifts. Other named capabilities skip that seed. - #[test] - fn a_real_aomenc_superres_stream_with_compound_obmc_and_interintra_decodes_pixel_exact() { - const NAME: &str = - "a_real_aomenc_superres_stream_with_compound_obmc_and_interintra_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height, frame_count) = (64usize, 64usize, 24usize); - let mut named_refusals = 0u32; - let mut matched = 0u32; - let n_attempts: u32 = std::env::var("EC_SCALEDREF_GATE_ATTEMPTS") - .ok() - .and_then(|s| s.parse().ok()) - .unwrap_or(12); - for attempt in 0..n_attempts { - let seed = 42 + attempt; - let duration = frame_count as f64 / 25.0; - let source = - gradients_source(seed, width, height, &format!("duration={duration}:rate=25")); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-pix_fmt", - "yuv420p", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let on = |name: &str| { - if std::env::var(name).as_deref() == Ok("0") { - "0" - } else { - "1" - } - }; - // lane-scaledref r2: warp is ON. A warp-capable frame header - // under a scaled reference is exactly the case r1 got wrong - // (the block must read the 2-symbol `obmc_cdf`, not the - // 3-symbol `motion_mode_cdf` -- libaom `motion_mode_allowed`, - // blockd.h:1484), and it decoded silently wrong pixels rather - // than refusing. `EC_SCALEDREF_WARP=0` turns it off for - // bisecting only. - let warp = format!("--enable-warped-motion={}", on("EC_SCALEDREF_WARP")); - // lane-scaledref r2: `EC_SCALEDREF_MODE=3` (qthresh) lets - // superres switch on and off per frame, so a compound block can - // reference one scaled and one unscaled reference -- the mixed - // case mode 1 (every frame scaled) never produces. - let superres_mode = format!( - "--superres-mode={}", - std::env::var("EC_SCALEDREF_MODE").unwrap_or_else(|_| "1".into()) - ); - let obmc = format!("--enable-obmc={}", on("EC_SCALEDREF_OBMC")); - let interintra = format!("--enable-interintra-comp={}", on("EC_SCALEDREF_II")); - let lag = format!( - "--lag-in-frames={}", - if on("EC_SCALEDREF_COMP") == "0" { - "0" - } else { - "25" - } - ); - let alt_ref = format!("--auto-alt-ref={}", on("EC_SCALEDREF_COMP")); - let args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=45", - "--cpu-used=0", - "--kf-max-dist=1000", - "--threads=1", - "--row-mt=0", - "--sb-size=64", - // superres on every frame, key and inter alike -- the scaled - // reference this gate is about. - // denominator 16 (the maximum) keeps the CODED frame - // 32x64 -- a multiple of 16 both ways, so no frame-edge - // 16x16 straddle forces a sub-16x16 partition this decoder - // still refuses on the aligned path ("an inter partition - // below 16x16"). Denominator 12 codes 43 columns and every - // seed refused there. - &superres_mode, - "--superres-denominator=16", - "--superres-kf-denominator=16", - // the four combinations this round lifts (each switchable - // by env for bisecting a mismatch without a rebuild) - &alt_ref, - &lag, - "--enable-order-hint=1", - &warp, - &obmc, - &interintra, - "--enable-smooth-interintra=1", - "--enable-interintra-wedge=0", - "--enable-masked-comp=0", - "--enable-onesided-comp=0", - "--enable-fwd-kf=0", - "--tune-content=default", - "--max-partition-size=32", - "--min-partition-size=32", - // everything this decoder still refuses under any reference - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-tx-size-search=0", - "--enable-cdef=0", - "--enable-restoration=0", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - "--enable-ref-frame-mvs=0", - "--obu", - "-o", - "-", - "-", - ]; - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let frames = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME} failed outright, not a named refusal (seed {seed}): {msg}" - ); - assert!( - !msg.contains("scaled reference"), - "{NAME} refused on a scaled reference (seed {seed}) -- those refusals \ - are exactly what this round lifts: {msg}" - ); - named_refusals += 1; - eprintln!("seed {seed} refusal (other capability): {msg}"); - continue; - } - Ok(frames) => frames, - }; - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count); - assert_eq!(frames.len(), frame_count); - if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") { - let mismatched = frames - .iter() - .zip(&ffmpeg_frames) - .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); - if mismatched { - std::fs::write(&path, &stream).expect("writing pinned stream"); - eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}"); - } - } - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!( - got.y, want.y, - "{NAME} frame {i} luma vs ffmpeg (seed {seed})" - ); - assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})"); - assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})"); - } - matched += 1; - } - eprintln!( - "{NAME}: {named_refusals} other-capability refusals, {matched}/{n_attempts} pixel-exact, \ - superres_hits={} predict_scaled_hits={} scaled_compound={} scaled_warp_fallback={} \ - scaled_obmc={} scaled_interintra={} scaled_block8={} scaled_warp_suppressed={} mixed_scale_compound={}", - crate::superres::superres_hits(), - crate::mc::predict_scaled_hits(), - crate::decode::scaled_compound_hits(), - crate::decode::scaled_warp_fallback_hits(), - crate::decode::scaled_obmc_hits(), - crate::decode::scaled_interintra_hits(), - crate::decode::scaled_block8_hits(), - crate::decode::scaled_warp_suppressed_hits(), - crate::decode::mixed_scale_compound_hits(), - ); - assert!( - matched > 0, - "{NAME}: every attempt refused on other capabilities; the gate proves nothing" - ); - assert!( - crate::mc::predict_scaled_hits() > 0, - "{NAME}: matched but zero predict_scaled_hits -- no block took the scaled MC path" - ); - // The 8x8 leaf is NOT asserted here: it stays refused (no recipe - // produced an 8x8 inter leaf at all), so its counter is a - // diagnostic only -- see this gate's own doc and decode.rs. - // `scaled_warp_suppressed` IS asserted: it counts the blocks whose - // WARPED_CAUSAL eligibility libaom drops because the reference is - // scaled, i.e. the blocks that must read `obmc_cdf`. Zero of them - // would mean this gate's `--enable-warped-motion=1` never reached a - // warp-eligible block and proves nothing about r2's fix. - assert!( - crate::decode::scaled_warp_suppressed_hits() > 0, - "{NAME}: {matched} matches but no block had its warp eligibility \ - suppressed by a scaled reference -- the warp arm proves nothing" - ); - for (hits, what) in [ - ( - crate::decode::scaled_compound_hits(), - "compound with a scaled reference", - ), - ( - crate::decode::scaled_obmc_hits(), - "OBMC with a scaled reference", - ), - ( - crate::decode::scaled_interintra_hits(), - "interintra with a scaled reference", - ), - ] { - assert!( - hits > 0, - "{NAME}: {matched} matches but zero blocks took {what}" - ); - } - } - - /// lane-defon r1: the 10-bit one-sided-compound hole -- - /// `--enable-onesided-comp` was spelled on in no 10-bit gate (5 of the 15 - /// pin it off, the rest default), so the UNIDIR_COMP_REFERENCE alphabet - /// was proven at 8 bits only while both of his films are 10-bit 4:2:0. - /// `--enable-diff-wtd-comp=1` is deliberately NOT spelled here (a flag a - /// gate turns on without asserting it fired is coverage theatre, class - /// gate-blind-to-feature): measured this round, the 10-bit `gradients` - /// fixture decodes 8/8 pixel-exact with `diffwtd_hits == 0` -- smooth - /// gradients never win - /// a difference-weighted mask (the 8-bit gate needs `mandelbrot`'s hard - /// diagonal edge, and [`ten_bit_tool_gate`] has no mandelbrot source), so - /// hard-asserting it here would fail on encoder choice, not on a decoder - /// defect. - #[test] - fn a_real_aomenc_10bit_stream_with_onesided_compound_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_10bit_stream_with_onesided_compound_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - ten_bit_tool_gate( - NAME, - 64, - 64, - 24, - &[ - "--enable-onesided-comp=1", - "--enable-masked-comp=1", - "--enable-dist-wtd-comp=0", - "--cq-level=45", - "--kf-max-dist=1000", - "--auto-alt-ref=1", - "--lag-in-frames=16", - "--enable-fwd-kf=0", - "--enable-order-hint=1", - "--enable-global-motion=0", - "--enable-warped-motion=1", - "--enable-obmc=1", - "--tune-content=default", - "--enable-interintra-comp=0", - "--enable-interintra-wedge=0", - "--enable-smooth-interintra=0", - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-tx-size-search=0", - "--enable-cdef=0", - "--enable-restoration=0", - "--max-partition-size=32", - "--min-partition-size=32", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - "--enable-ref-frame-mvs=0", - ], - &[42, 43, 44, 45, 46, 47, 48, 49], - &[( - "uni_comp_hits", - crate::decode::uni_comp_hits as fn() -> usize, - )], - ); - } - - /// lane-defon r1: the 10-bit sibling of - /// [`a_real_aomenc_stream_with_interintra_wedge_decodes_pixel_exact`] -- - /// `--enable-interintra-wedge=1` was spelled on in no 10-bit gate (5 of - /// the 15 pin it off), and his two films are 10-bit, so the 8-bit - /// gate alone proves nothing about the streams that matter. Same tool - /// set as the 8-bit recipe (`--enable-masked-comp=0` keeps inter blocks - /// off the COMPOUND_WEDGE path, fixed 32x32 partitions), driven through - /// [`ten_bit_tool_gate`], which hard-asserts `wii_hits` moved and - /// compares every plane against ffmpeg's own 10-bit decode. - #[test] - fn a_real_aomenc_10bit_stream_with_interintra_wedge_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_10bit_stream_with_interintra_wedge_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - ten_bit_tool_gate( - NAME, - 64, - 64, - 24, - &[ - "--enable-interintra-wedge=1", - "--enable-interintra-comp=1", - "--enable-smooth-interintra=1", - "--cq-level=45", - "--kf-max-dist=1000", - "--auto-alt-ref=1", - "--lag-in-frames=16", - "--enable-fwd-kf=0", - "--enable-order-hint=1", - "--enable-warped-motion=1", - "--enable-obmc=1", - "--tune-content=default", - "--enable-masked-comp=0", - "--enable-onesided-comp=0", - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-tx-size-search=0", - "--enable-cdef=0", - "--enable-restoration=0", - "--max-partition-size=32", - "--min-partition-size=32", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - "--enable-ref-frame-mvs=0", - ], - &[42, 43, 44, 45, 46, 47, 48, 49], - &[ - ("wii_hits", crate::decode::wii_hits as fn() -> usize), - ( - "interintra_hits", - crate::decode::interintra_hits as fn() -> usize, - ), - ], - ); - } - - /// lane-wii r2: `--enable-interintra-wedge=1` streams must DECODE - /// pixel-exact -- the wedge-interintra syntax (adapting `wedge_index` - /// CDF symbol, fixed sign 0) and the wedge mask blend are ported over - /// the checksum-verified codebook. `--enable-masked-comp=0` stays so - /// the encoder cannot route inter blocks through the still-unported - /// COMPOUND_WEDGE/DIFFWTD path. A refusal naming interintra/wedge - /// fails the gate; refusals for OTHER named capabilities still skip - /// that seed. Zero `wii_hits` on a run means the encoder never - /// selected wedge-interintra -- soft-skipped (warned), not failed: - /// that is encoder choice, not a decoder bug. - #[test] - fn a_real_aomenc_stream_with_interintra_wedge_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_stream_with_interintra_wedge_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height, frame_count) = (64usize, 64usize, 24usize); - let mut named_refusals = 0u32; - let mut matched = 0u32; - let n_attempts: u32 = std::env::var("EC_WEDGE_GATE_ATTEMPTS") - .ok() - .and_then(|s| s.parse().ok()) - .unwrap_or(40); - for attempt in 0..n_attempts { - let seed = 42 + attempt; - let duration = frame_count as f64 / 25.0; - let source = if attempt % 2 == 0 { - gradients_source(seed, width, height, &format!("duration={duration}:rate=25")) - } else { - // `end_pts` does NOT bound mandelbrot (it generated 300+ - // frames and hung the gate for an hour); `-t` below is the - // real bound, matching every other mandelbrot gate recipe. - format!("mandelbrot=size={width}x{height}:rate=25") - }; - let duration_arg = format!("{duration}"); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-pix_fmt", - "yuv420p", - "-t", - &duration_arg, - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=45", - "--cpu-used=0", - "--kf-max-dist=1000", - "--threads=1", - "--row-mt=0", - "--auto-alt-ref=1", - "--lag-in-frames=16", - "--enable-fwd-kf=0", - "--enable-order-hint=1", - "--enable-warped-motion=1", - "--enable-obmc=1", - "--tune-content=default", - "--enable-masked-comp=0", - "--enable-interintra-comp=1", - "--enable-onesided-comp=0", - "--enable-interintra-wedge=1", - "--enable-smooth-interintra=1", - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-tx-size-search=0", - "--enable-cdef=0", - "--enable-restoration=0", - "--max-partition-size=32", - "--min-partition-size=32", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - "--enable-ref-frame-mvs=0", - "--obu", - "-o", - "-", - "-", - ]; - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let frames = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME} failed outright, not a named refusal (seed {seed}): {msg}" - ); - // Verifier note (lane-wii r2): no refusal string containing - // "wedge"/"interintra" exists in the decoder any more, so - // string-forbidding asserts here would be vacuous (class - // gate-blind-to-feature). The proof this gate carries is - // pixel-exact decode plus the wii_hits count printed below. - named_refusals += 1; - eprintln!("seed {seed} refusal (non-wedge capability): {msg}"); - continue; - } - Ok(frames) => frames, - }; - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count); - assert_eq!(frames.len(), frame_count); - let mismatched = frames - .iter() - .zip(&ffmpeg_frames) - .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); - if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") { - std::fs::write(&path, &stream).expect("writing pinned stream"); - eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}"); - } - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!( - got.y, want.y, - "{NAME} frame {i} luma vs ffmpeg (seed {seed})" - ); - assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})"); - assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})"); - } - // lane-hidden r2 (class gate-blind-to-hidden-frames): the same - // stream again, comparing EVERY decode-order frame -- the hidden - // (show_frame == 0) alt-ref frames the ffmpeg compare above - // cannot see, because both sides of it emit shown frames only. - let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME); - eprintln!( - "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \ - {hidden_n} hidden, all pixel-exact vs the oracle" - ); - // lane-hidden r2 SECOND ARM (the recipe above is untouched): - // libaom's temporal alt-ref filter absorbs this recipe's hidden - // frames, so the compare above is vacuous -- re-encode the same - // fixture with --arnr-maxframes=0 and compare THOSE. - if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) { - eprintln!( - "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \ - decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle" - ); - } - matched += 1; - } - assert!( - matched > 0, - "{NAME}: every attempt refused on other capabilities; the gate never exercised wedge-interintra" - ); - // Hardened from a soft-note (verifier: gate-blind-to-feature): the - // recipe fired wedge-interintra on EVERY one of 6 hammer runs - // (wii_hits 2-7), so a zero-hit run is a regression, not sampling. - assert!( - crate::decode::wii_hits() > 0, - "{NAME}: {matched} pixel-exact matches but zero wedge-interintra blocks fired -- \ - the blend is unexercised (recipe fired 2-7 hits per run when landed)" - ); - eprintln!( - "{NAME}: {named_refusals} other-capability refusals, {matched} pixel-exact matches out of {n_attempts}, wii_hits={}", - crate::decode::wii_hits() - ); - } - - /// lane-gmaffine r1: an inter frame whose `global_motion_params` carries a - /// SIX-parameter (`AFFINE`) model for a single-reference frame -- refused - /// by name since lane-gm r4 because no aomenc recipe ever reached it. - /// The reason it never did is in libaom's own encoder, not in the - /// content: `av1/encoder/global_motion_facade.c:24` pins the model search - /// to `ROTZOOM` at both ends, so *no* `--enable-global-motion=1` command - /// line over any source can produce the case. The decoder must still - /// handle it (the bitstream allows it, `read_global_motion_params` reads - /// params 4/5 with their own subexp references, and ffmpeg decodes it), - /// so this gate widens exactly that one encoder-side search range in a - /// side build and encodes with it. Everything downstream is ordinary - /// libaom and the pixel oracle is still ffmpeg. - /// - /// Content: rotation composed with a progressive *anisotropic* stretch -- - /// a similarity transform plus unequal axis scaling is precisely what a - /// 4-parameter ROTZOOM model cannot express, which is what makes the - /// encoder's RD pick AFFINE. `affine_gm_hits()` hard-asserts that real - /// blocks were predicted through the 6-parameter warp, not merely that a - /// header parsed one (class `gate-blind-to-feature`). - #[test] - fn a_real_affine_global_motion_stream_decodes_pixel_exact() { - const NAME: &str = "a_real_affine_global_motion_stream_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_affine_aomenc() { - eprintln!( - "SKIP {NAME}: no affine-capable aomenc at {} (scripts/build-aom-affine-oracle.sh)", - affine_aomenc_path().display() - ); - return; - } - let (width, height, frame_count) = (64usize, 64usize, 24usize); - let duration = frame_count as f64 / 25.0; - // Both depths: his own AV1 library is yuv420p10le throughout, and a - // 10-bit AFFINE warp runs the same `warp_affine` over wider samples. - for depth in [8u32, 10u32] { - // `-t` is the real bound on mandelbrot (it ignores `end_pts` and - // has hung a gate for an hour); the 96x96 source is rotated and - // then stretched horizontally only, and cropped back to 64x64. - let source = format!( - "mandelbrot=size=96x96:rate=25,rotate=a=0.12*t:c=black,\ - scale=w='ceil(96*(1+0.03*n)/2)*2':h=96:eval=frame,crop={width}:{height}" - ); - let pix_fmt = if depth == 10 { - "yuv420p10le" - } else { - "yuv420p" - }; - let mut ff_args: Vec<&str> = vec![ - "-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", pix_fmt, - ]; - // y4m has no official 10-bit tag, same as the 10-bit gate above. - if depth == 10 { - ff_args.extend(["-strict", "-1"]); - } - let duration_arg = duration.to_string(); - ff_args.extend(["-t", &duration_arg, "-f", "yuv4mpegpipe", "-"]); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args(&ff_args) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let bit_depth = format!("--bit-depth={depth}"); - let input_bit_depth = format!("--input-bit-depth={depth}"); - let args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=45", - "--cpu-used=0", - "--kf-max-dist=1000", - "--threads=1", - "--row-mt=0", - "--auto-alt-ref=0", - "--lag-in-frames=0", - "--enable-fwd-kf=0", - "--enable-order-hint=1", - "--enable-global-motion=1", - "--enable-warped-motion=0", - "--enable-obmc=0", - "--tune-content=default", - "--enable-masked-comp=0", - "--enable-interintra-comp=0", - "--enable-onesided-comp=0", - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-tx-size-search=0", - "--enable-cdef=0", - "--enable-restoration=0", - "--max-partition-size=32", - "--min-partition-size=32", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - "--enable-ref-frame-mvs=0", - &bit_depth, - &input_bit_depth, - "--obu", - "-o", - "-", - "-", - ]; - let out = run_with_stdin(Command::new(affine_aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let before = crate::decode::affine_gm_hits(); - let frames = - decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME} ({depth}-bit): {e}")); - let ffmpeg_frames = if depth == 10 { - ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count) - } else { - ffmpeg_decode_sequence(&stream, width, height, frame_count) - }; - assert_eq!(frames.len(), frame_count); - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!(got.y, want.y, "{NAME} {depth}-bit frame {i} luma vs ffmpeg"); - assert_eq!(got.u, want.u, "{NAME} {depth}-bit frame {i} U vs ffmpeg"); - assert_eq!(got.v, want.v, "{NAME} {depth}-bit frame {i} V vs ffmpeg"); - } - let hits = crate::decode::affine_gm_hits() - before; - assert!( - hits > 0, - "{NAME} ({depth}-bit): decoded pixel-exact but no block was predicted through a \ - 6-parameter global-motion warp -- the AFFINE path is unexercised" - ); - eprintln!( - "{NAME}: {depth}-bit, {frame_count} frames pixel-exact, affine_gm_hits={hits}" - ); - } - } - - /// lane-av1gwarp12: the SINGLE-reference GLOBAL-warp witness at 12 bits - /// -- the open half lane-av112bitw recorded (engagement 0 on every prior - /// 12-bit content). The decode path is the same `warp_affine` with - /// `warp_round_0(12)` the local-warp witness proved, fed by - /// `global_warp_params(gm_ref.params)` at `decode_inter_block`'s - /// single-ref arm -- but composition had no stream: the travelling-box - /// source fits only TRANSLATION global models (excluded by - /// `is_global_mv_block`), and the rotating mandelbrot reached the global - /// models only on compound blocks. This recipe closes it: rotation + - /// uniform zoom (a similarity transform, ROTZOOM's exact family), the - /// compound tools off so a global model can only ride a single-reference - /// GLOBALMV block, and partitions pinned to 32 so the 8x8 leaf arm is - /// structurally out of the stream. Vanilla aomenc pins its gm search to - /// ROTZOOM (`global_motion_facade.c:24`), so every >TRANSLATION model a - /// real aomenc emits is ROTZOOM; AFFINE needs the widened side build - /// (`a_real_affine_global_motion_stream_decodes_pixel_exact`). - /// - /// Non-vacuous by construction: `rotzoom_gm_warp_hits()` hard-asserts a - /// 16x16+ block was really predicted through the global warp with a - /// ROTZOOM model, the zero `compound_warp_hits` delta keeps the - /// single-reference premise honest, and every plane of every frame - /// compares against ffmpeg. - #[test] - fn a_real_rotzoom_global_warp_12bit_stream_decodes_pixel_exact() { - const NAME: &str = "a_real_rotzoom_global_warp_12bit_stream_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - const W: usize = 128; - const H: usize = 128; - const FRAMES: usize = 16; - let y4m = y4m_12bit_rotzoom_gm_source(FRAMES); - let stream = encode_12bit( - &y4m, - FRAMES, - &[ - "--enable-global-motion=1", - "--enable-warped-motion=0", - "--enable-obmc=0", - "--enable-masked-comp=0", - "--enable-interintra-comp=0", - "--enable-onesided-comp=0", - "--enable-ref-frame-mvs=0", - "--min-partition-size=32", - "--max-partition-size=32", - ], - ); - assert_12bit_sequence_header(&stream, NAME); - let (before_rotzoom, before_affine, before_selected, before_compound) = ( - decode::rotzoom_gm_warp_hits(), - decode::affine_gm_hits(), - decode::warp_selected_hits(), - decode::compound_warp_hits(), - ); - let frames = decode_stream(&stream).unwrap_or_else(|e| { - panic!("{NAME}: decode_stream refused a real 12-bit global-warp stream: {e}") - }); - assert_eq!(frames.len(), FRAMES); - let (delta_rotzoom, delta_affine, delta_selected) = ( - decode::rotzoom_gm_warp_hits() - before_rotzoom, - decode::affine_gm_hits() - before_affine, - decode::warp_selected_hits() - before_selected, - ); - eprintln!( - "{NAME}: gm_warp_engagement rotzoom(single-ref global warp)={delta_rotzoom} \ - affine={delta_affine} selected_local_warp={delta_selected}" - ); - assert!( - delta_rotzoom > 0, - "{NAME}: decoded but no single-reference ROTZOOM global-warp block fired -- \ - the 12-bit single-ref global-warp path is unexercised and the pixel \ - compare would prove nothing" - ); - assert_eq!( - decode::compound_warp_hits() - before_compound, - 0, - "{NAME}: a compound warp block ran -- the single-reference premise is gone" - ); - let ffmpeg_frames = ffmpeg_decode_sequence_12bit(&stream, W, H, FRAMES); - for (i, (ours, reference)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!(ours.y, reference.y, "{NAME} frame {i} luma vs ffmpeg"); - assert_eq!(ours.u, reference.u, "{NAME} frame {i} U vs ffmpeg"); - assert_eq!(ours.v, reference.v, "{NAME} frame {i} V vs ffmpeg"); - } - eprintln!( - "{NAME}: {FRAMES} frames pixel-exact vs ffmpeg, rotzoom_gm_warp_hits={delta_rotzoom}" - ); - } - - /// lane-gmaffine r1 item (3): `GLOBALMV` at an 8x8 leaf, ROTZOOM global - /// motion, warp built from the frame's own model. - #[test] - fn a_real_globalmv_8x8_leaf_stream_decodes_pixel_exact() { - const NAME: &str = "a_real_globalmv_8x8_leaf_stream_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - run_8x8_leaf_motion_gate(NAME, true, crate::decode::globalmv_hits_8); - } - - /// lane-gmaffine r1 item (2): `WARPED_CAUSAL` at an 8x8 leaf -- - /// findSamples + `av1_find_projection` + the warp filter at BLOCK_8X8. - #[test] - fn a_real_warped_causal_8x8_leaf_stream_decodes_pixel_exact() { - const NAME: &str = "a_real_warped_causal_8x8_leaf_stream_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - run_8x8_leaf_motion_gate(NAME, false, crate::decode::warp_hits_8); - } - - /// lane-rect16 r1/r2: a plain default-settings aomenc run over lavfi - /// `mandelbrot` (`--cpu-used=4 --end-usage=q --cq-level=32`, no - /// `--enable-*` flags) used to refuse frame 0 outright with "a partition - /// below 16x16 other than a clean split". r1 root-caused the FIRST hit to - /// a `PARTITION_VERT_B` `partition_w16` symbol at mi=(3,2) and wired it - /// (left 8x16 real `decode_block_rect` strip + two stacked 8x8 - /// `decode_leaf8` leaves on the right). r2 re-measured after that fix - /// (`decision-before-quantiser`-shaped: don't trust a stale premise) and - /// found this stream's REAL first-hit blocker in z-order is earlier, at - /// mi=(0,7): a plain `PARTITION_HORZ`. That arm is now wired too - /// (`decode_leaf_rect`, sibling to `decode_leaf8` but real-mi-addressed - /// for a non-square strip) -- `horz_vert_intra_hits` proves it fires. - /// This exact stream's own HORZ block at mi=(0,7) is *coded* (real - /// coefficients), which is NOT ported (same ceiling as VERT_B's own - /// non-skip refusal -- no rectangular-transform coefficient tables at - /// this size), so decode still stops there and `vert_b_intra_hits` - /// never gets a chance to increment on this particular stream. This gate - /// proves the HORZ arm fires and the OLD (now-false) two-clause refusal - /// never reappears, not a pixel-exact decode of this stream. - #[test] - fn a_real_aomenc_stream_with_mandelbrot_fires_the_vert_b_partition_arm() { - const NAME: &str = "a_real_aomenc_stream_with_mandelbrot_fires_the_vert_b_partition_arm"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height) = (192usize, 128usize); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &format!("mandelbrot=size={width}x{height}"), - "-pix_fmt", - "yuv420p", - "-t", - "1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let out = run_with_stdin( - Command::new(aomenc_path()).args([ - "--threads=1", - "--row-mt=0", - "--sb-size=64", - "--cpu-used=4", - "--end-usage=q", - "--cq-level=32", - "--passes=1", - "--obu", - "-o", - "-", - "-", - ]), - &y4m.stdout, - ); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - // lane-rect16 r2: the recipe above was missing `--passes=1` -- - // without it aomenc silently ran 2-pass and wrote nothing to stdout - // on pass 1 (still exit 0), so this gate always decoded an EMPTY - // stream and never actually exercised the arm it claims to gate. - assert!( - !stream.is_empty(), - "{NAME}: aomenc wrote an empty stream (missing --passes=1?)" - ); - let result = decode_stream(&stream); - // The now-lifted false claim ("codes only the square arms below - // 16x16") must never appear again. - if let Err(e) = &result { - let msg = e.to_string(); - assert!( - !msg.contains("this decoder codes only the square arms below 16x16"), - "{NAME}: the OLD (disproved) refusal reappeared: {msg}" - ); - } - assert!( - crate::decode::horz_vert_intra_hits() > 0, - "{NAME}: the plain PARTITION_HORZ/VERT arm never fired on this stream (regression -- \ - it fired deterministically at mi=(0,7) when this gate was written)" - ); - eprintln!( - "{NAME}: horz_vert_intra_hits={}, vert_b_intra_hits={}, decode result: {:?}", - crate::decode::horz_vert_intra_hits(), - crate::decode::vert_b_intra_hits(), - result.as_ref().map(|f| f.len()).map_err(|e| e.to_string()) - ); - } - - /// lane-rectx r3: a real `aomenc` stream whose 16x16-level - /// `PARTITION_HORZ`/`PARTITION_VERT` strips are CODED (non-skip), i.e. - /// carry genuine `TX_16X8`/`TX_8X16` luma coefficients and their - /// `TX_8X4`/`TX_4X8` chroma halves through [`decode_leaf_rect`]'s - /// lane-rectx arm -- the refusal "a coded (non-skip) HORZ/VERT rect strip - /// below 16x16" this round lifts. `--min-partition-size=8 - /// --max-partition-size=32 --enable-rect-partitions=1` is what makes - /// aomenc reach for a 16x8 leaf at all; mandelbrot at `cq-level=24` is - /// what makes those leaves non-skip (a gradient fixture codes them all - /// away). `--reduced-tx-type-set=1` pins the five-symbol - /// `EXT_TX_SET_DTT4_IDTX` alphabet: without it aomenc also writes - /// `V_DCT`/`H_DCT`, whose 1D tx classes [`read_coeffs_rect`] still - /// refuses by name (see the r3 report's open residue), so a `=0` run - /// would prove nothing about the 2D path it does support. - /// - /// r2 shipped this path unproven; it was wrong. `TxbSet::LumaRect16x8` - /// read its `tx_type` symbol from the 16x16 row, but libaom's - /// `read_tx_type` indexes `intra_ext_tx_cdf[eset][txsize_sqr_map[tx_size]]` - /// and `txsize_sqr_map[TX_16X8] == TX_8X8` -- a five-symbol CDF where a - /// seven-symbol one belonged, desyncing at the FIRST coded rect leaf - /// (whole frame wrong from pixel (0,0)). - #[test] - fn a_real_aomenc_stream_with_a_coded_rect_strip_below_16x16_decodes_pixel_exact() { - const NAME: &str = - "a_real_aomenc_stream_with_a_coded_rect_strip_below_16x16_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height) = (64usize, 64usize); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &format!("mandelbrot=size={width}x{height}:start_x=-0.6"), - "-pix_fmt", - "yuv420p", - "-t", - "1", - "-vframes", - "1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let encode = || { - let out = run_with_stdin( - Command::new(aomenc_path()).args([ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=16", - "--cpu-used=4", - "--threads=1", - "--row-mt=0", - "--sb-size=64", - "--kf-max-dist=0", - "--enable-rect-partitions=1", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-tx-size-search=0", - // Filter intra on a strip is a separate, still-refused - // predictor (`filter intra on a HORZ/VERT strip`); this - // gate is about the rect RESIDUAL path, so it is off here - // and covered by the square filter-intra gate instead. - "--enable-filter-intra=0", - "--reduced-tx-type-set=1", - "--min-partition-size=8", - "--max-partition-size=32", - "--obu", - "-o", - "-", - "-", - ]), - &y4m.stdout, - ); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - out.stdout - }; - // The fixture rule: an encoder output is only a pin if it reproduces. - let stream = encode(); - assert_eq!( - stream, - encode(), - "{NAME}: aomenc output is not reproducible for this recipe" - ); - let before = crate::decode::rect_leaf_coeff_hits(); - let frames = decode_stream(&stream) - .unwrap_or_else(|e| panic!("{NAME}: decode failed, not a pixel mismatch: {e}")); - let fired = crate::decode::rect_leaf_coeff_hits() - before; - assert!( - fired > 0, - "{NAME}: the stream decoded but no coded (non-skip) rect leaf fired -- \ - the gate proves nothing" - ); - // The ENCODE's frame count, asserted ABOVE the oracle call: the y4m is - // rendered with `-t 1` and `-vframes 1` (27566) -- one frame at the - // source's default rate 25 -- and aomenc runs with no `--limit` and - // `--kf-max-dist=0` (27593), so the stream codes exactly 1 frame. - assert_eq!(frames.len(), 1, "{NAME}: expected one key frame"); - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frames.len()); - assert_eq!( - ffmpeg_frames.len(), - frames.len(), - "{NAME}: ffmpeg frame count" - ); - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!( - got.y, want.y, - "{NAME} frame {i} luma vs ffmpeg ({fired} coded rect leaves)" - ); - assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg"); - assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg"); - } - eprintln!("{NAME}: pixel-exact, rect_leaf_coeff_hits={fired}"); - } - - /// lane-rectx r5: the same 16x8/8x16 rect leaves, but this time proving - /// what a LATER, non-strip block reads from them. `decode_leaf_rect` took - /// the mi-exact intra mode map in r4; `decode_block`/`decode_block_rect`/ - /// `decode_block_rect64` did not, so a 32x16 strip whose left neighbour was - /// a 16x8 leaf still read the coarse per-16x16 `left_mode` slot -- which no - /// sub-16x16 block ever writes -- and picked a DIFFERENT `kf_y_mode` CDF row - /// for the same decoded mode value. The stream stayed in sync through mode - /// info (`EC_TRACE_MODE_STEP` ranges match up to that symbol) and then - /// diverged inside the block's own coefficients: the whole bottom-right - /// 32x32 quadrant of this fixture decoded wrong (1650 bytes) while the - /// three earlier quadrants were exact -- wrong pixels returned as success. - /// `mode_mi_override_hits` counts exactly the reads where the mi-exact - /// neighbour disagrees with the coarse slot, so a regression that drops the - /// override again fails the counter as well as the pixels. - #[test] - fn a_real_aomenc_stream_whose_square_block_reads_a_sub16_neighbours_mode_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_stream_whose_square_block_reads_a_sub16_neighbours_mode_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height) = (64usize, 64usize); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &format!("rgbtestsrc=size={width}x{height}"), - "-pix_fmt", - "yuv420p", - "-t", - "1", - "-vframes", - "1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - // Two swept cells of the r4 sweep that decoded to completion with - // WRONG pixels (1714 and 1650 bytes): `--reduced-tx-type-set` and - // `--enable-filter-intra` are the two axes that move which block sizes - // aomenc reaches for here; both arms are pinned. - let mut total_overrides = 0usize; - for (rtx, filter_intra) in [("1", "0"), ("0", "1")] { - let encode = || { - let out = run_with_stdin( - Command::new(aomenc_path()).args([ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=32", - "--cpu-used=4", - "--threads=1", - "--row-mt=0", - "--sb-size=64", - "--kf-max-dist=0", - "--enable-rect-partitions=1", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-tx-size-search=0", - "--enable-cdef=0", - "--enable-restoration=0", - &format!("--enable-filter-intra={filter_intra}"), - &format!("--reduced-tx-type-set={rtx}"), - "--min-partition-size=8", - "--max-partition-size=32", - "--obu", - "-o", - "-", - "-", - ]), - &y4m.stdout, - ); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - out.stdout - }; - let stream = encode(); - assert_eq!( - stream, - encode(), - "{NAME}: aomenc output is not reproducible (rtx={rtx} filter_intra={filter_intra})" - ); - let before = crate::decode::mode_mi_override_hits(); - let frames = decode_stream(&stream).unwrap_or_else(|e| { - panic!("{NAME}: decode failed (rtx={rtx} filter_intra={filter_intra}): {e}") - }); - // Counted only on an attempt that actually decoded AND is compared - // below -- a refusal never contributes to the firing assert. - let overrides = crate::decode::mode_mi_override_hits() - before; - // The ENCODE's frame count, asserted ABOVE the oracle call: the y4m is - // rendered ONCE outside this loop with `-t 1` and `-vframes 1` - // (27792) -- one frame at the source's default rate 25 -- and aomenc - // runs with no `--limit` and `--kf-max-dist=0` (27726), so both - // (rtx, filter_intra) arms code exactly 1 frame. - assert_eq!(frames.len(), 1, "{NAME}: expected one key frame"); - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frames.len()); - assert_eq!( - ffmpeg_frames.len(), - frames.len(), - "{NAME}: ffmpeg frame count" - ); - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!( - got.y, want.y, - "{NAME} frame {i} luma vs ffmpeg (rtx={rtx} filter_intra={filter_intra}, \ - {overrides} mi-exact mode overrides)" - ); - assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (rtx={rtx})"); - assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (rtx={rtx})"); - } - total_overrides += overrides; - } - assert!( - total_overrides > 0, - "{NAME}: no non-strip block ever read a mi-exact neighbour that disagreed with its \ - coarse slot -- the gate proves nothing" - ); - eprintln!("{NAME}: pixel-exact, mode_mi_override_hits={total_overrides}"); - } - - /// lane-cfl r1: the chroma intra-edge FILTER TYPE is the neighbour's - /// `uv_mode` (libaom `get_filt_type`, reconintra.c: `chroma_above_mbmi`/ - /// `chroma_left_mbmi` -> `is_smooth` on `uv_mode`), and two whole decode - /// paths passed a hardcoded `false` for it -- `decode_leaf_8x8` (every - /// 8x8 leaf of a SPLIT) and `decode_leaf_rect` (every rect strip below - /// 16x16), on a stale "chroma stays false (exact) until a smooth/paeth - /// uv_mode can reach decode at all" comment. On top of that the coarse - /// `above_uv_mode`/`left_uv_mode` cells are 16px-granular and their - /// `for cell in 0..w / SUB` write runs ZERO times for any block below - /// 16x16, so even the paths that DID read them saw whatever a - /// 16x16-or-larger block had left there (class: context read from one - /// cell / neighbour map at the wrong granularity). Result on this - /// recipe: luma byte-exact, entropy ladder identical, and 40 U + 86 V - /// chroma bytes wrong -- every one of them downstream of one 4x4 chroma - /// block at mi(8,12) whose D135 + `angle_delta_uv=-3` left edge was - /// filtered at the wrong strength (`ft=0` where the instrumented aomdec - /// prints `ft=1`, left edge `95,59,30,28` vs `90,61,37,29`). - /// - /// Both arms hard-assert per-attempt counters for the two chroma block - /// shapes involved (`UV_CFL_PRED` blocks, nonzero `angle_delta_uv` - /// blocks) plus the mi-exact UV-neighbour override, and are counted only - /// on an attempt that decoded AND is pixel-compared. - #[test] - fn a_real_aomenc_stream_whose_chroma_edge_filter_reads_a_sub16_neighbours_uv_mode_decodes_pixel_exact() - { - const NAME: &str = "a_real_aomenc_stream_whose_chroma_edge_filter_reads_a_sub16_neighbours_uv_mode_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let mut compared = 0usize; - let (width, height) = (64usize, 64usize); - // 8-bit arm = the r5 residue cell ("mandfi161"); 10-bit arm = its - // twin through the same recipe at `--bit-depth=10`. - for depth in [8usize, 10] { - let pix = if depth == 10 { - "yuv420p10le" - } else { - "yuv420p" - }; - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &format!("mandelbrot=size={width}x{height}:start_x=-0.6"), - "-pix_fmt", - pix, - "-strict", - "-1", - "-t", - "1", - "-vframes", - "1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "{NAME}: ffmpeg fixture (depth={depth}): {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let encode = || { - let out = run_with_stdin( - Command::new(aomenc_path()).args([ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=16", - "--cpu-used=4", - "--threads=1", - "--row-mt=0", - "--sb-size=64", - "--kf-max-dist=0", - "--enable-rect-partitions=1", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-tx-size-search=0", - "--enable-filter-intra=1", - "--reduced-tx-type-set=1", - "--min-partition-size=8", - "--max-partition-size=32", - &format!("--input-bit-depth={depth}"), - &format!("--bit-depth={depth}"), - "--obu", - "-o", - "-", - "-", - ]), - &y4m.stdout, - ); - assert!( - out.status.success(), - "aomenc refused the fixture (depth={depth}): {}", - String::from_utf8_lossy(&out.stderr) - ); - out.stdout - }; - let stream = encode(); - assert_eq!( - stream, - encode(), - "{NAME}: aomenc output is not reproducible (depth={depth})" - ); - let before_cfl = crate::decode::cfl_block_hits(); - let before_angle = crate::decode::uv_angle_delta_hits(); - let before_uv = crate::decode::uv_mode_mi_override_hits(); - let frames = match decode_stream(&stream) { - Ok(frames) => frames, - // Only a NAMED refusal is tolerated (COMMON rule): the 10-bit - // twin of this recipe still stops at another lane's open - // sub-16 AB-partition / strip-filter-intra refusals, so it - // cannot be compared yet. Any other error is a failure, and - // `compared` below keeps the test from passing vacuously. - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME}: decode failed (depth={depth}): {msg}" - ); - eprintln!("{NAME}: depth={depth} arm refused (not compared): {msg}"); - continue; - } - }; - compared += 1; - // Read only on an attempt that decoded AND is compared below. - let cfl_blocks = crate::decode::cfl_block_hits() - before_cfl; - let angle_blocks = crate::decode::uv_angle_delta_hits() - before_angle; - let uv_overrides = crate::decode::uv_mode_mi_override_hits() - before_uv; - // The ENCODE's frame count, asserted ABOVE the oracle call: the y4m is - // rendered with `-t 1` and `-vframes 1` (27852) -- one frame at the - // source's default rate 25 -- and aomenc runs with no `--limit` and - // `--kf-max-dist=0` (27890), so both depths code exactly 1 frame. - assert_eq!( - frames.len(), - 1, - "{NAME}: expected one key frame (depth={depth})" - ); - let ffmpeg_frames = if depth == 10 { - ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len()) - } else { - ffmpeg_decode_sequence(&stream, width, height, frames.len()) - }; - assert_eq!( - ffmpeg_frames.len(), - frames.len(), - "{NAME}: ffmpeg frame count" - ); - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!( - got.y, want.y, - "{NAME} frame {i} luma vs ffmpeg (depth={depth})" - ); - assert_eq!( - got.u, want.u, - "{NAME} frame {i} U vs ffmpeg (depth={depth}, {cfl_blocks} CFL blocks, \ - {angle_blocks} nonzero-angle_delta_uv blocks, {uv_overrides} mi-exact UV \ - neighbour overrides)" - ); - assert_eq!( - got.v, want.v, - "{NAME} frame {i} V vs ffmpeg (depth={depth}, {cfl_blocks} CFL blocks, \ - {angle_blocks} nonzero-angle_delta_uv blocks, {uv_overrides} mi-exact UV \ - neighbour overrides)" - ); - } - assert!( - cfl_blocks > 0, - "{NAME}: no UV_CFL_PRED block decoded (depth={depth}) -- the gate proves nothing" - ); - assert!( - angle_blocks > 0, - "{NAME}: no nonzero angle_delta_uv chroma block decoded (depth={depth}) -- \ - the chroma intra-edge filter path never ran" - ); - assert!( - uv_overrides > 0, - "{NAME}: no chroma edge-filter read ever took a mi-exact UV neighbour that \ - disagreed with its coarse 16x16 slot (depth={depth}) -- the r1 defect is \ - not exercised" - ); - eprintln!( - "{NAME}: pixel-exact at {depth}-bit, cfl_blocks={cfl_blocks} \ - angle_delta_uv_blocks={angle_blocks} uv_mi_overrides={uv_overrides}" - ); - } - assert!( - compared > 0, - "{NAME}: every arm refused -- the gate compared no pixels at all" - ); - } - - /// lane-reelckf r1: ReelC's key frames decoded with no refusal and WRONG - /// CHROMA (luma bit-exact at every one of ten seek points), from two - /// defects this gate pins: - /// - /// 1. a SKIPPED intra block whose `uv_mode` is `UV_CFL_PRED` still - /// predicts with the CfL term -- libaom - /// `predict_and_reconstruct_intra_block` (decodeframe.c) calls - /// `av1_predict_intra_block_facade` unconditionally and only guards - /// the residual on `mbmi->skip_txfm`. Three skip arms (the 16x16-level - /// 1:4 chroma pair and the two sub-8x8 4x4 groups) dropped it. - /// 2. the chroma intra-edge FILTER TYPE of a 1:4 pair comes from the - /// CHROMA REFERENCE position (libaom `get_intra_edge_filter_type` -> - /// `chroma_above_mbmi`/`chroma_left_mbmi`), not from the closing - /// strip: at the closing strip the above cell is the pair's own first - /// strip, the mi-exact UV map misses and the coarse fallback answers, - /// which flipped `av1_use_intra_edge_upsample` (blk_wh 12 <= 16 for - /// type 0, no upsample for type 1) and moved directional chroma by - /// +-1..3. - /// - /// Recipe is a real `aomenc --sb-size=128 --cpu-used=0` (the shape ReelC - /// uses) with 1:4 partitions and CfL on, both bit depths, and both - /// counters hard-asserted per compared attempt. - #[test] - fn a_real_aomenc_sb128_stream_whose_skipped_cfl_and_1to4_chroma_pairs_decode_pixel_exact() { - const NAME: &str = - "a_real_aomenc_sb128_stream_whose_skipped_cfl_and_1to4_chroma_pairs_decode_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let mut compared = 0usize; - let (width, height) = (256usize, 256usize); - for depth in [8usize, 10] { - let pix = if depth == 10 { - "yuv420p10le" - } else { - "yuv420p" - }; - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &format!( - "mandelbrot=size={width}x{height},\ - noise=alls=20:allf=t+u:all_seed=7" - ), - "-pix_fmt", - pix, - "-strict", - "-1", - "-t", - "1", - "-vframes", - "1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "{NAME}: ffmpeg fixture (depth={depth}): {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let encode = || { - let out = run_with_stdin( - Command::new(aomenc_path()).args([ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=52", - "--cpu-used=0", - "--threads=1", - "--row-mt=0", - "--sb-size=128", - "--kf-max-dist=0", - "--enable-rect-partitions=1", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=1", - "--enable-cfl-intra=1", - "--enable-tx-size-search=0", - "--enable-filter-intra=0", - "--enable-intra-edge-filter=1", - "--reduced-tx-type-set=1", - "--min-partition-size=4", - "--max-partition-size=32", - &format!("--input-bit-depth={depth}"), - &format!("--bit-depth={depth}"), - "--obu", - "-o", - "-", - "-", - ]), - &y4m.stdout, - ); - assert!( - out.status.success(), - "aomenc refused the fixture (depth={depth}): {}", - String::from_utf8_lossy(&out.stderr) - ); - out.stdout - }; - let stream = encode(); - assert_eq!( - stream, - encode(), - "{NAME}: aomenc output is not reproducible (depth={depth})" - ); - let before = crate::decode::reelc_chroma_counters(); - let frames = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME}: decode failed (depth={depth}): {msg}" - ); - eprintln!("{NAME}: depth={depth} arm refused (not compared): {msg}"); - continue; - } - }; - compared += 1; - // Counters read only on an attempt that decoded AND is compared. - let after = crate::decode::reelc_chroma_counters(); - let (skip_cfl, dir_pairs) = (after.0 - before.0, after.1 - before.1); - // The ENCODE's frame count: the y4m is rendered with `-t 1` and - // `-vframes 1` (28056) -- one frame at the source's default rate 25 - // -- and aomenc runs with no `--limit` and `--kf-max-dist=0` - // (28088), so both depths code exactly 1 frame. Asserted ABOVE the - // oracle call. - assert_eq!(frames.len(), 1, "{NAME}: depth={depth} key frame"); - let ffmpeg_frames = if depth == 10 { - ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len()) - } else { - ffmpeg_decode_sequence(&stream, width, height, frames.len()) - }; - assert_eq!( - ffmpeg_frames.len(), - frames.len(), - "{NAME}: ffmpeg frame count" - ); - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!(got.y, want.y, "{NAME} frame {i} luma (depth={depth})"); - assert_eq!( - got.u, want.u, - "{NAME} frame {i} U (depth={depth}, {skip_cfl} skipped-CfL blocks, \ - {dir_pairs} directional 1:4 chroma pairs)" - ); - assert_eq!( - got.v, want.v, - "{NAME} frame {i} V (depth={depth}, {skip_cfl} skipped-CfL blocks, \ - {dir_pairs} directional 1:4 chroma pairs)" - ); - } - // Defect 1 (skipped `UV_CFL_PRED`) is NOT asserted here: 20 aomenc - // recipes (cq 40..63, 9 lavfi sources, min/max-partition 4..64, - // both `--sb-size=128` and 64) never made the encoder pick a - // skipped 1:4 / sub-8x8 CfL block, so an assert would only ever - // fire on his real film. Its evidence is ReelC's own key frames - // (lanes/reelckf-r1.report.md): ss=2700 went 499 wrong chroma - // samples -> 0 on this fix alone. The count is printed so a future - // recipe that does reach it is visible immediately. r2 pinned that - // film frame as a fixture instead: - // `a_real_film_key_frame_with_a_skipped_cfl_block_decodes_pixel_exact` - // hard-asserts the counter. - assert!( - dir_pairs > 0, - "{NAME}: no directional 1:4 chroma pair decoded (depth={depth}) -- defect 2 \ - is not exercised" - ); - eprintln!( - "{NAME}: pixel-exact at {depth}-bit over {} frames, skipped_cfl={skip_cfl} \ - directional_1to4_chroma_pairs={dir_pairs}", - frames.len() - ); - } - assert!( - compared > 0, - "{NAME}: every arm refused -- the gate compared no pixels at all" - ); - } - - /// lane-ab16 r1: real `aomenc --enable-ab-partitions=1` streams whose - /// 16x16 blocks are split T-shaped (`PARTITION_HORZ_A`/`_HORZ_B`/ - /// `_VERT_A`/`_VERT_B`: two 8x8 squares plus one 16x8/8x16 strip), the - /// refusals "a HORZ_A/HORZ_B/VERT_A partition below 16x16" and "a coded - /// (non-skip) HORZ_B/VERT_B rect strip below 16x16" this round lifts. - /// `--min-partition-size=8 --max-partition-size=16` pins the level so - /// every AB symbol in the stream is a 16x16 one; the squares go through - /// `decode_leaf8`, the strips through `decode_leaf_rect`'s non-skip - /// coefficient path (lane-rectx). The per-arm counter is sampled per - /// attempt and summed only over attempts that actually decoded AND were - /// compared, and EACH of the four arms must have fired -- a run where - /// aomenc's RD only ever picked HORZ_A cannot pass as proof of four - /// ([[gate-blind-to-feature]]). 8-bit and 10-bit; `--tile-columns=1` is - /// NOT among the attempts (base tile defect, reproducer in the r1 - /// report), and `--enable-tx-size-search` is left at aomenc's default - /// (ON) -- pinning it off hid a panic in the TX4 sub-grid of an 8x8 - /// square inside a `PARTITION_VERT_A`/`_B` (r2). - #[test] - fn a_real_aomenc_stream_with_ab_partitions_below_16x16_decodes_pixel_exact() { - const NAME: &str = - "a_real_aomenc_stream_with_ab_partitions_below_16x16_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - struct Attempt { - src: &'static str, - w: usize, - h: usize, - cq: u32, - ten_bit: bool, - tile_cols: u32, - /// Left at aomenc's default (ON) instead of pinned off: reaches - /// the TX4 sub-grid of an 8x8 square inside a - /// `PARTITION_VERT_A`/`_B` (r2's panic), at the cost of the - /// strip-level split transform lane-rectx still refuses. - tx_size_search: bool, - } - // Recipes chosen by a ~200-cell sweep of {source, size, cq} at this - // level (r1 report): one cell per arm that is pixel-exact end to end, - // plus two 10-bit cells. `--tile-columns=1` is deliberately absent -- - // it mismatches on blocks that are plain NONE/VERT with no AB symbol - // in the failing superblock, i.e. a base tile defect this lane - // neither introduced nor owns (reproducer pinned in the r1 report). - let attempts = [ - Attempt { - src: "yuvtestsrc=size=64x64", - w: 64, - h: 64, - cq: 22, - ten_bit: false, - tile_cols: 0, - tx_size_search: false, - }, - Attempt { - src: "rgbtestsrc=size=64x64", - w: 64, - h: 64, - cq: 20, - ten_bit: false, - tile_cols: 0, - tx_size_search: false, - }, - Attempt { - src: "rgbtestsrc=size=64x64", - w: 64, - h: 64, - cq: 50, - ten_bit: false, - tile_cols: 0, - tx_size_search: false, - }, - Attempt { - src: "mandelbrot=size=64x64:start_x=-1.0", - w: 64, - h: 64, - cq: 14, - ten_bit: false, - tile_cols: 0, - tx_size_search: false, - }, - // 10-bit: the only two cells of the sweep that are exact at this - // depth (HORZ_A and VERT_A); the 10-bit HORZ_B/VERT_B cells all - // trip the base chroma defect the r1 report pins, so those two - // arms are proven 8-bit only. - Attempt { - src: "yuvtestsrc=size=64x64", - w: 64, - h: 64, - cq: 30, - ten_bit: true, - tile_cols: 0, - tx_size_search: false, - }, - Attempt { - src: "mandelbrot=size=64x64:start_x=0.4", - w: 64, - h: 64, - cq: 30, - ten_bit: true, - tile_cols: 0, - tx_size_search: false, - }, - // `--enable-tx-size-search` at aomenc's default: an 8x8 square of - // a VERT_A/VERT_B resolves to a 2x2 grid of TX4 units, which is - // the reach lookup that had no table row and panicked (r2). These - // attempts may legitimately stop at lane-rectx's still-standing - // "strip with a split transform" refusal -- an `unsupported` - // message is tolerated, a panic or a pixel mismatch is not, and - // at least one of them must reach a TX4 unit inside a vertical AB - // partition. - Attempt { - src: "yuvtestsrc=size=64x64", - w: 64, - h: 64, - cq: 55, - ten_bit: false, - tile_cols: 0, - tx_size_search: true, - }, - Attempt { - src: "yuvtestsrc=size=64x64", - w: 64, - h: 64, - cq: 22, - ten_bit: false, - tile_cols: 0, - tx_size_search: true, - }, - Attempt { - src: "rgbtestsrc=size=64x64", - w: 64, - h: 64, - cq: 20, - ten_bit: false, - tile_cols: 0, - tx_size_search: true, - }, - Attempt { - src: "mandelbrot=size=64x64:start_x=-1.0", - w: 64, - h: 64, - cq: 14, - ten_bit: false, - tile_cols: 0, - tx_size_search: true, - }, - ]; - let mut arms = [0usize; 4]; - let mut compared = 0usize; - let mut tx4_reached = 0usize; - let mut tx4_compared = 0usize; - for a in &attempts { - let desc = format!( - "{} cq={} {}bit tiles={}", - a.src, - a.cq, - if a.ten_bit { 10 } else { 8 }, - a.tile_cols - ); - let mut ff: Vec = vec![ - "-v".into(), - "error".into(), - "-f".into(), - "lavfi".into(), - "-i".into(), - a.src.into(), - "-pix_fmt".into(), - if a.ten_bit { - "yuv420p10le".into() - } else { - "yuv420p".into() - }, - ]; - if a.ten_bit { - ff.push("-strict".into()); - ff.push("-1".into()); - } - ff.extend([ - "-t".into(), - "1".into(), - "-vframes".into(), - "1".into(), - "-f".into(), - "yuv4mpegpipe".into(), - "-".into(), - ]); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args(&ff) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture {desc}: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let encode = || { - let mut args: Vec = vec![ - "--codec=av1".into(), - "--passes=1".into(), - "--end-usage=q".into(), - format!("--cq-level={}", a.cq), - "--cpu-used=4".into(), - "--threads=1".into(), - "--row-mt=0".into(), - "--sb-size=64".into(), - "--kf-max-dist=0".into(), - "--limit=1".into(), - "--enable-rect-partitions=1".into(), - "--enable-ab-partitions=1".into(), - "--enable-1to4-partitions=0".into(), - format!("--enable-tx-size-search={}", u8::from(a.tx_size_search)), - // Filter intra ON a rect strip is a separate, still-refused - // predictor; this gate is about the AB partition wiring. - "--enable-filter-intra=0".into(), - "--reduced-tx-type-set=1".into(), - "--min-partition-size=8".into(), - "--max-partition-size=16".into(), - format!("--tile-columns={}", a.tile_cols), - ]; - if a.ten_bit { - args.push("--input-bit-depth=10".into()); - args.push("--bit-depth=10".into()); - } - args.extend(["--obu".into(), "-o".into(), "-".into(), "-".into()]); - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused {desc}: {}", - String::from_utf8_lossy(&out.stderr) - ); - out.stdout - }; - let stream = encode(); - assert!( - !stream.is_empty(), - "{NAME}: {desc}: aomenc wrote an empty stream" - ); - assert_eq!( - stream, - encode(), - "{NAME}: {desc}: aomenc output is not reproducible" - ); - let before = crate::decode::ab16_hits_by_arm(); - let tx4_before = crate::decode::vert_ab_tx4_hits(); - let decoded = decode_stream(&stream); - let tx4_this = crate::decode::vert_ab_tx4_hits() - tx4_before; - // Counted even when the attempt later stops at another lane's - // refusal: reaching this lookup at all is what r2 fixed. - tx4_reached += tx4_this; - let frames = match decoded { - Ok(frames) => frames, - // Only lane-rectx's split-transform strip refusal may stop a - // tx-size-search attempt; a panic never reaches here at all. - Err(e) if a.tx_size_search => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME}: {desc}: decode failed with a non-refusal error: {msg}" - ); - eprintln!("{NAME}: {desc} refused after {tx4_this} vert-AB TX4 units: {msg}"); - continue; - } - Err(e) => panic!("{NAME}: {desc}: decode failed, not a pixel mismatch: {e}"), - }; - let after = crate::decode::ab16_hits_by_arm(); - let this: Vec = (0..4).map(|i| after[i] - before[i]).collect(); - eprintln!("{NAME}: {desc} decoded, arms this attempt={this:?}"); - // The ENCODE's frame count: every attempt's y4m is rendered with - // `-t 1` and `-vframes 1` (28367) -- one frame whatever the source's - // rate -- and aomenc carries `--limit=1` (28401), so all six arms - // code exactly 1 frame. Asserted ABOVE the oracle call. - assert_eq!(frames.len(), 1, "{NAME}: {desc} key frame"); - let want = if a.ten_bit { - ffmpeg_decode_sequence_10bit(&stream, a.w, a.h, frames.len()) - } else { - ffmpeg_decode_sequence(&stream, a.w, a.h, frames.len()) - }; - assert_eq!( - want.len(), - frames.len(), - "{NAME}: {desc}: ffmpeg frame count" - ); - for (i, (got, w)) in frames.iter().zip(&want).enumerate() { - assert_eq!(got.y, w.y, "{NAME}: {desc} frame {i} luma vs ffmpeg"); - assert_eq!(got.u, w.u, "{NAME}: {desc} frame {i} U vs ffmpeg"); - assert_eq!(got.v, w.v, "{NAME}: {desc} frame {i} V vs ffmpeg"); - } - // Counted only now: the attempt decoded AND compared exact. - if a.tx_size_search { - tx4_compared += 1; - eprintln!("{NAME}: {desc} pixel-exact, vert-AB TX4 units={tx4_this}"); - continue; - } - for i in 0..4 { - arms[i] += after[i] - before[i]; - } - compared += 1; - eprintln!("{NAME}: {desc} pixel-exact"); - } - assert_eq!( - compared, - attempts.iter().filter(|a| !a.tx_size_search).count(), - "{NAME}: every fixed-transform attempt must decode and compare" - ); - // Until the lane-rectsplitx merge every tx-size-search attempt stopped - // at "a HORZ/VERT intra strip below 16x16 with a split transform", so - // this gate could only claim that the TX4 sub-grid of an 8x8 square - // inside a VERT_A/VERT_B was REACHED (`tx4_reached`, counted even on a - // refused attempt). With per-TU rect prediction those same attempts now - // decode to the end and compare pixel-exact, and they carry no vert-AB - // TX4 unit at all -- the pre-merge nonzero count came from decodes that - // were still desynced when they hit the refusal (class - // counter-from-refused-stream). The full pixel compare is the stronger - // claim and replaces it; the lookup's VALUES stay pinned against libaom - // in `of_tu_keeps_the_ordinary_answer_and_uses_the_block_row_under_vert_ab`. - eprintln!( - "{NAME}: vert-AB TX4 units reached across tx-size-search attempts: {tx4_reached}" - ); - let _ = tx4_reached; - assert_eq!( - tx4_compared, - attempts.iter().filter(|a| a.tx_size_search).count(), - "{NAME}: every --enable-tx-size-search=1 attempt must now decode to the end and \ - compare pixel-exact (the split-transform strip refusal these used to stop at is \ - lifted); the vert-AB TX4 lookup values stay pinned by \ - `of_tu_keeps_the_ordinary_answer_and_uses_the_block_row_under_vert_ab`" - ); - for (i, arm) in ["HORZ_A", "HORZ_B", "VERT_A", "VERT_B"].iter().enumerate() { - assert!( - arms[i] > 0, - "{NAME}: PARTITION_{arm} at 16x16 never fired across {compared} \ - compared streams -- the gate proves nothing about that arm (arms={arms:?})" - ); - } - eprintln!( - "{NAME}: pixel-exact on {compared} streams, ab16 arms(HORZ_A,HORZ_B,VERT_A,VERT_B)={arms:?}" - ); - } - - #[test] - // The recipe SEARCH, not a lane's scratch any more: 9 sources x 7 cq x - // rtx on/off, 28 s measured, and it is the evidence that no aomenc rect-tx - // recipe mismatches -- which is what the un-ignored rect gates rest on. - #[ignore = "recipe search: 9 sources x 7 cq x rtx on/off, 28 s; establishes that no aomenc rect-tx recipe mismatches"] - fn sweep_rectx_recipes() { - let _gate_lock = lock_gate_counters(); - let srcs: Vec = vec![ - "mandelbrot=size=64x64:start_x=0.4".into(), - "mandelbrot=size=64x64:start_x=-0.6".into(), - "mandelbrot=size=64x64:start_x=0.1".into(), - "mandelbrot=size=128x128:start_x=0.4".into(), - "mandelbrot=size=128x128:start_x=-0.6".into(), - "testsrc2=size=64x64".into(), - "testsrc2=size=128x128".into(), - "rgbtestsrc=size=64x64".into(), - "smptebars=size=128x128".into(), - ]; - for start_x in srcs { - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &start_x, - "-pix_fmt", - "yuv420p", - "-t", - "1", - "-vframes", - "1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg"); - assert!(y4m.status.success()); - let (width, height) = if start_x.contains("128x128") { - (128usize, 128usize) - } else { - (64usize, 64usize) - }; - for cq in [16u32, 20, 24, 28, 32, 40, 50] { - for rtx in ["0", "1"] { - let out = run_with_stdin( - Command::new(aomenc_path()).args([ - "--codec=av1", - "--passes=1", - "--end-usage=q", - &format!("--cq-level={cq}"), - "--cpu-used=4", - "--threads=1", - "--row-mt=0", - "--sb-size=64", - "--kf-max-dist=0", - "--enable-rect-partitions=1", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-tx-size-search=0", - "--enable-cdef=0", - "--enable-restoration=0", - &format!("--reduced-tx-type-set={rtx}"), - "--min-partition-size=8", - "--max-partition-size=32", - "--obu", - "-o", - "-", - "-", - ]), - &y4m.stdout, - ); - assert!(out.status.success()); - let stream = out.stdout; - let before = crate::decode::rect_leaf_coeff_hits(); - let res = decode_stream(&stream); - let fired = crate::decode::rect_leaf_coeff_hits() - before; - match res { - Err(e) => { - eprintln!("x={start_x} cq={cq} rtx={rtx} fired={fired} REFUSED {e}") - } - Ok(frames) => { - // The ENCODE's frame count: the y4m is rendered with - // `-t 1` and `-vframes 1` (28747) -- one frame, and - // the sources carry no explicit `:rate=` so that - // `-vframes` is the binding bound -- and aomenc runs - // with `--kf-max-dist=0` and no `--limit` - // (28782), so all 126 arms code exactly 1 frame. - // This sweep asserts no verdict, but `bad` below is - // the NUMBER of mismatching frames it reports, so a - // decode that showed fewer frames than the wire - // would silently under-report it. Pinned here, above - // the oracle call, for that reason. - assert_eq!(frames.len(), 1, "x={start_x} cq={cq} rtx={rtx} key frame"); - let want = ffmpeg_decode_sequence(&stream, width, height, frames.len()); - let bad = frames - .iter() - .zip(&want) - .filter(|(g, w)| g.y != w.y || g.u != w.u || g.v != w.v) - .count(); - eprintln!( - "x={start_x} cq={cq} rtx={rtx} fired={fired} frames={} mismatched={bad}", - frames.len() - ); - if bad == 0 { - continue; - } - let (g, w) = (&frames[0], &want[0]); - for br in 0..height / 8 { - let mut line = String::new(); - for bc in 0..width / 8 { - let mut n = 0; - for row in br * 8..br * 8 + 8 { - for col in bc * 8..bc * 8 + 8 { - if g.y[row * width + col] != w.y[row * width + col] { - n += 1; - } - } - } - line.push_str(&format!("{n:4}")); - } - eprintln!(" blk8 row{br}: {line}"); - } - } - } - } - } - } - } - - /// lane-rectgate r1: every prior gate pins `--enable-rect-partitions=0 - /// --enable-ab-partitions=0 --min/max-partition-size=32` so aomenc never - /// gets to choose a real rect/ab split. This charter's premise ("rect - /// HORZ/VERT + HORZ_A/HORZ_B/VERT_A/VERT_B landed during the warp lane") - /// does NOT hold: `decode_frame`'s inter-tile `match part32` only has - /// arms for `PARTITION_NONE`/`SPLIT`/`HORZ_B` -- `HORZ`, `VERT`, - /// `HORZ_A`, `VERT_A`, `VERT_B`, `HORZ_4`, `VERT_4` all fall into the - /// generic "a partition type this encoder never writes" `_` arm. Two - /// recipes were swept empirically (40 attempts each) to characterize the - /// gap: - /// - `--enable-rect-partitions=1 --enable-ab-partitions=1`, no - /// min/max clamp: 0/40 matched -- every attempt hit either the - /// screen-content refusal or a genuinely-unimplemented partition value - /// (1/2/6/7/9 all observed), always somewhere in the 24-frame stream. - /// - Same, but `--enable-1to4-partitions=0` explicit and - /// `--min-partition-size=16`: still 0/40, `value=9` (`VERT_4`) - /// dominates -- this build's `--enable-1to4-partitions=0` does NOT - /// suppress `VERT_4` selection (aomenc-side, confirmed by direct flag - /// toggle; outside this decoder). This recipe (below) restores the - /// `--enable-rect-partitions=0 --min/max-partition-size=32` pin every - /// other gate uses, flipping only `--enable-ab-partitions=1`: matches - /// cleanly (33/40, rest screen-content refusals) but - /// `extended_partition_hits` stayed 0 -- confirmed with the same probe - /// wired into the already-green warp gate too (144 `warp_selected_hits`, - /// 0 `extended_partition_hits`), so `PARTITION_HORZ_B` itself is - /// apparently never chosen by aomenc for this small gradient fixture at - /// `cq-level=45` regardless of clamp. No decode defect (crash or pixel - /// mismatch) was found in any sweep -- every refusal is a correctly - /// named, non-silent "unsupported" error. A refusal or mismatch naming - /// any OTHER already-ported capability (warp, obmc, interintra) still - /// fails the gate outright. - #[test] - fn a_real_aomenc_stream_with_free_partitions_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_stream_with_free_partitions_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height, frame_count) = (64usize, 64usize, 24usize); - let mut named_refusals = 0u32; - let mut matched = 0u32; - let n_attempts: u32 = std::env::var("EC_RECTGATE_ATTEMPTS") - .ok() - .and_then(|s| s.parse().ok()) - .unwrap_or(40); - for attempt in 0..n_attempts { - let seed = 42 + attempt; - let duration = frame_count as f64 / 25.0; - let source = - gradients_source(seed, width, height, &format!("duration={duration}:rate=25")); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-pix_fmt", - "yuv420p", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=45", - "--cpu-used=0", - "--kf-max-dist=1000", - "--threads=1", - "--row-mt=0", - "--auto-alt-ref=1", - "--lag-in-frames=16", - "--enable-fwd-kf=0", - "--enable-order-hint=1", - "--enable-warped-motion=1", - "--enable-obmc=1", - "--tune-content=default", - "--enable-masked-comp=0", - "--enable-interintra-comp=0", - "--enable-onesided-comp=0", - "--enable-interintra-wedge=0", - "--enable-smooth-interintra=0", - // lane-rect r2: HORZ/VERT decode for real (rect-flake-1 - // byte-exact: size_h + warp dims + OBMC overlap + tx height) - // -- free recipe restored; remaining partition kinds refuse - // by name and skip their seeds. - "--enable-rect-partitions=1", - "--enable-ab-partitions=1", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-tx-size-search=0", - "--enable-cdef=0", - "--enable-restoration=0", - "--max-partition-size=32", - "--min-partition-size=16", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - "--enable-ref-frame-mvs=0", - "--obu", - "-o", - "-", - "-", - ]; - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let frames = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME} failed outright, not a named refusal (seed {seed}): {msg}" - ); - for banned in ["warp", "obmc", "interintra"] { - assert!( - !msg.contains(banned), - "{NAME} refused on {banned} (seed {seed}) -- that capability is \ - ported and this recipe does not need it: {msg}" - ); - } - named_refusals += 1; - eprintln!("seed {seed} refusal: {msg}"); - continue; - } - Ok(frames) => frames, - }; - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count); - assert_eq!(frames.len(), frame_count); - let mismatched = frames - .iter() - .zip(&ffmpeg_frames) - .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); - if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") { - std::fs::write(&path, &stream).expect("writing pinned stream"); - eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}"); - } - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!( - got.y, want.y, - "{NAME} frame {i} luma vs ffmpeg (seed {seed})" - ); - assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})"); - assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})"); - } - // lane-hidden r2 (class gate-blind-to-hidden-frames): the same - // stream again, comparing EVERY decode-order frame -- the hidden - // (show_frame == 0) alt-ref frames the ffmpeg compare above - // cannot see, because both sides of it emit shown frames only. - let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME); - eprintln!( - "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \ - {hidden_n} hidden, all pixel-exact vs the oracle" - ); - // lane-hidden r2 SECOND ARM (the recipe above is untouched): - // libaom's temporal alt-ref filter absorbs this recipe's hidden - // frames, so the compare above is vacuous -- re-encode the same - // fixture with --arnr-maxframes=0 and compare THOSE. - if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) { - eprintln!( - "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \ - decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle" - ); - } - matched += 1; - } - assert!( - matched > 0, - "{NAME}: every attempt refused; the gate never decoded a free-partition stream" - ); - // lane-partitions r1: HORZ/VERT arms landed, so the diversity probe - // graduates from rectgate r1's eprintln to a report line on - // `rect_partition_hits`; a zero-hit run SOFT-reports (aomenc RD may - // legitimately never pick a rect split in a small window -- same - // sampling caveat as the masked-compound gate's zero-hit runs). - // `extended_partition_hits` (HORZ_B) stays unasserted per rectgate r1. - if crate::decode::rect_partition_hits() == 0 { - eprintln!( - "{NAME}: SOFT-NOTE -- zero HORZ/VERT strips fired this run \ - ({matched} matches, {named_refusals} refusals); sampling, not a regression" - ); - } else { - // r5: the desync was the tx-depth symbol being read - // unconditionally where both square paths gate it on `tx_select` - // -- with --enable-tx-size-search=0 the encoder writes no such - // symbol and the decoder consumed one that was never there. With - // that fixed the real coefficient decode is pixel-exact, so this - // is a HARD assert again: strips fired but no coefficients read - // would mean the coded path silently stopped being exercised. - assert!( - crate::decode::rect_coeff_hits() > 0, - "{NAME}: {} HORZ/VERT strips fired but rect_coeff_hits==0 -- the \ - coded rect path is no longer exercised", - crate::decode::rect_partition_hits() - ); - } - eprintln!( - "{NAME}: {named_refusals} named refusals, {matched} pixel-exact matches out of {n_attempts}, rect_partition_hits={} rect_coeff_hits={} extended_partition_hits={} partab_hits={}", - crate::decode::rect_partition_hits(), - crate::decode::rect_coeff_hits(), - crate::decode::extended_partition_hits(), - crate::decode::partab_hits() - ); - } - - /// lane-partab r1: `--enable-ab-partitions=1` (aomenc default-on) INTER - /// streams must consume PARTITION_HORZ_A/VERT_A/VERT_B entropy-exact AND - /// decode pixel-exact -- `partab_hits() > 0` is soft-skipped on a - /// zero-hit run (aomenc RD may legitimately never pick an AB split in a - /// small window, same sampling caveat as wedge/rect). The INTER AB - /// refusal is FORBIDDEN (decode.rs names it "an INTER 32x32 partition - /// ..."); intra-frame AB refusals stay accepted named refusals -- the - /// intra dispatch is a later lane. Recipe = the free-partition gate's, - /// which fires AB live (r1: partab_hits 6/2/4/3/1/5 over six - /// 40-attempt runs). - #[test] - fn a_real_aomenc_stream_with_ab_partitions_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_stream_with_ab_partitions_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height, frame_count) = (64usize, 64usize, 24usize); - let mut named_refusals = 0u32; - let mut matched = 0u32; - let n_attempts: u32 = std::env::var("EC_RECTGATE_ATTEMPTS") - .ok() - .and_then(|s| s.parse().ok()) - .unwrap_or(40); - for attempt in 0..n_attempts { - let seed = 42 + attempt; - let duration = frame_count as f64 / 25.0; - let source = - gradients_source(seed, width, height, &format!("duration={duration}:rate=25")); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-pix_fmt", - "yuv420p", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=45", - "--cpu-used=0", - "--kf-max-dist=1000", - "--threads=1", - "--row-mt=0", - "--auto-alt-ref=1", - "--lag-in-frames=16", - "--enable-fwd-kf=0", - "--enable-order-hint=1", - "--enable-warped-motion=1", - "--enable-obmc=1", - "--tune-content=default", - "--enable-masked-comp=0", - "--enable-interintra-comp=0", - "--enable-onesided-comp=0", - "--enable-interintra-wedge=0", - "--enable-smooth-interintra=0", - // lane-rect r2 recipe, kept byte-identical by lane-partab - // r1: free partition search, 1to4 off, intra tools off. - "--enable-rect-partitions=1", - "--enable-ab-partitions=1", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-tx-size-search=0", - "--enable-cdef=0", - "--enable-restoration=0", - "--max-partition-size=32", - "--min-partition-size=16", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - "--enable-ref-frame-mvs=0", - "--obu", - "-o", - "-", - "-", - ]; - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let frames = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME} failed outright, not a named refusal (seed {seed}): {msg}" - ); - for banned in ["warp", "obmc", "interintra"] { - assert!( - !msg.contains(banned), - "{NAME} refused on {banned} (seed {seed}) -- that capability is \ - ported and this recipe does not need it: {msg}" - ); - } - for v in [4, 6, 7] { - assert!( - !msg.contains(&format!( - "an INTER 32x32 partition type this encoder never writes \ - (value={v})" - )), - "{NAME} refused an INTER AB partition (value={v}, seed {seed}) -- \ - all three AB arms are ported, this refusal is forbidden: {msg}" - ); - } - named_refusals += 1; - eprintln!("seed {seed} refusal: {msg}"); - continue; - } - Ok(frames) => frames, - }; - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count); - assert_eq!(frames.len(), frame_count); - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!( - got.y, want.y, - "{NAME} frame {i} luma vs ffmpeg (seed {seed})" - ); - assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})"); - assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})"); - } - // lane-hidden r2 (class gate-blind-to-hidden-frames): the same - // stream again, comparing EVERY decode-order frame -- the hidden - // (show_frame == 0) alt-ref frames the ffmpeg compare above - // cannot see, because both sides of it emit shown frames only. - let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME); - eprintln!( - "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \ - {hidden_n} hidden, all pixel-exact vs the oracle" - ); - // lane-hidden r2 SECOND ARM (the recipe above is untouched): - // libaom's temporal alt-ref filter absorbs this recipe's hidden - // frames, so the compare above is vacuous -- re-encode the same - // fixture with --arnr-maxframes=0 and compare THOSE. - if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) { - eprintln!( - "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \ - decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle" - ); - } - matched += 1; - } - assert!( - matched > 0, - "{NAME}: every attempt refused; the gate never decoded a stream" - ); - if crate::decode::partab_hits() == 0 { - eprintln!( - "{NAME}: SOFT-NOTE -- zero AB partitions fired this run \ - ({matched} matches, {named_refusals} refusals); sampling, not a regression" - ); - } - eprintln!( - "{NAME}: {named_refusals} named refusals, {matched} pixel-exact matches out of {n_attempts}, partab_hits={}", - crate::decode::partab_hits() - ); - } - - /// lane-ab32 r1: the 32x32-level AB arms (`PARTITION_HORZ_A`/`_HORZ_B`/ - /// `_VERT_A`/`_VERT_B` -- two 16x16 squares plus one 32x16/16x32 strip) - /// are decoded on the INTRA path (decode.rs `PARTITION_HORZ_A` .. the - /// 32x32 refusal) but nothing asserted they fire: the INTER AB gate above - /// only SOFT-notes `partab_hits`, and the four per-arm counters - /// lane-part32 added had no consumer at all (class - /// `refusal-lifted-without-a-gate`). This drives a real key-frame-only - /// aomenc at `--enable-ab-partitions=1 --enable-rect-partitions=1 - /// --sb-size=64 --min-partition-size=16 --max-partition-size=32`, so every - /// AB split aomenc picks is a 32-level one, pixel-compares every - /// successful decode against ffmpeg's decode of the same bytes, and - /// hard-asserts each arm fired at least once over the seed sweep -- - /// counting deltas only from attempts that decoded AND compared (class - /// `counter-from-refused-stream`). - #[test] - fn a_real_aomenc_stream_with_a_32_level_ab_partition_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_stream_with_a_32_level_ab_partition_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height) = (256usize, 256usize); - let arms: [(&str, fn() -> usize); 4] = [ - ("HORZ_A_32", crate::decode::intra_horz_a_hits), - ("HORZ_B_32", crate::decode::intra_horz_b_hits), - ("VERT_A_32", crate::decode::intra_vert_a_hits), - ("VERT_B_32", crate::decode::intra_vert_b_hits), - ]; - let mut totals = [0usize; 4]; - let mut refusals: Vec = Vec::new(); - let mut compared = 0usize; - for &seed in &LR_SEEDS { - // Smooth gradients code as PARTITION_NONE everywhere (r1: 16/16 - // attempts decoded pixel-exact with zero AB hits), so the fixture - // carries seeded noise to give the intra RD a reason to split. - let source = format!( - "{},noise=alls=40:all_seed={seed}", - gradients_source(seed, width, height, "duration=0.04:rate=25") - ); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-frames:v", - "1", - "-pix_fmt", - "yuv420p", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "{NAME}: ffmpeg fixture (seed {seed}): {}", - String::from_utf8_lossy(&y4m.stderr) - ); - // The flags under test come LAST: aomenc keeps the LAST - // occurrence of a repeated flag (measured 2026-09-02 by md5 of - // four orderings), so an override appended after the base recipe - // is the one that lands. Nothing here is repeated, and each of the - // four arm counters below proves the AB flag actually arrived. - let args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=45", - "--cpu-used=0", - "--limit=1", - "--kf-max-dist=0", - "--lag-in-frames=0", - "--threads=1", - "--row-mt=0", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-tx-size-search=0", - "--enable-cdef=0", - "--enable-restoration=0", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - "--enable-ref-frame-mvs=0", - "--sb-size=64", - "--enable-rect-partitions=1", - "--enable-ab-partitions=1", - "--min-partition-size=16", - "--max-partition-size=32", - "--obu", - "-o", - "-", - "-", - ]; - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused the fixture (seed {seed}): {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let before: Vec = arms.iter().map(|(_, f)| f()).collect(); - let frames = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME} failed outright, not a named refusal (seed {seed}): {msg}" - ); - for v in [4, 5, 6, 7] { - assert!( - !msg.contains(&format!( - "a 32x32 partition type this decoder does not code (value={v})" - )), - "{NAME} refused a 32-level AB partition (value={v}, seed {seed}) -- \ - all four arms are ported, this refusal is forbidden: {msg}" - ); - } - refusals.push(format!("seed {seed}: {msg}")); - continue; - } - Ok(frames) => frames, - }; - let deltas: Vec = arms - .iter() - .zip(before.iter()) - .map(|((_, f), b)| f() - b) - .collect(); - let fired: Vec = arms - .iter() - .zip(deltas.iter()) - .map(|((label, _), d)| format!("{label}={d}")) - .collect(); - let fired = fired.join(" "); - // The ENCODE's frame count: `gradients_source` (6015) is rendered with - // `duration=0.04:rate=25` (29116) and `-frames:v 1` (29119) caps the - // y4m at one frame; aomenc runs with `--limit=1` and - // `--kf-max-dist=0` (29150) and so codes exactly that one. Asserted - // ABOVE the oracle call -- it holds for every one of the 16 seeds. - assert_eq!(frames.len(), 1, "{NAME}: seed {seed} key frame"); - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frames.len()); - assert_eq!( - frames.len(), - ffmpeg_frames.len(), - "{NAME}: seed {seed}: shown-frame count vs ffmpeg" - ); - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!( - got.y, want.y, - "{NAME} frame {i} luma vs ffmpeg (seed {seed}) [{fired}]" - ); - assert_eq!( - got.u, want.u, - "{NAME} frame {i} U vs ffmpeg (seed {seed}) [{fired}]" - ); - assert_eq!( - got.v, want.v, - "{NAME} frame {i} V vs ffmpeg (seed {seed}) [{fired}]" - ); - } - compared += 1; - for (i, d) in deltas.iter().enumerate() { - totals[i] += d; - } - } - assert!( - compared > 0, - "{NAME}: every attempt hit a named refusal:\n{}", - refusals.join("\n") - ); - for (i, (label, _)) in arms.iter().enumerate() { - assert!( - totals[i] > 0, - "{NAME}: {compared} attempt(s) decoded pixel-exact but {label} never fired -- \ - the gate would prove nothing about that arm. refusals:\n{}", - refusals.join("\n") - ); - } - eprintln!( - "{NAME}: {compared}/{} attempts pixel-exact, HORZ_A_32={} HORZ_B_32={} \ - VERT_A_32={} VERT_B_32={}, {} named refusals", - LR_SEEDS.len(), - totals[0], - totals[1], - totals[2], - totals[3], - refusals.len() - ); - } - - /// lane-ab32 r1: the 10-bit twin of the gate above -- his two films are - /// yuv420p10le, so an 8-bit-only AB gate proves nothing about the streams - /// that matter. Same recipe through [`ten_bit_tool_gate`], which sums the - /// per-arm counters only over attempts that decoded and pixel-compared. - #[test] - fn a_real_aomenc_10bit_stream_with_a_32_level_ab_partition_decodes_pixel_exact() { - const NAME: &str = - "a_real_aomenc_10bit_stream_with_a_32_level_ab_partition_decodes_pixel_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - ten_bit_tool_gate( - NAME, - 256, - 256, - 1, - &[ - "--ec-fixture-noise", - "--cq-level=45", - "--limit=1", - "--kf-max-dist=0", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-tx-size-search=0", - "--enable-cdef=0", - "--enable-restoration=0", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - "--enable-ref-frame-mvs=0", - // last wins: the flags under test go after the base recipe - "--enable-rect-partitions=1", - "--enable-ab-partitions=1", - "--min-partition-size=16", - "--max-partition-size=32", - ], - &LR_SEEDS, - &[ - ("HORZ_A_32", crate::decode::intra_horz_a_hits), - ("HORZ_B_32", crate::decode::intra_horz_b_hits), - ("VERT_A_32", crate::decode::intra_vert_a_hits), - ("VERT_B_32", crate::decode::intra_vert_b_hits), - ], - ); - } - - /// 8-bit arm of [`run_fimv_motion_mode_gate`]. - #[test] - fn a_real_force_integer_mv_warp_stream_decodes_pixel_exact() { - run_fimv_motion_mode_gate( - "a_real_force_integer_mv_warp_stream_decodes_pixel_exact", - false, - ); - } - - /// 10-bit arm of [`run_fimv_motion_mode_gate`] -- both of his films are - /// `yuv420p10le`. - #[test] - fn a_real_force_integer_mv_warp_10bit_stream_decodes_pixel_exact() { - run_fimv_motion_mode_gate( - "a_real_force_integer_mv_warp_10bit_stream_decodes_pixel_exact", - true, - ); - } - - /// 8-bit arm of [`run_compound_global_warp_gate`]. - #[test] - fn a_real_compound_global_warp_stream_decodes_pixel_exact() { - run_compound_global_warp_gate( - "a_real_compound_global_warp_stream_decodes_pixel_exact", - 8, - 32, - false, - ); - } - - /// 10-bit arm of [`run_compound_global_warp_gate`] -- both of his films are - /// `yuv420p10le`, and `warp_affine`'s `bd` was hardcoded 8 before r1. - /// - /// Un-ignored 2026-09-04: the pre-existing 10-bit compound MC defect that blocked it is gone. Ablation run by lane-cwarp r1 on this - /// very recipe: with `--enable-global-motion=0 --enable-warped-motion=0` - /// (no warp of any kind reachable) the 10-bit stream STILL mismatches at - /// frame 1 luma, cq 32; with `--auto-alt-ref=0 --lag-in-frames=0 - /// --enable-dist-wtd-comp=0` (single-reference 10-bit inter only) the same - /// recipe is 6/6 pixel-exact. So: 10-bit single-ref inter is exact, 10-bit - /// compound is not. `mc::diffwtd_mask`'s missing `(bd - 8)` round term was - /// found and fixed while bisecting this, but is NOT the whole defect. - /// The warp wiring under test here is bit-depth generic. - #[test] - fn a_real_compound_global_warp_10bit_stream_decodes_pixel_exact() { - run_compound_global_warp_gate( - "a_real_compound_global_warp_10bit_stream_decodes_pixel_exact", - 10, - 32, - false, - ); - } - - /// 12-bit arm of [`run_compound_global_warp_gate`] (lane-av112bitw): the - /// same rotating-mandelbrot recipe at `--bit-depth=12`. Pre-lift the - /// first `GLOBAL_GLOBALMV` block under a ROTZOOM model refused ("warped - /// motion at 12 bits"); the lift runs the same `warp::warp_round_0` bump - /// through `warp_affine_compound` (`reduce_bits_horiz` 5, compound - /// `reduce_bits_vert` stays 7, the CONV_BUF blend bias one octave down: - /// `(1 << (bd + 2)) + (1 << (bd + 1))`). - #[test] - fn a_real_compound_global_warp_12bit_stream_decodes_pixel_exact() { - run_compound_global_warp_gate( - "a_real_compound_global_warp_12bit_stream_decodes_pixel_exact", - 12, - 32, - false, - ); - } - - /// 12-bit 8x8 compound-warp LEAF arm (lane-av112bitw, reviewer gap): the - /// same recipe with the 32x32 partition pin dropped to min 8, so the RD - /// can code an 8x8 `GLOBAL_GLOBALMV` leaf whose two references warp per - /// slot -- `decode_inter_block8`'s `COMPOUND_WARP_HITS_8` path, which - /// the 32x32-pinned compound witness structurally cannot reach. Hard- - /// asserts `compound_warp_hits_8() > 0` (an 8x8 compound warp leaf bumps - /// it alongside [`decode::compound_warp_hits`]; a 16x16+ one cannot), so - /// a stream of only bigger warped blocks fails this gate. - #[test] - fn a_real_compound_global_warp_12bit_8x8_leaf_stream_decodes_pixel_exact() { - run_compound_global_warp_gate( - "a_real_compound_global_warp_12bit_8x8_leaf_stream_decodes_pixel_exact", - 12, - 8, - true, - ); - } - - /// 8-bit arm of [`run_diffwtd_inferred_64x64_gate`]. - #[test] - fn a_real_aomenc_stream_with_a_diffwtd_compound_64x64_block_decodes_pixel_exact() { - run_diffwtd_inferred_64x64_gate( - "a_real_aomenc_stream_with_a_diffwtd_compound_64x64_block_decodes_pixel_exact", - false, - ); - } - - /// 10-bit arm of [`run_diffwtd_inferred_64x64_gate`] -- both of his films - /// are `yuv420p10le`. - #[test] - fn a_real_aomenc_10bit_stream_with_a_diffwtd_compound_64x64_block_decodes_pixel_exact() { - run_diffwtd_inferred_64x64_gate( - "a_real_aomenc_10bit_stream_with_a_diffwtd_compound_64x64_block_decodes_pixel_exact", - true, - ); - } - - /// lane-maskcomp r2 / lane-wedge r3: `--enable-masked-comp=1` streams - /// must consume `compound_type`/`wedge_idx`/`wedge_sign`/`mask_type` - /// entropy-exact AND build the real blend, DIFFWTD or WEDGE -- - /// `masked_compound_hits() > 0` is a hard assert and BOTH - /// `COMPOUND_DIFFWTD` and `COMPOUND_WEDGE` refusals are now FORBIDDEN - /// (matches interintra's own gate). r3: `--enable-dist-wtd-comp=0` - /// (forces the masked choice toward wedge when comp_group_idx==1) plus - /// a hard-diagonal-edge `geq` source (wedge's OBLIQUE directions favor - /// a real diagonal edge over the r2 gradients content) to fire - /// COMPOUND_WEDGE live; `wedge_hits()` is soft-skipped (not hard - /// asserted) on a zero-hit run -- the recipe search is not proven to - /// converge every run, see charter's "if no recipe fires" fallback. - #[test] - fn a_real_aomenc_stream_with_masked_compound_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_stream_with_masked_compound_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height, frame_count) = (64usize, 64usize, 24usize); - let mut named_refusals = 0u32; - let mut matched = 0u32; - let n_attempts: u32 = std::env::var("EC_MASKCOMP_GATE_ATTEMPTS") - .ok() - .and_then(|s| s.parse().ok()) - .unwrap_or(80); - for attempt in 0..n_attempts { - let seed = 42 + attempt; - let duration = frame_count as f64 / 25.0; - // lane-wedge r3: a hard diagonal edge (not a smooth gradient) - // is the content wedge's OBLIQUE master masks are shaped for -- - // `mandelbrot`'s pan position varies the edge angle/position - // across attempts the way the r2 gradients seed did. - let source = format!( - "mandelbrot=size={width}x{height}:rate=25:start_x={sx}:start_y={sy}", - sx = -0.6 + 0.005 * (attempt as f64), - sy = -0.4 + 0.005 * (attempt as f64) - ); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-t", - &duration.to_string(), - "-pix_fmt", - "yuv420p", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let args: Vec<&str> = vec![ - // lane-defon r1: explicit on-value (aomenc keeps the FIRST - // occurrence, so overrides go before the base list). - "--enable-diff-wtd-comp=1", - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=45", - "--cpu-used=0", - "--kf-max-dist=1000", - "--threads=1", - "--row-mt=0", - "--auto-alt-ref=1", - "--lag-in-frames=16", - "--enable-fwd-kf=0", - "--enable-order-hint=1", - "--enable-warped-motion=1", - // r3: mandelbrot's pan/zoom triggers aomenc's single-ref - // GLOBALMV global-motion search (a capability distinct from - // and outside this lane's scope) -- off, matching this - // gate's own goal of exercising masked compound, not GM. - "--enable-global-motion=0", - "--enable-obmc=1", - "--tune-content=default", - "--enable-masked-comp=1", - // r3: force the masked choice toward wedge (r2 always set - // this =1; distance-weighted compound competes with the - // wedge/diffwtd choice for the same comp_group_idx==1 slot). - "--enable-dist-wtd-comp=0", - "--enable-interintra-comp=1", - "--enable-onesided-comp=0", - "--enable-interintra-wedge=0", - "--enable-smooth-interintra=1", - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-tx-size-search=0", - "--enable-cdef=0", - "--enable-restoration=0", - "--max-partition-size=32", - "--min-partition-size=32", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - "--enable-ref-frame-mvs=0", - "--obu", - "-o", - "-", - "-", - ]; - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let frames = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME} failed outright, not a named refusal (seed {seed}): {msg}" - ); - assert!( - !msg.contains("warp"), - "{NAME} refused on warp (seed {seed}) -- warp decode is ported: {msg}" - ); - assert!( - !msg.contains("masked COMPOUND_REFERENCE"), - "{NAME} refused a masked-compound block (seed {seed}) -- both DIFFWTD \ - and WEDGE blends are ported, this refusal is forbidden: {msg}" - ); - assert!( - !msg.contains("interintra"), - "{NAME} refused on interintra (seed {seed}) -- non-wedge \ - interintra is ported: {msg}" - ); - named_refusals += 1; - eprintln!("seed {seed} refusal: {msg}"); - if std::env::var_os("EC_AV1_GATE_DUMP").is_some() { - // r1's self-pin is armed via EC_AV1_GATE_DUMP= - // only for a real pixel MISMATCH below, not for this - // still-expected named refusal. - } - continue; - } - Ok(frames) => frames, - }; - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count); - assert_eq!(frames.len(), frame_count); - let mismatched = frames - .iter() - .zip(&ffmpeg_frames) - .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); - if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") { - std::fs::write(&path, &stream).expect("writing pinned stream"); - eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}"); - } - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!( - got.y, want.y, - "{NAME} frame {i} luma vs ffmpeg (seed {seed})" - ); - assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})"); - assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})"); - } - // lane-hidden r2 (class gate-blind-to-hidden-frames): the same - // stream again, comparing EVERY decode-order frame -- the hidden - // (show_frame == 0) alt-ref frames the ffmpeg compare above - // cannot see, because both sides of it emit shown frames only. - let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME); - eprintln!( - "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \ - {hidden_n} hidden, all pixel-exact vs the oracle" - ); - // lane-hidden r2 SECOND ARM (the recipe above is untouched): - // libaom's temporal alt-ref filter absorbs this recipe's hidden - // frames, so the compare above is vacuous -- re-encode the same - // fixture with --arnr-maxframes=0 and compare THOSE. - if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) { - eprintln!( - "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \ - decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle" - ); - } - matched += 1; - } - // r1: observed flaky at 40 attempts -- aomenc's cpu-used=0 RD is - // run-to-run nondeterministic in whether it ever picks - // comp_group_idx == 1 for this synthetic gradients content, and - // allow_screen_content_tools sometimes eats most of a small seed - // window (class gate-recipe-confound / never-fired-gate, memory). - // 80 attempts is the mitigation, not a fix; a still-zero run here - // is that sampling flake, not a decode regression -- check - // masked_compound_hits/named_refusals in the panic message before - // assuming a real bug. - // r2: DIFFWTD is ported and gated, so a zero-hit run is no longer - // soft-skipped -- hard assert, matching the interintra gate. - assert!( - crate::decode::masked_compound_hits() > 0, - "{NAME}: zero masked-compound blocks fired ({matched} matches, {named_refusals} \ - other refusals out of {n_attempts}) -- gate proved nothing this run" - ); - // lane-defon r1: `--enable-diff-wtd-comp=1` is now spelled on this - // recipe, so the DIFFWTD half of MASKED_COMPOUND_HITS must fire. - assert!( - crate::decode::diffwtd_hits() > 0, - "{NAME}: zero COMPOUND_DIFFWTD blends ({matched} matches, {named_refusals} \ - other refusals out of {n_attempts}) -- --enable-diff-wtd-comp=1 proved nothing" - ); - // r3: wedge_hits() is soft-skipped, not hard-asserted -- the recipe - // search (dist-wtd-comp=0 + diagonal mandelbrot content) is not - // proven to fire wedge on every run; charter's fallback is to land - // the checksum-verified codebook + blend with this soft path. - if crate::decode::wedge_hits() == 0 { - eprintln!( - "{NAME}: WARNING wedge_hits()==0 this run -- COMPOUND_WEDGE never fired \ - ({matched} matches, {named_refusals} refusals out of {n_attempts}); codebook \ - is checksum-verified but unexercised live this run" - ); - } - eprintln!( - "{NAME}: {named_refusals} other-capability refusals, {matched} pixel-exact matches \ - out of {n_attempts}, masked_compound_hits={} wedge_hits={}", - crate::decode::masked_compound_hits(), - crate::decode::wedge_hits() - ); - } - - /// lane-inter16ab r5: `COMPOUND_WEDGE` on a RECTANGULAR inter block -- - /// the shapes `av1_wedge_params_lookup` gives the `hgtw`/`hltw` - /// codebooks (8x16/16x32/8x32 and 16x8/32x16/32x8), which this decoder - /// refused by name until this round ("the wedge codebook is - /// square-only"). `--enable-rect-partitions=1` with - /// `--min-partition-size=16 --max-partition-size=32` is what makes - /// aomenc's RD put a masked compound block on a 16x32/32x16 strip - /// (measured: ~/.cache/inter16ab-tmp/rw2.sh, 24/24 streams at cq 50/55 - /// carry one and decode to the end at BOTH bit depths). - /// - /// Class `counter-from-refused-stream`: the per-shape counters are read - /// as a DELTA around one attempt and only counted for attempts that - /// decoded fully AND compared pixel-exact -- a refused attempt's hits - /// are discarded. Every decode-order frame (including hidden alt-ref - /// frames) is compared via [`decode_all_frames_vs_oracle`], and an - /// attempt that mismatches while carrying NO rect wedge fails the gate - /// through `oos_mismatch` rather than being blamed on this lane. - #[test] - fn a_real_aomenc_stream_with_a_rectangular_compound_wedge_decodes_pixel_exact() { - const NAME: &str = - "a_real_aomenc_stream_with_a_rectangular_compound_wedge_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height, frame_count) = (96usize, 96usize, 24usize); - // Per rect shape (8x16, 16x8, 16x32, 32x16, 8x32, 32x8), summed over - // the attempts that decoded AND matched. - let mut shapes_proved = [0usize; 6]; - let (mut named_refusals, mut matched, mut oos_mismatch) = (0u32, 0u32, 0u32); - let mut attempts = 0u32; - for bit_depth in [8u32, 10u32] { - for &cq in &[50u32, 55] { - for a in 0..4u32 { - attempts += 1; - let duration = frame_count as f64 / 25.0; - // Same hard-diagonal-edge content the square wedge gate - // uses (wedge's masters are OBLIQUE), panned per attempt. - let source = format!( - "mandelbrot=size={width}x{height}:rate=25:start_x={sx}:start_y={sy}", - sx = -0.6 + 0.01 * (a as f64), - sy = -0.4 + 0.01 * (a as f64) - ); - let pix_fmt = if bit_depth == 10 { - "yuv420p10le" - } else { - "yuv420p" - }; - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-t", - &duration.to_string(), - "-pix_fmt", - pix_fmt, - "-strict", - "-1", - "-f", - "yuv4mpegpipe", - "-strict", - "-1", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "{NAME}: ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let cq_arg = format!("--cq-level={cq}"); - let depth_arg = format!("--bit-depth={bit_depth}"); - let input_depth_arg = format!("--input-bit-depth={bit_depth}"); - let args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - &cq_arg, - "--cpu-used=0", - &depth_arg, - &input_depth_arg, - "--kf-max-dist=1000", - "--threads=1", - "--row-mt=0", - "--auto-alt-ref=1", - "--lag-in-frames=16", - "--enable-fwd-kf=0", - "--enable-order-hint=1", - "--enable-warped-motion=1", - "--enable-global-motion=0", - "--enable-obmc=1", - "--enable-diff-wtd-comp=1", - "--enable-interintra-comp=1", - "--enable-onesided-comp=0", - "--enable-interintra-wedge=1", - "--enable-smooth-interintra=1", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-tx-size-search=0", - "--enable-cdef=0", - "--enable-restoration=0", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - "--enable-ref-frame-mvs=0", - // Per-arm overrides LAST (aomenc keeps the last - // occurrence of a repeated --enable-* flag): masked - // compound ON, distance-weighted OFF so the - // comp_group_idx==1 slot goes to wedge/diffwtd, and - // rectangular partitions ON at 16/32 -- the shapes - // the hgtw/hltw codebooks exist for. - "--enable-masked-comp=1", - "--enable-dist-wtd-comp=0", - "--enable-rect-partitions=1", - "--min-partition-size=16", - "--max-partition-size=32", - "--obu", - "-o", - "-", - "-", - ]; - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let before = crate::stream::rect_wedge_hits(); - let frames = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME} failed outright, not a named refusal \ - ({bit_depth}-bit cq{cq} attempt {a}): {msg}" - ); - assert!( - !msg.contains("wedge codebook is square-only"), - "{NAME}: the rect wedge codebook is ported -- this refusal is \ - forbidden ({bit_depth}-bit cq{cq} attempt {a}): {msg}" - ); - named_refusals += 1; - eprintln!("{bit_depth}-bit cq{cq} attempt {a} refusal: {msg}"); - continue; - } - Ok(frames) => frames, - }; - let after = crate::stream::rect_wedge_hits(); - let fired: Vec = (0..6).map(|k| after[k] - before[k]).collect(); - let ffmpeg_frames = if bit_depth == 10 { - ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count) - } else { - ffmpeg_decode_sequence(&stream, width, height, frame_count) - }; - assert_eq!(frames.len(), ffmpeg_frames.len()); - let mismatched = frames - .iter() - .zip(&ffmpeg_frames) - .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); - if fired.iter().sum::() == 0 { - if mismatched { - oos_mismatch += 1; - eprintln!( - "{NAME}: {bit_depth}-bit cq{cq} attempt {a} MISMATCHES with zero \ - rectangular wedge block -- another shape's defect" - ); - } - continue; - } - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!( - got.y, want.y, - "{NAME} frame {i} luma vs ffmpeg ({bit_depth}-bit cq{cq} attempt {a}, shapes {fired:?})" - ); - assert_eq!( - got.u, want.u, - "{NAME} frame {i} U vs ffmpeg ({bit_depth}-bit cq{cq} attempt {a}, shapes {fired:?})" - ); - assert_eq!( - got.v, want.v, - "{NAME} frame {i} V vs ffmpeg ({bit_depth}-bit cq{cq} attempt {a}, shapes {fired:?})" - ); - } - // class gate-blind-to-hidden-frames: the shown-frame - // compare above cannot see the alt-ref frames this - // recipe's --lag-in-frames=16 produces. - let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME); - eprintln!( - "{NAME}: {bit_depth}-bit cq{cq} attempt {a}: shapes {fired:?}, \ - {hidden_total} decode-order frames ({hidden_n} hidden) pixel-exact" - ); - for k in 0..6 { - shapes_proved[k] += fired[k]; - } - matched += 1; - } - } - } - eprintln!( - "{NAME}: {named_refusals} named refusals, {matched} pixel-exact attempts out of \ - {attempts}, rect wedge blocks per shape \ - (8x16,16x8,16x32,32x16,8x32,32x8)={shapes_proved:?}, {oos_mismatch} zero-wedge \ - mismatches" - ); - assert_eq!( - oos_mismatch, 0, - "{NAME}: {oos_mismatch} attempt(s) carrying no rectangular wedge mismatched ffmpeg \ - -- a defect of another shape, not a pass" - ); - // The claim: a rectangular wedge codebook row (hgtw AND hltw) was - // used on a stream that then decoded pixel-exact. 16x32 is hgtw - // (h > w), 32x16 is hltw (h < w) -- one of each, so a transposed - // codebook/signflip pair cannot pass this. - assert!( - shapes_proved[2] > 0 && shapes_proved[3] > 0, - "{NAME}: no pixel-exact attempt used both an hgtw (16x32) and an hltw (32x16) \ - rectangular wedge codebook row (per shape {shapes_proved:?}, {matched} matches, \ - {named_refusals} refusals out of {attempts}) -- the recipe proved nothing" - ); - } diff --git a/crates/ec-av1/src/stream/tests/t07.rs b/crates/ec-av1/src/stream/tests/t07.rs deleted file mode 100644 index 3ddb8ad2..00000000 --- a/crates/ec-av1/src/stream/tests/t07.rs +++ /dev/null @@ -1,4479 +0,0 @@ -use super::*; -use super::support::*; -use super::gates_a::*; -use super::gates_b::*; -use crate::probe::run_with_stdin; -use std::process::{Command, Stdio}; - - /// lane-lr r3: proves stage 1/2's exit criterion -- a real - /// `--enable-restoration=1` aomenc stream must survive the whole - /// partition walk (every symbol read entropy-exact) and land on the - /// NEW, narrowed refusal ("read but not applied"), never desync into - /// some other named refusal or an outright decode panic. Multi-superblock - /// fixture (192x128 = 3x2 SBs of 64px) per the charter's own trap - /// warning -- a single-SB fixture can never re-enter `read_lr` a second - /// time and would leave `SWITCHABLE_HITS`/etc. proving only one call - /// site, not the per-SB loop. - #[test] - fn a_real_aomenc_stream_with_restoration_reads_lr_symbols_correctly() { - const NAME: &str = "a_real_aomenc_stream_with_restoration_reads_lr_symbols_correctly"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - // lane-reelckf2 r1: 152 = 2*64+24, not 128 -- the 8-bit twin of the - // partial-bottom-stripe LR gate below. Stripe shapes at 128 rows are - // a strict subset of those at 152 (56, 64, then the 32-row tail whose - // below boundary is the frame's own last row). - let (width, height) = (192usize, 152usize); - let n_attempts: u32 = std::env::var("EC_LR_GATE_ATTEMPTS") - .ok() - .and_then(|s| s.parse().ok()) - .unwrap_or(40); - let mut lr_refusals = 0u32; - let mut other_refusals = Vec::new(); - // lane-reelckf2 r1: the two special stripe shapes this size now has. - let stripe0_before = crate::restoration::lr_stripe0_hits(); - let last_stripe_before = crate::restoration::lr_last_stripe_hits(); - for attempt in 0..n_attempts { - let seed = 42 + attempt; - // Diagnosis knob: which content makes RD pick an 8x16/16x8 strip - // AND filter intra on it is a search (see lanes/fistrip-r1.report.md). - let source = match std::env::var("EC_FISTRIP_SRC").unwrap_or_default().as_str() { - "bars" => format!("smptebars=size={width}x{height}:duration=0.04:rate=25"), - "src2" => format!("testsrc2=size={width}x{height}:duration=0.04:rate=25"), - "noise" => format!( - "nullsrc=size={width}x{height}:duration=0.04:rate=25,geq=random(1)*255:128:128" - ), - _ => gradients_source(seed, width, height, "duration=0.04:rate=25"), - }; - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args(["-v", "error", "-f", "lavfi", "-i"]) - .arg(&source) - .args(["-pix_fmt", "yuv420p", "-f", "yuv4mpegpipe", "-"]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let out = run_with_stdin( - Command::new(aomenc_path()).args([ - "--codec=av1", - "--passes=1", - "--end-usage=q", - // r3: a low cq-level (high quality/bitrate) is load-bearing -- - // sampled live (2026-08-30) that aomenc's RD only ever picks a - // non-`RESTORE_NONE` frame_restoration_type at cq-level<=20 for - // this fixture; cq-level=45 (this gate's sibling gates' usual - // value) landed `uses_lr=false` on every attempt. - "--cq-level=15", - "--cpu-used=0", - "--threads=1", - "--row-mt=0", - // r3: this decoder always assumes 64px superblocks - // (`decode.rs` hardcodes `SB_MI=16`, ledger `lane-sb128` - // dead-ends) -- force aomenc to match rather than risk - // the unrelated sb128 gap eating this gate's own window. - "--sb-size=64", - "--enable-restoration=1", - "--enable-cdef=0", - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-tx-size-search=0", - "--max-partition-size=32", - "--min-partition-size=16", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - "--enable-ref-frame-mvs=0", - "--enable-warped-motion=0", - "--enable-global-motion=0", - "--enable-masked-comp=0", - "--enable-interintra-comp=0", - "--enable-obmc=0", - "--obu", - "-o", - "-", - "-", - ]), - &y4m.stdout, - ); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - match decode_stream(&stream) { - Ok(pics) => { - // r4: the pixel filters are wired -- every `uses_lr` - // frame must now decode Ok AND match an independent - // decoder pixel-exact, not just refuse cleanly. - // The ENCODE's frame count: every `EC_FISTRIP_SRC` branch - // and the `gradients_source` default (30568-30573) render at - // `rate=25` with a 1-frame `duration=0.04`, and aomenc runs - // with no `--limit` (30590) -- so each attempt's stream codes - // exactly 1 frame. Asserted ABOVE the oracle call. - assert_eq!(pics.len(), 1, "{NAME}: seed {seed} key frame"); - let reference = ffmpeg_decode_sequence(&stream, width, height, pics.len()); - let mismatched = pics - .iter() - .zip(&reference) - .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); - // r7: pin a mismatching stream the same way the - // masked-compound gate does -- lets a follow-up round - // decode this exact seed's bytes directly instead of - // re-deriving them from a live 40-attempt sweep. - if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") { - std::fs::write(&path, &stream).expect("writing pinned stream"); - eprintln!( - "EC_AV1_GATE_DUMP: wrote mismatching LR stream (seed {seed}) to {path}" - ); - } - for (i, (pic, refpic)) in pics.iter().zip(reference.iter()).enumerate() { - assert_eq!( - pic.y, refpic.y, - "{NAME}: luma mismatch (seed {seed} frame {i})" - ); - assert_eq!( - pic.u, refpic.u, - "{NAME}: U mismatch (seed {seed} frame {i})" - ); - assert_eq!( - pic.v, refpic.v, - "{NAME}: V mismatch (seed {seed} frame {i})" - ); - } - lr_refusals += 1; // reused below as "attempts that actually exercised LR pixels" - } - Err(e) => { - let msg = e.to_string(); - other_refusals.push(format!("seed {seed}: {msg}")); - } - } - } - assert!( - other_refusals.is_empty(), - "{NAME}: {} attempts failed outright instead of decoding:\n{}", - other_refusals.len(), - other_refusals.join("\n") - ); - assert!( - lr_refusals > 0, - "{NAME}: no attempt ever decoded pixel-exact ({n_attempts} attempts)" - ); - // Any real (non-`RESTORE_NONE`) filter kind is acceptable proof -- - // aomenc's RD picks the frame-level `restoration_type` itself (not - // always `Switchable`; observed `Sgrproj` live at cq-level=15 for - // this fixture), so hard-requiring one specific arm would be the - // gate-recipe-confound class (ledger). - let total_hits = crate::restoration::wiener_hits() - + crate::restoration::sgrproj_hits() - + crate::restoration::switchable_hits(); - assert!( - total_hits > 0, - "{NAME}: {lr_refusals} LR refusals fired but read_lr_unit never decoded a real \ - (non-None) filter -- gate proved nothing about the symbol path" - ); - // lane-reelckf2 r1: a size with a partial bottom stripe proves nothing - // about the two frame-edge stripe shapes unless a real filter actually - // ran on them (`filter_restoration_unit`). - assert!( - crate::restoration::lr_stripe0_hits() > stripe0_before - && crate::restoration::lr_last_stripe_hits() > last_stripe_before, - "{NAME}: no filtered stripe took the frame's own top/bottom row as its boundary \ - (stripe0 +{}, last +{})", - crate::restoration::lr_stripe0_hits() - stripe0_before, - crate::restoration::lr_last_stripe_hits() - last_stripe_before - ); - eprintln!( - "{NAME}: {lr_refusals} LR refusals, {} other refusals out of {n_attempts}, \ - wiener_hits={} sgrproj_hits={} switchable_hits={}", - other_refusals.len(), - crate::restoration::wiener_hits(), - crate::restoration::sgrproj_hits(), - crate::restoration::switchable_hits() - ); - } - - /// r8: decode the ONE pinned stream `EC_AV1_GATE_DUMP` captured in r7 - /// (`fixtures/lr-sgr-r7.obu`, seed 46) directly -- not the live - /// 40-attempt sweep, which reuses `v_start` coordinates across unrelated - /// seeds/frames and made r6's captured 9 bytes unprovable. Run with - /// `EC_LR_CALL_DUMP=1` set (see `restoration.rs`'s `apply_sgrproj_stripe`) - /// to get the real window on stderr, call-uniquely keyed to `xqd == - /// [-16,-32]` rather than any coordinate. - /// lane-av1pinslive r4: this gate asserted NOTHING. It `eprintln!`d per-frame - /// mismatch flags and returned, so it could not go red on a decode regression - /// -- which is why r3 left it `#[ignore]`d on that fact rather than un-ignoring - /// it. It now carries the same three things its three siblings have: a pinned - /// FRAME COUNT, a length assert before the zip, and per-plane per-frame pixel - /// asserts. The diagnostic print is kept, and now runs BEFORE the asserts so a - /// failure still names the shape of the divergence. - /// - /// The frame count is the substantive fix. The old body passed `pics.len()` as - /// ffmpeg's EXPECTED count: - /// let reference = ffmpeg_decode_sequence(&stream, 192, 128, pics.len()); - /// so a decoder that emitted ZERO frames asked ffmpeg for zero frames, the zip - /// compared no pairs, and the gate passed having proved nothing -- the exact - /// vacuous-pass shape the `cmpaudit` lane swept elsewhere in this crate. The - /// count now comes from the FIXTURE (`FRAMES`), so losing the frame reds on the - /// count instead of comparing nothing. - /// - /// On "does it compare only frame 0": the loop always visited every frame; this - /// pin simply holds one (`frame 0` was the only line the pre-r4 run printed). - /// The loop is unchanged in that respect and still visits every frame it gets. - /// - /// The `EC_LR_CALL_DUMP=1` window is unchanged and still needs that env -- but - /// it is a debugging session layered on a real gate now, not the gate itself. - #[test] - fn pinned_lr_sgr_stream_call_unique_dump() { - const NAME: &str = "pinned_lr_sgr_stream_call_unique_dump"; - const W: usize = 192; - const H: usize = 128; - /// Measured: the pre-r4 run printed `frame 0` and no other frame line. - const FRAMES: usize = 1; - let path = std::env::var("EC_AV1_GATE_DUMP_PIN") - .map(std::path::PathBuf::from) - .unwrap_or_else(|_| crate_pin("lr-sgr-r7.obu")); - let stream = require_pin(&path, "lr-sgr-r7.obu"); - let pics = decode_stream(&stream).expect("pinned lr-sgr-r7.obu must decode"); - assert_eq!( - pics.len(), - FRAMES, - "{NAME}: decoded {} frame(s), the pinned stream holds {FRAMES} -- a short \ - decode would otherwise ask ffmpeg for the same short count and compare \ - nothing", - pics.len() - ); - for f in &pics { - assert_eq!((f.width, f.height), (W, H), "{NAME}: dimensions"); - } - if !have_ffmpeg() { - eprintln!( - "SKIP {NAME}: no ffmpeg -- the pixel compare IS this gate's claim, so it \ - proves nothing here; set EC_AV1_REQUIRE_FFMPEG=1 to make that a hard \ - failure instead" - ); - return; - } - let reference = ffmpeg_decode_sequence(&stream, W, H, FRAMES); - assert_eq!( - reference.len(), - FRAMES, - "{NAME}: ffmpeg returned {} frame(s), expected {FRAMES}", - reference.len() - ); - for (i, (got, want)) in pics.iter().zip(&reference).enumerate() { - let y_mismatch = got.y != want.y; - let u_mismatch = got.u != want.u; - let v_mismatch = got.v != want.v; - eprintln!( - "frame {i}: y_mismatch={y_mismatch} u_mismatch={u_mismatch} v_mismatch={v_mismatch}" - ); - if y_mismatch { - let n = got.y.iter().zip(&want.y).filter(|(a, b)| a != b).count(); - eprintln!(" {n} luma bytes differ / {}", got.y.len()); - } - if v_mismatch { - let w = 96usize; // chroma plane width (192/2) - for (idx, (a, b)) in got.v.iter().zip(&want.v).enumerate() { - if a != b { - eprintln!(" V[{},{}] got={a} want={b}", idx / w, idx % w); - } - } - } - assert_eq!( - got.y, want.y, - "{NAME} frame {i} luma vs ffmpeg (pinned lr-sgr)" - ); - assert_eq!( - got.u, want.u, - "{NAME} frame {i} U vs ffmpeg (pinned lr-sgr)" - ); - assert_eq!( - got.v, want.v, - "{NAME} frame {i} V vs ffmpeg (pinned lr-sgr)" - ); - } - eprintln!( - "{NAME}: {FRAMES} frame(s) byte-exact vs ffmpeg from {}", - path.display() - ); - } - - /// lane-realworld r2: `read_cdef` (spec 5.11.56) ported -- per-superblock - /// `cdef_idx`, wired at all five `skip`-decode sites, `apply_cdef` looks - /// up strength through the grid instead of a hardcoded `[0]`. Structure - /// copied from `a_real_aomenc_stream_with_masked_compound_decodes_pixel_exact` - /// but `--enable-cdef=1` (the one thing that gate turns off) and every - /// *other* filter/mode feature this lane doesn't touch disabled, so a - /// mismatch here can only be attributed to CDEF. `cdef_idx_hits()` is a - /// hard assert -- a run that never reads a real cdef_idx symbol proves - /// nothing (class `gate-blind-to-feature`). - #[test] - fn a_real_aomenc_stream_with_cdef_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_stream_with_cdef_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - // cdef_bits selects among PER-SUPERBLOCK strengths -- a single-SB - // 64x64 frame (the other gates' size) gives aomenc nothing to - // differentiate, so it always writes bits=0 and cdef_idx is never - // read. 128x64 = 2 SBs is the minimum that lets aomenc's RD ever - // pick bits > 0. Multi-SB content at --cpu-used=0 (every other - // gate's setting) makes aomenc pick PARTITION_HORZ_4/VERT_B etc. - // at the top SB level regardless of the ab/1to4-partitions=0 - // flags below (a real gap: this decoder's intra part64 match only - // covers NONE/SPLIT, and the inter path blindly assumes SPLIT -- - // both pre-existing, out of this lane's scope); --cpu-used=4 - // avoids that RD path entirely and needs --aq-mode=0 - // --deltaq-mode=0 to keep delta_q/delta_lf (next lane step) off. - let (width, height, frame_count) = (128usize, 64usize, 24usize); - let mut named_refusals = 0u32; - let mut matched = 0u32; - let n_attempts: u32 = std::env::var("EC_CDEF_GATE_ATTEMPTS") - .ok() - .and_then(|s| s.parse().ok()) - .unwrap_or(40); - for attempt in 0..n_attempts { - let seed = 42 + attempt; - let duration = frame_count as f64 / 25.0; - // mandelbrot's ringing-prone hard edges are what CDEF's RD - // search targets; flat gradients (charter's first guess) may - // never make aomenc choose cdef_bits > 0. - let source = format!( - "mandelbrot=size={width}x{height}:rate=25:start_x={sx}:start_y={sy}", - sx = -0.6 + 0.005 * (attempt as f64), - sy = -0.4 + 0.005 * (attempt as f64) - ); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-t", - &duration.to_string(), - "-pix_fmt", - "yuv420p", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=45", - "--cpu-used=4", - "--aq-mode=0", - "--deltaq-mode=0", - "--enable-cdef=0", - "--kf-max-dist=1000", - "--threads=1", - "--row-mt=0", - "--auto-alt-ref=1", - "--lag-in-frames=16", - "--enable-fwd-kf=0", - "--enable-order-hint=1", - // r2: a starved inter toolset (everything below off) pushes - // aomenc's RD toward exotic partition shapes (HORZ_4/VERT_B - // etc.) at the SB(64) level even with those partition - // flags off -- this decoder's part64 8/9/10-way arms and - // the inter path's blind SPLIT assumption don't cover that; - // keeping the same rich toolset the (working, ab/1to4-off) - // masked-compound gate uses avoids it. - "--enable-warped-motion=1", - "--enable-global-motion=0", - "--enable-obmc=1", - "--tune-content=default", - "--enable-masked-comp=1", - "--enable-dist-wtd-comp=0", - "--enable-interintra-comp=1", - "--enable-onesided-comp=0", - "--enable-interintra-wedge=0", - "--enable-smooth-interintra=1", - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-tx-size-search=0", - "--enable-cdef=1", - "--enable-restoration=0", - "--max-partition-size=32", - "--min-partition-size=32", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - "--enable-ref-frame-mvs=0", - "--obu", - "-o", - "-", - "-", - ]; - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let frames = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME} failed outright, not a named refusal (seed {seed}): {msg}" - ); - assert!( - !msg.contains("cdef"), - "{NAME} refused on cdef (seed {seed}) -- cdef_idx decode is ported: {msg}" - ); - named_refusals += 1; - eprintln!("seed {seed} refusal: {msg}"); - continue; - } - Ok(frames) => frames, - }; - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count); - assert_eq!(frames.len(), frame_count); - let mismatched = frames - .iter() - .zip(&ffmpeg_frames) - .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); - if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") { - std::fs::write(&path, &stream).expect("writing pinned stream"); - eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}"); - } - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!( - got.y, want.y, - "{NAME} frame {i} luma vs ffmpeg (seed {seed})" - ); - assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})"); - assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})"); - } - // lane-hidden r2 (class gate-blind-to-hidden-frames): the same - // stream again, comparing EVERY decode-order frame -- the hidden - // (show_frame == 0) alt-ref frames the ffmpeg compare above - // cannot see, because both sides of it emit shown frames only. - let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME); - eprintln!( - "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \ - {hidden_n} hidden, all pixel-exact vs the oracle" - ); - // lane-hidden r2 SECOND ARM (the recipe above is untouched): - // libaom's temporal alt-ref filter absorbs this recipe's hidden - // frames, so the compare above is vacuous -- re-encode the same - // fixture with --arnr-maxframes=0 and compare THOSE. - if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) { - eprintln!( - "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \ - decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle" - ); - } - matched += 1; - } - assert!( - crate::decode::cdef_idx_hits() > 0, - "{NAME}: zero cdef_idx blocks fired ({matched} matches, {named_refusals} other \ - refusals out of {n_attempts}) -- gate proved nothing this run" - ); - eprintln!( - "{NAME}: {named_refusals} other-capability refusals, {matched} pixel-exact matches \ - out of {n_attempts}, cdef_idx_hits={}", - crate::decode::cdef_idx_hits() - ); - } - - /// lane-edgeboth r1 GATE: frame sizes whose width AND height are both - /// 8 mod 16, so the bottom-right corner of the frame is a partition node - /// with `has_rows == false && has_cols == false` at every level it - /// reaches -- libaom `decode_partition` forces PARTITION_SPLIT there and - /// reads NO symbol (`else if (!has_rows && !has_cols) partition = - /// PARTITION_SPLIT;`), then drops the out-of-frame children on its - /// `if (mi_row >= mi_rows || mi_col >= mi_cols) return;` early return. - /// The 64 and 32 levels already inferred that split; the 16 level refused - /// by name until r1, on both the intra (key) and the inter path -- so both - /// arms are swept here. Every compared attempt must show a 16-level - /// both-cut hit, and the sweep must show 32- and 64-level hits too (200x72 - /// puts all three levels in that state: mi_cols 50, mi_rows 18, so the - /// nodes at mi (16,48) of size 64, 32 and 16 are all cut on both axes). - #[test] - fn a_real_aomenc_both_axes_cut_corner_block_decodes_pixel_exact() { - both_axes_cut_sweep( - "a_real_aomenc_both_axes_cut_corner_block_decodes_pixel_exact", - ("key", 1, "--kf-max-dist=0", "--limit=1"), - ); - } - - /// lane-edgeboth r1, INTER half of the same lift. Un-ignored 2026-09-04: the inter frame-edge half-strip band defect that blocked it is gone. As measured then: the inter path's both-cut corner block - /// itself decodes exactly (200x72 inter cq 32, luma diff bounding box rows - /// 64..=71 cols 15..=186 -- the corner at cols 192..=199 is clean), but the - /// bottom 8-row frame-edge BAND of an inter frame is wrong, and the - /// control 192x72 (width a multiple of 16, so zero both-cut nodes: hits - /// [0,0,0,0]) fails identically at rows 64..=71 cols 8..=188. That band is - /// the forced one-axis HORZ half strip on the inter path -- lane-oddh's - /// own inter gate is `#[ignore]`d for the same arm -- so this gate turns - /// green with that defect, not with anything this lane changed. - #[test] - fn a_real_aomenc_both_axes_cut_corner_inter_frames_decode_pixel_exact() { - both_axes_cut_sweep( - "a_real_aomenc_both_axes_cut_corner_inter_frames_decode_pixel_exact", - ("inter", 6, "--kf-max-dist=9999", "--limit=6"), - ); - } - - /// lane-tiny r4 GATE (was r1's `#[ignore]`d probe): every tiny key-frame - /// size real aomenc will encode, decoded pixel-exact against ffmpeg. - /// Tiny frames are where every edge/partial-superblock corner case is - /// forced, and this sweep is what found both r3's filter-intra tx_type - /// CDF row and r4's chroma-transform-size deblock defect -- so it - /// hard-asserts now: a decode error, a refusal, or one differing sample - /// at any size/seed fails. Only a genuinely absent oracle skips, and - /// `EC_AV1_REQUIRE_AOMENC=1` turns that into a failure too. - #[test] - fn a_real_aomenc_tiny_frame_size_sweep_decodes_pixel_exact() { - if !have_ffmpeg() || !have_aomenc() { - eprintln!("SKIP: no ffmpeg/aomenc"); - return; - } - // lane-oddh r2: the second half of this list is the odd-height / - // odd-width ladder -- frame sizes whose last superblock row or column - // is a partial 64 (72 = one full SB plus 8 rows, 136 = two plus 8), - // which is where the frame-edge half-strip path r1 added is the only - // way to code the edge. 192x136 is the inter-sized member. - let sizes: &[(usize, usize)] = &[ - (8, 8), - (16, 16), - (32, 32), - (16, 32), - (32, 16), - (64, 64), - (48, 48), - (24, 24), - (64, 72), - (72, 64), - (64, 136), - (136, 64), - (192, 136), - ]; - let mut total_exact = 0u32; - for &(width, height) in sizes { - let mut ok = 0u32; - let mut bad = 0u32; - let mut refused = 0u32; - let n = 10u32; - for attempt in 0..n { - let seed = 42 + attempt; - let source = format!( - "mandelbrot=size={width}x{height}:rate=25:start_x={sx}:start_y={sy}", - sx = -0.6 + 0.005 * (attempt as f64), - sy = -0.4 + 0.005 * (attempt as f64) - ); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-t", - "0.04", - "-pix_fmt", - "yuv420p", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let max_part = width.max(height).min(64).next_power_of_two(); - let min_part = width.min(height).next_power_of_two().max(8).min(max_part); - let max_part_arg = format!("--max-partition-size={max_part}"); - let min_part_arg = format!("--min-partition-size={min_part}"); - let args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=32", - "--cpu-used=4", - "--kf-max-dist=0", - "--limit=1", - "--threads=1", - "--row-mt=0", - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - &max_part_arg, - &min_part_arg, - "--obu", - "-o", - "-", - "-", - ]; - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let frames = match decode_stream(&stream) { - Err(e) => { - // A NAMED refusal is the only non-exact outcome this - // gate tolerates (8x8 still needs a rectangular - // transform); anything else is a hard failure, and - // the floor assert below keeps that from going - // vacuous. - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{width}x{height} seed {seed}: failed outright, not a named \ - refusal: {msg}" - ); - eprintln!(" {width}x{height} seed {seed}: REFUSED {msg}"); - refused += 1; - continue; - } - Ok(f) => f, - }; - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1); - if frames.len() == 1 - && frames[0].y == ffmpeg_frames[0].y - && frames[0].u == ffmpeg_frames[0].u - && frames[0].v == ffmpeg_frames[0].v - { - ok += 1; - } else { - bad += 1; - let nd = |a: &[u16], b: &[u16]| a.iter().zip(b).filter(|(x, y)| x != y).count(); - let (ndy, ndu, ndv) = ( - nd(&frames[0].y, &ffmpeg_frames[0].y), - nd(&frames[0].u, &ffmpeg_frames[0].u), - nd(&frames[0].v, &ffmpeg_frames[0].v), - ); - let mut first = None; - for row in 0..height { - for col in 0..width { - let i = row * width + col; - if frames[0].y[i] != ffmpeg_frames[0].y[i] { - first = Some((row, col, frames[0].y[i], ffmpeg_frames[0].y[i])); - break; - } - } - if first.is_some() { - break; - } - } - let ndiff = frames[0] - .y - .iter() - .zip(&ffmpeg_frames[0].y) - .filter(|(a, b)| a != b) - .count(); - eprintln!( - " {width}x{height} seed {seed}: MISMATCH first_diff={first:?} \ - ndiff_luma={ndiff}/{} ndiff y/u/v={ndy}/{ndu}/{ndv}", - width * height - ); - } - } - assert_eq!( - bad, 0, - "{width}x{height}: {bad} of {n} seeds decoded to WRONG PIXELS ({ok} exact, \ - {refused} named refusals)" - ); - eprintln!("{width}x{height}: {ok}/{n} pixel-exact, {refused} named refusals"); - total_exact += ok; - } - // Hit counter: the sweep proved nothing unless every size x seed - // attempt really ran end to end (aomenc -> us -> ffmpeg compare). - // Floor (hit counter): 12 of the 13 sizes must decode all 10 seeds - // pixel-exact -- only 8x8 is allowed to refuse outright today. If a - // future change makes sizes refuse instead of decode, this fails - // rather than passing on refusals alone. - assert!( - total_exact >= 120, - "tiny sweep only reached {total_exact} pixel-exact attempts (floor 70) -- \ - refusals cannot substitute for decodes" - ); - eprintln!("tiny frame sweep: {total_exact} pixel-exact attempts"); - } - - /// lane-tiny r1: re-decodes the known-failing 32x32 seed 45 fixture with - /// `EC_AV1_TRACE` on to inspect what mode/tx this single-block frame - /// picked. Diagnostic only, `#[ignore]`d, run manually with --nocapture. - #[test] - #[ignore = "diagnostic, run manually with --nocapture"] - fn probe_tiny_32x32_trace() { - if !have_ffmpeg() || !have_aomenc() { - eprintln!("SKIP: no ffmpeg/aomenc"); - return; - } - let (width, height) = (32usize, 32usize); - let attempt = 3u32; // seed 45 - let source = format!( - "mandelbrot=size={width}x{height}:rate=25:start_x={sx}:start_y={sy}", - sx = -0.6 + 0.005 * (attempt as f64), - sy = -0.4 + 0.005 * (attempt as f64) - ); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-t", - "0.04", - "-pix_fmt", - "yuv420p", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!(y4m.status.success()); - let args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=32", - "--cpu-used=4", - "--kf-max-dist=0", - "--limit=1", - "--threads=1", - "--row-mt=0", - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--max-partition-size=32", - "--min-partition-size=32", - "--enable-filter-intra=0", - "--obu", - "-o", - "-", - "-", - ]; - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!(out.status.success()); - let stream = out.stdout; - let frames = decode_stream(&stream).expect("decode"); - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1); - let mismatched = frames[0].y != ffmpeg_frames[0].y; - eprintln!("mismatched={mismatched}"); - } - - /// lane-tiny r2: decodes a raw OBU stream at `EC_TINY_FIXTURE_PATH` -- - /// no ffmpeg/aomenc invocation -- so a range ladder can be run - /// (`EC_TRACE_MODE_STEP=1`) against the exact same bytes fed to the - /// oracle aomdec, byte for byte. `#[ignore]`d diagnostic, no assertion. - #[test] - // Panics with `set EC_TINY_FIXTURE_PATH to an .obu file: NotPresent` - // without the var -- it has no default and cannot run unattended. Prints - // `decoded N frame(s)` or `REFUSED: `; asserts nothing. - #[ignore = "diagnostic: needs EC_TINY_FIXTURE_PATH naming an .obu; prints decode/REFUSED, asserts nothing"] - fn probe_tiny_fixture_trace() { - let path = std::env::var("EC_TINY_FIXTURE_PATH") - .expect("set EC_TINY_FIXTURE_PATH to an .obu file"); - let stream = std::fs::read(&path).expect("reading fixture"); - match decode_stream(&stream) { - Ok(frames) => { - eprintln!("decoded {} frame(s)", frames.len()); - if let Ok(dump) = std::env::var("EC_TINY_FIXTURE_Y_DUMP") { - let bytes: Vec = frames[0].y.iter().map(|&v| v as u8).collect(); - std::fs::write(&dump, &bytes).expect("dump y plane"); - } - } - Err(e) => eprintln!("REFUSED: {e}"), - } - } - - /// Pinned streams captured by `EC_AV1_GATE_DUMP` off - /// `a_real_aomenc_stream_with_warped_motion_refuses_or_matches` -- each - /// one is a former mismatch, kept as a regression pin (warp-mismatch: - /// the WARPED_CAUSAL interp-read suppression; warp-flake-7: the same - /// suppression for skip_mode blocks; warp-flake-5: mvstack entry - /// clamping; ii-flake-1..8: interintra neighbours excluded from - /// warp-sample gathering, ref_frame[1] == INTRA_FRAME in the mi grid). - /// `EC_AV1_GATE_DUMP_PIN` overrides to a single stream. - /// - /// Un-`#[ignore]`d with the pin shape fixed: the fourteen pins are COMMITTED - /// under `crates/ec-av1/fixtures/`, so the gate runs on a clean checkout - /// and carries `warp_selected_hits` 0 -> 113 over the set instead of - /// skipping GREEN having read nothing. - #[test] - fn pinned_warp_stream_decodes_pixel_exact() { - if !have_ffmpeg() { - eprintln!("SKIP pinned_warp_stream_decodes_pixel_exact: no ffmpeg"); - return; - } - // Every pin is COMMITTED under `crates/ec-av1/fixtures/` and named by a - // string literal, which is the convention every other pinned gate here - // uses and the only shape the pin census can resolve name-by-name. The - // old shape -- one GITIGNORED root directory literal plus a runtime - // name list formatted against it -- can never be satisfied by a - // committed tree, so this gate skipped GREEN having tested nothing. - let pins = match std::env::var("EC_AV1_GATE_DUMP_PIN") { - Ok(p) => vec![std::path::PathBuf::from(p)], - Err(_) => vec![ - crate_pin("warp-mismatch.obu"), - crate_pin("warp-flake-5.obu"), - crate_pin("warp-flake-7.obu"), - crate_pin("ii-flake-1.obu"), - crate_pin("ii-flake-2.obu"), - crate_pin("ii-flake-3.obu"), - crate_pin("ii-flake-5.obu"), - crate_pin("ii-flake-6.obu"), - crate_pin("ii-flake-7.obu"), - crate_pin("ii-flake-8.obu"), - // switchable_interp missing from reset_counts (counter - // saturation slowed the adaptation rate) -- unrelated to - // interintra, caught by the same gate. - crate_pin("ii-flake-9.obu"), - // lane-rect r2: HORZ strip rect defects (mvstack size_h, - // warp sample/projection dims, OBMC overlap, deblock tx-h). - crate_pin("rect-flake-1.obu"), - // scan_row/scan_col weight `inc` min'd by the wrong candidate - // axis (width vs height) -- ties reordered DRL entry 1 for a - // block under a 32x16 strip, and suppressed the -5 extended - // row scan. - crate_pin("rect-flake-2.obu"), - // overlappable_left stepped the vertical walk by the - // neighbour's WIDTH: a 32x16 left strip swallowed the strip - // below it, blending the wrong OBMC prediction there. - crate_pin("rect-flake-3.obu"), - ], - }; - for path in pins { - eprintln!("pin: {}", path.display()); - check_pinned_warp_stream(&path); - } - } - - /// `LAST2_FRAME`/`LAST3_FRAME` are just older slots in the same forward - /// reference-buffer ring `LAST_FRAME`/`GOLDEN_FRAME` already prove -- - /// dropping the golden gate's `--max-reference-frames=3 - /// --reduced-reference-set=1` narrowing (which suppresses exactly these) - /// and running long enough for aomenc's own buffer rotation to reach - /// past the first 2 frames is the whole difference. - #[test] - fn a_real_aomenc_stream_with_a_last2_reference_decodes_pixel_exact() { - a_real_aomenc_single_ref_gate( - "a_real_aomenc_stream_with_a_last2_reference_decodes_pixel_exact", - crate::mvstack::LAST2_FRAME, - "LAST2_FRAME", - &["--auto-alt-ref=0", "--lag-in-frames=0"], - 64, - 64, - 8, - 120, - ); - } - - #[test] - fn a_real_aomenc_stream_with_a_last3_reference_decodes_pixel_exact() { - a_real_aomenc_single_ref_gate( - "a_real_aomenc_stream_with_a_last3_reference_decodes_pixel_exact", - crate::mvstack::LAST3_FRAME, - "LAST3_FRAME", - &["--auto-alt-ref=0", "--lag-in-frames=0"], - 64, - 64, - 8, - 120, - ); - } - - /// `BWDREF`/`ALTREF2`/`ALTREF` are all backward (display-order-forward) - /// references that only exist once aomenc builds a hierarchical GOP -- - /// `--auto-alt-ref=1 --lag-in-frames` (need at least one full mini-GOP - /// of lookahead) is what makes aomenc code them at all; without it - /// every attempt would hit this decoder's own real, still-open - /// per-block sign-bias gap by never drawing the reference in the first - /// place, not by proving it correct. - #[test] - fn a_real_aomenc_stream_with_a_bwdref_reference_decodes_pixel_exact() { - a_real_aomenc_single_ref_gate( - "a_real_aomenc_stream_with_a_bwdref_reference_decodes_pixel_exact", - crate::mvstack::BWDREF_FRAME, - "BWDREF_FRAME", - &[ - "--auto-alt-ref=1", - "--lag-in-frames=16", - "--enable-fwd-kf=0", - ], - 64, - 64, - 16, - 120, - ); - } - - /// lane-altref2 r1: 16 frames was too short for aomenc to ever build a - /// second-level alt-ref pyramid, so this gate ran 86 attempts and fired - /// ALTREF2 exactly zero times (class `gate-blind-to-feature`) -- the - /// flags were already right, only the clip length was wrong. A 64-frame - /// clip at the same `--lag-in-frames=16` gives aomenc enough lookahead - /// to schedule a 2-level GF pyramid and reliably codes ALTREF2 (4/4 - /// hits on a plain seed-42 direct-aomenc probe; see - /// lanes/altref2-r1.report.md for the recipe search table). Firing is - /// now HARD-asserted below: the gate fails rather than skips if - /// `ref_hits(ALTREF2_FRAME)` does not advance. - #[test] - fn a_real_aomenc_stream_with_an_altref2_reference_decodes_pixel_exact() { - let before = decode::ref_hits(crate::mvstack::ALTREF2_FRAME); - a_real_aomenc_single_ref_gate( - "a_real_aomenc_stream_with_an_altref2_reference_decodes_pixel_exact", - crate::mvstack::ALTREF2_FRAME, - "ALTREF2_FRAME", - &[ - "--auto-alt-ref=1", - "--lag-in-frames=16", - "--enable-fwd-kf=0", - ], - 64, - 64, - 64, - 120, - ); - let after = decode::ref_hits(crate::mvstack::ALTREF2_FRAME); - assert!( - after > before, - "a_real_aomenc_stream_with_an_altref2_reference_decodes_pixel_exact: \ - ALTREF2_FRAME never fired across 120 attempts -- the gate is vacuous \ - again (class gate-blind-to-feature); see lanes/altref2-r1.report.md \ - for the recipe that is supposed to make this fire" - ); - } - - #[test] - fn a_real_aomenc_stream_with_an_altref_reference_decodes_pixel_exact() { - a_real_aomenc_single_ref_gate( - "a_real_aomenc_stream_with_an_altref_reference_decodes_pixel_exact", - crate::mvstack::ALTREF_FRAME, - "ALTREF_FRAME", - &[ - "--auto-alt-ref=1", - "--lag-in-frames=16", - "--enable-fwd-kf=0", - ], - 64, - 64, - 16, - 120, - ); - } - - #[test] - fn a_real_aomenc_stream_with_temporal_mvs_decodes_pixel_exact() { - a_real_aomenc_temporal_mv_gate(42, 40); - } - - #[test] - fn a_real_aomenc_compound_mv_stack_with_temporal_mvs_decodes_pixel_exact() { - a_real_aomenc_compound_mv_stack_gate( - "a_real_aomenc_compound_mv_stack_with_temporal_mvs_decodes_pixel_exact", - 42, - 30, - 8, - 64, - 0, - 64, - 0, - ); - } - - #[test] - fn a_real_aomenc_compound_mv_stack_with_global_motion_decodes_pixel_exact() { - a_real_aomenc_compound_mv_stack_gate( - "a_real_aomenc_compound_mv_stack_with_global_motion_decodes_pixel_exact", - 80, - 30, - 8, - 64, - 1, - 64, - 0, - ); - } - - #[test] - fn a_real_aomenc_10bit_compound_mv_stack_at_128_superblocks_decodes_pixel_exact() { - a_real_aomenc_compound_mv_stack_gate( - "a_real_aomenc_10bit_compound_mv_stack_at_128_superblocks_decodes_pixel_exact", - 120, - 30, - 10, - 128, - 1, - 64, - 0, - ); - } - - /// Was a KNOWN OPEN DEFECT (found by lane-mvtwin r1, `#[ignore]`d for it): - /// a real aomenc stream 128 px wide with `--tile-columns=1` (two 64-px - /// tile columns) mis-decoded frame 1's luma against ffmpeg at seed 200 - /// with this exact recipe. lane-t900 r15 RE-MEASURED it on the merged tip - /// (after the motion-field tile clamp, the per-tile txfm/mode band resets - /// and the 8x8-compound interp-filter read landed): the arm decodes - /// pixel-exact, so the `#[ignore]` is removed and the multi-tile mv-stack - /// coverage is live. - /// - /// It is also the ONLY arm that reaches r1 defect 3 (the col reach is - /// clamped to `tile_col0`, not the frame edge): the counter - /// `mvstack::tile_reach_clips` advanced to 60 on this stream. Defect 3 - /// itself is proven deterministically by - /// `mvstack::tests::the_row_reach_is_clamped_to_the_tile_origin_not_the_frame_edge`. - #[test] - fn a_real_aomenc_compound_mv_stack_across_two_tile_columns_decodes_pixel_exact() { - let name = "a_real_aomenc_compound_mv_stack_across_two_tile_columns_decodes_pixel_exact"; - let before = crate::mvstack::tile_reach_clips(); - a_real_aomenc_compound_mv_stack_gate(name, 200, 30, 8, 64, 0, 128, 1); - assert!( - crate::mvstack::tile_reach_clips() > before, - "{name}: no block was ever built inside a tile past mi 0 -- \ - --tile-columns=1 did not produce a second tile column" - ); - } - - /// bisect scratch: decode a pinned stream exactly once -- generic - /// pin-repro tool, kept for manual use. - #[test] - // Panics with `set EC_AV1_PIN to the .obu path: NotPresent` without the - // var. Prints `OK: N frames` or `ERR: ` -- a one-line "does this pin - // decode at all" check, so it asserts nothing by design. - #[ignore = "scratch: decodes the .obu at EC_AV1_PIN and prints OK/ERR; asserts nothing"] - fn scratch_decode_pinned_stream_once() { - let path = std::env::var("EC_AV1_PIN").expect("set EC_AV1_PIN to the .obu path"); - let stream = std::fs::read(&path).expect("read pinned stream"); - match decode_stream(&stream) { - Ok(frames) => eprintln!("OK: {} frames", frames.len()), - Err(e) => eprintln!("ERR: {e}"), - } - } - - /// scratch: isolate a pinned mismatching stream's first divergent pixel. - #[test] - // Panics with `set EC_AV1_PIN to the .obu path: NotPresent` without the - // var, AND the built-in geometry defaults (W=64, H=64, N=1) are wrong for - // every real pin: they are the 64x64 seed-42 pin's own numbers, so on any - // other pin the run dies inside the ffmpeg oracle with a frame-size - // assert (`expected 1 4:2:0 frames ... left 24576 right 6144`) instead of - // saying "you forgot the geometry". Set all four. - #[ignore = "scratch: needs EC_AV1_PIN plus EC_AV1_PIN_W/H/N at the pin's REAL geometry (defaults 64/64/1 are wrong for every other pin); prints the first divergent pixel per plane"] - fn scratch_isolate_pinned_mismatch() { - let path = std::env::var("EC_AV1_PIN").expect("set EC_AV1_PIN to the .obu path"); - let stream = std::fs::read(&path).expect("read pinned stream"); - { - let mut p = Av1Parser::new(); - let mut pos = 0usize; - while pos < stream.len() { - let obu = p.parse_obu(&stream[pos..]).expect("parse"); - pos += obu.total_size; - if let ObuKind::Frame(header, _) = obu.kind { - eprintln!("interpolation_filter: {:?}", header.interpolation_filter); - eprintln!("cdef: {:?}", header.cdef); - eprintln!("quantization: {:?}", header.quantization); - eprintln!( - "coded_lossless: {:?} tx_mode: {:?}", - header.coded_lossless, header.tx_mode - ); - eprintln!("delta: {:?}", header.delta); - eprintln!("segmentation: {:?}", header.segmentation); - eprintln!("loop_restoration: {:?}", header.loop_restoration); - eprintln!( - "use_128x128_superblock: {:?} disable_cdf_update: {:?} disable_frame_end_update_cdf: {:?} primary_ref_frame: {:?} allow_high_precision_mv: {:?} force_integer_mv: {:?}", - p.sequence_header().map(|s| s.use_128x128_superblock), - header.disable_cdf_update, - header.disable_frame_end_update_cdf, - header.primary_ref_frame, - header.allow_high_precision_mv, - header.force_integer_mv, - ); - } - } - } - let width = std::env::var("EC_AV1_PIN_W") - .map(|s| s.parse().unwrap()) - .unwrap_or(64); - let height = std::env::var("EC_AV1_PIN_H") - .map(|s| s.parse().unwrap()) - .unwrap_or(64); - let frame_count = std::env::var("EC_AV1_PIN_N") - .map(|s| s.parse().unwrap()) - .unwrap_or(4); - let frames = decode_stream(&stream).expect("our decode"); - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count); - // The `.min()` chain below is a scratch diagnostic that tolerates a - // pinned stream whose counts disagree, but a SILENT shortfall reads as - // "these frames matched" for frames nobody compared. Say how many are - // actually walked. - let walked = frame_count.min(frames.len()).min(ffmpeg_frames.len()); - if walked < frame_count { - eprintln!( - "pinned stream: asked for {frame_count} frames (EC_AV1_PIN_N), we show {}, ffmpeg \ - shows {} -- comparing the first {walked} only", - frames.len(), - ffmpeg_frames.len() - ); - } - for f in 0..walked { - let ours = &frames[f]; - let theirs = &ffmpeg_frames[f]; - for (plane_name, a, b, w) in [ - ("y", &ours.y, &theirs.y, width), - ("u", &ours.u, &theirs.u, width / 2), - ("v", &ours.v, &theirs.v, width / 2), - ] { - // A short plane would zip-truncate the walk below and report - // MATCH over the prefix the two share. - assert_eq!( - a.len(), - b.len(), - "frame {f} plane {plane_name}: ours has {} samples, ffmpeg's has {}", - a.len(), - b.len() - ); - let mut first = None; - let mut count = 0; - let mut worst = 0i32; - for (i, (x, y)) in a.iter().zip(b.iter()).enumerate() { - if x != y { - count += 1; - if first.is_none() { - first = Some(i); - } - worst = worst.max((*x as i32 - *y as i32).abs()); - } - } - if let Some(i) = first { - eprintln!( - "frame {f} plane {plane_name}: {count} mismatches (worst delta {worst}), first at offset {i} (row {}, col {}) ours={} theirs={}", - i / w, - i % w, - a[i], - b[i] - ); - } else { - eprintln!("frame {f} plane {plane_name}: MATCH"); - } - } - } - } - - /// Final round of the TX4/tx-class lane's own gate: `--min-partition-size=8 - /// --max-partition-size=8` pins every leaf to exactly 8x8 (spec - /// 5.11.4's own boundary carve-out aside, which a multiple-of-8 frame - /// never triggers), so a real `aomenc` stream from this recipe can only - /// legitimately read `PARTITION_NONE` at every `bsize=3` node -- any - /// other value this decoder sees there is a genuine desync, not a - /// "partition below 8x8" the encoder actually wrote (traced live against - /// a debug `aomdec` 2026-08-27: the true bitstream's own 8x8 partition - /// reads are all `NONE`; the mismatch was `base_ctx`'s DC-position - /// short-circuit firing for `TX_CLASS_HORIZ`/`VERT` too, off by one - /// `BR` read into a spurious extra Golomb call). The sinusoidal-stripe - /// `geq` source (a smooth luma ramp, not the sharp two-tone stripes that - /// tripped `aomenc`'s screen-content-tools auto-detect) is what actually - /// resolves `V_DCT`/`H_DCT` (`TxClass::of`) on some 8x8 TUs at this - /// content's frequency; the attempt loop moves on from named refusals - /// (`allow_screen_content_tools`, angle-delta) same as every other - /// multi-seed recipe in this file, and only counts a run as a genuine - /// firing when [`decode::tx_class1_hits`] actually moved. - #[test] - fn a_real_aomenc_min8_stream_with_tx_class1_decodes_pixel_exact() { - if !have_ffmpeg() { - eprintln!( - "SKIP a_real_aomenc_min8_stream_with_tx_class1_decodes_pixel_exact: no ffmpeg" - ); - return; - } - if !have_aomenc() { - eprintln!( - "SKIP a_real_aomenc_min8_stream_with_tx_class1_decodes_pixel_exact: no aomenc at {}", - aomenc_path().display() - ); - return; - } - let (width, height) = (64usize, 64usize); - let mut refusals = Vec::new(); - let mut fired_runs = 0u32; - let mut uncounted_exact = 0u32; - for attempt in 0..60u32 { - let cq = 20 + (attempt % 5) * 10; - let period = [4u32, 6, 8, 12, 16][(attempt as usize / 5) % 5]; - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - "testsrc2=size=64x64:rate=25", - "-vf", - &format!( - "geq=lum='128+80*sin(2*PI*Y/{period})':cb=128:cr=128,noise=alls=6:allf=t" - ), - "-pix_fmt", - "yuv420p", - "-t", - "0.04", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let out = run_with_stdin( - Command::new(aomenc_path()).args([ - "--codec=av1", - "--passes=1", - "--end-usage=q", - &format!("--cq-level={cq}"), - "--cpu-used=0", - "--enable-directional-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-rect-partitions=0", - "--enable-angle-delta=0", - "--enable-palette=0", - "--reduced-tx-type-set=0", - "--enable-restoration=0", - "--enable-cdef=0", - "--loopfilter-control=0", - "--min-partition-size=8", - "--max-partition-size=8", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack; - // leaving it on silently desyncs symbols on inter frames (grainfix lesson). - "--enable-ref-frame-mvs=0", - "--tune-content=default", - "--obu", - "-o", - "-", - "-", - ]), - &y4m.stdout, - ); - if !out.status.success() { - refusals.push(format!( - "cq={cq} period={period}: aomenc itself refused the fixture" - )); - continue; - } - let stream = out.stdout; - let before = decode::tx_class1_hits(); - let frames = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => { - refusals.push(format!("cq={cq} period={period}: {e}")); - continue; - } - }; - // class [[gate-skips-on-its-own-failure]]: a decode that succeeded - // is ALWAYS pixel-compared below; the hit counter only decides whether - // the attempt counts toward the firing total. - let counted = decode::tx_class1_hits() != before; - if !counted { - uncounted_exact += 1; - refusals.push(format!( - "cq={cq} period={period}: decoded and pixel-compared, but no block read a \ - V_DCT/H_DCT tx_type" - )); - } - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1); - assert_eq!( - frames[0].y, ffmpeg_frames[0].y, - "luma vs ffmpeg (cq={cq} period={period})" - ); - assert_eq!( - frames[0].u, ffmpeg_frames[0].u, - "U vs ffmpeg (cq={cq} period={period})" - ); - assert_eq!( - frames[0].v, ffmpeg_frames[0].v, - "V vs ffmpeg (cq={cq} period={period})" - ); - if counted { - fired_runs += 1; - if fired_runs >= 4 { - gate_buckets( - "a_real_aomenc_min8_stream_with_tx_class1_decodes_pixel_exact", - fired_runs, - uncounted_exact, - refusals.len() - uncounted_exact as usize, - ); - return; - } - } - } - gate_buckets( - "a_real_aomenc_min8_stream_with_tx_class1_decodes_pixel_exact", - fired_runs, - uncounted_exact, - refusals.len() - uncounted_exact as usize, - ); - panic!( - "fewer than 4 firing+pixel-exact runs out of 60 attempts:\n{}", - refusals.join("\n") - ); - } - - /// lane-cdef r1: CDEF's per-8x8 skip band under sub-16x16 inter leaves. - /// - /// `apply_cdef` excludes an 8x8 luma unit whose four mi cells are all - /// `skip_txfm` (libaom `cdef.c:29-38 is_8x8_block_skip`, called from - /// `av1_cdef_compute_sb_list`'s dlist loop). `decode_inter_block8` -- the - /// leaf path `--min-partition-size=4` makes aomenc pick for a 16x16 group - /// -- wrote the loop-filter grid but never that skip band, so an all-skip - /// group kept the PREVIOUS frame's flags and got filtered where libaom - /// skips it (3 luma samples, decode-order frames 3 and 4 of the 192x128 - /// cq-8 stream below, at the frame's last 8x8 column). - /// - /// Both counters are hard asserts per compared attempt: `cdef_skipped_units` - /// proves the all-skip dlist exclusion was actually reached, and - /// `inter8_skip_band_hits` proves the 8x8 leaf path (the writer that used - /// to be missing) ran on the same stream. - #[test] - fn a_real_aomenc_stream_with_cdef_and_sub16_inter_leaves_decodes_pixel_exact() { - if !have_aomenc() { - return; - } - let (width, height, frames) = (192usize, 128usize, 6usize); - let mut refusals: Vec = Vec::new(); - let mut fired = 0u32; - let mut cdef_fired = 0u32; - let mut leaf_fired = 0u32; - for (depth, cq, sp) in [ - (8u32, 8u32, 3u32), - (8, 10, 3), - (8, 12, 6), - (10, 8, 3), - (10, 12, 6), - ] { - let pix = if depth == 10 { - "yuv420p10le" - } else { - "yuv420p" - }; - let src = format!( - "color=c=gray:s={width}x{height}:d=0.24:r=25,format=gray,\ - geq=lum='128+58*sin((X+N*{sp})/6)+18*sin(Y/23)',format=yuv420p" - ); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &src, - "-t", - "0.24", - "-pix_fmt", - pix, - "-strict", - "-1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let out = run_with_stdin( - Command::new(aomenc_path()).args([ - "--codec=av1", - "--passes=1", - "--end-usage=q", - &format!("--cq-level={cq}"), - "--cpu-used=0", - "--threads=1", - "--row-mt=0", - "--sb-size=64", - &format!("--bit-depth={depth}"), - &format!("--input-bit-depth={depth}"), - "--enable-restoration=0", - "--enable-palette=0", - "--deltaq-mode=0", - "--enable-filter-intra=0", - "--enable-cfl-intra=0", - "--enable-intrabc=0", - "--lag-in-frames=0", - "--enable-obmc=0", - "--enable-tx-size-search=1", - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--min-partition-size=4", - "--max-partition-size=16", - // Last occurrence of a repeated --enable-* flag wins - // (aomenc-last-flag-wins): CDEF stays ON, and the two - // counters below prove the filter really ran. - "--enable-cdef=1", - "--obu", - "-o", - "-", - "-", - ]), - &y4m.stdout, - ); - assert!( - out.status.success(), - "aomenc refused the fixture (depth={depth} cq={cq})" - ); - let stream = out.stdout; - let skipped_before = decode::cdef_skipped_units(); - let leaves_before = decode::inter8_skip_band_hits(); - let decoded = match decode_stream(&stream) { - Ok(f) => f, - Err(e) => { - let msg = e.to_string(); - assert!( - msg.starts_with("unsupported: "), - "decode error that is not a named refusal \ - (depth={depth} cq={cq}): {msg}" - ); - refusals.push(format!("depth={depth} cq={cq}: {msg}")); - continue; - } - }; - assert_eq!(decoded.len(), frames, "frame count (depth={depth} cq={cq})"); - // lane-leaf8tx r2: continue-and-sweep, not a per-attempt hard - // assert. Lifting a refusal reshuffles WHICH attempt this gate - // lands on (class [[parallel-flake-is-attempt-selection]]): the - // first decoded attempt need not carry a sub-16 leaf, and - // aborting there skipped the pixel compare entirely. Every - // decoded attempt is compared; the counters are asserted once, - // at the end, over the compared attempts. - if decode::cdef_skipped_units() > skipped_before { - cdef_fired += 1; - } - if decode::inter8_skip_band_hits() > leaves_before { - leaf_fired += 1; - } - let reference = if depth == 10 { - ffmpeg_decode_sequence_10bit(&stream, width, height, frames) - } else { - ffmpeg_decode_sequence(&stream, width, height, frames) - }; - for (i, (ours, theirs)) in decoded.iter().zip(reference.iter()).enumerate() { - assert_eq!(ours.y, theirs.y, "luma frame {i} (depth={depth} cq={cq})"); - assert_eq!(ours.u, theirs.u, "U frame {i} (depth={depth} cq={cq})"); - assert_eq!(ours.v, theirs.v, "V frame {i} (depth={depth} cq={cq})"); - } - fired += 1; - } - // Three of the five arms land on OTHER open refusals (a non-DC chroma - // mode on an 8x8 inter leaf; inter partitions below 8x8) -- the two - // 8-bit cq 8/10 arms ARE the streams the defect was found on, and each - // hard-asserts both counters plus all six frames on all three planes. - assert!( - fired >= 2, - "fewer than 2 decoded+pixel-exact attempts:\n{}", - refusals.join("\n") - ); - assert!( - cdef_fired > 0, - "no compared attempt excluded an 8x8 CDEF unit by the all-skip rule \ - ({fired} compared):\n{}", - refusals.join("\n") - ); - assert!( - leaf_fired > 0, - "no compared attempt had a sub-16x16 inter leaf write the CDEF skip band \ - ({fired} compared):\n{}", - refusals.join("\n") - ); - } - - /// lane-cdefstrip r1: the CDEF skip band under SKIPPED rectangular inter - /// strips (32x8 / 8x32 / 64x16 / 16x64 / 32x64 / 64x32, the rect and 1:4 - /// arms), the sibling of the 8x8-leaf case lane-cdef fixed. - /// - /// A fresh `Neighbours` seeds `skip_grid` all-`false` ("not skip"), so any - /// decode arm that resolves `skip` and forgets `fill_skip_grid_rect` makes - /// `apply_cdef` FILTER an 8x8 unit libaom's `is_8x8_block_skip` - /// (`cdef.c:29-38`, `av1_cdef_compute_sb_list`'s dlist test) excludes -- - /// a +-1 band that no entropy or prediction check can see. - /// `decode::cdef_unwritten_skip_units` is the direct instrument for that - /// class: it counts 8x8 CDEF units none of whose four mi cells any coded - /// block wrote this frame, and this gate hard-asserts it stays 0 while - /// `decode::rect_skip_band_hits` proves skipped rect strips really ran. - /// - /// MEASURED (lane-cdefstrip r1, 177 real aomenc streams incl. every arm - /// below): the count is already 0 everywhere -- the charter's premise that - /// the rect strip arms never write the band is FALSE. This gate is the - /// regression fence for it, not a fix. - #[test] - fn a_real_aomenc_stream_with_skipped_rect_inter_strips_keeps_the_cdef_skip_band() { - if !have_aomenc() { - return; - } - let (width, height, frames) = (192usize, 128usize, 6usize); - let mut refusals: Vec = Vec::new(); - let mut fired = 0u32; - // (depth, cq, source): the arms measured pixel-exact end to end in the - // r1 sweep (~/.cache/cdefstrip-tmp/sw.sh). Source `b` is the two-axis - // moving sinusoid that makes aomenc pick 16x64/32x64/8x32 strips at - // low cq and 32x8/64x16 at high cq; `a` is lane-inter16ab's source. - let src_b = "120+55*sin((X+N*4)/7)+40*sin((Y-N*2)/11)"; - let src_a = "128+60*sin((Y+N*3)/5)+30*sin(X/23)"; - for (depth, cq, lum) in [ - (8u32, 18u32, src_b), - (8, 45, src_b), - (10, 18, src_b), - (10, 24, src_b), - (10, 24, src_a), - (8, 24, src_a), - ] { - let pix = if depth == 10 { - "yuv420p10le" - } else { - "yuv420p" - }; - let src = format!( - "color=c=gray:s={width}x{height}:d=0.24:r=25,format=gray,\ - geq=lum='{lum}',format=yuv420p" - ); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &src, - "-t", - "0.24", - "-pix_fmt", - pix, - "-strict", - "-1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let out = run_with_stdin( - Command::new(aomenc_path()).args([ - "--codec=av1", - "--passes=1", - "--end-usage=q", - &format!("--cq-level={cq}"), - "--cpu-used=0", - "--threads=1", - "--row-mt=0", - "--sb-size=64", - &format!("--bit-depth={depth}"), - &format!("--input-bit-depth={depth}"), - "--enable-restoration=0", - "--enable-palette=0", - "--deltaq-mode=0", - "--enable-filter-intra=0", - "--enable-cfl-intra=0", - "--enable-intrabc=0", - "--lag-in-frames=0", - "--kf-max-dist=9999", - "--tile-columns=0", - "--enable-tx-size-search=0", - "--enable-ab-partitions=0", - "--min-partition-size=8", - "--max-partition-size=64", - // Last occurrence wins (aomenc-last-flag-wins): the three - // flags this gate is about stay last. - "--enable-rect-partitions=1", - "--enable-1to4-partitions=1", - "--enable-cdef=1", - "--obu", - "-o", - "-", - "-", - ]), - &y4m.stdout, - ); - assert!( - out.status.success(), - "aomenc refused the fixture (depth={depth} cq={cq})" - ); - let stream = out.stdout; - let unwritten_before = decode::cdef_unwritten_skip_units(); - let rect_skip_before = decode::rect_skip_band_hits(); - let skipped_before = decode::cdef_skipped_units(); - let decoded = match decode_stream(&stream) { - Ok(f) => f, - Err(e) => { - let msg = e.to_string(); - assert!( - msg.starts_with("unsupported: "), - "decode error that is not a named refusal \ - (depth={depth} cq={cq}): {msg}" - ); - refusals.push(format!("depth={depth} cq={cq}: {msg}")); - continue; - } - }; - assert_eq!(decoded.len(), frames, "frame count (depth={depth} cq={cq})"); - assert_eq!( - decode::cdef_unwritten_skip_units(), - unwritten_before, - "an 8x8 CDEF unit was judged from an UNWRITTEN skip band \ - (a decode arm resolved `skip` without `fill_skip_grid_rect`) \ - (depth={depth} cq={cq})" - ); - let reference = if depth == 10 { - ffmpeg_decode_sequence_10bit(&stream, width, height, frames) - } else { - ffmpeg_decode_sequence(&stream, width, height, frames) - }; - for (i, (ours, theirs)) in decoded.iter().zip(reference.iter()).enumerate() { - assert_eq!(ours.y, theirs.y, "luma frame {i} (depth={depth} cq={cq})"); - assert_eq!(ours.u, theirs.u, "U frame {i} (depth={depth} cq={cq})"); - assert_eq!(ours.v, theirs.v, "V frame {i} (depth={depth} cq={cq})"); - } - // Pixels are asserted for EVERY decoded attempt above; an attempt - // counts as FIRING only if this stream really exercised the class - // (a skipped rect strip wrote the band AND CDEF consulted it via - // the all-skip exclusion). aomenc picking no skipped strip at a - // given cq is a non-firing attempt, never a weakened assert. - let rect_skips = decode::rect_skip_band_hits() - rect_skip_before; - let excluded = decode::cdef_skipped_units() - skipped_before; - if rect_skips == 0 || excluded == 0 { - refusals.push(format!( - "depth={depth} cq={cq}: exact but did not fire \ - (skipped rect strips {rect_skips}, excluded 8x8 units {excluded})" - )); - continue; - } - fired += 1; - } - eprintln!( - "a_real_aomenc_stream_with_skipped_rect_inter_strips_keeps_the_cdef_skip_band: \ - {fired} firing+exact attempts, unwritten skip-band units {}, \ - skipped rect strips {}, 8x8 units excluded {}\n{}", - decode::cdef_unwritten_skip_units(), - decode::rect_skip_band_hits(), - decode::cdef_skipped_units(), - refusals.join("\n") - ); - assert!( - fired >= 3, - "fewer than 3 firing+pixel-exact attempts:\n{}", - refusals.join("\n") - ); - } - - /// lane-sub8 r1: `--min-partition-size=4` on fine-detail noisy gradients - /// at low cq reliably makes aomenc split an 8x8 block all the way to - /// four `BLOCK_4X4` leaves (`PARTITION_SPLIT` below 8x8, spec - /// `decode_partition`'s recursion bottom) -- confirmed with - /// `EC_AV1_TRACE=1` against `examples/decode_probe` before this gate was - /// written (`partition_w8 ... value=3` at mi=(0,0) on the very first - /// block). [`decode::sub8_split_hits`] hard-asserts the path actually - /// ran rather than every attempt landing on `PARTITION_NONE`. - #[test] - fn a_real_aomenc_stream_with_a_sub8_split_decodes_pixel_exact() { - if !have_ffmpeg() { - eprintln!("SKIP a_real_aomenc_stream_with_a_sub8_split_decodes_pixel_exact: no ffmpeg"); - return; - } - if !have_aomenc() { - let msg = format!("no aomenc at {}", aomenc_path().display()); - assert!( - std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none(), - "EC_AV1_REQUIRE_AOMENC is set but {msg}" - ); - eprintln!("SKIP a_real_aomenc_stream_with_a_sub8_split_decodes_pixel_exact: {msg}"); - return; - } - // round 2: `--enable-rect-partitions=0` was added below to keep - // aomenc off HORZ/VERT-below-8x8 elsewhere in the same tile, but it - // is NOT sufficient alone -- see the round-2 report - // (lanes/sub8-r1.report.md) for the live finding: 0/160 attempts - // across both 64x64 and a spatially-isolated single-16x16-leaf - // fixture passed, and every SPLIT that fires is immediately - // followed by a spurious HORZ/VERT read on the very next sibling - // 8x8 leaf, which reads as a real desync left behind by - // `decode_leaf_split4`/`read_intra_mode_sub8`, not an encoder - // choice this recipe can dodge. Tried and rejected: shrinking the - // frame to 16x16 (single 16x16 leaf, at most 4 candidate 8x8s) -- - // that surfaces an UNRELATED pre-existing tiny-frame edge-straddle - // defect (reproduces with zero sub8 code involved, `--min-partition - // -size`/`--max-partition-size` absent entirely), so it is not a - // safe way to isolate the leaf count. Left red; do not "fix" this - // gate by picking fixture parameters that dodge the desync without - // finding it. - // lane-sub8 r6: three arms. The mi-granular mode maps - // (`sub8_mode_col`/`uv_mode_col` and their row twins) are per TILE -- - // the verifier's repro was a 128x64 `--tile-columns=1` stream (seeds - // 207/228) whose every mismatching luma pixel sat at x>=64, the tile - // boundary -- so one arm per tile axis is part of this gate. - for (width, height, tile_args) in [ - (64usize, 64usize, &[][..]), - (128usize, 64usize, &["--tile-columns=1"][..]), - (64usize, 128usize, &["--tile-rows=1"][..]), - ] { - let mut refusals = Vec::new(); - let mut fired_runs = 0u32; - for attempt in 0..40u32 { - let seed = 100 + attempt; - let cq = 6 + (attempt % 4) * 2; - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &gradients_source(seed, width, height, "rate=25"), - "-vf", - // `noise` without `all_seed` re-renders differently on - // every run (seeded-fixture-not-reproducible); pinning it - // makes (seed, cq) name one exact stream. - &format!("noise=alls=40:allf=t:all_seed={seed},format=yuv420p"), - "-t", - "0.04", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let out = run_with_stdin( - Command::new(aomenc_path()) - .args([ - "--codec=av1", - "--passes=1", - "--end-usage=q", - &format!("--cq-level={cq}"), - "--cpu-used=0", - "--threads=1", - "--row-mt=0", - "--sb-size=64", - "--min-partition-size=4", - "--max-partition-size=8", - // Below 8x8 only PARTITION_NONE/SPLIT are decodable (HORZ/VERT - // need a real rectangular transform, see the module doc above); - // disabling rect partitions entirely -- not just AB -- keeps - // aomenc from picking the still-refused HORZ/VERT arms almost - // every attempt (round 2 measured ~90% HORZ/VERT-below-8x8 - // refusals with --enable-ab-partitions=0 alone). - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=1", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-restoration=0", - "--enable-cdef=0", - "--loopfilter-control=0", - // use_ref_frame_mvs (temporal MV projection) is unimplemented in - // mvstack; this is a key-frame-only fixture, but keep it off for - // safety against a run that emits a second frame. - "--enable-ref-frame-mvs=0", - "--limit=1", - "--obu", - "-o", - "-", - "-", - ]) - .args(tile_args), - &y4m.stdout, - ); - if !out.status.success() { - refusals.push(format!( - "seed={seed} cq={cq}: aomenc itself refused the fixture" - )); - continue; - } - let stream = out.stdout; - let before = decode::sub8_split_hits(); - let tiles_before = decode::tile_hits(); - let frames = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => { - // Only a named refusal ("unsupported: ...") is a skip - // reason; any other decode error is this decoder failing. - let msg = e.to_string(); - assert!( - msg.starts_with("unsupported: "), - "decode error that is not a named refusal \ - (seed={seed} cq={cq} tiles={tile_args:?}): {msg}" - ); - refusals.push(format!("seed={seed} cq={cq}: {msg}")); - continue; - } - }; - // gate-blind-to-feature: a tile arm must actually decode more - // than one tile, not merely carry `tile_info.cols > 1`. - assert!( - tile_args.is_empty() || decode::tile_hits() - tiles_before >= 2, - "tiles={tile_args:?} decoded only {} tile(s) (seed={seed} cq={cq})", - decode::tile_hits() - tiles_before - ); - if decode::sub8_split_hits() == before { - refusals.push(format!( - "seed={seed} cq={cq}: decoded, but no block read a real PARTITION_SPLIT below 8x8" - )); - continue; - } - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1); - assert_eq!( - frames[0].y, ffmpeg_frames[0].y, - "luma vs ffmpeg (seed={seed} cq={cq})" - ); - assert_eq!( - frames[0].u, ffmpeg_frames[0].u, - "U vs ffmpeg (seed={seed} cq={cq})" - ); - assert_eq!( - frames[0].v, ffmpeg_frames[0].v, - "V vs ffmpeg (seed={seed} cq={cq})" - ); - fired_runs += 1; - if fired_runs >= 4 { - break; - } - } - assert!( - fired_runs >= 4, - "fewer than 4 firing+pixel-exact runs out of 40 attempts \ - ({width}x{height} tiles={tile_args:?}):\n{}", - refusals.join("\n") - ); - } - } - - /// lane-tx4x8: `--enable-rect-partitions=1` with `--min-partition-size=4 - /// --max-partition-size=8` on fine-detail noisy gradients makes aomenc - /// pick `PARTITION_VERT`/`PARTITION_HORZ` at the 8x8 level -- two - /// `BLOCK_4X8`/`BLOCK_8X4` leaves, the last sub-8x8 shape this decoder - /// refused (it needed a real `TX_4X8`/`TX_8X4`: rect scan, 32-position - /// `eob_pt`, `TX_4X4` `tx_type` row over `TX_8X8` coefficient tables). - /// Both [`decode::tx4x8_coded_hits`] and [`decode::tx8x4_coded_hits`] are - /// hard-asserted per firing attempt so neither orientation can ride along - /// on the other ([[gate-blind-to-feature]]), and only leaves that coded - /// REAL coefficients count -- a skipped leaf never runs the transform. - /// Arms: 8-bit 16x16, an 8-bit `--tile-columns=1` 128x16 (the mi-granular - /// mode maps are per tile), and a 10-bit 16x16 -- 16-pixel fixtures, for - /// the reason the comment inside the loop gives. - #[test] - fn a_real_aomenc_stream_with_a_sub8_rect_leaf_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_stream_with_a_sub8_rect_leaf_decodes_pixel_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - let msg = format!("no aomenc at {}", aomenc_path().display()); - assert!( - std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none(), - "EC_AV1_REQUIRE_AOMENC is set but {msg}" - ); - eprintln!("SKIP {NAME}: {msg}"); - return; - } - // 16-pixel-tall/wide fixtures on purpose: at 64x64 EVERY attempt - // dies on a 16x16-LEVEL rect refusal belonging to other lanes - // ("a HORZ/VERT intra strip with a split transform", "a coded - // (non-skip) HORZ/VERT rect strip below 16x16", "a HORZ_A/HORZ_B/ - // VERT_A partition below 16x16") -- `--max-partition-size=8` does - // NOT stop aomenc coding a 16x16 as two 16x8 strips, measured - // 39/40 attempts refused. A 16x16 frame is one 16x16 block, so the - // encoder either splits it to 8x8s (this lane's path) or codes it - // whole; measured 12/12 attempts decoding, 3/12 with BOTH - // orientations coded. - for (width, height, tile_args, bit_depth) in [ - (16usize, 16usize, &[][..], 8u8), - (128usize, 16usize, &["--tile-columns=1"][..], 8u8), - (16usize, 16usize, &[][..], 10u8), - ] { - let mut refusals = Vec::new(); - let mut fired_runs = 0u32; - let mut split_tx = 0usize; - for attempt in 0..40u32 { - let seed = 300 + attempt; - let cq = 6 + (attempt % 4) * 2; - let pix_fmt = if bit_depth == 10 { - "yuv420p10le" - } else { - "yuv420p" - }; - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &format!("testsrc2=size={width}x{height}:rate=25"), - "-vf", - &format!("noise=alls=40:allf=t:all_seed={seed},format={pix_fmt}"), - "-strict", - "-1", - "-t", - "0.04", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let out = run_with_stdin( - Command::new(aomenc_path()) - .args([ - "--codec=av1", - "--passes=1", - "--end-usage=q", - &format!("--cq-level={cq}"), - "--cpu-used=0", - "--threads=1", - "--row-mt=0", - "--sb-size=64", - "--min-partition-size=4", - "--max-partition-size=8", - // The tool under test: rect partitions ON, at a size - // where the only rect shapes are 4x8 and 8x4. - "--enable-rect-partitions=1", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-restoration=0", - "--enable-cdef=0", - "--loopfilter-control=0", - "--enable-ref-frame-mvs=0", - // Filter intra on a 4x8/8x4 leaf is refused by name - // (`predict_filter_intra` is square-only in this - // decoder, the same refusal the 16x16-level strips - // carry); with it on, that refusal -- not this - // lane's path -- is what most attempts hit. - "--enable-filter-intra=0", - "--limit=1", - "--obu", - "-o", - "-", - "-", - ]) - .args(if bit_depth == 10 { - &["--input-bit-depth=10", "--bit-depth=10"][..] - } else { - &[][..] - }) - .args(tile_args), - &y4m.stdout, - ); - if !out.status.success() { - refusals.push(format!( - "seed={seed} cq={cq}: aomenc itself refused the fixture" - )); - continue; - } - let stream = out.stdout; - let vert_before = decode::tx4x8_coded_hits(); - let horz_before = decode::tx8x4_coded_hits(); - let split_before = decode::rect8_split_tx_hits(); - let tiles_before = decode::tile_hits(); - let frames = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => { - let msg = e.to_string(); - assert!( - msg.starts_with("unsupported: "), - "decode error that is not a named refusal \ - (seed={seed} cq={cq} depth={bit_depth} tiles={tile_args:?}): {msg}" - ); - refusals.push(format!("seed={seed} cq={cq}: {msg}")); - continue; - } - }; - assert!( - tile_args.is_empty() || decode::tile_hits() - tiles_before >= 2, - "tiles={tile_args:?} decoded only {} tile(s) (seed={seed} cq={cq})", - decode::tile_hits() - tiles_before - ); - let vert = decode::tx4x8_coded_hits() - vert_before; - let horz = decode::tx8x4_coded_hits() - horz_before; - if vert == 0 || horz == 0 { - refusals.push(format!( - "seed={seed} cq={cq}: decoded, but coded 4x8={vert} 8x4={horz} leaves" - )); - continue; - } - let ffmpeg_frames = if bit_depth == 10 { - ffmpeg_decode_sequence_10bit(&stream, width, height, 1) - } else { - ffmpeg_decode_sequence(&stream, width, height, 1) - }; - assert_eq!( - frames[0].y, ffmpeg_frames[0].y, - "luma vs ffmpeg (seed={seed} cq={cq} depth={bit_depth} tiles={tile_args:?})" - ); - assert_eq!( - frames[0].u, ffmpeg_frames[0].u, - "U vs ffmpeg (seed={seed} cq={cq} depth={bit_depth})" - ); - assert_eq!( - frames[0].v, ffmpeg_frames[0].v, - "V vs ffmpeg (seed={seed} cq={cq} depth={bit_depth})" - ); - fired_runs += 1; - split_tx += decode::rect8_split_tx_hits() - split_before; - if fired_runs >= 4 { - break; - } - } - assert!( - fired_runs >= 4, - "fewer than 4 firing+pixel-exact runs out of 40 attempts \ - ({width}x{height} depth={bit_depth} tiles={tile_args:?}):\n{}", - refusals.join("\n") - ); - // aomenc's default `--enable-tx-size-search=1` makes TX_MODE_SELECT - // the frame's tx mode, so every sub-8x8 rect leaf carries a - // `tx_depth` symbol; depth 1 (two 4x4 transform units predicted one - // after the other) is the half of that path a whole-leaf transform - // would silently get wrong, so the gate proves it fired. - assert!( - split_tx > 0, - "no sub-8x8 rect leaf used a split (depth-1) transform in the \ - {fired_runs} pixel-exact runs ({width}x{height} depth={bit_depth})" - ); - } - } - - /// lane-fi8 r1: the sub8 rect-leaf gate above with the tool under test - /// turned ON (`--enable-filter-intra=1`, appended AFTER the base recipe - /// -- aomenc takes the FIRST occurrence of a repeated flag, so the base - /// recipe below carries no `--enable-filter-intra` at all). A DC_PRED - /// `BLOCK_4X8`/`BLOCK_8X4` leaf carries a `use_filter_intra` flag - /// (`av1_filter_intra_allowed_bsize` is "both sides <= 32"), which this - /// decoder read from `BLOCK_4X4`'s CDF row until this round -- the same - /// VALUE, a different interval, so it desynced a block or two later - /// ([[wrong-alphabet-same-value]]) -- and then refused the prediction by - /// name. Per attempt, only runs whose [`decode::filter_intra_rect_sub8_hits`] - /// delta is nonzero AND whose three planes match ffmpeg count; the wider - /// `filter_intra_rect_hits` would be satisfied by a 16x8 strip and prove - /// nothing about these shapes. Arms cover both transform depths - /// (`--enable-tx-size-search=1`, where a leaf may split into two 4x4 - /// units each predicted from the previous one's reconstruction, and `=0`, - /// one whole-leaf transform) and both bit depths. - #[test] - fn a_real_aomenc_stream_with_filter_intra_on_a_sub8_rect_leaf_decodes_pixel_exact() { - const NAME: &str = - "a_real_aomenc_stream_with_filter_intra_on_a_sub8_rect_leaf_decodes_pixel_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - let msg = format!("no aomenc at {}", aomenc_path().display()); - assert!( - std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none(), - "EC_AV1_REQUIRE_AOMENC is set but {msg}" - ); - eprintln!("SKIP {NAME}: {msg}"); - return; - } - let (width, height) = (16usize, 16usize); - for (tx_search, bit_depth) in [("1", 8u8), ("0", 8u8), ("1", 10u8)] { - let mut refusals = Vec::new(); - let mut fired_runs = 0u32; - let mut fi_leaves = 0usize; - let mut split_tx = 0usize; - for attempt in 0..80u32 { - let seed = 300 + attempt; - let cq = 6 + (attempt % 8) * 6; - let pix_fmt = if bit_depth == 10 { - "yuv420p10le" - } else { - "yuv420p" - }; - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &format!("testsrc2=size={width}x{height}:rate=25"), - "-vf", - &format!("noise=alls=40:allf=t:all_seed={seed},format={pix_fmt}"), - "-strict", - "-1", - "-t", - "0.04", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let out = run_with_stdin( - Command::new(aomenc_path()) - .args([ - "--codec=av1", - "--passes=1", - "--end-usage=q", - &format!("--cq-level={cq}"), - "--cpu-used=0", - "--threads=1", - "--row-mt=0", - "--sb-size=64", - "--min-partition-size=4", - "--max-partition-size=8", - "--enable-rect-partitions=1", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-restoration=0", - "--enable-cdef=0", - "--loopfilter-control=0", - "--enable-ref-frame-mvs=0", - // The tools under test, first occurrence in the - // command line (aomenc keeps the first). - "--enable-filter-intra=1", - &format!("--enable-tx-size-search={tx_search}"), - "--limit=1", - "--obu", - "-o", - "-", - "-", - ]) - .args(if bit_depth == 10 { - &["--input-bit-depth=10", "--bit-depth=10"][..] - } else { - &[][..] - }), - &y4m.stdout, - ); - if !out.status.success() { - refusals.push(format!("seed={seed} cq={cq}: aomenc itself refused")); - continue; - } - let stream = out.stdout; - let fi_before = decode::filter_intra_rect_sub8_hits(); - let split_before = decode::rect8_split_tx_hits(); - let frames = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => { - let msg = e.to_string(); - assert!( - msg.starts_with("unsupported: "), - "decode error that is not a named refusal \ - (seed={seed} cq={cq} depth={bit_depth} txs={tx_search}): {msg}" - ); - refusals.push(format!("seed={seed} cq={cq}: {msg}")); - continue; - } - }; - let fi = decode::filter_intra_rect_sub8_hits() - fi_before; - if fi == 0 { - refusals.push(format!( - "seed={seed} cq={cq}: decoded, but no 4x8/8x4 leaf used filter intra" - )); - continue; - } - let ffmpeg_frames = if bit_depth == 10 { - ffmpeg_decode_sequence_10bit(&stream, width, height, 1) - } else { - ffmpeg_decode_sequence(&stream, width, height, 1) - }; - assert_eq!( - frames[0].y, ffmpeg_frames[0].y, - "luma vs ffmpeg (seed={seed} cq={cq} depth={bit_depth} txs={tx_search})" - ); - assert_eq!( - frames[0].u, ffmpeg_frames[0].u, - "U vs ffmpeg (seed={seed} cq={cq} depth={bit_depth} txs={tx_search})" - ); - assert_eq!( - frames[0].v, ffmpeg_frames[0].v, - "V vs ffmpeg (seed={seed} cq={cq} depth={bit_depth} txs={tx_search})" - ); - fired_runs += 1; - fi_leaves += fi; - split_tx += decode::rect8_split_tx_hits() - split_before; - if fired_runs >= 3 { - break; - } - } - assert!( - fired_runs >= 3, - "{NAME}: fewer than 3 firing+pixel-exact runs out of 80 attempts \ - (depth={bit_depth} txs={tx_search}), {fi_leaves} filter-intra sub8 leaves \ - seen:\n{}", - refusals.join("\n") - ); - if tx_search == "1" { - assert!( - split_tx > 0, - "{NAME}: no sub-8x8 rect leaf used a split (depth-1) transform in the \ - {fired_runs} pixel-exact runs (depth={bit_depth})" - ); - } - eprintln!( - "{NAME}: depth={bit_depth} txs={tx_search} {fired_runs} pixel-exact runs, \ - {fi_leaves} filter-intra 4x8/8x4 leaves, split_tx={split_tx}" - ); - } - } - - /// lane-tx4x8 r3 ([[enumerate-table-domain]], [[tool-disabled-in-every-gate]]): - /// a 16x8/8x16 intra strip whose DIRECTIONAL mode reads above-right or - /// below-left samples. Which of those the decoder may read is - /// `Reach::of_rect`'s answer, and until this round `rect_reach_tables` - /// had no 16x8 row at all -- every 16x8 strip read libaom's `has_tr_32x16` - /// row instead of `has_tr_16x8`, wrong at 10 of the 21 reachable - /// superblock positions for above-right and 7 for below-left. No gate saw - /// it: the sibling strip gate (`coded_rect_strip_below_16x16`) runs with - /// smooth/paeth/DC modes, which never read past the block, so the wrong - /// bit changed no pixel there. - /// - /// So this gate turns every non-directional intra tool OFF - /// (`--enable-smooth-intra=0 --enable-paeth-intra=0 - /// --enable-filter-intra=0`) at `--min-partition-size=8 - /// --max-partition-size=16 --enable-rect-partitions=1`, and counts, per - /// attempt, the 16x8/8x16 strips whose prediction actually reached past - /// their own width or height ([`decode::rect_strip_reach_hits`], recorded - /// in the predictor's edge fetch). An attempt only counts when that - /// counter moved AND the frame is pixel-exact against ffmpeg. - /// - /// Un-ignored 2026-09-04: the sub-16x16 coded-strip and AB-partition refusals that blocked it are gone and the gate passes. When it was blocked: the 16x16-level strip decoder - /// refuses every NON-SKIP 16x8/8x16 strip ("a coded (non-skip) HORZ/VERT - /// rect strip below 16x16", `decode.rs`), and that is what real streams - /// contain -- measured on this exact recipe, 38 of 40 attempts died on - /// that refusal and 2 on a sub-16x16 AB partition, at cq 30/45/58 and at - /// `--min-partition-size=16` (which yields no 16x8 at all, aomenc bounds a - /// rect shape by its smaller side). The table routing is also pinned by the domain test - /// `encode::tests::every_rect_shape_reaches_what_libaom_says_over_the_whole_superblock` - /// against libaom's own `has_tr_*`/`has_bl_*` arrays. - #[test] - fn a_directional_16x8_strip_reads_the_right_above_right_samples() { - const NAME: &str = "a_directional_16x8_strip_reads_the_right_above_right_samples"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - let msg = format!("no aomenc at {}", aomenc_path().display()); - assert!( - std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none(), - "EC_AV1_REQUIRE_AOMENC is set but {msg}" - ); - eprintln!("SKIP {NAME}: {msg}"); - return; - } - // 64x16, not 64x64: a 16-tall frame is a single row of 16x16 blocks, - // so a HORZ arm is a 16x8 strip at column 0..3 of the superblock -- - // exactly the positions whose `has_tr_16x8`/`has_bl_16x8` bit the old - // routing got wrong -- while the frame is too short for aomenc to - // build the deep sub-16x16 partitions other lanes still refuse. It - // must also be WIDER than one block: at width 16 the block is the - // frame, and `x + bw < width` kills above-right before any table. - for (width, height, bit_depth) in [(64usize, 16usize, 8u8), (64, 16, 10u8)] { - let mut refusals = Vec::new(); - let mut fired_runs = 0u32; - let mut reach_hits = 0usize; - for attempt in 0..40u32 { - let seed = 700 + attempt; - // Coarse quantisers on lightly-dithered content: fine detail - // at low cq makes aomenc build the sub-16x16 partitions other - // lanes refuse, and 40/40 attempts died there. - let cq = 45 + (attempt % 4); - let half = height / 2; - let pix_fmt = if bit_depth == 10 { - "yuv420p10le" - } else { - "yuv420p" - }; - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &format!("testsrc2=size={width}x{half}:rate=25"), - "-f", - "lavfi", - "-i", - &format!("color=c=gray:s={width}x{half}:rate=25"), - "-filter_complex", - &format!( - "[0]noise=alls=8:allf=t:all_seed={seed}[t];[t][1]vstack,\ - format={pix_fmt}" - ), - "-strict", - "-1", - "-t", - "0.04", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let out = run_with_stdin( - Command::new(aomenc_path()) - .args([ - "--codec=av1", - "--passes=1", - "--end-usage=q", - &format!("--cq-level={cq}"), - "--cpu-used=0", - "--threads=1", - "--row-mt=0", - "--sb-size=64", - // The tool under test: 16x8/8x16 strips, predicted by - // a mode that reads beyond the block. - // aomenc bounds a RECT shape by its smaller side, so - // `--min-partition-size=16` yields no 16x8 at all - // (measured: 0 strips in 40 attempts); 8 is the - // smallest value that lets a 16x16 split HORZ/VERT. - "--min-partition-size=8", - "--max-partition-size=16", - // Largest transform per block: a split (depth-1) rect - // strip is a named refusal of another lane, and it - // ate every attempt while it was on. - "--enable-tx-size-search=0", - "--enable-rect-partitions=1", - "--enable-directional-intra=1", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-filter-intra=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-restoration=0", - "--enable-cdef=0", - "--loopfilter-control=0", - "--enable-ref-frame-mvs=0", - "--limit=1", - "--obu", - "-o", - "-", - "-", - ]) - .args(if bit_depth == 10 { - &["--input-bit-depth=10", "--bit-depth=10"][..] - } else { - &[][..] - }), - &y4m.stdout, - ); - if !out.status.success() { - refusals.push(format!( - "seed={seed} cq={cq}: aomenc itself refused the fixture" - )); - continue; - } - let stream = out.stdout; - let reach_before = decode::rect_strip_reach_hits(); - let pred_before = decode::rect_strip_pred_hits(); - let frames = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => { - let msg = e.to_string(); - assert!( - msg.starts_with("unsupported: "), - "decode error that is not a named refusal \ - (seed={seed} cq={cq} depth={bit_depth}): {msg}" - ); - refusals.push(format!("seed={seed} cq={cq}: {msg}")); - continue; - } - }; - let reached = decode::rect_strip_reach_hits() - reach_before; - let predicted = decode::rect_strip_pred_hits() - pred_before; - if predicted == 0 { - refusals.push(format!( - "seed={seed} cq={cq}: decoded, but no 16x8/8x16 strip in the frame" - )); - continue; - } - let ffmpeg_frames = if bit_depth == 10 { - ffmpeg_decode_sequence_10bit(&stream, width, height, 1) - } else { - ffmpeg_decode_sequence(&stream, width, height, 1) - }; - assert_eq!( - frames[0].y, ffmpeg_frames[0].y, - "luma vs ffmpeg (seed={seed} cq={cq} depth={bit_depth}, {predicted} strips, \ - {reached} of them reaching)" - ); - assert_eq!( - frames[0].u, ffmpeg_frames[0].u, - "U vs ffmpeg (seed={seed} cq={cq} depth={bit_depth})" - ); - assert_eq!( - frames[0].v, ffmpeg_frames[0].v, - "V vs ffmpeg (seed={seed} cq={cq} depth={bit_depth})" - ); - fired_runs += 1; - reach_hits += reached; - if fired_runs >= 4 { - break; - } - } - assert!( - fired_runs >= 4, - "fewer than 4 firing+pixel-exact runs out of 40 attempts \ - ({width}x{height} depth={bit_depth}, {reach_hits} reaching strips):\n{}", - refusals.join("\n") - ); - } - } - - /// lane-av1golden7 r9's decisive fixture: a real aomenc stream (seed 59, - /// `--tune-content=film`, GOLDEN_FRAME firing downstream) whose frame-0 - /// *intra keyframe* mismatched ffmpeg on 3855/4096 luma pixels -- traced - /// to `apply_grain=true` (spec 7.18.3 grain synthesis, now implemented in - /// `crate::film_grain`), entirely unrelated to GOLDEN_FRAME or frame - /// ordering. Frames beyond 0 in this fixture hit an unrelated, pre-existing - /// gap (`decode_inter_block`'s GOLDEN_FRAME MC path, lane-av1golden7's own - /// `golden7-forwarding-mismatch.obu`), so this test truncates the stream to - /// the sequence header + frame-0 OBUs only -- exactly the span the - /// mismatch was traced to -- rather than reaching into `decode.rs`/`mc.rs` - /// to widen MC support, which is out of this lane's scope. - #[test] - fn a_real_aomenc_stream_with_film_grain_decodes_pixel_exact() { - if !have_ffmpeg() { - eprintln!("SKIP a_real_aomenc_stream_with_film_grain_decodes_pixel_exact: no ffmpeg"); - return; - } - // lane-av1pinslive r3: this gate was LIVE while reading a GITIGNORED - // pin through a `concat!` literal and `.unwrap()` -- a clean checkout - // with no runner library PANICKED here rather than skipping. The bytes - // are now committed at `crates/ec-av1/fixtures/golden6-mismatch.obu` - // (452 bytes; sha256 - // `c56909b98542192b03f3a945e153475aa57a58a1586bf166513297296cb225b3`, - // recovered byte-for-byte from the runner library). - let data = require_pin( - &std::env::var("EC_AV1_GATE_DUMP_PIN") - .map(std::path::PathBuf::from) - .unwrap_or_else(|_| crate_pin("golden6-mismatch.obu")), - "golden6-mismatch.obu", - ); - // Truncate right after the first `Frame` OBU (the key frame): every - // byte up to there is sequence header + frame-0, which is a complete, - // independently decodable single-frame stream. - let mut parser = Av1Parser::new(); - let mut pos = 0usize; - let mut frame0_end = None; - while pos < data.len() { - let obu = parser.parse_obu(&data[pos..]).unwrap(); - pos += obu.total_size; - if matches!(obu.kind, ObuKind::Frame(..)) { - frame0_end = Some(pos); - break; - } - } - let data = &data[..frame0_end.expect("fixture has at least one frame OBU")]; - let (width, height) = (64usize, 64usize); - let ffmpeg_frames = ffmpeg_decode_sequence(data, width, height, 1); - let decoded = decode_stream(data).unwrap(); - assert_eq!(decoded.len(), 1); - let (got, want) = (&decoded[0], &ffmpeg_frames[0]); - assert_eq!(got.y, want.y, "frame 0 luma vs ffmpeg (film grain)"); - assert_eq!(got.u, want.u, "frame 0 U vs ffmpeg (film grain)"); - assert_eq!(got.v, want.v, "frame 0 V vs ffmpeg (film grain)"); - } - - /// A real-encoder sweep, not just the one pinned fixture above - /// (fixture-proves-symbol-not-signal class): several fresh - /// `--tune-content=film` draws at different seeds/content, each decoded - /// pixel-exact against ffmpeg's own AV1 decoder (which synthesizes grain - /// by default -- confirmed via `ffmpeg -h decoder=av1`, no - /// `-export_side_data`/grain-disable flag is passed anywhere in this - /// file). - #[test] - fn real_aomenc_film_grain_streams_decode_pixel_exact() { - if !have_ffmpeg() { - eprintln!("SKIP real_aomenc_film_grain_streams_decode_pixel_exact: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP real_aomenc_film_grain_streams_decode_pixel_exact: no aomenc"); - return; - } - let (width, height) = (64usize, 64usize); - for seed in [1u64, 2, 3] { - let dir = std::env::temp_dir().join(format!( - "ec-av1-filmgrain-gate-{}-{seed}", - std::process::id() - )); - std::fs::create_dir_all(&dir).unwrap(); - let yuv_path = dir.join("in.yuv"); - let obu_path = dir.join("out.obu"); - let frames = 3usize; - let luma = width * height; - let chroma = luma / 4; - let mut yuv = Vec::with_capacity((luma + 2 * chroma) * frames); - for f in 0..frames { - let card = panned_test_card(width, height, ((f as i32 + seed as i32) * 5) as i64); - yuv.extend(card.y.iter().map(|&v| v as u8)); - yuv.extend(card.u.iter().map(|&v| v as u8)); - yuv.extend(card.v.iter().map(|&v| v as u8)); - } - std::fs::write(&yuv_path, &yuv).unwrap(); - let status = Command::new(aomenc_path()) - .args([ - &format!("--width={width}"), - &format!("--height={height}"), - "--input-bit-depth=8", - "--bit-depth=8", - "--fps=25/1", - &format!("--limit={frames}"), - // The full constraint set of the forwarding/golden gates, - // so the streams stay inside this decoder's supported - // envelope and the gate isolates grain synthesis alone; - // `--tune-content=film` is the one flag under test (it - // enables apply_grain). - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=32", - "--cpu-used=0", - "--lag-in-frames=0", - "--auto-alt-ref=0", - "--kf-max-dist=1000", - "--threads=1", - "--row-mt=0", - "--max-reference-frames=3", - "--reduced-reference-set=1", - "--enable-warped-motion=0", - "--enable-obmc=0", - "--enable-masked-comp=0", - "--enable-interintra-comp=0", - "--enable-dist-wtd-comp=0", - "--enable-diff-wtd-comp=0", - "--enable-onesided-comp=0", - "--enable-interintra-wedge=0", - "--enable-smooth-interintra=0", - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-tx-size-search=0", - "--enable-cdef=0", - "--enable-restoration=0", - "--max-partition-size=32", - "--min-partition-size=32", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - // Temporal MV projection (`use_ref_frame_mvs`) has no - // decode path here (`mvstack.rs`'s documented corner-cut: - // `zero_mv_ctx` and the mode-context GLOBALMV_OFFSET bit - // are always computed as if it were off) -- this gate - // isolates grain synthesis, so it must stay inside that - // envelope like every other feature disabled above, not - // silently decode a wrong mode context. Root cause of - // this test's frame-1 mismatch: aomenc turns - // `use_ref_frame_mvs` on by default once order hints are - // enabled, unrelated to `--tune-content=film`. - "--enable-ref-frame-mvs=0", - "--tune-content=film", - "--obu", - "-o", - ]) - .arg(&obu_path) - .arg(&yuv_path) - .stdout(Stdio::null()) - .stderr(Stdio::null()) - .status() - .expect("aomenc failed to start"); - assert!(status.success(), "aomenc failed for seed {seed}"); - let encoded = std::fs::read(&obu_path).unwrap(); - let _ = std::fs::remove_dir_all(&dir); - - let mut parser = ec_av1_syntax::Av1Parser::new(); - let mut pos = 0usize; - let mut saw_grain = false; - while pos < encoded.len() { - let obu = parser.parse_obu(&encoded[pos..]).unwrap(); - pos += obu.total_size; - if let ec_av1_syntax::ObuKind::Frame(header, _) = obu.kind - && header.film_grain.apply_grain - { - saw_grain = true; - } - } - assert!(saw_grain, "seed {seed}: aomenc did not turn on apply_grain"); - - let ffmpeg_frames = ffmpeg_decode_sequence(&encoded, width, height, frames); - let decoded = decode_stream(&encoded).unwrap(); - assert_eq!(decoded.len(), frames, "seed {seed}"); - for (i, (got, want)) in decoded.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!(got.y, want.y, "seed {seed} frame {i} luma vs ffmpeg"); - assert_eq!(got.u, want.u, "seed {seed} frame {i} U vs ffmpeg"); - assert_eq!(got.v, want.v, "seed {seed} frame {i} V vs ffmpeg"); - } - } - } - - /// lane-tiles r3/r7: a real two-tile-column aomenc key frame, decoded - /// through [`decode_key_frame_tile_with_cdfs`] directly with the whole - /// `tiles: &[&[u8]]` list -- `decode_stream`'s `cols > 1 || rows > 1` - /// refusal (this file, ~line 292) still fires for any stream this wide, - /// so this gate bypasses it on purpose to prove the per-tile loop r2 - /// landed (fresh `SymbolDecoder`/CDF copy per tile, `Neighbours::start_tile`, - /// `PlaneBuf::set_tile_origin`) actually decodes both tiles pixel-exact - /// before that refusal is lifted. 128x64 is exactly two 64x64 - /// superblocks wide with `--tile-columns=1` (`TileCols=2`), so tile 1 is - /// also the frame's own right edge -- the known gap (`PlaneBuf`'s - /// tile_x0/tile_y0 only clip left/top reach, not a non-last column's - /// right-edge reach) does not apply to this fixture; it would to a - /// 3+-column one, proven separately by the four-tile-column gate below. - /// r7: `--loopfilter-control=0` REMOVED per the charter -- `PlaneBuf`'s - /// `tile_x1`/`tile_y1` clamps now receive real values at every call site - /// (r6's `set_tile_origin` sweep), so this gate now proves real - /// deblocking across the tile boundary too, not just decode with it off. - /// Tile count itself is a structural aomenc param, not - /// RD-dependent content, but this decoder's chroma smooth/paeth gap - /// (`decode.rs` "a smooth or paeth chroma mode (round 2)", unrelated to - /// tiles, pre-dating this lane) is content-dependent -- no aomenc flag - /// disables UV-only smooth/paeth search, so a small seed sweep is - /// needed the same way the sibling `a_real_aomenc_stream_with_*` gates - /// retry past unrelated named refusals (every refusal in this crate is - /// prefixed `"AV1 tile"` regardless of category, so unlike the sibling - /// gates' `warp`/`obmc`/`interintra` banned lists there is no - /// tile-specific substring to forbid here -- `matched > 0` plus the - /// hard `tile_hits > 1`/pixel-exact asserts on any actual decode are - /// the real proof). - #[test] - fn a_real_aomenc_stream_with_two_tile_columns_decodes_pixel_exact() { - let fctx = &crate::decode::FrameCtx::new(); - const NAME: &str = "a_real_aomenc_stream_with_two_tile_columns_decodes_pixel_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height) = (128usize, 64usize); - let mut matched = 0u32; - let mut named_refusals = 0u32; - // lane-modectx r1: luma `kf_y_mode` neighbour reads whose coarse - // fallback band held a previous tile's mode at a tile edge. Measured 0 - // -- `above_mode` is cleared per tile and `left_mode` per superblock - // row -- and that is exactly why the coarse fallback is safe where - // lane-mtfix's chroma one was not. Accumulated only for attempts that - // then compared pixel-exact (class counter-from-refused-stream). - let mut mode_edge_leaks = 0usize; - for attempt in 0..20u32 { - let seed = 42 + attempt; - let source = gradients_source(seed, width, height, "duration=0.04:rate=25"); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-pix_fmt", - "yuv420p", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let out = run_with_stdin( - Command::new(aomenc_path()).args([ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=45", - "--cpu-used=0", - "--limit=1", - "--kf-max-dist=1000", - "--threads=1", - "--row-mt=0", - "--tile-columns=1", - "--tile-rows=0", - // This decoder hardcodes SB_MI=16 (64px) superblocks - // everywhere (`decode.rs`'s sb128 dead-end, ledger - // `av1-superblock-contexts`) -- without this, aomenc's - // own default 128x128 superblock makes 128x64 exactly - // ONE superblock wide, so `--tile-columns=1` has nothing - // to split and `cols` comes back 1. - "--sb-size=64", - // Deblocking crosses tile boundaries by default (spec - // `loop_filter_across_tiles_enabled`); `PlaneBuf`'s - // tile_x0/tile_y0 origin only ever clips a tile's own - // left/top reach (r2/r3's documented known gap), so a - // non-last tile column's right-edge deblock would read - // into the next tile's still-undecoded/differently- - // origined samples. Off here since deblocking itself is - // not what this gate is proving. - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-tx-size-search=0", - "--enable-cdef=0", - "--enable-restoration=0", - "--max-partition-size=32", - "--min-partition-size=32", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - "--obu", - "-o", - "-", - "-", - ]), - &y4m.stdout, - ); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - - // Parse the stream ourselves (rather than `decode_stream`, whose - // multi-tile refusal is exactly what this gate exists to run - // ahead of) to reach the real `Frame` OBU's `tile_info` and its - // full `Vec` -- `Av1Parser::parse_obu` already locates - // every tile in a multi-tile tile group (`parse_tile_group`), it - // is only `decode_stream` that ever narrows this to - // `tiles.first()`. - let mut parser = Av1Parser::new(); - let mut pos = 0usize; - let mut frame = None; - while pos < stream.len() { - let obu_offset = pos; - let obu = parser.parse_obu(&stream[pos..]).unwrap(); - pos += obu.total_size; - if let ObuKind::Frame(header, tiles) = obu.kind { - frame = Some((header, tiles, obu_offset)); - break; - } - } - let (header, tiles, obu_offset) = frame.expect("stream has a Frame OBU"); - assert!( - header.tile_info.cols > 1, - "{NAME}: aomenc did not actually split into >1 tile column (cols={}, seed {seed})", - header.tile_info.cols - ); - assert_eq!( - tiles.len(), - header.tile_info.cols as usize, - "{NAME}: expected one tile per column (seed {seed})" - ); - // `Tile::offset` is relative to the buffer `parse_obu` was - // handed (`&stream[pos..]` at the time this OBU was parsed), so - // it needs `obu_offset` added back -- the same adjustment - // `decode_stream` makes for its own single-tile slice above. - let tile_bufs: Vec<&[u8]> = tiles - .iter() - .map(|t| &stream[obu_offset + t.offset..obu_offset + t.offset + t.size]) - .collect(); - - let enable_filter_intra = parser - .sequence_header() - .is_some_and(|seq| seq.enable_filter_intra); - let enable_edge_filter = parser - .sequence_header() - .is_some_and(|seq| seq.enable_intra_edge_filter); - - let before = crate::decode::tile_hits(); - let before_edge = crate::decode::mode_tile_edge_coarse_leaks(); - let picture = match decode_key_frame_tile_with_cdfs( - &tile_bufs, - &header.tile_info, - header.mi_cols, - header.mi_rows, - header.quantization.base_q_idx, - crate::quant::QuantDeltas { - y_dc: i32::from(header.quantization.delta_q_y_dc), - u_dc: i32::from(header.quantization.delta_q_u_dc), - u_ac: i32::from(header.quantization.delta_q_u_ac), - v_dc: i32::from(header.quantization.delta_q_v_dc), - v_ac: i32::from(header.quantization.delta_q_v_ac), - }, - header.frame_width, - header.frame_height, - enable_filter_intra, - enable_edge_filter, - &header.cdef, - &header.loop_filter, - &header.loop_restoration, - None, - header.tx_mode == TxMode::Select, - header.reduced_tx_set, - header.allow_screen_content_tools, - header.allow_intrabc, - header.delta, - fctx, - ) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME} failed outright, not a named refusal (seed {seed}): {msg}" - ); - named_refusals += 1; - eprintln!("seed {seed} refusal: {msg}"); - continue; - } - Ok((picture, _end_cdfs)) => picture, - }; - let hits = crate::decode::tile_hits() - before; - assert!( - hits > 1, - "{NAME}: tile_hits delta was {hits}, expected >1 -- both tiles must actually \ - decode, not just tile 0 (seed {seed})" - ); - - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1); - assert_eq!( - picture.y, ffmpeg_frames[0].y, - "{NAME}: luma vs ffmpeg (seed {seed})" - ); - assert_eq!( - picture.u, ffmpeg_frames[0].u, - "{NAME}: U vs ffmpeg (seed {seed})" - ); - assert_eq!( - picture.v, ffmpeg_frames[0].v, - "{NAME}: V vs ffmpeg (seed {seed})" - ); - mode_edge_leaks += crate::decode::mode_tile_edge_coarse_leaks() - before_edge; - matched += 1; - } - assert!( - matched > 0, - "{NAME}: every attempt refused ({named_refusals} refusals); the gate never decoded \ - a two-tile-column stream" - ); - assert_eq!( - mode_edge_leaks, 0, - "{NAME}: a luma mode neighbour read at a tile edge saw a NON-DC coarse band -- the \ - per-tile `above_mode` / per-superblock-row `left_mode` reset that makes the coarse \ - fallback safe has regressed" - ); - eprintln!( - "{NAME}: {matched} pixel-exact matches, {named_refusals} named refusals out of 20, \ - {mode_edge_leaks} tile-edge coarse leaks" - ); - } - - /// lane-tiles r8 stage 1: the same bypass-the-refusal pattern as the - /// two-tile-column gate above, this time for tile ROWS -- `decode_stream` - /// still refuses any `tile_info.rows > 1` stream, so this gate calls - /// [`decode_key_frame_tile_with_cdfs`] directly to prove the underlying - /// per-tile loop (already row/col-generic: `tile_num / tile_info.cols` - /// gives the row, `mi_row_starts`/`set_tile_origin`'s `y0`/`y1` are - /// exactly symmetric with the column gate's `x0`/`x1`) actually decodes - /// both tile rows pixel-exact before the refusal is lifted. 64x128 is - /// one 64px superblock wide and two tall with `--tile-rows=1` - /// (`TileRows=2`, `--tile-columns=0` keeps `cols=1` so only the row axis - /// is under test). Loop filter is left ON (no - /// `--loopfilter-control=0`) per the charter -- deblocking crosses tile - /// row boundaries by spec default exactly as it crosses column ones, and - /// `deblock_plane` runs once over the whole decoded picture after every - /// tile is in, with no tile-axis distinction, so there is no reason to - /// expect the row boundary to behave differently from the column one r7 - /// already proved -- this gate is what actually proves it either way. - #[test] - fn a_real_aomenc_stream_with_two_tile_rows_decodes_pixel_exact() { - let fctx = &crate::decode::FrameCtx::new(); - const NAME: &str = "a_real_aomenc_stream_with_two_tile_rows_decodes_pixel_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height) = (64usize, 128usize); - let mut matched = 0u32; - let mut named_refusals = 0u32; - for attempt in 0..20u32 { - let seed = 42 + attempt; - let source = gradients_source(seed, width, height, "duration=0.04:rate=25"); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-pix_fmt", - "yuv420p", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let out = run_with_stdin( - Command::new(aomenc_path()).args([ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=45", - "--cpu-used=0", - "--limit=1", - "--kf-max-dist=1000", - "--threads=1", - "--row-mt=0", - "--tile-columns=0", - "--tile-rows=1", - // This decoder hardcodes SB_MI=16 (64px) superblocks - // everywhere; without this aomenc's own default 128x128 - // superblock makes 64x128 exactly ONE superblock tall, - // so `--tile-rows=1` has nothing to split. - "--sb-size=64", - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-tx-size-search=0", - "--enable-cdef=0", - "--enable-restoration=0", - "--max-partition-size=32", - "--min-partition-size=32", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - "--obu", - "-o", - "-", - "-", - ]), - &y4m.stdout, - ); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - - let mut parser = Av1Parser::new(); - let mut pos = 0usize; - let mut frame = None; - while pos < stream.len() { - let obu_offset = pos; - let obu = parser.parse_obu(&stream[pos..]).unwrap(); - pos += obu.total_size; - if let ObuKind::Frame(header, tiles) = obu.kind { - frame = Some((header, tiles, obu_offset)); - break; - } - } - let (header, tiles, obu_offset) = frame.expect("stream has a Frame OBU"); - assert!( - header.tile_info.rows > 1, - "{NAME}: aomenc did not actually split into >1 tile row (rows={}, seed {seed})", - header.tile_info.rows - ); - assert_eq!( - tiles.len(), - header.tile_info.rows as usize, - "{NAME}: expected one tile per row (cols=1, seed {seed})" - ); - let tile_bufs: Vec<&[u8]> = tiles - .iter() - .map(|t| &stream[obu_offset + t.offset..obu_offset + t.offset + t.size]) - .collect(); - - let enable_filter_intra = parser - .sequence_header() - .is_some_and(|seq| seq.enable_filter_intra); - let enable_edge_filter = parser - .sequence_header() - .is_some_and(|seq| seq.enable_intra_edge_filter); - - let before = crate::decode::tile_hits(); - let picture = match decode_key_frame_tile_with_cdfs( - &tile_bufs, - &header.tile_info, - header.mi_cols, - header.mi_rows, - header.quantization.base_q_idx, - crate::quant::QuantDeltas { - y_dc: i32::from(header.quantization.delta_q_y_dc), - u_dc: i32::from(header.quantization.delta_q_u_dc), - u_ac: i32::from(header.quantization.delta_q_u_ac), - v_dc: i32::from(header.quantization.delta_q_v_dc), - v_ac: i32::from(header.quantization.delta_q_v_ac), - }, - header.frame_width, - header.frame_height, - enable_filter_intra, - enable_edge_filter, - &header.cdef, - &header.loop_filter, - &header.loop_restoration, - None, - header.tx_mode == TxMode::Select, - header.reduced_tx_set, - header.allow_screen_content_tools, - header.allow_intrabc, - header.delta, - fctx, - ) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME} failed outright, not a named refusal (seed {seed}): {msg}" - ); - named_refusals += 1; - eprintln!("seed {seed} refusal: {msg}"); - continue; - } - Ok((picture, _end_cdfs)) => picture, - }; - let hits = crate::decode::tile_hits() - before; - assert!( - hits > 1, - "{NAME}: tile_hits delta was {hits}, expected >1 -- both tile rows must actually \ - decode, not just tile 0 (seed {seed})" - ); - - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1); - assert_eq!( - picture.y, ffmpeg_frames[0].y, - "{NAME}: luma vs ffmpeg (seed {seed})" - ); - assert_eq!( - picture.u, ffmpeg_frames[0].u, - "{NAME}: U vs ffmpeg (seed {seed})" - ); - assert_eq!( - picture.v, ffmpeg_frames[0].v, - "{NAME}: V vs ffmpeg (seed {seed})" - ); - matched += 1; - } - assert!( - matched > 0, - "{NAME}: every attempt refused ({named_refusals} refusals); the gate never decoded \ - a two-tile-row stream" - ); - eprintln!( - "{NAME}: {matched} pixel-exact matches, {named_refusals} named refusals out of 20" - ); - } - - /// lane-tiles r8 stage 2/3: the same two-tile-row stream as the bypass - /// gate above, this time through `decode_stream` itself -- the entry - /// point real callers use, with the `rows > 1` refusal lifted (same - /// commit) so this actually reaches the tile decode instead of - /// refusing by name. Loop filter ON, no `--loopfilter-control=0`. - #[test] - fn a_real_aomenc_stream_with_two_tile_rows_decodes_through_decode_stream() { - const NAME: &str = "a_real_aomenc_stream_with_two_tile_rows_decodes_through_decode_stream"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height) = (64usize, 128usize); - let mut matched = 0u32; - let mut named_refusals = 0u32; - for attempt in 0..20u32 { - let seed = 42 + attempt; - let source = gradients_source(seed, width, height, "duration=0.04:rate=25"); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-pix_fmt", - "yuv420p", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let out = run_with_stdin( - Command::new(aomenc_path()).args([ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=45", - "--cpu-used=0", - "--limit=1", - "--kf-max-dist=1000", - "--threads=1", - "--row-mt=0", - "--tile-columns=0", - "--tile-rows=1", - "--sb-size=64", - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-tx-size-search=0", - "--enable-cdef=0", - "--enable-restoration=0", - "--max-partition-size=32", - "--min-partition-size=32", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - "--obu", - "-o", - "-", - "-", - ]), - &y4m.stdout, - ); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - - let before = crate::decode::tile_hits(); - let pictures = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME} failed outright, not a named refusal (seed {seed}): {msg}" - ); - named_refusals += 1; - eprintln!("seed {seed} refusal: {msg}"); - continue; - } - Ok(pictures) => pictures, - }; - let hits = crate::decode::tile_hits() - before; - assert!( - hits > 1, - "{NAME}: tile_hits delta was {hits}, expected >1 -- both tile rows must actually \ - decode, not just tile 0 (seed {seed})" - ); - assert_eq!( - pictures.len(), - 1, - "{NAME}: expected exactly 1 picture (seed {seed})" - ); - - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1); - assert_eq!( - pictures[0].y, ffmpeg_frames[0].y, - "{NAME}: luma vs ffmpeg (seed {seed})" - ); - assert_eq!( - pictures[0].u, ffmpeg_frames[0].u, - "{NAME}: U vs ffmpeg (seed {seed})" - ); - assert_eq!( - pictures[0].v, ffmpeg_frames[0].v, - "{NAME}: V vs ffmpeg (seed {seed})" - ); - matched += 1; - } - assert!( - matched > 0, - "{NAME}: every attempt refused ({named_refusals} refusals); decode_stream never \ - decoded a two-tile-row stream" - ); - eprintln!( - "{NAME}: {matched} pixel-exact matches, {named_refusals} named refusals out of 20" - ); - } - - /// lane-tiles r7: the `>2 tile columns` refusal's own capability, proven - /// separately from the 2-column gate above -- `--tile-columns=2` gives - /// aomenc `TileCols=4` (log2), a real non-last-column right-edge case the - /// 2-column fixture cannot exercise (there tile 1 IS the frame's right - /// edge). 256x64 is four 64x64 superblocks wide with `--sb-size=64`, so - /// each tile column is exactly one superblock. Loop filtering stays ON - /// (no `--loopfilter-control=0`) to prove the same reach-bound fix also - /// covers deblocking across an *interior* tile boundary, not just the - /// 2-column case's boundary-that-is-also-the-frame-edge. - #[test] - fn a_real_aomenc_stream_with_four_tile_columns_decodes_pixel_exact() { - let fctx = &crate::decode::FrameCtx::new(); - const NAME: &str = "a_real_aomenc_stream_with_four_tile_columns_decodes_pixel_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height) = (256usize, 64usize); - let mut matched = 0u32; - let mut named_refusals = 0u32; - for attempt in 0..20u32 { - let seed = 42 + attempt; - let source = gradients_source(seed, width, height, "duration=0.04:rate=25"); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-pix_fmt", - "yuv420p", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let out = run_with_stdin( - Command::new(aomenc_path()).args([ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=45", - "--cpu-used=0", - "--limit=1", - "--kf-max-dist=1000", - "--threads=1", - "--row-mt=0", - "--tile-columns=2", - "--tile-rows=0", - "--sb-size=64", - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-tx-size-search=0", - "--enable-cdef=0", - "--enable-restoration=0", - "--max-partition-size=32", - "--min-partition-size=32", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - "--obu", - "-o", - "-", - "-", - ]), - &y4m.stdout, - ); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - - let mut parser = Av1Parser::new(); - let mut pos = 0usize; - let mut frame = None; - while pos < stream.len() { - let obu_offset = pos; - let obu = parser.parse_obu(&stream[pos..]).unwrap(); - pos += obu.total_size; - if let ObuKind::Frame(header, tiles) = obu.kind { - frame = Some((header, tiles, obu_offset)); - break; - } - } - let (header, tiles, obu_offset) = frame.expect("stream has a Frame OBU"); - assert!( - header.tile_info.cols > 2, - "{NAME}: aomenc did not actually split into >2 tile columns (cols={}, seed {seed})", - header.tile_info.cols - ); - assert_eq!( - tiles.len(), - header.tile_info.cols as usize, - "{NAME}: expected one tile per column (seed {seed})" - ); - let tile_bufs: Vec<&[u8]> = tiles - .iter() - .map(|t| &stream[obu_offset + t.offset..obu_offset + t.offset + t.size]) - .collect(); - - let enable_filter_intra = parser - .sequence_header() - .is_some_and(|seq| seq.enable_filter_intra); - let enable_edge_filter = parser - .sequence_header() - .is_some_and(|seq| seq.enable_intra_edge_filter); - - let before = crate::decode::tile_hits(); - let picture = match decode_key_frame_tile_with_cdfs( - &tile_bufs, - &header.tile_info, - header.mi_cols, - header.mi_rows, - header.quantization.base_q_idx, - crate::quant::QuantDeltas { - y_dc: i32::from(header.quantization.delta_q_y_dc), - u_dc: i32::from(header.quantization.delta_q_u_dc), - u_ac: i32::from(header.quantization.delta_q_u_ac), - v_dc: i32::from(header.quantization.delta_q_v_dc), - v_ac: i32::from(header.quantization.delta_q_v_ac), - }, - header.frame_width, - header.frame_height, - enable_filter_intra, - enable_edge_filter, - &header.cdef, - &header.loop_filter, - &header.loop_restoration, - None, - header.tx_mode == TxMode::Select, - header.reduced_tx_set, - header.allow_screen_content_tools, - header.allow_intrabc, - header.delta, - fctx, - ) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME} failed outright, not a named refusal (seed {seed}): {msg}" - ); - named_refusals += 1; - eprintln!("seed {seed} refusal: {msg}"); - continue; - } - Ok((picture, _end_cdfs)) => picture, - }; - let hits = crate::decode::tile_hits() - before; - assert!( - hits > 2, - "{NAME}: tile_hits delta was {hits}, expected >2 -- all four tiles must actually \ - decode, not just a subset (seed {seed})" - ); - - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1); - assert_eq!( - picture.y, ffmpeg_frames[0].y, - "{NAME}: luma vs ffmpeg (seed {seed})" - ); - assert_eq!( - picture.u, ffmpeg_frames[0].u, - "{NAME}: U vs ffmpeg (seed {seed})" - ); - assert_eq!( - picture.v, ffmpeg_frames[0].v, - "{NAME}: V vs ffmpeg (seed {seed})" - ); - matched += 1; - } - assert!( - matched > 0, - "{NAME}: every attempt refused ({named_refusals} refusals); the gate never decoded \ - a four-tile-column stream" - ); - eprintln!( - "{NAME}: {matched} pixel-exact matches, {named_refusals} named refusals out of 20" - ); - } - - /// lane-tiles r8: the tile-*row* analogue of the four-tile-column gate - /// above -- `--tile-rows=2` gives aomenc `TileRows=4` (log2; uniform - /// tile spacing is always a power of two, so this is the smallest count - /// that has an interior row neither the top nor bottom frame edge, - /// mirroring why the column gate needed 4 columns rather than 3). 64x256 - /// is four 64x64 superblocks tall with `--sb-size=64`, one per tile row. - /// Loop filter ON, run through `decode_stream` itself since the - /// `rows > 1` refusal is already lifted by this commit. Also settles a - /// stale documentation claim found while writing this gate: the old - /// comment above `decode_stream`'s multi-tile block said - /// `context_update_tile_id != 0` was refused "further down" -- no such - /// refusal exists (`decode.rs` reads `tile_info.context_update_tile_id` - /// generically, never hardcoded to tile 0), and this fixture's own - /// aomenc runs pick 1/2/3 as often as 0 (RD-driven tile-size heuristic), - /// all 20/20 pixel-exact -- so the capability was already there, - /// undocumented and unproven; hard-asserted here so the proof can't go - /// unnoticed if it stops firing. - #[test] - fn a_real_aomenc_stream_with_four_tile_rows_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_stream_with_four_tile_rows_decodes_pixel_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height) = (64usize, 256usize); - let mut matched = 0u32; - let mut named_refusals = 0u32; - let mut saw_nonzero_context_update_tile_id = false; - for attempt in 0..20u32 { - let seed = 42 + attempt; - let source = gradients_source(seed, width, height, "duration=0.04:rate=25"); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-pix_fmt", - "yuv420p", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let out = run_with_stdin( - Command::new(aomenc_path()).args([ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=45", - "--cpu-used=0", - "--limit=1", - "--kf-max-dist=1000", - "--threads=1", - "--row-mt=0", - "--tile-columns=0", - "--tile-rows=2", - "--sb-size=64", - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-tx-size-search=0", - "--enable-cdef=0", - "--enable-restoration=0", - "--max-partition-size=32", - "--min-partition-size=32", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - "--obu", - "-o", - "-", - "-", - ]), - &y4m.stdout, - ); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - - let mut parser = Av1Parser::new(); - let mut pos = 0usize; - let mut rows_seen = 0u32; - while pos < stream.len() { - let obu = parser.parse_obu(&stream[pos..]).unwrap(); - pos += obu.total_size; - if let ObuKind::Frame(header, _) = &obu.kind { - rows_seen = header.tile_info.rows; - if header.tile_info.context_update_tile_id != 0 { - saw_nonzero_context_update_tile_id = true; - } - } - } - assert!( - rows_seen > 2, - "{NAME}: aomenc did not actually split into >2 tile rows (rows={rows_seen}, seed {seed})" - ); - - let before = crate::decode::tile_hits(); - let pictures = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME} failed outright, not a named refusal (seed {seed}): {msg}" - ); - named_refusals += 1; - eprintln!("seed {seed} refusal: {msg}"); - continue; - } - Ok(pictures) => pictures, - }; - let hits = crate::decode::tile_hits() - before; - assert!( - hits > 2, - "{NAME}: tile_hits delta was {hits}, expected >2 -- all four tile rows must \ - actually decode, not just a subset (seed {seed})" - ); - assert_eq!( - pictures.len(), - 1, - "{NAME}: expected exactly 1 picture (seed {seed})" - ); - - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1); - assert_eq!( - pictures[0].y, ffmpeg_frames[0].y, - "{NAME}: luma vs ffmpeg (seed {seed})" - ); - assert_eq!( - pictures[0].u, ffmpeg_frames[0].u, - "{NAME}: U vs ffmpeg (seed {seed})" - ); - assert_eq!( - pictures[0].v, ffmpeg_frames[0].v, - "{NAME}: V vs ffmpeg (seed {seed})" - ); - matched += 1; - } - assert!( - matched > 0, - "{NAME}: every attempt refused ({named_refusals} refusals); the gate never decoded \ - a four-tile-row stream" - ); - assert!( - saw_nonzero_context_update_tile_id, - "{NAME}: every attempt named context_update_tile_id=0 -- this sweep proves nothing \ - about the != 0 case (see the stale-refusal note above `decode_stream`'s multi-tile \ - comment: aomenc's own tile-size heuristic picks it, seen 1/2/3 live in a prior probe \ - run of this exact fixture, so a 20-attempt window not seeing it is the gate's own bug)" - ); - eprintln!( - "{NAME}: {matched} pixel-exact matches, {named_refusals} named refusals out of 20" - ); - } - - /// lane-tiles r4/r7: the same real two-tile-column stream as the - /// bypass gate above, this time run through `decode_stream` itself -- - /// the entry point real callers use. Proves the `cols > 1` refusal is - /// actually lifted (not just that the underlying per-tile loop works) - /// for a key frame; `--loopfilter-control=0` stays here for its own - /// sake (isolating the entry-point wiring from deblocking), but r7's - /// `a_real_aomenc_stream_with_four_tile_columns_decodes_pixel_exact` - /// bypass gate now proves loop filtering ON across a tile boundary too, - /// and the `cols > 1 && loop_filter_on` / `cols > 2` refusals this - /// comment used to describe are gone from `decode_stream`. - #[test] - fn a_real_aomenc_stream_with_two_tile_columns_decodes_through_decode_stream() { - const NAME: &str = - "a_real_aomenc_stream_with_two_tile_columns_decodes_through_decode_stream"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height) = (128usize, 64usize); - let mut matched = 0u32; - let mut named_refusals = 0u32; - for attempt in 0..20u32 { - let seed = 42 + attempt; - let source = gradients_source(seed, width, height, "duration=0.04:rate=25"); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-pix_fmt", - "yuv420p", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let out = run_with_stdin( - Command::new(aomenc_path()).args([ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=45", - "--cpu-used=0", - "--limit=1", - "--kf-max-dist=1000", - "--threads=1", - "--row-mt=0", - "--tile-columns=1", - "--tile-rows=0", - "--sb-size=64", - "--loopfilter-control=0", - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-tx-size-search=0", - "--enable-cdef=0", - "--enable-restoration=0", - "--max-partition-size=32", - "--min-partition-size=32", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - "--obu", - "-o", - "-", - "-", - ]), - &y4m.stdout, - ); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - - let before = crate::decode::tile_hits(); - let pictures = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME} failed outright, not a named refusal (seed {seed}): {msg}" - ); - named_refusals += 1; - eprintln!("seed {seed} refusal: {msg}"); - continue; - } - Ok(pictures) => pictures, - }; - let hits = crate::decode::tile_hits() - before; - assert!( - hits > 1, - "{NAME}: tile_hits delta was {hits}, expected >1 -- both tiles must actually \ - decode, not just tile 0 (seed {seed})" - ); - assert_eq!( - pictures.len(), - 1, - "{NAME}: expected exactly 1 picture (seed {seed})" - ); - - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1); - assert_eq!( - pictures[0].y, ffmpeg_frames[0].y, - "{NAME}: luma vs ffmpeg (seed {seed})" - ); - assert_eq!( - pictures[0].u, ffmpeg_frames[0].u, - "{NAME}: U vs ffmpeg (seed {seed})" - ); - assert_eq!( - pictures[0].v, ffmpeg_frames[0].v, - "{NAME}: V vs ffmpeg (seed {seed})" - ); - matched += 1; - } - assert!( - matched > 0, - "{NAME}: every attempt refused ({named_refusals} refusals); decode_stream never \ - decoded a two-tile-column stream" - ); - eprintln!( - "{NAME}: {matched} pixel-exact matches, {named_refusals} named refusals out of 20" - ); - } - - /// lane-realworld r6: r5 ported `maybe_read_delta_q`/`maybe_read_delta_lf` - /// and removed the whole-frame refusal, but no fixture anywhere set - /// `delta_lf_present` -- the removal was unproven. `--deltaq-mode=2` - /// (`DELTA_Q_PERCEPTUAL`, checked against libaom's own - /// `encodeframe.c:2192-2225`) sets `delta_q_present_flag` unconditionally - /// once `base_qindex > 0` (unlike the default `--deltaq-mode=1` - /// `DELTA_Q_OBJECTIVE`, which additionally requires an alt-ref-eligible - /// frame and `allow_deltaq_mode`'s own RD search); `--delta-lf-mode=1` - /// then ANDs `delta_lf_present_flag` on top - /// (`tool_cfg->enable_deltalf_mode`, `av1_cx_iface.c:1269-1270`). 128x64 - /// (2 SBs; this decoder hardcodes 64px SBs) is the charter's minimum for - /// a per-superblock symbol to have somewhere to differ; `--cpu-used=4` - /// (not the other gates' `=0`) sidesteps the multi-SB - /// HORZ_4/VERT_B-at-part64 gap the cdef gate's own comment documents - /// (lane-realworld r2 dead-end, part64 only covers NONE/SPLIT). Note: - /// libaom hardcodes `delta_lf_multi = DEFAULT_DELTA_LF_MULTI == 0` - /// (`enums.h:73`) with no CLI flag to set it -- this gate cannot and - /// does not claim to exercise this decoder's `delta_lf_multi` branch; - /// only the single-plane path is gate-proven. - #[test] - fn a_real_aomenc_stream_with_delta_q_and_delta_lf_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_stream_with_delta_q_and_delta_lf_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height, frame_count) = (128usize, 64usize, 24usize); - let mut named_refusals = 0u32; - let mut matched = 0u32; - let n_attempts: u32 = std::env::var("EC_DELTAQ_GATE_ATTEMPTS") - .ok() - .and_then(|s| s.parse().ok()) - .unwrap_or(40); - for attempt in 0..n_attempts { - let seed = 42 + attempt; - let duration = frame_count as f64 / 25.0; - // Mandelbrot's varying local contrast is what gives - // DELTA_Q_PERCEPTUAL's per-superblock RD something to - // differentiate; flat gradients risk every superblock - // resolving the same delta. - let source = format!( - "mandelbrot=size={width}x{height}:rate=25:start_x={sx}:start_y={sy}", - sx = -0.6 + 0.005 * (attempt as f64), - sy = -0.4 + 0.005 * (attempt as f64) - ); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-t", - &duration.to_string(), - "-pix_fmt", - "yuv420p", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=45", - "--cpu-used=4", - "--aq-mode=0", - "--deltaq-mode=2", - "--delta-lf-mode=1", - "--kf-max-dist=1000", - "--threads=1", - "--row-mt=0", - "--sb-size=64", - "--auto-alt-ref=1", - "--lag-in-frames=16", - "--enable-fwd-kf=0", - "--enable-order-hint=1", - "--enable-warped-motion=1", - "--enable-global-motion=0", - "--enable-obmc=1", - "--tune-content=default", - "--enable-masked-comp=1", - "--enable-dist-wtd-comp=0", - "--enable-interintra-comp=1", - "--enable-onesided-comp=0", - "--enable-interintra-wedge=0", - "--enable-smooth-interintra=1", - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-tx-size-search=0", - "--enable-cdef=1", - "--enable-restoration=0", - "--max-partition-size=32", - "--min-partition-size=32", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - "--enable-ref-frame-mvs=0", - "--obu", - "-o", - "-", - "-", - ]; - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let frames = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME} failed outright, not a named refusal (seed {seed}): {msg}" - ); - assert!( - !msg.contains("delta_q") && !msg.contains("delta_lf"), - "{NAME} refused on delta_q/delta_lf (seed {seed}) -- that read is ported: {msg}" - ); - named_refusals += 1; - eprintln!("seed {seed} refusal: {msg}"); - continue; - } - Ok(frames) => frames, - }; - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count); - assert_eq!(frames.len(), frame_count); - let mismatched = frames - .iter() - .zip(&ffmpeg_frames) - .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); - if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") { - std::fs::write(&path, &stream).expect("writing pinned stream"); - eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}"); - } - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!( - got.y, want.y, - "{NAME} frame {i} luma vs ffmpeg (seed {seed})" - ); - assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})"); - assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})"); - } - // lane-hidden r2 (class gate-blind-to-hidden-frames): the same - // stream again, comparing EVERY decode-order frame -- the hidden - // (show_frame == 0) alt-ref frames the ffmpeg compare above - // cannot see, because both sides of it emit shown frames only. - let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME); - eprintln!( - "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \ - {hidden_n} hidden, all pixel-exact vs the oracle" - ); - // lane-hidden r2 SECOND ARM (the recipe above is untouched): - // libaom's temporal alt-ref filter absorbs this recipe's hidden - // frames, so the compare above is vacuous -- re-encode the same - // fixture with --arnr-maxframes=0 and compare THOSE. - if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) { - eprintln!( - "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \ - decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle" - ); - } - matched += 1; - } - assert!( - matched > 0, - "{NAME}: every attempt refused on other capabilities ({named_refusals} refusals); \ - the gate never exercised delta_q/delta_lf" - ); - assert!( - crate::decode::delta_q_hits() > 0, - "{NAME}: {matched} pixel-exact matches but zero delta_q symbol groups fired -- \ - the reader is unexercised" - ); - assert!( - crate::decode::delta_lf_hits() > 0, - "{NAME}: {matched} pixel-exact matches but zero delta_lf symbol groups fired -- \ - the reader is unexercised" - ); - eprintln!( - "{NAME}: {named_refusals} other-capability refusals, {matched} pixel-exact matches \ - out of {n_attempts}, delta_q_hits={}, delta_lf_hits={}", - crate::decode::delta_q_hits(), - crate::decode::delta_lf_hits() - ); - } - - #[test] - fn a_real_aomenc_stream_with_variance_aq_segmentation_decodes_pixel_exact() { - run_segmentation_gate( - "a_real_aomenc_stream_with_variance_aq_segmentation_decodes_pixel_exact", - "1", - 8, - 16, - &["--end-usage=q", "--cq-level=45"], - ); - } - - // lane-seg r1 DEFERRED: an `--aq-mode=2` (complexity AQ) twin of the gate - // above. libaom only switches segmentation on for complexity AQ once the - // target bits per 64x64 superblock clear `sb64_target_rate >= 256` - // (`aq_complexity.c:is_sb_aq_enabled`), which needs `--end-usage=vbr`; - // every VBR recipe tried (cpu-used 0 and 4, 32x32 and 64x64 fixed - // partitions) makes aomenc pick partition shapes OTHER lanes still refuse - // (AB below 16x16, SB-level HORZ/VERT, part32 values 4/6), so 10/10 - // attempts refuse before a pixel is compared. The syntax exercised would - // be identical to variance AQ's (both features only ever set - // `SEG_LVL_ALT_Q` via `update_map`), so this is coverage, not capability. - // Unblocked by the sub-16x16 rect/AB partition lanes. - - /// His two AV1 films are both `yuv420p10le`, so every capability lands - /// with a 10-bit twin (memory `his-av1-library-is-10-bit`). KEY FRAME - /// ONLY (`frame_count = 1`): a 10-bit INTER frame does not decode - /// pixel-exact in this crate yet, segmentation or not -- lane-seg r1 ran - /// this same recipe with `--aq-mode=0` (segmentation off entirely) and it - /// still mismatched at frame 2, so the 16-frame 10-bit variant would be - /// gating an unrelated pre-existing gap. Variance AQ segments the key - /// frame too (`aq_variance.c`, `is_frame_aq_enabled` includes - /// `frame_is_intra_only`), so this still proves the 10-bit segment-id - /// read and the per-segment 10-bit dequant. - #[test] - fn a_real_aomenc_10bit_stream_with_aq_segmentation_decodes_pixel_exact() { - run_segmentation_gate( - "a_real_aomenc_10bit_stream_with_aq_segmentation_decodes_pixel_exact", - "1", - 10, - 1, - &["--end-usage=q", "--cq-level=45"], - ); - } - - /// lane-tiles r7: the gate stage 2 (r6, commit 8899fc1) shipped without - /// -- a real >1-tile-column stream with a genuine INTER frame (not just - /// the key-frame-only two-column gate above), decoded through - /// `decode_stream` itself. Same recipe as the key-frame gate - /// (`--sb-size=64`, `--tile-columns=1`, `--loopfilter-control=0`, the - /// same feature-disable envelope so the gate isolates the tile loop, not - /// an unrelated unimplemented mode) plus `--limit=2 --kf-max-dist=1000` - /// so frame 1 is a real inter frame, and `gradients_source`'s default - /// `speed=0.01` rotation (undisturbed -- not overridden by the tail) - /// gives it genuine motion against frame 0, so `decode_inter_frame_tile_ - /// with_cdfs`'s new per-tile loop and `MiGrid`'s per-tile bound actually - /// have to walk a live MV stack across the tile-column boundary, not - /// just replay skip/zero-mv blocks. Bounded with `duration=0.08` (2 - /// frames at rate=25) per the class in ledger - /// `refusal-claim-disproved-by-its-own-gate`/`gate-loader-slurps-whole- - /// file` (never leave an ffmpeg/lavfi generate unbounded). - #[test] - fn a_real_aomenc_stream_with_two_tile_columns_and_an_inter_frame_decodes_pixel_exact() { - const NAME: &str = - "a_real_aomenc_stream_with_two_tile_columns_and_an_inter_frame_decodes_pixel_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height) = (128usize, 64usize); - let frames = 2usize; - let mut matched = 0u32; - let mut named_refusals = 0u32; - for attempt in 0..20u32 { - let seed = 42 + attempt; - let source = gradients_source(seed, width, height, "duration=0.08:rate=25"); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-pix_fmt", - "yuv420p", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let out = run_with_stdin( - Command::new(aomenc_path()).args([ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=45", - "--cpu-used=0", - &format!("--limit={frames}"), - "--kf-max-dist=1000", - "--lag-in-frames=0", - "--auto-alt-ref=0", - "--threads=1", - "--row-mt=0", - "--tile-columns=1", - "--tile-rows=0", - "--sb-size=64", - "--loopfilter-control=0", - "--max-reference-frames=3", - "--reduced-reference-set=1", - "--enable-warped-motion=0", - "--enable-obmc=0", - "--enable-masked-comp=0", - "--enable-interintra-comp=0", - "--enable-dist-wtd-comp=0", - "--enable-diff-wtd-comp=0", - "--enable-onesided-comp=0", - "--enable-interintra-wedge=0", - "--enable-smooth-interintra=0", - "--enable-ref-frame-mvs=0", - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-tx-size-search=0", - "--enable-cdef=0", - "--enable-restoration=0", - "--max-partition-size=32", - "--min-partition-size=32", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - "--obu", - "-o", - "-", - "-", - ]), - &y4m.stdout, - ); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - - // Confirm aomenc actually split into >1 tile column and that - // frame 1 is a real inter frame before trusting a pixel match -- - // otherwise a match could mean "tiles collapsed to 1" or "frame - // 1 fell back to key", not "the inter tile loop ran". - let mut parser = Av1Parser::new(); - let mut pos = 0usize; - let mut saw_multi_tile_inter = false; - while pos < stream.len() { - let obu = parser.parse_obu(&stream[pos..]).unwrap(); - pos += obu.total_size; - if let ObuKind::Frame(header, _) = obu.kind - && header.frame_type != FrameType::Key - && header.tile_info.cols > 1 - { - saw_multi_tile_inter = true; - } - } - assert!( - saw_multi_tile_inter, - "{NAME}: seed {seed} never produced a >1-tile-column inter frame (aomenc \ - collapsed tiling or coded frame 1 as key)" - ); - - let before = crate::decode::tile_hits(); - let pictures = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME} failed outright, not a named refusal (seed {seed}): {msg}" - ); - named_refusals += 1; - eprintln!("seed {seed} refusal: {msg}"); - continue; - } - Ok(pictures) => pictures, - }; - let hits = crate::decode::tile_hits() - before; - assert!( - hits > frames, - "{NAME}: tile_hits delta was {hits}, expected > {frames} -- both tiles of both \ - frames must actually decode (seed {seed})" - ); - assert_eq!( - pictures.len(), - frames, - "{NAME}: expected {frames} pictures (seed {seed})" - ); - - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frames); - for (i, (got, want)) in pictures.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!( - got.y, want.y, - "{NAME}: seed {seed} frame {i} luma vs ffmpeg" - ); - assert_eq!(got.u, want.u, "{NAME}: seed {seed} frame {i} U vs ffmpeg"); - assert_eq!(got.v, want.v, "{NAME}: seed {seed} frame {i} V vs ffmpeg"); - } - matched += 1; - } - assert!( - matched > 0, - "{NAME}: every attempt refused ({named_refusals} refusals); decode_stream never \ - decoded a two-tile-column inter frame" - ); - eprintln!( - "{NAME}: {matched} pixel-exact matches, {named_refusals} named refusals out of 20" - ); - } - - /// lane-tiles r9: `--num-tile-groups` makes aomenc split one frame's - /// tiles across several `OBU_TILE_GROUP`s instead of folding them into - /// the single `OBU_FRAME` every other gate in this file relies on -- - /// verified live (`scratch_probe_num_tile_groups`, this round) to emit a - /// standalone `OBU_FRAME_HEADER` (`show_existing_frame == false`) - /// followed by two `OBU_TILE_GROUP` OBUs, one tile each. Before this - /// round `decode_stream` had no arm for `ObuKind::TileGroup` at all (it - /// fell through the catch-all `continue`, silently dropping the frame), - /// and its `ObuKind::FrameHeader` arm matched *every* frame header - /// unconditionally, so a standalone header was misrouted into the - /// `show_existing_frame` slot lookup and returned the wrong named error - /// ("a show_existing_frame header naming an empty reference slot") for a - /// frame that was never a show_existing_frame header. Both are fixed - /// above: the `FrameHeader` arm now checks `show_existing_frame`, and a - /// `pending_header`/`pending_tiles` accumulator collects tile groups - /// until the frame's `cols * rows` tiles have all arrived. - #[test] - fn a_real_aomenc_stream_with_several_tile_group_obus_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_stream_with_several_tile_group_obus_decodes_pixel_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height) = (64usize, 128usize); - let mut matched = 0u32; - let mut named_refusals = 0u32; - let mut saw_multiple_tile_group_obus = false; - for attempt in 0..20u32 { - let seed = 42 + attempt; - let source = gradients_source(seed, width, height, "duration=0.04:rate=25"); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-pix_fmt", - "yuv420p", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let out = run_with_stdin( - Command::new(aomenc_path()).args([ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=45", - "--cpu-used=0", - "--limit=1", - "--kf-max-dist=1000", - "--threads=1", - "--row-mt=0", - "--tile-columns=0", - "--tile-rows=1", - "--sb-size=64", - "--num-tile-groups=4", - "--loopfilter-control=0", - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-tx-size-search=0", - "--enable-cdef=0", - "--enable-restoration=0", - "--max-partition-size=32", - "--min-partition-size=32", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - "--obu", - "-o", - "-", - "-", - ]), - &y4m.stdout, - ); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - - let mut probe = Av1Parser::new(); - let mut pos = 0usize; - let mut tile_group_obus = 0u32; - while pos < stream.len() { - let obu = probe.parse_obu(&stream[pos..]).unwrap(); - pos += obu.total_size; - if matches!(obu.kind, ObuKind::TileGroup(_)) { - tile_group_obus += 1; - } - } - if tile_group_obus > 1 { - saw_multiple_tile_group_obus = true; - } - - let before = crate::decode::tile_hits(); - let pictures = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME} failed outright, not a named refusal (seed {seed}): {msg}" - ); - named_refusals += 1; - eprintln!("seed {seed} refusal: {msg}"); - continue; - } - Ok(pictures) => pictures, - }; - let hits = crate::decode::tile_hits() - before; - assert!( - hits > 0, - "{NAME}: tile_hits delta was {hits}, expected >0 (seed {seed})" - ); - assert_eq!( - pictures.len(), - 1, - "{NAME}: expected exactly 1 picture (seed {seed})" - ); - - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1); - assert_eq!( - pictures[0].y, ffmpeg_frames[0].y, - "{NAME}: luma vs ffmpeg (seed {seed})" - ); - assert_eq!( - pictures[0].u, ffmpeg_frames[0].u, - "{NAME}: U vs ffmpeg (seed {seed})" - ); - assert_eq!( - pictures[0].v, ffmpeg_frames[0].v, - "{NAME}: V vs ffmpeg (seed {seed})" - ); - matched += 1; - } - assert!( - matched > 0, - "{NAME}: every attempt refused ({named_refusals} refusals); decode_stream never \ - decoded a several-tile-group-OBUs stream" - ); - assert!( - saw_multiple_tile_group_obus, - "{NAME}: no attempt actually split into more than one OBU_TILE_GROUP -- this sweep \ - proves nothing about the multi-tile-group case (aomenc's --num-tile-groups is \ - RD/heuristic-driven, same as tile sizing)" - ); - eprintln!( - "{NAME}: {matched} pixel-exact matches, {named_refusals} named refusals out of 20" - ); - } diff --git a/crates/ec-av1/src/stream/tests/t08.rs b/crates/ec-av1/src/stream/tests/t08.rs deleted file mode 100644 index 2c9048a3..00000000 --- a/crates/ec-av1/src/stream/tests/t08.rs +++ /dev/null @@ -1,4540 +0,0 @@ -use super::*; -use super::support::*; -use super::gates_a::*; -use super::gates_b::*; -use crate::probe::run_with_stdin; -use std::process::{Command, Stdio}; - - /// lane-tiles r10: non-uniform tile spacing (`uniform_spacing_flag == 0`, - /// spec 5.9.15). aomenc never sets this from `--tile-columns`/ - /// `--tile-rows` (those always take the `uniform_spacing = 1` branch in - /// `set_tile_info`, libaom `encoder.c`), and `--auto-tiles` only takes - /// the non-uniform balancing path when `g_threads >= 2` -- this charter's - /// `--threads=1` rules that out. The only CLI surface that reaches - /// libaom's `else { tiles->uniform_spacing = 0; ... }` arm is the - /// explicit per-tile size lists `--tile-width=`/ - /// `--tile-height=` (`av1_cx_iface.c` `set_tile_info`, argument - /// parsing at `arg_defs.c`'s `.tile_width`/`.tile_height` -- present in - /// the binary, just not printed by `--help`). Probed live with - /// `aomenc --tile-width=1,3 --tile-height=1 --sb-size=64` on a 256x64 - /// source (4 SB columns, 1 SB row): confirmed by hand this round to - /// produce a real OBU stream aomdec/ffmpeg both decode. - /// - /// `decode.rs`'s tile loop was already generic over spacing before this - /// gate existed -- it walks `tile_info.mi_col_starts`/`mi_row_starts` - /// (populated identically by `read_tile_info` for both the uniform and - /// non-uniform branches, spec 5.9.15) and never recomputes tile bounds - /// from `cols_log2`/`rows_log2`. The only place in this crate that ever - /// refused non-uniform spacing is `frame.rs`'s OBU *writer* - /// (`"non-uniform tile spacing is not written"`), an unrelated encode - /// path this gate does not touch. So this is a staleness check, not new - /// machinery: prove the already-generic decode path live and pin it. - #[test] - fn a_real_aomenc_stream_with_non_uniform_tile_spacing_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_stream_with_non_uniform_tile_spacing_decodes_pixel_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height) = (256usize, 64usize); - let mut matched = 0u32; - let mut named_refusals = 0u32; - let mut saw_non_uniform_spacing = false; - for attempt in 0..20u32 { - let seed = 42 + attempt; - let source = gradients_source(seed, width, height, "duration=0.04:rate=25"); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-pix_fmt", - "yuv420p", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let out = run_with_stdin( - Command::new(aomenc_path()).args([ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=45", - "--cpu-used=0", - "--limit=1", - "--kf-max-dist=1000", - "--threads=1", - "--row-mt=0", - "--sb-size=64", - "--tile-width=1,3", - "--tile-height=1", - "--loopfilter-control=0", - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-tx-size-search=0", - "--enable-cdef=0", - "--enable-restoration=0", - "--max-partition-size=32", - "--min-partition-size=32", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - "--obu", - "-o", - "-", - "-", - ]), - &y4m.stdout, - ); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - - let mut probe = Av1Parser::new(); - let mut pos = 0usize; - while pos < stream.len() { - let obu = probe.parse_obu(&stream[pos..]).unwrap(); - pos += obu.total_size; - let tile_info = match &obu.kind { - ObuKind::Frame(header, _) => Some(&header.tile_info), - ObuKind::FrameHeader(header) if !header.show_existing_frame => { - Some(&header.tile_info) - } - _ => None, - }; - if let Some(info) = tile_info { - if !info.uniform_spacing { - saw_non_uniform_spacing = true; - } - assert!( - info.cols > 1 || info.rows > 1, - "{NAME}: --tile-width=1,3 --tile-height=1 produced only 1 tile \ - (cols={} rows={}, seed {seed}) -- fixture stopped exercising the case", - info.cols, - info.rows - ); - } - } - - let before = crate::decode::tile_hits(); - let pictures = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME} failed outright, not a named refusal (seed {seed}): {msg}" - ); - named_refusals += 1; - eprintln!("seed {seed} refusal: {msg}"); - continue; - } - Ok(pictures) => pictures, - }; - let hits = crate::decode::tile_hits() - before; - assert!( - hits > 0, - "{NAME}: tile_hits delta was {hits}, expected >0 (seed {seed})" - ); - assert_eq!( - pictures.len(), - 1, - "{NAME}: expected exactly 1 picture (seed {seed})" - ); - - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1); - assert_eq!( - pictures[0].y, ffmpeg_frames[0].y, - "{NAME}: luma vs ffmpeg (seed {seed})" - ); - assert_eq!( - pictures[0].u, ffmpeg_frames[0].u, - "{NAME}: U vs ffmpeg (seed {seed})" - ); - assert_eq!( - pictures[0].v, ffmpeg_frames[0].v, - "{NAME}: V vs ffmpeg (seed {seed})" - ); - matched += 1; - } - assert!( - matched > 0, - "{NAME}: every attempt refused ({named_refusals} refusals); decode_stream never \ - decoded a non-uniform-tile-spacing stream" - ); - assert!( - saw_non_uniform_spacing, - "{NAME}: no attempt actually set uniform_spacing_flag == 0 -- this sweep proves \ - nothing about the non-uniform case" - ); - eprintln!( - "{NAME}: {matched} pixel-exact matches, {named_refusals} named refusals out of 20" - ); - } - - /// lane-sb128 r1 gate: a real `aomenc --sb-size=128` stream (the size his - /// ReelC encode uses -- `EC_TRACE=1 aomdec reelc-head.obu` prints - /// `EC_PART mi_row=0 mi_col=0 bsize=15` = `BLOCK_128X128`) must decode - /// pixel-exact. `--max-partition-size=64` keeps the RD search from ever - /// choosing a 128-level NONE/HORZ/VERT/AB arm, so every 128 root here is - /// genuinely `PARTITION_SPLIT` -- the one arm - /// `decode_key_frame_tile_with_cdfs` codes; the other seven refuse by - /// name (`PART128_NON_SPLIT_REFUSAL`) and stay refused after this round. - /// - /// What the 128 root actually changes, and what this gate therefore - /// proves: the 8-symbol `partition_w128` CDF and its forced-split gather - /// at the frame edge, the quadrant VISIT ORDER (TL, TR, BL, BR inside one - /// superblock, not raster over 64x64 superblocks), one loop-restoration - /// read per 128x128 instead of per 64x64, `delta_q`/`delta_lf` once per - /// 128x128, and the per-64x64 `cdef_idx` read inside the 128 superblock. - /// 256x192 gives a 2x2 grid of 128 superblocks whose bottom row is a - /// partial superblock (the gathered forced-split read); 384x384 gives a - /// 3x3 grid of whole ones. 8-bit sweep plus one 10-bit stream (his films - /// are `yuv420p10le`). Only a missing tool SKIPs. - #[test] - fn a_real_aomenc_stream_with_128x128_superblocks_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_stream_with_128x128_superblocks_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let base: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=40", - "--cpu-used=0", - "--threads=1", - "--row-mt=0", - "--sb-size=128", - "--max-partition-size=64", - "--enable-rect-partitions=1", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - // aomenc emits PARTITION_HORZ_4/VERT_4 below 16x16 even with the - // flag off (ledger, lane-modectx r1), so bound the search instead. - "--min-partition-size=16", - "--enable-restoration=1", - "--enable-palette=0", - "--deltaq-mode=0", - "--enable-intrabc=0", - "--enable-tx-size-search=0", - "--limit=1", - ]; - let encode = |y4m: &[u8], extra: &[&str]| -> Vec { - let mut args = base.clone(); - args.extend_from_slice(extra); - args.extend_from_slice(&["--obu", "-o", "-", "-"]); - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), y4m); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - out.stdout - }; - let render = |seed: u32, width: usize, height: usize, ten_bit: bool| -> Vec { - let pix = if ten_bit { "yuv420p10le" } else { "yuv420p" }; - let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &gradients_source(seed, width, height, "duration=0.04:rate=25"), - "-pix_fmt", - pix, - "-strict", - "-1", - "-t", - "0.04", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - out.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - out.stdout - }; - let mut matched = 0u32; - let mut named_refusals = 0u32; - // (seed, width, height, 10-bit): 256x192 = 2x2 superblocks with a - // partial bottom row; 384x384 = 3x3 whole ones. - let arms: Vec<(u32, usize, usize, bool)> = vec![ - (42, 256, 192, false), - (43, 256, 192, false), - (44, 256, 192, false), - (45, 384, 384, false), - (46, 256, 192, true), - (47, 384, 384, true), - ]; - for (seed, width, height, ten_bit) in arms { - let y4m = render(seed, width, height, ten_bit); - let extra: Vec<&str> = if ten_bit { - vec!["--input-bit-depth=10", "--bit-depth=10"] - } else { - vec![] - }; - let stream = encode(&y4m, &extra); - let parsed = { - let mut parser = ec_av1_syntax::Av1Parser::new(); - let mut pos = 0usize; - while let Ok(obu) = parser.parse_obu(&stream[pos..]) { - pos += obu.total_size; - if pos >= stream.len() { - break; - } - } - parser - .sequence_header() - .map(|q| (q.use_128x128_superblock, q.color_config.bit_depth)) - }; - assert_eq!( - parsed, - Some((true, if ten_bit { 10 } else { 8 })), - "{NAME} (seed {seed}): the encoder did not write a 128x128-superblock \ - sequence header at the requested bit depth -- the flag never arrived" - ); - let frames = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME} failed outright, not a named refusal (seed {seed}): {msg}" - ); - named_refusals += 1; - eprintln!("seed {seed} refusal: {msg}"); - continue; - } - Ok(frames) => frames, - }; - let want = if ten_bit { - ffmpeg_decode_sequence_10bit(&stream, width, height, 1) - } else { - ffmpeg_decode_sequence(&stream, width, height, 1) - }; - assert_eq!(frames.len(), 1); - for (i, (got, want)) in frames.iter().zip(&want).enumerate() { - assert_eq!( - got.y, want.y, - "{NAME} frame {i} luma vs ffmpeg (seed {seed})" - ); - assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})"); - assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})"); - } - matched += 1; - } - assert!( - matched > 0, - "{NAME}: every attempt refused; the gate never decoded a stream" - ); - // 256x192 codes 3 whole + 1 partial superblock, 384x384 codes 9 whole - // ones, so a run that decoded anything at all must have read real 128 - // partition symbols and split every one of them. - assert!( - crate::decode::part128_symbols() >= 3 * matched as usize, - "{NAME}: only {} 128-level partition symbols over {matched} decoded streams -- \ - the 128 root never fired", - crate::decode::part128_symbols() - ); - assert!( - crate::decode::part128_split_hits() >= 4 * matched as usize, - "{NAME}: only {} 128 superblocks split", - crate::decode::part128_split_hits() - ); - eprintln!( - "{NAME}: {matched} pixel-exact, {named_refusals} named refusals, \ - part128_symbols={} part128_split_hits={}", - crate::decode::part128_symbols(), - crate::decode::part128_split_hits() - ); - } - - /// lane-sb128b r1 gate: a real `aomenc --sb-size=128` KEY frame whose 128 - /// roots resolve to `PARTITION_NONE` -- one whole 128x128 intra block, - /// four TX_64X64 luma transform units and FOUR TX_32X32 chroma units per - /// plane (`av1_get_max_uv_txsize(BLOCK_128X128)` is - /// `av1_get_adjusted_tx_size` of its 64x64 uv plane block's TX_64X64, so - /// TX_32X32) -- lane-sb128b r2's `chroma_split_tx_hits` asserts them. The r1 gate above pins `--max-partition-size=64`, which - /// makes every 128 root a forced SPLIT and leaves this arm unexercised. - /// Smooth gradients at a high `--cq-level` are what make the RD search - /// keep a whole 128x128 block; `part128_none_hits` HARD-asserts it did. - #[test] - fn a_real_aomenc_key_frame_with_a_128x128_none_partition_decodes_pixel_exact() { - const NAME: &str = - "a_real_aomenc_key_frame_with_a_128x128_none_partition_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let render = |seed: u32, width: usize, height: usize, ten_bit: bool| -> Vec { - let pix = if ten_bit { "yuv420p10le" } else { "yuv420p" }; - let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &gradients_source(seed, width, height, "duration=0.04:rate=25"), - "-pix_fmt", - pix, - "-strict", - "-1", - "-t", - "0.04", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - out.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - out.stdout - }; - let mut matched = 0u32; - let mut named_refusals = 0u32; - let mut none_arms = 0u32; - // (seed, cq, width, height, 10-bit). 384x384 is a 3x3 grid of whole - // 128 superblocks; 256x256 a 2x2. - let arms: Vec<(u32, &str, usize, usize, bool)> = vec![ - (42, "--cq-level=63", 384, 384, false), - (43, "--cq-level=55", 384, 384, false), - (44, "--cq-level=63", 256, 256, false), - (45, "--cq-level=63", 384, 384, true), - ]; - for (seed, cq, width, height, ten_bit) in arms { - let y4m = render(seed, width, height, ten_bit); - let mut args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - cq, - "--cpu-used=0", - "--threads=1", - "--row-mt=0", - "--sb-size=128", - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--min-partition-size=16", - "--enable-restoration=1", - "--enable-palette=0", - "--deltaq-mode=0", - "--enable-intrabc=0", - "--enable-tx-size-search=0", - "--limit=1", - ]; - if ten_bit { - args.extend_from_slice(&["--input-bit-depth=10", "--bit-depth=10"]); - } - args.extend_from_slice(&["--obu", "-o", "-", "-"]); - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let before = crate::decode::part128_none_hits(); - let frames = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME} failed outright, not a named refusal (seed {seed}): {msg}" - ); - named_refusals += 1; - eprintln!("seed {seed} refusal: {msg}"); - continue; - } - Ok(frames) => frames, - }; - let want = if ten_bit { - ffmpeg_decode_sequence_10bit(&stream, width, height, 1) - } else { - ffmpeg_decode_sequence(&stream, width, height, 1) - }; - assert_eq!(frames.len(), 1); - for (i, (got, want)) in frames.iter().zip(&want).enumerate() { - for (name, a, b, w) in [ - ("Y", &got.y, &want.y, width), - ("U", &got.u, &want.u, width / 2), - ("V", &got.v, &want.v, width / 2), - ] { - let n = a.iter().zip(b.iter()).filter(|(x, y)| x != y).count(); - let first = a.iter().zip(b.iter()).position(|(x, y)| x != y); - assert_eq!( - n, - 0, - "{NAME} frame {i} {name} vs ffmpeg (seed {seed}): {n} differ, first row {} col {} ours {:?} ffmpeg {:?}", - first.unwrap_or(0) / w, - first.unwrap_or(0) % w, - first.map(|k| a[k]), - first.map(|k| b[k]), - ); - assert_eq!( - a.len(), - b.len(), - "{NAME} frame {i} {name} vs ffmpeg (seed {seed}): ours has {} samples, \ - ffmpeg's has {} -- a short plane would zip-truncate the walk above \ - and hide a chroma-span defect", - a.len(), - b.len() - ); - } - } - let hits = crate::decode::part128_none_hits() - before; - eprintln!("seed {seed} cq {cq} {width}x{height}: part128_none_hits +{hits}"); - if hits > 0 { - none_arms += 1; - } - matched += 1; - } - assert!( - matched > 0, - "{NAME}: every attempt refused; the gate never decoded a stream" - ); - assert!( - none_arms > 0, - "{NAME}: {matched} stream(s) decoded pixel-exact but NOT ONE 128 root was \ - PARTITION_NONE -- the arm this gate exists for never fired" - ); - eprintln!( - "{NAME}: {matched} pixel-exact ({none_arms} with a 128 NONE root), \ - {named_refusals} named refusals, part128_none_hits={}", - crate::decode::part128_none_hits() - ); - } - - /// lane-sb128c r7 GATE: the 128 root's GATHERED bottom/right-edge arm -- - /// the only 128-partition shape the user's 1080p AV1 film reaches - /// (`mi_rows = 270`, so every bottom 128 row has `has_rows128 == false`, - /// one gathered bit, and the film codes `PARTITION_HORZ`: a 128x64 block - /// whose bottom half is outside the frame and never decoded). Frame sizes - /// here are chosen so the LAST superblock row (or column, for the VERT - /// twin at 192x256) is partial, which is what forces the gathered symbol. - /// Both the key frame and the inter frames of each stream carry the arm; - /// `part128_edge_*_hits` and `inter_sb128_*_hits` HARD-assert it fired, - /// and `decode_all_frames_vs_oracle` compares EVERY decode-order frame - /// (hidden alt-refs included) against the instrumented aomdec. - #[test] - fn a_real_aomenc_sb128_gathered_edge_horz_partition_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_sb128_gathered_edge_horz_partition_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - // (seed, cq, width, height, 10-bit, vertical twin). Every size has a - // PARTIAL last superblock row (or column, for the VERT twin): 320 px - // = 80 mi rows, two full 128 rows and a 64-px remainder; 256 px = 64 - // mi = two full rows and none, so the VERT arm uses 192 px = 48 mi on - // the column axis. A smooth `gradients` source makes the KEY frame - // take the arm too, which is still refused by name (square-block - // intra), so this gate's source is `mandelbrot`: its key frames split - // and its inter frames keep the 128x64/64x128 edge block. - // lane-vert46 r1: the last field picks a SMOOTH deterministic source - // (`geq` sinusoids, the sb128c r8 intra arm's own fixture) instead of - // `mandelbrot`. Arm 46 is the stream that exposed this round's two - // defects: mandelbrot's inter frames never put a 64x128 edge block - // next to a neighbour whose partition context or per-mu-chunk chroma - // DC sign decides a symbol, so both were invisible to arms 42-45. - let arms: Vec<(u32, &str, usize, usize, bool, bool, bool)> = vec![ - (42, "--cq-level=55", 384, 320, false, false, false), - (43, "--cq-level=55", 384, 320, true, false, false), - (44, "--cq-level=32", 192, 256, false, true, false), - (45, "--cq-level=45", 192, 256, true, true, false), - (46, "--cq-level=55", 192, 256, false, true, true), - ]; - let (mut matched, mut named_refusals) = (0u32, 0u32); - let (mut edge_arms, mut inter_arms) = (0u32, 0u32); - for (seed, cq, width, height, ten_bit, vert, smooth) in arms { - let pix = if ten_bit { "yuv420p10le" } else { "yuv420p" }; - let source = if smooth { - format!( - "nullsrc=size={width}x{height}:rate=25,format=yuv420p,\ - geq=lum='128+90*sin((X+2*N)/37)+30*sin(Y/29)':\ - cb='128+30*sin(X/23)':cr='128+30*sin((Y+N)/19)'" - ) - } else { - format!("mandelbrot=size={width}x{height}:rate=25:start_x=-0.6:start_y=-0.4") - }; - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-pix_fmt", - pix, - "-strict", - "-1", - "-t", - "0.2", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "{NAME}: ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let mut args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - cq, - "--cpu-used=0", - "--threads=1", - "--row-mt=0", - "--sb-size=128", - "--min-partition-size=64", - "--enable-rect-partitions=1", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-tx-size-search=0", - "--deltaq-mode=0", - "--limit=5", - ]; - if ten_bit { - args.extend_from_slice(&["--input-bit-depth=10", "--bit-depth=10"]); - } - args.extend_from_slice(&["--obu", "-o", "-", "-"]); - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "{NAME}: aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let (before_edge, before_inter) = if vert { - ( - crate::decode::part128_edge_vert_hits(), - crate::decode::inter_sb128_vert_hits(), - ) - } else { - ( - crate::decode::part128_edge_horz_hits(), - crate::decode::inter_sb128_horz_hits(), - ) - }; - // A refusal is still a legal outcome for an arm whose stream hits - // some OTHER lane's gap, but never for all of them (asserted - // below), and never as a silent skip. - if let Err(e) = decode_stream(&stream) { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME} failed outright, not a named refusal \ - (seed {seed} {width}x{height}): {msg}" - ); - named_refusals += 1; - eprintln!("{NAME}: seed {seed} {width}x{height} refusal: {msg}"); - continue; - } - let (frames, hidden) = decode_all_frames_vs_oracle( - &stream, - &format!("sb128c-edge-{seed}-{width}x{height}"), - ); - assert!(frames > 0, "{NAME}: no frames decoded at {width}x{height}"); - let (edge, inter) = if vert { - ( - crate::decode::part128_edge_vert_hits() - before_edge, - crate::decode::inter_sb128_vert_hits() - before_inter, - ) - } else { - ( - crate::decode::part128_edge_horz_hits() - before_edge, - crate::decode::inter_sb128_horz_hits() - before_inter, - ) - }; - eprintln!( - "{NAME}: seed {seed} cq {cq} {width}x{height} {}bit {}: \ - {frames} frames pixel-exact ({hidden} hidden), \ - edge_hits +{edge} inter_128rect_blocks +{inter}", - if ten_bit { 10 } else { 8 }, - if vert { "VERT" } else { "HORZ" }, - ); - if edge > 0 { - edge_arms += 1; - } - if inter > 0 { - inter_arms += 1; - } - matched += 1; - } - assert!( - matched > 0, - "{NAME}: every attempt refused ({named_refusals}); the gate never \ - decoded a stream" - ); - assert!( - edge_arms > 0, - "{NAME}: {matched} stream(s) decoded pixel-exact but NOT ONE 128 root \ - took the gathered frame-edge HORZ/VERT arm this gate exists for" - ); - assert!( - inter_arms > 0, - "{NAME}: the gathered arm fired only on key frames -- no INTER \ - 128x64/64x128 block was decoded, which is the film's own shape" - ); - } - - /// lane-sb128c r8: the 128 root's HORZ/VERT arm on a KEY frame -- one - /// 128x64 (or 64x128) INTRA block, the shape r7 still refused by name. - /// A smooth `gradients` source makes the key frame itself take the arm - /// (`mandelbrot`'s key frames always split), at sizes whose last - /// superblock row/column is a partial 64 so the gathered frame-edge bit - /// decides the root. `--enable-tx-size-search=1` on half the arms is what - /// makes the intra `tx_depth` symbol real (depth 1 = 32x32 units, - /// depth 2 = 16x16). Every decode-order frame (hidden alt-refs included) - /// is compared against the instrumented aomdec, and the per-depth - /// counters are printed for every compared attempt. - #[test] - fn a_real_aomenc_sb128_intra_rect_block_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_sb128_intra_rect_block_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - // (tag, cq, width, height, 10-bit, vertical twin, tx-size-search) - let arms: Vec<(u32, &str, usize, usize, bool, bool, bool)> = vec![ - (42, "--cq-level=55", 384, 320, false, false, false), - (43, "--cq-level=32", 384, 320, true, false, true), - (44, "--cq-level=8", 256, 192, false, false, true), - (46, "--cq-level=55", 192, 256, false, true, false), - (45, "--cq-level=45", 192, 256, true, true, true), - // lane-sb128c r10: a SECOND 128 superblock column is what the - // arms above never had -- the right 64x128 half of a 128-root - // VERT at mi_col 80 read its tx-depth symbol off the wrong CDF - // row and every unit column of a 128x64 chunk predicted from the - // not-yet-decoded chunk to its right. - (47, "--cq-level=45", 512, 512, false, false, true), - ]; - let (mut matched, mut named_refusals, mut out_of_scope) = (0u32, 0u32, 0u32); - let (mut horz_arms, mut vert_arms) = (0u32, 0u32); - let mut depth_seen = [0usize; 3]; - for (tag, cq, width, height, ten_bit, vert, tx_search) in arms { - let pix = if ten_bit { "yuv420p10le" } else { "yuv420p" }; - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", "error", "-f", "lavfi", "-i", - // DETERMINISTIC smooth source: lavfi `gradients` ignores - // its seed and gives a different picture every run (a - // whole round was spent on a "flake" that was really this), - // so the smoothness comes from long-period sinusoids - // through `geq` instead -- same effect on the encoder's - // partition choice, byte-identical across runs. - &format!( - "nullsrc=size={width}x{height}:rate=25,format=yuv420p, geq=lum='{lum}': cb='128+30*sin(X/23)':cr='128+30*sin((Y+N)/19)'", - // The 512x512 arm carries the r9 witness's own - // higher-frequency luma: the smooth two-term source - // gives every 128-rect block a whole-block TX_64X64 - // and no VERT root at all, which is exactly the - // combination that hid the tx-depth CDF row defect. - lum = if width == 512 { - "128+80*sin((X+3*N)/17)+50*sin(Y/29)+30*sin((X+Y)/13)" - } else { - "128+90*sin((X+2*N)/37)+30*sin(Y/29)" - } - ), - "-pix_fmt", pix, "-strict", "-1", "-t", "0.2", - "-f", "yuv4mpegpipe", "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "{NAME}: ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let mut args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - cq, - "--cpu-used=0", - "--threads=1", - "--row-mt=0", - "--sb-size=128", - "--min-partition-size=64", - "--enable-rect-partitions=1", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-palette=0", - "--enable-intrabc=0", - "--deltaq-mode=0", - "--limit=5", - // EVERY frame a key frame: this gate exists for the INTRA - // 128x64/64x128 block, and a mixed stream lands on other - // lanes' inter gaps (sub-8 leaves, rect inter residual) - // before it ever gets there. The inter twin of this same - // 128-root arm has its own gate - // (`..._sb128_gathered_edge_horz_partition_decodes_pixel_exact`). - "--kf-max-dist=1", - ]; - // AOMENC FLAG PRECEDENCE: the LAST occurrence wins, so this - // per-arm override goes after the base recipe. - args.push(if tx_search { - "--enable-tx-size-search=1" - } else { - "--enable-tx-size-search=0" - }); - if ten_bit { - args.extend_from_slice(&["--input-bit-depth=10", "--bit-depth=10"]); - } - args.extend_from_slice(&["--obu", "-o", "-", "-"]); - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "{NAME}: aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let before = intra_sb128_counters(); - if let Err(e) = decode_stream(&stream) { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME} failed outright, not a named refusal \ - (arm {tag} {width}x{height}): {msg}" - ); - named_refusals += 1; - eprintln!("{NAME}: arm {tag} {width}x{height} refusal: {msg}"); - continue; - } - let (frames, hidden) = decode_all_frames_vs_oracle( - &stream, - &format!("sb128c-intra-{tag}-{width}x{height}"), - ); - assert!(frames > 0, "{NAME}: no frames decoded at {width}x{height}"); - let after = intra_sb128_counters(); - let (horz, vert_hits) = (after.0 - before.0, after.1 - before.1); - let depth: Vec = (0..3).map(|i| after.2[i] - before.2[i]).collect(); - eprintln!( - "{NAME}: arm {tag} cq {cq} {width}x{height} {}bit {} txsearch={}: \ - {frames} frames pixel-exact ({hidden} hidden), \ - intra_128x64 +{horz} intra_64x128 +{vert_hits} \ - depth[64/32/16] {depth:?}", - if ten_bit { 10 } else { 8 }, - if vert { "VERT" } else { "HORZ" }, - u8::from(tx_search), - ); - if horz == 0 && vert_hits == 0 { - out_of_scope += 1; - } - if horz > 0 { - horz_arms += 1; - } - if vert_hits > 0 { - vert_arms += 1; - } - for i in 0..3 { - depth_seen[i] += depth[i]; - } - matched += 1; - } - assert!( - matched > 0, - "{NAME}: every attempt refused ({named_refusals}); the gate never \ - decoded a stream" - ); - assert!( - horz_arms > 0, - "{NAME}: {matched} stream(s) decoded pixel-exact ({out_of_scope} carried \ - no 128-root rect intra block at all) but NOT ONE key-frame 128x64 \ - block fired -- the shape this gate exists for" - ); - assert!( - vert_arms > 0, - "{NAME}: the VERT twin never produced a key-frame 64x128 block" - ); - assert!( - depth_seen[0] > 0, - "{NAME}: no depth-0 (TX_64X64) intra 128-rect block: {depth_seen:?}" - ); - } - - /// lane-sb128c r9 GATE: the four AB shapes at the 128 root - /// (`PARTITION_HORZ_A`/`_HORZ_B`/`_VERT_A`/`_VERT_B`), each one - /// 128x64/64x128 half plus two 64x64 quadrants in libaom - /// `decode_partition`'s visit order. The recipe is r8's measured one - /// (`--sb-size=128 --min-partition-size=64 --enable-ab-partitions=1` over - /// a 512x512 `geq` sinusoid), which is what made aomenc pick the shapes at - /// all; arms cover cq 18/45, 8 and 10 bit, and one INTER arm - /// (`--kf-max-dist=100`) so the shapes are exercised on both tile paths. - /// Continue-and-sweep: an arm that stops on ANOTHER lane's named refusal - /// is counted and skipped, a decode failure or a pixel mismatch is a hard - /// failure, and the end-of-sweep assert names which of the four fired. - #[test] - fn a_real_aomenc_sb128_ab_partition_at_the_128_root_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_sb128_ab_partition_at_the_128_root_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - // (tag, cq, width, height, 10-bit, inter) - let arms: Vec<(u32, &str, usize, usize, bool, bool)> = vec![ - (18, "--cq-level=18", 512, 512, false, false), - (45, "--cq-level=45", 512, 512, false, false), - (32, "--cq-level=32", 512, 512, true, false), - (55, "--cq-level=55", 384, 320, false, false), - (91, "--cq-level=45", 512, 512, false, true), - (92, "--cq-level=18", 512, 512, false, true), - ]; - let (mut matched, mut named_refusals, mut out_of_scope) = (0u32, 0u32, 0u32); - let mut ab_seen = [0usize; 4]; - let mut ab_inter = [0usize; 4]; - for (tag, cq, width, height, ten_bit, inter) in arms { - let pix = if ten_bit { "yuv420p10le" } else { "yuv420p" }; - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - // Same DETERMINISTIC sinusoid source that made aomenc pick - // the AB shapes in the r8 sweep (lavfi `gradients` ignores - // its seed and is not reproducible -- never use it here). - &format!( - "nullsrc=size={width}x{height}:rate=25,format=yuv420p,\ - geq=lum='128+80*sin((X+3*N)/17)+50*sin(Y/29)+30*sin((X+Y)/13)':\ - cb='128+30*sin(X/23)':cr='128+30*sin((Y+N)/19)'" - ), - "-pix_fmt", - pix, - "-strict", - "-1", - "-t", - "0.2", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "{NAME}: ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let mut args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - cq, - "--cpu-used=0", - "--threads=1", - "--row-mt=0", - "--sb-size=128", - "--min-partition-size=64", - "--enable-rect-partitions=1", - "--enable-ab-partitions=1", - "--enable-1to4-partitions=0", - "--enable-palette=0", - "--enable-intrabc=0", - "--deltaq-mode=0", - "--limit=5", - ]; - // AOMENC FLAG PRECEDENCE: last occurrence wins, so the per-arm - // key-frame cadence goes AFTER the base recipe. - args.push(if inter { - "--kf-max-dist=100" - } else { - "--kf-max-dist=1" - }); - if ten_bit { - args.extend_from_slice(&["--input-bit-depth=10", "--bit-depth=10"]); - } - args.extend_from_slice(&["--obu", "-o", "-", "-"]); - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "{NAME}: aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let before = sb128_ab_counters(); - if let Err(e) = decode_stream(&stream) { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME} failed outright, not a named refusal \ - (arm {tag} {width}x{height}): {msg}" - ); - named_refusals += 1; - eprintln!("{NAME}: arm {tag} {width}x{height} refusal: {msg}"); - continue; - } - let (frames, hidden) = - decode_all_frames_vs_oracle(&stream, &format!("sb128c-ab-{tag}-{width}x{height}")); - assert!(frames > 0, "{NAME}: no frames decoded at {width}x{height}"); - let after = sb128_ab_counters(); - let ab: Vec = (0..4).map(|i| after[i] - before[i]).collect(); - eprintln!( - "{NAME}: arm {tag} cq {cq} {width}x{height} {}bit {}: {frames} frames \ - pixel-exact ({hidden} hidden), AB[HORZ_A,HORZ_B,VERT_A,VERT_B] {ab:?}", - if ten_bit { 10 } else { 8 }, - if inter { "INTER" } else { "KEY" }, - ); - if ab.iter().sum::() == 0 { - out_of_scope += 1; - } - for i in 0..4 { - ab_seen[i] += ab[i]; - if inter { - ab_inter[i] += ab[i]; - } - } - matched += 1; - } - assert!( - matched > 0, - "{NAME}: every attempt refused ({named_refusals}); the gate never \ - decoded a stream" - ); - assert!( - ab_seen.iter().sum::() > 0, - "{NAME}: {matched} stream(s) decoded pixel-exact ({out_of_scope} carried \ - no 128-root AB partition at all) but NOT ONE AB shape fired -- the \ - shapes this gate exists for" - ); - // Which of the four this sweep actually reaches, hard-asserted so a - // later change that stops reaching one of them fails here instead of - // silently narrowing the gate (class `gate-blind-to-feature`). - for (i, name) in ["HORZ_A", "HORZ_B", "VERT_A", "VERT_B"].iter().enumerate() { - if AB_ARMS_REACHED[i] { - assert!( - ab_seen[i] > 0, - "{NAME}: PARTITION_{name} at the 128 root fired in the round that \ - pinned this gate but not now: {ab_seen:?}" - ); - } else { - eprintln!( - "{NAME}: PARTITION_{name} NOT reached by this sweep (aomenc never \ - picked it): {ab_seen:?}" - ); - } - } - assert!( - ab_inter.iter().sum::() > 0, - "{NAME}: the AB shapes fired only on KEY frames -- the inter tile path's \ - own AB arm was never exercised: key {ab_seen:?} inter {ab_inter:?}" - ); - } - - #[test] - #[ignore = "lane-sb128 r2 diagnostic: is the frame-6 mismatch sb128-specific?"] - fn sb128_r2_control_sb64() { - // lane-av1cmpaudit2: this control reaches the oracle, so it takes - // the gate mutex like every other one. - let _gate_lock = lock_gate_counters(); - let (width, height) = (256usize, 192usize); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &format!( - "{},noise=all_seed=53:alls=12:allf=t", - gradients_source(53, width, height, "duration=0.32:rate=25") - ), - "-pix_fmt", - "yuv420p", - "-t", - "0.32", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg"); - let out = run_with_stdin( - Command::new(aomenc_path()).args([ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=40", - "--cpu-used=2", - "--threads=1", - "--row-mt=0", - "--sb-size=64", - "--max-partition-size=64", - "--min-partition-size=32", - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-tx-size-search=0", - "--deltaq-mode=0", - "--limit=8", - "--obu", - "-o", - "-", - "-", - ]), - &y4m.stdout, - ); - assert!(out.status.success()); - let (frames, hidden) = decode_all_frames_vs_oracle(&out.stdout, "sb128-control-64"); - eprintln!("control sb64: {frames} frames exact ({hidden} hidden)"); - } - - /// lane-sb128 r2: an INTER SEQUENCE under a 128x128 superblock -- the - /// half ReelC is made of. r1 refused it by name (the inter tile loop - /// recursed a 64x64 root only); r2 ported `sb_visit_order` and the 128 - /// root (per-superblock `read_lr`, the 8-symbol `partition_w128` read with - /// its edge gather, `delta_q`/`delta_lf` at 128 granularity) into that - /// loop, so this gate replaces the refusal test. - /// - /// Every frame in DECODE order, hidden alt-refs included - /// ([`decode_all_frames_vs_oracle`], class gate-blind-to-hidden-frames): - /// `--lag-in-frames` is left at aomenc's default so the encoder really - /// emits them. Per-ATTEMPT counter deltas are hard asserts (class - /// counter-from-refused-stream: the helper panics on any refusal, so every - /// counted attempt is a compared one): 128 partition roots read on this - /// stream, `cdef_idx` reads (one per 64x64 quadrant inside the 128 - /// superblock), and temporal MV candidates (the inter-only path). Both bit - /// depths -- his films are `yuv420p10le`. Only a missing tool SKIPs. - #[test] - fn a_real_aomenc_inter_sequence_with_128x128_superblocks_decodes_pixel_exact() { - const NAME: &str = - "a_real_aomenc_inter_sequence_with_128x128_superblocks_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() || !have_aomenc() { - eprintln!("SKIP {NAME}: no ffmpeg/aomenc/aomdec"); - return; - } - let (width, height) = (256usize, 192usize); - for ten_bit in [false, true] { - let pix = if ten_bit { "yuv420p10le" } else { "yuv420p" }; - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &format!( - // Noise on top of the gradient is what makes aomenc - // signal a nonzero `cdef_bits` (a clean gradient codes - // with CDEF off, and the cdef_idx counter stays 0). - "{},noise=all_seed=53:alls=12:allf=t", - gradients_source(53, width, height, "duration=0.32:rate=25") - ), - "-pix_fmt", - pix, - "-strict", - "-1", - "-t", - "0.32", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "{NAME}: ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let mut args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=40", - "--cpu-used=2", - "--threads=1", - "--row-mt=0", - "--sb-size=128", - "--max-partition-size=64", - // aomenc emits PARTITION_HORZ_4/VERT_4 below 16x16 even with - // the flag off (ledger, lane-modectx r1), so bound the search. - "--min-partition-size=32", - // The inter path still refuses rectangular strips ("a non-skip - // rectangular (HORZ/VERT/HORZ_B) strip needs rectangular - // residual coding") -- another lane's gap, off here so this - // gate measures the 128 root and nothing else. - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-tx-size-search=0", - "--deltaq-mode=0", - "--limit=8", - ]; - if ten_bit { - args.extend_from_slice(&["--input-bit-depth=10", "--bit-depth=10"]); - } - args.extend_from_slice(&["--obu", "-o", "-", "-"]); - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "{NAME}: aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let header = { - let mut parser = ec_av1_syntax::Av1Parser::new(); - let mut pos = 0usize; - while let Ok(obu) = parser.parse_obu(&stream[pos..]) { - pos += obu.total_size; - if pos >= stream.len() { - break; - } - } - parser - .sequence_header() - .map(|q| (q.use_128x128_superblock, q.color_config.bit_depth)) - }; - assert_eq!( - header, - Some((true, if ten_bit { 10 } else { 8 })), - "{NAME}: the encoder did not write a 128x128-superblock sequence header at \ - the requested bit depth -- the flag never arrived" - ); - let before = ( - crate::decode::part128_symbols(), - crate::decode::cdef_idx_hits(), - crate::decode::tmv_hits(), - ); - let (frames, hidden) = decode_all_frames_vs_oracle( - &stream, - &format!("sb128-inter-{}", if ten_bit { 10 } else { 8 }), - ); - let (part128, cdef_idx, tmv) = ( - crate::decode::part128_symbols() - before.0, - crate::decode::cdef_idx_hits() - before.1, - crate::decode::tmv_hits() - before.2, - ); - assert!( - frames >= 6, - "{NAME} ({pix}): only {frames} frames in decode order, the recipe asks for 8" - ); - assert!( - part128 >= 3, - "{NAME} ({pix}): only {part128} 128-level partition symbols on this stream -- \ - the 128 root never fired on the inter frames" - ); - assert!( - cdef_idx >= 1, - "{NAME} ({pix}): no cdef_idx read -- the per-64x64-quadrant cdef read inside \ - the 128 superblock never fired" - ); - assert!( - tmv >= 1, - "{NAME} ({pix}): no temporal MV candidate -- the inter path never ran" - ); - eprintln!( - "{NAME} ({pix}): {frames} decode-order frames pixel-exact ({hidden} hidden), \ - part128_symbols={part128} cdef_idx_hits={cdef_idx} tmv_hits={tmv}" - ); - } - } - - /// lane-sb128c r1: an INTER frame whose 128x128 superblock root really - /// resolves `PARTITION_NONE` -- one whole 128x128 inter block, the shape - /// ReelC's first inter frame stops this decoder on. r1 wired it: four - /// TX_64X64 luma units (`max_txsize_rect_lookup[BLOCK_128X128]`), four - /// TX_32X32 chroma units (`av1_get_max_uv_txsize`), interleaved Y,U,V per - /// 64x64 "mu" chunk (libaom `decode_token_recon_block`) with the chroma - /// `txb_skip_ctx` offset-10 rows, and OBMC's overlap capped at a 64x64 - /// block's half (`reconinter.c` 860/899). - /// - /// `--max-partition-size=128` is what lets the root be NONE at all (the - /// sibling gate above pins 64, so its roots always SPLIT). Every arm hard - /// asserts its own `inter_sb128_none_hits` delta, so a recipe that stops - /// choosing the shape fails instead of passing vacuously; every decode - /// order frame is compared by [`decode_all_frames_vs_oracle`], which - /// panics on a refusal or any differing byte. Arms: 8-bit and 10-bit (his - /// films are 10-bit) with `tx-size-search=0` (TX_MODE_LARGEST, the block's - /// four TX_64X64 units come straight from `max_txsize_rect_lookup`) and an - /// 8-bit `tx-size-search=1` arm (the var-tx tree at 128). - // lane-sb128c r3: green. `--min-partition-size=32` let the RD search reach - // 16x16-level AB / SB-level AB shapes that other lanes still refuse (two of - // the three arms stopped there, measured); at 64 every arm decodes and the - // 128 root still resolves NONE. - #[test] - fn a_real_aomenc_inter_128x128_none_root_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_inter_128x128_none_root_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() || !have_aomenc() { - eprintln!("SKIP {NAME}: no ffmpeg/aomenc/aomdec"); - return; - } - let (width, height) = (256usize, 256usize); - let mut intra128_total = 0usize; - for (ten_bit, tx_search, seed) in - [(false, false, 61u32), (true, false, 61), (false, true, 62)] - { - let pix = if ten_bit { "yuv420p10le" } else { "yuv420p" }; - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &format!( - "{},noise=all_seed={seed}:alls=6:allf=t", - gradients_source(seed, width, height, "duration=0.32:rate=25") - ), - "-pix_fmt", - pix, - "-strict", - "-1", - "-t", - "0.32", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "{NAME}: ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let mut args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=62", - "--cpu-used=0", - "--threads=1", - "--row-mt=0", - "--sb-size=128", - "--max-partition-size=128", - "--min-partition-size=64", - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-palette=0", - "--enable-intrabc=0", - "--deltaq-mode=0", - "--limit=8", - ]; - // Spelled ONCE per invocation (a repeated `--enable-*` keeps its - // LAST occurrence, measured 2026-09-02). - args.push(if tx_search { - "--enable-tx-size-search=1" - } else { - "--enable-tx-size-search=0" - }); - if ten_bit { - args.extend_from_slice(&["--input-bit-depth=10", "--bit-depth=10"]); - } - args.extend_from_slice(&["--obu", "-o", "-", "-"]); - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "{NAME}: aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let header = { - let mut parser = ec_av1_syntax::Av1Parser::new(); - let mut pos = 0usize; - while let Ok(obu) = parser.parse_obu(&stream[pos..]) { - pos += obu.total_size; - if pos >= stream.len() { - break; - } - } - parser - .sequence_header() - .map(|q| (q.use_128x128_superblock, q.color_config.bit_depth)) - }; - assert_eq!( - header, - Some((true, if ten_bit { 10 } else { 8 })), - "{NAME}: the encoder did not write a 128x128-superblock sequence header at \ - the requested bit depth -- the flag never arrived" - ); - let before = ( - crate::decode::inter_sb128_none_hits(), - crate::decode::chroma_split_tx_hits(), - crate::decode::intra_128_in_inter_hits(), - ); - let (frames, hidden) = decode_all_frames_vs_oracle( - &stream, - &format!( - "sb128c-inter-none-{}-{}", - if ten_bit { 10 } else { 8 }, - tx_search - ), - ); - let (none128, chroma_units, intra128) = ( - crate::decode::inter_sb128_none_hits() - before.0, - crate::decode::chroma_split_tx_hits() - before.1, - crate::decode::intra_128_in_inter_hits() - before.2, - ); - intra128_total += intra128; - assert!( - frames >= 6, - "{NAME} ({pix} tx_search={tx_search}): only {frames} decode-order frames" - ); - assert!( - none128 >= 1, - "{NAME} ({pix} tx_search={tx_search}): no 128x128 PARTITION_NONE root on an \ - inter frame -- the recipe stopped exercising the shape this gate names" - ); - eprintln!( - "{NAME} ({pix} tx_search={tx_search}): {frames} decode-order frames pixel-exact \ - ({hidden} hidden), inter_sb128_none_hits={none128} chroma_units={chroma_units} \ - intra_128_in_inter={intra128}" - ); - } - assert!( - intra128_total >= 1, - "{NAME}: no INTRA-coded 128x128 block inside an inter frame across the three arms -- \ - the refusal this round lifted is no longer exercised" - ); - } - - /// lane-av1-444-128: a real `aomenc` stream whose inter frames are ONE - /// 128x128 PARTITION_NONE block each, non-skip, must walk that block's - /// chroma through the mu-chunk loop -- one TX_32X32 unit per 64x64 mu - /// chunk per plane at 4:2:0 (`decode_token_recon_block`'s mu walk with - /// `av1_get_max_uv_txsize(BLOCK_128X128)` = `TX_32X32`), each unit read - /// at its own origin against its own entropy-cell span and stamped - /// immediately (`av1_set_entropy_contexts`). The census asserts the walk - /// actually ran (four units per plane per coded 128-none block); the key - /// frame splits to 64x64 (detailed testsrc2 content), so the whole - /// stream stays inside the 4:2:0 paths this tree decodes. The 4:4:4 twin - /// of this shape (FOUR TX_32X32 units per chunk per plane) is witnessed - /// in `lanes/av1444128.report.md` and committed here as - /// `a_real_aomenc_444_intra_in_inter_128_root_codes_chroma_per_mu_chunk_unit_pixel_exact`. - /// lane-av1422lift: the sequence-header refusal is gone, so this tree no - /// longer refuses non-4:2:0 sequences by name. - #[test] - fn a_real_aomenc_128x128_none_inter_blocks_coded_chroma_per_mu_chunk_decodes_pixel_exact() { - const NAME: &str = - "a_real_aomenc_128x128_none_inter_blocks_coded_chroma_per_mu_chunk_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() || !have_aomenc() { - eprintln!("SKIP {NAME}: no ffmpeg/aomenc/aomdec"); - return; - } - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - "testsrc2=size=128x128:rate=30", - "-frames:v", - "12", - "-pix_fmt", - "yuv420p", - "-strict", - "-1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "{NAME}: ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=8", - "--cpu-used=2", - "--threads=1", - "--row-mt=0", - "--lag-in-frames=0", - "--kf-max-dist=100", - "--enable-fwd-kf=0", - "--sb-size=128", - "--max-partition-size=128", - "--min-partition-size=64", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cdef=0", - "--enable-restoration=0", - "--loopfilter-control=0", - "--enable-obmc=0", - "--enable-warped-motion=0", - "--enable-interintra-comp=0", - "--enable-interintra-wedge=0", - "--enable-smooth-interintra=0", - "--enable-ref-frame-mvs=0", - "--deltaq-mode=0", - "--tile-columns=0", - "--limit=12", - "--obu", - "-o", - "-", - "-", - ]; - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "{NAME}: aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let header = { - let mut parser = ec_av1_syntax::Av1Parser::new(); - let mut pos = 0usize; - while let Ok(obu) = parser.parse_obu(&stream[pos..]) { - pos += obu.total_size; - if pos >= stream.len() { - break; - } - } - parser - .sequence_header() - .map(|q| (q.use_128x128_superblock, q.color_config.bit_depth)) - }; - assert_eq!( - header, - Some((true, 8)), - "{NAME}: the encoder did not write a 128x128-superblock 8-bit sequence header -- \ - the flags never arrived" - ); - let before = ( - crate::decode::inter_sb128_none_hits(), - crate::decode::chroma_split_tx_hits(), - ); - let (frames, hidden) = decode_all_frames_vs_oracle(&stream, "av1444128-128none-mu-chroma"); - let (none128, chroma_units) = ( - crate::decode::inter_sb128_none_hits() - before.0, - crate::decode::chroma_split_tx_hits() - before.1, - ); - assert!(frames >= 11, "{NAME}: only {frames} decode-order frames"); - assert!( - none128 >= 8, - "{NAME}: only {none128} inter 128x128 PARTITION_NONE roots -- the recipe stopped \ - exercising the shape this gate names" - ); - assert!( - chroma_units >= 8 * 8, - "{NAME}: only {chroma_units} mu-chunk chroma units read -- the per-unit walk this \ - gate names never fired (four units per plane per coded 128-none inter block)" - ); - eprintln!( - "{NAME}: {frames} decode-order frames pixel-exact ({hidden} hidden), \ - inter_sb128_none_hits={none128} chroma_units={chroma_units}" - ); - } - - /// lane-av1ibc128arm: the INTRA-in-inter 128x128 root's mu-chunk chroma - /// arm (`decode_inter_block`'s `side > 64` arm, the intra half of the - /// inter pair the sibling gate above names) must code the mu chunk's - /// chroma as a PER-UNIT walk at every subsampling, and at 4:4:4 each - /// 64x64 mu chunk is FOUR TX_32X32 units per plane, not one. - /// - /// **The defect.** The arm hardcoded `cu_tx = 32`, `luma_span = cu_tx * - /// 2` and the chroma origin `cc * cu_tx` -- the 4:2:0 arithmetic, where a - /// mu chunk's chroma plane block is `64 >> 1 == 32` square and the whole - /// chunk IS one TX_32X32 unit. At 4:4:4 the chunk's chroma is 64x64, so - /// the arm (a) read one 32x32 unit where libaom codes four, (b) stamped - /// the unit's entropy context over the 4:2:0 64x64 luma span rather than - /// the unit's own 32x32, and (c) placed chunk 1's unit at `cpx + 32` - /// instead of `cpx + 64`, i.e. back inside chunk 0's samples. - /// - /// **`av1_get_max_uv_txsize` is NOT the source of a 64x64 chroma unit.** - /// `blockd.h:1371` is `av1_get_adjusted_tx_size(max_txsize_rect_lookup[ - /// get_plane_block_size(bsize, ss_x, ss_y)])`, and `av1_get_adjusted_tx_size` - /// (`blockd.h:1361`) takes NO subsampling argument -- it maps TX_64X64 / - /// TX_64X32 / TX_32X64 to TX_32X32 UNCONDITIONALLY, so even at ss (0,0) - /// (where `get_plane_block_size` returns BLOCK_128X128 and the lookup - /// entry is TX_64X64) the answer is TX_32X32. Measured on this gate's own - /// stream against the oracle's `EC_TRACE_COEFF`: every chroma read of the - /// 128x128 intra-in-inter root is `tx_size=3` (TX_32X32), four per plane - /// per mu chunk at (row,col) (0,0) (0,8) (8,0) (8,8). - /// - /// **The recipe** (128x256, 3 frames). `--sb-size=128` with - /// `--min-partition-size=64 --max-partition-size=128` keeps the - /// superblock root resolvable to `PARTITION_NONE`, and the noise-on- - /// gradient content is what makes the encoder's RD pick INTRA over inter - /// for a whole 128 root on an inter frame (a clean `testsrc2` stream - /// never does -- measured over 24 recipe/cell combinations, three of - /// which fired and none of them `testsrc2`): - /// ```text - /// ffmpeg -f lavfi -i "gradients=size=128x256:c0=..:c1=..:c2=..:c3=..:\ - /// seed=63:duration=0.12:rate=25,noise=all_seed=63:alls=6:allf=t" \ - /// -pix_fmt yuv444p -t 0.12 -f yuv4mpegpipe - | \ - /// aomenc --codec=av1 --profile=1 --passes=1 --end-usage=q --cq-level=62 \ - /// --cpu-used=0 --threads=1 --row-mt=0 --sb-size=128 --limit=3 \ - /// --max-partition-size=128 --min-partition-size=64 \ - /// --enable-rect-partitions=0 --enable-ab-partitions=0 \ - /// --enable-1to4-partitions=0 --enable-palette=0 \ - /// --enable-intrabc=0 --deltaq-mode=0 --enable-tx-size-search=0 \ - /// --obu -o out.obu - - /// ``` - /// Both `rate=25` and the frame limit are load-bearing: `gradients`' and - /// `noise`' patterns are time-parameterised, so a different rate or a - /// different `--limit` emits a different stream (and at `--limit=2` this - /// recipe stops choosing the shape at all -- measured, 0 fires). - /// - /// Non-vacuity, three ways: the sequence header is asserted really to be - /// 4:4:4 (`subsampling_x == subsampling_y == 0`) and 128-superblock; - /// `intra_128_in_inter_mu_chroma_hits()` must be non-zero, so the arm - /// really ran; and every decode-order frame is compared byte-for-byte - /// against the oracle by [`decode_all_frames_vs_oracle`], which panics on - /// a refusal or any differing byte. Red before the fix (the ss-aware - /// arithmetic and the per-unit walk reverted, the counter kept): decode- - /// order frame 2 differs in 44649 of 98304 bytes while the counter still - /// reads 4 -- the red is on PIXELS, not on the counter. - #[test] - fn a_real_aomenc_444_intra_in_inter_128_root_codes_chroma_per_mu_chunk_unit_pixel_exact() { - const NAME: &str = - "a_real_aomenc_444_intra_in_inter_128_root_codes_chroma_per_mu_chunk_unit_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() || !have_aomenc() { - eprintln!("SKIP {NAME}: no ffmpeg/aomenc/aomdec"); - return; - } - let (width, height) = (128usize, 256usize); - let source = format!( - "{},noise=all_seed=63:alls=6:allf=t", - gradients_source(63, width, height, "duration=0.12:rate=25") - ); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-pix_fmt", - "yuv444p", - "-t", - "0.12", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "{NAME}: ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let args: Vec<&str> = vec![ - "--codec=av1", - "--profile=1", - "--passes=1", - "--end-usage=q", - "--cq-level=62", - "--cpu-used=0", - "--threads=1", - "--row-mt=0", - "--sb-size=128", - "--limit=3", - "--max-partition-size=128", - "--min-partition-size=64", - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-palette=0", - "--enable-intrabc=0", - "--deltaq-mode=0", - "--enable-tx-size-search=0", - "--obu", - "-o", - "-", - "-", - ]; - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "{NAME}: aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - // The gate is only about 4:4:4 at a 128 superblock, so assert the - // parsed sequence header really is that before anything else: a - // stream that silently came back 4:2:0 would leave this arm - // unexercised while every other assert below still passed. - let header = { - let mut parser = ec_av1_syntax::Av1Parser::new(); - let mut pos = 0usize; - while let Ok(obu) = parser.parse_obu(&stream[pos..]) { - pos += obu.total_size; - if pos >= stream.len() { - break; - } - } - parser.sequence_header().map(|q| { - ( - q.use_128x128_superblock, - q.color_config.subsampling_x, - q.color_config.subsampling_y, - q.color_config.mono_chrome, - ) - }) - }; - assert_eq!( - header, - Some((true, 0, 0, false)), - "{NAME}: the encoder did not write a 4:4:4 (ss 0/0, non-mono) 128x128-superblock \ - sequence header -- the flags never arrived, so the arm this gate names is not \ - the one under test" - ); - let before = ( - crate::decode::intra_128_in_inter_hits(), - crate::decode::intra_128_in_inter_mu_chroma_hits(), - ); - let (frames, hidden) = decode_all_frames_vs_oracle(&stream, NAME); - let (roots, units) = ( - crate::decode::intra_128_in_inter_hits() - before.0, - crate::decode::intra_128_in_inter_mu_chroma_hits() - before.1, - ); - assert!( - frames >= 3, - "{NAME}: only {frames} decode-order frames ({hidden} hidden), the recipe asks for 3" - ); - assert!( - roots >= 1, - "{NAME}: no INTRA-coded 128x128 root inside an inter frame -- the recipe stopped \ - exercising the shape this gate names" - ); - // One mu chunk per arm firing, and at 4:4:4 FOUR units per plane per - // chunk (two 64x64 mu chunks per 128 root, two planes each). - assert!( - units >= 4, - "{NAME}: only {units} mu-chunk chroma reads across {roots} intra-in-inter 128 \ - root(s) -- the per-unit walk this gate names never fired (a 4:4:4 64x64 mu chunk \ - is FOUR TX_32X32 units per plane, not one)" - ); - eprintln!( - "{NAME}: {frames} decode-order frames pixel-exact ({hidden} hidden), \ - intra_128_in_inter={roots} mu_chunk_chroma_reads={units}" - ); - } - - /// lane-av1sb128chroma: the PINNED half of - /// [`a_real_aomenc_444_intra_in_inter_128_root_codes_chroma_per_mu_chunk_unit_pixel_exact`]. - /// That gate re-encodes its fixture on every run, so the arm it names had - /// NO committed 4:4:4 bytes at all: a host without ffmpeg/aomenc silently - /// skips it, and the whole committed 4:4:4 base is lossless 8-bit, so - /// nothing else in the crate decoded one of these streams. This gate is - /// the pin, and it also carries the COUNTER-PROOF arm: the recipe a - /// proposed 4:4:4 `--sb-size=128` chroma repair was argued from reads - /// ZERO on both the arm's own counters, so its green is vacuous. - /// - /// **Witness** `fixtures/444_intra_in_inter_128root_mu_chroma.obu`, - /// sha256 `f5999bd996fef820472dc7846e42cad3e62bd1f816fafd7f218e34b77786394a`, - /// 3570 bytes, 3 decode-order frames. Recipe (verified byte-reproducible): - /// ```text - /// ffmpeg -v error -f lavfi -i "gradients=size=128x256:c0=0xa1128f:c1=0xd98c48:\ - /// c2=0x120601:c3=0x4abfba:seed=63:duration=0.12:rate=25,\ - /// noise=all_seed=63:alls=6:allf=t" -pix_fmt yuv444p -t 0.12 -f yuv4mpegpipe - > in.y4m - /// aomenc --codec=av1 --profile=1 --passes=1 --end-usage=q --cq-level=62 \ - /// --cpu-used=0 --threads=1 --row-mt=0 --sb-size=128 --limit=3 \ - /// --max-partition-size=128 --min-partition-size=64 \ - /// --enable-rect-partitions=0 --enable-ab-partitions=0 \ - /// --enable-1to4-partitions=0 --enable-palette=0 --enable-intrabc=0 \ - /// --deltaq-mode=0 --enable-tx-size-search=0 --obu -o out.obu in.y4m - /// ``` - /// `duration=0.12:rate=25` and `--limit=3` are load-bearing (the - /// `gradients`/`noise` patterns are time-parameterised, and at `--limit=2` - /// the encoder stops choosing INTRA over inter for a whole 128 root). - /// - /// **Measured on this witness** (unpatched `main` `57834ee2`): the arm - /// fires `intra_128_in_inter_hits = 1` root and - /// `intra_128_in_inter_mu_chroma_hits = 4` mu-chunk chroma reads (a 4:4:4 - /// 64x64 mu chunk is FOUR TX_32X32 units per plane, two chunks, one - /// plane reached before the other), and all 3 frames are byte-exact - /// against the oracle. The claimed `cu_tx = 64` repair is refuted by two - /// independent measurements: (a) with `cu_tx` at 64 this arm PANICS -- - /// `no default scan for a 64-point transform` at `decode.rs:7197`, because - /// libaom's `av1_get_adjusted_tx_size` (blockd.h:1361) maps TX_64X64 to - /// TX_32X32 unconditionally, so a 4:4:4 chroma unit is never 64 and - /// `av1_scan_orders` has no 64-point chroma table; (b) with only the - /// luma-span and per-chunk-origin halves of that repair applied (`cu_tx` - /// left at 32 so the mutation reaches the pixels), this same witness goes - /// RED: Y 12537, U 16696, V 16667 wrong samples of 98304 per plane, - /// first at Y(90,120) ours 142 vs oracle 141, U(65,120) 153 vs 152, - /// V(64,120) 145 vs 146 -- all of it on decode-order frame 2, and the - /// counters still read 1/4, so the damage is on PIXELS. - #[test] - fn a_444_intra_in_inter_128root_muchroma_pinned_stream_decodes_pixel_exact() { - const NAME: &str = - "a_444_intra_in_inter_128root_muchroma_pinned_stream_decodes_pixel_exact"; - const WITNESS_LEN: usize = 3570; - const WITNESS_FNV: u64 = 0xe455_060d_f685_86dd; - const CONTROL_LEN: usize = 31602; - const CONTROL_FNV: u64 = 0xc542_f45f_f3a5_d494; - const W: usize = 128; - const H: usize = 256; - const FRAMES: usize = 3; - let dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("fixtures"); - let read_pinned = |name: &str, len: usize, fnv: u64| -> Vec { - let path = dir.join(name); - let bytes = std::fs::read(&path).unwrap_or_else(|e| { - panic!( - "{NAME}: pinned fixture {} is missing ({e}) -- the gate cannot run, \ - which is a failure, not a skip", - path.display() - ) - }); - assert_eq!(bytes.len(), len, "{NAME}: {name} length moved"); - assert_eq!(fnv1a64(&bytes), fnv, "{NAME}: {name} bytes moved"); - bytes - }; - let stream = read_pinned( - "444_intra_in_inter_128root_mu_chroma.obu", - WITNESS_LEN, - WITNESS_FNV, - ); - - let _gate_lock = lock_gate_counters(); - // The shape claim first: a stream that silently came back 4:2:0 would - // leave the arm unexercised while every other assert still passed. - let header = { - let mut parser = ec_av1_syntax::Av1Parser::new(); - let mut pos = 0usize; - while let Ok(obu) = parser.parse_obu(&stream[pos..]) { - pos += obu.total_size; - if pos >= stream.len() { - break; - } - } - parser.sequence_header().map(|q| { - ( - q.use_128x128_superblock, - q.color_config.subsampling_x, - q.color_config.subsampling_y, - q.color_config.mono_chrome, - ) - }) - }; - assert_eq!( - header, - Some((true, 0, 0, false)), - "{NAME}: the witness is not a 4:4:4 (ss 0/0, non-mono) 128x128-superblock stream \ - -- {header:?}, so the arm under test is not the one that ran" - ); - let before = ( - crate::decode::intra_128_in_inter_hits(), - crate::decode::intra_128_in_inter_mu_chroma_hits(), - ); - let (decoded, hidden) = decode_all_frames_vs_oracle(&stream, NAME); - let (roots, units) = ( - crate::decode::intra_128_in_inter_hits() - before.0, - crate::decode::intra_128_in_inter_mu_chroma_hits() - before.1, - ); - assert_eq!(decoded, FRAMES, "{NAME}: decode-order frame count"); - // At 4:4:4 the chroma planes are full resolution; a decoder that kept - // the 4:2:0 extent would hand quarter-size chroma to the byte compare, - // which cannot pass. Say it here rather than let the compare stand in - // for the shape claim. - for f in crate::stream::decode_stream(&stream) - .unwrap_or_else(|e| panic!("{NAME}: the witness no longer decodes cleanly: {e}")) - { - assert_eq!((f.width, f.height), (W, H), "{NAME}: frame dimensions"); - assert_eq!( - f.u.len(), - W * H, - "{NAME}: chroma plane is {} samples", - f.u.len() - ); - } - assert!( - roots >= 1, - "{NAME}: no INTRA-coded 128x128 root inside an inter frame -- the arm under \ - test never ran" - ); - assert!( - units >= 4, - "{NAME}: only {units} mu-chunk chroma reads across {roots} intra-in-inter 128 \ - root(s) -- a 4:4:4 64x64 mu chunk is FOUR TX_32X32 units per plane, so fewer \ - than four means the per-unit walk this gate names did not run" - ); - eprintln!( - "{NAME}: {decoded} decode-order frame(s) pixel-exact ({hidden} hidden), \ - intra_128_in_inter={roots} mu_chunk_chroma_reads={units}" - ); - - // The COUNTER-PROOF arm. The 4:4:4 `--sb-size=128 --cq-level=20` - // `testsrc2` recipe a 64-point-chroma repair was argued from is - // byte-exact on all 24 frames AND reads ZERO on both of the arm's - // counters: on clean `testsrc2` the encoder's RD never picks INTRA - // over inter for a whole 128 root, so that stream cannot witness this - // arm at all. Pinning it keeps the refutation reproducible in-crate - // with no encoder on the host. - let control = read_pinned("444_sb128cq20_tsrc2_control.obu", CONTROL_LEN, CONTROL_FNV); - let ctl_header = { - let mut parser = ec_av1_syntax::Av1Parser::new(); - let mut pos = 0usize; - while let Ok(obu) = parser.parse_obu(&control[pos..]) { - pos += obu.total_size; - if pos >= control.len() { - break; - } - } - parser.sequence_header().map(|q| { - ( - q.use_128x128_superblock, - q.color_config.subsampling_x, - q.color_config.subsampling_y, - ) - }) - }; - assert_eq!( - ctl_header, - Some((true, 0, 0)), - "{NAME}: the control stream is not the 4:4:4 128-superblock stream its recipe \ - names -- {ctl_header:?}" - ); - let ctl_before = ( - crate::decode::intra_128_in_inter_hits(), - crate::decode::intra_128_in_inter_mu_chroma_hits(), - ); - let ctl_frames = crate::stream::decode_stream(&control) - .unwrap_or_else(|e| panic!("{NAME}: the control stream no longer decodes: {e}")) - .len(); - let ctl = ( - crate::decode::intra_128_in_inter_hits() - ctl_before.0, - crate::decode::intra_128_in_inter_mu_chroma_hits() - ctl_before.1, - ); - assert_eq!(ctl_frames, 24, "{NAME}: control frame count"); - assert_eq!( - ctl, - (0, 0), - "{NAME}: the control stream now reaches the arm ({ctl:?}) -- the witness's \ - non-vacuity argument rested on `testsrc2` never choosing an \ - intra-coded 128 root, and that is no longer true, so the two \ - fixtures no longer separate the cells" - ); - if aomdec_available(NAME) { - let (ctl_decoded, ctl_hidden) = decode_all_frames_vs_oracle(&control, NAME); - assert_eq!(ctl_decoded, 24, "{NAME}: control decode-order frame count"); - eprintln!("{NAME}: control {ctl_decoded} frame(s) pixel-exact ({ctl_hidden} hidden)"); - } - } - - /// lane-av1muchunk422b: the **compound** `side > 64` mu-chunk walk -- - /// per-unit chroma allocation of `decode_inter_block`'s compound arm, site - /// 2 of `lanes/av1muchunk422.report.md`, which that lane's recipes all - /// missed (`part128 none=0` on a 384x256 frame). - /// - /// Reachability, shared with the intra-in-inter twin below: the streams - /// that reach this walk are 128-as-the-whole-frame (`--sb-size=128 - /// --min-partition-size=128 --max-partition-size=128`, PARTITION_NONE - /// forced; here `part128 none=7`) and LOSSY, which is load-bearing: each arm - /// has a lossless branch that returns before the unit loop, and - /// `W_intrabc.obu` reaches both guards at ss (1,0) allocating nothing. That - /// is why [`crate::decode::mu_chunk_compound_units`] counts at the - /// ALLOCATION and not at the guard; the counter-proof at the end of the - /// intra test pins that gap. The single-reference twin of site 2 (site 5) - /// shares this exact source text and is routed out of the counter by - /// `is_compound`. - /// - /// **7 of the 8 streams this lane generated DIVERGED from ffmpeg; only - /// `i6_grad128_iis` (the intra-in-inter fixture, pinned in the twin test - /// below) was byte-exact.** lane-av1muchunk422sym has since fixed this - /// pin's stream: the compound mu-chunk walk gathered its CHROMA - /// coefficient context with the plain rect rule, which at ss (1, 0) counts - /// one chroma column twice in the above vote (see the walk's own comment). - /// **The stream is now byte-exact against the instrumented aomdec over all - /// 7 decode-order frames (6 shown + 1 hidden alt-ref)**, so this test - /// carries both halves: the counter witness that the walk ran AND the - /// exactness witness. The pinned V-plane hashes run without an oracle; - /// `decode_all_frames_vs_oracle` adds the decode-order compare when one is - /// present. The counter half still stops this fixture silently ceasing to - /// reach the walk it was pinned for. - /// - /// Recipe (byte-reproducible; whole aomenc argv): - /// ```text - /// ffmpeg -v error -f lavfi -i "testsrc2=size=128x128:rate=25" -t 0.24 \ - /// -pix_fmt yuv422p -f yuv4mpegpipe - > tsrc128.y4m - /// aomenc --codec=av1 --profile=2 --input-chroma-subsampling-x=1 \ - /// --input-chroma-subsampling-y=0 --passes=1 --end-usage=q --cq-level=62 \ - /// --cpu-used=0 --threads=1 --row-mt=0 --sb-size=128 \ - /// --min-partition-size=128 --max-partition-size=128 \ - /// --enable-rect-partitions=0 --enable-ab-partitions=0 \ - /// --enable-1to4-partitions=0 --enable-palette=0 --enable-intrabc=0 \ - /// --deltaq-mode=0 --enable-tx-size-search=0 --enable-interintra-comp=1 \ - /// --enable-interintra-wedge=1 --enable-smooth-interintra=1 --obu -o X - /// ``` - #[test] - fn a_422_muchunk_compound_128root_pinned_stream_reaches_its_unit_walk() { - const NAME: &str = "a_422_muchunk_compound_128root_pinned_stream_reaches_its_unit_walk"; - const FILE: &str = "422_muchunk_compound_128root.obu"; - const LEN: usize = 895; - const FNV: u64 = 0xfb28_f9a7_cf23_9897; - const MIN_UNITS: usize = 32; - // lane-av1muchunk422sym: shown frame 2's V plane byte-for-byte (it is - // the first intrinsically wrong frame; the pre-fix square gather put - // 2138 of these 8192 samples off by up to 4), and shown frame 0's as - // the unaffected control. 0xa0e5_8bf4_207b_29ba is the ffmpeg/aomdec - // exact plane. - const SHOWN_F2_V_FNV: u64 = 0xa0e5_8bf4_207b_29ba; - const SHOWN_F0_V_FNV: u64 = 0xcc5e_3291_1915_9024; - /// Chroma (36, 60) of shown frame 2 -- the FIRST sample that moved, - /// `60 * 64 + 36`. The pre-fix square gather read 113, the oracle 112. - const FIRST_WRONG_V: usize = 3876; - const SHOWN_F2_V_AT_FIRST_WRONG: u16 = 112; - let _gate_lock = lock_gate_counters(); - let stream = read_pinned_muchunk_fixture(FILE, LEN, FNV, NAME); - assert_eq!( - obu_stream_shape(&stream), - Some((true, 1, 0, false)), - "{NAME}: {FILE} is not a 4:2:2 (ss 1/0, non-mono) 128x128-superblock stream" - ); - let before = ( - crate::decode::mu_chunk_compound_units(), - crate::decode::mu_chunk_intra_in_inter_units(), - ); - let shown = crate::stream::decode_stream(&stream) - .unwrap_or_else(|e| panic!("{NAME}: {FILE} no longer decodes cleanly: {e}")); - let frames = shown.len(); - let (compound, intra) = ( - crate::decode::mu_chunk_compound_units() - before.0, - crate::decode::mu_chunk_intra_in_inter_units() - before.1, - ); - assert_eq!(frames, 6, "{NAME}: {FILE} shown-frame count"); - assert!( - compound >= MIN_UNITS, - "{NAME}: {FILE} allocated only {compound} compound `side > 64` mu-chunk units \ - (expected >= {MIN_UNITS}) -- the walk this gate names did not run" - ); - assert_eq!( - intra, 0, - "{NAME}: {FILE} also ran the intra-in-inter walk ({intra} units) -- the two fixtures \ - no longer separate the cells" - ); - // lane-av1muchunk422sym: the EXACTNESS half the diagnostic lane handed - // over ("when a fix lane lands, add the oracle compare to this test"). - // The fix routes this walk's CHROMA context gather through the 4:2:2 - // pair rule (`around_mi_422_chroma`): at ss (1, 0) one chroma column - // spans two luma mi columns, so the plain rect gather summed the unit's - // above dc sign twice and `dc_sign_ctx`'s signum flipped whenever above - // and left cancelled. The first wrong symbol was the DC SIGN of the V - // unit at chunk (1, 1) of decode frame 2 -- ours read - // `dc_sign_cdf[1]`, the oracle row 0. - // - // The pinned half below needs NO oracle and is therefore the one that - // cannot silently skip: shown frame 2 (the first intrinsically wrong - // frame) is asserted sample-for-sample on its V plane. Frame 0's is - // asserted too, as the unaffected control that fails if the gather is - // "fixed" past its own cell. - assert_eq!( - shown[0].v.len(), - 64 * 128, - "{NAME}: {FILE} is no longer 4:2:2 -- the V plane shape moved" - ); - assert_eq!( - fnv1a64(&shown[2].v.iter().map(|&s| s as u8).collect::>()), - SHOWN_F2_V_FNV, - "{NAME}: {FILE} shown frame 2's V plane moved -- the compound mu-chunk walk's 4:2:2 \ - chroma context gather is wrong again (first sample to move is chroma (36, 60), index \ - 3876, expected {})", - SHOWN_F2_V_AT_FIRST_WRONG - ); - assert_eq!( - shown[2].v[FIRST_WRONG_V], SHOWN_F2_V_AT_FIRST_WRONG, - "{NAME}: {FILE} shown frame 2 V[3876] (chroma (36, 60)) is {} -- the pre-fix square \ - gather read 113 here", - shown[2].v[FIRST_WRONG_V] - ); - assert_eq!( - fnv1a64(&shown[0].v.iter().map(|&s| s as u8).collect::>()), - SHOWN_F0_V_FNV, - "{NAME}: {FILE} shown frame 0's V plane moved -- the 4:2:2 routing changed a frame it \ - must not touch" - ); - if aomdec_available(NAME) { - let (decoded, hidden) = decode_all_frames_vs_oracle(&stream, NAME); - assert_eq!(decoded, 7, "{NAME}: {FILE} decode-order frame count"); - eprintln!( - "{NAME}: {FILE} byte-exact over {decoded} decode-order frame(s) ({hidden} hidden), \ - compound_units={compound} intra_in_inter_units={intra}" - ); - } else { - eprintln!( - "{NAME}: {FILE} compound_units={compound} intra_in_inter_units={intra} -- the \ - decode-order oracle compare above did NOT run (no aomdec)" - ); - } - } - - /// lane-av1muchunk422b: the **intra-in-inter** `side > 64` mu-chunk walk -- - /// per-unit chroma allocation of the intra-in-inter arm (site 8 of - /// `lanes/av1muchunk422.report.md`). This is the ONE stream of the eight - /// this lane generated that is BYTE-EXACT against the ffmpeg/aom oracle - /// (`i6_grad128_iis`), so unlike its compound twin this gate asserts - /// pixel-exactness over every decode-order frame AND that the site counter - /// moved. See the compound test above for the shared reachability and - /// count-at-the-ALLOCATION argument. - /// - /// Recipe (byte-reproducible; same aomenc argv as the compound test except - /// for the source): - /// ```text - /// ffmpeg -v error -f lavfi -i "gradients=size=128x256:c0=0xa1128f:\ - /// c1=0xd98c48:c2=0x120601:c3=0x4abfba:seed=63:duration=0.24:rate=25,\ - /// noise=all_seed=63:alls=6:allf=t" -t 0.24 -pix_fmt yuv422p \ - /// -f yuv4mpegpipe - > grad256.y4m - /// aomenc --codec=av1 --profile=2 --input-chroma-subsampling-x=1 \ - /// --input-chroma-subsampling-y=0 --passes=1 --end-usage=q --cq-level=62 \ - /// --cpu-used=0 --threads=1 --row-mt=0 --sb-size=128 \ - /// --min-partition-size=128 --max-partition-size=128 \ - /// --enable-rect-partitions=0 --enable-ab-partitions=0 \ - /// --enable-1to4-partitions=0 --enable-palette=0 --enable-intrabc=0 \ - /// --deltaq-mode=0 --enable-tx-size-search=0 --enable-interintra-comp=1 \ - /// --enable-interintra-wedge=1 --enable-smooth-interintra=1 --obu -o X - /// ``` - #[test] - fn a_422_muchunk_intra_in_inter_128root_pinned_stream_is_exact_and_reaches_its_unit_walk() { - const NAME: &str = - "a_422_muchunk_intra_in_inter_128root_pinned_stream_is_exact_and_reaches_its_unit_walk"; - const FILE: &str = "422_muchunk_intra_in_inter_128root.obu"; - const LEN: usize = 391; - const FNV: u64 = 0xe4d7_2c19_5a11_1f4f; - const MIN_UNITS: usize = 16; - // 6 shown frames + the 1 hidden alt-ref frame the oracle also emits. - const DECODED: usize = 7; - let _gate_lock = lock_gate_counters(); - let stream = read_pinned_muchunk_fixture(FILE, LEN, FNV, NAME); - assert_eq!( - obu_stream_shape(&stream), - Some((true, 1, 0, false)), - "{NAME}: {FILE} is not a 4:2:2 (ss 1/0, non-mono) 128x128-superblock stream" - ); - let before = ( - crate::decode::mu_chunk_compound_units(), - crate::decode::mu_chunk_intra_in_inter_units(), - ); - let frames = crate::stream::decode_stream(&stream) - .unwrap_or_else(|e| panic!("{NAME}: {FILE} no longer decodes cleanly: {e}")) - .len(); - let (compound, intra) = ( - crate::decode::mu_chunk_compound_units() - before.0, - crate::decode::mu_chunk_intra_in_inter_units() - before.1, - ); - assert_eq!(frames, 6, "{NAME}: {FILE} shown-frame count"); - assert!( - intra >= MIN_UNITS, - "{NAME}: {FILE} allocated only {intra} intra-in-inter `side > 64` mu-chunk units \ - (expected >= {MIN_UNITS}) -- the site counter this gate names did not move" - ); - assert_eq!( - compound, 0, - "{NAME}: {FILE} also ran the compound walk ({compound} units) -- the two fixtures no \ - longer separate the cells" - ); - if aomdec_available(NAME) { - let (decoded, hidden) = decode_all_frames_vs_oracle(&stream, NAME); - assert_eq!(decoded, DECODED, "{NAME}: {FILE} decode-order frame count"); - eprintln!( - "{NAME}: {FILE} byte-exact over {decoded} decode-order frame(s) ({hidden} \ - hidden), intra_in_inter_units={intra}" - ); - } - - // The counter-proof: the LOSSLESS 4:2:2 stream that reaches both - // `side > 64` guards at ss (1,0) and allocates nothing. `W_intrabc` - // is the fixture the prior lane measured `site 2 = 0` on, and this - // pins why that zero was real -- the arm's lossless branch returns - // before the unit loop. - let dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("fixtures"); - let intrabc = std::fs::read(dir.join("W_intrabc.obu")) - .expect("W_intrabc.obu is missing -- the counter-proof cannot run"); - let proof_before = ( - crate::decode::mu_chunk_compound_units(), - crate::decode::mu_chunk_intra_in_inter_units(), - crate::decode::intra_128_in_inter_mu_chroma_hits(), - ); - let proof_frames = crate::stream::decode_stream(&intrabc) - .expect("W_intrabc.obu no longer decodes") - .len(); - let proof = ( - crate::decode::mu_chunk_compound_units() - proof_before.0, - crate::decode::mu_chunk_intra_in_inter_units() - proof_before.1, - crate::decode::intra_128_in_inter_mu_chroma_hits() - proof_before.2, - ); - assert_eq!(proof_frames, 16, "{NAME}: W_intrabc shown-frame count"); - assert_eq!( - (proof.0, proof.1), - (0, 0), - "{NAME}: W_intrabc now allocates mu-chunk units ({}, {}) -- it cannot be the \ - counter-proof any more", - proof.0, - proof.1 - ); - assert!( - proof.2 > 0, - "{NAME}: W_intrabc no longer reaches the intra-in-inter guard at all \ - (INTRA_128_IN_INTER_MU_CHROMA_HITS delta 0), so its zero allocations prove \ - nothing about the guard-to-allocation gap this gate rests on" - ); - eprintln!( - "{NAME}: counter-proof W_intrabc allocations=({}, {}) with the intra-in-inter guard \ - fired {} time(s)", - proof.0, proof.1, proof.2 - ); - } - - /// lane-av1muchunk422iis: the **intra-in-inter** `side > 64` mu-chunk - /// walk at 128x256 (TWO 128-superblock rows), site 8's second stream. - /// lane-av1muchunk422class measured this stream diverging with the class - /// signature -- V-plane-only diffs, first wrong sample V (row 190, col 36) - /// of shown frame 2 (V index `190 * 64 + 36 = 12196`, ours 147 vs - /// ffmpeg's 146), a byte-identical decode before and after the compound - /// fix, and the SAME `dc_sign_ctx` fork the compound fix targeted, on the - /// TX_32X32 chroma unit of THIS walk. The walk gathered its chroma - /// context with the plain luma `around_mi` (decode.rs:46820), which at - /// ss (1, 0) sums `unit_luma_w / MI` above cells where libaom sums - /// `txb_w_unit` -- twice as many -- flipping the signum whenever the - /// doubled above vote cancels the left one (see the walk's own comment). - /// - /// The fixture is the hunt's `i5_grad256_iis.obu` (sha256 - /// `64794f278eee738dcc59d90dc0c7c4ef2828c5b7c13724760a33be11f224908e`), - /// pinned byte-for-byte. Recipe: same aomenc argv as the 128x128 twin - /// below, source `gradients=size=128x256:...:seed=63:duration=0.24:rate=25, - /// noise=all_seed=63:alls=6:allf=t` (NOT re-encoded by this lane; the - /// bytes are the hunted bytes). - /// - /// Three halves, in order: (a) the site counter moved AND this stream - /// never enters the compound walk; (b) an ORACLE-FREE V-plane pin of - /// shown frame 2 plus the one sample that moved, so the exactness half - /// cannot silently skip; (c) the required ffmpeg compare -- every plane - /// of every shown frame byte-exact -- and the decode-order oracle compare - /// when one is available. - #[test] - fn a_422_muchunk_intra_in_inter_128x256_stream_is_exact_and_reaches_its_unit_walk() { - const NAME: &str = - "a_422_muchunk_intra_in_inter_128x256_stream_is_exact_and_reaches_its_unit_walk"; - const FILE: &str = "422_muchunk_intra_in_inter_128x256.obu"; - const LEN: usize = 667; - const FNV: u64 = 0x2bee_eba3_052b_f9a3; - const MIN_UNITS: usize = 96; - // 6 shown frames; the oracle also emits 1 hidden alt-ref frame. - const SHOWN: usize = 6; - // Shown frame 2's V plane, 4:2:2 at 128x256 -> 64 x 256 chroma. - const F2_V_FNV: u64 = 0xa7ba_8711_9d13_8fe5; - // V (row 190, col 36): the first sample that moved. The pre-fix - // square gather read 147 here, ffmpeg 146. - const FIRST_WRONG_V: usize = 190 * 64 + 36; - const F2_V_AT_FIRST_WRONG: u16 = 146; - let _gate_lock = lock_gate_counters(); - let stream = read_pinned_muchunk_fixture(FILE, LEN, FNV, NAME); - assert_eq!( - obu_stream_shape(&stream), - Some((true, 1, 0, false)), - "{NAME}: {FILE} is not a 4:2:2 (ss 1/0, non-mono) 128-superblock stream" - ); - let before = ( - crate::decode::mu_chunk_compound_units(), - crate::decode::mu_chunk_intra_in_inter_units(), - ); - let shown = crate::stream::decode_stream(&stream) - .unwrap_or_else(|e| panic!("{NAME}: {FILE} no longer decodes cleanly: {e}")); - let frames = shown.len(); - let (compound, intra) = ( - crate::decode::mu_chunk_compound_units() - before.0, - crate::decode::mu_chunk_intra_in_inter_units() - before.1, - ); - assert_eq!(frames, SHOWN, "{NAME}: {FILE} shown-frame count"); - assert!( - intra >= MIN_UNITS, - "{NAME}: {FILE} allocated only {intra} intra-in-inter `side > 64` mu-chunk units \ - (expected >= {MIN_UNITS}) -- the site counter this gate names did not move" - ); - assert_eq!( - compound, 0, - "{NAME}: {FILE} also ran the compound walk ({compound} units) -- the two cells are \ - no longer separated" - ); - // (b) the oracle-free half: the V plane of the first intrinsically - // wrong frame, sample-for-sample, plus the one sample the pre-fix - // gather got wrong. - assert_eq!( - shown[2].v.len(), - 64 * 256, - "{NAME}: {FILE} is no longer 4:2:2 at 128x256 -- the V plane shape moved" - ); - assert_eq!( - shown[2].v[FIRST_WRONG_V], F2_V_AT_FIRST_WRONG, - "{NAME}: {FILE} shown frame 2 V[{FIRST_WRONG_V}] (chroma (190, 36)) is {} -- the \ - pre-fix square gather read 147 here", - shown[2].v[FIRST_WRONG_V] - ); - assert_eq!( - fnv1a64(&shown[2].v.iter().map(|&s| s as u8).collect::>()), - F2_V_FNV, - "{NAME}: {FILE} shown frame 2's V plane moved -- the intra-in-inter mu-chunk walk's \ - 4:2:2 chroma context gather is wrong again (first sample to move is chroma (190, \ - 36), index {FIRST_WRONG_V})" - ); - // (c) the required ffmpeg compare: every plane of every shown frame. - if !have_ffmpeg() { - eprintln!( - "SKIP {NAME}: no ffmpeg -- the 4:2:2 pixel compare this gate exists for did NOT \ - run (set EC_AV1_REQUIRE_FFMPEG=1 to make this a failure)" - ); - return; - } - let ff = ffmpeg_decode_sequence_422(&stream, 128, 256, SHOWN); - assert_eq!(ff.len(), SHOWN, "{NAME}: {FILE} ffmpeg shown-frame count"); - for (i, (got, want)) in shown.iter().zip(&ff).enumerate() { - assert_eq!( - got.y, want.y, - "{NAME}: {FILE} shown frame {i} luma vs ffmpeg" - ); - assert_eq!(got.u, want.u, "{NAME}: {FILE} shown frame {i} U vs ffmpeg"); - assert_eq!(got.v, want.v, "{NAME}: {FILE} shown frame {i} V vs ffmpeg"); - } - if aomdec_available(NAME) { - let (decoded, hidden) = decode_all_frames_vs_oracle(&stream, NAME); - assert_eq!( - decoded, - SHOWN + 1, - "{NAME}: {FILE} decode-order frame count" - ); - eprintln!( - "{NAME}: {FILE} byte-exact vs ffmpeg over {SHOWN} shown frames and vs the \ - decode-order oracle over {decoded} frame(s) ({hidden} hidden), \ - intra_in_inter_units={intra}" - ); - } else { - eprintln!( - "{NAME}: {FILE} byte-exact vs ffmpeg over {SHOWN} shown frames, \ - intra_in_inter_units={intra} -- the decode-order oracle compare above did NOT \ - run (no aomdec)" - ); - } - } - - /// lane-av1muchunkluma: the **compound-arm CONTENT** stream that reaches - /// only the intra-in-inter `side > 64` mu-chunk walk. `aomenc` was driven - /// with the compound arm's own flags (`--enable-masked-comp=1 - /// --enable-onesided-comp=1 --auto-alt-ref=1`), so it *is* the compound - /// hunt's `c3_grad128_comp` -- but its partition search never enters the - /// compound mu-chunk walk (0 `compound/singleref` probe lines, 16 - /// `intra_in_inter` ones), so its ONLY mu-chunk walk is site 8. - /// - /// lane-av1muchunk422class measured this stream diverging on the - /// then-current tree: first wrong sample **Y (62, 6) of shown frame 1** - /// (`62 * 128 + 6 = 7942`, ours 74, ffmpeg 75) and a byte-identical decode - /// before and after the compound DC-sign fix. lane-av1muchunk422iis's - /// intra-in-inter gather fix closed it: the pinned halves below are the - /// exact plane and the exact sample the pre-fix square gather moved. - /// - /// Recipe (byte-reproducible; re-encoded by this lane from the frozen - /// `grad128.y4m`, sha256 `ab8b23137c4efc818884efcf0bb6ccda363bae4b8360f2ca10ca68506cbb777d`, - /// which itself regenerates byte-for-byte): - /// ```text - /// ffmpeg -v error -f lavfi -i "gradients=size=128x128:c0=0xa1128f:\ - /// c1=0xd98c48:c2=0x120601:c3=0x4abfba:seed=63:duration=0.24:rate=25,\ - /// noise=all_seed=63:alls=6:allf=t" -t 0.24 -pix_fmt yuv422p \ - /// -f yuv4mpegpipe - > grad128.y4m - /// aomenc --codec=av1 --profile=2 --input-chroma-subsampling-x=1 \ - /// --input-chroma-subsampling-y=0 --passes=1 --end-usage=q --cq-level=40 \ - /// --cpu-used=0 --threads=1 --row-mt=0 --sb-size=128 \ - /// --min-partition-size=128 --max-partition-size=128 \ - /// --enable-rect-partitions=0 --enable-ab-partitions=0 \ - /// --enable-1to4-partitions=0 --enable-palette=0 --enable-intrabc=0 \ - /// --deltaq-mode=0 --enable-tx-size-search=0 --limit=6 --lag-in-frames=25 \ - /// --auto-alt-ref=1 --enable-global-motion=1 --enable-warped-motion=1 \ - /// --enable-masked-comp=1 --enable-diff-wtd-comp=1 --enable-onesided-comp=1 \ - /// --obu -o c3_grad128_comp.obu grad128.y4m - /// ``` - #[test] - fn a_422_muchunk_iis_128root_grad128_comp_stream_is_exact_and_reaches_its_unit_walk() { - const NAME: &str = - "a_422_muchunk_iis_128root_grad128_comp_stream_is_exact_and_reaches_its_unit_walk"; - const FILE: &str = "422_muchunk_iis_128root_grad128.obu"; - const LEN: usize = 34449; - const FNV: u64 = 0xfc59_a295_38db_577e; - const MIN_UNITS: usize = 16; - const SHOWN: usize = 6; - // The stream carried in frame 1, the first frame the pre-fix gather - // moved; frame 0 is the unaffected control. - const F1_Y_FNV: u64 = 0x1b17_b4c2_4bd3_58d9; - const F0_Y_FNV: u64 = 0x7666_cd9b_dc47_be3f; - // Y (62, 6) of shown frame 1: the first sample that moved. The - // pre-fix square gather read 74 here, ffmpeg 75. - const FIRST_WRONG_Y: usize = 62 * 128 + 6; - const F1_Y_AT_FIRST_WRONG: u16 = 75; - let _gate_lock = lock_gate_counters(); - let stream = read_pinned_muchunk_fixture(FILE, LEN, FNV, NAME); - assert_eq!( - obu_stream_shape(&stream), - Some((true, 1, 0, false)), - "{NAME}: {FILE} is not a 4:2:2 (ss 1/0, non-mono) 128x128-superblock stream" - ); - let before = ( - crate::decode::mu_chunk_compound_units(), - crate::decode::mu_chunk_intra_in_inter_units(), - ); - let shown = crate::stream::decode_stream(&stream) - .unwrap_or_else(|e| panic!("{NAME}: {FILE} no longer decodes cleanly: {e}")); - let frames = shown.len(); - let (compound, intra) = ( - crate::decode::mu_chunk_compound_units() - before.0, - crate::decode::mu_chunk_intra_in_inter_units() - before.1, - ); - assert_eq!(frames, SHOWN, "{NAME}: {FILE} shown-frame count"); - assert!( - intra >= MIN_UNITS, - "{NAME}: {FILE} allocated only {intra} intra-in-inter `side > 64` mu-chunk units \ - (expected >= {MIN_UNITS}) -- the site counter this gate names did not move" - ); - assert_eq!( - compound, 0, - "{NAME}: {FILE} moved the compound-named counter ({compound} units) -- this stream's \ - only mu-chunk walk is the intra-in-inter one and the cells are no longer separated" - ); - // (b) the oracle-free half: shown frame 1 (the first frame the pre-fix - // gather moved) is asserted sample-for-sample on its luma plane, plus - // the single sample that moved first; shown frame 0's luma is the - // unaffected control that fails if the gather is "fixed" past its own - // cell. - assert_eq!( - shown[1].y.len(), - 128 * 128, - "{NAME}: {FILE} is no longer 4:2:2 at 128x128 -- the luma plane shape moved" - ); - assert_eq!( - fnv1a64(&shown[1].y.iter().map(|&s| s as u8).collect::>()), - F1_Y_FNV, - "{NAME}: {FILE} shown frame 1's luma moved -- the intra-in-inter mu-chunk walk's 4:2:2 \ - chroma context gather is wrong again (first sample to move is Y (62, 6), index \ - {FIRST_WRONG_Y})" - ); - assert_eq!( - shown[1].y[FIRST_WRONG_Y], F1_Y_AT_FIRST_WRONG, - "{NAME}: {FILE} shown frame 1 Y[{FIRST_WRONG_Y}] (luma (62, 6)) is {} -- the pre-fix \ - square gather read 74 here", - shown[1].y[FIRST_WRONG_Y] - ); - assert_eq!( - fnv1a64(&shown[0].y.iter().map(|&s| s as u8).collect::>()), - F0_Y_FNV, - "{NAME}: {FILE} shown frame 0's luma moved -- the 4:2:2 routing changed a frame it \ - must not touch" - ); - // (c) the required ffmpeg compare: every plane of every shown frame. - if !have_ffmpeg() { - eprintln!( - "SKIP {NAME}: no ffmpeg -- the 4:2:2 pixel compare this gate exists for did NOT \ - run (set EC_AV1_REQUIRE_FFMPEG=1 to make this a failure)" - ); - return; - } - let ff = ffmpeg_decode_sequence_422(&stream, 128, 128, SHOWN); - assert_eq!(ff.len(), SHOWN, "{NAME}: {FILE} ffmpeg shown-frame count"); - for (i, (got, want)) in shown.iter().zip(&ff).enumerate() { - assert_eq!( - got.y, want.y, - "{NAME}: {FILE} shown frame {i} luma vs ffmpeg" - ); - assert_eq!(got.u, want.u, "{NAME}: {FILE} shown frame {i} U vs ffmpeg"); - assert_eq!(got.v, want.v, "{NAME}: {FILE} shown frame {i} V vs ffmpeg"); - } - if aomdec_available(NAME) { - let (decoded, hidden) = decode_all_frames_vs_oracle(&stream, NAME); - assert_eq!( - decoded, - SHOWN + 1, - "{NAME}: {FILE} decode-order frame count (6 shown + the hidden alt-ref)" - ); - eprintln!( - "{NAME}: {FILE} byte-exact vs ffmpeg over {SHOWN} shown frames and vs the \ - decode-order oracle over {decoded} frame(s) ({hidden} hidden), \ - compound_units={compound} intra_in_inter_units={intra}" - ); - } else { - eprintln!( - "{NAME}: {FILE} byte-exact vs ffmpeg over {SHOWN} shown frames, \ - compound_units={compound} intra_in_inter_units={intra} -- the decode-order \ - oracle compare above did NOT run (no aomdec)" - ); - } - } - - /// lane-av1muchunkluma: the 128x256 twin of the gate above -- the compound - /// hunt's `c4_grad256_comp`. Unlike c3 this stream reaches BOTH `side > 64` - /// mu-chunk walks (16 `intra_in_inter` probe lines, 24 `compound/singleref` - /// ones with `compound=false`, i.e. the single-reference twin), yet - /// lane-av1muchunk422class measured it diverging luma-first (first wrong - /// sample **Y (126, 3) of shown frame 1**, `126 * 128 + 3 = 16131`, ours - /// 94, ffmpeg 93). This lane re-measured it: still diverging on the - /// pre-iis-gather tree, byte-exact on current `main`, so the - /// intra-in-inter gather is what closed it -- its `MU_CHUNK_COMPOUND_UNITS` - /// delta stays 0 (the counter names the compound arm only), which is why - /// the gate's site half asserts the intra-in-inter counter. - /// - /// Recipe: same `aomenc` argv as the 128x128 gate above with the 128x256 - /// source (`gradients=size=128x256`, the frozen `grad256.y4m`, sha256 - /// `03c7fab7a6abc4e6764836cd2d35e76489438ecdba4ca1167fcd868250c0464c`, - /// which regenerates byte-for-byte). - #[test] - fn a_422_muchunk_iis_128x256_grad256_comp_stream_is_exact_and_reaches_its_unit_walk() { - const NAME: &str = - "a_422_muchunk_iis_128x256_grad256_comp_stream_is_exact_and_reaches_its_unit_walk"; - const FILE: &str = "422_muchunk_iis_128x256_grad256.obu"; - const LEN: usize = 68925; - const FNV: u64 = 0x65b8_d4dd_3806_7e09; - const MIN_UNITS: usize = 16; - const SHOWN: usize = 6; - const F1_Y_FNV: u64 = 0x75e6_e790_47a8_9882; - const F0_Y_FNV: u64 = 0x1265_8460_c00e_a10f; - // Y (126, 3) of shown frame 1: the first sample that moved. The - // pre-fix square gather read 94 here, ffmpeg 93. - const FIRST_WRONG_Y: usize = 126 * 128 + 3; - const F1_Y_AT_FIRST_WRONG: u16 = 93; - let _gate_lock = lock_gate_counters(); - let stream = read_pinned_muchunk_fixture(FILE, LEN, FNV, NAME); - assert_eq!( - obu_stream_shape(&stream), - Some((true, 1, 0, false)), - "{NAME}: {FILE} is not a 4:2:2 (ss 1/0, non-mono) 128x128-superblock stream" - ); - let before = ( - crate::decode::mu_chunk_compound_units(), - crate::decode::mu_chunk_intra_in_inter_units(), - ); - let shown = crate::stream::decode_stream(&stream) - .unwrap_or_else(|e| panic!("{NAME}: {FILE} no longer decodes cleanly: {e}")); - let frames = shown.len(); - let (compound, intra) = ( - crate::decode::mu_chunk_compound_units() - before.0, - crate::decode::mu_chunk_intra_in_inter_units() - before.1, - ); - assert_eq!(frames, SHOWN, "{NAME}: {FILE} shown-frame count"); - assert!( - intra >= MIN_UNITS, - "{NAME}: {FILE} allocated only {intra} intra-in-inter `side > 64` mu-chunk units \ - (expected >= {MIN_UNITS}) -- the site counter this gate names did not move" - ); - assert_eq!( - compound, 0, - "{NAME}: {FILE} moved the compound-named counter ({compound} units) -- the fixture's \ - `compound/singleref` hits are its single-reference twin, which must not be counted \ - here" - ); - assert_eq!( - shown[1].y.len(), - 128 * 256, - "{NAME}: {FILE} is no longer 4:2:2 at 128x256 -- the luma plane shape moved" - ); - assert_eq!( - fnv1a64(&shown[1].y.iter().map(|&s| s as u8).collect::>()), - F1_Y_FNV, - "{NAME}: {FILE} shown frame 1's luma moved -- the intra-in-inter mu-chunk walk's 4:2:2 \ - chroma context gather is wrong again (first sample to move is Y (126, 3), index \ - {FIRST_WRONG_Y})" - ); - assert_eq!( - shown[1].y[FIRST_WRONG_Y], F1_Y_AT_FIRST_WRONG, - "{NAME}: {FILE} shown frame 1 Y[{FIRST_WRONG_Y}] (luma (126, 3)) is {} -- the pre-fix \ - square gather read 94 here", - shown[1].y[FIRST_WRONG_Y] - ); - assert_eq!( - fnv1a64(&shown[0].y.iter().map(|&s| s as u8).collect::>()), - F0_Y_FNV, - "{NAME}: {FILE} shown frame 0's luma moved -- the 4:2:2 routing changed a frame it \ - must not touch" - ); - if !have_ffmpeg() { - eprintln!( - "SKIP {NAME}: no ffmpeg -- the 4:2:2 pixel compare this gate exists for did NOT \ - run (set EC_AV1_REQUIRE_FFMPEG=1 to make this a failure)" - ); - return; - } - let ff = ffmpeg_decode_sequence_422(&stream, 128, 256, SHOWN); - assert_eq!(ff.len(), SHOWN, "{NAME}: {FILE} ffmpeg shown-frame count"); - for (i, (got, want)) in shown.iter().zip(&ff).enumerate() { - assert_eq!( - got.y, want.y, - "{NAME}: {FILE} shown frame {i} luma vs ffmpeg" - ); - assert_eq!(got.u, want.u, "{NAME}: {FILE} shown frame {i} U vs ffmpeg"); - assert_eq!(got.v, want.v, "{NAME}: {FILE} shown frame {i} V vs ffmpeg"); - } - if aomdec_available(NAME) { - let (decoded, hidden) = decode_all_frames_vs_oracle(&stream, NAME); - assert_eq!( - decoded, - SHOWN + 1, - "{NAME}: {FILE} decode-order frame count (6 shown + the hidden alt-ref)" - ); - eprintln!( - "{NAME}: {FILE} byte-exact vs ffmpeg over {SHOWN} shown frames and vs the \ - decode-order oracle over {decoded} frame(s) ({hidden} hidden), \ - compound_units={compound} intra_in_inter_units={intra}" - ); - } else { - eprintln!( - "{NAME}: {FILE} byte-exact vs ffmpeg over {SHOWN} shown frames, \ - compound_units={compound} intra_in_inter_units={intra} -- the decode-order \ - oracle compare above did NOT run (no aomdec)" - ); - } - } - - /// lane-sbpart r2: a real `aomenc` stream whose superblock-level - /// partition decision is genuinely HORZ/VERT (not NONE/SPLIT) must - /// decode pixel-exact through [`crate::decode::decode_block_rect64`] -- - /// `sb_rect_hits() > 0` is a HARD assert (this round's rule: a removed - /// refusal needs a firing gate in the same commit, not a green suite - /// that never took the new path). Recipe = the charter's own, verified - /// live by r1: `--min/max-partition-size=32/64` keeps the RD search - /// from ever recursing below 32x32, so every SB-level decision is - /// genuinely NONE/SPLIT/HORZ/VERT; a `gradients` source blended with - /// `testsrc2` (lavfi `blend=all_mode=average`) keeps the content from - /// being flat enough that the search stops at NONE every time. - #[test] - fn a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact() { - const NAME: &str = - "a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height, frame_count) = (192usize, 128usize, 1usize); - let mut named_refusals = 0u32; - let mut matched = 0u32; - let n_attempts: u32 = std::env::var("EC_SBPART_GATE_ATTEMPTS") - .ok() - .and_then(|s| s.parse().ok()) - .unwrap_or(40); - for attempt in 0..n_attempts { - let seed = 42 + attempt; - let duration = frame_count as f64 / 25.0; - let source = - gradients_source(seed, width, height, &format!("duration={duration}:rate=25")); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-pix_fmt", - "yuv420p", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=45", - "--cpu-used=0", - "--threads=1", - "--row-mt=0", - "--sb-size=64", - "--enable-rect-partitions=1", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--min-partition-size=32", - "--max-partition-size=64", - "--enable-restoration=0", - "--enable-palette=0", - "--deltaq-mode=0", - "--enable-cdef=0", - "--enable-filter-intra=0", - "--enable-cfl-intra=0", - "--enable-intrabc=0", - "--enable-tx-size-search=0", - "--obu", - "-o", - "-", - "-", - ]; - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let frames = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME} failed outright, not a named refusal (seed {seed}): {msg}" - ); - // r5: the four SB-level AB arms (`partition_w64` 4-7) - // decode since this round, so the only partition refusal - // left at 64x64 is the 1:4 pair (values 8/9, four - // 64x16/16x64 strips, whose luma TX_64X16 this decoder - // has no transform for); the refusals this loop actually - // counts on these fixtures are the pre-existing - // screen-content-palette strip one. Every refusal is - // named, so a genuine decode failure still fails the - // assert above rather than skipping. - named_refusals += 1; - eprintln!("seed {seed} refusal: {msg}"); - continue; - } - Ok(frames) => frames, - }; - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count); - assert_eq!(frames.len(), frame_count); - let mismatched = frames - .iter() - .zip(&ffmpeg_frames) - .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); - if mismatched - && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") { - std::fs::write(&path, &stream).expect("writing pinned stream"); - eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}"); - } - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!( - got.y, want.y, - "{NAME} frame {i} luma vs ffmpeg (seed {seed})" - ); - assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})"); - assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})"); - } - matched += 1; - } - assert!( - matched > 0, - "{NAME}: every attempt refused; the gate never decoded a stream" - ); - assert!( - crate::decode::sb_rect_hits() > 0, - "{NAME}: zero superblock-level HORZ/VERT blocks fired ({matched} matches, \ - {named_refusals} refusals out of {n_attempts}) -- gate proved nothing this run" - ); - eprintln!( - "{NAME}: {named_refusals} named refusals, {matched} pixel-exact matches out of \ - {n_attempts}, sb_rect_hits={}", - crate::decode::sb_rect_hits() - ); - } - - /// lane-golomb r2 gate: a 32x32-level block that STRADDLES the frame edge - /// and whose partition is the gathered edge bit's `PARTITION_HORZ` (bottom - /// edge) / `PARTITION_VERT` (right edge). Since r1 that bit can name - /// HORZ/VERT instead of always inferring SPLIT, so the second 32x16/16x32 - /// half is out of frame and must NOT be decoded (libaom `decode_partition`: - /// `case PARTITION_HORZ: decode_block(top); if (has_rows) decode_block(bottom)`). - /// The AB and 1:4 arms need no such guard: at an edge libaom's - /// `ec_read_partition_impl` can only yield HORZ/VERT/SPLIT, so those arms - /// are unreachable there. - /// - /// Geometry: 192x80 (mi_rows=20 -- the second SB row is 16 px tall, so its - /// 32-level blocks at y=64 have `has_rows32 == false`) and 80x192 for the - /// right edge. Natural content (`testsrc2`); `smptebars`-style screen - /// content trips the palette/screen-content refusal before the edge is - /// reached. cq sweep, 8-bit and 10-bit, plus a 5-frame inter arm. - /// Counters are sampled per attempt and summed only over attempts that - /// decoded AND pixel-compared (class `counter-from-refused-stream`). - #[test] - fn a_real_aomenc_stream_with_a_32x32_frame_edge_rect_partition_decodes_pixel_exact() { - edge32_gate( - "a_real_aomenc_stream_with_a_32x32_frame_edge_rect_partition_decodes_pixel_exact", - false, - ); - } - - /// lane-golomb r2 OPEN DEFECT, pinned as a runnable test: with the 16-px - /// straddling band left FLAT the encoder answers the 32-level edge bit - /// with HORZ (`edge32=[2, 0, 2, 0]` on 192x80 cq40 8-bit), the guard added - /// this round keeps the stream in entropy sync -- every pixel outside the - /// two edge strips matches ffmpeg -- but the strips themselves - /// reconstruct wrong: `plane Y: 1081 pixels differ, first at row 62 col - /// 128`, diffs confined to rows 62..79 over ~64 columns (exactly the two - /// 32x16 strips plus the deblock bleed above them). That is a - /// reconstruction defect inside the strip (prediction/availability), not - /// the partition guard. Un-ignored 2026-09-04: that reconstruction defect is gone and the two edge strips decode exactly. - #[test] - fn a_32x32_frame_edge_rect_partition_with_a_flat_band_decodes_pixel_exact() { - edge32_gate( - "a_32x32_frame_edge_rect_partition_with_a_flat_band_decodes_pixel_exact", - true, - ); - } - - /// lane-golomb r9 OPEN DEFECT, pinned as a runnable test: a frame whose - /// height (192x68) or width (68x192) is not a multiple of 8 leaves a 4-px - /// straddling band inside the mi-rounded plane, and every INTER frame's - /// output is +-1 wrong across that band and the columns/rows next to it - /// (`68x192 cq35 8-bit: frame 1 plane Y: 145 pixels differ, first at row 0 - /// col 64`, mass in columns 64..67). r9 bisected it stage by stage against - /// the instrumented aomdec on that exact stream: - /// * `EC_AV1_PREFILT_DUMP` frame 1 is BYTE-IDENTICAL over the cropped - /// 68 columns -- reconstruction and inter prediction are exact, so the - /// charter's "MC reads past the crop" hypothesis is refuted a second time. - /// * `EC_AV1_POSTDEBLOCK_DUMP` with `EC_AV1_DEBUG_SKIP_CDEF=1` also matches - /// aomdec's own post-deblock dump (which is 72 columns wide, i.e. it - /// exposes the straddling band) -- the deblock, including its - /// `frame_width` clip, is correct. - /// * The divergence therefore enters in CDEF, at the last 8x8 CDEF block - /// column/row, which is the one that straddles the crop edge. - /// lane-cdef r2: CLOSED, and un-ignored. r1 rooted the luma half in - /// `apply_cdef`'s direction search, which clamped at the CROPPED frame - /// edge while libaom runs `cdef_find_dir` over `cdef_prepare_fb`'s buffer - /// -- whose columns/rows past the MI-ROUNDED extent (`hsize = nhb << - /// mi_wide_l2`, `cdef.c:164-167`, and the `frame_boundary[RIGHT]` - /// CDEF_VERY_LARGE fill at `cdef.c:249-256`) are CDEF_VERY_LARGE, not the - /// last real sample. The chroma half was lane-golomb r8's loop-restoration - /// plane size (LR is the one post-decode filter sized by the CROP, not the - /// mi grid) plus its reference-size fix; merging both branches takes all - /// four arms to 0 differing pixels on Y, U and V. - /// - /// Arms: 192x68 and 68x192 (a 4-px straddling band on one axis), 5 frames, - /// 8-bit and 10-bit, plus a `--tile-columns=1` twin of each (COMMON's - /// neighbour-map rule -- the skip band CDEF reads is a per-mi side band). - /// RE-MEASURED lane-t900 r15 on the merged tip: all 64 attempts (8 arms x - /// 8 cq levels, single- and multi-tile alike) decode pixel-exact with ZERO - /// named refusals -- on 2026-09-02 all 32 multi-tile attempts still refused - /// by name, so that half compared nothing (class - /// `counter-from-refused-stream`). `compared_multi_tile` is asserted below - /// so the multi-tile twins can never silently go back to comparing - /// nothing. - /// Hard-asserts `decode::cdef_straddle_units()` grew: a FILTERED 8x8 CDEF - /// unit whose extent crosses the crop edge is the only shape for which - /// clamping and padding differ, so a zero delta would make these arms - /// vacuous for this defect. - #[test] - fn a_frame_edge_straddling_band_decodes_pixel_exact() { - edge32_gate("a_frame_edge_straddling_band_decodes_pixel_exact", false); - } - - /// lane-sqchroma r1 gate: a plain SQUARE-partition intra key frame with - /// REAL chroma (no `hue=s=0` guard) and aomenc's tx-size search left at - /// its own DEFAULT (on) -- the combination the user's films hit - /// everywhere and that no gate in this file covered: every older recipe - /// pins `--enable-tx-size-search=0`, and the one that does not - /// (`a_real_aomenc_stream_with_a_split_transform_horz_vert_strip_decodes_pixel_exact`) - /// desaturates its fixture. With the search on, RD gives a square block a - /// luma transform smaller than its own side while chroma keeps the - /// block's single `side/2` transform and its own `uv_mode`-derived - /// `tx_type` -- the pair [`crate::decode::sq_chroma_tx_hits`] counts and - /// this gate hard-asserts, so a stream whose split-transform blocks all - /// landed on `DC_PRED` chroma cannot pass for free. - /// - /// Sweeps seeds 8-bit and finishes with one 10-bit stream of the same - /// recipe (his films are `yuv420p10le`), whose sequence header's - /// `bit_depth` is asserted before any pixel is compared. Only a missing - /// tool SKIPs: a decode error that is not a named refusal, and every - /// pixel mismatch, FAIL. - #[test] - fn a_real_aomenc_intra_stream_with_tx_size_search_and_chroma_decodes_pixel_exact() { - const NAME: &str = - "a_real_aomenc_intra_stream_with_tx_size_search_and_chroma_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height) = (192usize, 128usize); - // NOTE: no `--enable-tx-size-search=0` (the point of this gate), and - // no chroma filter on the fixture (the other point). Square - // partitions only: rect/AB/1to4 all off. - let base_args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cpu-used=0", - "--threads=1", - "--row-mt=0", - "--sb-size=64", - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--min-partition-size=16", - "--max-partition-size=32", - "--enable-restoration=0", - "--enable-palette=0", - "--deltaq-mode=0", - "--enable-intrabc=0", - "--limit=1", - ]; - let encode = |y4m: &[u8], extra: &[&str]| -> Vec { - let mut args = base_args.clone(); - args.extend_from_slice(extra); - args.extend_from_slice(&["--obu", "-o", "-", "-"]); - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), y4m); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - assert!( - !out.stdout.is_empty(), - "{NAME}: aomenc wrote an empty stream" - ); - out.stdout - }; - let render = |source: &str, pix_fmt: &str| -> Vec { - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - source, - "-t", - "0.04", - "-pix_fmt", - pix_fmt, - "-strict", - "-1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - y4m.stdout - }; - let mut named_refusals = 0u32; - let mut matched = 0u32; - // Hits counted ONLY over attempts that decoded AND pixel-compared: - // a stream that later refuses must not lend its firings to the - // assertion below (class refusal-hides-a-defect). - let mut firing = 0usize; - let n_attempts: u32 = std::env::var("EC_SQCHROMA_GATE_ATTEMPTS") - .ok() - .and_then(|s| s.parse().ok()) - .unwrap_or(10); - for attempt in 0..n_attempts { - let seed = 42 + attempt; - // Two quantisers per seed: the coarse one keeps most blocks on - // one transform, the fine one is what actually splits them. - let cq = if attempt % 2 == 0 { - "--cq-level=20" - } else { - "--cq-level=40" - }; - let y4m = render( - &gradients_source(seed, width, height, "duration=0.04:rate=25"), - "yuv420p", - ); - let stream = encode(&y4m, &[cq]); - let before = crate::decode::sq_chroma_tx_hits(); - let frames = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME} failed outright, not a named refusal (seed {seed}): {msg}" - ); - named_refusals += 1; - continue; - } - Ok(frames) => frames, - }; - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1); - assert_eq!(frames.len(), 1, "{NAME}: expected one frame (seed {seed})"); - assert_eq!( - frames[0].y, ffmpeg_frames[0].y, - "{NAME} luma vs ffmpeg (seed {seed})" - ); - assert_eq!( - frames[0].u, ffmpeg_frames[0].u, - "{NAME} U vs ffmpeg (seed {seed})" - ); - assert_eq!( - frames[0].v, ffmpeg_frames[0].v, - "{NAME} V vs ffmpeg (seed {seed})" - ); - firing += crate::decode::sq_chroma_tx_hits() - before; - matched += 1; - } - // Same recipe, 10-bit: his two films are both yuv420p10le, so the - // square+tx-search+chroma claim is only worth anything if it holds - // at their bit depth too. - let y4m10 = render( - &gradients_source(42, width, height, "duration=0.04:rate=25"), - "yuv420p10le", - ); - let stream10 = encode( - &y4m10, - &["--cq-level=20", "--input-bit-depth=10", "--bit-depth=10"], - ); - let mut probe = Av1Parser::new(); - let mut pos = 0usize; - while pos < stream10.len() && probe.sequence_header().is_none() { - let obu = probe.parse_obu(&stream10[pos..]).unwrap(); - pos += obu.total_size; - } - assert_eq!( - probe - .sequence_header() - .expect("stream has a sequence header OBU") - .color_config - .bit_depth, - 10, - "{NAME}: aomenc did not actually write a 10-bit sequence header" - ); - let before10 = crate::decode::sq_chroma_tx_hits(); - let frames10 = match decode_stream(&stream10) { - Ok(frames) => frames, - Err(e) => panic!("{NAME}: decode_stream refused the 10-bit stream: {e}"), - }; - let ffmpeg10 = ffmpeg_decode_sequence_10bit(&stream10, width, height, 1); - assert_eq!( - frames10[0].y, ffmpeg10[0].y, - "{NAME} luma vs ffmpeg (10-bit)" - ); - assert_eq!(frames10[0].u, ffmpeg10[0].u, "{NAME} U vs ffmpeg (10-bit)"); - assert_eq!(frames10[0].v, ffmpeg10[0].v, "{NAME} V vs ffmpeg (10-bit)"); - let firing10 = crate::decode::sq_chroma_tx_hits() - before10; - firing += firing10; - matched += 1; - assert!( - matched > 1, - "{NAME}: every 8-bit attempt refused; the gate decoded only the 10-bit stream" - ); - assert!( - firing > 0, - "{NAME}: zero square blocks split their luma transform under a non-DC chroma mode \ - ({matched} matches, {named_refusals} refusals) -- gate proved nothing this run" - ); - eprintln!( - "{NAME}: {matched} pixel-exact decodes ({named_refusals} named refusals out of \ - {n_attempts} 8-bit attempts), split-tx-with-chroma blocks: {firing} \ - (10-bit stream: {firing10})" - ); - } - - /// lane-rectsplit r1 gate (a): a real `aomenc` key frame whose 32x32 - /// quadrants split HORZ/VERT into true 32x16/16x32 strips, with the - /// tx-size search left at aomenc's own default (ON) -- every sibling - /// recipe in this file pins `--enable-tx-size-search=0`, which is exactly - /// why the split-transform strip was never exercised. RD is then free to - /// give a strip a transform smaller than its own size, the case - /// [`crate::decode::decode_block_rect`] refused by name ("a HORZ/VERT - /// intra strip with a split transform (per-unit rect prediction is not - /// ported)") until this round ported the per-transform-unit predict-and- - /// reconstruct loop. Hard-asserts a nonzero `rect_split_tx_hits()` delta: - /// without it a stream that resolved every `tx_depth` to 0 would - /// pixel-match by construction and prove nothing. A decode error that is - /// not a named refusal, and any pixel mismatch, FAIL -- only a missing - /// tool skips. - #[test] - fn a_real_aomenc_stream_with_a_split_transform_horz_vert_strip_decodes_pixel_exact() { - const NAME: &str = - "a_real_aomenc_stream_with_a_split_transform_horz_vert_strip_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height) = (192usize, 128usize); - let before = crate::decode::rect_split_tx_hits(); - let mut named_refusals = 0u32; - let mut matched = 0u32; - // lane-rectsplit r2 (verifier finding): the feature counter is - // sampled PER ATTEMPT and folded in only after that attempt was - // decoded AND pixel-compared. One delta across the whole sweep - // counted strips decoded by attempts that went on to hit a named - // refusal, so the gate could pass with every COMPARED stream - // containing none of the feature at all. - let mut compared_hits = 0usize; - let mut split_so_far = 0usize; - // Bounded sweep: see this gate's own doc for the seed-77 residue and - // why extending it is a diagnosis knob, not a pass/fail one. - let n_attempts: u32 = std::env::var("EC_RECTSPLIT_GATE_ATTEMPTS") - .ok() - .and_then(|s| s.parse().ok()) - .unwrap_or(20); - for attempt in 0..n_attempts { - let seed = 42 + attempt; - let source = gradients_source(seed, width, height, "duration=0.04:rate=25"); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - // REAL chroma (lane-sqchroma r1 dropped the `hue=s=0` - // guard this recipe carried): the "PRE-EXISTING square-path - // chroma defect" that guard named does not reproduce at - // HEAD -- seeds 42..61, cq 12/20/32/45, plus testsrc2 and - // mandelbrot, all decode pixel-exact with - // `--enable-rect-partitions=0`, and this gate is green with - // the filter gone. Its own gate is - // `a_real_aomenc_intra_stream_with_tx_size_search_and_chroma_decodes_pixel_exact`. - "-pix_fmt", - "yuv420p", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - // NOTE: no `--enable-tx-size-search=0` here -- leaving aomenc's - // own default (search ON) is the entire point of this gate. - let args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=45", - "--cpu-used=0", - "--threads=1", - "--row-mt=0", - "--sb-size=64", - "--enable-rect-partitions=1", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--min-partition-size=16", - "--max-partition-size=32", - "--enable-restoration=0", - "--enable-palette=0", - "--deltaq-mode=0", - "--enable-cdef=0", - "--enable-filter-intra=0", - "--enable-cfl-intra=0", - "--enable-intrabc=0", - "--obu", - "-o", - "-", - "-", - ]; - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - assert!( - !stream.is_empty(), - "{NAME}: aomenc wrote an empty stream (seed {seed})" - ); - let attempt_before = crate::decode::rect_split_tx_hits(); - let frames = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME} failed outright, not a named refusal (seed {seed}): {msg}" - ); - named_refusals += 1; - continue; - } - Ok(frames) => frames, - }; - let after = crate::decode::rect_split_tx_hits(); - eprintln!( - "{NAME}: seed {seed} decoded, split-tx strips this stream: {}", - after - before - split_so_far - ); - split_so_far = after - before; - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1); - assert_eq!(frames.len(), 1, "{NAME}: expected one frame (seed {seed})"); - if let Some(i) = frames[0] - .y - .iter() - .zip(&ffmpeg_frames[0].y) - .position(|(a, b)| a != b) - { - let diffs: Vec = frames[0] - .y - .iter() - .zip(&ffmpeg_frames[0].y) - .enumerate() - .filter(|(_, (a, b))| a != b) - .map(|(j, _)| j) - .collect(); - let (x0, x1) = ( - diffs.iter().map(|j| j % width).min().unwrap(), - diffs.iter().map(|j| j % width).max().unwrap(), - ); - let (y0, y1) = (diffs[0] / width, diffs[diffs.len() - 1] / width); - eprintln!( - "{NAME}: seed {seed} first luma mismatch at ({}, {}) ours={} ffmpeg={} \ - -- {} mismatching samples, bbox x {x0}..={x1} y {y0}..={y1}", - i % width, - i / width, - frames[0].y[i], - ffmpeg_frames[0].y[i], - diffs.len(), - ); - } - assert_eq!( - frames[0].y, ffmpeg_frames[0].y, - "{NAME}: luma vs ffmpeg (seed {seed})" - ); - assert_eq!( - frames[0].u, ffmpeg_frames[0].u, - "{NAME}: U vs ffmpeg (seed {seed})" - ); - assert_eq!( - frames[0].v, ffmpeg_frames[0].v, - "{NAME}: V vs ffmpeg (seed {seed})" - ); - compared_hits += crate::decode::rect_split_tx_hits() - attempt_before; - matched += 1; - } - let split_hits = compared_hits; - assert!( - matched > 0, - "{NAME}: every attempt refused ({named_refusals} named refusals) -- gate decoded nothing" - ); - assert!( - split_hits > 0, - "{NAME}: zero HORZ/VERT strips resolved a split transform ({matched} pixel-exact \ - matches, {named_refusals} refusals out of {n_attempts}) -- gate proved nothing \ - this run" - ); - eprintln!( - "{NAME}: {matched} pixel-exact matches, {named_refusals} named refusals, \ - rect_split_tx_hits delta={split_hits} out of {n_attempts} attempts" - ); - } - - /// lane-rect1d r1 (copied from lane-rectclass r1): the class-correctness measurement for every - /// RECTANGULAR transform unit this decoder reads. [`crate::decode::read_coeffs_rect`] - /// handles `TxClass::TwoD` only -- it refuses by name both a coded - /// `tx_type` symbol and a non-2D default -- so the open question a - /// verifier raised was whether a real encoder ever puts a - /// `V_DCT`/`H_DCT` (`TX_CLASS_HORIZ`/`VERT`) type on a rect TU that - /// reaches this reader. The recipe deliberately maximises the chance: - /// `--enable-flip-idtx=1` (the flip/identity/1D types are exactly what - /// `EXT_TX_SET_DTT4_IDTX_1DDCT` and the wider inter sets add), - /// `--enable-tx-size-search=1`, rect partitions on, small minimum - /// partition size, both bit depths. Every successful decode is - /// pixel-compared; the rect-TU counter is folded in PER ATTEMPT and only - /// after that attempt compared (class `counter-from-refused-stream`), and - /// the class-1 refusal counter is summed over EVERY attempt including the - /// refused ones -- a refused attempt is exactly where a 1D class on a - /// rect TU would show up. - /// - /// lane-rect1d: on THIS tree `read_coeffs_rect` no longer refuses a 1D - /// class -- lane-tx4x8 gave it the mrow/mcol scan and the class-aware - /// base/br contexts -- so the live pins are `compared_class1 > 0` (the - /// flag arrived and 1D types were coded) plus the pixel compare itself. - #[test] - fn a_real_aomenc_stream_with_a_1d_tx_class_on_a_rect_transform_decodes_pixel_exact() { - const NAME: &str = - "a_real_aomenc_stream_with_a_1d_tx_class_on_a_rect_transform_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height) = (192usize, 128usize); - let mut named_refusals = 0u32; - let mut matched = 0u32; - let mut matched_10bit = 0u32; - let mut compared_rect_tus = 0usize; - let mut compared_rect_parts = 0usize; - let mut compared_tx_depths = 0usize; - let mut compared_class1 = 0usize; - let mut compared_rect_class1 = 0usize; - let n_attempts: u32 = std::env::var("EC_RECTCLASS_GATE_ATTEMPTS") - .ok() - .and_then(|s| s.parse().ok()) - .unwrap_or(12); - // Both bit depths in one sweep: his two films are yuv420p10le, and a - // class claim that only holds at 8 bits is worth nothing to them. - for attempt in 0..n_attempts { - let seed = 42 + attempt / 2; - let ten_bit = attempt % 2 == 1; - let pix_fmt = if ten_bit { "yuv420p10le" } else { "yuv420p" }; - // Content + quantiser sweep: the 1D (`V_DCT`/`H_DCT`) types RD can - // only pick on strongly one-directional detail, and only when the - // quantiser leaves that detail in the residual -- smooth gradients - // at cq 45 produced exactly zero of them (measured this round), - // which would have made the `--enable-flip-idtx=1` arrival assert - // fail rather than the gate pass vacuously. - let period = [4u32, 6, 8, 12, 16][(attempt as usize / 2) % 5]; - let source = format!("testsrc2=size={width}x{height}:rate=25"); - let filter = format!( - "geq=lum='128+80*sin(2*PI*Y/{period})':cb='128+60*sin(2*PI*X/{period})':cr=128,\ - noise=alls=6:allf=t" - ); - let cq = if attempt % 4 < 2 { - "--cq-level=20" - } else { - "--cq-level=40" - }; - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - // `-strict -1`: y4m calls 10-bit an unofficial pixel - // format and refuses to write the header otherwise (no-op - // at 8 bit). - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-vf", - &filter, - "-t", - "0.04", - "-pix_fmt", - pix_fmt, - "-strict", - "-1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - // aomenc keeps the LAST occurrence of a repeated `--enable-*` - // flag (measured 2026-09-02 by md5 of four orderings), so this - // lane's overrides come AFTER the base recipe. They are also - // proven to have ARRIVED rather than assumed: the asserts below - // pin a nonzero rect-partition, tx-depth and 1D-tx-class counter - // on pixel-compared attempts, one per override. - let mut args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - cq, - "--cpu-used=0", - "--threads=1", - "--row-mt=0", - "--sb-size=64", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-restoration=0", - "--enable-palette=0", - "--deltaq-mode=0", - "--enable-cdef=0", - "--enable-filter-intra=0", - "--enable-cfl-intra=0", - "--enable-intrabc=0", - ]; - if ten_bit { - args.extend_from_slice(&["--input-bit-depth=10", "--bit-depth=10"]); - } - args.extend_from_slice(&[ - "--enable-rect-partitions=1", - "--enable-tx-size-search=1", - "--enable-flip-idtx=1", - // Without this aomenc's reduced tx set narrows every block to - // DCT_DCT/IDTX and no 1D type can be coded at all -- the flag - // that actually gates the class, as the arrival assert below - // proved by staying at 0 without it. - "--reduced-tx-type-set=0", - "--min-partition-size=8", - "--max-partition-size=32", - "--obu", - "-o", - "-", - "-", - ]); - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - assert!( - !stream.is_empty(), - "{NAME}: aomenc wrote an empty stream (seed {seed})" - ); - if ten_bit { - let mut probe = Av1Parser::new(); - let mut pos = 0usize; - while pos < stream.len() && probe.sequence_header().is_none() { - let obu = probe.parse_obu(&stream[pos..]).unwrap(); - pos += obu.total_size; - } - assert_eq!( - probe - .sequence_header() - .expect("stream has a sequence header OBU") - .color_config - .bit_depth, - 10, - "{NAME}: aomenc did not actually write a 10-bit sequence header" - ); - } - let attempt_before = crate::decode::rect_coeff_tu_hits(); - let rect_before = crate::decode::rect_partition_hits(); - let depth_before = crate::decode::tx_depth_hits(); - let class1_before = crate::decode::tx_class1_hits(); - let rect_class1_before = crate::decode::rect_class1_hits(); - let frames = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME} failed outright, not a named refusal (seed {seed}, 10bit \ - {ten_bit}): {msg}" - ); - named_refusals += 1; - continue; - } - Ok(frames) => frames, - }; - let ffmpeg_frames = if ten_bit { - ffmpeg_decode_sequence_10bit(&stream, width, height, 1) - } else { - ffmpeg_decode_sequence(&stream, width, height, 1) - }; - assert_eq!(frames.len(), 1, "{NAME}: expected one frame (seed {seed})"); - assert_eq!( - frames[0].y, ffmpeg_frames[0].y, - "{NAME}: luma vs ffmpeg (seed {seed}, 10bit {ten_bit})" - ); - assert_eq!( - frames[0].u, ffmpeg_frames[0].u, - "{NAME}: U vs ffmpeg (seed {seed}, 10bit {ten_bit})" - ); - assert_eq!( - frames[0].v, ffmpeg_frames[0].v, - "{NAME}: V vs ffmpeg (seed {seed}, 10bit {ten_bit})" - ); - compared_rect_tus += crate::decode::rect_coeff_tu_hits() - attempt_before; - compared_rect_parts += crate::decode::rect_partition_hits() - rect_before; - compared_tx_depths += crate::decode::tx_depth_hits() - depth_before; - compared_class1 += crate::decode::tx_class1_hits() - class1_before; - compared_rect_class1 += crate::decode::rect_class1_hits() - rect_class1_before; - matched += 1; - matched_10bit += u32::from(ten_bit); - } - assert!( - matched > 0, - "{NAME}: every attempt refused ({named_refusals} named refusals) -- gate decoded \ - nothing" - ); - assert!( - matched_10bit > 0, - "{NAME}: every 10-bit attempt refused -- his films are yuv420p10le, so a gate that \ - only compared 8-bit streams proves nothing for them" - ); - assert!( - compared_rect_tus > 0, - "{NAME}: no pixel-exact attempt coded a single rectangular transform unit \ - ({matched} matches, {named_refusals} refusals out of {n_attempts}) -- the gate \ - measured nothing about rect coefficient reading" - ); - // FLAG ARRIVAL, one assert per override (a flag whose counter stays - // at 0 is an inert flag, not a passing gate). - assert!( - compared_rect_parts > 0, - "{NAME}: --enable-rect-partitions=1 never produced a rect partition on a compared \ - attempt ({matched} matches) -- the flag did not arrive" - ); - assert!( - compared_tx_depths > 0, - "{NAME}: --enable-tx-size-search=1 never produced a nonzero tx depth on a compared \ - attempt ({matched} matches) -- the flag did not arrive" - ); - assert!( - compared_class1 > 0, - "{NAME}: --enable-flip-idtx=1 never produced a V_DCT/H_DCT transform on a compared \ - attempt ({matched} matches) -- the 1D types live only in the extended ext-tx sets \ - this flag enables, so the flag did not arrive" - ); - // lane-rect1d r1: the pin of the LANE's own capability -- a V_DCT/H_DCT - // transform on a RECTANGULAR transform unit, read through - // `read_coeffs_rect`'s own 1D scan and contexts. `compared_class1` - // above counts square TUs too, so it can be nonzero while this path - // never fires. - assert!( - compared_rect_class1 > 0, - "{NAME}: no pixel-exact attempt put a 1D tx class on a RECTANGULAR transform \ - ({compared_class1} 1D transforms overall, {compared_rect_tus} rect coefficient \ - TUs) -- the gate proves nothing about the rect 1D path" - ); - eprintln!( - "{NAME}: {matched} pixel-exact decodes ({named_refusals} named refusals out of \ - {n_attempts} attempts, {matched_10bit} of the matches 10-bit), rect coefficient \ - TUs on compared attempts: {compared_rect_tus} ({compared_rect_class1} of them a \ - 1D tx class); flag arrival: rect partitions {compared_rect_parts}, tx \ - depths {compared_tx_depths}, 1D-class (square) transforms {compared_class1}" - ); - } - - /// lane-rectsplit r1 gate (c): gate (a)'s recipe with - /// `--enable-filter-intra=1` (every sibling gate here pins it to 0), so - /// aomenc's RD is free to pick `use_filter_intra` on a 32x16/16x32 strip - /// -- the case [`crate::decode::decode_block_rect`] refused by name - /// ("filter intra on a HORZ/VERT strip (this decoder predicts - /// square-only)") until this round gave `predict_filter_intra` its own - /// `bw`x`bh`. Hard-asserts a nonzero `filter_intra_rect_hits()` delta: - /// a stream where RD never picked filter intra on a strip would - /// pixel-match by construction and prove nothing. - #[test] - fn a_real_aomenc_stream_with_filter_intra_on_a_horz_vert_strip_decodes_pixel_exact() { - const NAME: &str = - "a_real_aomenc_stream_with_filter_intra_on_a_horz_vert_strip_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height) = (192usize, 128usize); - let rect_before = crate::decode::rect_partition_hits(); - let fi_square_before = crate::decode::filter_intra_hits(); - let mut named_refusals = 0u32; - let mut matched = 0u32; - // lane-rectsplit r2 (verifier finding): the feature counter is - // sampled PER ATTEMPT and folded in only after that attempt was - // decoded AND pixel-compared. One delta across the whole sweep - // counted strips decoded by attempts that went on to hit a named - // refusal, so the gate could pass with every COMPARED stream - // containing none of the feature at all. - let mut compared_hits = 0usize; - let n_attempts: u32 = std::env::var("EC_RECTSPLIT_GATE_ATTEMPTS") - .ok() - .and_then(|s| s.parse().ok()) - .unwrap_or(40); - for attempt in 0..n_attempts { - let seed = 42 + attempt; - // Diagnosis knob: which content makes RD pick a HORZ/VERT strip - // AND filter intra on it is a search (see this round's report). - let source = match std::env::var("EC_RECTSPLIT_SRC") - .unwrap_or_default() - .as_str() - { - "bars" => format!("smptebars=size={width}x{height}:duration=0.04:rate=25"), - "src2" => format!("testsrc2=size={width}x{height}:duration=0.04:rate=25"), - _ => gradients_source(seed, width, height, "duration=0.04:rate=25"), - }; - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - // Real chroma: the `hue=s=0` guard gate (a) carried is - // gone (lane-sqchroma r1 -- the square-path chroma defect - // it named does not reproduce at HEAD). - "-pix_fmt", - "yuv420p", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - // Diagnosis knob only (default is the gate's pinned recipe): - // which `--cq-level` makes aomenc's RD reach for filter intra on - // a strip is a search, and the sweep that found this one is in - // lanes/rectsplit-r1.report.md. - let cq = format!( - "--cq-level={}", - // Pinned by the sweep in lanes/rectsplit-r1.report.md: at - // cq 45 aomenc's RD picks a strip 18 times in 100 seeds and - // filter intra on none of them; at cq 25 strips are common - // (130/100 seeds) and filter intra lands on one every ~13 - // seeds. - std::env::var("EC_RECTSPLIT_CQ").unwrap_or_else(|_| "25".into()) - ); - let args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - &cq, - "--cpu-used=0", - "--threads=1", - "--row-mt=0", - "--sb-size=64", - "--enable-rect-partitions=1", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--min-partition-size=16", - "--max-partition-size=32", - "--enable-restoration=0", - "--enable-palette=0", - "--deltaq-mode=0", - "--enable-cdef=0", - // The point of this gate. - "--enable-filter-intra=1", - // NOTE (lane-rectsplit r2, verifier finding): every intra - // mode stays ON here. The square filter-intra gate reaches - // for filter intra by switching the directional/smooth/paeth - // competitors off, and this gate CANNOT: with them off - // aomenc stops picking rect partitions at all (rect - // strips 0/20 seeds, r1's table). What fires filter intra on - // a strip here is the quantiser (`--cq-level=25`), not the - // mode set -- `EC_RECTSPLIT_OFF` below is the diagnosis knob - // that re-runs the subset search. - "--enable-cfl-intra=0", - "--enable-intrabc=0", - "--obu", - "-o", - "-", - "-", - ]; - // Diagnosis knob (default: every intra mode on): turning the - // directional/smooth/paeth competitors off is how the square - // filter-intra gate makes RD reach for filter intra, but with all - // four off aomenc stops picking rect partitions here entirely - // (rect strips=0, filter-intra blocks=28, measured this round), - // so the firing recipe is a search over subsets. - let mut args = args; - let off = std::env::var("EC_RECTSPLIT_OFF").unwrap_or_default(); - for tool in off.split(',').filter(|t| !t.is_empty()) { - args.push(match tool { - "smooth" => "--enable-smooth-intra=0", - "paeth" => "--enable-paeth-intra=0", - "dir" => "--enable-directional-intra=0", - "angle" => "--enable-angle-delta=0", - other => panic!("unknown EC_RECTSPLIT_OFF entry {other}"), - }); - } - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - assert!( - !stream.is_empty(), - "{NAME}: aomenc wrote an empty stream (seed {seed})" - ); - let attempt_before = crate::decode::filter_intra_rect_hits(); - let frames = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME} failed outright, not a named refusal (seed {seed}): {msg}" - ); - named_refusals += 1; - continue; - } - Ok(frames) => frames, - }; - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1); - assert_eq!(frames.len(), 1, "{NAME}: expected one frame (seed {seed})"); - if let Some(i) = frames[0] - .y - .iter() - .zip(&ffmpeg_frames[0].y) - .position(|(a, b)| a != b) - { - let diffs: Vec = frames[0] - .y - .iter() - .zip(&ffmpeg_frames[0].y) - .enumerate() - .filter(|(_, (a, b))| a != b) - .map(|(j, _)| j) - .collect(); - let (x0, x1) = ( - diffs.iter().map(|j| j % width).min().unwrap(), - diffs.iter().map(|j| j % width).max().unwrap(), - ); - let (y0, y1) = (diffs[0] / width, diffs[diffs.len() - 1] / width); - eprintln!( - "{NAME}: seed {seed} first luma mismatch at ({}, {}) ours={} ffmpeg={} \ - -- {} mismatching samples, bbox x {x0}..={x1} y {y0}..={y1}", - i % width, - i / width, - frames[0].y[i], - ffmpeg_frames[0].y[i], - diffs.len(), - ); - } - assert_eq!( - frames[0].y, ffmpeg_frames[0].y, - "{NAME}: luma vs ffmpeg (seed {seed})" - ); - assert_eq!( - frames[0].u, ffmpeg_frames[0].u, - "{NAME}: U vs ffmpeg (seed {seed})" - ); - assert_eq!( - frames[0].v, ffmpeg_frames[0].v, - "{NAME}: V vs ffmpeg (seed {seed})" - ); - compared_hits += crate::decode::filter_intra_rect_hits() - attempt_before; - matched += 1; - } - let fi_hits = compared_hits; - eprintln!( - "{NAME}: rect strips this run={}, filter-intra blocks (any shape)={}", - crate::decode::rect_partition_hits() - rect_before, - crate::decode::filter_intra_hits() - fi_square_before - ); - assert!( - matched > 0, - "{NAME}: every attempt refused ({named_refusals} named refusals) -- gate decoded nothing" - ); - assert!( - fi_hits > 0, - "{NAME}: no HORZ/VERT strip used filter intra ({matched} pixel-exact matches, \ - {named_refusals} refusals out of {n_attempts}) -- gate proved nothing this run" - ); - eprintln!( - "{NAME}: {matched} pixel-exact matches, {named_refusals} named refusals, \ - filter_intra_rect_hits delta={fi_hits} out of {n_attempts} attempts" - ); - } - - /// lane-fistrip r1, the 10-bit arm of the strip gate (his films are - /// yuv420p10le). Same ceiling as its 8-bit twin, lifted in lane-rectsplitx - /// r3 (the split arm's `smooth_neighbor_uv`); before that, MEASURED over seeds - /// 42..61 the 8x16/16x8 strips aomenc writes filter intra on are - /// `skip=0`, which `decode_leaf_rect` refuses, so - /// `filter_intra_rect_sub16_hits` never reaches a pixel compare. - /// lane-fistrip r2 adds seeds 49 and 213 to the window: those are the two - /// seeds measured to fire the feature on the 8-BIT twin's recipe (this - /// arm's 10-bit encode is a different stream, so they are a widening, not - /// a measured firing set for this recipe). Green since r3. - #[test] - fn a_real_aomenc_10bit_filter_intra_on_a_sub16_strip_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_10bit_filter_intra_on_a_sub16_strip_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let mut seeds: Vec = (42..62).collect(); - seeds.push(213); - ten_bit_tool_gate( - NAME, - 192, - 128, - 1, - &[ - "--limit=1", - "--cq-level=25", - "--cpu-used=0", - "--threads=1", - "--row-mt=0", - "--sb-size=64", - "--enable-rect-partitions=1", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--min-partition-size=8", - "--max-partition-size=32", - "--enable-restoration=0", - "--enable-palette=0", - "--deltaq-mode=0", - "--enable-cdef=0", - "--enable-filter-intra=1", - "--enable-cfl-intra=0", - "--enable-intrabc=0", - ], - &seeds, - &[( - "filter_intra_rect_sub16_hits", - crate::decode::filter_intra_rect_sub16_hits as fn() -> usize, - )], - ); - } - - /// lane-fistrip r1, the pinned half of this lane's proof: one real - /// `aomenc` stream (recipe below, byte-reproducible -- md5 - /// ac3a64773e5454ee9b5d8650507063cd, hashed twice) whose key frame - /// carries four `BLOCK_16X8` DC_PRED leaves, one of which sets - /// `use_filter_intra`. `av1_filter_intra_allowed_bsize` allows 16x8, so - /// aomenc writes that flag; before this round `filter_intra_size_class_rect` - /// had no row for the shape, the symbol was never read, and the tile - /// desynced ON THAT BLOCK -- observable as a DIFFERENT named refusal - /// ("a HORZ/VERT intra strip below 16x16 with a split transform", a - /// `tx_depth` read out of a desynced stream) instead of this one. - /// - /// The stream cannot be pixel-compared yet: the 16x8 strip that carries - /// the flag is `skip=0`, and a coded rect strip below 16x16 has no - /// residual path here (its own refusal, another lane's ceiling). What - /// this test pins is the SYMBOL: the flag is read, the counter fires - /// once, and the decode stops at the coded-strip ceiling rather than - /// wandering off a desynced stream. - /// - /// Fixture recipe (`crates/ec-av1/fixtures/filter_intra_8x16_strip_seed49.obu`): - /// `ffmpeg -f lavfi -i gradients=size=192x128:c0=0x986ae1:c1=0xd3e49a: - /// c2=0x0b1e53:c3=0x42980c:seed=49:duration=0.04:rate=25 -pix_fmt yuv420p` - /// into `aomenc --codec=av1 --passes=1 --end-usage=q --cq-level=25 - /// --cpu-used=0 --threads=1 --row-mt=0 --sb-size=64 - /// --enable-rect-partitions=1 --enable-ab-partitions=0 - /// --enable-1to4-partitions=0 --min-partition-size=8 - /// --max-partition-size=32 --enable-restoration=0 --enable-palette=0 - /// --deltaq-mode=0 --enable-filter-intra=1 --enable-cfl-intra=0 - /// --enable-intrabc=0 --obu`. - #[test] - fn a_pinned_aomenc_16x8_strip_reads_its_use_filter_intra_flag() { - const NAME: &str = "a_pinned_aomenc_16x8_strip_reads_its_use_filter_intra_flag"; - let _gate_lock = lock_gate_counters(); - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("fixtures/filter_intra_8x16_strip_seed49.obu"); - let stream = std::fs::read(&path) - .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display())); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - let before = crate::decode::filter_intra_rect_sub16_hits(); - // lane-rectsplitx r1: the ceiling this fixture used to stop at (a - // sub-16 strip with a SPLIT transform) is ported, so the pinned - // stream is now a full pixel compare -- what the doc above said this - // test should become the round that ceiling lifted. - let frames = - decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME}: decode refused: {e}")); - let hits = crate::decode::filter_intra_rect_sub16_hits() - before; - // TWO now, not the one the truncated decode used to see: the frame - // no longer stops at the first filter-intra strip, so the second one - // later in the tile is reached as well (and the pixel compare below - // proves both reconstructed right). - assert_eq!( - hits, 2, - "{NAME}: expected both 16x8 strips to read use_filter_intra=1; got {hits}" - ); - // This is also the GATE for the sub-16 split-transform lift: both - // strips split their transform (`tx_depth != 0` on a BLOCK_16X8 -> - // two TX_8X8 units), which is the refusal this round removed. - let splits = crate::decode::sub16_split_hits(); - assert!( - splits > 0, - "{NAME}: no sub-16 strip split its transform -- the fixture no longer proves the \ - per-unit path this test gates" - ); - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 192, 128, 1); - assert_eq!(frames.len(), 1, "{NAME}: expected one frame"); - assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg"); - assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg"); - assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg"); - } - - /// lane-fistrip r1: the filter-intra strip gate above, one partition - /// level DOWN (`--min-partition-size=8`, so a 16x16 HORZ/VERT splits - /// into 8x16/16x8 leaves). `av1_filter_intra_allowed_bsize` is - /// `wide <= 32 && high <= 32`, which both of those satisfy, so aomenc - /// writes a `use_filter_intra` flag on every DC_PRED one of them -- - /// `filter_intra_size_class_rect` had no row for either shape and - /// [`crate::decode::read_intra_mode_rect`] therefore never READ that - /// symbol (class `symbol-consumption-gap`, a silent desync rather than - /// a refusal). Hard-asserts - /// [`crate::decode::filter_intra_rect_sub16_hits`], not the wider - /// `filter_intra_rect_hits`: a 32x16 strip firing filter intra would - /// satisfy that one and prove nothing about the new shapes. - /// MEASURED (lane-fistrip r1, seeds 42..=241; r2 re-ran 50..=241), which - /// is why the window carries the two firing seeds: over those 200 seeds at - /// cq 25 aomenc put filter intra on an 8x16/16x8 strip exactly TWICE -- - /// **seed 49 and seed 213** -- and both times that strip was `skip=0`, so - /// the attempt refused at the coded-rect-strip-below-16x16 ceiling before - /// any pixel compare (r1: 177 pixel-exact matches, 23 refusals, compared - /// sub16 delta 0, all-attempt delta 2; r2 seeds 50..=241: 172 matches, 20 - /// refusals, the one all-attempt hit at seed 213). BOTH firing seeds are - /// appended to this gate's seed window below, so it compares two real - /// hits. UN-IGNORED lane-rectsplitx r3: the ceiling lifted with the split - /// refusal, and the residual chroma defect was the split arm of - /// [`crate::decode::decode_leaf_rect`] passing `smooth_neighbor_uv: false` - /// where the unsplit arm passes the neighbour's real answer. The symbol - /// itself stays pinned by - /// [`a_pinned_aomenc_16x8_strip_reads_its_use_filter_intra_flag`]. - #[test] - fn a_real_aomenc_stream_with_filter_intra_on_a_sub16_horz_vert_strip_decodes_pixel_exact() { - const NAME: &str = - "a_real_aomenc_stream_with_filter_intra_on_a_sub16_horz_vert_strip_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height) = (192usize, 128usize); - let mut named_refusals = 0u32; - let mut matched = 0u32; - let mut compared_hits = 0usize; - let n_attempts: u32 = std::env::var("EC_FISTRIP_GATE_ATTEMPTS") - .ok() - .and_then(|s| s.parse().ok()) - .unwrap_or(40); - // lane-fistrip r2: the two seeds that MEASURABLY fire filter intra on - // an 8x16/16x8 strip are 49 and 213 -- the only two in seeds 42..=241 - // (r1 measured 42..=241 and reported "all-attempt delta 2" with seed - // 49; r2 re-ran seeds 50..=241 and found the second, log - // `$HOME/.cache/fistrip-seedscan-r2.log`: "seed 213 refused with sub16 - // filter-intra delta 1"). Both are appended to whatever window - // `EC_FISTRIP_GATE_ATTEMPTS` asks for, so the un-ignore after the - // coded-rect-strip ceiling lifts compares TWO real hits instead of - // depending on the default window happening to contain one. - const FIRING_SEEDS: [u32; 2] = [49, 213]; - let mut seeds: Vec = (0..n_attempts).map(|a| 42 + a).collect(); - for s in FIRING_SEEDS { - if !seeds.contains(&s) { - seeds.push(s); - } - } - let cq = format!( - "--cq-level={}", - std::env::var("EC_FISTRIP_CQ").unwrap_or_else(|_| "25".into()) - ); - // Diagnosis: the counter over EVERY attempt, refused ones included -- - // a filter-intra 8x16 strip inside an attempt that later refused - // (non-skip, split transform) fires this but never reaches - // `compared_hits`, and the two numbers differing is what says the - // recipe reaches the feature but this decoder's other ceilings hide - // it. - let all_before = crate::decode::filter_intra_rect_sub16_hits(); - for &seed in &seeds { - let source = gradients_source(seed, width, height, "duration=0.04:rate=25"); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-pix_fmt", - "yuv420p", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - &cq, - "--cpu-used=0", - "--threads=1", - "--row-mt=0", - "--sb-size=64", - "--enable-rect-partitions=1", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - // The point of this gate: one level below the 32x16/16x32 - // strips the sibling gate covers. - "--min-partition-size=8", - "--max-partition-size=32", - "--enable-restoration=0", - "--enable-palette=0", - "--deltaq-mode=0", - "--enable-cdef=0", - "--enable-filter-intra=1", - "--enable-cfl-intra=0", - "--enable-intrabc=0", - "--obu", - "-o", - "-", - "-", - ]; - // Diagnosis knob only (default: every intra mode on) -- the same - // subset search the 32x16/16x32 sibling gate carries. - let mut args = args; - let off = std::env::var("EC_FISTRIP_OFF").unwrap_or_default(); - for tool in off.split(',').filter(|t| !t.is_empty()) { - args.push(match tool { - "smooth" => "--enable-smooth-intra=0", - "paeth" => "--enable-paeth-intra=0", - "dir" => "--enable-directional-intra=0", - "angle" => "--enable-angle-delta=0", - other => panic!("unknown EC_FISTRIP_OFF entry {other}"), - }); - } - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - assert!( - !stream.is_empty(), - "{NAME}: aomenc wrote an empty stream (seed {seed})" - ); - let attempt_before = crate::decode::filter_intra_rect_sub16_hits(); - let frames = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME} failed outright, not a named refusal (seed {seed}): {msg}" - ); - // Diagnosis: a refused attempt that DID fire the feature - // says which other ceiling of this decoder hides it. - eprintln!( - "{NAME}: seed {seed} refused with sub16 filter-intra delta {}: {msg}", - crate::decode::filter_intra_rect_sub16_hits() - attempt_before - ); - named_refusals += 1; - continue; - } - Ok(frames) => frames, - }; - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1); - assert_eq!(frames.len(), 1, "{NAME}: expected one frame (seed {seed})"); - assert_eq!( - frames[0].y, ffmpeg_frames[0].y, - "{NAME}: luma vs ffmpeg (seed {seed})" - ); - assert_eq!( - frames[0].u, ffmpeg_frames[0].u, - "{NAME}: U vs ffmpeg (seed {seed})" - ); - assert_eq!( - frames[0].v, ffmpeg_frames[0].v, - "{NAME}: V vs ffmpeg (seed {seed})" - ); - compared_hits += crate::decode::filter_intra_rect_sub16_hits() - attempt_before; - matched += 1; - } - eprintln!( - "{NAME}: filter_intra_rect_sub16_hits over ALL attempts (refused included) = {}", - crate::decode::filter_intra_rect_sub16_hits() - all_before - ); - assert!( - matched > 0, - "{NAME}: every attempt refused ({named_refusals} named refusals) -- gate decoded nothing" - ); - assert!( - compared_hits > 0, - "{NAME}: no 8x16/16x8 strip used filter intra ({matched} pixel-exact matches, \ - {named_refusals} refusals out of {} attempts) -- gate proved nothing this run", - seeds.len() - ); - eprintln!( - "{NAME}: {matched} pixel-exact matches, {named_refusals} named refusals, \ - filter_intra_rect_sub16_hits delta={compared_hits} (all attempts including \ - refused: {}) out of {} attempts", - crate::decode::filter_intra_rect_sub16_hits() - all_before, - seeds.len() - ); - } - - /// lane-rectsplit r1 gate (b): [`a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact`]'s - /// own recipe (`--sb-size=64`, `--min/max-partition-size=32/64`, so every - /// SB-level decision is genuinely NONE/SPLIT/HORZ/VERT) with its - /// `--enable-tx-size-search=0` DROPPED: the 64x32/32x64 strips may then - /// carry a split transform, which [`crate::decode::decode_block_rect64`] - /// refused by name ("a superblock-level HORZ/VERT strip with a split - /// transform") until lane-rectsplit r2 lifted it. - /// - /// The hard assert is on [`crate::decode::rect_split_sb_interior_tu_hits`], - /// NOT the shared `rect_split_tx_hits()` gate (a) uses: that counter also - /// counts 32x32-level and depth-1 strips, whose units are all in the - /// first transform-unit row/column. Only a superblock-level strip split - /// past depth 1 has an INTERIOR unit (`row_off > 0 && col_off > 0`), - /// which is the per-unit availability rule this port exists for, and no - /// gate fired one before this round. - /// - /// This gate was `#[ignore]`d RED through r3 (seed 50 luma (171,56)). - /// Root cause, r4, TWO defects, neither of them availability -- the - /// strip's own per-unit prediction was exact all along: - /// 1. `av1_nz_map_ctx_offset` is indexed by libaom's COLUMN-major - /// `coeff_idx = col * 32 + row`, so [`crate::decode::base_ctx`] read - /// the `TX_32X64`/`TX_64X32` offset tables transposed (r2 saw this and - /// r3 reverted it, because "fixing" it turned the merged SB HORZ/VERT - /// gate RED at seed 43); - /// 2. that seed-43 RED was a SECOND defect the first one had been hiding - /// behind a refusal: `EOB_PT_512_CHROMA` was transcribed from - /// `av1_default_eob_multi512_cdfs`'s `eob_multi_ctx = 1` row (the flat - /// `V_DCT`/`H_DCT` distribution), so the first real 32x16 chroma - /// transform read `eob_pt` 7 where aomdec read 2. With both fixed, - /// seeds 43 and 50 are pixel-exact. - #[test] - fn a_real_aomenc_stream_with_a_split_transform_superblock_strip_decodes_pixel_exact() { - const NAME: &str = - "a_real_aomenc_stream_with_a_split_transform_superblock_strip_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height) = (192usize, 128usize); - let before = crate::decode::rect_split_tx_hits(); - let mut named_refusals = 0u32; - let mut matched = 0u32; - // lane-rectsplit r2 (verifier finding): the feature counter is - // sampled PER ATTEMPT and folded in only after that attempt was - // decoded AND pixel-compared. One delta across the whole sweep - // counted strips decoded by attempts that went on to hit a named - // refusal, so the gate could pass with every COMPARED stream - // containing none of the feature at all. - let mut compared_hits = 0usize; - let mut split_so_far = 0usize; - // Bounded sweep: see this gate's own doc for the seed-77 residue and - // why extending it is a diagnosis knob, not a pass/fail one. - let n_attempts: u32 = std::env::var("EC_RECTSPLIT_GATE_ATTEMPTS") - .ok() - .and_then(|s| s.parse().ok()) - .unwrap_or(20); - for attempt in 0..n_attempts { - let seed = 42 + attempt; - let source = gradients_source(seed, width, height, "duration=0.04:rate=25"); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - // REAL chroma (lane-sqchroma r1 dropped the `hue=s=0` - // guard this recipe carried): the "PRE-EXISTING square-path - // chroma defect" that guard named does not reproduce at - // HEAD -- seeds 42..61, cq 12/20/32/45, plus testsrc2 and - // mandelbrot, all decode pixel-exact with - // `--enable-rect-partitions=0`, and this gate is green with - // the filter gone. Its own gate is - // `a_real_aomenc_intra_stream_with_tx_size_search_and_chroma_decodes_pixel_exact`. - "-pix_fmt", - "yuv420p", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - // NOTE: no `--enable-tx-size-search=0` here -- leaving aomenc's - // own default (search ON) is the entire point of this gate. - let args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=45", - "--cpu-used=0", - "--threads=1", - "--row-mt=0", - "--sb-size=64", - "--enable-rect-partitions=1", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--min-partition-size=32", - "--max-partition-size=64", - "--enable-restoration=0", - "--enable-palette=0", - "--deltaq-mode=0", - "--enable-cdef=0", - "--enable-filter-intra=0", - "--enable-cfl-intra=0", - "--enable-intrabc=0", - "--obu", - "-o", - "-", - "-", - ]; - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - assert!( - !stream.is_empty(), - "{NAME}: aomenc wrote an empty stream (seed {seed})" - ); - let attempt_before = crate::decode::rect_split_sb_interior_tu_hits(); - let frames = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME} failed outright, not a named refusal (seed {seed}): {msg}" - ); - named_refusals += 1; - continue; - } - Ok(frames) => frames, - }; - let after = crate::decode::rect_split_tx_hits(); - eprintln!( - "{NAME}: seed {seed} decoded, split-tx strips this stream: {}", - after - before - split_so_far - ); - split_so_far = after - before; - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1); - assert_eq!(frames.len(), 1, "{NAME}: expected one frame (seed {seed})"); - if let Some(i) = frames[0] - .y - .iter() - .zip(&ffmpeg_frames[0].y) - .position(|(a, b)| a != b) - { - let diffs: Vec = frames[0] - .y - .iter() - .zip(&ffmpeg_frames[0].y) - .enumerate() - .filter(|(_, (a, b))| a != b) - .map(|(j, _)| j) - .collect(); - let (x0, x1) = ( - diffs.iter().map(|j| j % width).min().unwrap(), - diffs.iter().map(|j| j % width).max().unwrap(), - ); - let (y0, y1) = (diffs[0] / width, diffs[diffs.len() - 1] / width); - eprintln!( - "{NAME}: seed {seed} first luma mismatch at ({}, {}) ours={} ffmpeg={} \ - -- {} mismatching samples, bbox x {x0}..={x1} y {y0}..={y1}", - i % width, - i / width, - frames[0].y[i], - ffmpeg_frames[0].y[i], - diffs.len(), - ); - } - assert_eq!( - frames[0].y, ffmpeg_frames[0].y, - "{NAME}: luma vs ffmpeg (seed {seed})" - ); - assert_eq!( - frames[0].u, ffmpeg_frames[0].u, - "{NAME}: U vs ffmpeg (seed {seed})" - ); - assert_eq!( - frames[0].v, ffmpeg_frames[0].v, - "{NAME}: V vs ffmpeg (seed {seed})" - ); - compared_hits += crate::decode::rect_split_sb_interior_tu_hits() - attempt_before; - matched += 1; - } - let split_hits = compared_hits; - assert!( - matched > 0, - "{NAME}: every attempt refused ({named_refusals} named refusals) -- gate decoded nothing" - ); - assert!( - split_hits > 0, - "{NAME}: zero HORZ/VERT strips resolved a split transform ({matched} pixel-exact \ - matches, {named_refusals} refusals out of {n_attempts}) -- gate proved nothing \ - this run" - ); - eprintln!( - "{NAME}: {matched} pixel-exact matches, {named_refusals} named refusals, \ - rect_split_sb_interior_tu_hits delta={split_hits} (over COMPARED streams only) \ - out of {n_attempts} attempts" - ); - } - - /// lane-part32 r4: a real `aomenc` stream whose superblock-level - /// partition decision is one of the four AB arms (`PARTITION_HORZ_A`/ - /// `_B`/`VERT_A`/`_B` at 64x64: two 32x32 squares plus one 64x32/32x64 - /// strip) must decode pixel-exact. Same recipe as the HORZ/VERT sibling - /// above with `--enable-ab-partitions=1`; `sb_ab_hits() > 0` is a HARD - /// assert, so a run where aomenc's RD never picked an AB arm fails - /// rather than passing vacuously. - #[test] - fn a_real_aomenc_stream_with_a_superblock_level_ab_partition_decodes_pixel_exact() { - const NAME: &str = - "a_real_aomenc_stream_with_a_superblock_level_ab_partition_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height, frame_count) = (192usize, 128usize, 1usize); - let mut named_refusals = 0u32; - let mut matched = 0u32; - let n_attempts: u32 = std::env::var("EC_SBAB_GATE_ATTEMPTS") - .ok() - .and_then(|s| s.parse().ok()) - .unwrap_or(40); - for attempt in 0..n_attempts { - let seed = 42 + attempt; - let duration = frame_count as f64 / 25.0; - let source = - gradients_source(seed, width, height, &format!("duration={duration}:rate=25")); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-pix_fmt", - "yuv420p", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=45", - "--cpu-used=0", - "--threads=1", - "--row-mt=0", - "--sb-size=64", - "--enable-rect-partitions=1", - "--enable-ab-partitions=1", - "--enable-1to4-partitions=0", - "--min-partition-size=32", - "--max-partition-size=64", - "--enable-restoration=0", - "--enable-palette=0", - "--deltaq-mode=0", - "--enable-cdef=0", - "--enable-filter-intra=0", - "--enable-cfl-intra=0", - "--enable-intrabc=0", - "--enable-tx-size-search=0", - "--obu", - "-o", - "-", - "-", - ]; - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let frames = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME} failed outright, not a named refusal (seed {seed}): {msg}" - ); - // r5: the four SB-level AB arms (`partition_w64` 4-7) - // decode since this round, so the only partition refusal - // left at 64x64 is the 1:4 pair (values 8/9, four - // 64x16/16x64 strips, whose luma TX_64X16 this decoder - // has no transform for); the refusals this loop actually - // counts on these fixtures are the pre-existing - // screen-content-palette strip one. Every refusal is - // named, so a genuine decode failure still fails the - // assert above rather than skipping. - named_refusals += 1; - eprintln!("seed {seed} refusal: {msg}"); - continue; - } - Ok(frames) => frames, - }; - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count); - assert_eq!(frames.len(), frame_count); - let mismatched = frames - .iter() - .zip(&ffmpeg_frames) - .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); - if mismatched - && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") { - std::fs::write(&path, &stream).expect("writing pinned stream"); - eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}"); - } - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!( - got.y, want.y, - "{NAME} frame {i} luma vs ffmpeg (seed {seed})" - ); - assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})"); - assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})"); - } - matched += 1; - } - assert!( - matched > 0, - "{NAME}: every attempt refused; the gate never decoded a stream" - ); - let arms = crate::decode::sb_ab_hits_by_arm(); - for (i, name) in ["HORZ_A", "HORZ_B", "VERT_A", "VERT_B"].iter().enumerate() { - assert!( - arms[i] > 0, - "{NAME}: zero superblock-level PARTITION_{name} blocks fired (arms={arms:?}, \ - {matched} matches, {named_refusals} refusals out of {n_attempts}) -- that arm \ - proved nothing this run" - ); - } - eprintln!( - "{NAME}: {named_refusals} named refusals, {matched} pixel-exact matches out of \ - {n_attempts}, sb_ab_hits={} arms(HORZ_A,HORZ_B,VERT_A,VERT_B)={arms:?}", - crate::decode::sb_ab_hits() - ); - } diff --git a/crates/ec-av1/src/stream/tests/t09.rs b/crates/ec-av1/src/stream/tests/t09.rs deleted file mode 100644 index 861498da..00000000 --- a/crates/ec-av1/src/stream/tests/t09.rs +++ /dev/null @@ -1,4486 +0,0 @@ -use super::*; -use super::support::*; -use super::gates_a::*; -use super::gates_b::*; -use crate::probe::run_with_stdin; -use std::process::{Command, Stdio}; - - /// lane-part32 r2: prints the exact mismatch geometry (block coords, - /// got/want pixels) of the pinned seed-42 stream captured off - /// `a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact` - /// via `EC_AV1_GATE_DUMP`. Debug-only, `#[ignore]`d. - #[test] - // The geometry is HARD-CODED to the seed-42 pin (192x128, one frame): - // `ffmpeg_decode_sequence(&stream, 192, 128, 1)` plus the `width = 192` / - // `0..128` scan bounds below. Point it at any other pin and it does not - // say "wrong size" -- it dies inside the ffmpeg oracle with - // `expected 1 4:2:0 frames ... left 196162560 right 36864`. Measured - // against `fixtures/sbpart/seed42.obu` (the 192x128 pin it was written - // for): `total luma mismatches: 0`. - #[ignore = "debug harness: needs EC_AV1_GATE_DUMP_PIN at a 192x128 pin (the geometry is hard-coded; any other size dies in the ffmpeg oracle)"] - fn debug_part32_r2_sbpart_pin_mismatch_geometry() { - let path = std::env::var("EC_AV1_GATE_DUMP_PIN").expect("set EC_AV1_GATE_DUMP_PIN"); - let stream = std::fs::read(&path).expect("read pinned stream"); - let frames = decode_stream(&stream).expect("pinned stream must decode"); - if let Ok(dump) = std::env::var("EC_DEBUG_DUMP_Y") { - let bytes: Vec = frames[0].y.iter().map(|&v| v as u8).collect(); - std::fs::write(&dump, bytes).expect("write y dump"); - } - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 192, 128, 1); - let got = &frames[0]; - let want = &ffmpeg_frames[0]; - let width = 192usize; - let mut n = 0; - let (mut min_x, mut max_x, mut min_y, mut max_y) = (width, 0, 128, 0); - for y in 0..128usize { - for x in 0..width { - let idx = y * width + x; - if got.y[idx] != want.y[idx] { - n += 1; - min_x = min_x.min(x); - max_x = max_x.max(x); - min_y = min_y.min(y); - max_y = max_y.max(y); - } - } - } - eprintln!( - "total luma mismatches: {n} bbox x=[{min_x},{max_x}] y=[{min_y},{max_y}] frame=192x128" - ); - for y in 0..128usize { - let mut row_first = None; - let mut row_count = 0; - for x in 0..width { - let idx = y * width + x; - if got.y[idx] != want.y[idx] { - if row_first.is_none() { - row_first = Some(x); - } - row_count += 1; - } - } - if let Some(fx) = row_first { - eprintln!("row {y}: first mismatch x={fx} count={row_count}"); - } - } - } - - /// lane-rect64q r1, recipe rewritten by lane-av1recipehunt: the same - /// encoder-side situation as - /// [`a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact`] - /// -- a real superblock-level HORZ/VERT partition, so - /// [`crate::decode::decode_block_rect64`] runs -- but with `delta_q` left - /// ON, so that block's dequant sees a running `CURRENT_Q_IDX` that has - /// drifted away from the frame-constant `base_q_idx`. Real aomenc's - /// non-realtime default is `DELTA_Q_OBJECTIVE` (`av1_cx_iface.c:271`); the - /// `--deltaq-mode=0` sibling is the same command line with that one flag - /// added back, and this gate ASSERTS the pair differs (the control arm). - /// - /// **Why r1's recipe could not fire, measured (lane-av1recipehunt).** r1 - /// swept 40 attempts of `gradients` at 192x128 with `frame_count = 1` -- a - /// single KEY frame, and that is the whole reason. A one-frame encode - /// carries no inter frame, and `delta_q_present` needs the temporal (TPL) - /// model to see a spatial complexity map at all. At `frame_count = 1` the - /// sweep read ZERO `delta_q` symbol groups on every attempt: 40/40 streams - /// had `delta_q_hits() == 0` AND `rect64_qidx_drift_hits() == 0` -- a - /// different failure from "the drift never reached a rect64 block", and the - /// reason r1 could not see the feature at all. The fix is a real inter - /// sequence: 4 frames at 512x384 (`8x6` superblocks, so there IS a spatial - /// map for the quantizer to vary over). - /// - /// **The recipe**, exactly (the recorded command line; `--deltaq-mode` is - /// ABSENT, i.e. aomenc's default): - /// ```text - /// ffmpeg -v error -y -f lavfi -i testsrc2=size=512x384:rate=25 \ - /// -pix_fmt yuv420p -frames:v 4 -f yuv4mpegpipe src512.y4m - /// aomenc --codec=av1 --passes=1 --end-usage=q --cq-level=45 --cpu-used=0 \ - /// --threads=1 --row-mt=0 --sb-size=64 --enable-rect-partitions=1 \ - /// --enable-ab-partitions=0 --enable-1to4-partitions=0 \ - /// --min-partition-size=32 --max-partition-size=64 \ - /// --enable-restoration=0 --enable-palette=0 --enable-cdef=0 \ - /// --enable-filter-intra=0 --enable-cfl-intra=0 --enable-intrabc=0 \ - /// --enable-tx-size-search=0 --obu -o out.obu src512.y4m - /// ``` - /// Source `src512.y4m`: 1179730 bytes, sha256 - /// `f430d581497e4f6f7db07d0fc92476e92194e1f96c321988ec0739d475cbbe0c`. - /// Output `crates/ec-av1/fixtures/rect64_dq_drift.obu`: 8384 bytes, sha256 - /// `094e51bb21b6caccc905417e95a03f9131b448071567d0b14ec8850799ea2501` - /// (committed with `git add -f` past the `fixtures` gitignore, like every - /// sibling fixture). The gate re-encodes live and byte-compares against - /// that pin, so the pin is the expected output and not a second decode - /// path. MEASURED on the feature arm: 48 `delta_q` symbol groups read, 17 - /// `rect64_qidx_drift_hits`, `sb_rect_hits` firing (the `inter_rect` - /// census reads `64x32=2 32x64=2`), all 4 frames pixel-exact vs ffmpeg. - /// On the `--deltaq-mode=0` control: 0 groups, 0 drift, also pixel-exact -- - /// so the drift is the delta_q syntax, not some unrelated arm. - /// - /// `--cpu-used=0` is load-bearing, measured: the same source at - /// `--cpu-used=1` and `--cpu-used=3` reads the same 48 `delta_q` groups and - /// drifts ZERO times (the faster presets' RD never leaves a rect64 root in - /// a superblock whose quantizer moved). `--cq-level` is not: 45 and 55 - /// give the identical stream and the same drift count. - #[test] - fn a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_and_delta_q_decodes_pixel_exact() - { - const NAME: &str = "a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_and_delta_q_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - const FIXTURE_LEN: usize = 8384; - const FIXTURE_FNV: u64 = 0x3d91_a216_8006_3ef6; - let (width, height, frame_count) = (512usize, 384usize, 4usize); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-y", - "-f", - "lavfi", - "-i", - "testsrc2=size=512x384:rate=25", - "-pix_fmt", - "yuv420p", - "-frames:v", - "4", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - assert_eq!( - y4m.stdout.len(), - 1_179_730, - "{NAME}: the testsrc2 source is not the pinned 4-frame 512x384 y4m -- `rate=` \ - and `-frames:v` are both part of this recipe's identity" - ); - // Every flag spelled exactly once (class [[aomenc-last-flag-wins]]). - // `delta_q` is absent ON PURPOSE: aomenc's non-realtime default is - // DELTA_Q_OBJECTIVE, and the control arm below re-checks that by - // ADDING `--deltaq-mode=0` back. - let args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=45", - "--cpu-used=0", - "--threads=1", - "--row-mt=0", - "--sb-size=64", - "--enable-rect-partitions=1", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--min-partition-size=32", - "--max-partition-size=64", - "--enable-restoration=0", - "--enable-palette=0", - "--enable-cdef=0", - "--enable-filter-intra=0", - "--enable-cfl-intra=0", - "--enable-intrabc=0", - "--enable-tx-size-search=0", - "--obu", - "-o", - "-", - "-", - ]; - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: encoded size moved"); - assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: encoded bytes moved"); - let pin = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("fixtures/rect64_dq_drift.obu"); - assert_eq!( - std::fs::read(&pin).expect("fixtures/rect64_dq_drift.obu must be committed"), - stream, - "{NAME}: the live encode no longer matches the committed pin at {}", - pin.display() - ); - - let before = crate::decode::rect64_qidx_drift_hits(); - let frames = decode_stream(&stream) - .unwrap_or_else(|e| panic!("{NAME}: the pinned stream must decode: {e}")); - let drift = crate::decode::rect64_qidx_drift_hits() - before; - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count); - assert_eq!(frames.len(), frame_count); - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg"); - assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg"); - assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg"); - } - assert!( - crate::decode::sb_rect_hits() > 0, - "{NAME}: zero superblock-level HORZ/VERT blocks fired -- the recipe stopped producing \ - the shape the delta_q group is read inside" - ); - assert!( - drift > 0, - "{NAME}: {frame_count} frames pixel-exact but zero rect64 dequant calls ever saw \ - CURRENT_Q_IDX != base_q_idx -- delta_q was read and never moved the quantizer inside \ - a rect64 block, so this run proved nothing (class gate-blind-to-feature)" - ); - - // The control arm: the ONE flag separating this gate from the - // always-vacuous `--deltaq-mode=0` sibling, reverted. If this ever - // drifts too, delta_q is no longer what carries the coverage and the - // feature arm above is not the witness it claims to be. It is also this - // gate's own red-proof: dropping that one flag is exactly what turns - // the drift assert above red on its own precondition. - let mut control = args.clone(); - control.push("--deltaq-mode=0"); - let ctl = run_with_stdin(Command::new(aomenc_path()).args(&control), &y4m.stdout); - assert!( - ctl.status.success(), - "aomenc refused the --deltaq-mode=0 control: {}", - String::from_utf8_lossy(&ctl.stderr) - ); - let before = crate::decode::rect64_qidx_drift_hits(); - decode_stream(&ctl.stdout) - .unwrap_or_else(|e| panic!("{NAME}: the control stream must decode too: {e}")); - let ctl_drift = crate::decode::rect64_qidx_drift_hits() - before; - assert_eq!( - ctl_drift, 0, - "{NAME}: the --deltaq-mode=0 control drifted {ctl_drift} times -- delta_q is no \ - longer what moves CURRENT_Q_IDX inside a rect64 block, so the feature arm above is \ - not witnessing what it names" - ); - eprintln!( - "{NAME}: {frame_count} frames pixel-exact, sb_rect_hits={}, \ - rect64_qidx_drift_hits={drift} (--deltaq-mode=0 control: {ctl_drift}), stream \ - {FIXTURE_LEN} B fnv1a64={FIXTURE_FNV:016x}", - crate::decode::sb_rect_hits() - ); - } - - /// lane-sbpart r4: replays a pinned mismatch byte-for-byte off disk (no - /// aomenc/ffmpeg re-encode), same pattern as `pinned_golden3/4_stream_ - /// decodes_pixel_exact` -- fast red/green loop for the bisect, and lets - /// `EC_AV1_TRACE=1` be set for one run without re-driving the encoder. - /// - /// LIVE since lane-av1pinslive (it was `#[ignore]`d from lane-sbpart r4 - /// only because the bytes lived in a scratchpad). Bytes committed at - /// `crates/ec-av1/fixtures/sbpart-pin.obu` (238 bytes; sha256 - /// `62238fc077f45d89745d4d254b9c0465464003529da3b42d0a65631fbb7e16e9`), - /// re-encoded 2026-09-29 from the source gate's own recipe - /// (`a_real_aomenc_stream_with_rect_screen_content_decodes_pixel_exact`: - /// smptebars 192x128, single frame, `--sb-size=64 --enable-palette=1 - /// --min-partition-size=16 --max-partition-size=64`, cq=55). The command - /// is in `lanes/av1pins.report.md`. That gate's source list has no - /// 192x128 cell, so this pin is a 192x128 re-run of its recipe, not a - /// replay of the original mismatch bytes. - #[test] - fn pinned_sbpart_stream_decodes_pixel_exact() { - let path = std::env::var("EC_AV1_GATE_DUMP_PIN") - .map(std::path::PathBuf::from) - .unwrap_or_else(|_| crate_pin("sbpart-pin.obu")); - let Ok(stream) = std::fs::read(&path) else { - eprintln!( - "SKIP pinned_sbpart_stream_decodes_pixel_exact: no pinned bytes at {} \ - -- the committed copy is crates/ec-av1/fixtures/sbpart-pin.obu", - path.display() - ); - return; - }; - if !have_ffmpeg() { - eprintln!("SKIP pinned_sbpart_stream_decodes_pixel_exact: no ffmpeg"); - return; - } - let frames = decode_stream(&stream).expect("pinned stream must decode"); - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 192, 128, 1); - assert_eq!( - frames.len(), - ffmpeg_frames.len(), - "pinned stream decoded {} frames, ffmpeg {} -- a length mismatch would \ - make the zip below compare a mis-paired set", - frames.len(), - ffmpeg_frames.len() - ); - let (width, height) = (192usize, 128usize); - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - if std::env::var_os("EC_SBPART_DIAG").is_some() { - let (mut min_r, mut max_r, mut min_c, mut max_c, mut n) = - (usize::MAX, 0usize, usize::MAX, 0usize, 0usize); - for r in 0..height { - for c in 0..width { - let idx = r * width + c; - if got.y[idx] != want.y[idx] { - min_r = min_r.min(r); - max_r = max_r.max(r); - min_c = min_c.min(c); - max_c = max_c.max(c); - n += 1; - } - } - } - eprintln!( - "DIAG frame {i}: {n} luma mismatches, bbox rows [{min_r}..{max_r}] cols \ - [{min_c}..{max_c}] of {width}x{height}" - ); - // Per-64px-superblock-column mismatch counts, to see whether - // corruption starts exactly at the rect64 SB or bleeds into - // SBs decoded earlier (raster order). - for sb_col in 0..width.div_ceil(64) { - let c0 = sb_col * 64; - let c1 = (c0 + 64).min(width); - let mut cnt = 0usize; - let mut first = None; - for r in 0..height { - for c in c0..c1 { - let idx = r * width + c; - if got.y[idx] != want.y[idx] { - cnt += 1; - if first.is_none() { - first = Some((r, c)); - } - } - } - } - eprintln!( - "DIAG frame {i} sb_col {sb_col} (cols {c0}..{c1}): {cnt} mismatches, \ - first={first:?}" - ); - } - } - assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (pinned sbpart)"); - assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (pinned sbpart)"); - assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (pinned sbpart)"); - } - } - - /// lane-tx64x16 r1: a real `aomenc` stream whose superblock-level - /// partition decision is `PARTITION_HORZ_4`/`PARTITION_VERT_4` (four - /// 64x16 / 16x64 strips) must decode pixel-exact. Both arms are HARD - /// asserted, and only hits earned inside an attempt that then compared - /// pixel-exact against ffmpeg are counted -- a strip decoded by an - /// attempt that later refused proves nothing (class - /// gate-skips-on-its-own-failure). `--enable-1to4-partitions=1` is the - /// tool switch; `--min-partition-size=16` keeps the RD search from - /// recursing below 16x16, where several other unlanded partition shapes - /// live. - #[test] - fn a_real_aomenc_stream_with_a_superblock_level_1to4_partition_decodes_pixel_exact() { - const NAME: &str = - "a_real_aomenc_stream_with_a_superblock_level_1to4_partition_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height, frame_count) = (192usize, 128usize, 1usize); - let mut named_refusals = 0u32; - let mut matched = 0u32; - let (mut horz_proved, mut vert_proved) = (0usize, 0usize); - let (mut out_of_scope, mut out_of_scope_mismatch) = (0u32, 0u32); - let n_attempts: u32 = std::env::var("EC_TX64X16_GATE_ATTEMPTS") - .ok() - .and_then(|s| s.parse().ok()) - .unwrap_or(40); - for attempt in 0..n_attempts { - let seed = 42 + attempt; - let duration = frame_count as f64 / 25.0; - // Odd attempts render the SAME generator rotated 90 degrees - // (generated at height x width, then `transpose`), because - // aomenc's RD picks `PARTITION_VERT_4` on this content and - // essentially never `HORZ_4`: the two arms are a transposed - // pair, and a gate that only ever sees one of them cannot catch - // a transposed scan/context table (class scan-weights-cross-axis). - let source = if attempt % 2 == 0 { - gradients_source(seed, width, height, &format!("duration={duration}:rate=25")) - } else { - format!( - "{},transpose=1", - gradients_source(seed, height, width, &format!("duration={duration}:rate=25")) - ) - }; - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-pix_fmt", - "yuv420p", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=45", - "--cpu-used=0", - "--threads=1", - "--row-mt=0", - "--sb-size=64", - "--enable-rect-partitions=1", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=1", - "--min-partition-size=16", - "--max-partition-size=64", - "--enable-restoration=0", - "--enable-palette=0", - "--deltaq-mode=0", - "--enable-cdef=0", - "--enable-filter-intra=0", - "--enable-cfl-intra=0", - "--enable-intrabc=0", - "--enable-tx-size-search=0", - "--obu", - "-o", - "-", - "-", - ]; - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let before = ( - crate::decode::sb_rect4_horz_hits(), - crate::decode::sb_rect4_vert_hits(), - ); - let frames = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME} failed outright, not a named refusal (seed {seed}): {msg}" - ); - named_refusals += 1; - eprintln!("seed {seed} refusal: {msg}"); - continue; - } - Ok(frames) => frames, - }; - let (horz, vert) = ( - crate::decode::sb_rect4_horz_hits() - before.0, - crate::decode::sb_rect4_vert_hits() - before.1, - ); - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count); - assert_eq!(frames.len(), frame_count); - let mismatched = frames - .iter() - .zip(&ffmpeg_frames) - .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); - if horz + vert == 0 { - // Out of this gate's territory: aomenc's RD picked no 1:4 - // partition at all for this seed, so the attempt can neither - // prove nor disprove the arms under test. NOT silently - // dropped -- counted and printed, and a mismatch here is - // reported as a defect of another lane's shape (r1 found - // one: seed 55 of this very recipe decodes 3944 wrong luma - // samples with zero 1:4 blocks in the stream, first at - // (154, 59), inside the 64x32 `PARTITION_HORZ` superblock at - // (128, 64) -- see lanes/tx64x16-r1.report.md). Selecting on - // "the stream contains the feature", never on "the stream - // decoded correctly", is what keeps this from being survivor - // bias. - out_of_scope += 1; - if mismatched { - out_of_scope_mismatch += 1; - eprintln!( - "{NAME}: seed {seed} MISMATCHES with zero 1:4 blocks -- a pre-existing \ - defect of another shape, not this gate's arms" - ); - } - continue; - } - if mismatched - && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") { - std::fs::write(&path, &stream).expect("writing pinned stream"); - eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}"); - } - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!( - got.y, want.y, - "{NAME} frame {i} luma vs ffmpeg (seed {seed})" - ); - assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})"); - assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})"); - } - horz_proved += horz; - vert_proved += vert; - matched += 1; - } - assert!( - matched > 0, - "{NAME}: every attempt refused; the gate never decoded a stream" - ); - assert!( - horz_proved > 0 && vert_proved > 0, - "{NAME}: a 1:4 arm never fired inside a pixel-exact attempt \ - (horz={horz_proved}, vert={vert_proved}, {matched} matches, {named_refusals} \ - refusals out of {n_attempts}) -- gate proved nothing this run" - ); - eprintln!( - "{NAME}: {named_refusals} named refusals, {matched} pixel-exact matches out of \ - {n_attempts}, horz_4 strips={horz_proved}, vert_4 strips={vert_proved}, \ - {out_of_scope} attempts carried no 1:4 block ({out_of_scope_mismatch} of them \ - mismatched -- other lanes' shapes)" - ); - // Class gate-skips-on-its-own-failure: an attempt that decoded but - // does not carry this gate's shape is still a decode this crate got - // wrong. Counted separately so the message names the other shape, - // never tolerated. - assert_eq!( - out_of_scope_mismatch, 0, - "{NAME}: {out_of_scope_mismatch} attempt(s) with no 1:4 block decoded but \ - mismatched ffmpeg -- a defect of another shape, not a pass" - ); - } - - /// lane-tx64x16 r3: the 32x32-LEVEL 1:4 pair -- `PARTITION_HORZ_4` / - /// `PARTITION_VERT_4` at 32x32, i.e. four 32x8 / 8x32 strips, the arm the - /// ReelB mid-film extract stops at ("a 32x32 partition type this - /// decoder does not code (value=8)"). `--min-partition-size=8` is what - /// lets aomenc's RD reach the 32-level 1:4 shapes; `--max-partition-size=32` - /// keeps the superblock-level pair (already gated by its own test above) - /// out of the counters. Both orientations HARD-asserted per bit depth -- - /// the luma scans and the two new chroma scans (`SCAN_16X4`/`SCAN_4X16`) - /// are transposed pairs, so a one-sided gate cannot catch a transposition - /// (class scan-weights-cross-axis). `rect4_coeff_hits` is asserted too: - /// an all-skip stream would exercise none of the new coefficient tables - /// (class gate-blind-to-feature). Only hits earned inside an attempt that - /// then compared pixel-exact are counted (class - /// gate-skips-on-its-own-failure); the 10-bit arm is what retires - /// `enable-1to4-partitions` from `NEVER_EXERCISED_10BIT`. - /// lane-r14: the 16x16-level 1:4 pair -- four 16x4 (`PARTITION_HORZ_4`) or - /// 4x16 (`PARTITION_VERT_4`) strips, the shape the wall - /// "a 1:4 partition below 16x16" refused. Fixture: 4-PIXEL bands (the - /// 8-pixel ones of the 32-level gate above, one size down -- a 16x4 strip - /// is flat where a 16x8 one is not), transposed per attempt so a - /// transposed scan or nz-map table cannot pass (class - /// scan-weights-cross-axis), plus an explicit-seed noise layer that keeps - /// aomenc out of screen-content mode. `--enable-filter-intra=1` and - /// is ON: this shape reads `use_filter_intra` off its own CDF rows - /// (classes 12/13). The `--enable-tx-size-search=1` half of the window - /// splits the strip's transform (depth 1 = TX_8X4/TX_4X8, depth 2 = - /// TX_4X4). - /// - /// Counters: 16x4 strips, 4x16 strips, chroma-reference strips (the odd - /// strip of each 4:2:0 pair, the only one that codes chroma) and strips - /// with a coded residual must all be nonzero over the compared attempts, - /// and only attempts that DECODED and were compared pixel-exact count - /// (class gate-skips-on-its-own-failure). - #[test] - fn a_real_aomenc_stream_with_a_16_level_1to4_partition_decodes_pixel_exact() { - const NAME: &str = - "a_real_aomenc_stream_with_a_16_level_1to4_partition_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height, frame_count) = (192usize, 128usize, 1usize); - let n_attempts: u32 = std::env::var("EC_R14_GATE_ATTEMPTS") - .ok() - .and_then(|s| s.parse().ok()) - .unwrap_or(8); - for bit_depth in [8u32, 10u32] { - let mut named_refusals = 0u32; - let mut matched = 0u32; - let (mut horz_proved, mut vert_proved) = (0usize, 0usize); - let (mut chroma_proved, mut coeff_proved) = (0usize, 0usize); - let mut split_proved = 0usize; - // lane-kf1200: chroma pairs whose intra-edge filter type comes out - // different when read from the PAIR's base mi (libaom's - // `chroma_above_mbmi`) rather than the odd strip mi -- the shape - // that was silently wrong by 1 on the ReelB key frames. - let mut pair_filt_proved = 0usize; - let (mut out_of_scope, mut out_of_scope_mismatch) = (0u32, 0u32); - // The second half of the window turns `--enable-tx-size-search` on: - // that is what makes a 16x4 strip SPLIT its transform (depth 1 = - // TX_8X4, depth 2 = TX_4X4), the arm the first half never reaches. - for attempt in 0..n_attempts * 2 { - let tx_search = attempt >= n_attempts; - let attempt = attempt % n_attempts; - let seed = 42 + attempt; - let duration = frame_count as f64 / 25.0; - let axis = if attempt.is_multiple_of(2) { "Y" } else { "X" }; - let step = 67 + (attempt / 2) * 12; - let noise = 6 + (attempt % 4) * 3; - // lane-kf1200: the odd attempts carry CHROMA content. The - // original gray source leaves both chroma planes constant, so - // every `uv_mode` is DC and a pair's edge-filter type can never - // differ from its strip's -- the shape that shipped wrong for - // months. A smooth chroma gradient makes aomenc pick SMOOTH / - // directional `uv_mode`s next to each other. - let source = if attempt.is_multiple_of(2) { - format!( - "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\ - geq=lum='mod(floor({axis}/4)*{step},256)',\ - noise=alls={noise}:all_seed={seed},format=yuv420p" - ) - } else { - format!( - "color=c=black:s={width}x{height}:d={duration}:r=25,format=yuv420p,\ - geq=lum='mod(floor({axis}/4)*{step},256)'\ - :cb='128+100*sin((X+Y)/23)':cr='128+100*cos(X/19)',\ - noise=alls={noise}:all_seed={seed}" - ) - }; - let cq_level = format!("--cq-level={}", 24 + (attempt % 4) * 8); - let pix_fmt = if bit_depth == 10 { - "yuv420p10le" - } else { - "yuv420p" - }; - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-t", - &duration.to_string(), - "-pix_fmt", - pix_fmt, - "-strict", - "-1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let depth_arg = format!("--bit-depth={bit_depth}"); - let input_depth_arg = format!("--input-bit-depth={bit_depth}"); - let args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - &cq_level, - "--cpu-used=0", - "--threads=1", - "--row-mt=0", - "--sb-size=64", - &depth_arg, - &input_depth_arg, - "--enable-rect-partitions=1", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=1", - "--min-partition-size=4", - "--max-partition-size=16", - "--enable-restoration=0", - "--enable-palette=0", - "--deltaq-mode=0", - "--enable-filter-intra=1", - // lane-r14: CfL stays OFF here. This shape's CfL averages - // the luma of the whole PAIR and is written, but no gate - // asserts a CfL hit counter (there is none), and passing - // `=1` would retire `enable-cfl-intra` from - // `gate_coverage::NEVER_EXERCISED_*` on a flag alone -- - // exactly the false coverage that list exists to prevent. - "--enable-cfl-intra=0", - "--enable-intrabc=0", - if tx_search { - "--enable-tx-size-search=1" - } else { - "--enable-tx-size-search=0" - }, - "--obu", - "-o", - "-", - "-", - ]; - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let before = crate::decode::rect4_16_counters(); - let pair_filt_before = crate::decode::rect4_16_uv_pair_filt_hits(); - let frames = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME} failed outright, not a named refusal ({bit_depth}-bit, seed \ - {seed}): {msg}" - ); - named_refusals += 1; - eprintln!("{bit_depth}-bit seed {seed} refusal: {msg}"); - continue; - } - Ok(frames) => frames, - }; - let now = crate::decode::rect4_16_counters(); - let (horz, vert, chroma, coeff, split) = ( - now.0 - before.0, - now.1 - before.1, - now.2 - before.2, - now.3 - before.3, - now.4 - before.4, - ); - let ffmpeg_frames = if bit_depth == 10 { - ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count) - } else { - ffmpeg_decode_sequence(&stream, width, height, frame_count) - }; - assert_eq!(frames.len(), frame_count); - let mismatched = frames - .iter() - .zip(&ffmpeg_frames) - .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); - if horz + vert == 0 { - out_of_scope += 1; - if mismatched { - out_of_scope_mismatch += 1; - eprintln!( - "{NAME}: {bit_depth}-bit seed {seed} MISMATCHES with zero 16-level \ - 1:4 strips -- a pre-existing defect of another shape" - ); - } - continue; - } - if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") { - std::fs::write(&path, &stream).expect("writing pinned stream"); - eprintln!( - "EC_AV1_GATE_DUMP: wrote mismatching stream ({bit_depth}-bit, seed \ - {seed}) to {path}" - ); - } - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!( - got.y, want.y, - "{NAME} frame {i} luma vs ffmpeg ({bit_depth}-bit, seed {seed})" - ); - assert_eq!( - got.u, want.u, - "{NAME} frame {i} U vs ffmpeg ({bit_depth}-bit, seed {seed})" - ); - assert_eq!( - got.v, want.v, - "{NAME} frame {i} V vs ffmpeg ({bit_depth}-bit, seed {seed})" - ); - } - horz_proved += horz; - vert_proved += vert; - chroma_proved += chroma; - coeff_proved += coeff; - pair_filt_proved += crate::decode::rect4_16_uv_pair_filt_hits() - pair_filt_before; - split_proved += split; - matched += 1; - } - assert!( - matched > 0, - "{NAME}: every {bit_depth}-bit attempt refused or fell out of scope ({named_refusals} \ - refusals, {out_of_scope} out of scope); the gate proved nothing" - ); - assert_eq!( - out_of_scope_mismatch, 0, - "{NAME}: {out_of_scope_mismatch} {bit_depth}-bit attempt(s) mismatch with no \ - 16-level 1:4 strip at all" - ); - assert!( - horz_proved > 0 && vert_proved > 0, - "{NAME}: {bit_depth}-bit compared attempts decoded {horz_proved} 16x4 and \ - {vert_proved} 4x16 strips -- both orientations must fire or a transposed table \ - passes" - ); - assert!( - chroma_proved > 0, - "{NAME}: {bit_depth}-bit compared attempts closed {chroma_proved} chroma pairs" - ); - assert!( - coeff_proved > 0, - "{NAME}: {bit_depth}-bit compared attempts coded no residual on any strip" - ); - assert!( - split_proved > 0, - "{NAME}: {bit_depth}-bit compared attempts never split a strip's transform -- \ - the `--enable-tx-size-search=1` half of the window proved nothing" - ); - assert!( - pair_filt_proved > 0, - "{NAME}: {bit_depth}-bit compared attempts never decoded a chroma pair whose \ - edge-filter type differs between the pair's base mi and the strip's own mi -- \ - the lane-kf1200 fix is unexercised, so this gate would pass with it reverted" - ); - eprintln!( - "{NAME}: {bit_depth}-bit {matched} compared attempts, {horz_proved} 16x4 / \ - {vert_proved} 4x16 strips, {chroma_proved} chroma pairs, {coeff_proved} coded \ - units, {split_proved} split-transform strips, {pair_filt_proved} pair-base \ - filt-type flips, {named_refusals} refusals, {out_of_scope} out of scope" - ); - } - } - - #[test] - // lane-tx64x16 r4: the fixture r3 could not find. `gradients` never wins - // a 32-level 1:4 shape; 8-pixel BANDS do -- each 32x8 strip is flat, so - // HORZ_4 beats both HORZ (two bands per 32x16) and SPLIT, while the noise - // layer keeps aomenc out of screen-content mode. Measured 16 HORZ_4 / 24 - // VERT_4 strips per frame, both bit depths (lanes/tx64x16-r4.report.md). - fn a_real_aomenc_stream_with_a_32x32_level_1to4_partition_decodes_pixel_exact() { - const NAME: &str = - "a_real_aomenc_stream_with_a_32x32_level_1to4_partition_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height, frame_count) = (192usize, 128usize, 1usize); - let n_attempts: u32 = std::env::var("EC_TX64X16_GATE32_ATTEMPTS") - .ok() - .and_then(|s| s.parse().ok()) - .unwrap_or(8); - for bit_depth in [8u32, 10u32] { - let mut named_refusals = 0u32; - let mut matched = 0u32; - let (mut horz_proved, mut vert_proved, mut coeff_proved) = (0usize, 0usize, 0usize); - let (mut depth1_proved, mut depth2_proved) = (0usize, 0usize); - let (mut out_of_scope, mut out_of_scope_mismatch) = (0u32, 0u32); - // lane-rectsplitx r1: the SECOND half of the attempt window turns - // `--enable-tx-size-search` ON at low cq, which is what makes a - // 32-level 1:4 strip SPLIT its transform -- depth 1 is the 2:1 - // rect unit TX_16X8/TX_8X16 (`sub_tx_size_map[TX_32X8]`), depth 2 - // the square TX_8X8, and the two interleave across attempts, so - // both are asserted (a depth-2-only run leaves the rect-unit path - // unproved). - for attempt in 0..n_attempts * 2 { - let tx_search = attempt >= n_attempts; - let attempt = attempt % n_attempts; - let seed = 42 + attempt; - let duration = frame_count as f64 / 25.0; - // 8-pixel bands: a 32x8 strip is flat, a 32x16 one is not, so - // aomenc's RD picks HORZ_4 (bands across Y) / VERT_4 (bands - // across X). Odd attempts are the transposed source -- the - // transposed-pair discipline the superblock-level 1:4 gate - // above documents, and the only way a transposed scan table is - // caught (class scan-weights-cross-axis). The noise layer is - // what keeps the flat bands out of screen-content mode; its - // seed is explicit, never lavfi's ignored default. - let axis = if attempt.is_multiple_of(2) { "Y" } else { "X" }; - let step = 67 + (attempt / 2) * 12; - let noise = 6 + (attempt % 4) * 3; - let source = format!( - "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\ - geq=lum='mod(floor({axis}/8)*{step},256)',\ - noise=alls={noise}:all_seed={seed},format=yuv420p" - ); - // lane-band63: the second cq is 63, not 45 -- a near-max - // quantiser is where deblock/CDEF do the most work and where a - // 1:4 strip is most often skip; all 16 streams of this family at - // cq 63 (8- and 10-bit) decode pixel-exact. - let cq_level = if tx_search { - // 12..28: the window measured to fire both split depths on - // this fixture (lanes/tx64x16-r4.handoff.md). - format!("--cq-level={}", 12 + (attempt % 4) * 5) - } else { - format!("--cq-level={}", if attempt % 4 < 2 { 32 } else { 63 }) - }; - let pix_fmt = if bit_depth == 10 { - "yuv420p10le" - } else { - "yuv420p" - }; - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-t", - &duration.to_string(), - "-pix_fmt", - pix_fmt, - "-strict", - "-1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let depth_arg = format!("--bit-depth={bit_depth}"); - let input_depth_arg = format!("--input-bit-depth={bit_depth}"); - let args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - &cq_level, - "--cpu-used=0", - "--threads=1", - "--row-mt=0", - "--sb-size=64", - &depth_arg, - &input_depth_arg, - "--enable-rect-partitions=1", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=1", - "--min-partition-size=8", - "--max-partition-size=32", - "--enable-restoration=0", - "--enable-palette=0", - "--deltaq-mode=0", - "--enable-filter-intra=0", - "--enable-cfl-intra=0", - "--enable-intrabc=0", - if tx_search { - "--enable-tx-size-search=1" - } else { - "--enable-tx-size-search=0" - }, - "--obu", - "-o", - "-", - "-", - ]; - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let before = ( - crate::decode::rect4_32_horz_hits(), - crate::decode::rect4_32_vert_hits(), - crate::decode::rect4_coeff_hits(), - ); - let split_before = crate::decode::rect4_split_depth_hits(); - let frames = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME} failed outright, not a named refusal ({bit_depth}-bit, seed \ - {seed}): {msg}" - ); - named_refusals += 1; - eprintln!("{bit_depth}-bit seed {seed} refusal: {msg}"); - continue; - } - Ok(frames) => frames, - }; - let (horz, vert, coeff) = ( - crate::decode::rect4_32_horz_hits() - before.0, - crate::decode::rect4_32_vert_hits() - before.1, - crate::decode::rect4_coeff_hits() - before.2, - ); - let split_now = crate::decode::rect4_split_depth_hits(); - let (d1, d2) = (split_now.0 - split_before.0, split_now.1 - split_before.1); - let ffmpeg_frames = if bit_depth == 10 { - ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count) - } else { - ffmpeg_decode_sequence(&stream, width, height, frame_count) - }; - assert_eq!(frames.len(), frame_count); - let mismatched = frames - .iter() - .zip(&ffmpeg_frames) - .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); - if horz + vert == 0 { - // Out of this gate's territory (no 32-level 1:4 block in - // the stream): counted and printed, never silently - // dropped, and a mismatch here is another shape's defect. - out_of_scope += 1; - if mismatched { - out_of_scope_mismatch += 1; - eprintln!( - "{NAME}: {bit_depth}-bit seed {seed} MISMATCHES with zero 32-level \ - 1:4 blocks -- a pre-existing defect of another shape" - ); - } - continue; - } - if mismatched - && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") { - std::fs::write(&path, &stream).expect("writing pinned stream"); - eprintln!( - "EC_AV1_GATE_DUMP: wrote mismatching stream ({bit_depth}-bit, seed \ - {seed}) to {path}" - ); - } - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!( - got.y, want.y, - "{NAME} frame {i} luma vs ffmpeg ({bit_depth}-bit, seed {seed})" - ); - assert_eq!( - got.u, want.u, - "{NAME} frame {i} U vs ffmpeg ({bit_depth}-bit, seed {seed})" - ); - assert_eq!( - got.v, want.v, - "{NAME} frame {i} V vs ffmpeg ({bit_depth}-bit, seed {seed})" - ); - } - horz_proved += horz; - vert_proved += vert; - coeff_proved += coeff; - depth1_proved += d1; - depth2_proved += d2; - matched += 1; - } - assert!( - matched > 0, - "{NAME}: every {bit_depth}-bit attempt refused; the gate never decoded a stream" - ); - assert!( - horz_proved > 0 && vert_proved > 0, - "{NAME}: a 32-level 1:4 arm never fired inside a pixel-exact {bit_depth}-bit \ - attempt (horz={horz_proved}, vert={vert_proved}, {matched} matches, \ - {named_refusals} refusals out of {n_attempts}) -- gate proved nothing this run" - ); - assert!( - coeff_proved > 0, - "{NAME}: every {bit_depth}-bit 32-level 1:4 strip was skip -- the 32x8/16x4 \ - coefficient tables were never read" - ); - eprintln!( - "{NAME}: {bit_depth}-bit: {named_refusals} named refusals, {matched} pixel-exact \ - matches out of {n_attempts}, horz_4 strips={horz_proved}, vert_4 \ - strips={vert_proved}, coded strips={coeff_proved}, {out_of_scope} attempts \ - carried no 32-level 1:4 block ({out_of_scope_mismatch} mismatched)" - ); - // The split-transform halves of the window: both tx depths must - // have fired inside an attempt that then compared pixel-exact - // (class counter-from-refused-stream -- a global counter would - // count strips of attempts that later refused). - // lane-rectsplitx r2: BOTH depths are now decoded, so both are - // HARD-asserted -- depth 1 is the 2:1 rect unit - // (`sub_tx_size_map[TX_32X8] == TX_16X8`), depth 2 the square - // TX_8X8, and they interleave across the window; a run that only - // reached one of them proves half the walk. - assert!( - depth1_proved > 0 && depth2_proved > 0, - "{NAME}: {bit_depth}-bit: a 1:4 split-transform depth never fired inside a \ - pixel-exact attempt (depth1={depth1_proved}, depth2={depth2_proved}) -- the \ - tx-size-search half of the window proved nothing" - ); - eprintln!( - "{NAME}: {bit_depth}-bit split-transform 1:4 strips: depth1={depth1_proved}, \ - depth2={depth2_proved}" - ); - assert_eq!( - out_of_scope_mismatch, 0, - "{NAME}: {bit_depth}-bit: {out_of_scope_mismatch} attempt(s) with zero 32-level \ - 1:4 blocks decoded but mismatched ffmpeg -- a defect of another shape, not a pass" - ); - } - } - - /// lane-fi32x8 r1 (class symbol-consumption-gap): the 32x32-level 1:4 - /// strips (32x8/8x32) are inside `av1_filter_intra_allowed_bsize`'s - /// "both sides <= 32" bound, so libaom reads a `use_filter_intra` flag on - /// every DC_PRED one of them -- and `--enable-filter-intra` is ON by - /// aomenc default, so the sibling gate above (which spells it `=0`) could - /// never see it. `filter_intra_size_class_rect` had no row for either - /// shape, so the symbol was never read and the tile desynced silently - /// from that strip on. Same band fixture as the sibling (8-px bands + - /// seeded noise, both orientations), the ONLY recipe change being - /// `--enable-filter-intra=1` appended AFTER the base recipe (aomenc keeps - /// the LAST occurrence of a repeated `--enable-*` flag). The counter is - /// this shape's OWN (`filter_intra_rect4_hits`), not the shared rect one, - /// so a filter-intra 16x8 strip elsewhere in the frame cannot stand in - /// for it; only hits earned inside an attempt that then compared - /// pixel-exact are counted (class gate-skips-on-its-own-failure), and - /// both bit depths are asserted independently. - /// - /// `--enable-tx-size-search=0` is kept from the sibling recipe: a 1:4 - /// strip with `tx_depth != 0` is still refused by name ("a 32x32-level - /// 1:4 strip with a split transform"), so a search-on arm would only - /// harvest refusals, not coverage -- filter intra is proven at depth 0 - /// here and the per-TU case belongs to the round that lifts that refusal. - #[test] - fn a_real_aomenc_stream_with_filter_intra_on_a_32_level_1to4_strip_decodes_pixel_exact() { - const NAME: &str = - "a_real_aomenc_stream_with_filter_intra_on_a_32_level_1to4_strip_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height, frame_count) = (192usize, 128usize, 1usize); - let n_attempts: u32 = std::env::var("EC_FI32X8_GATE_ATTEMPTS") - .ok() - .and_then(|s| s.parse().ok()) - // 16, not 12 (measured, r1): the first attempt whose VERT_4 - // (8x32) strips pick filter intra at 8 bit is attempt 13. - .unwrap_or(16); - for bit_depth in [8u32, 10u32] { - let mut named_refusals = 0u32; - let mut matched = 0u32; - let (mut fi_horz_proved, mut fi_vert_proved, mut strips_proved) = - (0usize, 0usize, 0usize); - let (mut out_of_scope, mut out_of_scope_mismatch) = (0u32, 0u32); - for attempt in 0..n_attempts { - let seed = 42 + attempt; - let duration = frame_count as f64 / 25.0; - let axis = if attempt % 2 == 0 { "Y" } else { "X" }; - let step = 67 + (attempt / 2) * 12; - // A HEAVIER noise layer than the sibling gate's 6..15 (lane-fi32x8 r1, - // measured): filter intra is what aomenc reaches for when a flat - // band is noisy, so at 6..15 the flag fired on a 1:4 strip in 3 of - // 40 8-bit attempts and in NONE of 40 10-bit ones, while at 18..27 - // it fires in most attempts at BOTH depths. - let noise = 18 + (attempt % 4) * 3; - let source = format!( - "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\ - geq=lum='mod(floor({axis}/8)*{step},256)',\ - noise=alls={noise}:all_seed={seed},format=yuv420p" - ); - // lane-band63: 63 joins the rotation -- filter intra ON at a - // near-max quantiser is exactly the configuration the stale - // cq-63 premise blamed, and it decodes exact. - let cq_level = format!( - "--cq-level={}", - [32, 45, 55, 63][(attempt / 2 % 4) as usize] - ); - let pix_fmt = if bit_depth == 10 { - "yuv420p10le" - } else { - "yuv420p" - }; - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-t", - &duration.to_string(), - "-pix_fmt", - pix_fmt, - "-strict", - "-1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let depth_arg = format!("--bit-depth={bit_depth}"); - let input_depth_arg = format!("--input-bit-depth={bit_depth}"); - let args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - &cq_level, - "--cpu-used=0", - "--threads=1", - "--row-mt=0", - "--sb-size=64", - &depth_arg, - &input_depth_arg, - "--enable-rect-partitions=1", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=1", - "--min-partition-size=8", - "--max-partition-size=32", - "--enable-restoration=0", - "--enable-palette=0", - "--deltaq-mode=0", - "--enable-cfl-intra=0", - "--enable-intrabc=0", - "--enable-tx-size-search=0", - // The competing intra modes off (lane-fi32x8 r1): with - // directional/paeth/smooth intra available, aomenc's RD - // picks filter intra on a 32x8 strip in only ~3 of 40 - // attempts at 8 bit and NEVER at 10 bit (measured, see the - // r1 report), so this shape's own symbol would go - // unexercised at 10 bit. Leaving DC and filter intra as - // the block's luma intra choices makes the flag fire - // without weakening the gate: every decoded frame is - // still compared to ffmpeg in full. - "--enable-directional-intra=0", - "--enable-paeth-intra=0", - "--enable-smooth-intra=0", - // THE override, last (aomenc keeps the last occurrence). - "--enable-filter-intra=1", - "--obu", - "-o", - "-", - "-", - ]; - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let before = ( - crate::decode::filter_intra_rect4_horz_hits(), - crate::decode::filter_intra_rect4_vert_hits(), - crate::decode::rect4_32_horz_hits() + crate::decode::rect4_32_vert_hits(), - ); - let frames = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME} failed outright, not a named refusal ({bit_depth}-bit, seed \ - {seed}): {msg}" - ); - named_refusals += 1; - eprintln!("{bit_depth}-bit seed {seed} refusal: {msg}"); - continue; - } - Ok(frames) => frames, - }; - let (fi_horz, fi_vert, strips) = ( - crate::decode::filter_intra_rect4_horz_hits() - before.0, - crate::decode::filter_intra_rect4_vert_hits() - before.1, - crate::decode::rect4_32_horz_hits() + crate::decode::rect4_32_vert_hits() - - before.2, - ); - let fi = fi_horz + fi_vert; - let ffmpeg_frames = if bit_depth == 10 { - ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count) - } else { - ffmpeg_decode_sequence(&stream, width, height, frame_count) - }; - assert_eq!(frames.len(), frame_count); - let mismatched = frames - .iter() - .zip(&ffmpeg_frames) - .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); - // Per-attempt line (opt-in): which (seed, cq, axis, noise) - // actually made aomenc pick filter intra ON a 1:4 strip is - // exactly what a re-tune of this fixture needs, and it is not - // recoverable from the summary. - if std::env::var_os("EC_FI32X8_VERBOSE").is_some() { - eprintln!( - "{NAME}: {bit_depth}-bit seed {seed} {cq_level} axis={axis} noise={noise} \ - fi={fi_horz}+{fi_vert} strips={strips} mismatched={mismatched}" - ); - } - if fi == 0 { - out_of_scope += 1; - if mismatched { - out_of_scope_mismatch += 1; - eprintln!( - "{NAME}: {bit_depth}-bit seed {seed} MISMATCHES with zero \ - filter-intra 1:4 strips ({strips} plain 1:4 strips) -- a defect of \ - another shape" - ); - } - continue; - } - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!( - got.y, want.y, - "{NAME} frame {i} luma vs ffmpeg ({bit_depth}-bit, seed {seed})" - ); - assert_eq!( - got.u, want.u, - "{NAME} frame {i} U vs ffmpeg ({bit_depth}-bit, seed {seed})" - ); - assert_eq!( - got.v, want.v, - "{NAME} frame {i} V vs ffmpeg ({bit_depth}-bit, seed {seed})" - ); - } - fi_horz_proved += fi_horz; - fi_vert_proved += fi_vert; - strips_proved += strips; - matched += 1; - } - // BOTH orientations, per bit depth: rows 8/9 of `cdf::FILTER_INTRA` - // are asymmetric (18101 for 32x8, 20229 for 8x32), so a one-sided - // assert would pass on a transposed pair. - assert!( - fi_horz_proved > 0 && fi_vert_proved > 0 && matched > 0, - "{NAME}: a 32x8/8x32 strip orientation never read use_filter_intra=1 inside a \ - pixel-exact {bit_depth}-bit attempt (32x8={fi_horz_proved}, \ - 8x32={fi_vert_proved}, {matched} matches, {named_refusals} refusals, \ - {out_of_scope} attempts with no filter-intra 1:4 strip, out of {n_attempts}) \ - -- gate proved nothing this run" - ); - eprintln!( - "{NAME}: {bit_depth}-bit: {named_refusals} named refusals, {matched} pixel-exact \ - matches out of {n_attempts}, filter-intra 1:4 strips={fi_horz_proved}x(32x8)+{fi_vert_proved}x(8x32) of \ - {strips_proved} 1:4 strips, {out_of_scope} attempts carried none \ - ({out_of_scope_mismatch} mismatched)" - ); - assert_eq!( - out_of_scope_mismatch, 0, - "{NAME}: {bit_depth}-bit: {out_of_scope_mismatch} attempt(s) with zero \ - filter-intra 1:4 strips decoded but mismatched ffmpeg -- a defect of another \ - shape, not a pass" - ); - } - } - - #[test] - fn a_real_aomenc_multi_tile_intra_stream_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_multi_tile_intra_stream_decodes_pixel_exact"; - let before = crate::decode::uv_tile_edge_suppressed_hits(); - run_multi_tile_gate(NAME, 1, 1, 8, 1, &[], false, None); - // lane-mtfix r1: this is the only arm with a tile ROW boundary, so it - // is the one that exercises the tile-relative guard on the chroma - // edge-filter neighbour. Without the guard, seed 46's first block of - // the bottom-right tile read the tile ABOVE it and mis-filtered its - // chroma edge (U/V off by 1..2 over chroma x[120..127] y[32..37]). - if have_ffmpeg() && have_aomenc() { - assert!( - crate::decode::uv_tile_edge_suppressed_hits() > before, - "{NAME}: no chroma edge-filter neighbour read was suppressed at a tile edge -- \ - the tile-relative guard is untested by this gate" - ); - } - } - - /// lane-kf900 r1: a SKIPPED 8x8 intra leaf whose `tx_depth` symbol - /// resolved to TX_4X4 must publish 4 -- not its 8-px block side -- to the - /// next block's `get_tx_size_context` (libaom `set_txfm_ctxs(mbmi->tx_size, - /// ..., skip_txfm && is_inter_block(mbmi), xd)`; that skip term is always 0 - /// for an intra block). `decode_leaf8`'s tail wrote the literal 8, so the - /// rect strip below such a leaf read `tx_size_cat1` row 2 where libaom - /// reads row 1 -- same alphabet, wrong CDF row, the msac range diverged - /// mid-frame with NO refusal. `skip_split_tx_hits` was `pub` and asserted - /// by no gate at all before this one (class `tool-disabled-in-every-gate`). - #[test] - fn a_real_aomenc_stream_with_a_skipped_8x8_intra_leaf_whose_tx_split_decodes_pixel_exact() { - const NAME: &str = - "a_real_aomenc_stream_with_a_skipped_8x8_intra_leaf_whose_tx_split_decodes_pixel_exact"; - crate::decode::reset_skip_split_tx_hits(); - run_multi_tile_gate(NAME, 0, 0, 8, 1, &[], false, None); - // lane-kf900 r2: the counter assert that used to sit here is - // UNREACHABLE from aomenc. 108 measured recipes (72 at 8-bit, 36 at - // 10-bit: `geq` half-flat/half-noise, `mandelbrot`, `testsrc2`, - // `noise=all_seed=49`, cq 55/59/63, `--cpu-used=0..2`, - // `--enable-tx-size-search=1 --min-partition-size=8 - // --enable-rect-partitions=1`; log - // `$HOME/.cache/kf900/sweep/results{,10}.tsv`) produced - // `skip_split_tx_hits() == 0` on every stream that decoded, because - // libaom's own encoder forces `tx_size` to the block maximum once it - // decides `skip_txfm` -- so no aomenc stream carries a SKIPPED 8x8 - // intra leaf whose `tx_depth` resolved to `TX_4X4`. The film's - // encoder does; the counter is hard-asserted on the real stream in - // [`a_10bit_key_frame_with_skipped_8x8_intra_leaves_that_split_their_transform_decodes_luma_exact`]. - // These two arms stay as the pixel-exact multi-tile control. - } - - /// [`a_real_aomenc_stream_with_a_skipped_8x8_intra_leaf_whose_tx_split_decodes_pixel_exact`]'s - /// 10-bit arm -- the film that exposed the defect is yuv420p10le. - #[test] - fn a_real_aomenc_stream_with_a_skipped_8x8_intra_leaf_whose_tx_split_10bit_decodes_pixel_exact() - { - const NAME: &str = "a_real_aomenc_stream_with_a_skipped_8x8_intra_leaf_whose_tx_split_10bit_decodes_pixel_exact"; - crate::decode::reset_skip_split_tx_hits(); - run_multi_tile_gate(NAME, 0, 0, 10, 1, &[], false, None); - // lane-kf900 r2: the counter assert that used to sit here is - // UNREACHABLE from aomenc. 108 measured recipes (72 at 8-bit, 36 at - // 10-bit: `geq` half-flat/half-noise, `mandelbrot`, `testsrc2`, - // `noise=all_seed=49`, cq 55/59/63, `--cpu-used=0..2`, - // `--enable-tx-size-search=1 --min-partition-size=8 - // --enable-rect-partitions=1`; log - // `$HOME/.cache/kf900/sweep/results{,10}.tsv`) produced - // `skip_split_tx_hits() == 0` on every stream that decoded, because - // libaom's own encoder forces `tx_size` to the block maximum once it - // decides `skip_txfm` -- so no aomenc stream carries a SKIPPED 8x8 - // intra leaf whose `tx_depth` resolved to `TX_4X4`. The film's - // encoder does; the counter is hard-asserted on the real stream in - // [`a_10bit_key_frame_with_skipped_8x8_intra_leaves_that_split_their_transform_decodes_luma_exact`]. - // These two arms stay as the pixel-exact multi-tile control. - } - - #[test] - fn a_real_aomenc_multi_tile_intra_10bit_stream_decodes_pixel_exact() { - run_multi_tile_gate( - "a_real_aomenc_multi_tile_intra_10bit_stream_decodes_pixel_exact", - 2, - 0, - 10, - 1, - &[], - false, - None, - ); - } - - /// lane-t900 r19, the defect this arm exists for, now FIXED: spec 5.11.2 - /// `decode_tile` resets `RefLrWiener`/`RefSgrXqd` (the running - /// loop-restoration coefficient reference) to the midpoint filter at the - /// top of EVERY tile; `decode.rs` declared that state once per frame, so - /// every tile after the first decoded its Wiener/Sgrproj coefficients off - /// the previous tile's reference. The symbol COUNT is unchanged, so - /// entropy and reconstruction stayed byte-exact and only the filtered - /// pixels moved -- at seed 44 frame 0 (the key frame) the whole right tile - /// column, luma x[128..255] y[0..91], 1330 samples off by at most 2, with - /// chroma exact. Ladder that named it: `EC_AV1_PREFILT_DUMP` exact, - /// `EC_AV1_POSTDEBLOCK_DUMP` exact, `EC_AV1_POSTCDEF_DUMP` exact (that - /// last rung added to the oracle's `decodeframe.c` in this round), so the - /// only remaining stage was loop restoration. - #[test] - fn a_real_aomenc_multi_tile_inter_stream_decodes_pixel_exact() { - run_multi_tile_gate( - "a_real_aomenc_multi_tile_inter_stream_decodes_pixel_exact", - 1, - 1, - 8, - 16, - // Pre-existing, non-tile decoder limits this lane does not own: - // the inter path only recurses a superblock as SPLIT (so the SB - // level must be forced to split) and never reads a `tx_depth` - // symbol under `TxMode::Select`. Both are named refusals in - // `refusal_inventory.rs`; without these two flags every inter - // attempt refuses before a single tile edge is compared. - &["--max-partition-size=32", "--enable-tx-size-search=0"], - false, - None, - ); - } - - /// lane-tiles r11, the defect this arm exists for: `palette_ctx_and_cache` - /// / `palette_uv_cache` (`decode.rs`) read the LEFT palette neighbour with - /// no availability guard at all, where libaom's `av1_get_palette_cache` - /// takes `xd->left_mbmi`, which is NULL at the block's own TILE left - /// column. A second tile column therefore inherited the previous tile's - /// palette colours and `palette_y_mode` ctx. Screen content is what makes - /// aomenc pick palette at all, so this arm drives `--tune-content=screen - /// --enable-palette=1` over a 2-column grid and asserts a real palette - /// block actually fired. - /// `#[ignore]`d at r11 and NOT yet proof of the fix: with the broad tool - /// set every seed refuses before a palette block reconstructs - /// ("a HORZ_A/HORZ_B/VERT_A partition below 16x16"), and the per-arm - /// `extra` overrides do not switch the base recipe's tools off -- aomenc - /// keeps the FIRST occurrence of a repeated `--enable-*` flag (measured: - /// appending `--enable-rect-partitions=0` after the base `=1` changed the - /// refusal not at all). Next round: put `extra` BEFORE the base list in - /// `run_multi_tile_gate`'s args, then this arm should reach a palette - /// block on smptebars with rect/ab off. - #[test] - fn a_real_aomenc_multi_tile_palette_stream_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_multi_tile_palette_stream_decodes_pixel_exact"; - let before = crate::decode::palette_hits(); - run_multi_tile_gate( - NAME, - 1, - 0, - 8, - 1, - &[ - "--enable-palette=1", - "--tune-content=screen", - "--cq-level=30", - "--enable-tx-size-search=0", - "--max-partition-size=32", - // Screen content + rect strips is a separate, pre-existing - // refusal ("palette syntax is consumed for square blocks - // only"); this arm owns the palette CACHE at a tile edge, so - // it takes the square-only path the other palette gates take. - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - ], - true, - Some("smptebars"), - ); - if have_ffmpeg() && have_aomenc() { - assert!( - crate::decode::palette_hits() > before, - "{NAME}: no palette block fired -- the gate proves nothing about the palette \ - cache at a tile edge" - ); - } - } - - #[test] - fn a_real_aomenc_multi_tile_inter_10bit_stream_decodes_pixel_exact() { - run_multi_tile_gate( - "a_real_aomenc_multi_tile_inter_10bit_stream_decodes_pixel_exact", - 2, - 0, - 10, - 16, - // Pre-existing, non-tile decoder limits this lane does not own: - // the inter path only recurses a superblock as SPLIT (so the SB - // level must be forced to split) and never reads a `tx_depth` - // symbol under `TxMode::Select`. Both are named refusals in - // `refusal_inventory.rs`; without these two flags every inter - // attempt refuses before a single tile edge is compared. - &["--max-partition-size=32", "--enable-tx-size-search=0"], - false, - None, - ); - } - - /// lane-rectchroma r1: a real `aomenc` stream in which a HORZ/VERT strip - /// splits its transform (`--enable-tx-size-search` left ON) and whose - /// chroma half is one of the four rect shapes that had NO coefficient - /// tables in [`crate::decode`] before this round -- 32x8 / 8x32 (the 1:4 - /// superblock strips 64x16 / 16x64) and 8x4 / 4x8 (the 8x16 / 16x8 rect - /// of a 16x16-level AB partition). Every such strip refused by name - /// ("a coded HORZ/VERT strip whose chroma transform has no rect - /// coefficient tables here"), which is where both ReelC extracts stopped. - /// - /// Per-shape counters, deltas taken only over attempts that then compared - /// pixel-exact (class counter-from-refused-stream), on 8 AND 10 bit (his - /// films are `yuv420p10le`). Odd seeds render the source transposed so - /// the 32x8/8x32 and 8x4/4x8 pairs both fire -- a single-orientation - /// sweep cannot catch a transposed scan table (class - /// scan-weights-cross-axis). - #[test] - fn a_real_aomenc_stream_with_a_coded_strip_whose_chroma_is_a_4to1_or_sub8_rect_decodes_pixel_exact() - { - const NAME: &str = "a_real_aomenc_stream_with_a_coded_strip_whose_chroma_is_a_4to1_or_sub8_rect_decodes_pixel_exact"; - // No seed is excluded any more: seed 46's cq-32 mismatch was the - // per-transform-unit reach (lane-band46 / palette2 r12), and the pin - // below decodes it pixel-exact at both depths. - const EXCLUDED_SEEDS: &[u32] = &[]; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height) = (192usize, 128usize); - let n_attempts: u32 = std::env::var("EC_RECTCHROMA_GATE_ATTEMPTS") - .ok() - .and_then(|s| s.parse().ok()) - .unwrap_or(20); - // 32x8, 8x32, 8x4, 4x8, summed over both bit depths. - let mut proved = [0usize; 4]; - let mut matched = 0u32; - let mut refusals = 0u32; - // Diagnostics: how much of the territory the COMPARED streams carried - // at all, so a zero above reads as "recipe picked nothing" rather - // than "the shape never split" without another run. - let (mut split_strips, mut rect4_strips) = (0usize, 0usize); - let mut all_rect4 = 0usize; - // Asserted separately: this is the gate that takes `enable-1to4- - // partitions` off `gate_coverage::NEVER_EXERCISED_10BIT`, so the - // 10-bit half has to carry the shape on its own. - let mut rect4_strips_10bit = 0usize; - let (mut out_of_scope, mut out_of_scope_mismatch) = (0u32, 0u32); - // 1:4 strips whose transform splits ONCE (the unit is still a 2:1 - // rect) that decoded and compared pixel-exact. Until the rectsplitx - // merge this shape was refused by name and the gate counted the - // REFUSALS; counting the decoded hits instead keeps the same - // territory claim now that the capability landed (class - // counter-from-refused-stream: only attempts that compared exact - // count). - let mut depth1_decoded = 0usize; - for (bit_depth, cq) in [ - (8u32, 45u32), - (8, 32), - (8, 60), - (10, 45), - (10, 32), - (10, 60), - ] { - for attempt in 0..n_attempts { - let seed = 42 + attempt; - if EXCLUDED_SEEDS.contains(&seed) { - continue; - } - let stream = rectchroma_stream(bit_depth, cq, attempt, width, height); - let before = crate::decode::rect_split_chroma_shape_hits(); - let split_before = crate::decode::rect_split_tx_hits(); - let depth1_before = crate::decode::rect4_split_depth_hits().0; - let rect4_before = ( - crate::decode::sb_rect4_horz_hits(), - crate::decode::sb_rect4_vert_hits(), - ); - let frames = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME} failed outright, not a named refusal ({bit_depth}-bit seed \ - {seed}): {msg}" - ); - refusals += 1; - all_rect4 += (crate::decode::sb_rect4_horz_hits() - rect4_before.0) - + (crate::decode::sb_rect4_vert_hits() - rect4_before.1); - let r4 = (crate::decode::sb_rect4_horz_hits() - rect4_before.0) - + (crate::decode::sb_rect4_vert_hits() - rect4_before.1); - eprintln!( - "{NAME}: {bit_depth}-bit cq {cq} seed {seed} refusal (1:4 strips so \ - far {r4}): {msg}" - ); - continue; - } - Ok(frames) => frames, - }; - let after = crate::decode::rect_split_chroma_shape_hits(); - if (0..4).any(|k| after[k] > before[k]) { - eprintln!( - "{NAME}: {bit_depth}-bit cq {cq} seed {seed} carries chroma shapes \ - 32x8={} 8x32={} 8x4={} 4x8={}", - after[0] - before[0], - after[1] - before[1], - after[2] - before[2], - after[3] - before[3] - ); - } - let rect4_now = (crate::decode::sb_rect4_horz_hits() - rect4_before.0) - + (crate::decode::sb_rect4_vert_hits() - rect4_before.1); - // The ENCODE's frame count: `rectchroma_stream` (42059) renders - // `duration=0.04:rate=25` (42082) with `-t 0.04` (42094) -- one - // frame -- and its aomenc runs with no `--limit`, so every - // attempt's stream codes exactly 1 frame at both depths. - assert_eq!( - frames.len(), - 1, - "{NAME}: {bit_depth}-bit cq {cq} seed {seed} key frame" - ); - let reference = if bit_depth == 10 { - ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len()) - } else { - ffmpeg_decode_sequence(&stream, width, height, frames.len()) - }; - assert_eq!(frames.len(), reference.len(), "{NAME}: frame count"); - if rect4_now == 0 { - // Out of this gate's territory (same rule the sibling - // superblock-1:4 gate applies): aomenc picked no 1:4 - // strip at all, so the attempt can neither prove nor - // disprove this round's shape. Counted and PRINTED, never - // silently dropped -- selection is on "the stream carries - // the feature", never on "the stream decoded correctly". - out_of_scope += 1; - if frames - .iter() - .zip(&reference) - .any(|(g, w)| g.y != w.y || g.u != w.u || g.v != w.v) - { - out_of_scope_mismatch += 1; - eprintln!( - "{NAME}: {bit_depth}-bit cq {cq} seed {seed} MISMATCHES with zero \ - 1:4 strips -- a pre-existing defect of another shape, not this \ - gate's arms" - ); - } - continue; - } - for (i, (got, want)) in frames.iter().zip(&reference).enumerate() { - assert_eq!( - got.y, want.y, - "{NAME} frame {i} luma vs ffmpeg ({bit_depth}-bit cq {cq} seed {seed})" - ); - assert_eq!( - got.u, want.u, - "{NAME} frame {i} U vs ffmpeg ({bit_depth}-bit cq {cq} seed {seed})" - ); - assert_eq!( - got.v, want.v, - "{NAME} frame {i} V vs ffmpeg ({bit_depth}-bit cq {cq} seed {seed})" - ); - } - for k in 0..4 { - proved[k] += after[k] - before[k]; - } - split_strips += crate::decode::rect_split_tx_hits() - split_before; - depth1_decoded += crate::decode::rect4_split_depth_hits().0 - depth1_before; - let rect4 = (crate::decode::sb_rect4_horz_hits() - rect4_before.0) - + (crate::decode::sb_rect4_vert_hits() - rect4_before.1); - rect4_strips += rect4; - if bit_depth == 10 { - rect4_strips_10bit += rect4; - } - matched += 1; - } - } - eprintln!( - "{NAME}: {matched} pixel-exact matches, {refusals} named refusals out of \ - {} attempts; chroma shapes proved 32x8={} 8x32={} 8x4={} 4x8={}; compared \ - streams carried {split_strips} split-transform strips and {rect4_strips} \ - superblock 1:4 strips ({all_rect4} more in refused streams); {out_of_scope} \ - attempts carried no 1:4 strip ({out_of_scope_mismatch} of them mismatched -- \ - other shapes' defects)", - 6 * n_attempts, - proved[0], - proved[1], - proved[2], - proved[3] - ); - assert_eq!( - out_of_scope_mismatch, 0, - "{NAME}: {out_of_scope_mismatch} attempts carrying no 1:4 strip mismatched \ - ffmpeg -- a defect of another shape, not out of scope for the suite (the one \ - known case, seed 46, was the per-TU reach and is fixed)" - ); - assert!( - matched > 0, - "{NAME}: every attempt refused; the gate never decoded a stream" - ); - assert!( - rect4_strips_10bit > 0, - "{NAME}: no superblock 1:4 strip in any pixel-exact 10-BIT stream -- this gate is \ - what claims 10-bit coverage for enable-1to4-partitions" - ); - assert!( - rect4_strips > 0, - "{NAME}: no superblock 1:4 strip in any pixel-exact stream -- recipe lost its \ - territory, gate proved nothing this run" - ); - // r1's actual capability delta. Before this round a 1:4 strip whose - // transform depth is 1 was decoded as if its units were SQUARE - // (`bw.min(bh) >> (depth - 1)`), because `sub_tx_size_map[TX_64X16]` - // is TX_32X16, a 2:1 RECT, not TX_16X16 -- 8-bit cq 45 seed 42 of - // this very recipe decoded 2 such strips and MISMATCHED ffmpeg on - // frame 0 luma. It is now refused by name (rect luma transform units - // inside a split strip are unported; the chroma half's 32x8/8x32 - // tables this round wired are in place for it). This assert is what - // keeps that from silently regressing to a wrong-pixel decode. - assert!( - depth1_decoded > 0, - "{NAME}: no attempt decoded a depth-1 1:4 split strip -- the recipe no longer \ - covers the shape this round fixed" - ); - } - - /// PIN for the stream the chroma-rect gate used to exclude: cq 32 seed 46 - /// mismatched ffmpeg at BOTH bit depths while carrying zero 1:4 strips. - /// The defect was the per-transform-unit intra reach (lane-band46 / - /// palette2 r12); un-ignored 2026-09-02 once it decoded pixel-exact. - #[test] - fn the_chroma_rect_gates_excluded_seed_46_decodes_pixel_exact() { - const NAME: &str = "the_chroma_rect_gates_excluded_seed_46_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height) = (192usize, 128usize); - // seed 46 == attempt 4 of the gate's sweep, cq 32. - for bit_depth in [8u32, 10] { - let stream = rectchroma_stream(bit_depth, 32, 4, width, height); - let frames = decode_stream(&stream) - .unwrap_or_else(|e| panic!("{NAME}: {bit_depth}-bit seed 46 refused: {e}")); - // The ENCODE's frame count: `rectchroma_stream` (42059) renders - // `duration=0.04:rate=25` (42082) with `-t 0.04` (42094) -- one frame - // -- and its aomenc runs with no `--limit`, so the stream codes - // exactly 1 frame at both depths. Asserted ABOVE the oracle call. - assert_eq!(frames.len(), 1, "{NAME}: {bit_depth}-bit seed 46 key frame"); - let reference = if bit_depth == 10 { - ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len()) - } else { - ffmpeg_decode_sequence(&stream, width, height, frames.len()) - }; - assert_eq!(frames.len(), reference.len(), "{NAME}: frame count"); - for (i, (got, want)) in frames.iter().zip(&reference).enumerate() { - assert_eq!( - got.y, want.y, - "{NAME} frame {i} luma ({bit_depth}-bit seed 46)" - ); - assert_eq!( - got.u, want.u, - "{NAME} frame {i} U ({bit_depth}-bit seed 46)" - ); - assert_eq!( - got.v, want.v, - "{NAME} frame {i} V ({bit_depth}-bit seed 46)" - ); - } - } - } - - /// lane-band46 r1: a real `aomenc` band stream whose 16x16 (and 8x8) - /// intra blocks SPLIT their transform, so every unit but the first - /// answers `has_top_right`/`has_bottom_left` from its `row_off`/`col_off` - /// inside the parent block rather than from the standalone-block tables - /// (libaom `reconintra.c`; class reach-is-per-transform-unit). - /// - /// Seed 46 of the sibling 1:4-strip recipe is the stream that found it: - /// it carries ZERO 1:4 strips, so that gate skipped it as out of scope - /// while frame 0 luma mismatched ffmpeg over 916 samples -- the first at - /// (x 14, y 18), the second 8x8 transform unit of the D203_PRED block at - /// mi (4, 0), whose bottom-left samples sit in a unit that is not - /// reconstructed yet (`col_off > 0` => `has_bottom_left` is 0). The full - /// mode-info range ladder matched aomdec element for element, so the - /// defect was reconstruction, never entropy. - /// - /// The gate asserts the fix FIRED (`split_tu_reach_fix_hits`, transform - /// units whose reach differs from the old standalone answer) on 8 AND 10 - /// bit, and that seed 46 itself decodes pixel-exact. - #[test] - fn a_real_aomenc_band_stream_seed46_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_band_stream_seed46_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let (width, height) = (192usize, 128usize); - let mut matched = 0u32; - let mut refusals = 0u32; - let mut fixed_tus = 0usize; - let mut fixed_tus_10bit = 0usize; - let mut seed46_compared = [false; 2]; - for (di, bit_depth) in [8u32, 10].into_iter().enumerate() { - let pix_fmt = if bit_depth == 10 { - "yuv420p10le" - } else { - "yuv420p" - }; - for seed in 42u32..=51 { - // Byte-identical recipe to the 1:4-strip sibling gate, whose - // seed-46 attempt is what exposed this defect (that gate - // classes a no-1:4 stream as out of scope; this one compares - // it). - let bands = format!( - "geq=lum='mod(floor(Y/16),2)*160+48':cb=128:cr=128,noise=alls=10:all_seed={seed}" - ); - let source = if seed % 2 == 0 { - format!("color=c=black:size={width}x{height}:duration=0.04:rate=25,{bands}") - } else { - format!( - "color=c=black:size={height}x{width}:duration=0.04:rate=25,{bands},transpose=1" - ) - }; - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-t", - "0.04", - "-pix_fmt", - pix_fmt, - "-strict", - "-1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let depth_arg = format!("--bit-depth={bit_depth}"); - let input_depth_arg = format!("--input-bit-depth={bit_depth}"); - let out = run_with_stdin( - Command::new(aomenc_path()).args([ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=32", - "--cpu-used=0", - "--threads=1", - "--row-mt=0", - "--sb-size=64", - &depth_arg, - &input_depth_arg, - "--enable-rect-partitions=1", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=1", - "--min-partition-size=16", - "--max-partition-size=64", - // Left ON: this is what makes a 16x16 block code four - // 8x8 transform units, the shape the fix is about. - "--enable-tx-size-search=1", - "--enable-restoration=0", - "--enable-palette=0", - "--deltaq-mode=0", - "--enable-filter-intra=0", - "--enable-cfl-intra=0", - "--enable-intrabc=0", - "--obu", - "-o", - "-", - "-", - ]), - &y4m.stdout, - ); - assert!( - out.status.success(), - "{NAME}: aomenc refused the fixture: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = out.stdout; - let before = crate::decode::split_tu_reach_fix_hits(); - let frames = match decode_stream(&stream) { - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME} failed outright, not a named refusal ({bit_depth}-bit seed \ - {seed}): {msg}" - ); - assert!( - seed != 46, - "{NAME}: seed 46 ({bit_depth}-bit) must decode -- it is this gate's \ - pinned stream, and it refused: {msg}" - ); - refusals += 1; - eprintln!("{NAME}: {bit_depth}-bit seed {seed} refusal: {msg}"); - continue; - } - Ok(frames) => frames, - }; - // The ENCODE's frame count: `duration=0.04:rate=25` (42263) is - // one frame and `-t 0.04` (42277) caps the y4m there, and aomenc - // runs with no `--limit` -- so every arm (both depths, all 10 - // seeds) codes exactly 1 frame. Asserted ABOVE the oracle call. - assert_eq!( - frames.len(), - 1, - "{NAME}: {bit_depth}-bit seed {seed} key frame" - ); - let reference = if bit_depth == 10 { - ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len()) - } else { - ffmpeg_decode_sequence(&stream, width, height, frames.len()) - }; - assert_eq!(frames.len(), reference.len(), "{NAME}: frame count"); - for (i, (got, want)) in frames.iter().zip(&reference).enumerate() { - assert_eq!( - got.y, want.y, - "{NAME} frame {i} luma vs ffmpeg ({bit_depth}-bit seed {seed})" - ); - assert_eq!( - got.u, want.u, - "{NAME} frame {i} U vs ffmpeg ({bit_depth}-bit seed {seed})" - ); - assert_eq!( - got.v, want.v, - "{NAME} frame {i} V vs ffmpeg ({bit_depth}-bit seed {seed})" - ); - } - let fixed = crate::decode::split_tu_reach_fix_hits() - before; - fixed_tus += fixed; - if bit_depth == 10 { - fixed_tus_10bit += fixed; - } - if seed == 46 { - seed46_compared[di] = true; - } - matched += 1; - } - } - eprintln!( - "{NAME}: {matched} pixel-exact streams, {refusals} named refusals out of 20; \ - {fixed_tus} split transform units took the per-TU reach ({fixed_tus_10bit} of them \ - 10-bit)" - ); - assert!( - seed46_compared[0] && seed46_compared[1], - "{NAME}: seed 46 was not compared on both depths (8-bit {}, 10-bit {})", - seed46_compared[0], - seed46_compared[1] - ); - assert!( - fixed_tus > 0, - "{NAME}: no split transform unit answered its reach from its offset inside the \ - parent block -- the recipe lost the shape this gate pins" - ); - assert!( - fixed_tus_10bit > 0, - "{NAME}: the shape never appeared in a 10-BIT pixel-exact stream (his films are \ - yuv420p10le)" - ); - } - - /// lane-hgkf r1: a frame whose height (or width) is not a multiple of the - /// block size makes the last superblock row (column) read a GATHERED - /// partition bit instead of a full alphabet symbol -- and libaom's - /// `ec_read_partition_impl` answers that bit with `PARTITION_HORZ` - /// (resp. `VERT`) when it is 0, only `SPLIT` when it is 1. All three - /// key-frame edge readers (64-, 32- and 16-level) read the bit and threw - /// it away, forcing SPLIT; every such frame desynced at the first block - /// of its partial row. 192x136 / 136x192 is the smallest shape that hits - /// all three levels at once (136 = 2*64 + 8, so mi_rows = 34: the 64-, - /// 32- and 16-level halves all fall outside), and it is the shape of a - /// real 3840x1608 10-bit film key frame (1608 mod 64 == 8) that decoded - /// 51768 samples wrong before this round. - /// - /// The counter is sampled per attempt and read only on an attempt that - /// decoded AND is pixel-compared; slot 0/2 (the bit taken as HORZ/VERT) - /// must be nonzero or the gate proves nothing -- before this round that - /// arm was unreachable by construction. - #[test] - fn a_real_aomenc_stream_whose_frame_edge_partition_bit_is_horz_decodes_pixel_exact() { - const NAME: &str = - "a_real_aomenc_stream_whose_frame_edge_partition_bit_is_horz_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - let mut compared = 0usize; - let mut edge_horz_total = 0usize; - let mut edge_sub_total = 0usize; - let mut skip_split_tx_total = 0usize; - // The last two shapes are the ledger-measured 64-level pair: on a - // flat band (192x80 / 80x192) real aomenc answers the bottom-edge - // superblock with the 64-level HORZ/VERT, which the 136 shapes above - // never produce (their SBs always split down to the 32/16 levels). - // lane-kf1200 r3: the 2-/4-/6-mi partial bottom rows (h mod 64 == 8, - // 16, 24) with partial RIGHT columns as well (w mod 64 == 8), the - // geometry of the film key frames this lane chases. - for (width, height, flat) in [ - (192usize, 136usize, false), - (136usize, 192usize, false), - (192usize, 80usize, true), - (80usize, 192usize, true), - (200usize, 72usize, false), - (136usize, 88usize, false), - (264usize, 104usize, false), - ] { - // lane-kf1200 r3 (class `tool-disabled-in-every-gate`): the whole - // recipe ran with `--enable-tx-size-search=0`, so no block ever - // carried a nonzero `tx_depth` and the SKIPPED 8x8 leaf that - // resolves to TX_4X4 -- whose txfm context this round fixed -- - // was unreachable by construction. The second arm turns it on. - for tx_search in [0usize, 1] { - for depth in [8usize, 10] { - let pix = if depth == 10 { - "yuv420p10le" - } else { - "yuv420p" - }; - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &if flat { - format!("color=c=gray:size={width}x{height}") - } else { - format!("mandelbrot=size={width}x{height}:start_x=-0.6") - }, - "-pix_fmt", - pix, - "-strict", - "-1", - "-t", - "1", - "-vframes", - "1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "{NAME}: ffmpeg fixture ({width}x{height}, depth={depth}): {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let encode = || { - let out = run_with_stdin( - Command::new(aomenc_path()).args([ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=32", - "--cpu-used=3", - "--threads=1", - "--row-mt=0", - "--sb-size=64", - "--kf-max-dist=0", - "--enable-rect-partitions=1", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - &format!("--enable-tx-size-search={tx_search}"), - "--reduced-tx-type-set=1", - "--min-partition-size=8", - "--max-partition-size=64", - &format!("--input-bit-depth={depth}"), - &format!("--bit-depth={depth}"), - "--obu", - "-o", - "-", - "-", - ]), - &y4m.stdout, - ); - assert!( - out.status.success(), - "aomenc refused the fixture ({width}x{height}, depth={depth}): {}", - String::from_utf8_lossy(&out.stderr) - ); - out.stdout - }; - let stream = encode(); - assert_eq!( - stream, - encode(), - "{NAME}: aomenc output is not reproducible ({width}x{height}, depth={depth})" - ); - crate::decode::reset_edge_part_hits(); - crate::decode::reset_skip_split_tx_hits(); - let frames = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME}: decode failed ({width}x{height}, depth={depth}): {msg}" - ); - eprintln!( - "{NAME}: {width}x{height} depth={depth} arm refused (not compared): {msg}" - ); - continue; - } - }; - let hits = crate::decode::edge_part_hits(); - let skip_split_tx = crate::decode::skip_split_tx_hits(); - // The ENCODE's frame count: `-t 1` AND `-vframes 1` (42490) - // cap the y4m at one frame and aomenc is given that one frame - // with no `--limit`, so every arm's stream holds exactly 1 - // coded frame. Asserted ABOVE the oracle call so a decode that - // dropped it reds naming the encode. - assert_eq!( - frames.len(), - 1, - "{NAME}: {width}x{height} depth={depth} key frame" - ); - let ffmpeg_frames = if depth == 10 { - ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len()) - } else { - ffmpeg_decode_sequence(&stream, width, height, frames.len()) - }; - assert_eq!( - ffmpeg_frames.len(), - frames.len(), - "{NAME}: ffmpeg frame count" - ); - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!( - got.y, want.y, - "{NAME} frame {i} luma vs ffmpeg ({width}x{height}, depth={depth}, \ - edge bits horz/split 64-level {}/{}, sub-level {}/{})", - hits[0], hits[1], hits[2], hits[3] - ); - assert_eq!( - got.u, want.u, - "{NAME} frame {i} U vs ffmpeg ({width}x{height}, depth={depth})" - ); - assert_eq!( - got.v, want.v, - "{NAME} frame {i} V vs ffmpeg ({width}x{height}, depth={depth})" - ); - } - compared += 1; - edge_horz_total += hits[0]; - edge_sub_total += hits[2]; - skip_split_tx_total += skip_split_tx; - eprintln!( - "{NAME}: pixel-exact {width}x{height} at {depth}-bit tx_search={tx_search}, \ - edge bits 64-level horz/vert={} split={} sub-level horz/vert={} split={}, \ - skipped 8x8 leaves with TX_4X4 {skip_split_tx}", - hits[0], hits[1], hits[2], hits[3] - ); - } - } - } - assert!( - compared > 0, - "{NAME}: every arm refused -- the gate compared no pixels at all" - ); - assert!( - edge_horz_total > 0, - "{NAME}: no 64-level frame-edge bit was ever answered HORZ/VERT -- the arm this \ - round fixed never fired" - ); - assert!( - edge_sub_total > 0, - "{NAME}: no 32/16-level frame-edge bit was ever answered HORZ/VERT" - ); - // lane-kf1200 r3: the `--enable-tx-size-search=1` half of the window - // exists so a partial-row block can carry a nonzero `tx_depth` at all - // (the whole recipe ran with it OFF before -- class - // `tool-disabled-in-every-gate`). The SKIPPED 8x8 leaf that resolves - // to TX_4X4 -- whose txfm context this round fixed -- is NOT reachable - // from any synthetic source measured here (80 recipes, all zero), so - // that arm is asserted by the pinned film fixture - // `the_reelb_ss600_key_frame_skipped_split_tx_decodes_pixel_exact` - // instead; this counter is reported, not gated. - eprintln!( - "{NAME}: {skip_split_tx_total} skipped 8x8 TX_4X4 leaves across compared attempts" - ); - } - - /// lane-rectchroma2 r1, the defect this gate exists for: our inter path - /// predicts a RECTANGULAR block over its enclosing SQUARE buffer - /// (`side`x`side`, `chroma_side`x`chroma_side` -- see - /// [`crate::decode`]'s `write_w`/`write_h` corner-cut), and - /// [`crate::mc::predict_with_filters`] took libaom's narrow-block 4-tap - /// decision from that buffer's dimensions. libaom - /// (`av1_get_interp_filter_params_with_block_size`, called per axis from - /// `inter_predictor` with `w` then `h`) takes it from the PREDICTION - /// block's own dimensions, so an 8x16 / 16x8 inter block -- whose chroma - /// is 4x8 / 8x4 -- must use the 4-tap kernel on the short axis. Luma is - /// never <= 4 wide here, which is exactly why every such stream decoded - /// LUMA EXACT and differed by +-1 on scattered chroma samples of those - /// blocks (lane-interedge r1's 192x128 control, a size with no frame-edge - /// node at all). - /// - /// Full-plane (Y+U+V) compare of EVERY decode-order frame - /// (`--lag-in-frames=0`), both orientations (192x128 and its transposed - /// twin, so the 4x8 and 8x4 chroma shapes both fire -- class - /// `scan-weights-cross-axis`), 8 AND 10 bit (his films are yuv420p10le), - /// cq 20/32/45, CDEF and loop restoration left ON. The counter is reset - /// per attempt and read only on an attempt that decoded and compared - /// (class `counter-from-refused-stream`); it counts predictions whose - /// kernel choice DIFFERS from what the square buffer would have given, so - /// a zero means the recipe lost the shape this gate pins. - #[test] - fn a_real_aomenc_rect_inter_block_predicts_chroma_with_the_narrow_kernel_pixel_exact() { - const NAME: &str = - "a_real_aomenc_rect_inter_block_predicts_chroma_with_the_narrow_kernel_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); - return; - } - const FRAMES: usize = 6; - let mut compared = 0usize; - let mut narrow_by_depth = [0usize; 2]; - let mut narrow_by_shape = [0usize; 2]; - for (si, (width, height)) in [(192usize, 128usize), (128usize, 192usize)] - .into_iter() - .enumerate() - { - for (di, depth) in [8usize, 10].into_iter().enumerate() { - let pix = if depth == 10 { - "yuv420p10le" - } else { - "yuv420p" - }; - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &format!("mandelbrot=size={width}x{height}:rate=25"), - "-pix_fmt", - pix, - "-strict", - "-1", - "-vframes", - &FRAMES.to_string(), - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "{NAME}: ffmpeg fixture ({width}x{height}, depth={depth}): {}", - String::from_utf8_lossy(&y4m.stderr) - ); - for cq in [20usize, 32, 45] { - let encode = || { - let out = run_with_stdin( - Command::new(aomenc_path()).args([ - "--codec=av1", - "--passes=1", - "--end-usage=q", - &format!("--cq-level={cq}"), - "--cpu-used=4", - "--threads=1", - "--row-mt=0", - "--kf-max-dist=9999", - &format!("--limit={FRAMES}"), - "--lag-in-frames=0", - &format!("--bit-depth={depth}"), - &format!("--input-bit-depth={depth}"), - // Rect partitions ON is the whole point; every - // other tool below is another lane's open gap - // that would refuse before a pixel compare. - "--enable-rect-partitions=1", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--min-partition-size=8", - "--max-partition-size=64", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-warped-motion=0", - "--enable-obmc=0", - "--enable-masked-comp=0", - "--enable-interintra-comp=0", - "--enable-onesided-comp=0", - "--enable-interintra-wedge=0", - "--enable-smooth-interintra=0", - "--enable-ref-frame-mvs=0", - "--enable-angle-delta=0", - "--enable-cfl-intra=0", - "--enable-directional-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-filter-intra=0", - "--enable-tx-size-search=0", - "--obu", - "-o", - "-", - "-", - ]), - &y4m.stdout, - ); - assert!( - out.status.success(), - "aomenc refused the fixture ({width}x{height}, depth={depth}, \ - cq={cq}): {}", - String::from_utf8_lossy(&out.stderr) - ); - out.stdout - }; - let stream = encode(); - assert_eq!( - stream, - encode(), - "{NAME}: aomenc output is not reproducible ({width}x{height}, \ - depth={depth}, cq={cq})" - ); - crate::mc::reset_rect_narrow_kern_hits(); - let frames = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => { - let msg = e.to_string(); - assert!( - msg.contains("unsupported"), - "{NAME}: decode failed ({width}x{height}, depth={depth}, \ - cq={cq}): {msg}" - ); - eprintln!( - "{NAME}: {width}x{height} depth={depth} cq={cq} arm refused \ - (not compared): {msg}" - ); - continue; - } - }; - let narrow = crate::mc::rect_narrow_kern_hits(); - // The ENCODE's frame count, asserted ABOVE the oracle call, not - // our decode's length: `-vframes {FRAMES}` (42696) feeds aomenc - // exactly FRAMES frames and `--limit={FRAMES}` (42724) caps its - // output there. A decode that dropped a frame must red HERE, - // naming the encode, rather than hand the same short count to - // ffmpeg and let the helper's byte-length assert blame ffmpeg. - assert_eq!( - frames.len(), - FRAMES, - "{NAME}: not every coded frame was decoded ({width}x{height}, \ - depth={depth}, cq={cq})" - ); - let ffmpeg_frames = if depth == 10 { - ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len()) - } else { - ffmpeg_decode_sequence(&stream, width, height, frames.len()) - }; - assert_eq!( - ffmpeg_frames.len(), - frames.len(), - "{NAME}: ffmpeg frame count ({width}x{height}, depth={depth}, cq={cq})" - ); - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!( - got.y, want.y, - "{NAME} frame {i} luma vs ffmpeg ({width}x{height}, depth={depth}, \ - cq={cq}, narrow-kernel hits {narrow})" - ); - assert_eq!( - got.u, want.u, - "{NAME} frame {i} U vs ffmpeg ({width}x{height}, depth={depth}, \ - cq={cq}, narrow-kernel hits {narrow})" - ); - assert_eq!( - got.v, want.v, - "{NAME} frame {i} V vs ffmpeg ({width}x{height}, depth={depth}, \ - cq={cq}, narrow-kernel hits {narrow})" - ); - } - compared += 1; - narrow_by_depth[di] += narrow; - narrow_by_shape[si] += narrow; - eprintln!( - "{NAME}: {width}x{height} depth={depth} cq={cq} {} frames full-plane \ - exact, narrow-kernel hits {narrow}", - frames.len() - ); - } - } - } - assert_eq!( - compared, 12, - "{NAME}: only {compared} of 12 arms were pixel-compared -- a refusal makes this \ - gate vacuous" - ); - assert!( - narrow_by_depth[0] > 0 && narrow_by_depth[1] > 0, - "{NAME}: no rect-chroma narrow kernel fired at 8-bit ({}) or 10-bit ({}) -- the \ - recipe lost the shape this gate pins", - narrow_by_depth[0], - narrow_by_depth[1] - ); - assert!( - narrow_by_shape[0] > 0 && narrow_by_shape[1] > 0, - "{NAME}: the shape fired in only one orientation (192x128 {}, 128x192 {})", - narrow_by_shape[0], - narrow_by_shape[1] - ); - } - - /// lane-intra14 r1's decisive gate: a real aomenc INTER sequence with - /// `--enable-1to4-partitions=1`, whose fast-zooming content makes aomenc - /// code INTRA blocks inside inter frames on 1:4 strip shapes (32x8/8x32 at - /// the 32 level, 64x16/16x64 at the superblock level). Every such block - /// was the named refusal "an intra-coded 1:4 (or other non-2:1) rect strip - /// on the inter block path" until this round; they now decode through the - /// same `decode_block_rect4` / `decode_block_rect64` readers the KEY FRAME - /// 1:4 paths already prove, with only the mode-info read switched to - /// `read_intra_block_mode_info` (libaom decodemv.c:1189). - /// - /// Hard-asserts `intra_rect4_strip_in_inter_hits` (0 = 64x16, 1 = 16x64, - /// 2 = 32x8, 3 = 8x32) on the one pinned recipe below, and every - /// decode-order frame is compared. A decode that succeeds is ALWAYS - /// pixel-compared (class [[gate-skips-on-its-own-failure]]), and a recipe - /// that decodes exact without a counted strip is a FAILURE, never a pass. - /// The recipe, the pin and the `--enable-1to4-partitions=0` control arm - /// are documented on [`intra_rect4_in_inter_gate`]. - #[test] - // CLOSED by lane-av1recipehunt r1 (un-ignored). Two independent runs agree - // on why this gate was blind, and they are worth keeping side by side. - // - // lane-av1pins RE-RAN this gate in RELEASE on a21f3680 (the seven-lane - // merged tree) and found BOTH halves of the r2 record stale: - // * THE PIXEL BLOCKER IS GONE -- `counted-exact=0 uncounted-exact=40 - // named-refusals=0 (attempts 40)` at both bit depths, and not one - // mismatch line anywhere in the run log. 40/40 pixel-exact. - // * THE RECIPE NEVER FIRES -- every counted attempt reads - // `64x16=0 16x64=0 32x8=0 8x32=0`, so the assert trips on its - // non-vacuity precondition, not on any pixel. - // - // lane-av1recipehunt then found WHY, and closed it. The blindness is not - // the r2 "pre-existing INTER-frame pixel defect" (gone) and not the - // mandelbrot source: the old recipe produced ZERO 1:4 strips of ANY shape - // at ANY level, because `--min-partition-size=32` with an all-but-empty - // intra mode set never puts a 1:4 partition on aomenc's RD menu. - // MEASURED: the 32-level 1:4 counter is 0 in ALL 48 attempts at - // `--min-partition-size=16` and fires in 40 of 48 at 8 with - // `--enable-smooth-intra/paeth-intra/directional-intra/angle-delta=1` - // (a 32x8/8x32 strip needs an intra mode WORTH CODING; with those four - // off the only candidate is DC, and DC never wins a 1:4 strip against - // inter). That also explains r2's "`--enable-1to4-partitions=0` is - // byte-identical": with no 1:4 reachable at all, the flag had nothing to - // turn off. The new recipe is 256x192x6, `--min-partition-size=8`, the - // full intra mode set, `--cpu-used=2 --cq-level=63`; it fires 32x8=8 - // 8x32=11 and is pixel-exact on all 6 frames. See - // [`intra_rect4_in_inter_gate`] for the pin and the flag control arm. - fn a_real_aomenc_inter_sequence_with_an_intra_1to4_strip_decodes_pixel_exact() { - intra_rect4_in_inter_gate(8); - } - - /// The 10-bit arm (both of the user's films are `yuv420p10le`). - #[test] - // CLOSED by lane-av1recipehunt r1 (un-ignored), same recipe and same two - // reasons as the 8-bit arm above: lane-av1pins' RELEASE re-run showed the - // pixel blocker gone and the recipe never firing, and the root cause is - // `--min-partition-size=32` plus the pruned intra mode set, not the - // mandelbrot source. The 10-bit cell fires 32x8=12 8x32=7 and is - // pixel-exact on all 6 frames. - fn a_real_aomenc_inter_sequence_with_an_intra_1to4_strip_decodes_pixel_exact_10bit() { - intra_rect4_in_inter_gate(10); - } - - /// lane-intrasplit r1's decisive gate: a real aomenc INTER sequence in - /// which aomenc's RD picks an intra-coded HORZ/VERT *strip* (a 2:1 - /// rectangular partition) inside an inter frame AND splits its luma - /// transform (`tx_depth >= 1`). Until this round that block was the named - /// refusal "a split (nonzero tx_depth) transform on an intra HORZ/VERT - /// strip in an inter frame"; it now walks the key frame's own per-TU path - /// ([`decode::decode_rect_split`]). Hard-asserts - /// [`decode::intra_rect_in_inter_split_tx_hits`] per depth: an attempt - /// that never produced such a block proves nothing, and exhausting every - /// attempt is a FAILURE, not a SKIP. - #[test] - fn a_real_aomenc_inter_sequence_with_a_split_transform_intra_strip_decodes_pixel_exact() { - intra_rect_in_inter_split_tx_gate(8); - } - - /// The 10-bit arm (both of the user's films are `yuv420p10le`). - #[test] - fn a_real_aomenc_10bit_inter_sequence_with_a_split_transform_intra_strip_decodes_pixel_exact() { - intra_rect_in_inter_split_tx_gate(10); - } - - /// lane-t900 r21: the witness for the palette SYNTAX on a rect intra strip - /// inside a screen-content INTER frame. - /// - /// `read_palette_mode_info` is gated by the frame's - /// `allow_screen_content_tools` and by the block's own shape - /// (`palette_bsize_ctx_wh`: `min(w,h) >= 8`, `max(w,h) <= 64`), - /// with no square-only term -- so a `--tune-content=screen` inter frame - /// writes `palette_y_mode` (and `palette_uv_mode`) for an 8x16 or 16x8 - /// intra strip exactly as for a square block. This decoder's inter-path - /// intra arm skipped both symbols and refused the whole case by name ("a - /// HORZ/VERT intra strip in a screen-content frame (palette syntax is - /// consumed for square blocks only)"), which a real stream reached: - /// measured with `decode_probe`, `testsrc2` 256x192 at - /// `--tune-content=screen --enable-palette=0 --enable-intrabc=0` stops on - /// that refusal at an 8x16 strip (8-bit) / a 16x8 one (10-bit). - /// - /// Both arms now decode all ten frames pixel-exact against ffmpeg, and - /// [`decode::intra_rect_in_inter_screen_hits`] counts the strips that read - /// the syntax -- hard-asserted, because an attempt with no such strip - /// proves nothing about the case the refusal named. - /// - /// Note `--enable-palette=0`: the encoder's palette SEARCH is what this - /// gate must switch off, not the syntax. With it on, the key frame codes - /// a block that really uses a palette and stops on the separate, - /// still-live "a block that actually uses a palette (Y)" refusal before - /// any inter frame is reached (class `refusal-hides-a-defect`, measured on - /// six such encodes). - #[test] - fn a_real_aomenc_screen_inter_sequence_codes_palette_syntax_on_rect_intra_strips() { - screen_rect_intra_palette_syntax_gate(8); - } - - /// The 10-bit arm (both of the user's films are `yuv420p10le`). - #[test] - fn a_real_aomenc_10bit_screen_inter_sequence_codes_palette_syntax_on_rect_intra_strips() { - screen_rect_intra_palette_syntax_gate(10); - } - - /// lane-intra14 r4: the FILM witness for an intra block on a 1:4 partition - /// inside an INTER frame -- `crates/ec-av1/fixtures/reelb_intra14_witness.obu`, - /// 163057 bytes, sha256 - /// `0eff603bf1608e47faf5e6729670c4c77cf5c674dbad3a1533ac6660151fd90e`, - /// two decode-order frames (key + first inter) cut from two INDEPENDENT - /// `ffmpeg -ss 90 -t 2 -i <3840x1608 10-bit AV1 HDR10 mkv> -c:v copy -f obu` - /// runs that hashed identically. - /// - /// MEASURED (r4, 27 two-second segments of that film at ss 0..6000, probe - /// logs in the report): no aomenc recipe reaches this shape and only ONE - /// class of stream does -- the film's own inter frames. Decode-order frame - /// 1 of this fixture codes 3 intra 16x64 strips (`intra_rect4_in_inter` - /// 16x64=3, zero when the fixture is truncated to the key frame alone), so - /// the counter attribution is pinned to that frame. - /// - /// It is `#[ignore]`d for exactly ONE reason, and not this lane's shape: - /// that same frame stops at a SIBLING refusal, "a split intra strip whose - /// transform unit is 64x32 (no luma coefficient tables for that shape - /// here)". The moment TX_64X32/TX_32X64 luma coefficient tables land, drop - /// the `#[ignore]` -- everything else this gate needs (the reader, the - /// counter, the two-frame pixel compare) is in place and runs. - /// - /// lane-sub8x4 r3: un-`#[ignore]`d. The sibling refusal it waited on (the - /// un-split TX_64X32/TX_32X64 corner unit) is lifted in this round, so the - /// frame this gate exists for now finishes. - /// - /// lane-wit16x4 r1, MEASURED: this gate is blind to the frame it counts - /// (class `gate-blind-to-hidden-frames`). The fixture has two frame OBUs - /// and ONE shown frame, and `decode_probe` on the fixture truncated to its - /// first frame OBU reads `intra_rect4_in_inter 0/0/0/0` and - /// `intra16x4_in_inter 0/0/0` while matching ffmpeg exactly -- so all of - /// 4/23/28/72 (and the 4 intra 16x4 strips with them) live in the SECOND, - /// NO-SHOW frame, whose pixels ffmpeg never emits and this gate never - /// compares. Since that hidden frame also carries the intra 16x4/4x16 - /// strip whose refusal this round re-adds (no stream anywhere decodes - /// pixel-exact while that arm fires -- lanes/wit16x4-r1.report.md), the - /// decode now stops by name here. Un-ignored 2026-09-04: that re-added intra 16x4/4x16-in-inter refusal is gone and the gate passes. - #[test] - fn a_10bit_film_inter_frame_with_intra_1to4_strips_decodes_pixel_exact() { - const NAME: &str = "a_10bit_film_inter_frame_with_intra_1to4_strips_decodes_pixel_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("fixtures/reelb_intra14_witness.obu"); - let stream = std::fs::read(&path) - .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display())); - let (width, height) = (3840usize, 1608usize); - let before = intra_rect4_in_inter_counters(); - let frames = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => panic!("{NAME}: decode_stream refused: {e}"), - }; - let now = intra_rect4_in_inter_counters(); - let fired = - (now.0 - before.0) + (now.1 - before.1) + (now.2 - before.2) + (now.3 - before.3); - assert!( - fired > 0, - "{NAME}: zero intra 1:4 strips in an inter frame (64x16/16x64/32x8/8x32 = \ - {}/{}/{}/{}) -- the fixture stopped carrying the shape this gate exists for", - now.0 - before.0, - now.1 - before.1, - now.2 - before.2, - now.3 - before.3 - ); - // lane-sub8x4 r3, MEASURED when this gate first RAN: the fixture has - // TWO frame OBUs but only ONE SHOWN frame -- a raw - // `ffmpeg -i -pix_fmt yuv420p10le -f rawvideo` writes exactly - // 18524160 bytes, one 3840x1608 10-bit frame, so the second is a - // no-show frame and `frames.len() == 2` was never true. The compare is - // not vacuous: ffmpeg's own frame count is asserted equal to ours. - assert_eq!( - frames.len(), - 1, - "{NAME}: one shown frame (the second frame OBU is a no-show)" - ); - assert_eq!((frames[0].width, frames[0].height), (width, height)); - let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len()); - assert_eq!( - ffmpeg_frames.len(), - frames.len(), - "{NAME}: ffmpeg returned {} frames, we decoded {}", - ffmpeg_frames.len(), - frames.len() - ); - for (i, (ours, theirs)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!(ours.y, theirs.y, "{NAME}: frame {i} luma vs ffmpeg"); - assert_eq!(ours.u, theirs.u, "{NAME}: frame {i} U vs ffmpeg"); - assert_eq!(ours.v, theirs.v, "{NAME}: frame {i} V vs ffmpeg"); - } - eprintln!( - "{NAME}: {fired} intra 1:4 strips in an inter frame, the shown frame pixel-exact" - ); - } - - /// lane-sub8x4 r3 / lane-wit16x4 r1: the FILM witness for the un-split - /// TX_64X32/TX_32X64 corner unit of a split intra strip. - /// - /// r3 wrote this gate as a witness for TWO arms; its intra 16x4/4x16 - /// numbers were PHANTOMS (class `counter-from-refused-stream`), counted - /// while decode-order frame 33 of this very prefix was desynced. On the - /// merged tip (lane-frame36 r2 fixed that desync) the fixture decodes all - /// 33 frames pixel-exact and `intra16x4_in_inter` reads 0/0/0, so the gate - /// panicked "the intra 16x4/4x16 strip arm did not fire". lane-wit16x4 r1 - /// re-measured every counter, split the claim, and re-added the - /// 16x4/4x16-in-inter refusal (no stream on this tree decodes exactly - /// while that arm fires -- see the note at `decode.rs`'s `strip16`). - /// - /// `crates/ec-av1/fixtures/reelb_rect64_intra16x4_witness.obu`, 23472 bytes, - /// sha256 `c9e721088766163b9dbeb9fa8dd8b257ff0ec7f9157fc350de4d3c33cd9ec4e4`: - /// the first 50 frame-carrying OBUs of `ffmpeg -ss 0 -t 2 -i <3840x1608 - /// 10-bit AV1 HDR10 mkv> -c:v copy -f obu`, cut twice from independent - /// ffmpeg runs that hashed identically. 33 decode-order frames. - /// - /// MEASURED on the merged tip (`decode_probe`, EC_PROBE_OUT16 vs - /// `ffmpeg -pix_fmt yuv420p10le`): all 33 frames 0 differing bytes, and - /// `rect64_corner_tu` fires 64x32=148 32x64=123 (r3's 90/5 came out of the - /// desynced decode). `intra16x4_in_inter` reads 0/0/0 here and is asserted - /// as such -- if a later change makes that arm fire on this stream, the - /// refusal that now guards it moved and this gate says so. - /// - /// Refusal strings: "a split intra strip whose transform unit is - /// {tx_w}x{tx_h}" stays NARROWED (every shape other than 64x32/32x64 -- - /// that is what this gate lifts), and "an intra 16x4/4x16 strip inside an - /// inter 16x16-level 1:4 partition" is back to its FULL width. - #[test] - fn a_10bit_film_frames_with_rect64_corner_tus_decode_pixel_exact() { - const NAME: &str = "a_10bit_film_frames_with_rect64_corner_tus_decode_pixel_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("fixtures/reelb_rect64_intra16x4_witness.obu"); - let stream = std::fs::read(&path) - .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display())); - let (width, height) = (3840usize, 1608usize); - let before16 = crate::decode::intra16x4_in_inter_hits(); - let before64 = ( - crate::decode::rect64_corner_tu_hits(0), - crate::decode::rect64_corner_tu_hits(1), - ); - let frames = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => panic!("{NAME}: decode_stream refused: {e}"), - }; - let now16 = crate::decode::intra16x4_in_inter_hits(); - let fired16 = ( - now16.0 - before16.0, - now16.1 - before16.1, - now16.2 - before16.2, - ); - let fired64 = ( - crate::decode::rect64_corner_tu_hits(0) - before64.0, - crate::decode::rect64_corner_tu_hits(1) - before64.1, - ); - // Hard counter asserts: the lift may not rest on a stream that stopped - // carrying its shape (class `tool-disabled-in-every-gate`). - assert_eq!( - fired16, - (0, 0, 0), - "{NAME}: this stream carries NO intra 16x4/4x16 strip in an inter 1:4 \ - partition (r3's 31/17/23 were phantoms of the frame-33 desync); a \ - non-zero count here means the refusal guarding that arm moved" - ); - assert!( - fired64.0 > 0 && fired64.1 > 0, - "{NAME}: the un-split TX_64X32/TX_32X64 corner arm did not fire (64x32={} 32x64={})", - fired64.0, - fired64.1 - ); - assert_eq!(frames.len(), 33, "{NAME}: 33 decode-order frames"); - assert_eq!((frames[0].width, frames[0].height), (width, height)); - let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len()); - assert_eq!( - ffmpeg_frames.len(), - frames.len(), - "{NAME}: ffmpeg returned {} frames, we decoded {}", - ffmpeg_frames.len(), - frames.len() - ); - for (i, (ours, theirs)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!(ours.y, theirs.y, "{NAME}: frame {i} luma vs ffmpeg"); - assert_eq!(ours.u, theirs.u, "{NAME}: frame {i} U vs ffmpeg"); - assert_eq!(ours.v, theirs.v, "{NAME}: frame {i} V vs ffmpeg"); - } - eprintln!( - "{NAME}: 33 frames pixel-exact, rect64_corner_tu 64x32={} 32x64={} \ - (intra16x4_in_inter {} {} {}, refused shape)", - fired64.0, fired64.1, fired16.0, fired16.1, fired16.2 - ); - } - - /// lane-thread2 (iv): frame-parallel decoding changes nothing a caller - /// can observe. Two real streams are decoded through - /// [`decode_stream_with_threads`] at 1 and at 4 threads and every sink - /// call is compared -- decode index, shown flag, and all three planes. - /// - /// `reelb_arf_witness.obu` is the one that proves the parallel path: it - /// carries hidden alt-refs, which is exactly the case where "output in - /// coded order" is not the same as "output in the order workers finish", - /// and under lane-thread3's dependency-aware scheduling 39 of its 40 - /// coded frames (all but the key frame) are decoded off the main thread - /// -- MORE than its 37 shown frames, which is the point: lane-thread2's - /// leaf rule dispatched 18. `palette_screen_witness.obu` is the - /// complement, an 8-bit screen stream whose every coded frame refreshes a - /// slot: lane-thread2 dispatched NOTHING for it, lane-thread3 dispatches - /// all 14 of its non-key frames. Both counts are asserted exactly, plus - /// the "more than half the shown frames really ran on a worker" bound, so - /// neither arm can pass vacuously. - #[test] - fn a_real_stream_decodes_identically_with_one_and_four_threads() { - const NAME: &str = "a_real_stream_decodes_identically_with_one_and_four_threads"; - // (fixture, shown frames, frames a 4-thread run must dispatch) - for (fixture, shown_frames, want_dispatched) in [ - ("fixtures/reelb_arf_witness.obu", 37usize, 39usize), - ("fixtures/palette_screen_witness.obu", 15, 14), - ] { - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join(fixture); - let stream = std::fs::read(&path) - .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display())); - let run = |threads: usize| -> Vec<(usize, bool, Picture)> { - let mut out = Vec::new(); - decode_stream_with_threads(&stream, threads, |p, idx, shown| { - out.push((idx, shown, p.clone())); - Ok(()) - }) - .unwrap_or_else(|e| panic!("{NAME}: {fixture} at {threads} threads refused: {e}")); - out - }; - let serial = run(1); - let before = frames_dispatched(); - let parallel = run(4); - let dispatched = frames_dispatched() - before; - assert_eq!( - dispatched, want_dispatched, - "{NAME}: {fixture} dispatched {dispatched} frames to workers, expected {want_dispatched}" - ); - assert!( - dispatched * 2 > shown_frames, - "{NAME}: {fixture} dispatched {dispatched} frames, not even half of its {shown_frames} shown frames -- the parallel path is barely exercised" - ); - assert_eq!( - serial.iter().filter(|f| f.1).count(), - shown_frames, - "{NAME}: {fixture} shown frames" - ); - assert_eq!( - serial.len(), - parallel.len(), - "{NAME}: {fixture} sink call count differs" - ); - for (i, (a, b)) in serial.iter().zip(¶llel).enumerate() { - assert_eq!(a.0, b.0, "{NAME}: {fixture} sink {i} decode index"); - assert_eq!(a.1, b.1, "{NAME}: {fixture} sink {i} shown flag"); - assert_eq!(a.2.y, b.2.y, "{NAME}: {fixture} sink {i} luma"); - assert_eq!(a.2.u, b.2.u, "{NAME}: {fixture} sink {i} U"); - assert_eq!(a.2.v, b.2.v, "{NAME}: {fixture} sink {i} V"); - } - eprintln!( - "{NAME}: {fixture} {} sink calls identical, {dispatched} decoded on workers", - serial.len() - ); - } - } - - /// lane-frame36 r2: the hidden-ARF witness. `crates/ec-av1/fixtures/ - /// reelb_arf_witness.obu`, 32126 bytes, sha256 - /// `7f3b060da5aa9c537633e760c4af71316237db7692f6ae0d459bd2c2dd867d37`: - /// the first 58 frame-carrying OBUs of a 2 s head cut of the 10-bit - /// 3840x1608 AV1 HDR10 stream, 40 decode-order frames, 37 shown. - /// - /// What it covers that no earlier fixture did: decode-order frame 33 is a - /// HIDDEN alt-ref (`show_frame=0`, order_hint 64, `cdef_bits=1`, loop - /// restoration `[Switchable, Sgrproj, Switchable]`, `skip_mode_frame` - /// [1,6]) -- the first frame of the stream carrying a SPLIT - /// superblock-level intra strip in an inter frame. Its 16x64 strip at - /// mi(192,140) reads `tx_depth=1` (TX_16X32), and until this round - /// [`decode_block_rect64`]'s split arm returned past the tail that - /// publishes the `TXFM_CONTEXT` bands, so the 32x64 block at mi(192,144) - /// read the row's init value 64 as its left transform height and took - /// `tx_size_cat3` row 2 where aomdec takes row 1 -- a desync no shown - /// frame exposed until the ARF was displayed (class - /// `gate-blind-to-hidden-frames`). - /// - /// The counter assert is on `rect64_split_txfm_publish_hits`, the split - /// arm that was silent, so a stream that stopped carrying the shape fails - /// the gate instead of passing it vacuously. - #[test] - fn a_10bit_film_hidden_arf_with_split_superblock_strips_decodes_pixel_exact() { - const NAME: &str = - "a_10bit_film_hidden_arf_with_split_superblock_strips_decodes_pixel_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - let path = - std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures/reelb_arf_witness.obu"); - let stream = std::fs::read(&path) - .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display())); - let (width, height) = (3840usize, 1608usize); - let before = crate::decode::rect64_split_txfm_publish_hits(); - let frames = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => panic!("{NAME}: decode_stream refused: {e}"), - }; - let fired = crate::decode::rect64_split_txfm_publish_hits() - before; - assert!( - fired > 0, - "{NAME}: no split superblock-level strip in the stream -- the gate would be vacuous" - ); - assert_eq!(frames.len(), 37, "{NAME}: 37 shown frames"); - assert_eq!((frames[0].width, frames[0].height), (width, height)); - let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len()); - assert_eq!( - ffmpeg_frames.len(), - frames.len(), - "{NAME}: ffmpeg returned {} frames, we decoded {}", - ffmpeg_frames.len(), - frames.len() - ); - for (i, (ours, theirs)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!(ours.y, theirs.y, "{NAME}: frame {i} luma vs ffmpeg"); - assert_eq!(ours.u, theirs.u, "{NAME}: frame {i} U vs ffmpeg"); - assert_eq!(ours.v, theirs.v, "{NAME}: frame {i} V vs ffmpeg"); - } - eprintln!( - "{NAME}: 37 shown frames pixel-exact on every plane, \ - rect64_split_txfm_publish={fired}" - ); - } - - /// lane-unwritten-dep: the UNWRITTEN-SAMPLE census at the point the output is - /// taken, over the real film fixtures that carry hidden alt-refs. - /// - /// SCOPE, stated rather than implied: the census is taken where - /// `EC_AV1_FINAL_DUMP` writes, which is BEFORE `apply_grain`. The claim is - /// therefore over the PRE-GRAIN planes -- which are also the bytes the - /// reference bank stores and every later frame predicts from, the dependency - /// that matters. Every filter writes IN PLACE into the buffer this scans, so - /// none of them can open a hole outside its extent. `apply_grain` is the one - /// stage after this scan that ALLOCATES a new picture, and this census never - /// sees it: the claim is NOT "the caller's final grained picture has no hole". - /// - /// lane-av1graincensus: that paragraph is still true of THIS gate and is not - /// weakened by the pointer below -- what changed is that the gap it names is - /// no longer UNMEASURED. - /// [`the_grained_picture_the_caller_receives_carries_no_unwritten_plane_sample`] - /// measures the grained picture `apply_grain` returns, over its own counters, - /// and is the gate that carries the post-grain claim. - /// - /// NON-VACUITY, the part that makes this gate worth having: a census is only a - /// measurement if it CAN report non-zero. The control is a SYNTHETIC positive - /// -- the census is handed planes with a known number of sentinel samples and - /// must report exactly that number. It deliberately does NOT use a fixture: - /// the corpus's one witness with a real hole (`440_request_is_422`) is REFUSED - /// by lane/av1unwritten, so a fixture-carried control goes red on merge for a - /// reason unrelated to this gate. A synthetic control cannot be refused and - /// cannot change behaviour when a lane lands. It is proven by mutation in the - /// same run: neutering `census_unwritten_final` reds it (lane report §5). - /// - /// WHAT THIS IS NOT, corrected from an earlier revision of this comment: it - /// does NOT rest on a claim that the pre-deblock census is blind. That claim - /// was wrong. It came from `dump_stage16` cropping chroma as `(fw/2, fh/2)` -- - /// a 4:2:0 assumption -- so on a 64x64 4:2:2 frame 2048 chroma samples were in - /// no stage dump at all, and an earlier revision read that blind spot as - /// "identical pre-deblock, so deblock creates the dependence". With per-axis - /// extents the corrected measurement is the opposite: the pre-deblock dump on - /// `440_request_is_422` already DIFFERS by 2158 bytes and the exact u16 census - /// finds 224 unwritten samples (U 112, V 112, rows 36..63, whole 4x4 groups) -- - /// the same count `lanes/av1unwritten.report.md` reports. The hole is present - /// before any filter runs and the pre-deblock census SEES it. This census is - /// here because it is the measurement taken where the OUTPUT is taken, which - /// spans the whole route from the tile walk to the caller. - /// - /// The four film fixtures are the corpus's real 10-bit streams with hidden - /// alt-refs -- the shapes where a hidden frame's unwritten region would feed - /// a later DISPLAYED frame through the reference bank, which is the only way - /// an unwritten sample could reach output on a stream that decodes correctly. - /// All four measure 0 here AND 0 on the pre-deblock census. - /// - /// Measured on `8d6998d7` with a provenance-verified probe (`strings` on the - /// binary names only this worktree; reelb_arf sha256 `7f3b060da5aa9c53`, - /// reelb_rect64 `c9e721088766163b`): - /// - /// ```text - /// pre-deblock census (u16, whole plane, 0xDEAD counted per frame) - /// 440_request_is_422 224 <- also lane/av1unwritten's own number - /// reelb_arf_witness 0 - /// reelb_rect64_intra16x4_witness 0 - /// this gate (pre-grain, at the output point) - /// reelb_arf_witness 0 - /// reelb_rect64_intra16x4_witness 0 - /// gm_small_side_witness 0 - /// reelc_sb128_inter_witness 0 - /// ``` - #[test] - fn the_frame_the_caller_receives_carries_no_unwritten_plane_sample() { - const NAME: &str = "the_frame_the_caller_receives_carries_no_unwritten_plane_sample"; - let _gate_lock = lock_gate_counters(); - - // The census needs the sentinel FILL, which is env-gated (see - // `fresh_plane`), and this crate forbids `set_var` (see `envflags`), so - // the fill cannot be switched from inside a test process. The child - // process below is therefore how the measurement is taken; what the - // parent asserts is the CHILD's reported count. - let census = |fixture: &str| -> (usize, usize) { - let exe = std::env::current_exe().expect("test binary path"); - let out = std::process::Command::new(exe) - .args([ - "--exact", - "stream::tests::t09::uwdep_child_unwritten_census", - "--nocapture", - ]) - .env("UWDEP_CENSUS_FIXTURE", fixture) - .env("EC_AV1_PLANE_SENTINEL", "1") - .output() - .expect("running the census child"); - // `--nocapture` puts the child's `println!` on its stderr, so both - // streams are searched. - let text = format!( - "{}{}", - String::from_utf8_lossy(&out.stdout), - String::from_utf8_lossy(&out.stderr), - ); - text.lines() - .find_map(|l| l.strip_prefix("UWDEP_CENSUS ")) - .and_then(parse_census_line) - .unwrap_or_else(|| { - panic!( - "{NAME}: the census child reported no count for {fixture} \ - (child said: {:?})", - text.trim() - ) - }) - }; - - // Non-vacuity FIRST, and SYNTHETIC on purpose (see the doc comment): the - // census is handed planes with a known number of sentinel samples and must - // report exactly that number. No fixture is involved, so this cannot be - // affected by lane/av1unwritten refusing `440_request_is_422` on merge. - // The fill is env-gated, so even this runs in the child. - let (synthetic, synthetic_scanned) = census_synthetic(); - assert_eq!( - synthetic_scanned, 40, - "{NAME}: the synthetic control scanned {synthetic_scanned} samples, expected 40 \ - (16 + 16 + 8) -- the census did not look at what it was handed" - ); - assert_eq!( - synthetic, 7, - "{NAME}: the census reported {synthetic} for planes carrying exactly 7 sentinel \ - samples -- the census is not measuring what it claims, so every zero below is \ - meaningless (class: census-silently-blind)" - ); - - for fixture in [ - "reelb_arf_witness", - "reelb_rect64_intra16x4_witness", - "gm_small_side_witness", - "reelc_sb128_inter_witness", - ] { - let (n, scanned) = census(fixture); - assert!( - scanned > 0, - "{NAME}: the census scanned 0 samples on {fixture} -- the call at the output \ - point is not running, so the {n} below proves nothing (class: \ - census-never-ran). Deleting the call site reproduces this." - ); - assert_eq!( - n, 0, - "{NAME}: {fixture} hands the caller {n} samples the tile walk never wrote" - ); - } - } - - /// lane-av1graincensus: the picture the caller RECEIVES -- including film - /// grain -- carries no unwritten plane sample. - /// - /// # WHAT THIS GATE IS FOR, and the blind spot it closes - /// - /// [`the_frame_the_caller_receives_carries_no_unwritten_plane_sample`] scans - /// at `stream.rs`'s `EC_AV1_FINAL_DUMP` site, which is BEFORE `apply_grain`. - /// Every filter (deblock/CDEF/LR/superres) writes IN PLACE into the buffer it - /// scans, so none of them can open a hole outside its extent -- but - /// `apply_grain` is the one stage after that scan that ALLOCATES a fresh - /// picture: `film_grain::uninit_plane`, `Vec::with_capacity` + `set_len`, no - /// fill, with correctness resting on a band row partition rather than on the - /// type system. `lanes/unwritten-dep.report.md` §6 and §8 declined to claim - /// anything about that destination. This gate measures it. - /// - /// # WHY THE COUNT CAN BE NON-ZERO (the part that makes it a census) - /// - /// Counting `== plane_poison()` over an uninitialised buffer is a census that - /// reports ~0 either way: a hole survives with probability ~1/65536, not - /// always. `uninit_plane` therefore fills with the poison under the SAME - /// predicate `fresh_plane` honours. With the sentinel off -- every shipped - /// build -- `uninit_plane` is still `with_capacity` + `set_len`, so the - /// corner-cut it documents is untouched. - /// - /// # SCOPE, stated not implied - /// - /// The claim is over the picture the caller receives ON A GRAINED FRAME, in - /// its final form, after the noise. It is NOT a claim that the pre-grain - /// census already covered this -- that census never sees this buffer -- and it - /// is NOT a claim about a frame whose grain step does not run. - /// - /// # NON-VACUITY, two arms, both required - /// - /// 1. **synthetic, first, and with a DIFFERENT known count (5, not the - /// pre-grain arm's 7)** so a gate reading the wrong counter goes red. No - /// fixture involved, so no lane's refusal can redden it. - /// 2. **per-fixture `scanned > 0`** -- `unwritten == 0` is also what a build - /// with the census call deleted reports. `scanned > 0` is reachable only by - /// `apply_grain` actually running, so it is at once the - /// proof-that-grain-fired and the deletion control. - /// - /// Both mutations are in `lanes/av1graincensus.report.md`: deleting the - /// `census_unwritten_grained` call at `apply_grain`'s return reds arm 2, and - /// forcing ONE poison sample into a grained picture reds arm 2's count. - #[test] - fn the_grained_picture_the_caller_receives_carries_no_unwritten_plane_sample() { - const NAME: &str = - "the_grained_picture_the_caller_receives_carries_no_unwritten_plane_sample"; - let _gate_lock = lock_gate_counters(); - - let (syn, syn_scanned) = grain_census_synthetic(); - assert_eq!( - syn_scanned, 40, - "{NAME}: the synthetic control scanned {syn_scanned} samples, expected 40 \ - (16 + 16 + 8) -- the grained census did not look at what it was handed" - ); - assert_eq!( - syn, 5, - "{NAME}: the grained census reported {syn} for planes carrying exactly 5 sentinel \ - samples -- it is not measuring what it claims, so every zero below is \ - meaningless (class: census-silently-blind). Note 5, not the pre-grain arm's 7: \ - reading the wrong counter is the failure this number catches." - ); - - // Small and cheap: a 4:2:2 grain stream, a 4:2:0 one that also runs - // CDEF+LR, and the real 10-bit 3840x1608 hidden-alt-ref film whose height - // is not a multiple of the 32-pixel band row -- the shape where the band - // row partition has a tail. - for fixture in [ - "s422_grain_160x128", - "grain_cdef_lr_128x128", - "reelb_arf_witness", - ] { - let (n, scanned) = grain_census(fixture); - assert!( - scanned > 0, - "{NAME}: the grained census scanned 0 samples on {fixture} -- the call at \ - `apply_grain`'s return is not running (or grain never fired), so the {n} \ - below proves nothing (class: census-never-ran). Deleting the call in \ - apply_grain reproduces this." - ); - assert_eq!( - n, 0, - "{NAME}: {fixture} hands the caller a grained picture with {n} samples the \ - grain destination's band copy never wrote" - ); - } - } - - /// The child half of - /// [`the_frame_the_caller_receives_carries_no_unwritten_plane_sample`]: decodes - /// the fixture named in `UWDEP_CENSUS_FIXTURE` with the sentinel fill live and - /// prints `UWDEP_CENSUS frames=` plus a frame-count assertion. - /// - /// A `#[test]` rather than an example because it needs the crate's own - /// in-process counter -- which no external binary could read. - #[test] - fn uwdep_child_unwritten_census() { - // Reached with NEITHER variable set means a normal suite run: the parent - // invokes this test BY NAME with the variable set, so there is nothing to - // measure here. Asserting the fill instead made every full suite red - // (`stream::tests::uwdep_child_unwritten_census` is in the default test - // list), and the run it wanted to catch is already caught on the parent's - // side, which panics when the child prints no census line. A standalone - // run SAYS it skipped rather than passing silently. - if std::env::var_os("UWDEP_CENSUS_SYNTHETIC").is_none() - && std::env::var_os("UWDEP_CENSUS_FIXTURE").is_none() - { - println!("UWDEP_CENSUS skipped: not invoked as a census child"); - return; - } - assert!( - std::env::var_os("EC_AV1_PLANE_SENTINEL").is_some(), - "the census child ran without EC_AV1_PLANE_SENTINEL, so the fill was never live \ - and the count is meaningless" - ); - // The non-vacuity control: no decode, no fixture, just the census over - // planes with a KNOWN number of sentinel samples. 3 + 4 + 0 = 7. - if std::env::var_os("UWDEP_CENSUS_SYNTHETIC").is_some() { - const S: u16 = 0xDEAD; - let mut a = vec![7u16; 16]; - let mut b = vec![7u16; 16]; - let c = vec![7u16; 8]; - for s in a.iter_mut().take(3) { - *s = S; - } - for s in b.iter_mut().take(4) { - *s = S; - } - let _ = decode::take_final_unwritten_samples(); - decode::census_unwritten_final(&a, &b, &c); - let n = decode::take_final_unwritten_samples(); - let scanned = decode::take_final_census_scanned(); - println!("UWDEP_CENSUS {n} synthetic=1 scanned={scanned}"); - // lane-av1graincensus: the grained census over the SAME planes but a - // DIFFERENT known count, 2 + 3 + 0 = 5. Deliberately not 7: a parent - // that read the pre-grain counter for the grained arm would see 7 and - // go red, so the two arms cannot be confused for one another. - for s in a.iter_mut().take(3) { - *s = 7; - } - for s in b.iter_mut().take(4) { - *s = 7; - } - for s in a.iter_mut().take(2) { - *s = S; - } - for s in b.iter_mut().take(3) { - *s = S; - } - let _ = decode::take_grained_unwritten_samples(); - decode::census_unwritten_grained(&a, &b, &c); - let gn = decode::take_grained_unwritten_samples(); - let gscanned = decode::take_grained_census_scanned(); - println!("GRAINCENSUS {gn} synthetic=1 scanned={gscanned}"); - return; - } - let Ok(fixture) = std::env::var("UWDEP_CENSUS_FIXTURE") else { - // Not a census run: the parent invokes this test by name, so being - // reached without the variable means a normal suite run. - return; - }; - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join(format!("fixtures/{fixture}.obu")); - let stream = - std::fs::read(&path).unwrap_or_else(|e| panic!("reading {}: {e}", path.display())); - let _ = decode::take_final_unwritten_samples(); - // Both counters are drained BEFORE the decode: they are process-global - // and this child may inherit nothing, but a partial run must not be able - // to add its numbers to another test's. - let _ = decode::take_grained_unwritten_samples(); - let frames = decode_stream(&stream).unwrap_or_else(|e| panic!("{fixture} refused: {e}")); - let n = decode::take_final_unwritten_samples(); - let scanned = decode::take_final_census_scanned(); - println!("UWDEP_CENSUS {n} frames={} scanned={scanned}", frames.len()); - // lane-av1graincensus: the post-grain census, over the picture - // `apply_grain` returns. A different prefix from `UWDEP_CENSUS`, so - // neither parent can pick up the other's line. - let gn = decode::take_grained_unwritten_samples(); - let gscanned = decode::take_grained_census_scanned(); - println!( - "GRAINCENSUS {gn} frames={} scanned={gscanned}", - frames.len() - ); - } - - /// lane-av1uballoc: the frame the caller receives does not depend on what - /// the plane buffer held before the decode wrote it. - /// - /// Four runs of the same fixtures, each in its own process (the fill and - /// the alloc closure are both process-constant env reads -- see - /// [`crate::envflags`] -- and this crate forbids `set_var`), must agree on - /// one hash per fixture: - /// - /// * `EC_AV1_PLANE_SENTINEL=0xDEAD` and `=0xBEEF` -- two DIFFERENT - /// impossible values for the same buffer. This is the arm that can - /// actually FAIL: if any reader's value reaches the picture, changing the - /// poison changes the output. Equal hashes are a statement about a READ, - /// which is what the poisoned-read check in [`decode::fresh_plane`] needs and what no - /// census in the crate measures. - /// * the sentinel OFF (the shipped zeroed allocation), which must agree - /// with the poisoned runs. This is the "same with the sentinel off" - /// arm; on its own it is weak (the allocator may hand out the same - /// ambient bytes twice) and is here as the join between the two worlds. - /// - /// NON-VACUITY, first and synthetic: [`allocdet_synthetic`] hashes two - /// pictures that differ in ONE sample and asserts the hashes DIFFER. A hash - /// that cannot see a one-sample difference would make every equality below - /// vacuous, and it is the failure mode a "0 errors" style result has. - /// Second: every arm must report `frames>0`, so a child that decoded - /// nothing cannot agree with another child that decoded nothing. - #[test] - fn the_frame_does_not_depend_on_the_plane_buffers_initial_content() { - const NAME: &str = "the_frame_does_not_depend_on_the_plane_buffers_initial_content"; - let _gate_lock = lock_gate_counters(); - // Kept SMALL on purpose: the whole gate is 4 child processes x this - // list, and the suite runs it in a DEBUG build. A first revision used - // the 1920x792 film fixtures here and took 252 s, which is not a gate - // anyone keeps. These ten cover every shape the region list names -- - // 4:2:2 (12-bit key, inter, sb128 intrabc, 17-frame odd-size), 4:4:4 - // (lossless sb64, intrabc rect4, 128-root mu), a padded odd size, an - // off-tile chroma walk, and superres+CDEF+LR -- for ~1.3 s per arm. - // - // lane-av1graincensus adds FILM GRAIN. `apply_grain`'s `uninit_plane` is - // the crate's only OTHER `Vec::with_capacity` + `set_len` allocation, and - // before this row the only gate that can catch a READ of it had no grain - // fixture at all, so that path had no coverage here. It matters: with - // the grain band's clean-row copy neutered, the noise kernels read the - // destination to build `avgLuma` and the picture's values then depend on - // whatever the buffer held -- a dependence the 0xDEAD-vs-0xBEEF arm - // exists to catch and the unwritten-sample census cannot (the read value - // is overwritten before the census runs). Measured in - // `lanes/av1graincensus.report.md` §5. `s422_grain_160x128` is the - // smallest grain fixture, so the arm grows by ~0.05 s. - const FIXTURES: &[&str] = &[ - "s422_12bit_160x128", - "422_inter_160x128_3f", - "422_intrabc_sb128_strip", - "s422_352x242_10b", - "ll444_sb64_1to4_lossless", - "444_intrabc_rect4_witness", - "444_intra_in_inter_128root_mu_chroma", - "svt1-split-tx-pin", - "mix176_offtile_chroma_clip", - "superres_kf_cdef_lr_64x64", - "s422_grain_160x128", - ]; - - let (a, b) = allocdet_synthetic(); - assert_ne!( - a, b, - "{NAME}: the content hash returned the same value for two pictures differing in one \ - sample, so every equality below is vacuous -- this gate would pass on any decoder, \ - including one that returns garbage (class: hash-cannot-see-content)" - ); - - let arms: [(&str, Option<&str>, &str); 3] = [ - ("poison-dead", Some("0xDEAD"), "zeroed"), - ("poison-beef", Some("0xBEEF"), "zeroed"), - ("alloc-zeroed", None, "zeroed"), - ]; - let mut baseline: Option> = None; - for (label, poison, alloc) in arms { - let rows = allocdet_child(FIXTURES, poison, alloc); - assert_eq!( - rows.len(), - FIXTURES.len(), - "{NAME}: the {label} arm reported {} of {} fixtures -- a run that decoded \ - nothing can agree with another run that decoded nothing", - rows.len(), - FIXTURES.len() - ); - for (f, frames, _) in &rows { - assert!( - *frames > 0, - "{NAME}: the {label} arm decoded 0 frames of {f}; the hashes it compared are \ - over nothing" - ); - } - match &baseline { - None => baseline = Some(rows), - Some(first) => { - for (i, (f, frames, h)) in rows.iter().enumerate() { - let (bf, bframes, bh) = &first[i]; - assert_eq!( - bf, f, - "{NAME}: arm {label} reported fixture {f} where the \ - baseline reported {bf} -- the arms are not comparable" - ); - assert_eq!( - bframes, frames, - "{NAME}: {f} decoded {frames} frames under \ - {label} and {bframes} under the baseline arm" - ); - assert_eq!( - bh, h, - "{NAME}: {f} decoded to a DIFFERENT picture depending on what the \ - plane buffer held before the decode wrote it -- {label} gave {h:016x}, \ - the baseline arm gave {bh:016x}. A read of uninitialised memory \ - reaches the caller's frame (see decode::fresh_plane)." - ); - } - } - } - } - } - - /// The child half of - /// [`the_frame_does_not_depend_on_the_plane_buffers_initial_content`]: - /// decodes every fixture named in `ALLOCDET_FIXTURES` and prints one - /// `ALLOCDET` line each. - /// - /// With `ALLOCDET_SYNTHETIC` set it instead prints the two hashes the - /// non-vacuity control compares -- two pictures differing in ONE sample -- - /// and decodes nothing. - #[test] - fn allocdet_child_decode() { - if std::env::var_os("ALLOCDET_SYNTHETIC").is_some() { - let (a, b) = allocdet_synthetic(); - println!("ALLOCDET_SYNTHETIC {a:016x} {b:016x}"); - return; - } - let Ok(list) = std::env::var("ALLOCDET_FIXTURES") else { - // Reached without either variable == a normal suite run: the parent - // names this test with ALLOCDET_FIXTURES (or ALLOCDET_SYNTHETIC) set, - // so there is nothing to measure here. Asserting the variable instead - // made every full suite red (caught by the server suite at the merged - // head); the parent already fails when the child prints no ALLOCDET - // line, so a skip cannot hide a broken child. Print rather than - // pass silently. - println!("ALLOCDET skipped: not invoked as a census child"); - return; - }; - let mut hash = 0xcbf2_9ce4_8422_2325u64; - for fixture in list.split(',').filter(|s| !s.is_empty()) { - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join(format!("fixtures/{fixture}.obu")); - let stream = - std::fs::read(&path).unwrap_or_else(|e| panic!("reading {}: {e}", path.display())); - let mut frames = 0usize; - decode_stream_with(&stream, |pic, _idx, shown| { - if !shown { - return Ok(()); - } - frames += 1; - for p in [&pic.y, &pic.u, &pic.v] { - for &s in p.iter() { - for b in s.to_le_bytes() { - hash ^= u64::from(b); - hash = hash.wrapping_mul(0x0000_0100_0000_01b3); - } - } - } - Ok(()) - }) - .unwrap_or_else(|e| panic!("{fixture} refused: {e}")); - println!("ALLOCDET {fixture} frames={frames} hash={hash:016x}"); - } - } - - /// lane-t900 r6: the 128-superblock INTER witness. - /// `crates/ec-av1/fixtures/reelc_sb128_inter_witness.obu`, 177773 bytes, - /// sha256 `09d995946d27695ef4b7b1a24a4d7ad85f8e2c8176d58ee54e825efc061f9cbc`: - /// the first 23 frame-carrying OBUs of a 2 s cut taken 900 s into a 10-bit - /// 1920x792 AV1 stream with `use_128x128_superblock=1`, 16 decode-order - /// frames, 15 shown. Cut twice independently from the source (`-ss 900 -t 2 - /// -c:v copy` then the OBU truncation) -- both cuts hash identically. - /// lane-t900 r7 extended it from 19 OBUs / 14 frames: decode-order frame 14 - /// is the ONLY frame in this repository's fixtures whose sub-8x8 inter - /// chroma inherits a `tx_type` from a chroma-reference sub-block that - /// differs from its group's first sub-block AND codes coefficients - /// (`sub8_chroma_tx_from_ref_hits`), i.e. the only frame that can tell - /// `av1_get_tx_type`'s two candidate rules apart. - /// - /// It is the first stream in this repository that decodes exactly while - /// five separately-found defects' paths all fire, which is why the asserts - /// below are on all of them: - /// - /// * `warp_plane_suppress_hits` (r5) -- `av1_init_warp_params` bails out at - /// `block_width < 8 || block_height < 8` on the PLANE's own block, so the - /// 4x8 chroma of an 8x16 luma block is predicted translationally while its - /// luma warps. Gated on the square side before r5. - /// * `inter_sb128_vert_hits` + `cdef_idx_hits` (r5) -- the second half of a - /// 128-root HORZ/VERT inter block must read its OWN `cdef_idx` literal - /// (libaom `cdef_transmitted[4]`, one flag per 64x64 CDEF unit). - /// * `interintra_rect_hits` (r4) -- interintra on a RECTANGULAR block built - /// a square intra predictor before. - /// * `non_chroma_ref_ctx_skip_hits` (r3) -- a block that is not the chroma - /// reference of its 4:2:0 pair leaves its neighbours' chroma coefficient - /// contexts untouched (`nplanes = 1 + (num_planes - 1) * is_chroma_ref`). - /// * `intra_in_inter_txctx_hits` (r2) -- an intra strip in an INTER frame - /// takes its `tx_depth` row from the real `TXFM_CONTEXT` bands, not the - /// key frame's deblock grid. - /// * `edge_filter_mi_fix_hits` (r4) -- both halves of a split intra block - /// read their OWN mi-exact intra-edge-filter neighbours. - /// - /// It is ALSO the witness that lifted the intra-16x4-in-inter opt-in -- that path decodes by default now, gated here: - /// `intra16x4_in_inter` fires 78x 16x4 + 149x 4x16 (108 chroma-paired) - /// inside frames that are decoded AND compared exact -- not counted out of - /// a refused or desynced stream the way lane-sub8x4 r3's phantom was - /// (class `counter-from-refused-stream`). The 128x64/64x128 intra-in-inter - /// arm fires 0 times here, so THAT refusal is untouched. - /// - /// All 14 decode-order frames (including the 2 no-show frames ffmpeg never - /// hands back) were compared byte-exact against instrumented aomdec with - /// `EC_AV1_FINAL_DUMP` -- see the lane report's EVIDENCE line; the gate - /// itself compares the 12 shown frames on every plane. - #[test] - fn a_10bit_128sb_film_frames_with_warp_cdef_and_interintra_decode_pixel_exact() { - const NAME: &str = - "a_10bit_128sb_film_frames_with_warp_cdef_and_interintra_decode_pixel_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("fixtures/reelc_sb128_inter_witness.obu"); - let stream = std::fs::read(&path) - .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display())); - let (width, height) = (1920usize, 792usize); - let before = ( - crate::decode::warp_plane_suppress_hits(), - crate::decode::cdef_idx_hits(), - crate::decode::inter_sb128_vert_hits(), - crate::decode::interintra_rect_hits(), - crate::decode::non_chroma_ref_ctx_skip_hits(), - crate::decode::intra_in_inter_txctx_hits(), - crate::decode::edge_filter_mi_fix_hits(), - ); - let sub8tx_before = crate::decode::sub8_chroma_tx_from_ref_hits(); - // lane-t900 r8: the intra edge-filter type an INTER neighbour keeps - // non-smooth (the coarse SUB band still holds an older SMOOTH mode). - let notsmooth_before = crate::decode::inter_neighbour_not_smooth_hits(); - // lane-t900 r10: the rect warp top-right reach (600 blocks here). - let tr_before = crate::decode::tr_reach_longer_side_hits(); - let i16_before = crate::decode::intra16x4_in_inter_hits(); - // lane-t900 r14: OBMC neighbour strips that run past the frame edge - // (792 luma rows = 198 mi rows, so every bottom-row 32x32 block - // overhangs) -- the shape whose prediction size used to be clamped. - let edge_before = crate::decode::obmc_edge_span_hits(); - let frames = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => panic!("{NAME}: decode_stream refused: {e}"), - }; - let obmc_edge_span = crate::decode::obmc_edge_span_hits() - edge_before; - let fired = ( - crate::decode::warp_plane_suppress_hits() - before.0, - crate::decode::cdef_idx_hits() - before.1, - crate::decode::inter_sb128_vert_hits() - before.2, - crate::decode::interintra_rect_hits() - before.3, - crate::decode::non_chroma_ref_ctx_skip_hits() - before.4, - crate::decode::intra_in_inter_txctx_hits() - before.5, - crate::decode::edge_filter_mi_fix_hits() - before.6, - ); - let sub8tx = crate::decode::sub8_chroma_tx_from_ref_hits() - sub8tx_before; - let notsmooth = crate::decode::inter_neighbour_not_smooth_hits() - notsmooth_before; - let tr = crate::decode::tr_reach_longer_side_hits() - tr_before; - let i16_now = crate::decode::intra16x4_in_inter_hits(); - let i16 = ( - i16_now.0 - i16_before.0, - i16_now.1 - i16_before.1, - i16_now.2 - i16_before.2, - ); - for (what, n) in [ - ("warp_plane_suppress", fired.0), - ("cdef_idx", fired.1), - ("inter_sb128_vert", fired.2), - ("interintra_rect", fired.3), - ("non_chroma_ref_ctx_skip", fired.4), - ("intra_in_inter_txctx", fired.5), - ("edge_filter_mi_fix", fired.6), - ("intra16x4_in_inter 16x4", i16.0), - ("intra16x4_in_inter 4x16", i16.1), - ("intra16x4_in_inter chroma_ref", i16.2), - ("sub8_chroma_tx_from_ref", sub8tx), - ("inter_neighbour_not_smooth", notsmooth), - ("tr_reach_longer_side", tr), - ("obmc_edge_span", obmc_edge_span), - ] { - assert!( - n > 0, - "{NAME}: {what} never fired on this stream -- the gate would be vacuous for it" - ); - } - assert_eq!(frames.len(), 15, "{NAME}: 15 shown frames"); - assert_eq!((frames[0].width, frames[0].height), (width, height)); - let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len()); - assert_eq!( - ffmpeg_frames.len(), - frames.len(), - "{NAME}: ffmpeg returned {} frames, we decoded {}", - ffmpeg_frames.len(), - frames.len() - ); - for (i, (ours, theirs)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!(ours.y, theirs.y, "{NAME}: frame {i} luma vs ffmpeg"); - assert_eq!(ours.u, theirs.u, "{NAME}: frame {i} U vs ffmpeg"); - assert_eq!(ours.v, theirs.v, "{NAME}: frame {i} V vs ffmpeg"); - } - eprintln!( - "{NAME}: 15 shown frames pixel-exact on every plane; warp_plane_suppress={} \ - cdef_idx={} inter_sb128_vert={} interintra_rect={} non_chroma_ref_ctx_skip={} \ - intra_in_inter_txctx={} edge_filter_mi_fix={} intra16x4_in_inter={:?} \ - sub8_chroma_tx_from_ref={sub8tx} inter_neighbour_not_smooth={notsmooth} \ - tr_reach_longer_side={tr} obmc_edge_span={obmc_edge_span}", - fired.0, fired.1, fired.2, fired.3, fired.4, fired.5, fired.6, i16 - ); - } - - /// lane-t900 r16/r17: a 10-bit 512x512 `--sb-size=128` stream in which - /// every 128 root is a var-tx block, and the gate for the SKIPPED-128-block - /// luma entropy reset (r17). It was BUILT as an intra-128-in-inter witness - /// and r16 measured three hits of that arm in it -- every one of them an - /// artifact of the desync fixed here (class `counter-from-refused-stream`). - /// Decoding exactly, the arm fires ZERO times, so this stream does not - /// carry that shape; the intra-128-in-inter path decodes by default now, gated by `an_intra_coded_128_half_inside_an_inter_frame_decodes_pixel_exact`. Renamed - /// out of `an_intra_coded_128x64_block_inside_an_inter_frame_...` for that - /// reason -- the fixture keeps the original intent in its own name. - /// - /// `crates/ec-av1/fixtures/intra128_in_inter_witness.obu`, 13066 bytes, - /// sha256 `dd41fc39367a3d38bf8a8a8106dc30d91b716b2a9123fdfa4716930f4f98caf9`, - /// produced by this repository's aomenc oracle: - /// - /// ```text - /// aomenc --codec=av1 -w 512 -h 512 --input-bit-depth=10 --bit-depth=10 \ - /// --sb-size=128 --min-partition-size=64 --max-partition-size=128 \ - /// --enable-rect-partitions=1 --kf-max-dist=9999 --lag-in-frames=0 \ - /// --cpu-used=1 --end-usage=q --cq-level=24 --threads=1 --obu -o s.obu src.y4m - /// ``` - /// - /// The source is 10 frames of 10-bit 512x512 whose left two superblock - /// columns carry 128-wide bands 64 rows apart (so the 128 root's cheapest - /// split is `PARTITION_HORZ`) and whose right two carry 64-wide vertical - /// bands (`PARTITION_VERT`), with two hard scene cuts at frames 4 and 7 and - /// `--kf-max-dist=9999` so those cuts must be coded as INTER frames whose - /// content no reference holds. It is the first stream found in this - /// repository that makes the encoder code a 128-root HORZ/VERT half INTRA - /// inside an inter frame at all: `intra128_in_inter` fires 1x 128x64 + - /// 2x 64x128. Three recipes that do NOT fire it, so the shape matters: a - /// small new patch on a static background (the frame costs 80 bytes, the - /// encoder skips), unstructured texture (the 128 root always SPLITs), and - /// cyclically repeating phases (GOLDEN holds an earlier phase, so the cut - /// is predicted rather than coded intra). - /// - /// r16 could not lift the opt-in: the three hits landed in a frame this - /// decoder did not decode exactly, and a counter read out of a desynced - /// frame proves nothing (class `counter-from-refused-stream`). The blocker - /// was a SEPARATE defect on the inter path, not this arm -- the same source - /// re-encoded with every optional tool disabled fired the arm 0 times and - /// desynced on exactly the same frames, and the same source at - /// `--sb-size=64` decoded all 10 frames byte-exact. - /// - /// r17 root cause, and what this gate now pins (class - /// `early-return-skips-tail`): a SKIPPED inter block - /// whose `read_block_tx_size` still hands back var-tx leaves -- which every - /// 128 root does under `TX_MODE_LARGEST` -- took `decode_inter_block`'s - /// `if skip` arm, so the per-transform-unit luma publication loop never - /// ran, and the block-level `record_split_luma_rect_mi` deliberately writes - /// no plane 0. The skipped block therefore left the PREVIOUS block's luma - /// coefficient levels standing where libaom's `av1_reset_entropy_context` - /// zeroes all three planes over the block. First-bad before the fix - /// (`EC_TRACE_COEFF` on both decoders, prefiltered to the - /// `all_zero`/`eob`/`after_bases` tags, filtered index 426): frame 1, the - /// 128x128 `is_inter=1 skip=0` block at mi(32,64), its first luma TU - /// (`bc=0 br=0`, TX_64X64) -- aomdec `txb_skip` ctx 1 (`top == 0 && - /// left == 0`), ours ctx 2, entry range equal on both, because the skipped - /// 128x128 block at mi(32,32) never cleared `left[32..48]` (ours 1, - /// aomdec 0). With the publication restored the whole 10-frame filtered - /// ladder matches 1397/1397 steps. - /// - #[test] - fn a_128_superblock_stream_whose_skipped_blocks_are_var_tx_decodes_pixel_exact() { - const NAME: &str = - "a_128_superblock_stream_whose_skipped_blocks_are_var_tx_decodes_pixel_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("fixtures/intra128_in_inter_witness.obu"); - let stream = std::fs::read(&path) - .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display())); - let (width, height) = (512usize, 512usize); - let before = crate::decode::skip_vartx_luma_reset_hits(); - let intra128_before = intra128_in_inter_counters(); - let frames = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => panic!("{NAME}: decode_stream refused: {e}"), - }; - let fired = crate::decode::skip_vartx_luma_reset_hits() - before; - assert!( - fired > 0, - "{NAME}: no skipped var-tx block cleared its own luma coefficient \ - contexts -- the gate would be vacuous for the defect it pins" - ); - let intra128_now = intra128_in_inter_counters(); - assert_eq!( - [ - intra128_now[0] - intra128_before[0], - intra128_now[1] - intra128_before[1] - ], - [0, 0], - "{NAME}: this stream does not carry a 128-root intra half -- the \ - witness for that arm is `intra128_in_inter_witness2.obu` (r18)" - ); - assert_eq!(frames.len(), 10, "{NAME}: 10 shown frames"); - assert_eq!((frames[0].width, frames[0].height), (width, height)); - let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len()); - assert_eq!( - ffmpeg_frames.len(), - frames.len(), - "{NAME}: ffmpeg returned {} frames, we decoded {}", - ffmpeg_frames.len(), - frames.len() - ); - for (i, (ours, theirs)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!(ours.y, theirs.y, "{NAME}: frame {i} luma vs ffmpeg"); - assert_eq!(ours.u, theirs.u, "{NAME}: frame {i} U vs ffmpeg"); - assert_eq!(ours.v, theirs.v, "{NAME}: frame {i} V vs ffmpeg"); - } - eprintln!( - "{NAME}: 10 shown frames pixel-exact on every plane; \ - skip_vartx_luma_reset={fired}" - ); - } - - /// lane-t900 r18 GATE: a 128-root `PARTITION_HORZ`/`PARTITION_VERT` half - /// coded INTRA inside an INTER frame -- the shape an opt-in guarded from - /// lane-inter128intra r1 until this round; it decodes by default now, gated by this stream. - /// - /// What r16 and r17 could not find, and what this recipe exploits: libaom - /// does not PICK a 128-root HORZ/VERT in the frame interior -- r16's - /// 512x512 witness codes its 128 roots as NONE (96) or SPLIT (64) and - /// nothing else, and a textured 640x384 sweep the same. The shape appears - /// where the frame EDGE forces it: with a partial last superblock ROW - /// `has_rows128 == false`, so `PARTITION_HORZ` is implied and only the - /// 128x64 top half is decoded; a partial last COLUMN implies the 64x128 - /// left half the same way (the arm the - /// `..._sb128_gathered_edge_horz_partition_...` gate pins for INTER - /// blocks). Put content no reference holds in exactly those two bands and - /// the encoder codes those forced halves INTRA. - /// - /// `crates/ec-av1/fixtures/intra128_in_inter_witness2.obu`, 86516 bytes, - /// sha256 `cace4cc3a5ba4dc5f8c7c219e87c9052351e832cad3d7f4c8ffe09288a6d7ccf`, - /// produced by this repository's aomenc oracle: - /// - /// ```text - /// aomenc --codec=av1 -w 704 -h 320 --input-bit-depth=10 --bit-depth=10 \ - /// --sb-size=128 --max-partition-size=128 --enable-rect-partitions=1 \ - /// --enable-ab-partitions=0 --enable-1to4-partitions=0 \ - /// --enable-intrabc=0 --enable-palette=0 --tune=psnr \ - /// --kf-max-dist=9999 --lag-in-frames=0 --cpu-used=1 --end-usage=q \ - /// --cq-level=20 --threads=1 --passes=1 --obu -o s.obu src.y4m - /// ``` - /// - /// The source is 15 frames of 10-bit 704x320 (704 = 5*128 + 64 and - /// 320 = 2*128 + 64, so BOTH the last superblock column and the last - /// superblock row are partial) whose interior is a low-passed noise - /// texture panning 4 px per frame -- an exact integer translation, so - /// inter predicts it and intra never would -- and whose bottom 64 rows and - /// right 64 columns are replaced at frames 6, 9 and 12 by a fresh smooth - /// diagonal ramp with a different angle and offset each time. No - /// reference holds that content (`--lag-in-frames=0`, so there is no - /// hidden alt-ref either), it is internally smooth, and it lands exactly - /// in the edge-forced halves: `intra128_in_inter` fires 3x 128x64 and - /// 6x 64x128, every one of them inside a frame this gate compares - /// byte-exact against ffmpeg (class `counter-from-refused-stream`). - #[test] - fn an_intra_coded_128_half_inside_an_inter_frame_decodes_pixel_exact() { - const NAME: &str = "an_intra_coded_128_half_inside_an_inter_frame_decodes_pixel_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("fixtures/intra128_in_inter_witness2.obu"); - let stream = std::fs::read(&path) - .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display())); - let (width, height) = (704usize, 320usize); - let before = intra128_in_inter_counters(); - let frames = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => panic!("{NAME}: decode_stream refused: {e}"), - }; - let after = intra128_in_inter_counters(); - let fired = [after[0] - before[0], after[1] - before[1]]; - assert!( - fired[0] > 0 && fired[1] > 0, - "{NAME}: intra-128-in-inter fired {fired:?} (128x64, 64x128) -- both \ - arms must fire or the gate is vacuous for the one that did not" - ); - assert_eq!(frames.len(), 15, "{NAME}: 15 shown frames"); - assert_eq!((frames[0].width, frames[0].height), (width, height)); - let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len()); - assert_eq!( - ffmpeg_frames.len(), - frames.len(), - "{NAME}: ffmpeg returned {} frames, we decoded {}", - ffmpeg_frames.len(), - frames.len() - ); - for (i, (ours, theirs)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!(ours.y, theirs.y, "{NAME}: frame {i} luma vs ffmpeg"); - assert_eq!(ours.u, theirs.u, "{NAME}: frame {i} U vs ffmpeg"); - assert_eq!(ours.v, theirs.v, "{NAME}: frame {i} V vs ffmpeg"); - } - eprintln!( - "{NAME}: 15 shown frames pixel-exact on every plane; \ - intra128_in_inter 128x64={} 64x128={}", - fired[0], fired[1] - ); - } - - /// lane-t900 r32 GATE for the LIFTED refusal "a HORZ/VERT intra strip in - /// a screen-content frame (palette syntax is consumed for square blocks - /// only)": the r18 edge-forced recipe re-encoded with - /// `--tune-content=screen`, i.e. the exact case that refusal guarded. - /// - /// `crates/ec-av1/fixtures/intra128_in_inter_screen_witness.obu`, 119048 - /// bytes, sha256 - /// `c84a493f90327f5d2bea038a42e87cbfe56762b5c6a856d76b4bff9797c5ea09`, - /// from this repository's aomenc oracle over r18's own 10-bit 704x320 - /// source (`gen3.py`): the r18 flag set plus `--tune-content=screen - /// --enable-palette=0 --enable-intrabc=0 --cq-level=20`. Three cq levels - /// were swept (20/35/50); all three fire, and the `--enable-rect-\ - /// partitions=0` twin of each codes ZERO 128-root halves, which is what - /// says the shape here is the coded HORZ/VERT arm and not an artefact. - /// - /// The lift's proof is r31's enumeration - /// (`no_block_footprint_with_a_128_pixel_side_can_carry_palette_syntax`): - /// `av1_allow_palette`'s `bw > 64 || bh > 64` bound means a 128x64/64x128 - /// half codes no palette syntax at all, so the screen flag changes nothing - /// about its syntax. This is the WITNESS that the lifted arm is reachable - /// and decodes, which r23's census could not produce. - #[test] - fn an_intra_coded_128_half_in_a_screen_content_inter_frame_decodes_pixel_exact() { - const NAME: &str = - "an_intra_coded_128_half_in_a_screen_content_inter_frame_decodes_pixel_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("fixtures/intra128_in_inter_screen_witness.obu"); - let stream = std::fs::read(&path) - .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display())); - let (width, height) = (704usize, 320usize); - // The refusal named `allow_screen_content_tools`, so the gate reads - // that bit out of the frame headers rather than trusting the encoder - // flag (class `gate-blind-to-feature`). - let mut screen_frames = 0u32; - { - let mut p = Av1Parser::new(); - let mut pos = 0usize; - while pos < stream.len() { - let obu = p.parse_obu(&stream[pos..]).expect("parse"); - pos += obu.total_size; - let header = match &obu.kind { - ObuKind::Frame(h, _) => Some(&**h), - ObuKind::FrameHeader(h) => Some(&**h), - _ => None, - }; - if header.is_some_and(|h| h.allow_screen_content_tools) { - screen_frames += 1; - } - } - } - assert!( - screen_frames > 0, - "{NAME}: no frame sets allow_screen_content_tools -- the gate no longer \ - exercises the lifted refusal's own condition" - ); - let before = intra128_in_inter_counters(); - let frames = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => panic!("{NAME}: decode_stream refused: {e}"), - }; - let after = intra128_in_inter_counters(); - let fired = [after[0] - before[0], after[1] - before[1]]; - assert!( - fired[0] > 0 && fired[1] > 0, - "{NAME}: intra-128-in-inter fired {fired:?} (128x64, 64x128) -- both arms \ - must fire or the lift is unwitnessed at the one that did not" - ); - assert_eq!(frames.len(), 15, "{NAME}: 15 shown frames"); - assert_eq!((frames[0].width, frames[0].height), (width, height)); - let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len()); - assert_eq!( - ffmpeg_frames.len(), - frames.len(), - "{NAME}: frame count vs ffmpeg" - ); - for (i, (ours, theirs)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!(ours.y, theirs.y, "{NAME}: frame {i} luma vs ffmpeg"); - assert_eq!(ours.u, theirs.u, "{NAME}: frame {i} U vs ffmpeg"); - assert_eq!(ours.v, theirs.v, "{NAME}: frame {i} V vs ffmpeg"); - } - eprintln!( - "{NAME}: {screen_frames} screen-content frame(s), 15 shown frames pixel-exact \ - on every plane; intra128_in_inter 128x64={} 64x128={}", - fired[0], fired[1] - ); - } - - /// lane-t900 r22 GATE: a real `aomenc --tune-content=screen - /// --enable-palette=1` stream whose INTER frames reconstruct palette - /// blocks (Y and UV), at both bit depths. - /// - /// Recipe (both fixtures, 15 frames, key + 14 inter, 256x192, one tile): - /// `aomenc --codec=av1 --passes=1 --end-usage=q --cq-level=20 --cpu-used=1 - /// --threads=1 --row-mt=0 --lag-in-frames=0 --kf-max-dist=9999 - /// --sb-size=64 --tune-content=screen --enable-palette=1 - /// --enable-intrabc=0 --obu` (plus `--bit-depth=10 --profile=0` for the - /// twin) over a synthetic screen-like source: two luma levels on a 16x16 - /// grid, four chroma levels on an 8x8 one, both re-keyed per frame so the - /// encoder cannot predict the new blocks and codes them INTRA inside the - /// inter frames. `--enable-palette=0` on the same source is 13% larger, - /// which is what says the tool is really used. - /// - /// What this pins that no key-frame palette gate can: the palette - /// colour-index CDFs are this decoder's only VARIABLE-ALPHABET tables (the - /// reader takes `[..=n]` of a `[u16; 9]` row, so `update_cdf`'s counter - /// lives at index `n`), and `Cdfs::reset_counts` zeroed slot 8 instead -- - /// so every colour-index row crossed a frame boundary with a SATURATED - /// count and adapted at rate 6 where libaom, counting from 0, adapts at 4. - /// The first inter-frame palette block's map desynced at its THIRD - /// colour-index symbol (decode-order frame 3, mi(40,0), map cell (0,2): - /// ours cdf0 = 32768-1071, aomdec's = 32768-971, same ctx, same value, - /// different range). - #[test] - fn a_real_aomenc_screen_stream_with_palette_blocks_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_screen_stream_with_palette_blocks_decodes_pixel_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - for (fixture, ten_bit) in [ - ("fixtures/palette_screen_witness.obu", false), - ("fixtures/palette_screen_witness_10bit.obu", true), - ] { - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join(fixture); - let stream = std::fs::read(&path) - .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display())); - let (width, height) = (256usize, 192usize); - let before = intra_in_inter_palette_hits(); - let frames = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => panic!("{NAME} [{fixture}]: decode_stream refused: {e}"), - }; - let after = intra_in_inter_palette_hits(); - let (fired_y, fired_uv) = (after.0 - before.0, after.1 - before.1); - assert!( - fired_y > 0 && fired_uv > 0, - "{NAME} [{fixture}]: inter-frame palette fired y={fired_y} uv={fired_uv} \ - -- both planes must fire or the gate is vacuous for the one that did not" - ); - assert_eq!(frames.len(), 15, "{NAME} [{fixture}]: 15 shown frames"); - let ffmpeg_frames = if ten_bit { - ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len()) - } else { - ffmpeg_decode_sequence(&stream, width, height, frames.len()) - }; - assert_eq!( - ffmpeg_frames.len(), - frames.len(), - "{NAME} [{fixture}]: frame count" - ); - for (i, (ours, theirs)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!( - ours.y, theirs.y, - "{NAME} [{fixture}]: frame {i} luma vs ffmpeg" - ); - assert_eq!( - ours.u, theirs.u, - "{NAME} [{fixture}]: frame {i} U vs ffmpeg" - ); - assert_eq!( - ours.v, theirs.v, - "{NAME} [{fixture}]: frame {i} V vs ffmpeg" - ); - } - eprintln!( - "{NAME} [{fixture}]: 15 frames pixel-exact on every plane; \ - inter-frame palette y={fired_y} uv={fired_uv}" - ); - } - } - - /// lane-t900 r23 GATE for the two LIFTED refusals `"a block that actually - /// uses a palette (Y)/(UV) -- reconstruction is out of scope"` at their - /// 8x8-LEAF site ([`crate::decode`]'s `decode_inter_block8` intra arm): - /// a palette block on an 8x8 intra leaf inside an inter frame. - /// - /// Recipe (`fixtures/palette_screen_leaf8_witness.obu`): 256x192, 15 - /// frames, a static two-level 16x16 screen background with a 96x96 patch - /// of hashed 4x4 colour cells that moves non-periodically (so no - /// reference holds it and the encoder codes it INTRA inside the inter - /// frames), `aomenc --tune-content=screen --enable-palette=1 - /// --enable-intrabc=0 --sb-size=64 --cq-level=20 --cpu-used=1 - /// --lag-in-frames=0 --kf-max-dist=9999 --max-partition-size=8` -- the - /// partition cap is what puts the palette on BLOCK_8X8 rather than on the - /// 16x16/16x8 blocks r22's recipe produced. `EC_PALSYN=1` on aomdec - /// counts 25 `bsize=BLOCK_8X8 palette_size>0` blocks past the key frame. - /// - /// What it caught beyond the refusal itself: a sub-8x8 group publishes no - /// palette state, so it left the row's `left_palette_size` band holding an - /// earlier 8x8 palette block's size and `av1_get_palette_mode_ctx` read 1 - /// where libaom gathers 0 (decode-order frame 1, mi(30,30), palette size - /// decoded as 8 instead of 2) -- class `new-map-ignores-tile-edge`, fixed - /// at all three sub-8x8 tails. - #[test] - fn a_screen_stream_with_palette_8x8_leaves_in_inter_frames_decodes_pixel_exact() { - const NAME: &str = - "a_screen_stream_with_palette_8x8_leaves_in_inter_frames_decodes_pixel_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("fixtures/palette_screen_leaf8_witness.obu"); - let stream = std::fs::read(&path) - .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display())); - let before = inter8_palette_hits(); - let frames = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => panic!("{NAME}: decode_stream refused: {e}"), - }; - let after = inter8_palette_hits(); - let (fired_y, fired_uv) = (after.0 - before.0, after.1 - before.1); - assert!( - fired_y > 0, - "{NAME}: no palette block on an 8x8 leaf inside an inter frame \ - -- the gate is vacuous for the site whose refusal it pins" - ); - assert_eq!(frames.len(), 15, "{NAME}: 15 shown frames"); - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 256, 192, frames.len()); - assert_eq!(ffmpeg_frames.len(), frames.len(), "{NAME}: frame count"); - for (i, (ours, theirs)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!(ours.y, theirs.y, "{NAME}: frame {i} luma vs ffmpeg"); - assert_eq!(ours.u, theirs.u, "{NAME}: frame {i} U vs ffmpeg"); - assert_eq!(ours.v, theirs.v, "{NAME}: frame {i} V vs ffmpeg"); - } - eprintln!("{NAME}: 15 frames pixel-exact; 8x8-leaf palette y={fired_y} uv={fired_uv}"); - } - - /// lane-t900 r22 GATE for the LIFTED refusal `"a HORZ/VERT intra strip in - /// a screen-content frame (palette syntax is consumed for square blocks - /// only)"` on its 16x4/4x16 arm: that arm routes through - /// `decode_rect4_16_strip`, which takes `allow_screen_content_tools` and - /// reads the whole palette syntax itself, so the refusal was a stale - /// premise (the key-frame path proves that body). This 10-bit - /// `--tune-content=screen` stream reached that exact refusal before the - /// lift and now decodes all 15 frames pixel-exact while 8 inter-frame - /// palette blocks reconstruct. - #[test] - fn a_screen_stream_with_16x4_intra_strips_in_inter_frames_decodes_pixel_exact() { - const NAME: &str = - "a_screen_stream_with_16x4_intra_strips_in_inter_frames_decodes_pixel_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("fixtures/palette_screen_strip16_witness_10bit.obu"); - let stream = std::fs::read(&path) - .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display())); - let before = intra_in_inter_palette_hits(); - let frames = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => panic!("{NAME}: decode_stream refused: {e}"), - }; - let fired_y = intra_in_inter_palette_hits().0 - before.0; - assert!( - fired_y > 0, - "{NAME}: no inter-frame palette block -- gate is vacuous" - ); - assert_eq!(frames.len(), 15, "{NAME}: 15 shown frames"); - let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, 256, 192, frames.len()); - for (i, (ours, theirs)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!(ours.y, theirs.y, "{NAME}: frame {i} luma vs ffmpeg"); - assert_eq!(ours.u, theirs.u, "{NAME}: frame {i} U vs ffmpeg"); - assert_eq!(ours.v, theirs.v, "{NAME}: frame {i} V vs ffmpeg"); - } - eprintln!("{NAME}: 15 frames pixel-exact; inter-frame palette y={fired_y}"); - } - - /// lane-t900 r20 GATE, refusal A -- `"a non-skip rectangular - /// (HORZ/VERT/HORZ_B) strip needs rectangular residual coding"`. - /// - /// That string is a claim about a SHAPE, so what proves it is the set of - /// shapes the inter block path presents. `inter_piece!` sets - /// `reject_residual` to `$ww != $side || $wh != $side`, i.e. only for a - /// block whose true footprint is not its square CDF context, and the - /// refusal then needs `!rect_inter_residual_supported(write_w, write_h)`. - /// So it can fire only for a footprint that is BOTH rectangular (or a - /// square smaller than its own context) AND missing from that table. - /// - /// This gate measures the domain instead of asserting it: - /// [`crate::decode::inter_block_shape_mask`] records every - /// `(side, write_w, write_h)` triple decoded on this thread, with bit 31 - /// reserved for a triple [`crate::decode::INTER_BLOCK_SHAPES`] does not - /// list. Three real streams -- a 10-bit 1920x792 128-superblock film cut, - /// its 128-root intra witness and the 1920x792 small-side warp cut, - /// together ~140k inter blocks -- decode without a refusal and present - /// exactly 18 triples: the four square ones (`write == side`, where - /// `reject_residual` is false) and the fourteen rectangular AV1 block - /// shapes, every one of which `rect_inter_residual_supported` covers. No - /// square-inside-a-larger-context triple appears at all. - /// - /// Measured 2026-09-04: mask covers 18/18 listed triples, bit 31 clear, - /// 0 refusals. - #[test] - fn a_block_shape_census_over_three_real_streams_leaves_the_rect_residual_refusal_unreachable() { - const NAME: &str = "a_block_shape_census_over_three_real_streams_leaves_the_rect_residual_refusal_unreachable"; - const REFUSAL: &str = - "a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual coding"; - let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures"); - let mut blocks = 0usize; - for name in [ - "reelc_sb128_inter_witness.obu", - "intra128_in_inter_witness2.obu", - "gm_small_side_witness.obu", - ] { - let path = dir.join(name); - let stream = std::fs::read(&path) - .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display())); - match decode_stream(&stream) { - Ok(frames) => { - assert!(!frames.is_empty(), "{NAME}: {name} decoded no frame"); - blocks += frames.len(); - } - Err(e) => { - assert!( - !format!("{e}").contains(REFUSAL), - "{NAME}: {name} hit the refusal this gate proves unreachable: {e}" - ); - panic!("{NAME}: {name} refused: {e}"); - } - } - } - assert!(blocks > 0, "{NAME}: no frames decoded"); - let mask = crate::decode::inter_block_shape_mask(); - assert_eq!( - mask & crate::decode::INTER_BLOCK_SHAPE_UNLISTED, - 0, - "{NAME}: a (side, write_w, write_h) triple outside INTER_BLOCK_SHAPES was decoded -- the census no longer describes the inter path's domain, so {REFUSAL:?} is not proven by it" - ); - for (i, &(side, w, h)) in crate::decode::INTER_BLOCK_SHAPES.iter().enumerate() { - assert!( - mask & (1u32 << i) != 0, - "{NAME}: {side}: {w}x{h} never decoded -- the census would prove nothing about it" - ); - // `reject_residual` is false for a square footprint (`write == - // side`), so only the rectangular ones can reach the refusal. - if (w, h) != (side, side) { - assert!( - crate::decode::rect_inter_residual_supported(w, h), - "{NAME}: {w}x{h} is decoded by real streams with reject_residual set but has no rectangular residual path -- {REFUSAL:?} is reachable" - ); - } - } - eprintln!( - "{NAME}: 3 streams, 0 refusals, {} of {} listed (side, write) triples decoded, bit31 clear", - crate::decode::INTER_BLOCK_SHAPES.len(), - crate::decode::INTER_BLOCK_SHAPES.len() - ); - } - - /// lane-t900 r20 GATE, refusal C -- `"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)"`. - /// - /// The arm fires for an INTRA footprint with a side below 8 that carries - /// no chroma-pair record (`strip16`). Two measurements make that a claim - /// rather than a hope: - /// - /// * the block-shape census: the ONLY sub-8 footprints three real streams - /// present are 16x4 and 4x16 at a 16-px context, i.e. the strips of a - /// 16x16-level 1:4 partition -- and that caller sets - /// `INTER_STRIP_CHROMA` for every one of its four strips before the - /// block is decoded, so the record is never missing there; - /// * the sibling counter: the SUPPORTED path - /// ([`crate::decode::intra16x4_in_inter_hits`]) fires on both - /// orientations, chroma-paired, inside streams that decode with no - /// refusal at all. - /// - /// Measured 2026-09-04: 3 streams, 0 refusals, 78 16x4 + 149 4x16 (108 - /// chroma-paired), and 2 of 2 sub-8 census triples are the 1:4 strips. - #[test] - fn a_sub8_footprint_census_over_real_streams_leaves_the_intra_16x4_pairing_refusal_unreachable() - { - const NAME: &str = "a_sub8_footprint_census_over_real_streams_leaves_the_intra_16x4_pairing_refusal_unreachable"; - const REFUSAL: &str = "an intra 16x4/4x16 strip inside an inter 16x16-level 1:4 partition"; - let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures"); - let before = crate::decode::intra16x4_in_inter_hits(); - for name in [ - "reelc_sb128_inter_witness.obu", - "intra128_in_inter_witness2.obu", - "gm_small_side_witness.obu", - ] { - let path = dir.join(name); - let stream = std::fs::read(&path) - .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display())); - if let Err(e) = decode_stream(&stream) { - assert!( - !format!("{e}").contains(REFUSAL), - "{NAME}: {name} hit the refusal this gate proves unreachable: {e}" - ); - panic!("{NAME}: {name} refused: {e}"); - } - } - let after = crate::decode::intra16x4_in_inter_hits(); - let fired = (after.0 - before.0, after.1 - before.1, after.2 - before.2); - assert!( - fired.0 > 0 && fired.1 > 0 && fired.2 > 0, - "{NAME}: the SUPPORTED intra 16x4/4x16-in-inter path fired {fired:?} \ - (16x4, 4x16, chroma-paired) -- with a sibling at zero the refusal's claim is \ - untested from the other side" - ); - let sub8: Vec<(usize, usize, usize)> = crate::decode::INTER_BLOCK_SHAPES - .iter() - .copied() - .filter(|&(_, w, h)| w.min(h) < 8) - .collect(); - assert_eq!( - sub8, - vec![(16, 4, 16), (16, 16, 4)], - "{NAME}: the sub-8 footprints the inter path presents are no longer just the \ - 16x16-level 1:4 strips, whose caller always records the chroma pair -- the \ - refusal's domain changed" - ); - let mask = crate::decode::inter_block_shape_mask(); - for (i, &(side, w, h)) in crate::decode::INTER_BLOCK_SHAPES.iter().enumerate() { - if w.min(h) < 8 { - assert!( - mask & (1u32 << i) != 0, - "{NAME}: {side}: {w}x{h} never decoded -- the sub-8 census is vacuous" - ); - } - } - eprintln!( - "{NAME}: 3 streams, 0 refusals, intra16x4_in_inter 16x4={} 4x16={} chroma_ref={}, \ - sub-8 census triples {sub8:?}", - fired.0, fired.1, fired.2 - ); - } - - /// lane-t900 r10: the small-side GLOBALMV / rect warp-reach witness. - /// `crates/ec-av1/fixtures/gm_small_side_witness.obu`, 1158066 bytes, - /// sha256 `f1cdbcbb8d6d469c7957d70252ab42b24ab75f48a717600ffa25991458775dca`: - /// the first 50 frame-carrying OBUs of a 2 s cut taken 5400 s into a 10-bit - /// 1920x792 AV1 stream with `use_128x128_superblock=1` -- 34 decode-order - /// frames, 33 shown, every ARF in it coded with `allow_warped_motion=1`. - /// Truncated twice independently from the same source, both cuts hash - /// identically. All 34 DECODE-order frames (the hidden ARF included) were - /// compared byte-exact against instrumented aomdec with `EC_AV1_FINAL_DUMP` - /// -- see the lane report's EVIDENCE line; the gate itself compares the 33 - /// shown frames on every plane, which is all ffmpeg hands back. - /// - /// It is the only stream in this repository that fires BOTH r9/r10 paths: - /// - /// * `gm_nontrans_small_side_hits` -- libaom `is_nontrans_global_motion` - /// returns 0 at `AOMMIN(mi_size_wide, mi_size_high) < 2` BEFORE it looks - /// at any warp model, so a GLOBALMV block with a 4-px side still reads - /// its interp filter. We suppressed that symbol before r9. - /// * `tr_reach_longer_side_hits` -- `av1_findSamples` probes the top-right - /// warp sample at `AOMMAX(xd->width, xd->height)` (mvref_common.c:1235) - /// with libaom's two rect shape refinements - /// (`is_last_vertical_rect` / `is_first_horizontal_rect`, - /// av1_common_int.h:1419-1428) applied; probing at the block's WIDTH - /// instead picks the 3-symbol `motion_mode` alphabet where libaom reads - /// the 2-symbol `obmc` one -- same value, different narrowing. - #[test] - fn a_10bit_film_frames_with_small_side_globalmv_and_rect_warp_reach_decode_pixel_exact() { - const NAME: &str = - "a_10bit_film_frames_with_small_side_globalmv_and_rect_warp_reach_decode_pixel_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("fixtures/gm_small_side_witness.obu"); - let stream = std::fs::read(&path) - .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display())); - let (width, height) = (1920usize, 792usize); - let gm_before = crate::decode::gm_nontrans_small_side_hits(); - let tr_before = crate::decode::tr_reach_longer_side_hits(); - // lane-t900 r13: this stream is also the witness for r12's mi-granular - // uv_mode grid -- the chroma edge-filter neighbour read that the coarse - // one-slot-per-column map answered wrongly inside a sub-8x8 pair. - let uv_before = crate::decode::uv_mode_grid_override_hits(); - let frames = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => panic!("{NAME}: decode_stream refused: {e}"), - }; - let gm = crate::decode::gm_nontrans_small_side_hits() - gm_before; - let tr = crate::decode::tr_reach_longer_side_hits() - tr_before; - let uvg = crate::decode::uv_mode_grid_override_hits() - uv_before; - assert!( - uvg > 0, - "{NAME}: uv_mode_grid_override never fired -- the chroma edge-filter \ - grid read would be untested" - ); - assert!( - gm > 0, - "{NAME}: gm_nontrans_small_side never fired -- the gate would be vacuous for it" - ); - assert!( - tr > 0, - "{NAME}: tr_reach_longer_side never fired -- the gate would be vacuous for it" - ); - assert_eq!(frames.len(), 33, "{NAME}: 33 shown frames"); - assert_eq!((frames[0].width, frames[0].height), (width, height)); - let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len()); - assert_eq!( - ffmpeg_frames.len(), - frames.len(), - "{NAME}: ffmpeg returned {} frames, we decoded {}", - ffmpeg_frames.len(), - frames.len() - ); - for (i, (ours, theirs)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!(ours.y, theirs.y, "{NAME}: frame {i} luma vs ffmpeg"); - assert_eq!(ours.u, theirs.u, "{NAME}: frame {i} U vs ffmpeg"); - assert_eq!(ours.v, theirs.v, "{NAME}: frame {i} V vs ffmpeg"); - } - eprintln!( - "{NAME}: 33 shown frames pixel-exact on every plane; \ - gm_nontrans_small_side={gm} tr_reach_longer_side={tr} \ - uv_mode_grid_override={uvg}" - ); - } - - /// lane-film10fix: the DECODE-ORDER half of the two charter-named 10-bit - /// film gates, against the instrumented `aomdec` rather than ffmpeg. - /// - /// `a_10bit_128sb_film_frames_with_warp_cdef_and_interintra_...` (15 shown - /// frames) and `a_10bit_film_frames_with_small_side_globalmv_and_rect_warp_...` - /// (33 shown) each hold exactly ONE hidden alt-ref frame, and both - /// compare through `ffmpeg_decode_sequence_10bit`, which emits SHOWN - /// frames only. So one frame in 16 and one in 34 of each stream is - /// outside both gates' reach -- class `gate-blind-to-hidden-frames`: a - /// defect in a hidden frame surfaces only as drift on some later shown - /// frame, if at all. Their doc comments claim the hidden frames were - /// compared byte-exact against aomdec, but that measurement lived in a - /// lane report, not in a test, so nothing re-ran it. - /// - /// This gate is that measurement, committed. - /// [`decode_all_frames_vs_oracle`] writes `EC_AV1_FINAL_DUMP` on both - /// sides (ours in `decode_stream`, the oracle's in rung 12 of - /// `scripts/instrument-aom-oracle.sh`) and byte-compares EVERY decode-order - /// frame, hidden included. Both fixtures are the same 1920x792 10-bit - /// films their own gates pin, at the sha256 those gates record. - /// - /// The frame counts are asserted, not just reported: 16 = 15 shown + 1 - /// hidden, 34 = 33 shown + 1. A stream that quietly lost its hidden ARF - /// would make this compare fewer frames and would otherwise read as a - /// pass. - #[test] - fn the_two_10bit_film_pins_match_aomdec_on_every_decode_order_frame() { - const NAME: &str = "the_two_10bit_film_pins_match_aomdec_on_every_decode_order_frame"; - let _gate_lock = lock_gate_counters(); - if !aomdec_available(NAME) { - return; - } - // The pin paths are BOUND HERE, from literals, rather than built from - // the loop variable: `crate_pin`'s argument has to be a literal the - // fixture-library census can resolve, or invariant 4 reports this gate - // as UNPROVEN ("name built at runtime -- this census cannot resolve - // it") and a preflight that checks code shape goes RED. - let pins: [(&str, std::path::PathBuf, usize, usize); 2] = [ - ( - "reelc_sb128_inter_witness.obu", - crate_pin("reelc_sb128_inter_witness.obu"), - 16usize, - 15usize, - ), - ( - "gm_small_side_witness.obu", - crate_pin("gm_small_side_witness.obu"), - 34usize, - 33usize, - ), - ]; - for (pin, path, frames, shown) in pins { - let stream = - std::fs::read(&path).unwrap_or_else(|e| panic!("{NAME}: reading {pin}: {e}")); - let (decoded, hidden) = decode_all_frames_vs_oracle(&stream, NAME); - assert_eq!( - (decoded, hidden), - (frames, frames - shown), - "{NAME}: {pin} must decode to {frames} decode-order frames of which {shown} are \ - shown -- a stream that lost its hidden alt-ref would make the byte compare below \ - cover less than it claims" - ); - eprintln!( - "{NAME}: {pin} {decoded} decode-order frames ({hidden} hidden) byte-exact vs \ - aomdec EC_AV1_FINAL_DUMP on every plane" - ); - } - } - - /// lane-t900 r11: the frame-edge MV clamp witness. - /// - /// `crates/ec-av1/fixtures/reelb_head_mvclamp_witness.obu` (72158 bytes, - /// sha256 451a9b138995e636f22308847a123b5c8621d4908cd93772cf5bbf2b37df39d7, - /// truncated twice independently to identical hashes) is the first 80 - /// frame-carrying OBUs of a 10-bit 3840x1608 HDR film head -- the SMALLEST - /// such prefix that fires the clamp (N=79 fires 0, N=80 fires 5). 55 - /// decode-order frames, 52 shown, every decode-order frame byte-identical - /// to instrumented aomdec (`EC_AV1_FINAL_DUMP`, see the r11 report). - /// - /// The path it pins: libaom's `mb_to_right_edge` / `mb_to_bottom_edge` - /// (`set_mi_row_col`, av1_common_int.h) are SIGNED, and a block that - /// overhangs the frame's right/bottom edge keeps its full `bw4`/`bh4`, so - /// `mi_cols - bw4 - mi_col` and `mi_rows - bh4 - mi_row` go NEGATIVE there - /// and `clamp_mv_ref` (mvref_common.h) narrows the stack window by that - /// much. This frame height is 1608 -> `mi_rows == 402`, so every 64x64 - /// block on the bottom row overhangs by 14 mi units. Computing that - /// difference in `usize` saturated it to 0 and left the window 448 subpel - /// too wide, so an edge block's predictor was never clamped -- one 64x64 - /// NEWMV block at mi(400,368) took `mv0=(224,568)` where libaom takes - /// `(32,568)`, its MC then read the replicated bottom row instead of real - /// reference rows, and the frame missed by 221 bytes. - #[test] - fn a_10bit_film_frames_with_frame_edge_mv_clamping_decode_pixel_exact() { - const NAME: &str = "a_10bit_film_frames_with_frame_edge_mv_clamping_decode_pixel_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("fixtures/reelb_head_mvclamp_witness.obu"); - let stream = std::fs::read(&path) - .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display())); - let (width, height) = (3840usize, 1608usize); - let clamp_before = crate::mvstack::mv_clamp_edge_overhang_hits(); - let frames = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => panic!("{NAME}: decode_stream refused: {e}"), - }; - let clamped = crate::mvstack::mv_clamp_edge_overhang_hits() - clamp_before; - assert!( - clamped > 0, - "{NAME}: mv_clamp_edge_overhang never fired -- the gate would be vacuous for it" - ); - assert_eq!(frames.len(), 52, "{NAME}: 52 shown frames"); - assert_eq!((frames[0].width, frames[0].height), (width, height)); - let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len()); - assert_eq!( - ffmpeg_frames.len(), - frames.len(), - "{NAME}: ffmpeg returned {} frames, we decoded {}", - ffmpeg_frames.len(), - frames.len() - ); - for (i, (ours, theirs)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!(ours.y, theirs.y, "{NAME}: frame {i} luma vs ffmpeg"); - assert_eq!(ours.u, theirs.u, "{NAME}: frame {i} U vs ffmpeg"); - assert_eq!(ours.v, theirs.v, "{NAME}: frame {i} V vs ffmpeg"); - } - eprintln!( - "{NAME}: 52 shown frames pixel-exact on every plane; \ - mv_clamp_edge_overhang={clamped}" - ); - } diff --git a/crates/ec-av1/src/stream/tests/t10.rs b/crates/ec-av1/src/stream/tests/t10.rs deleted file mode 100644 index 23c66748..00000000 --- a/crates/ec-av1/src/stream/tests/t10.rs +++ /dev/null @@ -1,4293 +0,0 @@ -use super::*; -use super::support::*; -use super::gates_a::*; -use crate::probe::run_with_stdin; -use std::process::{Command, Stdio}; - - /// lane-sub8x4 r2, the gate that lifts BOTH sub-8x8 intra refusals ("an - /// intra 4x4 block inside an inter frame's sub-8x8 split" and "an intra - /// 8x4/4x8 block inside an inter frame's sub-8x8 HORZ/VERT partition"). - /// - /// Recipe (measured, `~/.cache/sub8intra-tmp/sweep3.sh`): a 24-row band of - /// per-frame-moving noise over a smooth sinusoid, `--min-partition-size=4 - /// --max-partition-size=8 --enable-1to4-partitions=0` -- at that maximum a - /// 16x4 shape cannot exist, so nothing here can be confused with the - /// still-refused intra 1:4 strip, and the noise band is what makes aomenc's - /// RD pick INTRA leaves inside an inter frame's 8x8 groups. 12 arms - /// (8/10-bit x cq 48/55/63 x 128x128/192x128) plus one `--tile-columns=1` - /// arm (COMMON's neighbour-map rule: these leaves publish per-mi side - /// bands), 6 frames each, every decode-order frame and all three planes - /// compared against ffmpeg. Continue-and-sweep: a NAMED refusal is - /// recorded and the arm skipped, any other decode error or any pixel - /// mismatch fails the gate on the spot. - /// - /// The end-of-sweep assert reads all five - /// [`decode::sub8_intra_rect_hits`] cells -- 8x4 leaves, 4x8 leaves, the - /// chroma-reference ones (which code the group's 4x4 chroma intra), - /// `is_sub8x8_inter`-false MIXED groups, and the `PARTITION_SPLIT` 4x4 - /// leaves (the second refusal's own arm) -- so neither lifted refusal - /// rests on a stream that never carried its shape. - #[test] - fn a_real_aomenc_inter_sequence_with_intra_sub8x8_leaves_decodes_pixel_exact() { - const NAME: &str = - "a_real_aomenc_inter_sequence_with_intra_sub8x8_leaves_decodes_pixel_exact"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - if !have_aomenc() { - let msg = format!("no aomenc at {}", aomenc_path().display()); - assert!( - std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none(), - "EC_AV1_REQUIRE_AOMENC is set but {msg}" - ); - eprintln!("SKIP {NAME}: {msg}"); - return; - } - const FRAMES: usize = 6; - // One arm's stream, byte for byte: the lavfi source (a moving 24-row - // random band over `128+50*sin(x/7)`) feeds aomenc through a pipe. - let encode = |depth: u32, cq: u32, width: usize, height: usize, tiles: bool| -> Vec { - let pix = if depth == 10 { - "yuv420p10le" - } else { - "yuv420p" - }; - let source = format!( - "color=c=gray:s={width}x{height}:d=0.24:r=25,format=gray,\ - geq=lum='if(lt(mod(Y+N*37\\,{height})\\,24)\\,random(N*100+X+Y)*255\\,128+50*sin(X/7))',\ - format={pix}" - ); - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-t", - "0.24", - "-pix_fmt", - pix, - "-strict", - "-1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "{NAME}: ffmpeg fixture (depth={depth} cq={cq} {width}x{height}): {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let cq_arg = format!("--cq-level={cq}"); - let mut args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - &cq_arg, - "--cpu-used=0", - "--threads=1", - "--row-mt=0", - "--sb-size=64", - "--enable-restoration=0", - "--enable-palette=0", - "--deltaq-mode=0", - "--enable-intrabc=0", - "--lag-in-frames=0", - "--kf-max-dist=9999", - "--enable-tx-size-search=1", - "--enable-rect-partitions=1", - // The 16x4/4x16 intra strip is a DIFFERENT (still refused) - // shape; keeping 1:4 off is what makes a refusal here mean - // this gate's own arm. - "--enable-1to4-partitions=0", - "--min-partition-size=4", - "--max-partition-size=8", - ]; - if depth == 10 { - args.push("--bit-depth=10"); - args.push("--input-bit-depth=10"); - } - // AOMENC FLAG PRECEDENCE (COMMON): the per-arm override goes last. - args.push(if tiles { - "--tile-columns=1" - } else { - "--tile-columns=0" - }); - args.extend(["--obu", "-o", "-", "-"]); - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "{NAME}: aomenc refused the fixture (depth={depth} cq={cq} {width}x{height}): {}", - String::from_utf8_lossy(&out.stderr) - ); - out.stdout - }; - - let mut refusals: Vec = Vec::new(); - let mut exact_arms = 0u32; - let mut fired = [0usize; 5]; - let mut checked_reproducible = false; - let mut arms: Vec<(u32, u32, usize, usize, bool)> = Vec::new(); - for depth in [8u32, 10] { - for cq in [48u32, 55, 63] { - for (w, h) in [(128usize, 128usize), (192usize, 128usize)] { - arms.push((depth, cq, w, h, false)); - } - } - } - // lane-sub8x4 r3: the `--tile-columns=1` arm COMMON's neighbour-map - // rule asks for. It was excluded in r2 because it desynced at - // decode-order frame 4 -- identically with `--min-partition-size=16 - // --max-partition-size=16`, i.e. with no sub-8x8 block at all. That was - // main's `1d2259c` (the saved motion field kept only the LAST tile's - // columns), merged into this lane in r3; the arm is restored here. - arms.push((8, 63, 192, 128, true)); - for (depth, cq, width, height, tiles) in arms { - let arm = format!("depth={depth} cq={cq} {width}x{height} tiles={tiles}"); - let stream = encode(depth, cq, width, height, tiles); - if !checked_reproducible { - // seeded-fixture-not-reproducible: prove the recipe names ONE - // stream before any measurement rests on it. - let again = encode(depth, cq, width, height, tiles); - assert_eq!( - stream, - again, - "{NAME}: the fixture recipe is not reproducible ({arm}, {} vs {} bytes)", - stream.len(), - again.len() - ); - checked_reproducible = true; - } - let before = decode::sub8_intra_rect_hits(); - let tiles_before = decode::tile_hits(); - let frames = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => { - let msg = e.to_string(); - assert!( - msg.starts_with("unsupported: "), - "{NAME}: decode error that is not a named refusal ({arm}): {msg}" - ); - refusals.push(format!("{arm}: {msg}")); - continue; - } - }; - assert_eq!( - frames.len(), - FRAMES, - "{NAME}: {arm} decoded {} frames", - frames.len() - ); - assert!( - !tiles || decode::tile_hits() - tiles_before >= 2, - "{NAME}: {arm} decoded only {} tile(s)", - decode::tile_hits() - tiles_before - ); - let theirs = if depth == 10 { - ffmpeg_decode_sequence_10bit(&stream, width, height, FRAMES) - } else { - ffmpeg_decode_sequence(&stream, width, height, FRAMES) - }; - for (i, (ours, theirs)) in frames.iter().zip(&theirs).enumerate() { - assert_eq!(ours.y, theirs.y, "{NAME}: {arm} frame {i} luma vs ffmpeg"); - assert_eq!(ours.u, theirs.u, "{NAME}: {arm} frame {i} U vs ffmpeg"); - assert_eq!(ours.v, theirs.v, "{NAME}: {arm} frame {i} V vs ffmpeg"); - } - let now = decode::sub8_intra_rect_hits(); - let delta = [ - now.0 - before.0, - now.1 - before.1, - now.2 - before.2, - now.3 - before.3, - now.4 - before.4, - ]; - exact_arms += 1; - for (slot, d) in fired.iter_mut().zip(delta) { - *slot += d; - } - eprintln!( - "{NAME}: {arm} EXACT 8x4={} 4x8={} chroma_ref={} mixed={} split4x4={}", - delta[0], delta[1], delta[2], delta[3], delta[4] - ); - } - assert!( - exact_arms >= 12, - "{NAME}: only {exact_arms} arm(s) decoded and compared exact; refusals:\n{}", - refusals.join("\n") - ); - for (cell, what) in fired.iter().zip([ - "intra 8x4 leaves", - "intra 4x8 leaves", - "chroma-reference intra leaves", - "is_sub8x8_inter-false MIXED groups", - "intra 4x4 leaves of a sub-8x8 PARTITION_SPLIT", - ]) { - assert!( - *cell > 0, - "{NAME}: zero {what} over {exact_arms} pixel-exact arms -- the lifted refusal \ - rests on nothing (counters {fired:?})" - ); - } - eprintln!( - "{NAME}: {exact_arms} arms pixel-exact over {FRAMES} frames each, counters {fired:?}" - ); - } - - /// lane-thread1: every per-frame/per-stream decode state now lives in - /// [`crate::decode::FrameCtx`], not in a `thread_local!`. A static that - /// comes back would silently re-break frame-parallel decoding (a worker - /// thread sees an empty copy) without failing any pixel gate, so pin the - /// 38 names by name against the sources themselves. - #[test] - fn no_per_frame_state_is_thread_local_any_more() { - const MOVED: [&str; 38] = [ - "SB128", - "CDEF_BITS", - "BIT_DEPTH", - "SUPERRES", - "CDEF_TRANSMITTED", - "CDEF_SB_COLS", - "CDEF_IDX_GRID", - "DELTA_Q_PRESENT", - "DELTA_Q_RES", - "CURRENT_Q_IDX", - "QUANT_DELTAS", - "DELTA_LF_PRESENT", - "DELTA_LF_RES", - "DELTA_LF_MULTI", - "CURRENT_DELTA_LF", - "SEG", - "SEG_IDS", - "PREV_SEG_IDS", - "SEG_MI_DIMS", - "ABOVE_SEG_PRED", - "LEFT_SEG_PRED", - "CUR_SEGMENT_ID", - "SEG_TILE_ORIGIN", - "TX_SELECT_INTER", - "REDUCED_TX_SET_INTER", - "ENABLE_FILTER_INTRA_INTER", - "PALETTE_PRED", - "INTRABC_MI_GRID", - "INTRABC_DV", - "LUMA_TX_TYPE", - "INTRABC_CHROMA_TX", - "INTRA_IN_INTER_MODE", - "INTER_STRIP_CHROMA", - "INTER_LAST_MC", - "ENABLE_EDGE_FILTER", - "LAST_FRAME_WIDE_MARGIN", - "REACH_SB_PX", - "GRAIN_BIT_DEPTH", - ]; - let sources = [ - ("decode.rs", crate::test_source::module_source("decode")), - ("encode.rs", crate::test_source::module_source("encode")), - ("film_grain.rs", include_str!("../../film_grain.rs")), - ]; - let mut back = Vec::new(); - for (name, src) in sources { - for line in src.lines() { - let t = line.trim_start().trim_start_matches("pub(crate) "); - if let Some(rest) = t.strip_prefix("static ") { - let ident = rest.split(':').next().unwrap_or("").trim(); - if MOVED.contains(&ident) { - back.push(format!("{name}: {ident}")); - } - } - } - } - assert!( - back.is_empty(), - "per-frame state is thread_local again (belongs in FrameCtx): {back:?}" - ); - // ... and the scratch pools / gate counters DID stay thread-local: - // this file's own counter reads run on the test thread. - assert!( - crate::test_source::module_source("decode").contains("thread_local!"), - "the scratch pools and gate hit counters are still thread_local by design" - ); - } - - /// lane-d792: a frame whose height the superblock grid CUTS, decoded - /// against ffmpeg on every ladder point of BOTH reference encoders. - /// - /// WHY IT EXISTS: the reference encoders answer a straddling frame with - /// rectangular partitions in the cut superblock row -- the only place - /// these streams code a 16x8/8x4 transform unit at all -- and the rect - /// intra dequant path was reading the FRAME's quantizer index where every - /// square path reads the block's segment-adjusted one - /// (`SEG_LVL_ALT_Q`, class `parsed-then-discarded`). Every gate size - /// before this one was a whole number of superblocks, so no gate ever - /// decoded such a unit: the 1920x792 native BD arm's reference-decode - /// assertion was red on all four rav1e points and this is its small, - /// fast, encoder-independent form. - /// - /// 384x152 is 2 superblocks + 24 px (the 1920x792 straddle, film A's own - /// coded size) and 384x184 is 2 + 56 px (the 1920x1080 straddle), so both - /// the "less than half inside" and the "more than half inside" edge - /// superblock shapes are covered. - #[test] - fn a_straddling_frame_decodes_exactly_on_both_reference_encoders_ladders() { - const NAME: &str = "a_straddling_frame_decodes_exactly_on_both_reference_encoders_ladders"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - const FRAMES: usize = 4; - let mut checked = 0usize; - // The SEGMENTED half of this gate, built BY RECIPE. - // - // The defect this gate exists for only shows on a stream whose - // segments carry distinct `SEG_LVL_ALT_Q`, and neither `testsrc2` nor - // the repo's own clip turns activity segmentation on at all (ledger - // dead-end: 16 ladder points all pass with the defect still in). The - // contrast is therefore built here -- half flat grey, half heavy - // noise -- and libaom's `-aq-mode 1` answers it with segments whose - // quantizer indices differ; `block_q_span()` asserts exactly that, so - // the gate cannot go quietly blind (class `gate-blind-to-feature`). - // This replaces two crops of a real film that could never be - // committed and so SKIPped on every fresh clone. - for (w, h) in [(384usize, 152usize), (384, 184)] { - for crf in ["20", "35"] { - let half = (w / 2).to_string(); - let flat = format!("color=c=gray:s={half}x{h}:r=25:d=1"); - let busy = format!("{flat},noise=alls=80:all_seed=7:allf=t+u"); - let args: Vec = [ - "-v", - "error", - "-f", - "lavfi", - "-i", - &flat, - "-f", - "lavfi", - "-i", - &busy, - "-filter_complex", - "[0:v][1:v]hstack=inputs=2,format=yuv420p", - "-frames:v", - &FRAMES.to_string(), - "-pix_fmt", - "yuv420p", - "-an", - "-threads", - "1", - "-g", - &FRAMES.to_string(), - "-c:v", - "libaom-av1", - "-cpu-used", - "6", - "-b:v", - "0", - "-crf", - crf, - // libaom's activity segmentation, i.e. `SEG_LVL_ALT_Q`. - "-aq-mode", - "1", - "-f", - "obu", - "-", - ] - .iter() - .map(|s| (*s).to_string()) - .collect(); - let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args(&args) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - if !out.status.success() { - eprintln!( - "SKIP {NAME}: ffmpeg cannot encode the segmented {w}x{h} recipe ({})", - String::from_utf8_lossy(&out.stderr) - .lines() - .last() - .unwrap_or("") - ); - continue; - } - let stream = out.stdout; - let want = ffmpeg_decode_sequence(&stream, w, h, FRAMES); - crate::decode::reset_segment_hits(); - let got = decode_stream(&stream).unwrap_or_else(|e| { - panic!("{NAME}: the segmented {w}x{h} crf {crf} recipe refused: {e}") - }); - let (lo, hi) = crate::decode::block_q_span(); - assert!( - hi > lo, - "{NAME}: the segmented {w}x{h} crf {crf} recipe dequantized every block \ - with q {lo} -- no segment carried a distinct SEG_LVL_ALT_Q, so this row \ - would pass with the rect dequant defect back in ({} segment ids seen)", - crate::decode::segment_ids_seen() - ); - assert_eq!( - got.len(), - want.len(), - "{NAME}: segmented {w}x{h} frame count" - ); - for (f, (o, r)) in got.iter().zip(&want).enumerate() { - for (plane, a, b) in [("Y", &o.y, &r.y), ("U", &o.u, &r.u), ("V", &o.v, &r.v)] { - if let Some(i) = a.iter().zip(b.iter()).position(|(x, y)| x != y) { - let stride = if plane == "Y" { w } else { w / 2 }; - panic!( - "{NAME}: segmented {w}x{h} crf {crf}, frame {f} plane {plane} \ - sample ({}, {}): ours {} vs ffmpeg {} (block q span {lo}..{hi})", - i % stride, - i / stride, - a[i], - b[i], - ); - } - assert_eq!( - a.len(), - b.len(), - "{NAME}: segmented {w}x{h} crf {crf}, frame {f} plane {plane}: ours \ - has {} samples, ffmpeg's has {} -- a short plane would \ - zip-truncate the walk above and hide a chroma-span defect", - a.len(), - b.len() - ); - } - } - eprintln!("{NAME}: segmented {w}x{h} crf {crf} exact, block q span {lo}..{hi}"); - checked += 1; - } - } - for (w, h) in [(384usize, 152usize), (384, 184)] { - // The ENCODER-LADDER half: both reference encoders, every - // ladder point, on real (non-bars) content. These rows code ONE - // segment, so they do not gate `SEG_LVL_ALT_Q` -- that is the - // recipe rows' job above -- but they are the rectangular - // partition coverage rav1e's straddle answer adds. - // lane-av1clipprobe: the one probe. This one is worse than a plain - // skip -- it `return`s from the middle of the gate, so everything - // asserted above it had already run and the encoder-ladder half - // silently never did, leaving a half-executed gate reported green. - let Some(clip) = - crate::library_fixture::require("video/h264-1080p-23.976-8bit.mp4", NAME) - else { - return; - }; - for (encoder, points) in [ - ("librav1e", ["50", "100", "150", "200"]), - ("libaom-av1", ["5", "20", "35", "45"]), - ] { - for point in points { - let mut args: Vec = - ["-v", "error", "-i", clip.to_str().expect("fixture path")] - .iter() - .map(|s| (*s).to_string()) - .collect(); - args.extend( - [ - "-frames:v", - &FRAMES.to_string(), - "-vf", - &format!("crop={w}:{h}:768:400"), - "-pix_fmt", - "yuv420p", - "-an", - ] - .iter() - .map(|s| (*s).to_string()), - ); - args.extend( - ["-threads", "1", "-g", &FRAMES.to_string(), "-c:v", encoder] - .iter() - .map(|s| (*s).to_string()), - ); - if encoder == "librav1e" { - args.push("-rav1e-params".into()); - args.push(format!( - "speed=6:quantizer={point}:tile_cols=1:tile_rows=1:threads=1" - )); - } else { - args.extend( - // `-aq-mode 1`: libaom's activity segmentation, - // i.e. `SEG_LVL_ALT_Q` -- the feature the rect - // dequant path used to drop. - [ - "-cpu-used", - "6", - "-b:v", - "0", - "-crf", - point, - "-aq-mode", - "1", - ] - .iter() - .map(|s| (*s).to_string()), - ); - } - args.extend(["-f", "obu", "-"].iter().map(|s| (*s).to_string())); - let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args(&args) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - if !out.status.success() { - eprintln!( - "SKIP {NAME}: ffmpeg cannot encode {w}x{h} with {encoder} ({})", - String::from_utf8_lossy(&out.stderr) - .lines() - .last() - .unwrap_or("") - ); - continue; - } - let stream = out.stdout; - let want = ffmpeg_decode_sequence(&stream, w, h, FRAMES); - let got = decode_stream(&stream).unwrap_or_else(|e| { - panic!("{NAME}: {encoder} {point} at {w}x{h} refused: {e}") - }); - assert_eq!( - got.len(), - want.len(), - "{NAME}: {encoder} {point} at {w}x{h} frame count" - ); - for (f, (o, r)) in got.iter().zip(&want).enumerate() { - for (plane, a, b) in - [("Y", &o.y, &r.y), ("U", &o.u, &r.u), ("V", &o.v, &r.v)] - { - if let Some(i) = a.iter().zip(b.iter()).position(|(x, y)| x != y) { - let stride = if plane == "Y" { w } else { w / 2 }; - panic!( - "{NAME}: {encoder} {point} at {w}x{h}, frame {f} plane \ - {plane} sample ({}, {}): ours {} vs ffmpeg {}", - i % stride, - i / stride, - a[i], - b[i], - ); - } - assert_eq!( - a.len(), - b.len(), - "{NAME}: {encoder} {point} at {w}x{h}, frame {f} plane {plane}: \ - ours has {} samples, ffmpeg's has {} -- a short plane would \ - zip-truncate the walk above and hide a chroma-span defect", - a.len(), - b.len() - ); - } - } - checked += 1; - } - } - } - assert!( - checked > 0, - "{NAME}: neither reference encoder was available" - ); - eprintln!("{NAME}: {checked} straddling reference points decoded sample-exact"); - } - - /// lane-seg2: a SEGMENTED key frame that also codes sub-8x8 INTRA leaves. - /// - /// WHY IT EXISTS: `read_intra_mode_sub8` -- the reader every `BLOCK_4X4` - /// split leaf and every 8x4/4x8 leaf goes through -- never called spec - /// 5.11.6's `intra_segment_id` at all. On a stream with segmentation on - /// it therefore (a) left the block's `segment_id` symbol unread, so the - /// tile desynced from the frame's first sub-8x8 partition on, and (b) - /// dequantized the leaf with the PREVIOUS block's `SEG_LVL_ALT_Q`. - /// Reading it with a hardcoded 1x1 mi footprint was the second half of - /// the same defect: an 8x4 leaf left its second mi cell at segment 0, - /// which the next block read back as its spatial prediction and CDF row. - /// - /// RECIPE: flat gray + heavy `noise` (the contrast is what turns libaom's - /// activity segmentation on -- a `testsrc2`/bars source codes ONE segment - /// and passes with the defect in, ledger dead-end `gate film rows are - /// colour bars`), at `-crf 5 -cpu-used 2`, which is the measured corner - /// where libaom answers with sub-8x8 intra partitions. Measured on this - /// exact stream: red before either half of the fix (134k/134k samples - /// off), green with both. - #[test] - fn a_segmented_key_frame_with_sub_8x8_intra_leaves_decodes_exactly() { - const NAME: &str = "a_segmented_key_frame_with_sub_8x8_intra_leaves_decodes_exactly"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - const FRAMES: usize = 4; - let (w, h) = (384usize, 152usize); - let src = format!("color=c=gray:s={w}x{h}:r=25,noise=alls=80:all_seed=7:allf=t+u"); - let args: Vec = [ - "-v", - "error", - "-f", - "lavfi", - "-i", - &src, - "-frames:v", - "4", - "-pix_fmt", - "yuv420p", - "-an", - "-threads", - "1", - "-g", - "4", - "-c:v", - "libaom-av1", - "-cpu-used", - "2", - "-b:v", - "0", - "-crf", - "5", - "-aq-mode", - "1", - "-f", - "obu", - "-", - ] - .iter() - .map(|s| (*s).to_string()) - .collect(); - let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args(&args) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - if !out.status.success() { - eprintln!( - "SKIP {NAME}: ffmpeg cannot encode with libaom-av1 ({})", - String::from_utf8_lossy(&out.stderr) - .lines() - .last() - .unwrap_or("") - ); - return; - } - let stream = out.stdout; - crate::decode::reset_segment_hits(); - let want = ffmpeg_decode_sequence(&stream, w, h, FRAMES); - let got = decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME}: refused: {e}")); - assert_eq!(got.len(), want.len(), "{NAME}: frame count"); - for (f, (o, r)) in got.iter().zip(&want).enumerate() { - for (plane, a, b) in [("Y", &o.y, &r.y), ("U", &o.u, &r.u), ("V", &o.v, &r.v)] { - if let Some(i) = a.iter().zip(b.iter()).position(|(x, y)| x != y) { - let stride = if plane == "Y" { w } else { w / 2 }; - panic!( - "{NAME}: frame {f} plane {plane} sample ({}, {}): ours {} vs ffmpeg {}", - i % stride, - i / stride, - a[i], - b[i], - ); - } - assert_eq!( - a.len(), - b.len(), - "{NAME}: frame {f} plane {plane}: ours has {} samples, ffmpeg's has {} -- a \ - short plane would zip-truncate the walk above and hide a chroma-span \ - defect", - a.len(), - b.len() - ); - } - } - // The property is asserted, not hoped for: without more than one - // segment this row would pass with the defect still in. - assert!( - crate::decode::segment_ids_seen() >= 2, - "{NAME}: vacuous run -- {} distinct segment ids", - crate::decode::segment_ids_seen() - ); - eprintln!( - "{NAME}: {FRAMES} frames sample-exact, {} segment_id symbols, {} distinct ids", - crate::decode::segment_id_hits(), - crate::decode::segment_ids_seen() - ); - } - - /// lane-av1leftref: the left chroma reference's `+ss_y` ROW term - /// (libaom `av1_common_int.h:1400-1401`, `chroma_left_mi = - /// base_mi[ss_y * mi_stride - 1]` -- one mi row DOWN at 4:2:0 and 4:4:0, - /// on its own row at 4:2:2 and 4:4:4). This decoder read its own row at - /// every subsampling until this lane. - /// - /// The read is only observable when the two cells hold DIFFERENT blocks -- - /// a left neighbour at most 1 mi tall (1 mi = 4 luma px, so a 4x4/8x4/16x4 - /// /32x4/64x4 leaf). lane-av1leftwit measured that shape off a per-cell - /// owner stamp instead of the mode value: `uv_left_1mi_split_hits()` counts - /// decode-path reads whose two cells were written by DIFFERENT blocks, and - /// it is NOT zero -- five committed fixtures carry it (15 reads in all, - /// `lanes/av1leftwit.report.md`). What no committed fixture shows is the two - /// blocks DISAGREEING on `uv_mode`, which is what `mode_diff`/`smooth_diff` - /// below measure. So this gate pins both halves honestly: the arm runs - /// thousands of times, the shape it needs is genuinely reached, and the - /// term has not yet been seen to change an answer. Its exactness arms are - /// what would decide the shipped read if a DIFF bucket ever went non-zero. - /// - /// A non-zero DIFF bucket is not a failure here -- it is the first stream - /// that witnesses the term, and the exactness arms below are what then - /// decide whether the shipped read is the one that matches the oracle. - #[test] - fn a_4to20_key_frame_takes_the_left_chroma_reference_read_its_libaom_row() { - const NAME: &str = "a_4to20_key_frame_takes_the_left_chroma_reference_read_its_libaom_row"; - if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); - return; - } - // 3840x1608 10-bit key frame, the densest 4:2:0 intra leaf mix in the - // fixture set and the stream that carries the most `+ss_y` reads. - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures/reelb_kf900.obu"); - let stream = std::fs::read(&path) - .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display())); - let (width, height) = (3840usize, 1608usize); - let before = crate::decode::uv_left_ss_y_reads(); - let frames = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => panic!("{NAME}: decode_stream refused: {e}"), - }; - let reads = crate::decode::uv_left_ss_y_reads() - before; - let mode_diff = crate::decode::uv_left_ss_y_mode_diff_hits(); - let smooth_diff = crate::decode::uv_left_ss_y_smooth_diff_hits(); - assert!( - reads > 1000, - "{NAME}: only {reads} chroma edge-filter reads took the `+ss_y` left \ - reference -- the arm this test pins is barely exercised, so the gate \ - proves little" - ); - assert_eq!(frames.len(), 1, "{NAME}: one key frame"); - assert_eq!((frames[0].width, frames[0].height), (width, height)); - // The term is unreachable on this stream, so luma and BOTH chroma - // planes must come out byte-identical to ffmpeg's decode. Luma alone - // (what the kf900 gate asserts) would not notice a chroma edge-filter - // type moving. - let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1); - assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg"); - assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg"); - assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg"); - eprintln!( - "{NAME}: {reads} left-reference reads, +ss_y changed the mode {mode_diff} \ - and the smooth boolean {smooth_diff} times, all three planes pixel-exact" - ); - } - - /// lane-av1leftwit: the `+ss_y` term's SHAPE is reachable on the decode - /// path, and this is the gate that says so. - /// - /// lane-av1leftref shipped the left read's `+ss_y` row term with the - /// argument that the shape it needs -- a left neighbour at most 1 mi tall, - /// so the cell this decoder read and the cell libaom reads belong to - /// different blocks -- is "structurally absent, because aomenc never starts - /// a block on an odd mi row". Both halves of that are wrong. libaom's - /// `PARTITION_HORZ_4` puts its `i == 0` child on the PARENT's own mi row - /// (`decode_partition`, `av1/decoder/decodeframe.c`: `mi_row + i * bw / 4`), - /// and a 16x16 parent sits on a 4-mi grid, so a 1-mi-tall leaf at an EVEN - /// row is what the syntax asks for, not forbids. And the shape is measured - /// in the corpus: these two fixtures each present it to a real decode-path - /// read. - /// - /// The counter is `decode::uv_left_1mi_split_hits()`, incremented only - /// where `decode_path` is true -- the snapping form every decode call site - /// uses -- so the 16x4/4x16 pair witness's counter-only mirror (which - /// reads an odd mi row and feeds `RECT4_16_UV_PAIR_FILT_HITS`) cannot - /// inflate it. `UV_LEFT_SS_Y_READS` alone would prove nothing: it counts - /// every read with a left neighbour, whether or not the two cells differ. - /// - /// NON-VACUITY: the `uv_owner` stamp the counter turns on was removed for - /// one build; both arms fell to 0 and this gate failed on the census - /// (report §5), so a decoder that stops recording which block owns a cell - /// fails here instead of passing vacuously. It is deliberately NOT a - /// mutation of the `+ss_y` term itself: the term's own mutation leaves - /// these reads untouched, which is the honest limit of what the fixture - /// set can decide (the kf900 gate above owns the exactness side). - #[test] - fn a_committed_4to20_stream_presents_a_one_mi_left_neighbour_to_a_decode_path_read() { - const NAME: &str = - "a_committed_4to20_stream_presents_a_one_mi_left_neighbour_to_a_decode_path_read"; - // (fixture, frames, width, height, measured split-owner reads) - let arms: [(&str, usize, usize, usize, usize); 2] = [ - ("gm_small_side_witness.obu", 33, 1920, 792, 5), - ("reelc_sb128_inter_witness.obu", 15, 1920, 792, 7), - ]; - for (fixture, want_frames, width, height, want_split) in arms { - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("fixtures") - .join(fixture); - let stream = std::fs::read(&path) - .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display())); - let before_split = crate::decode::uv_left_1mi_split_hits(); - let before_reads = crate::decode::uv_left_ss_y_reads(); - let before_mode = crate::decode::uv_left_ss_y_mode_diff_hits(); - let before_smooth = crate::decode::uv_left_ss_y_smooth_diff_hits(); - let frames = match decode_stream(&stream) { - Ok(frames) => frames, - Err(e) => panic!("{NAME}: {fixture} refused: {e}"), - }; - let split = crate::decode::uv_left_1mi_split_hits() - before_split; - assert_eq!(frames.len(), want_frames, "{NAME}: {fixture} frame count"); - assert!( - frames - .iter() - .all(|f| (f.width, f.height) == (width, height)), - "{NAME}: {fixture} is not {width}x{height}" - ); - assert_eq!( - split, want_split, - "{NAME}: {fixture} presented {split} 1-mi-tall left neighbours to \ - a decode-path read, measured {want_split} -- the census this \ - gate pins moved" - ); - // Printed, not asserted: `== 0` would pin an accident, and a - // non-zero value is the first WITNESS of the term rather than a - // failure (that is what the kf900 gate above then decides against - // the oracle). - eprintln!( - "{NAME}: {fixture}: {split} 1-mi-tall left neighbours in \ - {} decode-path reads, +ss_y changed the mode {} and the smooth \ - boolean {} times", - crate::decode::uv_left_ss_y_reads() - before_reads, - crate::decode::uv_left_ss_y_mode_diff_hits() - before_mode, - crate::decode::uv_left_ss_y_smooth_diff_hits() - before_smooth, - ); - } - } - - /// lane-av1formatsweep: the ODD CODED DIMENSION cell -- a frame whose - /// width or height is not a multiple of 8, so the last mode-info column - /// and the last chroma plane row/column are PARTIAL (`mi_cols * 8 > - /// width`, and at 4:2:0 the chroma plane is `ceil(w/2) x ceil(h/2)`). - /// - /// Nothing else in this file ever encoded one: every frame size in the - /// suite (the `tiny_frame_size_sweep` ladder included -- 8,16,24,32,48, - /// 64,72,136,192) is a multiple of 8, so the partial-chroma-plane walk - /// had no committed exactness evidence at any depth. The class matters - /// for a 4:2:2 lift too: at ss (1,0) the chroma plane is - /// `ceil(w/2) x h`, so the partial extent lands on the OTHER axis. - /// - /// NON-VACUITY: `decode::inter_edge_strip_hits()` (the frame-edge strip - /// walk) is asserted to fire, and the even-size control arm is asserted - /// to leave it at zero -- measured: 130x122 -> `[0,2,0,4,0,6]`, - /// 130x130 -> `[0,3,0,2,24,6]`, 128x96 -> all zero. Without that pair a - /// decoder that dropped the partial column entirely would still pass the - /// pixel compare (class `gate-blind-to-feature`). - /// - /// Recipe (deterministic: single pass, single thread, no row-mt): - /// `ffmpeg -f lavfi -i testsrc2=size=x:rate=25 -frames:v 4 - /// -pix_fmt -f yuv4mpegpipe -` piped to - /// `aomenc --codec=av1 --passes=1 --end-usage=q --cq-level=20 - /// --cpu-used=2 --threads=1 --row-mt=0 --lag-in-frames=0 - /// --kf-max-dist=100 --limit=4 --obu -o - -`, plus - /// `--input-bit-depth=N --bit-depth=N` at 10 and 12 bits. The 12-bit arm - /// uses the smoothed `mandelbrot` source because a sharp-edged source - /// makes aomenc set `allow_screen_content_tools`, which this decoder - /// refuses BY NAME at 12 bits (see `a_12bit_screen_content_stream_is_ - /// refused_by_name`). - /// - /// NON-VACUITY, RED-BEFORE PROVEN: the mode-info grid's ceil is the - /// arithmetic this cell depends on, and mutating it turns every arm red - /// -- `ec-av1-syntax`'s `h.mi_cols = 2 * ((h.frame_width + 7) >> 3)` - /// floored to `2 * (h.frame_width >> 3)` makes the first arm fail at - /// decode-order frame 0, byte 128 (ours 74 vs oracle 170, 11538 bytes - /// differ); reverted, the gate is green again. A NEARER mutation, - /// flooring `decode::round_ss` from libaom's `ROUND_POWER_OF_TWO`, - /// leaves this gate GREEN and is not evidence either way: aomenc rounds - /// a 4:2:0 frame's coded size DOWN to even, so no stream this recipe can - /// produce codes an odd luma dimension, and the chroma-extent ceil only - /// differs from its floor when the luma dimension is itself odd. - /// - /// Also asserted, so a recipe that silently became even-dimensioned can - /// not pass as this cell: the header's `ss (1,1)` and bit depth, the - /// partial mode-info grid (`mi*8 > dim`), every frame's chroma plane - /// being `ceil(w/2)*ceil(h/2)`, and - /// `decode::inter_edge_strip_hits()` non-zero after a per-arm reset -- - /// measured per arm: `[0,6,0,4,48,12]`, `[0,0,0,4,0,6]`, - /// `[0,4,0,10,0,10]`, `[0,4,0,8,0,12]`, `[0,4,0,8,0,8]`, - /// `[0,0,0,12,0,14]`, where the even-size control (128x96) reads all - /// zeros. Without the counter a decoder that dropped the partial column - /// entirely would still pass the pixel compare (class - /// `gate-blind-to-feature`). - #[test] - fn a_real_aomenc_odd_coded_dimension_streams_decode_pixel_exact() { - const NAME: &str = "a_real_aomenc_odd_coded_dimension_streams_decode_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() || !have_aomenc() { - eprintln!("SKIP {NAME}: no ffmpeg/aomenc"); - return; - } - // (width, height, pix_fmt, bit_depth, smooth_source) - let arms: &[(usize, usize, &str, usize, bool)] = &[ - (130, 130, "yuv420p", 8, false), - (66, 66, "yuv420p", 8, false), - (194, 122, "yuv420p", 8, false), - (130, 122, "yuv420p", 8, false), - (130, 122, "yuv420p10le", 10, false), - (130, 122, "yuv420p12le", 12, true), - ]; - let mut odd_arms = 0usize; - for &(width, height, pix_fmt, bit_depth, smooth) in arms { - let stream = odd_dim_stream(width, height, pix_fmt, bit_depth, smooth); - // The header must really carry the odd geometry, or the arm - // silently degrades to an even-dimension stream (class - // `arrival-not-intent`). - let (mi_cols, mi_rows) = odd_dim_header_mi_grid(&stream, NAME, bit_depth); - assert!( - mi_cols * 8 > width || mi_rows * 8 > height, - "{NAME}: {width}x{height} is not an odd coded dimension \ - (mi grid {mi_cols}x{mi_rows})" - ); - // Reset per attempt, never a delta across arms (class - // `counter-from-refused-stream`). - crate::decode::reset_inter_edge_strip_hits(); - let (frames_decoded, _hidden) = decode_all_frames_vs_oracle(&stream, NAME); - let frames = decode_stream(&stream) - .unwrap_or_else(|e| panic!("{NAME}: refused {width}x{height}: {e}")); - let chroma = width.div_ceil(2) * height.div_ceil(2); - for (i, f) in frames.iter().enumerate() { - assert_eq!(f.y.len(), width * height, "{NAME}: frame {i} luma extent"); - assert_eq!( - f.u.len(), - chroma, - "{NAME}: frame {i} chroma extent -- a {width}x{height} frame's \ - chroma plane is ceil(w/2)*ceil(h/2) = {chroma}, not w/2*h/2" - ); - } - let edge = crate::decode::inter_edge_strip_hits(); - assert!( - edge.iter().any(|&n| n > 0), - "{NAME}: {width}x{height} decoded byte-exact but walked NO \ - frame-edge strip -- the partial-column chroma extent this \ - cell exists for was never reached (class \ - `gate-blind-to-feature`): {edge:?}" - ); - eprintln!( - "{NAME}: {width}x{height} {pix_fmt}: {frames_decoded} frames \ - byte-exact vs aomdec, frame-edge walk {edge:?}" - ); - odd_arms += 1; - } - assert!(odd_arms == arms.len(), "{NAME}: arm loop ended early"); - } - - /// lane-av1formatsweep: the 4:4:4 x 10-BIT cell. Every committed 4:4:4 - /// exactness gate in this file is `--lossless=1` at 8 bits - /// (`a_real_aomenc_lossless_444_key_frame_decodes_sample_exact`, - /// `a_lossless_444_min_partition64_inter_stream_decodes_pixel_exact`, - /// `a_lossless_444_defaultp_inter_strip_stream_decodes_byte_exact`, the - /// `ll444_*` pins), so the whole committed 4:4:4 evidence base is LOSSLESS - /// 8-bit: no 4:4:4 stream above 8 bits had a committed exactness gate. - /// - /// NON-VACUITY: `decode::rect_split_lossless_chroma444_hits()` -- the - /// per-4x4 chroma unit walk a lossless HORZ/VERT strip takes at - /// subsampling 0/0 -- is asserted to fire (measured 32 units on this - /// recipe), and the sequence header is asserted to say ss (0,0) at - /// 10-bit before any pixel is trusted. A 4:2:0 stream of the same - /// content leaves that counter at zero, so the pixel compare alone would - /// not prove the 4:4:4 chroma path ran (class `gate-blind-to-feature`). - /// - /// Recipe: `testsrc2 128x96` yuv444p10le 6 frames, `aomenc --codec=av1 - /// --profile=1 --input-bit-depth=10 --bit-depth=10 --lossless=1 - /// --enable-palette=0 --enable-intrabc=0 --cq-level=20 --cpu-used=2 - /// --passes=1 --end-usage=q --threads=1 --row-mt=0 --lag-in-frames=0 - /// --kf-max-dist=100 --limit=6 --obu -o - -`. - #[test] - fn a_lossless_444_10bit_inter_stream_decodes_pixel_exact() { - const NAME: &str = "a_lossless_444_10bit_inter_stream_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() || !have_aomenc() { - eprintln!("SKIP {NAME}: no ffmpeg/aomenc"); - return; - } - let stream = chroma_format_stream( - 128, - 96, - "yuv444p10le", - 10, - 6, - &[ - "--lossless=1", - "--enable-palette=0", - "--enable-intrabc=0", - // `--cpu-used=2`, NOT 0: at `--cpu-used=0` aomenc reaches - // the 128-root partition (measured `part128: split=1 - // none=5` where this recipe reads `none=0`) and THAT stream - // diverges at 10-bit 4:4:4 from frame 1 on -- 11152 of - // 36864 samples, first at Y(8,4), with ffmpeg and aomdec - // agreeing on the reference. Handoff, not this gate's - // subject; see `lanes/av1formatsweep.report.md`. - "--cpu-used=2", - "--cq-level=20", - ], - 0, - ); - assert_444_header(&stream, NAME, 10); - let before_444 = crate::decode::rect_split_lossless_chroma444_hits(); - let (frames_decoded, _hidden) = decode_all_frames_vs_oracle(&stream, NAME); - assert!( - crate::decode::rect_split_lossless_chroma444_hits() > before_444, - "{NAME} went blind: no lossless strip walked its chroma as 4:4:4 \ - 4x4 units" - ); - assert!( - frames_decoded >= 6, - "{NAME}: expected the six-frame recipe to decode" - ); - eprintln!("{NAME}: {frames_decoded} frames byte-exact vs aomdec at 10-bit 4:4:4"); - } - - /// lane-av1formatsweep: the 4:4:4 x 12-BIT cell -- the deepest chroma - /// format the spec allows, and the one no committed gate reached. A - /// sharp-edged source makes aomenc set `allow_screen_content_tools`, - /// which this decoder refuses BY NAME at 12 bits (palette and intrabc - /// have no 12-bit witness), so the arm encodes the SMOOTHED - /// `mandelbrot` source -- the same trick `a_real_aomenc_12bit_stream_ - /// decodes_pixel_exact`'s in-tree source exists for. - /// - /// NON-VACUITY: the header is asserted to say ss (0,0) at 12 bits, - /// `mc::mc_subpel_hits()` (the 12-bit-sensitive subpel round pair) must - /// fire -- a key-frame-only stream would pass the pixel compare without - /// touching it -- and every decoded frame's chroma plane is asserted to - /// be FULL resolution, which is the 4:4:4 extent itself. - /// - /// Recipe: `mandelbrot 128x96` + `-vf gblur=sigma=6` yuv444p12le 6 frames, - /// `aomenc --codec=av1 --input-bit-depth=12 --bit-depth=12 --passes=1 - /// --end-usage=q --cq-level=20 --cpu-used=2 --threads=1 --row-mt=0 - /// --lag-in-frames=0 --kf-max-dist=100 --limit=6 --obu -o - -`. - /// aomenc picks `seq_profile=2` here (12-bit forces it) with - /// `subsampling_x/y = 0,0` -- still 4:4:4 planes. lane-av1422lift: 4:2:2 - /// (1,0) is DECODED now, so the only subsampling the decoder still asserts - /// against is the uncodable 4:4:0 (0,1) cell, closed by - /// `the_440_cell_is_not_a_codable_chroma_shape`. - #[test] - fn a_444_12bit_inter_sequence_decodes_pixel_exact() { - const NAME: &str = "a_444_12bit_inter_sequence_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() || !have_aomenc() { - eprintln!("SKIP {NAME}: no ffmpeg/aomenc"); - return; - } - let stream = chroma_format_stream(128, 96, "yuv444p12le", 12, 6, &["--cq-level=20"], 1); - assert_444_header(&stream, NAME, 12); - let before_subpel = crate::mc::mc_subpel_hits(); - let frames = decode_stream(&stream) - .unwrap_or_else(|e| panic!("{NAME}: refused a real 12-bit 4:4:4 stream: {e}")); - let (frames_decoded, _hidden) = decode_all_frames_vs_oracle(&stream, NAME); - assert!( - crate::mc::mc_subpel_hits() > before_subpel, - "{NAME} went blind: no subpel inter prediction ran, so the \ - 12-bit round pair is unexercised" - ); - // The 4:4:4 chroma EXTENT is the cell's own claim: at ss (0,0) the - // chroma planes are full resolution, so a decoder that kept the - // 4:2:0 extent would produce quarter-size chroma planes and a - // byte-length the oracle cannot even match. (CDEF is NOT asserted - // here: on this smoothed source CDEF runs but skips every band -- - // measured `cdef_band: rect_skip_writes=11`, zero index literals -- - // so a CDEF assertion would be a claim the witness cannot carry.) - for (i, f) in frames.iter().enumerate() { - assert_eq!( - f.u.len(), - 128 * 96, - "{NAME}: frame {i} chroma plane is {} samples -- at 4:4:4 it \ - must be full resolution (128x96), not the 4:2:0 quarter", - f.u.len() - ); - } - eprintln!("{NAME}: {frames_decoded} frames byte-exact vs aomdec at 12-bit 4:4:4"); - } - - /// lane-av1tilemeasure: 12-BIT 4:2:0 with tile ROWS genuinely enabled, and - /// with a 2x2 tile grid. `gate_coverage.rs` records that the multi-tile - /// 2D grid is covered "at both bit depths" -- meaning 8 and 10; 12 was the - /// gap, and the sweep's 12-bit "tile rows" cell (t420_12_row) never - /// encoded an untiled control, so nobody could say which stream it had - /// measured. - /// - /// Recipe (per arm): `mandelbrot 256x256` + `-vf gblur=sigma=6` - /// yuv420p12le 6 frames (the 12-bit screen-tools refusal fires on a sharp - /// source -- H6), `aomenc --codec=av1 --passes=1 --end-usage=q - /// --cq-level=20 --cpu-used=2 --enable-palette=0 --enable-intrabc=0 - /// --threads=1 --row-mt=0 --lag-in-frames=0 --kf-max-dist=100 --limit=6 - /// --input-bit-depth=12 --bit-depth=12 --obu -o - -` plus `--tile-rows=1` - /// (arm 1) or `--tile-columns=1 --tile-rows=1` (arm 2). - /// - /// NON-VACUITY, in the order a reader should check it: - /// 1. the sequence header is `ss (1,1)` at 12 bits - /// (`odd_dim_header_mi_grid`); - /// 2. EVERY frame header's parsed `tile_info` is 1x2 / 2x2 -- the trap-2 - /// guard: an untiled stream fails here before a pixel is read; - /// 3. `decode::tile_hits()` advances by at least one hit per tile per - /// frame, so tile 1 (and the second ROW) really decoded rather than the - /// first tile being decoded twice; - /// 4. every decoded plane is 256*256 samples -- a truncated or - /// quarter-extent decode fails the shape assert; - /// 5. `decode_all_frames_vs_oracle` asserts the decode-order frame COUNT - /// and each frame's byte LENGTH against the instrumented `aomdec` - /// before any sample is compared (a prefix compare is not a compare -- - /// the same report's trap 1). - #[test] - fn a_real_aomenc_12bit_stream_with_two_tile_rows_and_a_two_by_two_tile_grid_decodes_pixel_exact() - { - const NAME: &str = "a_real_aomenc_12bit_stream_with_two_tile_rows_and_a_two_by_two_tile_grid_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() || !have_aomenc() { - eprintln!("SKIP {NAME}: no ffmpeg/aomenc"); - return; - } - let arms: [(&str, &[&str], u32, u32); 2] = [ - ("two tile rows", &["--tile-rows=1"], 1, 2), - ( - "a 2x2 tile grid", - &["--tile-columns=1", "--tile-rows=1"], - 2, - 2, - ), - ]; - for (label, tiles, want_cols, want_rows) in arms { - let mut extra = vec![ - "--cq-level=20", - "--cpu-used=2", - "--enable-palette=0", - "--enable-intrabc=0", - ]; - extra.extend_from_slice(tiles); - let stream = chroma_format_stream(256, 256, "yuv420p12le", 12, 6, &extra, 1); - odd_dim_header_mi_grid(&stream, NAME, 12); - let facts = frame_facts(&stream, NAME); - assert_eq!( - facts.len(), - 6, - "{NAME} ({label}): expected six frame headers, parsed {}", - facts.len() - ); - for (i, f) in facts.iter().enumerate() { - assert_eq!( - (f.tile_cols, f.tile_rows), - (want_cols, want_rows), - "{NAME} ({label}): decode-order frame {i} parses tile_info {}x{}, not \ - {want_cols}x{want_rows} -- the aomenc tile flag was a NO-OP at this \ - geometry, so this arm would be measuring an untiled stream", - f.tile_cols, - f.tile_rows - ); - } - let before_tiles = crate::decode::tile_hits(); - let frames = decode_stream(&stream) - .unwrap_or_else(|e| panic!("{NAME} ({label}): refused the stream: {e}")); - let tile_hits = crate::decode::tile_hits() - before_tiles; - assert!( - tile_hits >= facts.len() * (want_cols * want_rows) as usize, - "{NAME} ({label}): tile_hits advanced by {tile_hits} over {} frames of a \ - {}x{} grid -- not every tile decoded", - facts.len(), - want_cols, - want_rows - ); - for (i, f) in frames.iter().enumerate() { - assert_eq!( - f.y.len(), - 256 * 256, - "{NAME} ({label}): frame {i} luma plane is {} samples, not 256x256", - f.y.len() - ); - } - let (frames_decoded, _hidden) = decode_all_frames_vs_oracle(&stream, NAME); - assert!( - frames_decoded >= 6, - "{NAME} ({label}): {frames_decoded} decode-order frames" - ); - eprintln!( - "{NAME} ({label}): {frames_decoded} frames byte-exact vs aomdec, tiles \ - {want_cols}x{want_rows} confirmed on every frame header, tile_hits {tile_hits}" - ); - } - } - - /// lane-av1tilemeasure: 4:4:4 SUPERRES at 8, 10 and 12 bits. The sweep's - /// superres row was `--superres-mode=1` alone, and measured that recipe - /// at 4:4:4 8 bits: this lane re-encoded it and read `use_superres` on - /// every frame header -- ZERO frames carried it, so that cell never - /// exercised the upscaler at all (the same "an aomenc flag is not - /// evidence" trap as tile rows, one axis over). libaom only signals - /// `use_superres` when a DENOMINATOR is given, so the arms here spell - /// `--superres-denominator=12 --superres-kf-denominator=12` and the - /// header says `use_superres=1` on all four frames. - /// - /// Recipe: `testsrc2 128x128` yuv444p10le (12-bit: the gblur'd - /// `mandelbrot`, H6) 4 frames, `aomenc --codec=av1 --passes=1 - /// --end-usage=q --cq-level=20 --cpu-used=2 --enable-palette=0 - /// --enable-intrabc=0 --superres-mode=1 --superres-denominator=12 - /// --superres-kf-denominator=12 --threads=1 --row-mt=0 --lag-in-frames=0 - /// --kf-max-dist=100 --limit=4 --input-bit-depth=N --bit-depth=N --obu - /// -o - -`. Coded width comes out 85px, upscaled to 128. - /// - /// NON-VACUITY: `ss (0,0)` at the claimed depth; EVERY frame header has - /// `use_superres` with a coded width strictly below the upscaled one (a - /// stream without it fails here, not at the pixel compare); - /// `superres::superres_hits()` advances once per frame (the upscaler - /// really ran); every decoded plane is the UPSCALED 128x128 -- a decoder - /// that forgot the upsample would hand back 85x128 and fail the shape - /// assert, and at `ss (0,0)` the chroma planes must be full resolution - /// too; then the length-asserting `aomdec` compare. - #[test] - fn a_real_aomenc_444_superres_stream_at_8_10_and_12_bit_decodes_pixel_exact() { - const NAME: &str = - "a_real_aomenc_444_superres_stream_at_8_10_and_12_bit_decodes_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() || !have_aomenc() { - eprintln!("SKIP {NAME}: no ffmpeg/aomenc"); - return; - } - for (depth, pix_fmt, smooth) in [ - (8usize, "yuv444p", 0u8), - (10, "yuv444p10le", 0), - (12, "yuv444p12le", 1), - ] { - let stream = chroma_format_stream( - 128, - 128, - pix_fmt, - depth, - 4, - &[ - "--cq-level=20", - "--cpu-used=2", - "--enable-palette=0", - "--enable-intrabc=0", - "--superres-mode=1", - "--superres-denominator=12", - "--superres-kf-denominator=12", - ], - smooth, - ); - assert_444_header(&stream, NAME, depth); - let facts = frame_facts(&stream, NAME); - for (i, f) in facts.iter().enumerate() { - assert!( - f.use_superres, - "{NAME} ({depth}-bit): decode-order frame {i} has use_superres=0 -- the \ - superres cell would be measuring an ordinary 4:4:4 stream" - ); - assert!( - f.coded_w < f.upscaled_w, - "{NAME} ({depth}-bit): frame {i} codes {}px and upscaled_width says {}px", - f.coded_w, - f.upscaled_w - ); - assert_eq!(f.upscaled_w, 128, "{NAME} ({depth}-bit): upscaled width"); - } - let before_sr = crate::superres::superres_hits(); - let frames = decode_stream(&stream) - .unwrap_or_else(|e| panic!("{NAME} ({depth}-bit): refused the stream: {e}")); - let superres_hits = crate::superres::superres_hits() - before_sr; - assert!( - superres_hits >= facts.len(), - "{NAME} ({depth}-bit): superres_hits advanced by {superres_hits} over {} \ - frames -- the upscaler never ran", - facts.len() - ); - for (i, f) in frames.iter().enumerate() { - assert_eq!( - f.y.len(), - 128 * 128, - "{NAME} ({depth}-bit): frame {i} luma is {} samples -- a superres decode \ - must hand back the UPSCALED 128x128, not the 85px coded width", - f.y.len() - ); - assert_eq!( - f.u.len(), - 128 * 128, - "{NAME} ({depth}-bit): frame {i} chroma is {} samples -- at 4:4:4 the chroma \ - plane is full resolution at the upscaled size", - f.u.len() - ); - } - let (frames_decoded, _hidden) = decode_all_frames_vs_oracle(&stream, NAME); - assert!( - frames_decoded >= 4, - "{NAME} ({depth}-bit): {frames_decoded} decode-order frames" - ); - eprintln!( - "{NAME} ({depth}-bit): {frames_decoded} frames byte-exact vs aomdec, \ - use_superres on every frame, superres_hits {superres_hits}" - ); - } - } - - /// lane-av1tilemeasure: 4:4:4 at PARTIAL and ODD coded dimensions, - /// 8/10/12 bits -- and a correction to what the sweep's "odd dims" cell - /// was measuring. - /// - /// **The sweep's odd-dimension 4:4:4 cells were not odd.** 66x66, - /// 130x122 and 194x130 are even in BOTH axes; what they are is "not a - /// multiple of 8", the same class as the 4:2:0 row the sweep measured as - /// "even, not a multiple of 8". This gate's own assert said so out loud - /// on its first run: `the 66x66 arm is even in BOTH axes`. The genuinely - /// odd arms are the two 12-bit ones, and they are producible only at 12 - /// bits: at 8 and 10 bits aomenc rounds a 4:4:4 odd size DOWN to even - /// (`67x67` -> coded 66x66, `131x131` -> coded 130x130, both measured), - /// the same rounding the sweep proved for 4:2:0. 12-bit (seq_profile 2) - /// keeps 67x67 and 65x67 odd, and both decode byte-exact. - /// - /// The sweep's 130x122 DIVERGENT verdict is also corrected here: this - /// lane re-encoded the identical stream (the bytes reproduce the - /// sweep's sha256 `c87ac65b…`) and it is byte-exact against `aomdec`. - /// That published verdict came from the prefix compare the same report - /// documents as its trap 1. - /// - /// Recipe per arm: `testsrc2 WxH` yuv444p[10le|12le] 4 frames (12-bit: - /// the gblur'd `mandelbrot`, H6), `aomenc --codec=av1 --passes=1 - /// --end-usage=q --cq-level=20 --cpu-used=2 --enable-palette=0 - /// --enable-intrabc=0 --threads=1 --row-mt=0 --lag-in-frames=0 - /// --kf-max-dist=100 --limit=4 --obu -o - -` (plus `--input-bit-depth` / - /// `--bit-depth` above 8). - /// - /// NON-VACUITY: `ss (0,0)` at the claimed depth; the arm is not a - /// multiple of 8 in some axis, and the `odd` flag says whether an axis is - /// odd, so an arm cannot quietly become the cell next door; EVERY frame - /// header's coded width and height are exactly the claimed sizes -- a - ///omenc rounding would make the arm measure a different geometry and fails - /// here rather than at the pixel compare; the mode-info grid is PARTIAL - /// (`mi_cols*8 > width` or `mi_rows*8 > height`), the partial-plane walk - /// the cell exists for; every decoded plane is exactly `width*height` (at - /// `ss (0,0)` the chroma planes are full resolution, so a 4:2:0 extent or - /// a truncated decode fails the shape assert); then the - /// length-asserting `aomdec` compare. - #[test] - fn a_real_aomenc_444_partial_and_odd_coded_dimension_streams_decode_pixel_exact() { - const NAME: &str = - "a_real_aomenc_444_partial_and_odd_coded_dimension_streams_decode_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() || !have_aomenc() { - eprintln!("SKIP {NAME}: no ffmpeg/aomenc"); - return; - } - // (width, height, bit depth, smooth source, an axis is odd) - let arms: [(usize, usize, usize, u8, bool); 10] = [ - (66, 66, 8, 0, false), - (98, 66, 8, 0, false), - (130, 122, 8, 0, false), - (66, 66, 10, 0, false), - (194, 130, 10, 0, false), - (130, 122, 10, 0, false), - (66, 66, 12, 1, false), - (130, 122, 12, 1, false), - (67, 67, 12, 1, true), - (65, 67, 12, 1, true), - ]; - for (w, h, depth, smooth, odd) in arms { - assert!( - w % 8 != 0 || h % 8 != 0, - "{NAME}: the {w}x{h} arm is a multiple of 8 -- it is not a partial-size cell" - ); - assert_eq!( - w % 2 == 1 || h % 2 == 1, - odd, - "{NAME}: the {w}x{h} arm's `odd` flag is wrong" - ); - let pix_fmt = match depth { - 8 => "yuv444p", - 10 => "yuv444p10le", - _ => "yuv444p12le", - }; - let stream = chroma_format_stream( - w, - h, - pix_fmt, - depth, - 4, - &[ - "--cq-level=20", - "--cpu-used=2", - "--enable-palette=0", - "--enable-intrabc=0", - ], - smooth, - ); - assert_444_header(&stream, NAME, depth); - let facts = frame_facts(&stream, NAME); - for (i, f) in facts.iter().enumerate() { - assert_eq!( - (f.coded_w as usize, f.coded_h as usize), - (w, h), - "{NAME} ({w}x{h} {depth}-bit): decode-order frame {i} codes {}x{} -- the arm \ - is not measuring the geometry it names", - f.coded_w, - f.coded_h - ); - assert!( - f.mi_cols as usize * 8 > w || f.mi_rows as usize * 8 > h, - "{NAME} ({w}x{h} {depth}-bit): frame {i} has a {}x{} mode-info grid, which \ - covers the frame exactly -- the partial-plane walk never runs", - f.mi_cols, - f.mi_rows - ); - } - let frames = decode_stream(&stream) - .unwrap_or_else(|e| panic!("{NAME} ({w}x{h} {depth}-bit): refused: {e}")); - for (i, f) in frames.iter().enumerate() { - assert_eq!( - f.y.len(), - w * h, - "{NAME} ({w}x{h} {depth}-bit): frame {i} luma is {} samples", - f.y.len() - ); - assert_eq!( - f.u.len(), - w * h, - "{NAME} ({w}x{h} {depth}-bit): frame {i} chroma is {} samples -- at 4:4:4 \ - the chroma plane is full resolution even at an odd coded size", - f.u.len() - ); - } - let (frames_decoded, _hidden) = decode_all_frames_vs_oracle(&stream, NAME); - assert!( - frames_decoded >= 4, - "{NAME} ({w}x{h} {depth}-bit): {frames_decoded} decode-order frames" - ); - eprintln!( - "{NAME}: {w}x{h} {depth}-bit codes exactly as named (odd axis: {odd}), \ - {frames_decoded} frames byte-exact vs aomdec" - ); - } - } - - /// lane-av1tilemeasure: the H3 CONTROL -- 4:4:4 LOSSLESS 8-bit with NO - /// tiles -- beside its two-tile-column sibling at the same geometry. The - /// sweep's H3 named a 90-chroma-sample divergence on a lossless 4:4:4 - /// tile-column stream; the control it never encoded is the untiled stream - /// at the same size, and without it "tiles cause it" and "4:4:4 lossless - /// chroma causes it" are the same sentence. Measured here: BOTH arms are - /// byte-exact against the oracle at 256x128, so at THIS geometry the - /// defect does not reproduce with or without tiles; the first 4:4:4 - /// lossless fork measured in this lane is at 192x192 (34 chroma samples, - /// first U(90,25)), where the tiled and untiled streams diverge at the - /// very same sample -- see `lanes/av1tilemeasure.report.md`. - /// - /// Recipe per arm: `testsrc2 256x128` yuv444p 6 frames, `aomenc - /// --codec=av1 --lossless=1 --passes=1 --end-usage=q --threads=1 - /// --row-mt=0 --lag-in-frames=0 --kf-max-dist=100 --limit=6 - /// --enable-palette=0 --enable-intrabc=0 --obu -o - -`, plus - /// `--tile-columns=1` on the sibling. - /// - /// NON-VACUITY: `ss (0,0)` at 8 bits; every frame header's parsed - /// `tile_info` is 1x1 for the control and 2x1 for the sibling (so the - /// control cannot silently become a tiled stream, which is the whole - /// point of the arm); `decode::rect_split_lossless_chroma444_hits()` - /// advances, i.e. a lossless strip really walked its chroma as 4:4:4 4x4 - /// units; then the length-asserting `aomdec` compare. - #[test] - fn a_lossless_444_8bit_untiled_control_and_its_two_tile_column_sibling_decode_pixel_exact() { - const NAME: &str = "a_lossless_444_8bit_untiled_control_and_its_two_tile_column_sibling_decode_pixel_exact"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() || !have_aomenc() { - eprintln!("SKIP {NAME}: no ffmpeg/aomenc"); - return; - } - let arms: [(&str, &[&str], u32, u32); 2] = [ - ( - "untiled control", - &["--lossless=1", "--enable-palette=0", "--enable-intrabc=0"], - 1, - 1, - ), - ( - "two tile columns", - &[ - "--lossless=1", - "--enable-palette=0", - "--enable-intrabc=0", - "--tile-columns=1", - ], - 2, - 1, - ), - ]; - for (label, flags, want_cols, want_rows) in arms { - let stream = chroma_format_stream(256, 128, "yuv444p", 8, 6, flags, 0); - assert_444_header(&stream, NAME, 8); - let facts = frame_facts(&stream, NAME); - for (i, f) in facts.iter().enumerate() { - assert_eq!( - (f.tile_cols, f.tile_rows), - (want_cols, want_rows), - "{NAME} ({label}): decode-order frame {i} parses tile_info {}x{}, not \ - {want_cols}x{want_rows}", - f.tile_cols, - f.tile_rows - ); - } - let before_444 = crate::decode::rect_split_lossless_chroma444_hits(); - let (frames_decoded, _hidden) = decode_all_frames_vs_oracle(&stream, NAME); - assert!( - crate::decode::rect_split_lossless_chroma444_hits() > before_444, - "{NAME} ({label}) went blind: no lossless strip walked its chroma as 4:4:4 4x4 \ - units, so the cell never reached the 4:4:4 chroma path" - ); - assert!( - frames_decoded >= 6, - "{NAME} ({label}): {frames_decoded} decode-order frames" - ); - eprintln!( - "{NAME} ({label}): {frames_decoded} frames byte-exact vs aomdec, tiles \ - {want_cols}x{want_rows} confirmed on every frame header" - ); - } - } - - /// lane-av1loss444kf: the 4:4:4 lossless 256x256 key frame's 49-sample - /// chroma damage, and the `Reach` a transform unit inside a sub-8x8 RECT - /// leaf must be given. - /// - /// The cell: `testsrc2 256x256 rate=25` yuv444p, 6 frames, - /// `aomenc --lossless=1 --enable-palette=0 --enable-intrabc=0` -- **109215 - /// bytes, sha256 `4563a01f1778600020ffa9f15bc05f5559321cf5712b99a29ed7192675dee6a4`, - /// fnv1a64 `0xbbb56442f393a9b2`**. Its key frame decodes with **21 U + 28 V - /// samples wrong** (U over x 196..207 / y 200..203, V over x 196..206), - /// luma exact, entropy bit-locked over all 81933 of its symbol reads and - /// its 12288 transform units at identical absolute `(plane, x, y)`. - /// - /// The defect: libaom's `has_bottom_left` (`reconintra.c:381`) is asked - /// with the **leaf's** `bsize`, the unit's `(row_off, col_off)` and - /// `tx_size` -- and its first branch inside the left column is - /// `if (row_off + bottom_left_count_unit < plane_bh_unit) return 1;`, the - /// block's OWN next row, already reconstructed. A 4x8 leaf's first TX_4X4 - /// unit therefore HAS four bottom-left samples. `sub8_leaf_chroma444` - /// instead looked a standalone `BLOCK_4X4` up at the unit's own position - /// (`Reach::of(4, upx, upy, ..)`), which answers false there, so - /// [`PlaneBuf::edges`] replicated the last left sample out to the edge's - /// full `bw + bh` reach and the unit predicted D203/CFL from a fabricated - /// edge. The 4:2:2 twin of the same function was fixed this way already - /// (lane-av1-422kf2, whose comment names the old lookup); this is its - /// 4:4:4 twin, still carrying the stale copy. - /// - /// Non-vacuity, in order: - /// 1. the live re-encode's length AND fnv1a64 -- a recipe or encoder drift - /// fails here instead of passing as this cell; - /// 2. [`assert_444_header`] -- at 4:2:0 the arm is unreachable (every - /// caller of `sub8_leaf_chroma444` sits behind `chroma_444`) and every - /// assert below would pass for free; - /// 3. [`key_frame_diffs`] == 0 samples, with the first differing sample - /// NAMED in the failure so a regression is a location, not a count; - /// 4. [`crate::decode::sub8_chroma444_lossless_tu_reach_hits`] rose over - /// the decode -- the units where the block-relative answer and the - /// standalone one disagree, which is what makes this a witness of the - /// FIXED path and not of a stream that merely has rect leaves. - #[test] - fn a_lossless_444_sub8_rect_leaf_chroma_reach_decodes_the_key_frame_pixel_exact() { - const NAME: &str = "lossless-444-sub8-rect-leaf-chroma-reach"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() || !have_aomenc() { - eprintln!("SKIP {NAME}: no ffmpeg/aomenc"); - return; - } - let stream = chroma_format_stream( - 256, - 256, - "yuv444p", - 8, - 6, - &["--lossless=1", "--enable-palette=0", "--enable-intrabc=0"], - 0, - ); - assert_eq!( - (stream.len(), fnv1a64(&stream)), - (109215, 0xbbb5_6442_f393_a9b2), - "{NAME}: the pinned 4:4:4 lossless 256x256 cell is {} bytes / fnv1a64 {:#x}, \ - not 109215 / 0xbbb56442f393a9b2 -- the recipe or the encoder drifted, so a \ - result here is not a result about this cell", - stream.len(), - fnv1a64(&stream) - ); - assert_444_header(&stream, NAME, 8); - crate::decode::reset_sub8_chroma444_tu_reach_hits(); - let (differing, first) = key_frame_diffs(&stream, NAME); - assert_eq!( - differing, 0, - "{NAME}: the 4:4:4 lossless key frame differs from aomdec in {differing} samples \ - (first {first:?} as (plane, x, y, ours, oracle)) -- a sub-8x8 RECT leaf's chroma \ - unit must be given the reach libaom's has_bottom_left computes for the LEAF, not a \ - standalone BLOCK_4X4 lookup at the unit's own position" - ); - let reach_hits = crate::decode::sub8_chroma444_lossless_tu_reach_hits(); - assert!( - reach_hits > 0, - "{NAME}: went blind -- not one 4:4:4 lossless rect-leaf chroma unit had the \ - block-relative reach disagree with the standalone BLOCK_4X4 lookup, so the cell \ - never reached the fixed path and the byte-exactness above proves nothing about it" - ); - eprintln!( - "{NAME}: key frame byte-exact vs aomdec (0 of 196608 samples differ), {reach_hits} \ - rect-leaf chroma unit(s) took the block-relative reach" - ); - } - - /// lane-av1distwtd: the gate that pays the `enable-dist-wtd-comp` entry in - /// `gate_coverage.rs`'s [`NEVER_EXERCISED_8BIT`], and corrects its stated - /// reason. The entry said "distance-weighted compound is unimplemented" -- - /// it is NOT: [`crate::compound::dist_wtd_comp_weight_assign`] (lane-av1comp) - /// and `mc::combine_compound`'s weighted path have been in the tree since. - /// What was missing is a stream that CARRIES the tool. Proved producible - /// against aom 3.13.3: the flag maps onto the sequence header's - /// `enable_jnt_comp` bit (`av1_cx_iface.c:1062` -> - /// `order_hint_info.enable_dist_wtd_comp` -> `bitstream.c:2681` writes it - /// under `enable_order_hint`), and this recipe's parsed header prints - /// `jnt_comp=true` with `=1` and `jnt_comp=false` with `=0` -- the parsed - /// value is asserted, never the flag spelling, per the class - /// `knob-never-reached-the-tool` trap that mislabelled a cell once already. - /// - /// Three hard asserts, all load-bearing: - /// 1. the PARSED sequence header carries `enable_jnt_comp == true` (the - /// off-arm asserts `false` from the same recipe, so the bit is proven to - /// MOVE with the flag rather than to be set by something else); - /// 2. `dist_wtd_comp_hits() > 0` -- the `compound_idx == 0` arm, the only - /// branch whose blend weights are not the constant (8, 8). A stream - /// carrying the header bit while coding every compound block with - /// `compound_idx == 1` leaves this at 0 and decodes byte-identically - /// without the whole distance-weight path, so the counter -- not the - /// header bit -- is what makes this a witness of the TOOL; - /// 3. every frame pixel-compared against the oracle through - /// [`decode_all_frames_vs_oracle`], which length-asserts each - /// decode-order frame before zipping. - /// - /// `--min-partition-size=32` is what makes the arm fire: at 16 the encoder - /// emits 8x8 inter leaves this decoder refuses BY NAME, so a smaller - /// min-partition refuses before the `compound_idx` read ever runs (measured: - /// the `min=16` arm of the same recipe refuses with "an inter partition - /// below 16x16" and dumps zero `compound_idx` lines). `--cq-level=30` is - /// likewise load-bearing: at cq 45/55 the same arm encodes a single-ref - /// stream (zero `compound_idx` reads) and the counter assert would be - /// vacuous. - #[test] - fn a_distance_weighted_compound_stream_decodes_pixel_exact() { - const NAME: &str = "distwtd-comp"; - let _gate_lock = lock_gate_counters(); - if !have_aomenc() { - return; - } - assert!(have_ffmpeg(), "{NAME}: ffmpeg required"); - assert!( - aomdec_path().is_file(), - "{NAME}: aomenc resolved to {} but no aomdec sits beside it -- a \ - pixel-exactness gate that compares nothing is worse than no gate", - aomenc_path().display() - ); - let (width, height, frame_count) = (64usize, 64usize, 24usize); - // mandelbrot + a slow rotation: two genuinely different references at - // different temporal distances, which is what `dist_wtd_comp_weight_ - // assign` weights BY. A static or flat source has equal distances - // everywhere and every block collapses onto one weight row. - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - "mandelbrot=size=128x128:rate=25:start_x=-0.6:start_y=-0.4,\ - rotate=a=0.01*n:ow=128:oh=128:c=black,scale=64:64", - "-t", - "0.96", - "-pix_fmt", - "yuv420p", - "-strict", - "-1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "{NAME}: ffmpeg fixture: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - // the shared recipe; the flag under test is appended per arm so the - // two arms differ in exactly one argument. - let recipe: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=30", - "--cpu-used=0", - "--kf-max-dist=1000", - "--threads=1", - "--row-mt=0", - "--auto-alt-ref=1", - "--lag-in-frames=25", - "--enable-fwd-kf=0", - // `enable_jnt_comp` is only READ when order hints are on - // (`av1_cx_iface.c:1491` ANDs the two). - "--enable-order-hint=1", - "--enable-warped-motion=1", - "--tune-content=default", - "--min-partition-size=32", - "--max-partition-size=64", - // partition/intra tools this decoder does not code -- the same - // exclusion list every compound gate in this file carries. - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", - "--enable-tx-size-search=0", - "--enable-cdef=0", - "--enable-restoration=0", - "--enable-palette=0", - "--enable-intrabc=0", - "--enable-cfl-intra=0", - "--enable-ref-frame-mvs=0", - ]; - let encode = |flag: &str| -> Vec { - let out = run_with_stdin( - Command::new(aomenc_path()).args( - recipe - .iter() - .copied() - .chain([flag, "--obu", "-o", "-", "-"]), - ), - &y4m.stdout, - ); - assert!( - out.status.success(), - "{NAME}: aomenc refused the fixture with {flag}: {}", - String::from_utf8_lossy(&out.stderr) - ); - out.stdout - }; - // The PARSED header, read back off the encoded bytes -- never the - // command line. `Av1Parser` walks the real OBUs, so a flag the encoder - // ignored is caught here rather than inherited into coverage. - let parsed_jnt_comp = |stream: &[u8]| -> bool { - let mut parser = Av1Parser::new(); - let mut pos = 0usize; - while pos < stream.len() { - let obu = parser - .parse_obu(&stream[pos..]) - .expect("parsing our own OBUs"); - pos += obu.total_size; - } - parser - .sequence_header() - .expect("the stream carries a sequence header") - .enable_jnt_comp - }; - // NB: the OFF arm is spelled FIRST on purpose. `gate_coverage.rs`'s - // `flags_in` keeps the LAST `--enable-=` it finds in a gate - // body, so a trailing `=0` would make the whole gate read as "tool - // disabled" to the census and leave the entry unretired even though - // this gate does exercise the tool. Both arms are still asserted below. - let off = encode("--enable-dist-wtd-comp=0"); - let on = encode("--enable-dist-wtd-comp=1"); - // the bit MOVES with the flag, and it moves the BYTES: a flag the - // encoder accepted but ignored would fail both of these. - assert!( - parsed_jnt_comp(&on), - "{NAME}: the recipe spelled --enable-dist-wtd-comp=1 but the PARSED \ - sequence header carries enable_jnt_comp == false (class \ - knob-never-reached-the-tool) -- the gate would be vacuous" - ); - assert!( - !parsed_jnt_comp(&off), - "{NAME}: the same recipe with --enable-dist-wtd-comp=0 still parses \ - enable_jnt_comp == true, so the ON arm proves nothing about the flag" - ); - assert_ne!( - on.len(), - off.len(), - "{NAME}: both arms encoded {} bytes -- the flag changed nothing on \ - the wire, so neither arm is evidence for anything", - on.len() - ); - // shape non-vacuity, before any compare: at 4:2:0 a decoder keeping a - // subsampled extent would hand quarter-size planes to the byte compare. - let frames = decode_stream(&on).unwrap_or_else(|e| panic!("{NAME}: refused: {e}")); - assert_eq!( - frames.len(), - frame_count, - "{NAME}: expected {frame_count} shown frames" - ); - for (i, f) in frames.iter().enumerate() { - assert_eq!( - (f.width, f.height), - (width, height), - "{NAME}: frame {i} is {}x{}", - f.width, - f.height - ); - assert_eq!( - f.u.len(), - width * height / 4, - "{NAME}: frame {i} U plane is {} samples, not 4:2:0", - f.u.len() - ); - assert_eq!(f.v.len(), f.u.len(), "{NAME}: frame {i} V plane extent"); - assert_eq!(f.y.len(), width * height, "{NAME}: frame {i} luma extent"); - } - crate::decode::reset_dist_wtd_comp_hits(); - let hits_before = crate::decode::dist_wtd_comp_hits(); - let (oracle_frames, hidden) = decode_all_frames_vs_oracle(&on, NAME); - let dist_wtd = crate::decode::dist_wtd_comp_hits() - hits_before; - eprintln!( - "{NAME}: {oracle_frames} oracle frames ({hidden} hidden), \ - dist_wtd_comp_hits={dist_wtd}, on={} B off={} B", - on.len(), - off.len() - ); - assert!( - dist_wtd > 0, - "{NAME}: no block took the distance-weighted compound combine \ - (compound_idx == 0) across {oracle_frames} frames that carry \ - enable_jnt_comp = true -- every compound block used the simple \ - average, so this gate proves nothing about the tool" - ); - } - - /// lane-whtshape: a LOSSLESS 4:4:4 frame whose rect intra-BC blocks used - /// to code their chroma plane block as ONE rect transform unit -- a shape - /// libaom cannot code. `read_tx_mode` (`av1/decoder/decodeframe.c:140`) - /// returns `ONLY_4X4` for a `coded_lossless` frame BEFORE it looks at the - /// `tx_mode` symbol, `read_tx_size` (`:1117`) returns `TX_4X4` before it - /// looks at a tree, `get_vartx_max_txsize` (`av1/common/blockd.h:1447`) - /// returns `TX_4X4` for EVERY plane of a lossless block, and of - /// `av1/common/idct.c`'s `highbd_inv_txfm_add_*_c` only the 4x4 one carries - /// a `lossless` branch -- the rest fall through to the IDCT, because there - /// is no non-4x4 lossless inverse transform to dispatch to. - /// - /// The 8x4 unit that resulted reached the lossless Walsh-Hadamard path, - /// where a `debug_assert_eq!` named it in DEBUG and the RELEASE build died - /// one frame later with an opaque `range end index 8 out of range for slice - /// of length 0` (measured, not assumed -- see - /// lanes/whtshape.report.md r1). - /// - /// The witness is `fixtures/ll444_sb64_1to4_lossless.obu` (51107 bytes, - /// sha256 `fdb6467987095b99c8eb51b48743691d906b2d99d069f71f1d51b1abb6d2056e`), - /// encoded with the instrumented oracle - /// (`scripts/build-aom-oracle.sh`'s `aomenc`, 4:4:4 10-bit, `--lossless=1 - /// --profile=1 --i444 --enable-rect-partitions=1 - /// --enable-1to4-partitions=1 --min-partition-size=4 --max-partition-size=64 - /// --sb-size=64 --tune-content=screen --enable-intrabc=1 --enable-palette=1 - /// --cq-level=60 --enable-tx-size-search=0 --cpu-used=0 --limit=2`) over - /// `ffmpeg -f lavfi -i testsrc2=size=256x256:rate=25:duration=1 -pix_fmt - /// yuv444p10le -f rawvideo`. 4:2:0 cannot produce the shape at all -- its - /// smallest lossless chroma plane block is already 4x4 -- which is why the - /// 4:4:4 10-bit header is asserted. - /// - /// Four assertions, each with its own failure: - /// - /// 1. the route fired: `INTRABC_RECT_LOSSLESS_CHROMA4_HITS` is EXCLUSIVE to - /// the per-4x4 chroma walk (no other caller walks a rect intra-BC - /// block's chroma), so `>= 1` cannot be satisfied by the old - /// single-unit read; - /// 2. NO non-4x4 lossless transform unit was reconstructed - /// (`LOSSLESS_WHT_SPLIT_UNITS` delta 0) -- the shape-total WHT entry is - /// not quietly papering over a caller that is still wrong; - /// 3. the stream DECODES both frames (before the fix the same bytes were a - /// RELEASE panic and a Golomb-tail refusal in DEBUG); and - /// 4. a PIXEL comparison against the instrumented oracle's own - /// `EC_AV1_FINAL_DUMP`, in DECODE order. - /// - /// **(4) is a PREFIX floor, not an exactness claim, and it says so.** - /// Measured against the oracle, decode-order frame 0 (the key frame) is - /// byte-exact on all three planes for its first 32992 of 65536 samples -- - /// the whole frame above row 128, plus row 128 out to column 224. The - /// first differing sample there is (x=224, y=128) on Y, U and V alike: the - /// first column PAST the 16x8 lossless intra-BC block at mi (32, 52), - /// whose own 16x8 luma and chroma are byte-exact -- so the fork is at the - /// block boundary, in the block that FOLLOWS it. Decode-order frame 1 (the - /// inter frame) is exact to 55008 on luma and to 9378 on chroma. Both forks - /// are a SEPARATE defect this lane does not own; each is named with its - /// measurement in lanes/whtshape.report.md r3. Asserting "our output is - /// wrong by exactly N" would encode those defects as expected behaviour; - /// the per-frame, per-plane floor is the honest form, and it only grows. - #[test] - fn a_444_lossless_sb64_intrabc_rect_chroma_walks_4x4_units() { - const NAME: &str = "a_444_lossless_sb64_intrabc_rect_chroma_walks_4x4_units"; - const FIXTURE: &str = "ll444_sb64_1to4_lossless.obu"; - const FIXTURE_LEN: usize = 51107; - const FIXTURE_FNV: u64 = 0x7664_6a62_ddd3_4df2; - const FRAMES: usize = 2; - const PLANE: usize = 256 * 256; - /// Per decode-order frame, per plane (0=Y, 1=U, 2=V), the number of - /// leading samples MEASURED byte-exact against the oracle's - /// `EC_AV1_FINAL_DUMP`; the first differing sample is exactly this - /// index on that plane. Key frame: the whole frame above row 128 plus - /// row 128 out to column 224. Inter frame: luma exact to (224, 214), - /// chroma diverging early at (162, 36). - const EXACT_PREFIX: [[usize; 3]; 2] = [[32992, 32992, 32992], [55008, 9378, 9378]]; - let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join(format!("fixtures/{FIXTURE}")); - let stream = read_pin(&obu, FIXTURE_LEN, FIXTURE_FNV, NAME); - assert_444_header(&stream, NAME, 10); - - let _guard = lock_gate_counters(); - crate::decode::reset_intrabc_rect_lossless_chroma4_hits(); - let split_before = crate::decode::lossless_wht_split_units(); - let wht_before = crate::decode::lossless_wht_units(); - let frames = decode_stream(&stream) - .unwrap_or_else(|e| panic!("{NAME}: the pinned witness was refused: {e}")); - let chroma4 = crate::decode::intrabc_rect_lossless_chroma4_hits(); - let split = crate::decode::lossless_wht_split_units() - split_before; - let wht = crate::decode::lossless_wht_units() - wht_before; - - assert!( - chroma4 > 0, - "{NAME}: no LOSSLESS rect intra-BC block walked its chroma as 4x4 units \ - -- the corrected route never ran, so this gate is measuring the old \ - single rect unit (class gate-blind-to-feature)" - ); - assert_eq!( - split, 0, - "{NAME}: {split} 4x4 WHT unit(s) were reconstructed inside a LOSSLESS \ - transform unit that was itself not 4x4 -- a caller is still sizing a \ - lossless unit wrongly and the shape-total WHT entry is hiding it" - ); - assert!( - wht > 0, - "{NAME}: no lossless WHT unit ran at all -- vacuous" - ); - assert_eq!(frames.len(), FRAMES, "{NAME}: frame count"); - - // The probe decides; its own SKIP (and its assert under - // EC_AV1_REQUIRE_AOMDEC / EC_AV1_REQUIRE_AOMENC) has already been said. - if !aomdec_available(NAME) { - eprintln!( - "{NAME}: {chroma4} lossless rect intra-BC block(s) walked 4x4 chroma units, \ - {wht} WHT units, 0 split" - ); - return; - } - // The oracle's own final-frame dumps, in DECODE order, against ours. - let dir = std::env::temp_dir().join(format!("ec-av1-{NAME}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).expect("scratch dir"); - let in_obu = dir.join("in.obu"); - std::fs::write(&in_obu, &stream).expect("writing the stream"); - let aom_prefix = dir.join("aom"); - let out = crate::tool_cache::cached_output_io(Command::new(aomdec_path()) - .args(["--codec=av1", "-o"]) - .arg(dir.join("out.y4m")) - .arg(&in_obu) - .env("EC_AV1_FINAL_DUMP", &aom_prefix) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("aomdec failed to run"); - assert!( - out.status.success(), - "{NAME}: the oracle aomdec refused the stream: {}", - String::from_utf8_lossy(&out.stderr) - ); - let ours_prefix = dir.join("ours"); - set_final_dump_prefix(Some(ours_prefix.display().to_string())); - let shown = decode_stream(&stream) - .unwrap_or_else(|e| panic!("{NAME}: the second decode was refused: {e}")) - .len(); - set_final_dump_prefix(None); - let count = |prefix: &std::path::Path| -> usize { - let mut n = 0usize; - while std::path::PathBuf::from(format!("{}.f{n}", prefix.display())).is_file() { - n += 1; - } - n - }; - let oracle_frames = count(&aom_prefix); - let our_frames = count(&ours_prefix); - assert_eq!( - our_frames, oracle_frames, - "{NAME}: decoded {our_frames} frames in decode order, the oracle decoded \ - {oracle_frames}" - ); - for i in 0..oracle_frames { - let want = - std::fs::read(format!("{}.f{i}", aom_prefix.display())).expect("oracle dump"); - let got = std::fs::read(format!("{}.f{i}", ours_prefix.display())).expect("our dump"); - assert_eq!( - got.len(), - want.len(), - "{NAME}: decode-order frame {i} is {} bytes, the oracle's is {}", - got.len(), - want.len() - ); - assert_eq!( - got.len(), - 3 * PLANE * 2, - "{NAME}: decode-order frame {i} is not three 256x256 16-bit planes" - ); - for (plane, name) in [(0usize, "Y"), (1, "U"), (2, "V")] { - let at = plane * PLANE * 2; - let floor = EXACT_PREFIX[i.min(EXACT_PREFIX.len() - 1)][plane].min(PLANE); - if got[at..at + floor * 2] == want[at..at + floor * 2] { - continue; - } - let first = (0..floor) - .find(|&s| got[at + s * 2..at + s * 2 + 2] != want[at + s * 2..at + s * 2 + 2]) - .unwrap_or(floor); - panic!( - "{NAME}: decode-order frame {i} plane {name} diverges from the oracle at \ - sample {first} of {PLANE} (x={}, y={}) -- the exact prefix this gate pins \ - is {floor} and it only grows; the rest is the OPEN defect named in \ - lanes/whtshape.report.md r3", - first % 256, - first / 256 - ); - } - } - let _ = std::fs::remove_dir_all(&dir); - eprintln!( - "{NAME}: {chroma4} lossless rect intra-BC block(s) walked 4x4 chroma units, \ - {wht} WHT units, 0 split; {oracle_frames} decode-order frame(s) ({shown} shown) \ - byte-exact against the oracle up to the per-frame, per-plane exact prefix \ - -- the tail is the OPEN r3 defect, not an assertion" - ); - } - - /// lane-av1444edge: the two 4:4:4 lossy cells the chroma-format sweep - /// (§6.2) left as "unassigned, neither reduces to a known class". They - /// are one class, and it is the sibling gate's: a 1:4 (HORZ_4 / VERT_4) - /// inter strip's chroma coefficient context gathered at the 4:2:0 PAIR - /// extent at ss (0,0), where `is_chroma_reference` - /// (av1_common_int.h:1454) makes every block its own chroma reference so - /// no pair exists. What these two add is the geometry and the depth the - /// sibling's 128x96 gate does not reach. - /// - /// **Arm A -- partial-frame right edge, 130x122.** Neither dimension is a - /// multiple of 8 (the sweep's own odd-dimension gate covers 4:2:0 only, so - /// the 4:4:4 partial-column walk had no exactness evidence), and 66x66 is - /// EXACT at the same settings, so the walk is right at one odd geometry - /// and wrong at another. Arm B -- 256x128, 4 frames, with CDEF and loop - /// restoration both live on the last two frames. - /// - /// **The recipes** (the sweep's, byte-reproduced -- the truncated sha256 - /// prefixes it recorded, `c87ac65b…` and `06621606…`, match): - /// ```text - /// ffmpeg -f lavfi -i "testsrc2=size=x:rate=25" -frames:v 4 \ - /// -pix_fmt yuv444p -strict -1 -f yuv4mpegpipe - | \ - /// aomenc --codec=av1 --passes=1 --end-usage=q --cq-level=20 --cpu-used=2 \ - /// --threads=1 --row-mt=0 --lag-in-frames=0 --kf-max-dist=100 \ - /// --limit=4 --obu -o - - - /// ``` - /// (`rate=25` is load-bearing for the same reason as the sibling gate: - /// `testsrc2`'s pattern is time-parameterised.) - /// - /// Red before the fix, both arms: arm A frame 3, 11521 samples, first at - /// Y(128,16) (ours 134, oracle 170); arm B frame 2, 25296 samples, first - /// at Y(192,0) (ours 92, oracle 106), frame 3 51108 more. The - /// pre-loop-filter reconstruction already carries the identical first - /// wrong sample on both, so no filter is involved; in arm B the first - /// wrong superblock in DECODE order is SBcol2/SBrow0 (first wrong pixel - /// (128,48) = mi(12,32), whose mode/ref/mv are identical on both sides), - /// and the arithmetic fork lands on the very next block, mi(13,32), where - /// the oracle reads ref0 = LAST and we read GOLDEN. - /// - /// Non-vacuity, three ways per arm: the pinned bytes (length + FNV-1a); - /// the decoded chroma planes are full resolution, which is the ss (0,0) - /// shape claim; and `decode::rect4_inter_own_chroma444_hits()` must be - /// non-zero AND `inter16_rect4_counters()` must report 1:4 inter strips, - /// so the corrected route is known to have run rather than the gate - /// passing on a stream that never reached it. - #[test] - fn a_444_lossy_rect4_strip_stream_decodes_pixel_exact_at_odd_and_wide_geometries() { - const NAME: &str = - "a_444_lossy_rect4_strip_stream_decodes_pixel_exact_at_odd_and_wide_geometries"; - // (fixture, len, fnv1a64, width, height, strips HORZ_4 + VERT_4) - const ARMS: [(&str, usize, u64, usize, usize, usize); 2] = [ - ( - "fixtures/444_lossy_rect4_odd_130x122.obu", - 8945, - 0x5125_0554_751c_bf12, - 130, - 122, - 28, // measured 8 HORZ_4 + 20 VERT_4 - ), - ( - "fixtures/444_lossy_rect4_wide_256x128.obu", - 15239, - 0xf94a_0218_bb34_4f9e, - 256, - 128, - 76, // measured 60 HORZ_4 + 16 VERT_4 - ), - ]; - let _guard = lock_gate_counters(); - for (fixture, len, fnv, w, h, min_strips) in ARMS { - let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(fixture); - let stream = std::fs::read(&obu).unwrap_or_else(|e| { - panic!( - "{NAME}: pinned fixture {} is missing ({e}) -- the gate cannot \ - run, which is a failure, not a skip", - obu.display() - ) - }); - assert_eq!(stream.len(), len, "{NAME}: {fixture} length moved"); - assert_eq!(fnv1a64(&stream), fnv, "{NAME}: {fixture} bytes moved"); - - // The 1:4-strip counters are process-wide with no reset, so read - // them as a DELTA: a full-suite run has already put 1:4 strips - // through the decoder by the time this test starts, and an - // absolute count would be a non-vacuity assertion that passes on - // residue from another stream. - let before_strips = { - let (h, v, _, _) = crate::decode::inter16_rect4_counters(); - h + v - }; - crate::decode::reset_rect4_inter_own_chroma444_hits(); - let frames = decode_stream(&stream) - .unwrap_or_else(|e| panic!("{NAME}: {fixture} no longer decodes cleanly: {e}")); - let own_chroma = crate::decode::rect4_inter_own_chroma444_hits(); - let strips = { - let (h, v, _, _) = crate::decode::inter16_rect4_counters(); - h + v - before_strips - }; - assert!( - strips >= min_strips, - "{NAME}: {fixture} coded only {strips} 1:4 inter strips \ - (HORZ_4 + VERT_4), expected about {min_strips} -- the stream \ - moved, and the route this gate witnesses may no longer be on it" - ); - assert!( - own_chroma > 0, - "{NAME}: {fixture} ran no 1:4 inter strip over its own chroma \ - extent -- the corrected route never ran (class \ - gate-blind-to-feature)" - ); - assert_eq!(frames.len(), 4, "{NAME}: {fixture} frame count"); - for (i, f) in frames.iter().enumerate() { - assert_eq!( - (f.width, f.height), - (w, h), - "{NAME}: {fixture} frame {i} dimensions" - ); - // At 4:4:4 the chroma planes are full resolution; a decoder - // that kept the 4:2:0 extent would hand quarter-size chroma - // planes to the byte compare, which cannot pass. Say it here - // rather than let the compare stand in for the shape claim. - assert_eq!( - f.u.len(), - w * h, - "{NAME}: {fixture} frame {i} chroma plane is {} samples; at \ - 4:4:4 it must be full resolution ({w}x{h})", - f.u.len() - ); - } - if aomdec_available(NAME) { - let (decoded, hidden) = decode_all_frames_vs_oracle(&stream, NAME); - eprintln!( - "{NAME}: {fixture} {decoded} decode-order frame(s) \ - ({hidden} hidden) byte-exact vs aomdec, {own_chroma} own-extent \ - 1:4 chroma gather(s), {strips} 1:4 inter strip(s)" - ); - } - } - } - - /// lane-av1444d10: the 10-bit 4:4:4 352x242 cell the 4:2:2 census - /// (`lanes/av1422census.report.md` §4 class D) found diverging on chroma - /// only -- 0 / 1166 / 1413 over 17 of 17 decode frames, first bad sample - /// at decode frame 0 plane U row 224 col 64 -- and the fix for it, a byte - /// exact gate. 4:4:4 is a format this decoder claims to support, so the - /// cell is not probe-only evidence. - /// - /// **Why this cell and not its five same-depth controls.** `s444_*_10b` - /// at 320x242, 320x250, 352x250, 416x242 and 416x250, same encoder recipe, - /// same 10-bit depth, were all byte-exact before the fix and still are; only - /// 352x242 diverged. What 352x242 has is the first block of the cell whose - /// chroma is TALLER than the 32-pixel unit cap at ss (0,0): a 32x64 luma - /// strip keeps its 32x64 chroma, and `decode_block_rect`'s tiled chroma - /// walk splits it into `nh = 2` units of 32x32. Every other cell's chroma - /// blocks are <= 32 on both axes, so `nw * nh == 1` and the whole-block - /// buffer IS the unit's window -- the bug is invisible there. That is why - /// the census could report "geometry-sensitive" without the mechanism: - /// the sensitive axis is chroma UNIT COUNT, not frame width or height. - /// - /// **The defect.** Both tiled arms handed the unit the WHOLE block's - /// palette prediction buffer, and `PlaneBuf::reconstruct` reads its first - /// `side * side` entries, so unit (0,1) at pixel (64, 224) reconstructed - /// the block's row-192 palette values (flat 209) where libaom writes - /// row 224's (216). The neighbouring 32x32 `PAETH_PRED` block at - /// (96, 224), whose left edge sample IS that pixel, then propagated 19 - /// more wrong columns along its own top row -- which is why the census saw - /// 53 wrong columns rather than 32. - /// - /// **Red before the fix, by this gate's own name:** with the two - /// `palette_window` calls reverted the first wrong sample is decode frame - /// 0 plane U row 224 col 64 (ours 209, oracle 216) and the totals are - /// 0 / 1166 / 1413 over 17 decode frames. - /// - /// **Non-vacuity, four ways.** (1) The pinned bytes: length 24875 and - /// FNV-1a64 `0x7fda_dbb4_3bbf_9af3`, sha256 - /// `84df2f37cc7982f9a572443d85dfcc13bf366a64f3fb567391dcd5acd58a0ad2`. - /// (2) 17 decode-order frames at 352x242 with FULL-RESOLUTION chroma, so - /// a decoder that kept the 4:2:0 extent cannot pass the compare. - /// (3) `decode::chroma_palette_window_hits()` read as a delta must be at - /// least 1. After the refutation pass read the numbers back, that counter - /// is guarded on `nw * nh > 1`, so it fires ONLY for units of a block the - /// 32-cap actually tiled -- a hit is therefore proof that the tiled arm ran, - /// not merely that some palette chroma block existed, and a gate that - /// passed with the tiled arm removed would be gate-blind-to-feature. (4) The oracle comparator this gate leans on has - /// its own per-plane one-byte-flip liveness control in the crate - /// (`every_oracle_comparator_reds_on_a_one_byte_wrong_oracle`). - #[test] - fn a_444_lossy_palette_chroma_unit_window_is_byte_exact_at_352x242_10bit() { - const NAME: &str = "a_444_lossy_palette_chroma_unit_window_is_byte_exact_at_352x242_10bit"; - const FIXTURE: &str = "fixtures/444_lossy_palette_chroma_352x242_10b.obu"; - const LEN: usize = 24875; - const FNV: u64 = 0x7fda_dbb4_3bbf_9af3; - const W: usize = 352; - const H: usize = 242; - // 16 SHOWN frames (`--limit=16`); the oracle compare below is the one - // that walks all 17 DECODE-order pictures (16 shown + 1 hidden altref). - const FRAMES: usize = 16; - // measured 4 on this stream (two tiled palette chroma blocks x U and V) - const MIN_WINDOWED_UNITS: usize = 4; - let _guard = lock_gate_counters(); - let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(FIXTURE); - let stream = std::fs::read(&obu).unwrap_or_else(|e| { - panic!( - "{NAME}: pinned fixture {} is missing ({e}) -- the gate cannot run, \ - which is a failure, not a skip", - obu.display() - ) - }); - assert_eq!(stream.len(), LEN, "{NAME}: {FIXTURE} length moved"); - assert_eq!(fnv1a64(&stream), FNV, "{NAME}: {FIXTURE} bytes moved"); - - // Process-wide with no reset: read as a DELTA, or a full-suite run - // leaves residue that would make the reachability assert vacuous. - crate::decode::reset_chroma_palette_window_hits(); - let frames = decode_stream(&stream) - .unwrap_or_else(|e| panic!("{NAME}: {FIXTURE} no longer decodes cleanly: {e}")); - let windowed = crate::decode::chroma_palette_window_hits(); - assert!( - windowed >= MIN_WINDOWED_UNITS, - "{NAME}: {FIXTURE} ran {windowed} windowed palette chroma unit(s), \ - expected at least {MIN_WINDOWED_UNITS} -- the tiled chroma walk did \ - not reach a palette block, so the fixed lines never ran and this \ - gate is blind to the defect (class gate-blind-to-feature)" - ); - assert_eq!( - frames.len(), - FRAMES, - "{NAME}: {FIXTURE} decode-order frame count" - ); - for (i, f) in frames.iter().enumerate() { - assert_eq!( - (f.width, f.height), - (W, H), - "{NAME}: {FIXTURE} frame {i} dimensions" - ); - assert_eq!( - f.u.len(), - W * H, - "{NAME}: {FIXTURE} frame {i} chroma plane is {} samples; at 4:4:4 \ - it must be full resolution ({W}x{H})", - f.u.len() - ); - } - if aomdec_available(NAME) { - let (decoded, hidden) = decode_all_frames_vs_oracle(&stream, NAME); - eprintln!( - "{NAME}: {FIXTURE} {decoded} decode-order frame(s) ({hidden} hidden) \ - byte-exact vs aomdec, {windowed} windowed palette chroma unit(s)" - ); - } - } - - /// lane-av1444palw: the gate for the arm - /// `a_444_lossy_palette_chroma_unit_window_is_byte_exact_at_352x242_10bit` - /// could NOT reach -- the HORIZONTAL half of the same 32-capped chroma - /// walk in `decode_block_rect64` (`palette_window(pbuf, chroma_w, - /// cu_col * uw, cu_row * uh, uw, uh)`, the arms at decode.rs:20131 and - /// :20199). Its `cu_col` term is the axis the corpus census never - /// exercised: a 106-fixture trace of that walk found 16 windowed units and - /// every one had `nw == 1`, i.e. only the `cu_row` term (`nh = 2`) was - /// ever load-bearing. - /// - /// **What makes `nw >= 2` reachable.** At ss (0,0) the chroma plane block - /// equals the luma one, so a 64-WIDE luma rect block keeps `cw = 64` and - /// the 32-cap tiles it into `nw = 2` units. `decode_block_rect64` is the - /// only function owning this walk at a 64-wide block, reached from - /// `PARTITION_HORZ`/`HORZ_A`/`HORZ_B` (64x32) and `HORZ_4` (64x16). The - /// cells here came from sweeping `--min-partition-size` x `--cq-level` over - /// a 4:4:4 testsrc2 640x480 cell encoded with the lane-av1rect14 - /// `ibc640` flag set (rect + 1:4 partitions, `--min-partition-size=8 - /// --sb-size=64 --tune-content=screen --enable-palette=1 - /// --enable-intrabc=1 --enable-tx-size-search=0 --cpu-used=0 - /// --lag-in-frames=0 --kf-max-dist=1 --limit=1 --threads=1 - /// --tile-columns=0 --passes=1 --end-usage=q --profile=1`): - /// `--min-partition-size=8` is what yields the 64-wide strip, and - /// `cq-level=45` is what makes the chroma palette win on it. Census read - /// off `EC_PALWALK=1`, the diagnostic rung this lane added to - /// `decode_block_rect64`: - /// - /// * 10-bit `cq 45`: `bw=64 bh=16 cw=64 ch=16 uw=32 uh=16 nw=2 nh=1 puv=1` - /// -- the RECT-unit arm (`uw != uh`) carrying a chroma palette, `nw = 2`. - /// * 12-bit `cq 45`: `bw=64 bh=32 cw=64 ch=32 uw=32 uh=32 nw=2 nh=1 puv=1` - /// -- the SQUARE-unit arm carrying a chroma palette, `nw = 2`, on the - /// 12-bit chroma plane no prior gate had built. - /// - /// **Both cells are byte-exact against the instrumented `aomdec`** per - /// plane over the single decode-order frame (10-bit 0/0/0, 12-bit 0/0/0), - /// and the comparator's liveness is proved by a one-byte oracle tamper - /// moving the mismatch count 0 -> 1 at each depth. - /// - /// **Red without the per-unit window, by this gate's own numbers.** - /// Reverting both `palette_window` calls to the whole-block buffer (the - /// counter left armed) gives 0 / 25553 / 26139 on the 10-bit cell, first - /// wrong sample decode frame 0 plane U row 96 col 448 (mutant 810, oracle - /// 763; plane V the same sample 891 vs 767), and 0 / 6400 / 6400 on the - /// 12-bit cell, first wrong sample plane U row 352 col 160 (866 vs 2004). - /// Both are the `cu_col = 1` unit reading the block's column 0 -- this arm, - /// not a cascade. - /// - /// **Non-vacuity.** (1) pinned bytes: 3301 / 2571 with FNV-1a64 and - /// sha256 asserted. (2) the DERIVED condition: the counter is guarded on - /// `nw * nh > 1`, so a hit proves the tiled arm ran, and the floors below - /// are re-measured on these two streams (the pinned gate's floor of 4 was - /// a floor from ONE stream, not a census). (3) 640x480 with - /// FULL-RESOLUTION chroma, so a 4:2:0 extent cannot pass. (4) the crate's - /// own one-byte oracle-comparator liveness control. - #[test] - fn a_444_palette_chroma_horizontal_unit_window_is_byte_exact_10bit_and_12bit() { - const NAME: &str = - "a_444_palette_chroma_horizontal_unit_window_is_byte_exact_10bit_and_12bit"; - // (fixture, len, fnv1a64, bit_depth, min_windowed_units) - const ARMS: [(&str, usize, u64, usize, usize); 2] = [ - ( - "fixtures/444_palette_chroma_hstrip_640x480_10b.obu", - 3301, - 0x6f94_da75_95cd_9a17, - 10, - 8, - ), - ( - "fixtures/444_palette_chroma_hstrip_640x480_12b.obu", - 2571, - 0x65a5_8561_c1f3_538e, - 12, - 4, - ), - ]; - const W: usize = 640; - const H: usize = 480; - let _guard = lock_gate_counters(); - for (fixture, len, fnv, depth, min_units) in ARMS { - let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(fixture); - let stream = std::fs::read(&obu).unwrap_or_else(|e| { - panic!( - "{NAME}: pinned fixture {fixture} is missing ({e}) -- the gate cannot \ - run, which is a failure, not a skip" - ) - }); - assert_eq!(stream.len(), len, "{NAME}: {fixture} length moved"); - assert_eq!(fnv1a64(&stream), fnv, "{NAME}: {fixture} bytes moved"); - - crate::decode::reset_chroma_palette_window_hits(); - let frames = decode_stream(&stream) - .unwrap_or_else(|e| panic!("{NAME}: {fixture} no longer decodes cleanly: {e}")); - let windowed = crate::decode::chroma_palette_window_hits(); - assert!( - windowed >= min_units, - "{NAME}: {fixture} ran {windowed} windowed palette chroma unit(s), expected \ - at least {min_units} -- the 32-cap tiled chroma walk did not reach enough \ - palette blocks, so the horizontal windowing under test never ran and this \ - gate is blind to the defect (class gate-blind-to-feature)" - ); - assert_eq!( - frames.len(), - 1, - "{NAME}: {fixture} decode-order frame count" - ); - for (i, f) in frames.iter().enumerate() { - assert_eq!( - (f.width, f.height), - (W, H), - "{NAME}: {fixture} frame {i} dimensions" - ); - assert_eq!( - f.u.len(), - W * H, - "{NAME}: {fixture} frame {i} chroma plane is {} samples; at 4:4:4 it must \ - be full resolution ({W}x{H}) -- a {depth}-bit decoder that kept the \ - 4:2:0 extent cannot pass this compare", - f.u.len() - ); - } - if aomdec_available(NAME) { - let (decoded, hidden) = decode_all_frames_vs_oracle(&stream, NAME); - eprintln!( - "{NAME}: {fixture} ({depth}-bit) {decoded} decode-order frame(s) \ - ({hidden} hidden) byte-exact vs aomdec, {windowed} windowed palette \ - chroma unit(s)" - ); - } - } - } - - /// lane-av1cfl: the 4:4:4 CfL AC body is a DIFFERENT function from the - /// 4:2:0 one, and this gate is the proof that the format-blind - /// `cfl_ac_q3_at` (`bw / 2, bh / 2`, a 2x2 luma average per chroma - /// sample) is reached only at 4:2:0. - /// - /// **The claim this closes.** `cfl_ac_q3_at` has no `fctx`/`ss` - /// parameter, so at 4:4:4 it would be wrong twice over: the chroma - /// extent equals the luma extent when `ss_x == ss_y == 0`, and libaom - /// averages 2x2 luma per chroma sample at 4:2:0 but 1x1 at 4:4:4 - /// (`cfl_luma_subsampling_420_lbd_c` vs `cfl_luma_subsampling_444_lbd_c`, - /// `~/.cache/aom-oracle/src/av1/common/cfl.c:230` and `:257`). The - /// inherited report claimed "188 rung hits on the 4:4:4 set" - /// (`lanes/av1chromahalvings.report.md` r3.4). **It does not - /// reproduce**: the env-gated rung `EC_HALVSWEEP` in `cfl_ac_q3_at`, - /// swept over all 27 `*444*` pins, printed **0 hits on every one**, - /// while the 4:4:4 arm of `cfl_ac_ss` fired 4..312 times on the same - /// fixtures. The 4:4:4 CfL path is real and heavily exercised; it just - /// does not go through this function. `cfl_ac_ss` dispatches 4:4:4 and - /// 4:2:2 to their own transcriptions of libaom's 444/422 subsampling - /// bodies BEFORE the 4:2:0 fallthrough, and the fallthrough is the only - /// road to `cfl_ac_q3_at`. - /// - /// Two-sided on purpose. The 4:4:4 arm asserts `> 0` (the CfL path - /// fired, so the `== 0` below is a routing fact and not an absence of - /// CfL) and the 4:2:0 arm asserts `> 0` on the SAME counter (so the - /// counter is live and the 4:4:4 zero is not a dead one). Both arms - /// compare every decoded frame to the instrumented `aomdec` - /// plane by plane, and the 4:2:0 arm is the "unchanged" quote: its - /// per-plane mismatch counts must be 0/0/0. - /// - /// Provenance: both fixtures are aomenc-produced and already pinned - /// with sha256 by the gates named beside them. 4:4:4 lossy - /// `444_lossy_superres_mode2_256x128.obu` (16620 bytes, sha256 - /// `c18496cf3b7db0feca9aa904024cec2115be80b5b94f87c848ac52f9b32ffd97`, - /// `testsrc2=size=256x128:rate=25 -pix_fmt yuv444p`, `--passes=1 - /// --end-usage=q --cq-level=20 --cpu-used=2 --superres-mode=2 - /// --limit=4 --obu`, 4 frames); 4:2:0 lossy - /// `420_intrabc_rect4_witness.obu` (890 bytes, sha256 - /// `d01352af5059919cdce733abdcbae8e8240ac3c2a6190fa1bd96d3c6f945b979`). - #[test] - fn cfl_ac_444_routes_to_its_own_1x1_luma_body_and_420_to_the_2x2_average() { - const NAME: &str = "cfl_ac_444_routes_to_its_own_1x1_luma_body_and_420_to_the_2x2_average"; - // (fixture, len, fnv1a64, sha256, (w, h), frames, cfL arm index, is_444) - const ARMS: [(&str, usize, u64, &str, (usize, usize), usize, usize, bool); 2] = [ - ( - "fixtures/444_lossy_superres_mode2_256x128.obu", - 16620, - 0x8cbb_36b2_5e0f_07ab, - "c18496cf3b7db0feca9aa904024cec2115be80b5b94f87c848ac52f9b32ffd97", - (256, 128), - 4, - 0, - true, - ), - ( - "fixtures/420_intrabc_rect4_witness.obu", - 890, - 0x57ec_3da2_a63b_403a, - "d01352af5059919cdce733abdcbae8e8240ac3c2a6190fa1bd96d3c6f945b979", - (640, 480), - 1, - 2, - false, - ), - ]; - let _guard = lock_gate_counters(); - for (fixture, len, fnv, sha, (w, h), want_frames, arm_idx, is_444) in ARMS { - let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(fixture); - let stream = std::fs::read(&obu).unwrap_or_else(|e| { - panic!( - "{NAME}: pinned fixture {fixture} is missing ({e}) -- the gate cannot run, \ - which is a failure, not a skip" - ) - }); - assert_eq!(stream.len(), len, "{NAME}: {fixture} length moved"); - assert_eq!(fnv1a64(&stream), fnv, "{NAME}: {fixture} bytes moved"); - - // The arm counters are process-wide with no reset, so every read - // is a DELTA: a full-suite run has already put other streams' - // CfL blocks through this decoder, and an absolute count would be - // a non-vacuity assertion satisfied by residue. - let arms_before = crate::decode::cfl_ac_arm_hits(); - let q3_before = crate::decode::cfl_ac_q3_at_hits(); - let frames = decode_stream(&stream) - .unwrap_or_else(|e| panic!("{NAME}: {fixture} no longer decodes cleanly: {e}")); - let arms = crate::decode::cfl_ac_arm_hits(); - let q3_delta = crate::decode::cfl_ac_q3_at_hits() - q3_before; - let arm_delta: Vec = (0..4).map(|i| arms[i] - arms_before[i]).collect(); - - // The arm this stream's format MUST take, and the count that - // proves the CfL path is live on it. At 4:4:4 that is arm 0 - // (`cfl_luma_subsampling_444_lbd_c`'s 1x1 body); at 4:2:0 it is - // arm 2 (the square fallthrough into `cfl_ac_q3`). - assert!( - arm_delta[arm_idx] > 0, - "{NAME}: {fixture} ran {} 4:4:4 / {} 4:2:2 / {} 4:2:0-square / \ - {} 4:2:0-rect CfL blocks; arm {arm_idx} is the one this format must \ - take and it is ZERO -- the stream no longer exercises CfL, so the \ - routing assertion below would be vacuous (class gate-blind-to-feature)", - arm_delta[0], - arm_delta[1], - arm_delta[2], - arm_delta[3], - ); - if is_444 { - assert_eq!( - q3_delta, 0, - "{NAME}: {fixture} is 4:4:4 and entered the format-blind cfl_ac_q3_at \ - {q3_delta} time(s) -- its extent is bw/2, bh/2 and its footprint is a \ - 2x2 luma average, both wrong at ss (0,0) (libaom cfl.c:230 vs :257). \ - Arm deltas {arm_delta:?}. Either cfl_ac_ss lost its 4:4:4 arm or a new \ - caller reached cfl_ac_q3_at directly; both make this site LIVE" - ); - assert_eq!( - (arm_delta[2], arm_delta[3]), - (0, 0), - "{NAME}: {fixture} is 4:4:4 but ran the 4:2:0 CfL arms -- the format test \ - that keeps cfl_ac_q3_at format-blind has moved" - ); - } else { - assert!( - q3_delta > 0, - "{NAME}: {fixture} is 4:2:0 and cfl_ac_q3_at was entered ZERO times \ - (arm deltas {arm_delta:?}) -- the counter this gate proves 4:4:4 never \ - touches is dead on 4:2:0 too, so the 4:4:4 assertion is a dead zero" - ); - assert_eq!( - (arm_delta[0], arm_delta[1]), - (0, 0), - "{NAME}: {fixture} is 4:2:0 but ran a 4:4:4 or 4:2:2 CfL arm" - ); - } - assert_eq!(frames.len(), want_frames, "{NAME}: {fixture} frame count"); - for (i, f) in frames.iter().enumerate() { - assert_eq!( - (f.width, f.height), - (w, h), - "{NAME}: {fixture} frame {i} dimensions" - ); - if is_444 { - assert_eq!( - f.u.len(), - w * h, - "{NAME}: {fixture} frame {i} chroma plane is {} samples; at 4:4:4 it \ - must be full resolution ({w}x{h})", - f.u.len() - ); - } - } - // Per-plane mismatch counts against the instrumented oracle, so - // the "4:2:0 unchanged" claim is a number rather than a claim. - if aomdec_available(NAME) { - let [y, u, v] = oracle_plane_diffs( - &stream, - NAME, - [frames[0].y.len(), frames[0].u.len(), frames[0].v.len()], - ); - assert!( - y == 0 && u == 0 && v == 0, - "{NAME}: {fixture} differs from the oracle on {y}/{u}/{v} of the \ - {w}x{h} Y/U/V samples -- sha256 {sha}" - ); - eprintln!( - "{NAME}: {fixture} arm{arm_idx} {arm_delta:?}, cfl_ac_q3_at {q3_delta}, \ - per-plane Y/U/V mismatches vs aomdec {y}/{u}/{v} of {w}x{h}; \ - sha256 {sha}" - ); - } - } - } - - /// lane-av1cfl: the STATIC half of the same claim -- `cfl_ac_q3_at`'s - /// caller set, read out of the sources themselves, is what makes its - /// `bw / 2, bh / 2` extent and 2x2 luma footprint correct rather than - /// merely untested. The counter gate above measures that on two pinned - /// streams; this one survives a change no fixture would catch. - /// - /// **What is asserted, and why each part is load-bearing.** - /// - /// 1. `cfl_ac_q3_at` has exactly **three** call sites -- the two 4:2:0 - /// wrappers `cfl_ac_q3` / `cfl_ac_q3_rect` in `decode.rs` and the - /// encoder's CfL candidate in `encode.rs`. A fourth would be a new - /// road to a format-blind body. - /// 2. Both `decode.rs` wrappers are called from **exactly one** function, - /// `cfl_ac_ss`, and only from its LAST two arms -- the ones after the - /// `ss_x == 0 && ss_y == 0` (4:4:4) and `ss_x == 1 && ss_y == 0` - /// (4:2:2) tests. So every decode-side entry is 4:2:0 by - /// construction, whatever a stream's header says. - /// 3. The encoder's call site is 4:2:0 because `Colour::color_config` and - /// `unspecified_color_config` both hardcode `subsampling_x: 1, - /// subsampling_y: 1` -- there is no 4:4:4 encoder colour config in the - /// crate. A future encoder that grows one must thread `ss` into this - /// call, and the `subsampling_x: 0` count going above zero is what - /// says so. - /// - /// (0, 1) needs no arm: `ec-av1-syntax` reads `subsampling_y` only when - /// `subsampling_x == 1` (`crates/ec-av1-syntax/src/sequence.rs:483-485`), - /// so the pair is structurally uncodable and the 4:2:0 fallthrough is the - /// only residual. lane-av1422lift: this sentence used to end "4:2:2 is - /// refused at the sequence header", which was the wrong reason -- the - /// claim holds because `cfl_ac_ss` DISPATCHES `ss (1,0)` before the 4:2:0 - /// fallthrough, not because the format could not arrive. The gate's - /// mechanism is unchanged; only the reason was stale. - #[test] - fn cfl_ac_q3_at_is_reached_only_through_the_420_fallthrough_of_cfl_ac_ss() { - const NAME: &str = "cfl_ac_q3_at_is_reached_only_through_the_420_fallthrough_of_cfl_ac_ss"; - let decode = crate::test_source::module_source("decode"); - let encode = crate::test_source::module_source("encode"); - - // (1) The call-site set, definition excluded. A declaration is - // preceded by "pub(crate) fn " / "fn "; a call is not. - let mut sites: Vec<&str> = Vec::new(); - for src in [decode, encode] { - for (i, _) in src.match_indices("cfl_ac_q3_at(") { - if src[..i].ends_with("fn ") { - continue; - } - sites.push(if src == decode { - "decode.rs" - } else { - "encode.rs" - }); - } - } - let mut per_file: std::collections::BTreeMap<&str, usize> = - std::collections::BTreeMap::new(); - for s in &sites { - *per_file.entry(s).or_default() += 1; - } - assert_eq!( - per_file, - std::collections::BTreeMap::from([("decode.rs", 2), ("encode.rs", 1)]), - "{NAME}: cfl_ac_q3_at's call-site set changed -- {per_file:?} against an expected \ - 2 in decode.rs (the cfl_ac_q3 / cfl_ac_q3_rect wrappers) and 1 in encode.rs (the \ - encoder's CfL candidate). A new call site must thread the frame's subsampling in; \ - the body is a 4:2:0 2x2 luma average over a bw/2 x bh/2 extent and is WRONG at \ - 4:4:4 on both counts (libaom cfl_luma_subsampling_444_lbd_c is 1x1 over the full \ - extent, cfl.c:257)" - ); - - // (2) Both wrappers have exactly one caller, and it is cfl_ac_ss. - let cfl_ac_ss_at = decode - .find("fn cfl_ac_ss(") - .expect("cfl_ac_ss is gone -- re-derive the fallthrough arms below"); - for wrapper in ["cfl_ac_q3(", "cfl_ac_q3_rect("] { - let mut ats = Vec::new(); - for (i, _) in decode.match_indices(wrapper) { - if decode[..i].ends_with("fn ") { - continue; - } - ats.push(i); - } - // The scan string carries its own open paren, so it cannot match - // `cfl_ac_q3_rect(` or `cfl_ac_q3_at(` -- those are `cfl_ac_q3` - // followed by `_`, not `(`. No prefix filter is needed. - assert_eq!( - ats.len(), - 1, - "{NAME}: `{wrapper}` is called {} time(s) outside its own definition, expected \ - exactly 1 (from cfl_ac_ss) -- a second caller is a new road to the 4:2:0 \ - average that this gate's counter arm measures only on 4:2:0", - ats.len() - ); - assert!( - ats[0] > cfl_ac_ss_at && ats[0] < cfl_ac_ss_at + 4000, - "{NAME}: `{wrapper}`'s only call site is at byte {} and cfl_ac_ss is at {} -- \ - the call has moved out of the 4:2:0 fallthrough into something that may be \ - handed a 4:4:4 or 4:2:2 block", - ats[0], - cfl_ac_ss_at - ); - } - - // Inside cfl_ac_ss, the two format tests must come BEFORE both - // wrapper calls, and the wrappers must be the fallthrough -- a 4:4:4 - // block returns from the first arm and never reaches either. - let body_end = decode[cfl_ac_ss_at..] - .find("\nfn ") - .expect("cfl_ac_ss must be a top-level fn") - + cfl_ac_ss_at; - let body = &decode[cfl_ac_ss_at..body_end]; - let t444 = body.find("if ss_x == 0 && ss_y == 0 {").expect( - "cfl_ac_ss lost its 4:4:4 arm -- every 4:4:4 CfL block now falls into the \ -2:0 average", - ); - let t422 = body - .find("} else if ss_x == 1 && ss_y == 0 {") - .expect("cfl_ac_ss lost its 4:2:2 arm -- a 4:2:2 block would take the 4:2:0 average"); - let sq = body - .find("cfl_ac_q3(y, px, py, bw)") - .expect("cfl_ac_ss lost its 4:2:0 square fallthrough"); - let rect = body - .find("cfl_ac_q3_rect(y, px, py, bw, bh)") - .expect("cfl_ac_ss lost its 4:2:0 rect fallthrough"); - assert!( - t444 < t422 && t422 < sq && sq < rect, - "{NAME}: cfl_ac_ss's arm order moved (4:4:4 at {t444}, 4:2:2 at {t422}, 4:2:0 square \ - at {sq}, 4:2:0 rect at {rect}) -- the format-blind 2x2 average must stay the \ - FALLTHROUGH, after both format tests have had their chance to return" - ); - - // (3) The encoder's colour configs are 4:2:0 only. - for (src, label) in [ - (encode, "encode.rs"), - (crate::test_source::module_source("encoder"), "encoder.rs"), - ] { - let n = src.matches("subsampling_x: 0").count(); - assert_eq!( - n, 0, - "{NAME}: {label} now builds a 4:4:4 ColorConfig ({n} site(s)) -- the encoder's \ - cfl_ac_q3_at call (encode.rs) is a 4:2:0 2x2 average over a half extent and \ - must thread ss before any encoder can emit one" - ); - } - } - - /// lane-av1444edge r3: the FIRST 4:4:4 superres cell in the crate, and - /// the cell the chroma-format sweep's "4:4:4 superres" row was supposed - /// to be. - /// - /// **Why this gate exists at all.** §6.2 of - /// `lanes/av1formatsweep.report.md` recorded that cell as DIVERGENT from - /// frame 2 with a first wrong sample of Y(192,0). It was never a superres - /// cell: the recipe passed `--superres-mode=1` and no denominator, so - /// libaom's `get_superres_denom_for_qindex` - /// (`av1/encoder/superres_scale.c:143`) chose 8, and all four frame - /// headers of that stream read `use_superres=false denom=8`. Nothing was - /// ever scaled; it was a plain 4:4:4 lossy cq-20 stream, and its - /// divergence was the same H1 class as the 130x122 cell beside it (see - /// `lanes/av1444edge.report.md` §2). That is the trap this gate is built - /// to make impossible to repeat: it asserts the scaled geometry from the - /// PARSED HEADERS, so a future flag or heuristic change that silently - /// unsizes the stream makes the gate red on a header assertion instead of - /// turning into a differently-shaped exactness claim. - /// - /// **This is the only 4:4:4 superres coverage here.** All eight - /// pre-existing superres gates are 4:2:0, checked rather than assumed: - /// the two pinned fixtures parse `ss (1,1)` from their own sequence - /// headers (`superres_kf_cdef_lr_64x64.obu` 8-bit, - /// `superres_alltools_sb128_320x180.obu` 10-bit) and the six live-aomenc - /// gates all feed a `yuv420p` / `yuv420p10le` source. So this cell's - /// claim is scoped honestly: it is the FIRST 4:4:4 superres stream, not - /// a broadening of an existing family. - /// - /// **The recipe** (sha256 - /// `450caa3e31526a8973b9f64d5030a2f11b87bd60fac07aef121cb62af9bf85ff`, - /// 14808 bytes, 4 frames, `testsrc2 256x128 rate=25` yuv444p): - /// ```text - /// ffmpeg -f lavfi -i "testsrc2=size=256x128:rate=25" -frames:v 4 \ - /// -pix_fmt yuv444p -strict -1 -f yuv4mpegpipe - | \ - /// aomenc --codec=av1 --passes=1 --end-usage=q --cq-level=20 --cpu-used=2 \ - /// --threads=1 --row-mt=0 --lag-in-frames=0 --kf-max-dist=100 \ - /// --limit=4 --superres-mode=1 --superres-denominator=12 \ - /// --superres-kf-denominator=12 --obu -o - - - /// ``` - /// The two denominator flags are the whole point: without them the cell - /// does not exist. Verified byte-reproducible — re-encoding this recipe - /// reproduces the pinned 14808 bytes exactly. - /// - /// **What the cell exercises.** Coded 171x128 upscaled to 256x128 at - /// `denom = 12`, so a 4:4:4 chroma plane is upscaled at FULL resolution - /// (a 4:2:0 stream halves it first, and libaom's `av1_superres_upscale` - /// takes a different path per chroma format). Measured `superres_hits` 4 - /// and `mc::predict_scaled_hits` 2130 — the upscaler and scaled inter - /// prediction both run, so the cell is not passing on an unscaled - /// stream. - /// - /// Non-vacuity, four ways: the pinned bytes (length + FNV-1a); the parsed - /// headers really are `use_superres` at `denom 12` with the SCALED coded - /// size, and the coded width is re-derived from `UpscaledWidth` and the - /// denominator rather than only compared to a literal, so a re-pinned - /// fixture cannot drift past the assertion; both counters are asserted as - /// DELTAS; and every decode-order frame is compared byte-for-byte - /// through `decode_all_frames_vs_oracle`, which is what makes the - /// upscaled width on both sides a real check. - #[test] - fn a_444_lossy_superres_stream_decodes_pixel_exact() { - const NAME: &str = "a_444_lossy_superres_stream_decodes_pixel_exact"; - const FIXTURE: &str = "fixtures/444_lossy_superres_256x128_d12.obu"; - const FIXTURE_LEN: usize = 14808; - const FIXTURE_FNV: u64 = 0x44e0_d12f_1155_0e09; - /// Quoted so a re-pin has to be deliberate; the FNV above is what the - /// gate actually compares, this is what a human reads. - const FIXTURE_SHA256: &str = - "450caa3e31526a8973b9f64d5030a2f11b87bd60fac07aef121cb62af9bf85ff"; - const UPSCALED: (usize, usize) = (256, 128); - const CODED: (usize, usize) = (171, 128); - const DENOM: u8 = 12; - const FRAMES: usize = 4; - let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(FIXTURE); - let stream = std::fs::read(&obu).unwrap_or_else(|e| { - panic!( - "{NAME}: pinned fixture {} is missing ({e}) -- the gate cannot run, \ - which is a failure, not a skip", - obu.display() - ) - }); - assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: fixture length moved"); - assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: fixture bytes moved"); - - // --- the header facts the CELL depends on, parsed not assumed ------ - let mut parser = Av1Parser::new(); - let mut pos = 0usize; - let mut seq = None; - let mut heads: Vec = Vec::new(); - while pos < stream.len() { - let obu = parser - .parse_obu(&stream[pos..]) - .unwrap_or_else(|e| panic!("{NAME}: aomenc OBU does not parse: {e:?}")); - if obu.total_size == 0 { - break; - } - pos += obu.total_size; - match obu.kind { - ObuKind::SequenceHeader(s) => seq = Some(s), - ObuKind::FrameHeader(h) => heads.push(*h), - ObuKind::Frame(h, _) => heads.push(*h), - _ => {} - } - } - let seq = seq.unwrap_or_else(|| panic!("{NAME}: the stream carries no sequence header")); - assert_eq!( - ( - seq.color_config.subsampling_x, - seq.color_config.subsampling_y - ), - (0, 0), - "{NAME}: the stream is not 4:4:4 (ss = ({}, {}))", - seq.color_config.subsampling_x, - seq.color_config.subsampling_y - ); - assert_eq!( - seq.color_config.bit_depth, 8, - "{NAME}: not the 8-bit cell this gate names" - ); - assert!( - seq.enable_superres, - "{NAME}: the sequence header does not enable superres at all" - ); - assert_eq!( - heads.len(), - FRAMES, - "{NAME}: {} frame headers, expected {FRAMES}", - heads.len() - ); - for (i, h) in heads.iter().enumerate() { - // The assertion the phantom cell failed. Without the denominator - // flags aomenc picks 8 and this is false while the stream still - // decodes, which is how a whole sweep cell ends up mislabelled. - assert!( - h.use_superres, - "{NAME}: frame {i} has use_superres = false -- this is an UNSCALED \ - stream and the gate would be measuring something other than the \ - cell it names (class gate-blind-to-feature)" - ); - assert_eq!( - h.superres_denom, DENOM, - "{NAME}: frame {i} denominator moved from {DENOM}" - ); - assert_eq!( - (h.upscaled_width as usize, h.frame_height as usize), - (UPSCALED.0, UPSCALED.1), - "{NAME}: frame {i} upscaled size moved" - ); - assert_eq!( - (h.frame_width as usize, h.frame_height as usize), - (CODED.0, CODED.1), - "{NAME}: frame {i} CODED size moved -- this is the scaled half of \ - the cell and the part an unsized stream gets wrong" - ); - // Re-derive rather than only compare literals, so a re-pinned - // fixture cannot satisfy the numbers above while the scaled-size - // arithmetic has moved under them. - assert_eq!( - (h.upscaled_width * 8 + u32::from(DENOM) / 2) / u32::from(DENOM), - h.frame_width, - "{NAME}: frame {i}: FrameWidth is not (UpscaledWidth*8 + denom/2)/denom -- \ - the scaled size the cell rests on is not the spec's" - ); - } - - // --- the pixels ----------------------------------------------------- - let _guard = lock_gate_counters(); - let before_sr = crate::superres::superres_hits(); - let before_scaled = crate::mc::predict_scaled_hits(); - let frames = decode_stream(&stream).unwrap_or_else(|e| { - panic!("{NAME}: the pinned 4:4:4 superres stream was refused: {e}") - }); - let scaled_up = crate::superres::superres_hits() - before_sr; - let scaled_mc = crate::mc::predict_scaled_hits() - before_scaled; - assert!( - scaled_up > 0, - "{NAME}: zero superres_hits -- the upscaler never ran (class \ - gate-blind-to-feature)" - ); - assert!( - scaled_mc > 0, - "{NAME}: zero predict_scaled_hits -- no inter block read a scaled reference, \ - so the scaled-PREDICTION half of the cell is unexercised (class \ - gate-blind-to-feature)" - ); - assert_eq!(frames.len(), FRAMES, "{NAME}: decoded frame count"); - for (i, f) in frames.iter().enumerate() { - // The upscale must have REPLACED the frame: a decoder that - // returned the 171-wide coded picture fails here, and without - // this check the chroma-shape assertion below could be satisfied - // by quarter-size planes. - assert_eq!( - (f.width, f.height), - UPSCALED, - "{NAME}: frame {i} came back {}x{}, not the UPSCALED {}x{}", - f.width, - f.height, - UPSCALED.0, - UPSCALED.1 - ); - assert_eq!( - f.u.len(), - UPSCALED.0 * UPSCALED.1, - "{NAME}: frame {i} chroma plane is {} samples; at 4:4:4 upscaled it must \ - be full resolution ({}x{})", - f.u.len(), - UPSCALED.0, - UPSCALED.1 - ); - assert_eq!( - f.v.len(), - UPSCALED.0 * UPSCALED.1, - "{NAME}: frame {i} V plane is {} samples, expected full resolution", - f.v.len() - ); - } - if aomdec_available(NAME) { - let (decoded, hidden) = decode_all_frames_vs_oracle(&stream, NAME); - eprintln!( - "{NAME}: {decoded} decode-order frame(s) ({hidden} hidden) byte-exact vs \ - aomdec at {UPSCALED:?} upscaled from {CODED:?} denom {DENOM}, \ - {scaled_up} upscale(s), {scaled_mc} scaled MC block(s); fixture sha256 \ - {FIXTURE_SHA256}" - ); - } - } - - /// lane-av1superpin (a): `--superres-mode=1 --superres-denominator=9`, the - /// WIDEST frame-edge margin this 256x128 geometry allows -- coded 228x128 - /// upscaled to 256x128, `denom = 9`, on all four frames. - /// - /// **Why 9 and not 12.** The den=12 cell beside it (coded 171x128) is the - /// one the chroma-format sweep's matrix row ended up pointing at, and - /// denom 16 (coded 128x128) is the degenerate one where the coded width - /// equals the superblock grid exactly. Nine is the largest denominator - /// libaom's own `SUPERRES_NUM` ladder accepts here and still scales, and - /// it is the member that leaves the most coded samples at the frame's - /// right edge: `228 * 8 / 256` of the frame is a 28-column upscale margin, - /// against 12's 85 columns. A wide margin is where a round-trip is most - /// likely to read past the coded picture, so it is the member worth - /// pinning next to the den=12 one. - /// - /// **The recipe** (sha256 - /// `3d619ee0fda3d9bb9cf8ff0541ba00ea5d83ae38cd8eec1322f8dbbbe6a5ec96`, - /// 17437 bytes, 4 frames, `testsrc2 256x128 rate=25` yuv444p): - /// ```text - /// ffmpeg -f lavfi -i "testsrc2=size=256x128:rate=25" -frames:v 4 \ - /// -pix_fmt yuv444p -strict -1 -f yuv4mpegpipe - | \ - /// aomenc --codec=av1 --passes=1 --end-usage=q --cq-level=20 --cpu-used=2 \ - /// --threads=1 --row-mt=0 --lag-in-frames=0 --kf-max-dist=100 \ - /// --limit=4 --superres-mode=1 --superres-denominator=9 \ - /// --superres-kf-denominator=9 --obu -o - - - /// ``` - /// Byte-reproducible: re-encoding this recipe reproduces the pinned 17437 - /// bytes exactly, and the PARSED headers of that re-encode were read - /// (`frame=228x128 upscaled=256 use_superres=true denom=9` on all four) -- - /// which is where the numbers below come from, not from the flags. - #[test] - fn a_444_lossy_superres_mode1_den9_stream_decodes_pixel_exact() { - a_444_superres_arm( - "a_444_lossy_superres_mode1_den9_stream_decodes_pixel_exact", - "fixtures/444_lossy_superres_256x128_d9.obu", - 17437, - 0x1ff2_fb84_528f_aa05, - "3d619ee0fda3d9bb9cf8ff0541ba00ea5d83ae38cd8eec1322f8dbbbe6a5ec96", - (256, 128), - &[(9, 228); 4], - ); - } - - /// lane-av1superpin (b): `--superres-mode=2` (random denominator), coded - /// 186x128 on the first frame and a DIFFERENT denominator on each frame - /// after it. - /// - /// **This is the cell that makes the flag-vs-header distinction - /// unavoidable.** Measured on the pinned bytes by parsing every frame - /// header, `--superres-mode=2` does not honour `--superres-denominator` - /// at all -- encoding the recipe four times (no denominator, then 9, 12, - /// 16) produced ONE stream, sha256 - /// `c18496cf3b7db0feca9aa904024cec2115be80b5b94f87c848ac52f9b32ffd97` - /// (16620 bytes), byte-identical every time -- and the parsed headers of - /// that stream are: - /// - /// ```text - /// FH0 frame=186x128 upscaled=256 use_superres=true denom=11 - /// FH1 frame=146x128 upscaled=256 use_superres=true denom=14 - /// FH2 frame=137x128 upscaled=256 use_superres=true denom=15 - /// FH3 frame=228x128 upscaled=256 use_superres=true denom=9 - /// ``` - /// - /// So a gate written against this cell that read the flag instead of the - /// header would assert `denom == 9` (or 12, or 16) and be wrong on three - /// of four frames -- or, worse, pass while printing numbers the stream does - /// not carry. Three of the four parsed denominators (11, 14, 15) are values - /// no flag on the command line ever named, which is the property the arm - /// below asserts directly. - /// - /// **Why it is worth a gate of its own** beyond the flag-ignoring point: - /// the den=12 and den=9 cells both scale every frame at one denominator, - /// so `av1_superres_upscale` is only ever handed one coded-to-upscaled - /// ratio. This stream hands it four (256->186, 256->146, 256->137, - /// 256->228) in one decode, and libaom's upscaler picks its filter taps - /// from `denom` per frame. That is the case a single-denominator gate - /// cannot reach. - /// - /// **The recipe**: - /// ```text - /// ffmpeg -f lavfi -i "testsrc2=size=256x128:rate=25" -frames:v 4 \ - /// -pix_fmt yuv444p -strict -1 -f yuv4mpegpipe - | \ - /// aomenc --codec=av1 --passes=1 --end-usage=q --cq-level=20 --cpu-used=2 \ - /// --threads=1 --row-mt=0 --lag-in-frames=0 --kf-max-dist=100 \ - /// --limit=4 --superres-mode=2 --obu -o - - - /// ``` - #[test] - fn a_444_lossy_superres_mode2_random_denom_stream_decodes_pixel_exact() { - const NAME: &str = "a_444_lossy_superres_mode2_random_denom_stream_decodes_pixel_exact"; - let heads = a_444_superres_arm( - NAME, - "fixtures/444_lossy_superres_mode2_256x128.obu", - 16620, - 0x8cbb_36b2_5e0f_07ab, - "c18496cf3b7db0feca9aa904024cec2115be80b5b94f87c848ac52f9b32ffd97", - (256, 128), - &[(11, 186), (14, 146), (15, 137), (9, 228)], - ); - - // The flag-ignoring arm. Every denominator libaom accepted on the - // command line, plus the recipe's own "no denominator at all", must - // land on the SAME bytes as the pinned fixture. If a future libaom - // starts honouring the flag under mode 2 this goes red -- and that is - // the point: the gate above is pinned to parsed denominators, so the - // day the flag starts mattering the pin has to be re-derived from the - // stream, not from the recipe. - if !have_ffmpeg() || !have_aomenc() { - eprintln!("{NAME}: flag-ignoring arm skipped (no ffmpeg/aomenc)"); - return; - } - let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - "testsrc2=size=256x128:rate=25", - "-frames:v", - "4", - "-pix_fmt", - "yuv444p", - "-strict", - "-1", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("ffmpeg failed to run"); - assert!( - y4m.status.success(), - "{NAME}: ffmpeg refused to generate the y4m source: {}", - String::from_utf8_lossy(&y4m.stderr) - ); - let pinned = std::fs::read( - std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("fixtures/444_lossy_superres_mode2_256x128.obu"), - ) - .expect("pinned fixture disappeared between the two reads"); - for extra in [ - vec![], - vec!["--superres-denominator=9"], - vec!["--superres-denominator=12"], - vec!["--superres-denominator=16"], - ] { - let mut args: Vec<&str> = vec![ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=20", - "--cpu-used=2", - "--threads=1", - "--row-mt=0", - "--lag-in-frames=0", - "--kf-max-dist=100", - "--limit=4", - "--superres-mode=2", - ]; - args.extend(extra.iter().copied()); - args.extend(["--obu", "-o", "-", "-"]); - let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); - assert!( - out.status.success(), - "{NAME}: aomenc refused the recipe with {extra:?}: {}", - String::from_utf8_lossy(&out.stderr) - ); - assert_eq!( - out.stdout.len(), - pinned.len(), - "{NAME}: --superres-mode=2 {extra:?} produced {} bytes, pinned is {} -- \ - mode 2 now honours --superres-denominator (or stopped scaling), and this \ - gate's per-frame denominators are pinned to the PARSED headers, not to \ - the recipe", - out.stdout.len(), - pinned.len() - ); - assert_eq!( - fnv1a64(&out.stdout), - fnv1a64(&pinned), - "{NAME}: --superres-mode=2 {extra:?} does NOT reproduce the pinned bytes" - ); - } - // And the denominators the stream carries must include values no flag - // on the command line ever named -- the property that makes "read the - // parsed header" the only correct source for the table above. - let flagged = [9u8, 12, 16]; - assert!( - heads - .iter() - .any(|h| h.superres_denom > 0 && !flagged.contains(&h.superres_denom)), - "{NAME}: every parsed denominator is one of the flags {flagged:?} -- if libaom \ - ever starts honouring --superres-denominator under mode 2 this cell stops being \ - the flag-ignoring one and the pin has to be re-derived" - ); - eprintln!( - "{NAME}: --superres-mode=2 with no/9/12/16 denominator flags all reproduce the \ - pinned {} bytes; parsed denominators {:?} (flag values {flagged:?} ignored)", - pinned.len(), - heads.iter().map(|h| h.superres_denom).collect::>() - ); - } - - /// lane-av1lossy128x96: the 128x96 sibling of the pinned 128x128 witness - /// `a_pinned_444_inter_stream_chroma_units_inherit_their_own_quadrants_tx_type` - /// (commit 6c33f204). That fix closed the "4:4:4 lossy + TX size search" - /// divergence (H2) for the 128x128 twin; the 128x96 geometry -- two whole - /// 64x64 roots over a frame whose second block row is only 32 rows tall, - /// which is why it exercises BOTH chroma planes and a partial block row -- - /// was left ungated, and it is the geometry the sweep measured the - /// U+V form of the defect on (608 wrong samples from decode-order frame 2). - /// - /// Measured for this lane on the fix's parent `4155c7c7`: decode-order - /// frames 2 and 3 differ from the oracle in 608 and 692 samples (luma - /// exact, U and V wrong), entropy bit-identical; at HEAD and at `6c33f204` - /// all four frames are byte-exact. So the defect is FIXED and this gate is - /// the pin that keeps it fixed. - /// - /// Recipe (encoded LIVE, no fixture): `testsrc2 128x96:rate=25` yuv444p - /// 4 frames, `aomenc --profile=1 --codec=av1 --passes=1 --end-usage=q - /// --cq-level=20 --cpu-used=2 --sb-size=64 --min-partition-size=64 - /// --max-partition-size=64 --enable-tx-size-search=1 --threads=1 --row-mt=0 - /// --lag-in-frames=0 --kf-max-dist=100 --limit=4 --obu -o - -`. - /// Search ON: 21830 B, sha256 `7380bcbbfb791c6a369850357211223e20fab959423135951f6eb43ffbfcfebd`, - /// fnv1a64 `0x1ba3fe9a4335bdbb`. Control arm, same recipe with - /// `--enable-tx-size-search=0`: 21296 B, sha256 - /// `347edcc9f4899fb05b15174b82d37f6562dcc6fe7691af0ed9ba4efd6cc878c6`, - /// fnv1a64 `0x2f87d8e98c9db686`. - /// - /// NON-VACUITY, and the search flag is NOT the assert: the recipe SPELLS - /// `--enable-tx-size-search=1` (aomenc keeps the FIRST occurrence, and a - /// flag left defaulted is "unknown", not "on"), and then - /// 1. every frame header's PARSED `tx_mode` is `TxMode::Select` - /// (`TX_MODE_SELECT`) -- the searched transform mode is really in the - /// bitstream, not merely requested. The control arm asserts the - /// opposite (`TxMode::Largest`), so neither arm can pass on the other's - /// stream; - /// 2. the sequence header is `ss (0,0)` at 8 bits (`assert_444_header`), - /// and the stream is byte-identical to the recorded encode (length + - /// fnv1a64), so an aomenc that stopped producing this cell fails here - /// rather than silently measuring something else; - /// 3. `decode::chroma_quad_leaf_tx_diff_hits()` strictly increases on the - /// search arm -- the number that says the per-quadrant resolve CHANGED - /// an answer, which is the defect itself. It must be exactly 0 on the - /// search-off control: with no var-tx there is no four-leaf luma tree, - /// so the arm is unreachable and a counter that fired there would be - /// counting something else; - /// 4. every decoded plane is 128*96 (at `ss (0,0)` chroma is full - /// resolution, so a subsampled extent fails the shape assert); - /// 5. `decode_all_frames_vs_oracle` asserts the decode-order frame COUNT - /// and each frame's byte LENGTH before any sample is compared. - /// - /// Red-before: reverting ONLY the per-quadrant resolve in - /// `decode_inter_block`'s 64x64 four-unit chroma arm (the `covering_leaf_tx_type` - /// call back to the block-level `first_tx_type`, counters and this gate - /// untouched) turns this gate red on decode-order frame 2 with 608 bytes - /// differing, and green again on restore. - #[test] - fn a_real_aomenc_444_whole_64_root_tx_size_search_stream_decodes_pixel_exact_at_128x96() { - const NAME: &str = - "a_real_aomenc_444_whole_64_root_tx_size_search_stream_decodes_pixel_exact_at_128x96"; - let _gate_lock = lock_gate_counters(); - if !have_ffmpeg() || !have_aomenc() { - eprintln!("SKIP {NAME}: no ffmpeg/aomenc"); - return; - } - // (label, --enable-tx-size-search, parsed tx mode, bytes, fnv1a64) - let arms: [(&str, &str, TxMode, usize, u64); 2] = [ - ( - "tx size search on", - "1", - TxMode::Select, - 21830, - 0x1ba3_fe9a_4335_bdbb, - ), - ( - "tx size search off (control)", - "0", - TxMode::Largest, - 21296, - 0x2f87_d8e9_8c9d_b686, - ), - ]; - for (label, search, want_mode, want_len, want_fnv) in arms { - let search_flag = format!("--enable-tx-size-search={search}"); - let stream = chroma_format_stream( - 128, - 96, - "yuv444p", - 8, - 4, - &[ - "--profile=1", - "--cq-level=20", - "--cpu-used=2", - "--sb-size=64", - "--min-partition-size=64", - "--max-partition-size=64", - &search_flag, - ], - 0, - ); - assert_444_header(&stream, NAME, 8); - assert_eq!( - stream.len(), - want_len, - "{NAME} ({label}): aomenc produced {} bytes, not the recorded {want_len} -- the \ - recipe no longer makes this cell", - stream.len() - ); - assert_eq!( - fnv1a64(&stream), - want_fnv, - "{NAME} ({label}): the encoded bytes moved" - ); - // PARSED, not requested: the transform mode the bitstream carries. - let mut parser = Av1Parser::new(); - let mut pos = 0usize; - let mut modes: Vec = Vec::new(); - while pos < stream.len() { - let obu = parser - .parse_obu(&stream[pos..]) - .unwrap_or_else(|e| panic!("{NAME}: aomenc OBU does not parse: {e:?}")); - if obu.total_size == 0 { - break; - } - pos += obu.total_size; - if let ObuKind::FrameHeader(h) | ObuKind::Frame(h, _) = obu.kind { - modes.push(h.tx_mode); - } - } - assert_eq!( - modes.len(), - 4, - "{NAME} ({label}): four frame headers expected" - ); - for (i, mode) in modes.iter().enumerate() { - assert_eq!( - *mode, want_mode, - "{NAME} ({label}): decode-order frame {i} carries tx_mode {mode:?}, not \ - {want_mode:?} -- the searched-transform claim is about the bitstream" - ); - } - let diff0 = crate::decode::chroma_quad_leaf_tx_diff_hits(); - let frames = decode_stream(&stream) - .unwrap_or_else(|e| panic!("{NAME} ({label}): refused the stream: {e}")); - let diff = crate::decode::chroma_quad_leaf_tx_diff_hits() - diff0; - for (i, f) in frames.iter().enumerate() { - assert_eq!( - f.y.len(), - 128 * 96, - "{NAME} ({label}): frame {i} luma is {} samples, not 128x96", - f.y.len() - ); - assert_eq!( - f.u.len(), - 128 * 96, - "{NAME} ({label}): frame {i} U is {} samples -- at 4:4:4 the chroma plane is \ - full resolution", - f.u.len() - ); - } - // Pixel compare FIRST: it is the informative failure (it names the - // decode-order frame and the sample), and the counter assert below - // is the guard that says WHY the cell is not vacuous. - let (frames_decoded, _hidden) = decode_all_frames_vs_oracle(&stream, NAME); - assert!( - frames_decoded >= 4, - "{NAME} ({label}): {frames_decoded} decode-order frames" - ); - if label.starts_with("tx size search on") { - assert!( - diff >= 2, - "{NAME}: the per-quadrant tx_type resolve never CHANGED an answer (diff \ - {diff}) -- on this stream the four-leaf luma tree under a searched transform \ - is exactly what makes the block-level value wrong" - ); - } else { - assert_eq!( - diff, 0, - "{NAME}: the four-unit 4:4:4 chroma arm fired with tx size search OFF \ - ({diff} resolves) -- the counter is not measuring the searched path" - ); - } - eprintln!( - "{NAME} ({label}): {frames_decoded} frames byte-exact vs aomdec, tx_mode \ - {want_mode:?} on every frame, quad-tx resolves that differed {diff}" - ); - } - } - - /// lane-ibc444c: the 4:4:4 intra-BC chroma cell. `decode_intrabc_rect` - /// sized a rect intra-BC block's chroma plane block with a hardcoded 4:2:0 - /// halving (`bw / 2`, `bh / 2`, origin `px / 2`). - /// `av1_get_max_uv_txsize` (`av1/common/blockd.h`) is `ss_size_lookup[bsize]` - /// and applies NO halving of its own, and `get_vartx_max_txsize` (`:1447`) - /// then reads that plane block as `max_txsize_rect_lookup[plane_bsize]`. So - /// at 4:4:4 an 8x16 luma block's chroma plane block is 8x16 and libaom - /// codes it as ONE TX_8X16, while the halving read the same 8x16 footprint - /// as ONE 4x8 rect unit. - /// - /// **Localised by trace, not by reading** (`EC_IBCTX`, this commit's rung - /// on `read_coeffs_rect`, paired against the oracle's `EC_ECDUMP_IN` by - /// STREAM BIT POSITION — never by the 16-bit `rng`, which collides at this - /// scale, and never by a plane label, which is the ORACLE's side of the - /// pairing): - /// - /// ```text - /// oracle bit 6870 plane=0 mi=(92,104) tx=7 (TX_8X16) all_zero=0 - /// ours bit 6885 8x16 skip_ctx=0 decode.rs (read_inter_plane_rect) - /// oracle bit 6878 plane=1 mi=(92,104) tx=7 (TX_8X16) all_zero=1 - /// ours bit 6893 4x8 skip_ctx=0 decode.rs <-- FORK - /// oracle bit 6879 plane=2 mi=(92,104) tx=7 (TX_8X16) all_zero=1 - /// ours bit 6902 4x8 skip_ctx=0 decode.rs - /// ``` - /// - /// The `txb_skip` VALUE first disagrees one unit before the bit position - /// does: the oracle skips the U unit, we do not, we burn 14 extra bits, and - /// every later symbol decodes from the wrong place. Reverting the two - /// arithmetic lines reproduces luma sample **205264** as the first wrong - /// sample — the exact ceiling `lanes/av1444rect.report.md` rounds 3-4 - /// documented — which is the red-before proof. - /// - /// **The 4:4:4 pixel arm is a PREFIX, not an exactness claim, and the - /// residual is an ENTROPY fork — NOT a reconstruction one.** An earlier - /// round of this lane claimed the coefficient ladder was "bit-exact for all - /// 2359 oracle units" and inferred from that the tail was reconstruction. - /// **That claim was wrong and is retracted** (see this branch's report r2): - /// the walk compared entry bits at matching LIST INDICES across two traces - /// of different lengths, and the square `read_coeffs` reader logs an - /// `all_zero` step even for a read that consumes ZERO bits, so it paired - /// 0-bit lines against real units. Measured on this branch, with the - /// 0-bit filter applied to BOTH sides: - /// - /// ```text - /// oracle all_zero reads 2395 (2359 with a real position) - /// our all_zero lines 3999 - /// our lines that consumed bits 1326 - /// 1:1 entry-bit matches, monotone merge 71 - /// ``` - /// - /// We perform ~1069 FEWER real symbol reads than the oracle. A - /// reconstruction-only defect cannot make a symbol count come up short, so - /// the tail is a second entropy fork, first visible in U and V at - /// **(x=160, y=80) = mi (20, 40)**, spreading to the whole x[320,640) - /// y[160,480) quadrant. (A figure of "1910 units matching 1:1 with 486 vs - /// 486 non-zero-bit reads" was relayed to this lane and does NOT reproduce - /// here — re-measure before quoting either number.) - /// - /// **The next reader must pair by BIT INTERVAL, not by index.** The oracle's - /// `EC_ECDUMP_IN` prints only the ENTRY position; there is no post position, - /// and entry bits alone drift the moment per-unit bit consumption differs. - /// The unblock is one line of oracle instrumentation OUTSIDE the repo — - /// print `aom_reader_tell(r)` after the `aom_read_symbol` at - /// `~/.cache/aom-oracle/src/av1/decoder/decodetxb.c:158` — then pair on - /// `(entry, post)`, which is exact and collision-free. Coordinate the - /// rebuild with the main session; every lane's oracle binary moves. - /// - /// 4:2:0 identity is a first-class arm, not a claim: `ss_x = ss_y = 1` - /// makes `bw >> ss_x` the same arithmetic as the halving, and the pinned - /// 4:2:0 twin (`420_intrabc_rect4_witness.obu`) is asserted byte-exact - /// against the oracle in the same run. - /// lane-av1offtile: a lossless HORZ/VERT strip's PLANE-MAJOR 4x4 chroma - /// walk is bounded by the CHROMA PLANE, not by the block's own footprint. - /// - /// libaom bounds every transform walk per PLANE -- `max_block_wide` / - /// `max_block_high` (`av1_common_int.h:1565`) add `mb_to_right_edge >> - /// (3 + pd->subsampling_x)` to the plane block's size before the - /// `>> MI_SIZE_LOG2`, and `av1_foreach_transformed_block_in_plane` - /// (`decodeframe.c:1124`) drops any unit whose `blk_col`/`blk_row` is past - /// them. `decode_rect_split`'s luma walk carries that clip - /// (`decode.rs`, the `tu_px >= y.true_width` guard lane-hgkf r1 added for - /// the LUMA plane); its lossless chroma walk counted `chroma_w / 4` x - /// `chroma_h / 4` off the block instead, so a block overhanging the bottom- - /// right frame edge read chroma transform units that do not exist. - /// - /// MEASURED on `mix176_offtile_chroma_clip.obu`, whose bytes are frame 0 - /// of the 4:2:0 8-bit `mix_176x144_6.obu` - /// (`ffmpeg -f lavfi -i testsrc2=size=176x144:rate=25 -frames:v 6 - /// -pix_fmt yuv420p`, then `aomenc --codec=av1 --obu --passes=1 - /// --cpu-used=4 --limit=6 --end-usage=q --cq-level=0 --aq-mode=1`; the - /// whole 6-frame stream is 20 069 B, sha256 - /// `02b15d0d5b08aa5aebf139aee94c31b4f8363d14649c238cd7a19a9785ef124a`, - /// and this fixture is its first 4 581 B -- the temporal delimiter, - /// sequence header and frame-0 OBU, nothing else). The bottom-right - /// superblock is the 48x16 sliver of a 176x144 frame, and its block at - /// `mi=(32,32)` `px=(128,128)` is `bw=64 bh=32`, so the chroma plane - /// block (`cpx=64 cpy=64`, plane 88x72) is 32x16 where only 24x8 is coded. - /// That is `cw_n` 8 -> 6 and `ch_n` 4 -> 2: **20 phantom units per plane, - /// 40 in total**, and 40 is exactly the extra-read count the paired - /// `EC_SYMR` ladder measures (ours 25792..25831, the oracle doing a - /// range-coder init for the next frame there). - /// - /// The unit count below is the load-bearing number, not the pixels: the - /// 40 phantom reads all carry `all_zero` and consume no data (the bit - /// position freezes at 36288), so frame 0's pixels are byte-exact EITHER - /// WAY and a pixel compare alone would be blind to this defect. Frame 0's - /// transform-unit count is 2413 without the clip and 2373 with it, and - /// **2373 is the oracle's own count** -- the number of `EC_ECDUMP_IN` - /// lines the shared `aomdec` prints for the same bytes. Reverting the - /// clip restores 2413 and fails this assert; that is the mutation proof. - /// - /// What the 40 reads cost, on the FULL 6-frame stream rather than this - /// prefix: the desync is 11 970 reads downstream of them, where the - /// exhausted tile yields an unbounded `read_golomb` tail and the decoder - /// refuses with `unsupported: AV1 tile (a Golomb tail longer than this - /// decoder reads)` -- a supported 4:2:0 8-bit cell lost to a walk that ran - /// off its own tile. Fixing the walk moves the first remaining divergence - /// on the full stream from SYMR 25 792 to 29 411, a different block at a - /// different geometry (the var-tx/`lossless` conjunct lane-av1mixllfork - /// and lane-av1golomb320 own), and both this clip and that one applied - /// together decode the cell and match the oracle byte for byte. That - /// composition is measured, not claimed: this gate pins only the walk - /// this commit fixes. - #[test] - fn a_420_lossless_rect_chroma_walk_is_bounded_by_the_chroma_plane() { - const NAME: &str = "a_420_lossless_rect_chroma_walk_is_bounded_by_the_chroma_plane"; - const FIXTURE: &str = "mix176_offtile_chroma_clip.obu"; - const FIXTURE_LEN: usize = 4581; - const FIXTURE_FNV: u64 = 0x5e31be5efc9c3c1d; - /// The oracle's own `EC_ECDUMP_IN` count for these bytes. - const ORACLE_UNITS: usize = 2373; - const W: usize = 176; - const H: usize = 144; - - let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join(format!("fixtures/{FIXTURE}")); - let stream = read_pin(&path, FIXTURE_LEN, FIXTURE_FNV, NAME); - assert_eq!( - stream_bit_depth(&stream, NAME), - 8, - "{NAME}: the pinned witness is not 8-bit" - ); - - let _guard = lock_gate_counters(); - crate::decode::reset_rect_split_lossless_chroma_offtile_hits(); - crate::decode::reset_census_unit_n(); - let frames = decode_stream(&stream) - .unwrap_or_else(|e| panic!("{NAME}: the pinned witness no longer decodes: {e}")); - assert_eq!(frames.len(), 1, "{NAME}: frame count"); - assert_eq!( - (frames[0].width, frames[0].height), - (W, H), - "{NAME}: dimensions" - ); - - // Non-vacuity: the clip must have run on this fixture, or the unit - // count below is just "the walk happened to be short here" (class - // gate-blind-to-feature). - let clipped = crate::decode::rect_split_lossless_chroma_offtile_hits(); - assert!( - clipped > 0, - "{NAME}: no lossless rect chroma unit fell outside the chroma plane -- \ - the corrected walk never ran, so this gate is measuring the \ - unclipped one (class gate-blind-to-feature)" - ); - - // The oracle-anchored red-before/green-after: 2413 without the clip. - let units = crate::decode::census_unit_n(); - assert_eq!( - units, ORACLE_UNITS, - "{NAME}: frame 0 walked {units} transform units, the oracle's own \ - EC_ECDUMP_IN census for these bytes is {ORACLE_UNITS}" - ); - - decode_all_frames_vs_oracle(&stream, NAME); - } - - #[test] - fn a_444_intrabc_rect_chroma_plane_block_is_the_block_footprint() { - const NAME: &str = "a_444_intrabc_rect_chroma_plane_block_is_the_block_footprint"; - const F444: &str = "444_intrabc_rect4_witness.obu"; - const F444_LEN: usize = 1016; - const F420: &str = "420_intrabc_rect4_witness.obu"; - const F420_LEN: usize = 890; - let read = |name: &str, file: &str, len: usize| -> Vec { - let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join(format!("fixtures/{file}")); - let bytes = std::fs::read(&path) - .unwrap_or_else(|e| panic!("{name}: pinned fixture {file} missing: {e}")); - assert_eq!(bytes.len(), len, "{name}: {file} length moved"); - bytes - }; - let stream444 = read(NAME, F444, F444_LEN); - let stream420 = read(NAME, F420, F420_LEN); - // The defect only exists where `ss_size_lookup` != the 4:2:0 halving. - assert_444_header(&stream444, NAME, 8); - - let _guard = lock_gate_counters(); - crate::decode::reset_ibc_rect_chroma_footprint_444_hits(); - let frames = decode_stream(&stream444) - .unwrap_or_else(|e| panic!("{NAME}: the pinned 4:4:4 witness was refused: {e}")); - let hits = crate::decode::ibc_rect_chroma_footprint_444_hits(); - assert_eq!(frames.len(), 1, "{NAME}: frame count"); - assert!( - hits > 0, - "{NAME}: no rect intra-BC block was sized at 4:4:4 -- the corrected \ - footprint never ran, so this gate is measuring the hardcoded 4:2:0 \ - halving (class gate-blind-to-feature)" - ); - - // lane-av1oraclepost: main's shared probe. With - // EC_AV1_REQUIRE_AOMDEC / EC_AV1_REQUIRE_AOMENC set it is a HARD - // failure, so a batch run cannot report GREEN with the compare never - // run -- ONE presence-check shape in the crate. - if !aomdec_available(NAME) { - eprintln!("{NAME}: {hits} rect intra-BC block(s) sized at 4:4:4; pixel arm SKIPPED"); - return; - } - - // 4:2:0 identity FIRST and in full. - decode_all_frames_vs_oracle(&stream420, &format!("{NAME}-420")); - - // 4:4:4 is a per-plane exact PREFIX, not an exactness claim, and the - // doc above says why. Asserting "wrong by exactly N" would encode the - // open entropy fork as expected behaviour; the floor is the honest form - // and it only ever grows. - const PLANE: usize = 640 * 480; - const EXACT_PREFIX: [usize; 3] = [PLANE, 51360, 51360]; - let dir = std::env::temp_dir().join(format!("ec-av1-{NAME}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).expect("scratch dir"); - let in_obu = dir.join("in.obu"); - std::fs::write(&in_obu, &stream444).expect("writing the stream"); - let aom_prefix = dir.join("aom"); - let out = crate::tool_cache::cached_output_io(Command::new(aomdec_path()) - .args(["--codec=av1", "-o"]) - .arg(dir.join("out.y4m")) - .arg(&in_obu) - .env("EC_AV1_FINAL_DUMP", &aom_prefix) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("aomdec failed to run"); - assert!( - out.status.success(), - "{NAME}: the oracle aomdec refused the stream: {}", - String::from_utf8_lossy(&out.stderr) - ); - let ours_prefix = dir.join("ours"); - set_final_dump_prefix(Some(ours_prefix.display().to_string())); - let _ = decode_stream(&stream444).expect("second decode"); - set_final_dump_prefix(None); - let aom_dump = std::fs::read(format!("{}.f0", aom_prefix.display())).expect("oracle dump"); - let our_dump = std::fs::read(format!("{}.f0", ours_prefix.display())).expect("our dump"); - assert_eq!( - our_dump.len(), - aom_dump.len(), - "{NAME}: our frame is {} bytes, the oracle's is {}", - our_dump.len(), - aom_dump.len() - ); - assert_eq!(aom_dump.len(), 3 * PLANE, "{NAME}: 8-bit 4:4:4 640x480"); - for (plane, name) in [(0usize, "Y"), (1, "U"), (2, "V")] { - let at = plane * PLANE; - let floor = EXACT_PREFIX[plane]; - if our_dump[at..at + floor] == aom_dump[at..at + floor] { - continue; - } - let first = (0..floor) - .find(|&s| our_dump[at + s] != aom_dump[at + s]) - .unwrap_or(floor); - panic!( - "{NAME}: plane {name} diverges from the oracle at sample {first} of {PLANE} \ - (x={}, y={}) -- the exact prefix this gate pins is {floor} and it only \ - grows; the chroma tail is the OPEN entropy fork in \ - lanes/ibc444c.report.md r2", - first % 640, - first / 640 - ); - } - let _ = std::fs::remove_dir_all(&dir); - eprintln!( - "{NAME}: {hits} rect intra-BC block(s) sized at 4:4:4; 4:2:0 twin \ - byte-exact; 4:4:4 luma byte-exact (307200/307200), U and V byte-exact to \ - sample 51360 -- the chroma tail is the OPEN entropy fork \ - (lanes/ibc444c.report.md r2), NOT an assertion" - ); - } - - /// lane-av1chromarect: the 128-root intra-BC HORZ/VERT strip's chroma - /// plane block, on the 4:4:4 LOSSY witness `fixtures/r512.obu` that - /// reaches `decode_intrabc_owned_rect` five times. - /// - /// The extent is the ss-derived one (`bw >> ss_x` by `bh >> ss_y`; - /// `av1_get_max_uv_txsize` = `ss_size_lookup[bsize]`, blockd.h:1372), and - /// the plane block is walked by `get_vartx_max_txsize` steps -- a 4:4:4 - /// 32x64 luma block's chroma plane block is 32x64, which libaom codes as - /// TWO `TX_32X32` units, not as one 32x64 transform. - /// - /// This gate WAS the refusal assertion "a rectangular inter chroma - /// transform unit whose shape has no coefficient table set here", put - /// there one commit earlier so that the day the arm landed it would go - /// RED and force this rewrite. The refusal string is GONE from the - /// witness's decode because nothing reaches it any more, not because it - /// was deleted: `rect_inter_chroma_set` still refuses (32, 64) and the - /// string is still in the source, it is just not on this path any more. - /// - /// The floors were RAISED to full byte-exactness on all three planes of - /// all three frames by lane-av1chromadc, which closed the "open chroma - /// fork" this gate used to carry: a skipped 64x64 square block at 4:4:4 - /// has a 64x64 chroma plane block, libaom walks it as a 2x2 grid of - /// `TX_32X32` units, and the intra-BC chroma override was handed to every - /// unit whole instead of windowed per unit (see - /// `a_444_skipped_64x64_square_block_windows_its_chroma_override_per_unit` - /// and lanes/av1chromadc.report.md). The history of these floors: - /// - /// * lane-av1chromarect, after the ss-derived extent and the multi-unit - /// walk: `[[262144, 229728, 229728], [262144, 65704, 65704], - /// [262144, 262144, 262144]]` -- luma exact on all three frames, frame 2 - /// exact on all three planes, 79969 chroma samples still wrong. - /// * lane-av1chromadc: `[[262144; 3]; 3]` -- every plane of every frame - /// byte-exact against aomdec. Floors only ever grow. - #[test] - fn a_444_intrabc_owned_rect_strip_sizes_its_chroma_plane_block_and_decodes() { - const NAME: &str = - "a_444_intrabc_owned_rect_strip_sizes_its_chroma_plane_block_and_decodes"; - const FILE: &str = "r512.obu"; - const LEN: usize = 6948; - /// 512x512 8-bit 4:4:4, one plane. - const PLANE: usize = 512 * 512; - /// Exact prefix per (frame, plane), decode order. FULL: every plane of - /// every frame is byte-exact against the oracle. - const EXACT_PREFIX: [[usize; 3]; 3] = [[PLANE; 3]; 3]; - let path = - std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(format!("fixtures/{FILE}")); - let stream = std::fs::read(&path) - .unwrap_or_else(|e| panic!("{NAME}: pinned fixture {FILE} missing: {e}")); - assert_eq!(stream.len(), LEN, "{NAME}: {FILE} length moved"); - assert_444_header(&stream, NAME, 8); - - let _guard = lock_gate_counters(); - reset_ibc_owned_rect_chroma_footprint_444_hits(); - // The refusal this gate used to assert must NOT be what happens now. - let dir = std::env::temp_dir().join(format!("ec-av1-{NAME}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).expect("scratch dir"); - let obu = dir.join("in.obu"); - std::fs::write(&obu, &stream).expect("writing the stream"); - let aom_prefix = dir.join("aom"); - let out = crate::tool_cache::cached_output_io(Command::new(aomdec_path()) - .args(["--codec=av1", "-o"]) - .arg(dir.join("out.y4m")) - .arg(&obu) - .env("EC_AV1_FINAL_DUMP", &aom_prefix) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("aomdec failed to run"); - assert!( - out.status.success(), - "{NAME}: the oracle aomdec refused the stream: {}", - String::from_utf8_lossy(&out.stderr) - ); - let ours_prefix = dir.join("ours"); - set_final_dump_prefix(Some(ours_prefix.display().to_string())); - let decoded = decode_stream(&stream); - set_final_dump_prefix(None); - if let Err(e) = decoded { - panic!( - "{NAME}: this decoder refused the witness: {e} -- the chroma plane block is \ - sized ss-wide and walked in `get_vartx_max_txsize` units, so the 4:4:4 32x64 \ - plane block is two TX_32X32 units, NOT the rect unit the refusal named" - ); - } - let hits = ibc_owned_rect_chroma_footprint_444_hits(); - assert_eq!( - hits, 5, - "{NAME}: {hits} 128-root intra-BC strip(s) sized at 4:4:4, not 5 -- the witness \ - stopped exercising the arm" - ); - assert!( - !std::fs::read(format!("{}.f0", ours_prefix.display())) - .unwrap_or_default() - .is_empty(), - "{NAME}: our decoder wrote no frame" - ); - // Index loop mirrors the spec's per-position form over several offsets; an iterator would obscure it. - #[allow(clippy::needless_range_loop)] - for f in 0..3 { - let aom_dump = std::fs::read(format!("{}.f{f}", aom_prefix.display())) - .unwrap_or_else(|e| panic!("{NAME}: oracle dump f{f} missing: {e}")); - let our_dump = std::fs::read(format!("{}.f{f}", ours_prefix.display())) - .unwrap_or_else(|e| panic!("{NAME}: our dump f{f} missing: {e}")); - assert_eq!( - our_dump.len(), - 3 * PLANE, - "{NAME}: frame {f} is not 8-bit 4:4:4 512x512" - ); - assert_eq!( - our_dump.len(), - aom_dump.len(), - "{NAME}: frame {f} length differs" - ); - for (plane, name) in [(0usize, "Y"), (1, "U"), (2, "V")] { - let at = plane * PLANE; - let floor = EXACT_PREFIX[f][plane]; - if our_dump[at..at + floor] == aom_dump[at..at + floor] { - continue; - } - let first = (0..floor) - .find(|&s| our_dump[at + s] != aom_dump[at + s]) - .unwrap_or(floor); - panic!( - "{NAME}: frame {f} plane {name} diverges from the oracle at sample {first} \ - of {PLANE} (x={}, y={}) -- the exact prefix this gate pins is {floor} and \ - it only grows", - first % 512, - first / 512 - ); - } - } - let _ = std::fs::remove_dir_all(&dir); - } - - /// lane-av1ibcfork: the SECOND 4:4:4 intra-BC witness, and the one the - /// entropy investigation was chartered against. `444_intrabc_rect4_witness.obu` - /// reaches `decode_intrabc_owned_rect`'s SKIP arm once -- the 64x32 block at - /// mi (40,80) -- and is byte-exact on all three planes. - /// - /// Why a second witness and not a repeat of - /// `a_444_intrabc_owned_rect_strip_sizes_its_chroma_plane_block_and_decodes` - /// (which pins `r512.obu`): the skip arm's defect was a wrong PLACE, not a - /// wrong size, and the two shapes produce DIFFERENT symptoms. `r512.obu`'s - /// 128-root strips fail as a sizing error inside the coefficient walk; this - /// witness's 64x32 skip block read no coefficient at all, so the only - /// symptom was pixels -- a 32x16 window committed at (px/2, py/2) = - /// (160,80) over a region another block had already reconstructed, and its - /// own 64x32 footprint at (320,160) left unwritten. Measured before the - /// ss correction: U 72945 / V 64865 of 307200 wrong, first at (160,80) on - /// both planes, luma byte-exact; the two 8x8-cell difference components - /// were 8 cells at x[160,192) y[80,96) and 1182 cells over the whole - /// x[320,640) y[160,480) quadrant -- one wrong-place write, not two. - /// - /// Full byte-exactness, not a prefix. That is possible only because - /// `lane-av1chromarect` (the ss-derived extent and origins, this function - /// included -- the skip arm was where the defect was first reached) and - /// `lane-av1chromadc` (the per-unit windowed chroma override) both landed; - /// before them this witness carried the open tail - /// `lanes/ibc444c.report.md` r2 recorded. The 4:2:0 twin is asserted - /// byte-exact in the same run, where `>> ss_x` IS `/ 2`. - #[test] - fn a_444_intrabc_rect4_witness_is_byte_exact_after_the_skip_arm_footprint() { - const NAME: &str = "a_444_intrabc_rect4_witness_is_byte_exact_after_the_skip_arm_footprint"; - const F444: &str = "444_intrabc_rect4_witness.obu"; - const F444_LEN: usize = 1016; - const F420: &str = "420_intrabc_rect4_witness.obu"; - const F420_LEN: usize = 890; - const PLANE: usize = 640 * 480; - let read = |file: &str, len: usize| -> Vec { - let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join(format!("fixtures/{file}")); - let data = - std::fs::read(&path).unwrap_or_else(|e| panic!("{NAME}: reading {file}: {e}")); - assert_eq!(data.len(), len, "{NAME}: {file} is pinned at {len} bytes"); - data - }; - let stream444 = read(F444, F444_LEN); - let stream420 = read(F420, F420_LEN); - assert_444_header(&stream444, NAME, 8); - - let _guard = lock_gate_counters(); - if !aomdec_available(NAME) { - eprintln!("{NAME}: SKIP -- no aomdec; run scripts/build-aom-oracle.sh"); - return; - } - // 4:2:0 identity FIRST and in full: `>> ss_x` is `/ 2` at ss=1, so - // this arm is the measurement, not a claim about it. - decode_all_frames_vs_oracle(&stream420, &format!("{NAME}-420")); - - crate::decode::reset_ibc_owned_rect_chroma_footprint_444_hits(); - let dir = std::env::temp_dir().join(format!("ec-av1-{NAME}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).expect("scratch dir"); - let in_obu = dir.join("in.obu"); - std::fs::write(&in_obu, &stream444).expect("writing the stream"); - let aom_prefix = dir.join("aom"); - let out = crate::tool_cache::cached_output_io(Command::new(aomdec_path()) - .args(["--codec=av1", "-o"]) - .arg(dir.join("out.y4m")) - .arg(&in_obu) - .env("EC_AV1_FINAL_DUMP", &aom_prefix) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("aomdec failed to run"); - assert!( - out.status.success(), - "{NAME}: the oracle aomdec refused the stream: {}", - String::from_utf8_lossy(&out.stderr) - ); - let ours_prefix = dir.join("ours"); - set_final_dump_prefix(Some(ours_prefix.display().to_string())); - let _ = decode_stream(&stream444).expect("second decode"); - set_final_dump_prefix(None); - let hits = crate::decode::ibc_owned_rect_chroma_footprint_444_hits(); - assert!( - hits > 0, - "{NAME}: no rect intra-BC block committed a 4:4:4 chroma plane block -- the \ - ss-derived footprint never ran, so this gate is measuring a hardcoded halving \ - (class gate-blind-to-feature)" - ); - let aom_dump = std::fs::read(format!("{}.f0", aom_prefix.display())).expect("oracle dump"); - let our_dump = std::fs::read(format!("{}.f0", ours_prefix.display())).expect("our dump"); - assert_eq!(aom_dump.len(), 3 * PLANE, "{NAME}: 8-bit 4:4:4 640x480"); - assert_eq!( - our_dump.len(), - aom_dump.len(), - "{NAME}: our frame is {} bytes, the oracle's is {}", - our_dump.len(), - aom_dump.len() - ); - for (plane, name) in [(0usize, "Y"), (1, "U"), (2, "V")] { - let at = plane * PLANE; - if our_dump[at..at + PLANE] == aom_dump[at..at + PLANE] { - continue; - } - let first = (0..PLANE) - .find(|&s| our_dump[at + s] != aom_dump[at + s]) - .unwrap_or(PLANE); - panic!( - "{NAME}: plane {name} diverges from the oracle at sample {first} of {PLANE} \ - (x={}, y={}) -- this gate pins FULL byte-exactness on all three planes", - first % 640, - first / 640 - ); - } - let _ = std::fs::remove_dir_all(&dir); - eprintln!( - "{NAME}: {hits} rect intra-BC block(s) committed a 4:4:4 chroma plane block; \ - 4:2:0 twin byte-exact; 4:4:4 byte-exact on all three planes \ - (307200 samples each)" - ); - } - - /// lane-av1chromadc: a SKIPPED 64x64 square block at 4:4:4 has a 64x64 - /// chroma plane block, which libaom walks as a 2x2 grid of `TX_32X32` units - /// (`get_vartx_max_txsize`: `av1_get_adjusted_tx_size(TX_64X64) = - /// TX_32X32`). The intra-BC / UV-palette chroma override - /// ([`decode_block`]'s `intrabc_bufs` / `palette_uv_bufs`, the - /// `PALETTE_PRED` slot) is a whole-`chroma_side x chroma_height` buffer and - /// must be WINDOWED per unit: `PlaneBuf::reconstruct` uses the buffer it - /// takes as the unit's own `side x side` prediction. At 4:2:0 the chroma - /// plane block is one 32x32 unit, so the whole buffer IS that unit's - /// window and the bug is invisible -- which is why it survived every 4:2:0 - /// gate. At 4:4:4 every unit was handed the buffer's FIRST 32x32, so the - /// block's right and bottom chroma columns were a copy of its top-left - /// unit. - /// - /// The witness: `fixtures/r512.obu`, 4:4:4 8-bit 512x512, three frames. The - /// seed is frame 0, `mi=(112,80)`, `px=(320,448)`, `side=64`, `skip=1`, - /// `mode=0`, `uv_mode=0` -- a skipped intra-BC block at the frame's bottom - /// edge. Its chroma unit `cu=(1,0)` at `px=(352,448)` reconstructs a flat - /// 241 (U) / 110 (V) where the oracle has 202 / 222, because it read the - /// same override window as `cu=(0,0)`. - /// - /// This gate asserts FULL frame exactness on all three planes of all three - /// frames. It is the red-before: on the unpatched tree it fails at - /// `(352,448)` of frame 0, which is the seed's second chroma unit. - #[test] - fn a_444_skipped_64x64_square_block_windows_its_chroma_override_per_unit() { - const NAME: &str = "a_444_skipped_64x64_square_block_windows_its_chroma_override_per_unit"; - const FILE: &str = "r512.obu"; - const LEN: usize = 6948; - const PLANE: usize = 512 * 512; - let path = - std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(format!("fixtures/{FILE}")); - let stream = std::fs::read(&path) - .unwrap_or_else(|e| panic!("{NAME}: pinned fixture {FILE} missing: {e}")); - assert_eq!(stream.len(), LEN, "{NAME}: {FILE} length moved"); - assert_444_header(&stream, NAME, 8); - - let _guard = lock_gate_counters(); - reset_skip_chroma_override_window_hits(); - let dir = std::env::temp_dir().join(format!("ec-av1-{NAME}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).expect("scratch dir"); - let obu = dir.join("in.obu"); - std::fs::write(&obu, &stream).expect("writing the stream"); - let aom_prefix = dir.join("aom"); - let out = crate::tool_cache::cached_output_io(Command::new(aomdec_path()) - .args(["--codec=av1", "-o"]) - .arg(dir.join("out.y4m")) - .arg(&obu) - .env("EC_AV1_FINAL_DUMP", &aom_prefix) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("aomdec failed to run"); - assert!( - out.status.success(), - "{NAME}: the oracle aomdec refused the stream: {}", - String::from_utf8_lossy(&out.stderr) - ); - let ours_prefix = dir.join("ours"); - set_final_dump_prefix(Some(ours_prefix.display().to_string())); - if let Err(e) = decode_stream(&stream) { - panic!("{NAME}: this decoder refused the witness: {e}"); - } - set_final_dump_prefix(None); - // Non-vacuity: the windowed arm must have run, or the exactness below - // is measuring a witness that never reached the 2x2 chroma walk. - let windows = skip_chroma_override_window_hits(); - assert!( - windows >= 8, - "{NAME}: {windows} windowed chroma override unit(s) on this witness, expected at \ - least 8 (two skipped 64x64 intra-BC blocks x 2x2 units x 2 planes) -- the witness \ - stopped exercising the arm, so the exactness below is vacuous" - ); - for f in 0..3 { - let aom_dump = std::fs::read(format!("{}.f{f}", aom_prefix.display())) - .unwrap_or_else(|e| panic!("{NAME}: oracle dump f{f} missing: {e}")); - let our_dump = std::fs::read(format!("{}.f{f}", ours_prefix.display())) - .unwrap_or_else(|e| panic!("{NAME}: our dump f{f} missing: {e}")); - assert_eq!( - our_dump.len(), - 3 * PLANE, - "{NAME}: frame {f} is not 8-bit 4:4:4 512x512" - ); - for (plane, name) in [(0usize, "Y"), (1, "U"), (2, "V")] { - let at = plane * PLANE; - if our_dump[at..at + PLANE] == aom_dump[at..at + PLANE] { - continue; - } - let first = (0..PLANE) - .find(|&s| our_dump[at + s] != aom_dump[at + s]) - .unwrap_or(PLANE); - let wrong = (0..PLANE) - .filter(|&s| our_dump[at + s] != aom_dump[at + s]) - .count(); - panic!( - "{NAME}: decode-order frame {f} plane {name} is byte-exact nowhere -- first \ - divergence at sample {first} of {PLANE} (x={}, y={}), {wrong} samples \ - wrong. The seed is frame 0, mi=(112,80) px=(320,448) side=64 skip=1, whose \ - chroma unit cu=(1,0) at px=(352,448) must be the SECOND 32x32 window of \ - the block's chroma override and not a copy of cu=(0,0)'s.", - first % 512, - first / 512 - ); - } - } - let _ = std::fs::remove_dir_all(&dir); - } - - /// lane-av1rectreach, the 2x1 / 1x2 half of the class sweep - /// `a_444_skipped_64x64_square_block_windows_its_chroma_override_per_unit` - /// opened: `decode_rect_split`'s `chroma_tiled` walk is the THIRD site that - /// walks a 4:4:4 chroma plane block as a grid of Chroma32 units, and the - /// only one that handed every unit the BLOCK's reach. - /// - /// The other two are already per-unit and are not touched by this gate: - /// `decode_block`'s skip arm (`chroma_window`, lane-av1chromadc) and - /// `decode_block`'s coded arm (its own `tu_reach_rect`) both resolve - /// `has_top_right` per transform unit, the way libaom's - /// `av1_build_intra_predictors` does - /// (`has_top_right`, defined reconintra.c:196, called from - /// `av1_build_intra_predictors` at reconintra.c:1847), - /// fed the chroma txb walk's own `blk_col`/`blk_row`). - /// - /// Witness `fixtures/r512_rect2x1_1x2_444.obu`, 2697 B, - /// sha256 `a009ec580a1ff24250be53e11b8d09616da71e095cefd5eb621c941d40a8688b`: - /// - /// ```text - /// ffmpeg -f lavfi -i testsrc2=size=256x256:rate=1:duration=1 -pix_fmt yuv444p \ - /// -f rawvideo in.yuv - /// aomenc --codec=av1 -w 256 -h 256 --i444 --sb-size=64 --enable-palette=1 \ - /// --enable-rect-partitions=1 --enable-1to4-partitions=1 \ - /// --min-partition-size=32 --cq-level=40 --profile=1 --obu --limit=1 \ - /// -o r512_rect2x1_1x2_444.obu in.yuv - /// ``` - /// - /// (aom-affine aomenc, one key frame, 4:4:4 8-bit 256x256.) It reaches - /// BOTH grid shapes: a 64x32 chroma plane block as `nw=2 nh=1` of 32x32 - /// and a 32x64 one as `nw=1 nh=2`. - /// - /// RED-BEFORE, on the unpatched tree, measured with `EC_AV1_FINAL_DUMP` - /// (aomdec) against `set_final_dump_prefix` (ours), 786432 B per frame: - /// frame 0 plane Y 0 wrong, plane U 130 wrong, plane V 30 wrong -- all of - /// them in the right 6 columns of the `cu=(0,0)` unit at `mi=(48,48)` - /// `px=(192,192)`, a 64x32 block whose right edge IS the frame's, so the - /// block-level reach denied an above-right that libaom's per-unit - /// `col_off + top_right_count_unit < plane_bw_unit` (0 + 8 < 16) grants. - /// After: 0 wrong on all three planes. - #[test] - fn a_444_rect_strip_chroma_tiled_2x1_and_1x2_units_take_their_own_above_right_reach() { - const NAME: &str = - "a_444_rect_strip_chroma_tiled_2x1_and_1x2_units_take_their_own_above_right_reach"; - const FILE: &str = "r512_rect2x1_1x2_444.obu"; - const LEN: usize = 2697; - const SHA: &str = "a009ec580a1ff24250be53e11b8d09616da71e095cefd5eb621c941d40a8688b"; - const W: usize = 256; - const PLANE: usize = W * W; - let path = - std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(format!("fixtures/{FILE}")); - let stream = std::fs::read(&path) - .unwrap_or_else(|e| panic!("{NAME}: pinned fixture {FILE} missing: {e}")); - assert_eq!(stream.len(), LEN, "{NAME}: {FILE} length moved"); - assert_444_header(&stream, NAME, 8); - // The byte pin is fnv1a64, the same load-bearing-identity hash every - // other pinned gate here uses; the sha256 in this test's comment is - // the provenance half. A silent stream swap under the same name - // cannot stay green. - assert_eq!( - fnv1a64(&stream), - 0x2751ccaa079cc422, - "{NAME}: {FILE} bytes drifted from the fnv1a64 pin above (provenance sha256 \ - {SHA}) -- regenerate the stream with the recipe in this test's comment and \ - re-pin the length, the fnv1a64 and the sha256 together" - ); - - let _guard = lock_gate_counters(); - reset_rect_tiled_chroma_grid_hits(); - let dir = std::env::temp_dir().join(format!("ec-av1-{NAME}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).expect("scratch dir"); - let obu = dir.join("in.obu"); - std::fs::write(&obu, &stream).expect("writing the stream"); - let aom_prefix = dir.join("aom"); - let out = crate::tool_cache::cached_output_io(Command::new(aomdec_path()) - .args(["--codec=av1", "-o"]) - .arg(dir.join("out.y4m")) - .arg(&obu) - .env("EC_AV1_FINAL_DUMP", &aom_prefix) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("aomdec failed to run"); - assert!( - out.status.success(), - "{NAME}: the oracle aomdec refused the stream: {}", - String::from_utf8_lossy(&out.stderr) - ); - let ours_prefix = dir.join("ours"); - set_final_dump_prefix(Some(ours_prefix.display().to_string())); - if let Err(e) = decode_stream(&stream) { - panic!("{NAME}: this decoder refused the witness: {e}"); - } - set_final_dump_prefix(None); - - // Non-vacuity, in the order the claim depends on it: the walk must - // have reached a 2x1 AND a 1x2 grid, and at least one unit must have - // a per-unit reach that DIFFERS from the block-level one. Without the - // last one the two answers would be interchangeable everywhere and - // the exactness below would be measuring a witness the fix cannot - // touch. (It does not check the argument identity -- see - // `RECT_TILED_CHROMA_UNIT_REACH_HITS`; the exactness assert below is - // what reds when the substitution is deleted.) - let (reach_hits, h2x1, h1x2, h_nxn) = rect_tiled_chroma_grid_hits(); - assert!( - h2x1 >= 4 && h1x2 >= 4, - "{NAME}: the walk reached {h2x1} unit(s) in a 2x1 grid and {h1x2} in a 1x2 grid \ - (other multi-unit shapes: {h_nxn}), expected at least 4 of each -- the witness \ - stopped exercising one of the two grid shapes, so half the claim is vacuous" - ); - assert!( - reach_hits >= 1, - "{NAME}: {reach_hits} chroma unit(s) had a per-unit reach differing from the \ - block-level one, expected at least 1 -- on the unpatched tree every unit took \ - the block's reach, so the exactness below is vacuous" - ); - - let aom_dump = std::fs::read(format!("{}.f0", aom_prefix.display())) - .unwrap_or_else(|e| panic!("{NAME}: oracle dump f0 missing: {e}")); - let our_dump = std::fs::read(format!("{}.f0", ours_prefix.display())) - .unwrap_or_else(|e| panic!("{NAME}: our dump f0 missing: {e}")); - assert_eq!( - our_dump.len(), - 3 * PLANE, - "{NAME}: frame 0 is not 8-bit 4:4:4 256x256" - ); - for (plane, pname) in [(0usize, "Y"), (1, "U"), (2, "V")] { - let at = plane * PLANE; - if our_dump[at..at + PLANE] == aom_dump[at..at + PLANE] { - continue; - } - let first = (0..PLANE) - .find(|&s| our_dump[at + s] != aom_dump[at + s]) - .unwrap_or(PLANE); - let wrong = (0..PLANE) - .filter(|&s| our_dump[at + s] != aom_dump[at + s]) - .count(); - panic!( - "{NAME}: frame 0 plane {pname} is byte-exact nowhere -- first divergence at \ - sample {first} of {PLANE} (x={}, y={}), {wrong} samples wrong. Each unit of \ - this walk must resolve `has_top_right` over ITS OWN extent \ - (reconintra.c:196/1847), not the block's: the seed unit is cu=(0,0) of \ - 64x32 chroma grid at mi=(48,48) px=(192,192), whose right 6 columns are the \ - ones the truncated above row moved.", - first % W, - first / W - ); - } - let _ = std::fs::remove_dir_all(&dir); - } - - /// The UV-PALETTE half of the same class, and the cell - /// `lanes/av1chromadc.report.md` §5 left explicitly UNMEASURED ("every - /// multi-unit walk on this witness is `src=intrabc`; the UV-palette source - /// never reaches a multi-unit chroma walk here, so its arm of the sweep is - /// argued from the shared code path, not witnessed"). This witness is the - /// measurement: it puts a UV-palette block on a 1x2 16x64 chroma grid - /// (`mi=(32,12)`) as well as plenty of non-palette ones. - /// - /// Witness `fixtures/r512_rect1x2_444_palette.obu`, 2250 B, - /// sha256 `fad03c69087f316c1a117e8d8a70769d161b332bce7b2998e646312bb78fb067`: - /// - /// ```text - /// ffmpeg -f lavfi -i testsrc2=size=256x256:rate=1:duration=1 -pix_fmt yuv444p \ - /// -f rawvideo in.yuv - /// aomenc --codec=av1 -w 256 -h 256 --i444 --sb-size=64 --enable-palette=1 \ - /// --enable-rect-partitions=1 --enable-1to4-partitions=1 \ - /// --min-partition-size=16 --cq-level=40 --profile=1 --obu --limit=1 \ - /// -o r512_rect1x2_444_palette.obu in.yuv - /// ``` - /// - /// (`--min-partition-size=16` is what puts the 16x64 chroma grid on a - /// strip at all; at 32 the encoder only ever picks 32x64 / 64x32.) The - /// per-unit reach the fix installs is the same line for the palette and - /// the non-palette unit -- the palette only supplies the PREDICTION - /// (`palette_window`, decode.rs:12784), never the reach -- so this gate - /// exists to pin the prediction source down, not to re-prove the reach. - #[test] - fn a_444_rect_strip_chroma_tiled_1x2_palette_grid_decodes_byte_exact() { - const NAME: &str = "a_444_rect_strip_chroma_tiled_1x2_palette_grid_decodes_byte_exact"; - const FILE: &str = "r512_rect1x2_444_palette.obu"; - const LEN: usize = 2250; - const SHA: &str = "fad03c69087f316c1a117e8d8a70769d161b332bce7b2998e646312bb78fb067"; - const W: usize = 256; - const PLANE: usize = W * W; - let path = - std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(format!("fixtures/{FILE}")); - let stream = std::fs::read(&path) - .unwrap_or_else(|e| panic!("{NAME}: pinned fixture {FILE} missing: {e}")); - assert_eq!(stream.len(), LEN, "{NAME}: {FILE} length moved"); - assert_444_header(&stream, NAME, 8); - assert_eq!( - fnv1a64(&stream), - 0x7759753a0d3f75a2, - "{NAME}: {FILE} bytes drifted from the fnv1a64 pin above (provenance sha256 \ - {SHA}) -- regenerate the stream with the recipe in this test's comment and \ - re-pin the length, the fnv1a64 and the sha256 together" - ); - - let _guard = lock_gate_counters(); - reset_rect_tiled_chroma_grid_hits(); - let dir = std::env::temp_dir().join(format!("ec-av1-{NAME}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).expect("scratch dir"); - let obu = dir.join("in.obu"); - std::fs::write(&obu, &stream).expect("writing the stream"); - let aom_prefix = dir.join("aom"); - let out = crate::tool_cache::cached_output_io(Command::new(aomdec_path()) - .args(["--codec=av1", "-o"]) - .arg(dir.join("out.y4m")) - .arg(&obu) - .env("EC_AV1_FINAL_DUMP", &aom_prefix) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), None, |c| c.output()) - .expect("aomdec failed to run"); - assert!( - out.status.success(), - "{NAME}: the oracle aomdec refused the stream: {}", - String::from_utf8_lossy(&out.stderr) - ); - let ours_prefix = dir.join("ours"); - set_final_dump_prefix(Some(ours_prefix.display().to_string())); - if let Err(e) = decode_stream(&stream) { - panic!("{NAME}: this decoder refused the witness: {e}"); - } - set_final_dump_prefix(None); - - let (_reach_hits, h2x1, h1x2, _h_nxn) = rect_tiled_chroma_grid_hits(); - assert!( - h1x2 >= 4, - "{NAME}: the walk reached {h1x2} unit(s) in a 1x2 grid ({h2x1} in a 2x1), expected \ - at least 4 of the 1x2 -- the witness stopped exercising the arm" - ); - - let aom_dump = std::fs::read(format!("{}.f0", aom_prefix.display())) - .unwrap_or_else(|e| panic!("{NAME}: oracle dump f0 missing: {e}")); - let our_dump = std::fs::read(format!("{}.f0", ours_prefix.display())) - .unwrap_or_else(|e| panic!("{NAME}: our dump f0 missing: {e}")); - assert_eq!( - our_dump.len(), - 3 * PLANE, - "{NAME}: frame 0 is not 8-bit 4:4:4 256x256" - ); - for (plane, pname) in [(0usize, "Y"), (1, "U"), (2, "V")] { - let at = plane * PLANE; - if our_dump[at..at + PLANE] == aom_dump[at..at + PLANE] { - continue; - } - let first = (0..PLANE) - .find(|&s| our_dump[at + s] != aom_dump[at + s]) - .unwrap_or(PLANE); - let wrong = (0..PLANE) - .filter(|&s| our_dump[at + s] != aom_dump[at + s]) - .count(); - panic!( - "{NAME}: frame 0 plane {pname} is byte-exact nowhere -- first divergence at \ - sample {first} of {PLANE} (x={}, y={}), {wrong} samples wrong.", - first % W, - first / W - ); - } - let _ = std::fs::remove_dir_all(&dir); - } diff --git a/crates/ec-av1/src/tool_cache.rs b/crates/ec-av1/src/tool_cache.rs deleted file mode 100644 index 7f99c52a..00000000 --- a/crates/ec-av1/src/tool_cache.rs +++ /dev/null @@ -1,326 +0,0 @@ -//! Content-addressed cache of external-tool results, for test builds only. -//! -//! The gates shell out to ffmpeg (lavfi source generation, y4m and raw -//! loaders), aomenc (encodes) and aomdec / ffmpeg (oracle decodes). Those -//! results are deterministic functions of the program, its arguments, its -//! explicit environment, its working directory, its stdin and the contents of -//! every input file, so a second run can reuse them. The decoder under test is -//! never routed through here: only the external tool's `Output` is cached. -//! -//! Shell scripts are never cached: they can read hidden inputs (the control -//! tests' ffmpeg/aomdec shims read a sibling file), which no key can cover. -//! -//! A call is cached only when every path-like argument already names an -//! existing file (its content is hashed into the key) or a `/dev/` node. Any -//! other path-like argument is an output the tool would write, which cannot be -//! snapshotted, so that call simply runs. Only successful runs are stored. -//! -//! Environment: `EC_TOOL_CACHE=0|off` disables the cache; `EC_TOOL_CACHE_DIR` -//! overrides the directory (default `$HOME/.cache/ec-tool-cache`). - -use std::ffi::OsStr; -use std::fs; -use std::io::{self, Read}; -use std::os::unix::ffi::OsStrExt; -use std::os::unix::process::ExitStatusExt; -use std::path::{Path, PathBuf}; -use std::process::{Command, ExitStatus, Output}; -use std::time::{SystemTime, UNIX_EPOCH}; - -/// Outputs larger than this are run every time instead of stored. -const CAP_BYTES: u64 = 256 << 20; -const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; -const BASIS_A: u64 = 0xcbf2_9ce4_8422_2325; -const BASIS_B: u64 = 0x8422_2325_cbf2_9ce4; - -/// Two independent 64-bit FNV-1a passes, giving a 128-bit key without deps. -struct Hash { - a: u64, - b: u64, -} - -impl Hash { - fn new() -> Self { - Hash { - a: BASIS_A, - b: BASIS_B, - } - } - - fn bytes(&mut self, data: &[u8]) { - for &x in data { - self.a = (self.a ^ u64::from(x)).wrapping_mul(FNV_PRIME); - self.b = (self.b ^ u64::from(x)).wrapping_mul(FNV_PRIME); - } - } - - /// A length-prefixed field, so adjacent fields cannot run together. - fn part(&mut self, data: &[u8]) { - self.bytes(&u64::try_from(data.len()).unwrap_or(u64::MAX).to_le_bytes()); - self.bytes(data); - } - - fn hex(&self) -> String { - format!("{:016x}{:016x}", self.a, self.b) - } -} - -/// The cache directory, or `None` when the cache is disabled. -fn env_dir() -> Option { - if matches!( - std::env::var("EC_TOOL_CACHE").as_deref(), - Ok("0" | "off") - ) { - return None; - } - if let Some(d) = std::env::var_os("EC_TOOL_CACHE_DIR") { - return Some(PathBuf::from(d)); - } - Some(PathBuf::from(std::env::var_os("HOME")?).join(".cache/ec-tool-cache")) -} - -/// Runs `cmd` through the cache (or straight through when disabled). `run` -/// performs the real spawn; it is called at most once. -/// -/// # Panics -/// Never from the cache itself; `run` is infallible here, so the internal -/// `io::Result` is always `Ok`. -pub(crate) fn cached_output( - cmd: &mut Command, - stdin: Option<&[u8]>, - run: impl FnOnce(&mut Command) -> Output, -) -> Output { - match cached_output_io(cmd, stdin, |c| Ok(run(c))) { - Ok(out) => out, - Err(e) => panic!("tool cache: infallible run failed: {e}"), - } -} - -/// [`cached_output`] for callers that handle the `io::Result` of `.output()`. -pub(crate) fn cached_output_io( - cmd: &mut Command, - stdin: Option<&[u8]>, - run: impl FnOnce(&mut Command) -> io::Result, -) -> io::Result { - match env_dir() { - None => run(cmd), - Some(dir) => cached_output_in(&dir, cmd, stdin, run), - } -} - -fn cached_output_in( - dir: &Path, - cmd: &mut Command, - stdin: Option<&[u8]>, - run: impl FnOnce(&mut Command) -> io::Result, -) -> io::Result { - let Some(key) = build_key(cmd, stdin) else { - return run(cmd); - }; - if let Some(hit) = load(dir, &key) { - return Ok(hit); - } - let out = run(cmd)?; - let size = u64::try_from(out.stdout.len()).unwrap_or(u64::MAX) - + u64::try_from(out.stderr.len()).unwrap_or(u64::MAX); - if out.status.success() && size <= CAP_BYTES { - // A failed store only costs the next run its cache hit. - let _ = store(dir, &key, &out); - } - Ok(out) -} - -/// Resolves `prog` to a canonical path, searching PATH for bare names. -fn resolve_program(prog: &OsStr) -> Option { - let p = Path::new(prog); - let found = if p.components().count() > 1 { - p.to_path_buf() - } else { - let path = std::env::var_os("PATH")?; - std::env::split_paths(&path) - .map(|d| d.join(prog)) - .find(|c| c.is_file())? - }; - fs::canonicalize(found).ok() -} - -/// A path-like argument: contains '/' and is not a `key:value` filter or a -/// string with spaces. Those are the arguments that could name an output. -fn path_like(c: &[u8]) -> bool { - c.contains(&b'/') && !c.contains(&b':') && !c.contains(&b' ') -} - -/// The argument itself and, for `--opt=path` / `key=path`, the part after the -/// first '='. -fn candidates(arg: &[u8]) -> [&[u8]; 2] { - let after = arg - .iter() - .position(|&b| b == b'=') - .map_or(&arg[0..0], |i| &arg[i + 1..]); - [arg, after] -} - -fn hash_file(h: &mut Hash, path: &Path) -> io::Result<()> { - let mut f = fs::File::open(path)?; - let len = f.metadata()?.len(); - h.bytes(b"file"); - h.bytes(&len.to_le_bytes()); - let mut buf = vec![0u8; 1 << 16]; - loop { - let n = f.read(&mut buf)?; - if n == 0 { - break; - } - h.bytes(&buf[..n]); - } - Ok(()) -} - -/// The key for this call, or `None` when the call must not be cached. -fn build_key(cmd: &Command, stdin: Option<&[u8]>) -> Option { - let prog = resolve_program(cmd.get_program())?; - let meta = fs::metadata(&prog).ok()?; - // A script can read state the key cannot see (the test shims read a - // sibling `offsets` file), so only real binaries are cached. - let mut magic = [0u8; 2]; - if fs::File::open(&prog).ok()?.read(&mut magic).ok()? == 2 && &magic == b"#!" { - return None; - } - let mtime = meta - .modified() - .ok()? - .duration_since(UNIX_EPOCH) - .ok()? - .as_nanos(); - - let mut h = Hash::new(); - h.part(b"ec-tool-cache/v1"); - h.part(prog.as_os_str().as_bytes()); - h.bytes(&meta.len().to_le_bytes()); - h.bytes(&mtime.to_le_bytes()); - - let args: Vec<&OsStr> = cmd.get_args().collect(); - h.part(&u64::try_from(args.len()).ok()?.to_le_bytes()); - for arg in &args { - h.part(arg.as_bytes()); - } - - // Relative paths resolve against the process cwd unless the command sets - // its own, so both are part of the identity. - h.part(std::env::current_dir().ok()?.as_os_str().as_bytes()); - match cmd.get_current_dir() { - Some(d) => { - h.bytes(b"\x01"); - h.part(d.as_os_str().as_bytes()); - } - None => h.bytes(b"\x00"), - } - for (k, v) in cmd.get_envs() { - h.part(k.as_bytes()); - match v { - Some(v) => { - h.bytes(b"\x01"); - h.part(v.as_bytes()); - } - None => h.bytes(b"\x00"), - } - } - - match stdin { - Some(data) => { - h.bytes(b"stdin\x01"); - h.part(data); - } - None => h.bytes(b"stdin\x00"), - } - - for arg in &args { - for cand in candidates(arg.as_bytes()) { - if cand.is_empty() { - continue; - } - let os = OsStr::from_bytes(cand); - let path = Path::new(os); - if path.is_file() { - hash_file(&mut h, path).ok()?; - } else if path_like(cand) && !path.exists() && !cand.starts_with(b"/dev/") { - return None; - } - } - } - Some(h.hex()) -} - -fn load(dir: &Path, key: &str) -> Option { - let code = fs::read_to_string(dir.join(format!("{key}.code"))).ok()?; - if code.trim() != "0" { - return None; - } - Some(Output { - status: ExitStatus::from_raw(0), - stdout: fs::read(dir.join(format!("{key}.out"))).ok()?, - stderr: fs::read(dir.join(format!("{key}.err"))).ok()?, - }) -} - -fn store(dir: &Path, key: &str, out: &Output) -> io::Result<()> { - fs::create_dir_all(dir)?; - let nanos = SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap_or_default() - .as_nanos(); - let nonce = format!("tmp.{}.{nanos}", std::process::id()); - let files: [(&str, &[u8]); 3] = [ - ("out", &out.stdout[..]), - ("err", &out.stderr[..]), - ("code", &b"0"[..]), - ]; - for (ext, bytes) in files { - let tmp = dir.join(format!("{key}.{nonce}.{ext}")); - fs::write(&tmp, bytes)?; - fs::rename(&tmp, dir.join(format!("{key}.{ext}")))?; - } - Ok(()) -} - -#[cfg(test)] -mod tests { - use super::*; - use std::cell::Cell; - - #[test] - fn second_call_replays_and_uncacheable_calls_always_run() { - let nanos = SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap_or_default() - .as_nanos(); - let dir = std::env::temp_dir().join(format!( - "ec-tool-cache-test-{}-{nanos}", - std::process::id() - )); - let sh = || { - let mut c = Command::new("sh"); - c.args(["-c", "echo $RANDOM$$"]); - c - }; - let first = cached_output_in(&dir, &mut sh(), None, |c| c.output()).unwrap(); - let second = cached_output_in(&dir, &mut sh(), None, |c| c.output()).unwrap(); - assert_eq!(first.stdout, second.stdout); - - // An output path that does not exist yet cannot be snapshotted, so - // both calls must reach the run closure. - let runs = Cell::new(0); - let missing = dir.join("no-such-dir/out.bin"); - for _ in 0..2 { - let mut c = Command::new("sh"); - c.args(["-c", "true"]).arg(&missing); - cached_output_in(&dir, &mut c, None, |c| { - runs.set(runs.get() + 1); - c.output() - }) - .unwrap(); - } - assert_eq!(runs.get(), 2); - let _ = fs::remove_dir_all(&dir); - } -} diff --git a/scripts/build-aom-affine-oracle.sh b/scripts/build-aom-affine-oracle.sh deleted file mode 100755 index 34effa76..00000000 --- a/scripts/build-aom-affine-oracle.sh +++ /dev/null @@ -1,48 +0,0 @@ -#!/usr/bin/env bash -# Provision an aomenc that can emit AFFINE global motion. -# -# Stock libaom NEVER writes a 6-parameter (AFFINE) global-motion model: its -# encoder-side model search is pinned to ROTZOOM, -# -# av1/encoder/global_motion_facade.c:24 -# #define FIRST_GLOBAL_TRANS_TYPE ROTZOOM -# #define LAST_GLOBAL_TRANS_TYPE ROTZOOM -# -# so no `--enable-global-motion=1` recipe over any content can produce the -# AFFINE case the decoder must still handle (the *bitstream* allows it, the -# spec's `global_motion_params` reads 6 params, and ffmpeg decodes it). This -# builds a side copy of the oracle source with that search range widened to -# AFFINE -- decode-normative output, still ordinary libaom, still verified -# against ffmpeg -- into its own prefix so the shared oracle at -# ~/.cache/aom-oracle (used by every other gate) is untouched. -# -# Used by the `a_real_affine_global_motion_stream_decodes_pixel_exact` gate in -# crates/ec-av1/src/stream.rs. -set -euo pipefail - -ROOT="${AOM_AFFINE_ROOT:-$HOME/.cache/aom-affine}" -ORACLE_SRC="${AOM_ORACLE_ROOT:-$HOME/.cache/aom-oracle}/src" -SRC="$ROOT/src" -BUILD="$ROOT/build" - -if [ ! -d "$ORACLE_SRC/.git" ]; then - echo "no oracle source at $ORACLE_SRC -- run scripts/build-aom-oracle.sh first" >&2 - exit 1 -fi - -if [ ! -d "$SRC" ]; then - mkdir -p "$ROOT" - cp -a "$ORACLE_SRC" "$SRC" -fi - -facade="$SRC/av1/encoder/global_motion_facade.c" -sed -i 's/^#define LAST_GLOBAL_TRANS_TYPE ROTZOOM$/#define LAST_GLOBAL_TRANS_TYPE AFFINE/' "$facade" -grep -q '^#define LAST_GLOBAL_TRANS_TYPE AFFINE$' "$facade" || - { echo "patch did not apply to $facade" >&2; exit 1; } - -cmake -S "$SRC" -B "$BUILD" -G Ninja \ - -DCMAKE_BUILD_TYPE=Release \ - -DENABLE_TESTS=0 -DENABLE_DOCS=0 -DENABLE_EXAMPLES=1 -ninja -C "$BUILD" aomenc - -echo "affine-capable encoder ready: $BUILD/aomenc" diff --git a/scripts/build-aom-oracle.sh b/scripts/build-aom-oracle.sh deleted file mode 100755 index f7f308c1..00000000 --- a/scripts/build-aom-oracle.sh +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/env bash -# Provision the libaom oracle the ec-av1 gates and every decode-verification -# claim depend on: the C source (read as ground truth) plus aomenc/aomdec. -# -# It lives under ~/.cache, NOT /tmp: on 2026-08-30 a tmpfs reclaim wiped -# /tmp/libaom-src and all 20 aomenc gates in crates/ec-av1/src/stream.rs -# started SKIPping, leaving a green-but-vacuous suite. Re-run this whenever -# `cargo test -p ec-av1` prints "SKIP ...: no aomenc at ...". -# -# Needs an assembler (nasm or yasm) for the SIMD build. Without one it falls -# back to AOM_TARGET_CPU=generic (C only) automatically -- decode is normative -# so aomdec stays bit-exact either way, but encode is slower, which matters -# because every gate shells out to aomenc 40 times. Install nasm for speed. -set -euo pipefail - -VERSION="${AOM_VERSION:-v3.13.3}" -ROOT="${AOM_ORACLE_ROOT:-$HOME/.cache/aom-oracle}" -SRC="$ROOT/src" -BUILD="$ROOT/build" - -if [ ! -d "$SRC/.git" ]; then - git clone --depth 1 --branch "$VERSION" https://aomedia.googlesource.com/aom "$SRC" -fi - -# A cmake build tree bakes in its own absolute path and its source's, so a -# build dir that was produced elsewhere and then moved cannot regenerate -# (`ninja: error: rebuilding build.ninja`) -- which silently costs you the -# ability to re-instrument aomdec later. Never stage a build under one name -# and rename it; configure it where it will live. If the cache disagrees with -# where we are now, drop it and reconfigure in place. -if [ -f "$BUILD/CMakeCache.txt" ] && - ! grep -q "^CMAKE_HOME_DIRECTORY:INTERNAL=$SRC$" "$BUILD/CMakeCache.txt"; then - echo "build tree was configured for a different path -- reconfiguring in place" >&2 - rm -f "$BUILD/CMakeCache.txt" - rm -rf "$BUILD/CMakeFiles" -fi - -CPU_ARGS=() -if [ -n "${AOM_TARGET_CPU:-}" ]; then - CPU_ARGS=(-DAOM_TARGET_CPU="$AOM_TARGET_CPU") -elif ! command -v nasm >/dev/null && ! command -v yasm >/dev/null; then - echo "no nasm/yasm found -- falling back to the C-only (generic) build" >&2 - CPU_ARGS=(-DAOM_TARGET_CPU=generic) -fi - -cmake -S "$SRC" -B "$BUILD" -G Ninja \ - -DCMAKE_BUILD_TYPE=Release \ - -DENABLE_TESTS=0 -DENABLE_DOCS=0 -DENABLE_EXAMPLES=1 \ - -DCONFIG_INSPECTION=1 \ - "${CPU_ARGS[@]}" -ninja -C "$BUILD" aomenc aomdec - -echo "oracle ready:" -echo " source $SRC" -echo " aomenc $BUILD/aomenc" -echo " aomdec $BUILD/aomdec" diff --git a/scripts/check-aom-oracle-rungs.sh b/scripts/check-aom-oracle-rungs.sh deleted file mode 100755 index e75653bd..00000000 --- a/scripts/check-aom-oracle-rungs.sh +++ /dev/null @@ -1,225 +0,0 @@ -#!/usr/bin/env bash -# Anti-regression check for the aomdec dump rungs that -# scripts/instrument-aom-oracle.sh derives. -# -# Why this exists: the four u8-narrowing rungs (PREFILT, POSTDEBLOCK, -# PREFILT_WIDE, POSTCDEF) shipped with `fwrite(plane + r*stride, 1, w, f)`, -# which on a 10/12-bit stream reads a HALVED plane pointer -# (CONVERT_TO_BYTEPTR in aom_ports/mem.h) and SIGSEGVs with a 0-byte file -# (lanes/av1oraclehbd.report.md). A rung defect that only shows up as an -# aomdec crash during a decode is found late; this reds on the DERIVATION -# instead, in seconds, without a build. -# -# The same class of loss applies to the prediction rungs: EC_PREDOUT8 (rung -# 16) and EC_PREDND (rung 17) lived only in the hand-patched oracle tree, so -# a rebuild from the script dropped the only probe that prints on a 10/12-bit -# stream (both, and the pre-existing EC_PREDOUT, sit after an `is_hbd` early -# return). Those are asserted here too, from a PRISTINE reconintra.c. -# -# What it does: copies the oracle source tree to a scratch dir, replaces -# av1/decoder/decodeframe.c and av1/common/reconintra.c with the PRISTINE -# upstream files, runs the instrument script over the copy, and asserts the -# derived files' shape. The real oracle tree is never written to. -# -# EXIT CONTRACT (lane-av1stagegaps). A staging driver must be able to tell the -# three states apart, because "checker passed", "checker failed" and "checker -# never ran" all printed as `rungs_exit=1` (or as nothing at all) and the suite -# ran anyway. Measured 2026-09-30 on host host-d: the driver log showed -# === ORACLE RUNG CHECKER -# rungs_exit=1 ok_count=0 <- no detail line at all -# === SUITE -# while the real reason, with stderr visible, was a missing PREREQUISITE: -# no oracle source at /home/user/.cache/aom-oracle/src/av1/decoder/decodeframe.c -# $ ls ~/.cache/aom-oracle/ -# build <- binaries only, no src/ tree -# 0 GREEN every assertion below held. -# 3 NOTRUN a PREREQUISITE is absent (no oracle source tree, or the base ref -# is not in it). Nothing was asserted: this is NOT a pass and NOT a -# defect. scripts/av1-suite-preflight.sh maps it to `not-run` and -# BLOCKS the suite unless a waiver names the host. -# 1 FAIL a derived file violates the rung contract, or the instrument -# script errored / was not idempotent. - -# -# Usage: -# scripts/check-aom-oracle-rungs.sh [SRC_DIR] [BASE_REF] -# Defaults: $AOM_ORACLE_SRC or ~/.cache/aom-oracle/src, and base ref v3.13.3 -# (override with AOM_ORACLE_BASE_REF). Exit 0 = all assertions hold. -set -euo pipefail - -SRC="${1:-${AOM_ORACLE_SRC:-$HOME/.cache/aom-oracle/src}}" -BASE="${2:-${AOM_ORACLE_BASE_REF:-v3.13.3}}" -HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -DERIVED="$SRC/av1/decoder/decodeframe.c" -RECONINTRA="$SRC/av1/common/reconintra.c" -die_prereq() { echo "PREREQ-ABSENT: $*" >&2; exit 3; } - - -[ -f "$DERIVED" ] || die_prereq "no oracle source at $DERIVED (provision it: git clone -b v3.13.3 --depth 1 aom at $SRC)" -[ -f "$RECONINTRA" ] || die_prereq "no oracle source at $RECONINTRA (provision it: git clone -b v3.13.3 --depth 1 aom at $SRC)" -git -C "$SRC" rev-parse --verify "$BASE^{commit}" >/dev/null 2>&1 || { - die_prereq "base ref '$BASE' is not a commit in $SRC" -} - -# systemd-run's --setenv=TMPDIR points at a per-suite dir; if staging created -# the unit but not the dir, mktemp fails with an error that reads like a -# checker bug. It is the same class as a missing oracle tree: not asserted. -probe="$(mktemp -d "${TMPDIR:-$HOME/.cache/tmp}/aom-rung-check.XXXXXX" 2>/dev/null)" || - die_prereq "scratch dir ${TMPDIR:-$HOME/.cache/tmp} does not exist (staging must mkdir it)" -rmdir "$probe" -WORK="$(mktemp -d "${TMPDIR:-$HOME/.cache/tmp}/aom-rung-check.XXXXXX")" -trap 'rm -rf "$WORK"' EXIT -cp -a "$SRC" "$WORK/src" -git -C "$SRC" show "$BASE:av1/decoder/decodeframe.c" > "$WORK/src/av1/decoder/decodeframe.c" -git -C "$SRC" show "$BASE:av1/common/reconintra.c" > "$WORK/src/av1/common/reconintra.c" - -AOM_ORACLE_SRC="$WORK/src" bash "$HERE/instrument-aom-oracle.sh" > "$WORK/derive.log" 2>&1 || { - echo "FAIL: instrument-aom-oracle.sh errored on a pristine tree:" >&2 - tail -20 "$WORK/derive.log" >&2 - exit 1 -} -cp "$WORK/src/av1/decoder/decodeframe.c" "$WORK/derived.c" -cp "$WORK/src/av1/common/reconintra.c" "$WORK/derived-intra.c" - -# Re-running must be a no-op, or the repair pass is not idempotent and a -# second run would rewrite a tree under someone's feet. -AOM_ORACLE_SRC="$WORK/src" bash "$HERE/instrument-aom-oracle.sh" > "$WORK/rerun.log" 2>&1 -cmp -s "$WORK/derived.c" "$WORK/src/av1/decoder/decodeframe.c" || { - echo "FAIL: a second instrument-aom-oracle.sh run changed the derived file" >&2 - exit 1 -} -cmp -s "$WORK/derived-intra.c" "$WORK/src/av1/common/reconintra.c" || { - echo "FAIL: a second instrument-aom-oracle.sh run changed reconintra.c" >&2 - exit 1 -} - -fail=0 -check() { # description, actual, expected - if [ "$2" = "$3" ]; then - printf 'ok %-58s %s\n' "$1" "$2" - else - printf 'FAIL %-58s got %s, want %s\n' "$1" "$2" "$3" >&2 - fail=1 - fi -} - -legacy=$(grep -c 'fwrite(ec_b->[yuv]_buffer + ec_r \* ec_b->' "$WORK/derived.c" || true) -check "legacy u8 row loops left in the derived file" "$legacy" "0" - -rows=$(grep -c 'ec_dump_narrow_row(ec_f, ec_b, ec_b->[yuv]_buffer' "$WORK/derived.c" || true) -check "ec_dump_narrow_row call sites (4 rungs x 3 planes)" "$rows" "12" - -fin=$(grep -c 'ec_dump_finish(ec_f, "EC_AV1_' "$WORK/derived.c" || true) -check "ec_dump_finish call sites (one per narrowing rung)" "$fin" "4" - -for rung in EC_AV1_PREFILT_DUMP EC_AV1_POSTDEBLOCK_DUMP EC_AV1_PREFILT_WIDE_DUMP \ - EC_AV1_POSTCDEF_DUMP; do - n=$(grep -c "ec_dump_finish(ec_f, \"$rung\"" "$WORK/derived.c" || true) - check "byte-count check wired into $rung" "$n" "1" -done - -# Rung 12 (EC_AV1_FINAL_DUMP) is the depth-correct one and must stay that way: -# it converts, it writes 2 bytes per sample, and it is not routed through the -# narrowing checker. -conv=$(grep -c 'CONVERT_TO_SHORTPTR(ec_p8\[ec_pl\])' "$WORK/derived.c" || true) -check "rung 12 still converts plane pointers" "$conv" "1" -r12=$(grep -c 'ec_dump_finish(ec_f, "EC_AV1_FINAL_DUMP"' "$WORK/derived.c" || true) -check "rung 12 not routed through the narrowing checker" "$r12" "0" - -# --- rungs 16/17: the prediction rungs (lane-av1rungs17) -------------------- -# EC_PREDOUT8 must be installed at BOTH 8-bit prediction sites in -# reconintra.c -- the non-directional early return (DC, SMOOTH*, PAETH) and -# the directional / filter-intra tail. A one-site install would look fine on -# the directional arm and print nothing at all for every non-directional -# block, which is most of an intra frame. -p8=$(grep -c 'EC_PREDOUT8 mi_row=%d' "$WORK/derived-intra.c" || true) -check "rung 16 EC_PREDOUT8 install sites (both 8-bit paths)" "$p8" "2" - -# `mode=` is what makes a non-directional diff attributable at all; a rebuild -# that lost it would still install two sites and still pass the count above. -p8m=$(grep -c 'EC_PREDOUT8 mi_row=%d.*txh=%d mode=%d sum=%ld' "$WORK/derived-intra.c" || true) -check "rung 16 EC_PREDOUT8 sites carry mode= (EC_PREDND field order)" "$p8m" "2" - -# EC_PREDND is the hbd twin and the ONLY prediction probe that fires on a -# 10/12-bit stream. One site, at the non-directional early return. -pnd=$(grep -c 'EC_PREDND mi_row=%d' "$WORK/derived-intra.c" || true) -check "rung 17 EC_PREDND install sites (hbd non-directional)" "$pnd" "1" -pndm=$(grep -c 'txw=%d txh=%d mode=%d n_top=%d n_left=%d' "$WORK/derived-intra.c" || true) -check "rung 17 EC_PREDND site carries mode=" "$pndm" "1" - -# --- rungs 19/20: the intra-prediction IDENTITY + DC INPUTS rungs --------- -# EC_PREDOUT8/EC_PREDND print only SOME of the writes inside -# `av1_predict_intra_block`: the palette branch returns before either, and so -# do the two non-directional early returns' opposite number. A chroma region -# where no rung fires was therefore un-attributable -- three lanes of 4:2:2 -# work stalled on exactly that (lanes/av1422ctrigger §5b). EC_PIB prints the -# CALL IDENTITY before any early return, so "did a call happen and did it -# return early" is readable from the trace. -pib=$(grep -c 'EC_PIB mi_row=%d mi_col=%d plane=%d row_off=%d col_off=%d' "$WORK/derived-intra.c" || true) -check "rung 19 EC_PIB install sites (av1_predict_intra_block prologue)" "$pib" "1" - -pibb=$(grep -c 'txw=%d txh=%d mode=%d use_palette=%d' "$WORK/derived-intra.c" || true) -check "rung 19 EC_PIB carries use_palette= (the early-return bit)" "$pibb" "1" - -# EC_DCIN is what makes the DC VARIANT a printed field instead of an -# inference from the predicted value: four lanes read "libaom used dc_top" -# out of the number 202 without the availability operands being visible. -dcin=$(grep -c 'EC_DCIN mi_row=%d mi_col=%d plane=%d row_off=%d col_off=%d' "$WORK/derived-intra.c" || true) -check "rung 20 EC_DCIN install sites (8-bit + hbd non-directional)" "$dcin" "2" - -dcina=$(grep -c 'n_left=%d atop=%ld aleft=%ld dcv=%d up=%d left=%d cup=%d' "$WORK/derived-intra.c" || true) -check "rung 20 EC_DCIN prints availability operands + dcv + availability bits" "$dcina" "2" - -# --- rung 21: EC_DP, the branch decode_token_recon_block takes -------------- -# The inter arm (`predict_inter_block_visit`) prints NO intra rung, and the -# intra arm itself skips chroma on `!xd->is_chroma_ref`, so a block that -# emits no prediction rung is consistent with three different writers. -# EC_DP is what separates them -- it is how the INTRABC writer at the 4:2:2 -# seed was named (lanes/av1422ctattr §4). -dp=$(grep -c 'EC_DP mi_row=%d mi_col=%d bsize=%d inter=%d chroma_ref=%d' "$WORK/derived.c" || true) -check "rung 21 EC_DP install sites (decode_token_recon_block)" "$dp" "1" - -dpa=$(grep -c 'skip_txfm=%d bw=%d bh=%d planes=%d is_intrabc=%d' "$WORK/derived.c" || true) -check "rung 21 EC_DP carries is_intrabc= (the intra/inter branch bit)" "$dpa" "1" - -# Rung 16 claims to be idempotent in BOTH directions: an install on a -# pristine file, AND an upgrade of the no-`mode=` form the oracle tree's git -# HEAD carries. Rebuild the no-mode form, re-derive, and require the result to -# land back on the same bytes -- an upgrade path that silently no-ops (or -# double-writes) is exactly what a rebuild would hit. -python3 - "$WORK/derived-intra.c" "$WORK/nomode-intra.c" <<'PYUP' -import sys -s = open(sys.argv[1]).read() -# Strip `mode=` from the format string and `mode` from the argument list at -# both EC_PREDOUT8 sites only; EC_PREDND's own mode= must survive untouched. -for fmt_old, fmt_new in ( - ('txw=%d txh=%d mode=%d sum=%ld row0=", xd->mi_row', - 'txw=%d txh=%d sum=%ld row0=", xd->mi_row'), - ('txw=%d txh=%d mode=%d sum=%ld row0=", mi_row', - 'txw=%d txh=%d sum=%ld row0=", mi_row'), -): - assert fmt_old in s, "upgrade fixture: %r not found" % fmt_old - s = s.replace(fmt_old, fmt_new, 1) -assert s.count('col_off, txwpx, txhpx, mode, ec_sum);') == 2, "upgrade fixture: args" -s = s.replace('col_off, txwpx, txhpx, mode, ec_sum);', - 'col_off, txwpx, txhpx, ec_sum);') -assert 'EC_PREDOUT8 mi_row=%d' in s and s.count('txw=%d txh=%d sum=%ld row0=') == 2 -open(sys.argv[2], 'w').write(s) -PYUP -cp "$WORK/nomode-intra.c" "$WORK/src/av1/common/reconintra.c" -AOM_ORACLE_SRC="$WORK/src" bash "$HERE/instrument-aom-oracle.sh" > "$WORK/upgrade.log" 2>&1 || { - echo "FAIL: instrument-aom-oracle.sh errored on the no-mode reconintra.c:" >&2 - tail -20 "$WORK/upgrade.log" >&2 - exit 1 -} -cmp -s "$WORK/derived-intra.c" "$WORK/src/av1/common/reconintra.c" || { - echo "FAIL: re-deriving the no-mode EC_PREDOUT8 form did not land back on the derived bytes" >&2 - diff -u "$WORK/derived-intra.c" "$WORK/src/av1/common/reconintra.c" | head -30 >&2 - exit 1 -} - -if [ "$fail" -ne 0 ]; then - echo "FAIL: a derived file violates the rung contract (base $BASE)" >&2 - exit 1 -fi -echo "ok instrument-aom-oracle.sh derives the depth-correct, byte-checked rungs (base $BASE)" diff --git a/scripts/instrument-aom-oracle.sh b/scripts/instrument-aom-oracle.sh deleted file mode 100755 index 2004b043..00000000 --- a/scripts/instrument-aom-oracle.sh +++ /dev/null @@ -1,1528 +0,0 @@ -#!/usr/bin/env bash -# Add the decode-localization instrumentation to the libaom oracle's aomdec. -# -# These patches used to live only in the hand-built /tmp tree; the 2026-08-30 -# tmpfs reclaim destroyed them along with the tree (see memory -# oracle-in-reaped-dir). They are re-derived here so `build-aom-oracle.sh` + -# this script reproduce the full ladder from scratch. -# -# Rungs provided (both env-gated, so an uninstrumented run is unchanged): -# DEPTH TRAP (lane-av1oraclerungdepth): the DUMP rungs 1 / 6 / 7 / 15 write -# 1 byte per sample with no YV12_FLAG_HIGHBITDEPTH check (they are paired -# with decoder-side dumps that narrow to u8 on purpose). On a 10/12-bit -# stream they crash the oracle, or where they survive produce a file of -# EXACTLY HALF w*h*bps -- which looks like a truncated decode but is the -# rung's depth assumption. Each of those four carries a -# `DEPTH ASSUMPTION` block naming its decoder-side pair; rung 12 -# (EC_AV1_FINAL_DUMP) is the depth-correct one. -# EC_AV1_PREFILT_DUMP= -> .f per frame, Y then U then V, -# crop-sized rows, written after tile decode and BEFORE any loop filter, -# CDEF or LR. Diff against our own EC_AV1_PREFILT_DUMP to separate a -# reconstruction mismatch from a filtering one. -# EC_TRACE=1 -> "EC_PART mi_row=.. mi_col=.. bsize=.. ctx=.. tell=.. rng=.." -# before every partition symbol, "EC_PART_VAL .. value=.." after. The -# range ladder: compare rng element-by-element against our own -# `TRACE part32_pre` (class compare-range-not-tell -- ranges, never tell). -# EC_TRACE_COEFF=1 -> "EC_COEFF plane=.. row=.. col=.. tx_size=.. rng=.." -# before every coefficient block, "EC_COEFF_VAL .. rng=.." after. -# Partition granularity is too coarse to localize a coefficient desync; -# two lanes stalled on 2026-08-30 because this rung did not exist. -# EC_TRACE_MODE=1 -> "EC_MODE mi_row=.. mi_col=.. rng=.." before every inter -# block's mode info, "EC_MODE_VAL .. mode=.. ref0/1=.. mv0=.. rng=.." -# (rung 13 adds "stack=" to that line and an "EC_MODE_MV" line right -# after assign_mv) -# after -- the mv-stack/DRL/mv reads EC_PART cannot see. The same flag -# also emits "EC_IMODE .. rng=.." / "EC_IMODE_VAL .. mode=.. uv_mode=.. -# skip=.. tx=.. rng=.." around every INTRA key-frame block: without it -# the key-frame path has no traced symbol at all between the partition -# read and the first coefficient block, which is precisely the gap a -# rect-strip desync hides in. -# EC_AV1_POSTDEBLOCK_DUMP= -> .f per frame, Y then U then -# V, full ALIGNED-buffer rows (y_width/y_height, not y_crop_width -- -# cm->cur_frame->buf at this point is still the pre-superres buffer, -# but its aligned width already extends past FrameWidth out to the -# mi-aligned true width, which is exactly the margin content we need). -# Written right after av1_loop_filter_frame_mt returns and before -# CDEF/superres run -- ground truth for the post-deblock, pre-superres -# row content over frame_width..true_width that decode.rs stashes as -# its superres margin (lane-superres r5: hand-tracing the arithmetic -# could only prove our own self-consistency, not correctness against -# libaom). -# EC_AV1_POSTCDEF_DUMP= -> .f per frame, same shape as -# the POSTDEBLOCK rung (full ALIGNED-buffer rows), written right after -# the CDEF pass and before superres/LR -- splits a final-output -# mismatch into "already in CDEF" vs "introduced by loop restoration" -# without the 16-bit-only DUMP16 rungs (lane-av1422filter: on the -# pinned 4:2:2 keyframe this named the 251/259-sample CDEF chroma -# defect whose first samples were the ticket's first final samples). -# EC_TRACE_MODE_STEP=1 -> per-symbol range ladder inside -# ec_read_intra_frame_mode_info_impl (rung 5's renamed body): -# "EC_ISTEP mi_row=.. mi_col=.. name=skip val=.. rng=.." after -# read_skip_txfm, name=cdef/dq after read_cdef/read_delta_q_params, -# name=mode after mbmi->mode, name=angle_y after the Y angle_delta read, -# name=uv_mode after mbmi->uv_mode, name=angle_uv after the UV -# angle_delta read (rung 10, lane-sbpart r6). EC_TRACE_MODE's own -# before/after prints only bracket the WHOLE block; this is the -# per-symbol ladder the charter asked for to localize block2's first -# wrong read. -# Rung 9 (unconditional, no env gate) -- SGR per-tap ground truth -# (lane-lr r7): `calculate_intermediate_result` in -# av1/common/restoration.c is `static`, so a standalone harness cannot -# call it to get real A[]/B[] intermediate arrays, only the final -# flt0/flt1 via the public av1_selfguided_restoration_c. This rung -# drops `static` so an external harness can call it directly with a -# `dgd32`-style buffer (see scripts/lr-sgr-pin-harness.c) and diff -# every A[k]/B[k] tap against a from-scratch recompute -- the missing -# half of r6's 9-tap cross-check. No behaviour change (only linkage). -# -# Idempotent: re-running is a no-op. Rebuild afterwards with -# ninja -C ~/.cache/aom-oracle/build aomdec -set -euo pipefail -SRC="${AOM_ORACLE_SRC:-$HOME/.cache/aom-oracle/src}" -F="$SRC/av1/decoder/decodeframe.c" -[ -f "$F" ] || { echo "no oracle source at $F -- run scripts/build-aom-oracle.sh first" >&2; exit 1; } - -python3 - "$F" <<'PY' -import sys, re -path = sys.argv[1] -s = open(path).read() -if "EC_INSTRUMENTED" in s: - print("already instrumented (no-op)") - sys.exit(0) - -# --- rung 2: partition range ladder ------------------------------------- -old_sig = """static PARTITION_TYPE read_partition(MACROBLOCKD *xd, int mi_row, int mi_col, - aom_reader *r, int has_rows, int has_cols, - BLOCK_SIZE bsize) {""" -new_sig = """/* EC_INSTRUMENTED */ -static PARTITION_TYPE ec_read_partition_impl(MACROBLOCKD *xd, int mi_row, - int mi_col, aom_reader *r, - int has_rows, int has_cols, - BLOCK_SIZE bsize); - -static PARTITION_TYPE read_partition(MACROBLOCKD *xd, int mi_row, int mi_col, - aom_reader *r, int has_rows, int has_cols, - BLOCK_SIZE bsize) { - const int ec_trace = getenv("EC_TRACE") != NULL; - if (ec_trace) { - fprintf(stderr, - "EC_PART mi_row=%d mi_col=%d bsize=%d ctx=%d tell=%d rng=%u\\n", - mi_row, mi_col, (int)bsize, - partition_plane_context(xd, mi_row, mi_col, bsize), - (int)aom_reader_tell(r), (unsigned)r->ec.rng); - } - PARTITION_TYPE ec_p = - ec_read_partition_impl(xd, mi_row, mi_col, r, has_rows, has_cols, bsize); - if (ec_trace) { - fprintf(stderr, "EC_PART_VAL mi_row=%d mi_col=%d bsize=%d value=%d\\n", - mi_row, mi_col, (int)bsize, (int)ec_p); - } - return ec_p; -} - -static PARTITION_TYPE ec_read_partition_impl(MACROBLOCKD *xd, int mi_row, - int mi_col, aom_reader *r, - int has_rows, int has_cols, - BLOCK_SIZE bsize) {""" -assert old_sig in s, "read_partition signature moved" -s = s.replace(old_sig, new_sig, 1) - -# --- rung 1: pre-filter recon dump -------------------------------------- -# DEPTH ASSUMPTION (lane-av1oraclerungdepth): this rung writes 1 byte per -# sample and has NO YV12_FLAG_HIGHBITDEPTH check. That is deliberate -- it is -# byte-paired with our own EC_AV1_PREFILT_DUMP, which narrows 10/12-bit to u8 -# on purpose (decode.rs:20048-20054, `p.data.iter().map(|&s| s as u8)` in -# `dump_stage`). -# TRAP: on an HBD stream the file is EXACTLY HALF w*h*2 = w*h bytes, which -# reads like a truncated/short decode, not a decoder bug. For HBD use rung 12 -# EC_AV1_FINAL_DUMP (:730) -- it IS depth-correct (u8 / u16 LE). -# OBSERVED 2026-09-29 on the HBD oracle build (CONFIG_AV1_HIGHBITDEPTH=1) with -# the committed `av112bit-key.obu` (160x128 4:2:0 12-bit = 30720 samples): -# rung 12 wrote 61440 B (w*h*bps) and this rung's 1-byte fwrite SIGSEGVs inside -# fwrite (exit 139, 0-byte file); the bytes it would have written are 30720 B -# = exactly half. Either way this is the RUNG's depth assumption, not a decoder -# defect -- never read a half-length/empty file here as a truncated decode. -anchor = """ av1_alloc_cdef_buffers(cm, &pbi->cdef_worker, &pbi->cdef_sync, - pbi->num_workers, 1);""" -dump = """ { - const char *ec_dump = getenv("EC_AV1_PREFILT_DUMP"); - if (ec_dump) { - static int ec_prefilt_idx = 0; - char ec_path[1024]; - snprintf(ec_path, sizeof(ec_path), "%s.f%d", ec_dump, ec_prefilt_idx++); - FILE *ec_f = fopen(ec_path, "wb"); - if (ec_f) { - const YV12_BUFFER_CONFIG *ec_b = &cm->cur_frame->buf; - for (int ec_r = 0; ec_r < ec_b->y_crop_height; ++ec_r) - fwrite(ec_b->y_buffer + ec_r * ec_b->y_stride, 1, ec_b->y_crop_width, - ec_f); - if (num_planes > 1) { - for (int ec_r = 0; ec_r < ec_b->uv_crop_height; ++ec_r) - fwrite(ec_b->u_buffer + ec_r * ec_b->uv_stride, 1, - ec_b->uv_crop_width, ec_f); - for (int ec_r = 0; ec_r < ec_b->uv_crop_height; ++ec_r) - fwrite(ec_b->v_buffer + ec_r * ec_b->uv_stride, 1, - ec_b->uv_crop_width, ec_f); - } - fclose(ec_f); - } - } - } - -""" -assert anchor in s, "cdef alloc anchor moved" -s = s.replace(anchor, dump + anchor, 1) -open(path, "w").write(s) -print("instrumented") -PY -echo "now: ninja -C ${AOM_ORACLE_BUILD:-$HOME/.cache/aom-oracle/build} aomdec" - -# --- rung 3: coefficient range ladder (decodetxb.c) --------------------- -G="$SRC/av1/decoder/decodetxb.c" -[ -f "$G" ] || { echo "no oracle source at $G" >&2; exit 1; } - -python3 - "$G" <<'PYC' -import sys -path = sys.argv[1] -s = open(path).read() -if "EC_INSTRUMENTED" in s: - print("decodetxb already instrumented (no-op)") - sys.exit(0) - -old = """void av1_read_coeffs_txb(const AV1_COMMON *const cm, DecoderCodingBlock *dcb, - aom_reader *const r, const int plane, const int row, - const int col, const TX_SIZE tx_size) {""" -new = """/* EC_INSTRUMENTED */ -static void ec_read_coeffs_txb_impl(const AV1_COMMON *const cm, - DecoderCodingBlock *dcb, - aom_reader *const r, const int plane, - const int row, const int col, - const TX_SIZE tx_size); - -void av1_read_coeffs_txb(const AV1_COMMON *const cm, DecoderCodingBlock *dcb, - aom_reader *const r, const int plane, const int row, - const int col, const TX_SIZE tx_size) { - const int ec_trace = getenv("EC_TRACE_COEFF") != NULL; - if (ec_trace) { - fprintf(stderr, "EC_COEFF plane=%d row=%d col=%d tx_size=%d rng=%u\\n", - plane, row, col, (int)tx_size, (unsigned)r->ec.rng); - } - ec_read_coeffs_txb_impl(cm, dcb, r, plane, row, col, tx_size); - if (ec_trace) { - fprintf(stderr, "EC_COEFF_VAL plane=%d row=%d col=%d rng=%u\\n", plane, row, - col, (unsigned)r->ec.rng); - } -} - -static void ec_read_coeffs_txb_impl(const AV1_COMMON *const cm, - DecoderCodingBlock *dcb, - aom_reader *const r, const int plane, - const int row, const int col, - const TX_SIZE tx_size) {""" -assert old in s, "av1_read_coeffs_txb signature moved" -s = s.replace(old, new, 1) -open(path, "w").write(s) -print("decodetxb instrumented") -PYC - -# --- rung 4: mode-info range ladder (decodemv.c) ------------------------ -H="$SRC/av1/decoder/decodemv.c" -[ -f "$H" ] || { echo "no oracle source at $H" >&2; exit 1; } - -python3 - "$H" <<'PYM' -import sys -path = sys.argv[1] -s = open(path).read() -if "EC_INSTRUMENTED" in s: - print("decodemv already instrumented (no-op)") - sys.exit(0) - -old = """static void read_inter_block_mode_info(AV1Decoder *const pbi, - DecoderCodingBlock *dcb, - MB_MODE_INFO *const mbmi, - aom_reader *r) {""" -new = """/* EC_INSTRUMENTED */ -static void ec_read_inter_block_mode_info_impl(AV1Decoder *const pbi, - DecoderCodingBlock *dcb, - MB_MODE_INFO *const mbmi, - aom_reader *r); - -static void read_inter_block_mode_info(AV1Decoder *const pbi, - DecoderCodingBlock *dcb, - MB_MODE_INFO *const mbmi, - aom_reader *r) { - const int ec_trace = getenv("EC_TRACE_MODE") != NULL; - const MACROBLOCKD *const ec_xd = &dcb->xd; - if (ec_trace) { - fprintf(stderr, "EC_MODE mi_row=%d mi_col=%d rng=%u\\n", ec_xd->mi_row, - ec_xd->mi_col, (unsigned)r->ec.rng); - } - ec_read_inter_block_mode_info_impl(pbi, dcb, mbmi, r); - if (ec_trace) { - fprintf(stderr, - "EC_MODE_VAL mi_row=%d mi_col=%d mode=%d ref0=%d ref1=%d " - "mv0=(%d,%d) rng=%u\\n", - ec_xd->mi_row, ec_xd->mi_col, (int)mbmi->mode, - (int)mbmi->ref_frame[0], (int)mbmi->ref_frame[1], - mbmi->mv[0].as_mv.row, mbmi->mv[0].as_mv.col, - (unsigned)r->ec.rng); - } -} - -static void ec_read_inter_block_mode_info_impl(AV1Decoder *const pbi, - DecoderCodingBlock *dcb, - MB_MODE_INFO *const mbmi, - aom_reader *r) {""" -assert old in s, "read_inter_block_mode_info signature moved" -s = s.replace(old, new, 1) -open(path, "w").write(s) -print("decodemv instrumented") -PYM - -# --- rung 5: intra key-frame mode-info ladder (decodemv.c) -------------- -python3 - "$SRC/av1/decoder/decodemv.c" <<'PYI' -import sys -path = sys.argv[1] -s = open(path).read() -if "EC_INSTRUMENTED_INTRA" in s: - print("intra mode-info already instrumented (no-op)") - sys.exit(0) - -old = """static void read_intra_frame_mode_info(AV1_COMMON *const cm, - DecoderCodingBlock *dcb, aom_reader *r) {""" -new = """/* EC_INSTRUMENTED_INTRA */ -static void ec_read_intra_frame_mode_info_impl(AV1_COMMON *const cm, - DecoderCodingBlock *dcb, - aom_reader *r); - -static void read_intra_frame_mode_info(AV1_COMMON *const cm, - DecoderCodingBlock *dcb, aom_reader *r) { - const int ec_trace = getenv("EC_TRACE_MODE") != NULL; - const MACROBLOCKD *const ec_xd = &dcb->xd; - if (ec_trace) { - fprintf(stderr, "EC_IMODE mi_row=%d mi_col=%d bsize=%d rng=%u\\n", - ec_xd->mi_row, ec_xd->mi_col, (int)ec_xd->mi[0]->bsize, - (unsigned)r->ec.rng); - } - ec_read_intra_frame_mode_info_impl(cm, dcb, r); - if (ec_trace) { - const MB_MODE_INFO *const ec_mbmi = ec_xd->mi[0]; - fprintf(stderr, - "EC_IMODE_VAL mi_row=%d mi_col=%d mode=%d uv_mode=%d skip=%d " - "tx=%d rng=%u\\n", - ec_xd->mi_row, ec_xd->mi_col, (int)ec_mbmi->mode, - (int)ec_mbmi->uv_mode, (int)ec_mbmi->skip_txfm, - (int)ec_mbmi->tx_size, (unsigned)r->ec.rng); - } -} - -static void ec_read_intra_frame_mode_info_impl(AV1_COMMON *const cm, - DecoderCodingBlock *dcb, - aom_reader *r) {""" -assert old in s, "read_intra_frame_mode_info signature moved" -s = s.replace(old, new, 1) -open(path, "w").write(s) -print("intra mode-info instrumented") -PYI - -# --- rung 6: post-deblock, pre-superres row dump ------------------------ -# DEPTH ASSUMPTION (lane-av1oraclerungdepth): 1 byte per sample, NO -# YV12_FLAG_HIGHBITDEPTH check. Deliberate -- byte-paired with our -# EC_AV1_POSTDEBLOCK_DUMP, which narrows to u8 (decode.rs:20048-20054, -# `dump_stage(..., &y, &u, &v)` over the u16 planes; same closure at :53489). -# TRAP: on an HBD stream the file is EXACTLY HALF w*h*2, which reads like a -# truncated/short decode, not a decoder bug. For HBD use rung 12 -# EC_AV1_FINAL_DUMP (:730) -- depth-correct (u8 / u16 LE). -# OBSERVED 2026-09-29 (HBD build, av112bit-key.obu): the 1-byte fwrite SIGSEGVs -# (exit 139); where it survives it writes 30720 B where 61440 B is expected -- -# exactly half. That is this rung, not a truncated decode. -python3 - "$F" <<'PYD' -import sys -path = sys.argv[1] -s = open(path).read() -if "EC_INSTRUMENTED_POSTDEBLOCK" in s: - print("postdeblock dump already instrumented (no-op)") - sys.exit(0) - -anchor = """ if (cm->lf.filter_level[0] || cm->lf.filter_level[1]) { - av1_loop_filter_frame_mt(&cm->cur_frame->buf, cm, &pbi->dcb.xd, 0, - num_planes, 0, pbi->tile_workers, - pbi->num_workers, &pbi->lf_row_sync, 0); - } -""" -dump = """ - /* EC_INSTRUMENTED_POSTDEBLOCK */ - { - const char *ec_dump = getenv("EC_AV1_POSTDEBLOCK_DUMP"); - if (ec_dump) { - static int ec_postdeblock_idx = 0; - char ec_path[1024]; - snprintf(ec_path, sizeof(ec_path), "%s.f%d", ec_dump, - ec_postdeblock_idx++); - FILE *ec_f = fopen(ec_path, "wb"); - if (ec_f) { - const YV12_BUFFER_CONFIG *ec_b = &cm->cur_frame->buf; - /* Dump the FULL aligned buffer (y_width/y_height), not the - * crop_width/crop_height (== FrameWidth/FrameHeight): the - * superres margin (columns [FrameWidth, true mi-aligned width)) - * only exists in the aligned buffer -- lane-superres r5. */ - for (int ec_r = 0; ec_r < ec_b->y_height; ++ec_r) - fwrite(ec_b->y_buffer + ec_r * ec_b->y_stride, 1, ec_b->y_width, - ec_f); - if (num_planes > 1) { - for (int ec_r = 0; ec_r < ec_b->uv_height; ++ec_r) - fwrite(ec_b->u_buffer + ec_r * ec_b->uv_stride, 1, - ec_b->uv_width, ec_f); - for (int ec_r = 0; ec_r < ec_b->uv_height; ++ec_r) - fwrite(ec_b->v_buffer + ec_r * ec_b->uv_stride, 1, - ec_b->uv_width, ec_f); - } - fclose(ec_f); - } - } - } -""" -assert anchor in s, "loop filter call anchor moved" -s = s.replace(anchor, anchor + dump, 1) -open(path, "w").write(s) -print("postdeblock dump instrumented") -PYD - -# --- rung 7: pre-deblock, FULL aligned-buffer row dump (lane-superres r5) - -# EC_AV1_PREFILT_DUMP (rung 1) is used by other lanes at its existing -# y_crop_width/y_crop_height shape -- left untouched. This adds a second, -# additive env var at the SAME anchor (pre-loop-filter) but dumping the full -# y_width/y_height aligned buffer, so a margin-region reconstruction bug can -# be told apart from a margin-region deblock bug. -# DEPTH ASSUMPTION (lane-av1oraclerungdepth): 1 byte per sample, NO -# YV12_FLAG_HIGHBITDEPTH check. Deliberate -- byte-paired with our -# EC_AV1_PREFILT_WIDE_DUMP, which narrows to u8 (decode.rs:20078-20090, -# `dump_prefilter_wide`; same closure at :53489). TRAP: on an HBD -# stream the file is EXACTLY HALF w*h*2, which reads like a truncated/short -# decode, not a decoder bug. For HBD use rung 12 EC_AV1_FINAL_DUMP (:730) -- -# depth-correct (u8 / u16 LE). -# OBSERVED 2026-09-29 (HBD build, av112bit-key.obu): the 1-byte fwrite SIGSEGVs -# (exit 139); where it survives it writes 30720 B where 61440 B is expected -- -# exactly half. That is this rung, not a truncated decode. -python3 - "$F" <<'PYW' -import sys -path = sys.argv[1] -s = open(path).read() -if "EC_INSTRUMENTED_PREFILT_WIDE" in s: - print("prefilt-wide dump already instrumented (no-op)") - sys.exit(0) - -anchor = """ av1_alloc_cdef_buffers(cm, &pbi->cdef_worker, &pbi->cdef_sync, - pbi->num_workers, 1);""" -dump = """ /* EC_INSTRUMENTED_PREFILT_WIDE */ - { - const char *ec_dump = getenv("EC_AV1_PREFILT_WIDE_DUMP"); - if (ec_dump) { - static int ec_prefilt_wide_idx = 0; - char ec_path[1024]; - snprintf(ec_path, sizeof(ec_path), "%s.f%d", ec_dump, - ec_prefilt_wide_idx++); - FILE *ec_f = fopen(ec_path, "wb"); - if (ec_f) { - const YV12_BUFFER_CONFIG *ec_b = &cm->cur_frame->buf; - for (int ec_r = 0; ec_r < ec_b->y_height; ++ec_r) - fwrite(ec_b->y_buffer + ec_r * ec_b->y_stride, 1, ec_b->y_width, - ec_f); - if (num_planes > 1) { - for (int ec_r = 0; ec_r < ec_b->uv_height; ++ec_r) - fwrite(ec_b->u_buffer + ec_r * ec_b->uv_stride, 1, - ec_b->uv_width, ec_f); - for (int ec_r = 0; ec_r < ec_b->uv_height; ++ec_r) - fwrite(ec_b->v_buffer + ec_r * ec_b->uv_stride, 1, - ec_b->uv_width, ec_f); - } - fclose(ec_f); - } - } - } - -""" -assert anchor in s, "cdef alloc anchor moved" -s = s.replace(anchor, dump + anchor, 1) -open(path, "w").write(s) -print("prefilt-wide dump instrumented") -PYW -# --- rung 8: palette colour-index map range ladder (detokenize.c) ------- -# EC_TRACE_PALETTE=1 -> "EC_PAL row=.. col=.. ctx=.. n=.. rng=.." before every -# colour-index symbol in decode_color_map_tokens's wavefront, "EC_PAL_VAL -# row=.. col=.. color_idx=.. rng=.." after. lane-palette r4: r3 already -# cleared every table/context function against this same source line-for-line -# by hand; this rung is what lets a real per-symbol range compare (class -# compare-range-not-tell / equal-range-means-unread) replace that by-hand -# check instead of re-reading the tables again. -I="$SRC/av1/decoder/detokenize.c" -[ -f "$I" ] || { echo "no oracle source at $I" >&2; exit 1; } - -python3 - "$I" <<'PYP' -import sys -path = sys.argv[1] -s = open(path).read() -if "EC_INSTRUMENTED_PALETTE" in s: - print("palette map already instrumented (no-op)") - sys.exit(0) - -old = """ const int color_ctx = av1_get_palette_color_index_context( - color_map, plane_block_width, (i - j), j, n, color_order, NULL); - const int color_idx = aom_read_symbol( - r, color_map_cdf[n - PALETTE_MIN_SIZE][color_ctx], n, ACCT_STR); - assert(color_idx >= 0 && color_idx < n); - color_map[(i - j) * plane_block_width + j] = color_order[color_idx];""" -new = """/* EC_INSTRUMENTED_PALETTE */ - const int color_ctx = av1_get_palette_color_index_context( - color_map, plane_block_width, (i - j), j, n, color_order, NULL); - const int ec_pal_trace = getenv("EC_TRACE_PALETTE") != NULL; - if (ec_pal_trace) { - fprintf(stderr, "EC_PAL row=%d col=%d ctx=%d n=%d rng=%u\\n", (i - j), - j, color_ctx, n, (unsigned)r->ec.rng); - } - const int color_idx = aom_read_symbol( - r, color_map_cdf[n - PALETTE_MIN_SIZE][color_ctx], n, ACCT_STR); - assert(color_idx >= 0 && color_idx < n); - color_map[(i - j) * plane_block_width + j] = color_order[color_idx]; - if (ec_pal_trace) { - fprintf(stderr, "EC_PAL_VAL row=%d col=%d color_idx=%d rng=%u\\n", - (i - j), j, color_idx, (unsigned)r->ec.rng); - }""" -assert old in s, "decode_color_map_tokens loop body moved" -s = s.replace(old, new, 1) -s = s.replace( - "static void decode_color_map_tokens(Av1ColorMapParam *param, aom_reader *r) {", - "/* EC_INSTRUMENTED_PALETTE */\nstatic void decode_color_map_tokens(Av1ColorMapParam *param, aom_reader *r) {", - 1, -) -open(path, "w").write(s) -print("palette map instrumented") -PYP - -# --- rung 8b: palette map[0] (av1_read_uniform) range ladder ------------ -python3 - "$I" <<'PYP0' -import sys -path = sys.argv[1] -s = open(path).read() -if "EC_INSTRUMENTED_PALETTE_UNIFORM" in s: - print("palette map[0] already instrumented (no-op)") - sys.exit(0) - -old = """ // The first color index. - color_map[0] = av1_read_uniform(r, n); - assert(color_map[0] < n);""" -new = """ // The first color index. - /* EC_INSTRUMENTED_PALETTE_UNIFORM */ - if (getenv("EC_TRACE_PALETTE") != NULL) { - fprintf(stderr, "EC_PAL row=0 col=0 ctx=-1 n=%d rng=%u\\n", n, - (unsigned)r->ec.rng); - } - color_map[0] = av1_read_uniform(r, n); - assert(color_map[0] < n); - if (getenv("EC_TRACE_PALETTE") != NULL) { - fprintf(stderr, "EC_PAL_VAL row=0 col=0 color_idx=%d rng=%u\\n", - color_map[0], (unsigned)r->ec.rng); - }""" -assert old in s, "color_map[0] uniform read moved" -s = s.replace(old, new, 1) -open(path, "w").write(s) -print("palette map[0] instrumented") -PYP0 - -# --- rung 9: export calculate_intermediate_result for a direct harness call -I="$SRC/av1/common/restoration.c" -[ -f "$I" ] || { echo "no oracle source at $I" >&2; exit 1; } - -python3 - "$I" <<'PYA' -import sys -path = sys.argv[1] -s = open(path).read() -if "/* EC_INSTRUMENTED_AB */" in s: - print("calculate_intermediate_result already exported (no-op)") - sys.exit(0) - -old = """static void calculate_intermediate_result(int32_t *dgd, int width, int height,""" -new = """/* EC_INSTRUMENTED_AB */ -void calculate_intermediate_result(int32_t *dgd, int width, int height,""" -assert old in s, "calculate_intermediate_result signature moved" -s = s.replace(old, new, 1) -open(path, "w").write(s) -print("calculate_intermediate_result exported") -PYA - -# --- rung 10: per-symbol range ladder inside intra key-frame mode info -- -python3 - "$SRC/av1/decoder/decodemv.c" <<'PYS' -import sys -path = sys.argv[1] -s = open(path).read() -if "EC_INSTRUMENTED_INTRA_STEP" in s: - print("intra mode-info per-symbol ladder already instrumented (no-op)") - sys.exit(0) - -def step(name, val): - return """ { - const int ec_trace = getenv("EC_TRACE_MODE_STEP") != NULL; - if (ec_trace) { - fprintf(stderr, "EC_ISTEP mi_row=%%d mi_col=%%d name=%s val=%%d rng=%%u\\n", - xd->mi_row, xd->mi_col, (int)(%s), (unsigned)r->ec.rng); - } - } -""" % (name, val) - -old = " mbmi->skip_txfm = read_skip_txfm(cm, xd, mbmi->segment_id, r);\n" -assert old in s, "read_skip_txfm call moved" -s = s.replace(old, old + step("skip", "mbmi->skip_txfm"), 1) - -old = " read_cdef(cm, r, xd);\n" -assert old in s, "read_cdef call moved" -s = s.replace(old, old + step("cdef", "0"), 1) - -old = " read_delta_q_params(cm, xd, r);\n" -assert old in s, "read_delta_q_params call moved" -s = s.replace(old, old + step("dq", "xd->current_base_qindex"), 1) - -old = " mbmi->mode = read_intra_mode(r, get_y_mode_cdf(ec_ctx, above_mi, left_mi));\n" -assert old in s, "y mode read moved" -s = s.replace(old, old + step("mode", "mbmi->mode"), 1) - -old = """ mbmi->angle_delta[PLANE_TYPE_Y] = - (use_angle_delta && av1_is_directional_mode(mbmi->mode)) - ? read_angle_delta(r, ec_ctx->angle_delta_cdf[mbmi->mode - V_PRED]) - : 0; -""" -assert old in s, "angle_delta_y block moved" -s = s.replace(old, old + step("angle_y", "mbmi->angle_delta[PLANE_TYPE_Y]"), 1) - -old = """ mbmi->uv_mode = - read_intra_mode_uv(ec_ctx, r, is_cfl_allowed(xd), mbmi->mode); -""" -assert old in s, "uv_mode read moved" -s = s.replace(old, old + step("uv_mode", "mbmi->uv_mode"), 1) - -old = """ mbmi->angle_delta[PLANE_TYPE_UV] = - (use_angle_delta && av1_is_directional_mode(intra_mode)) - ? read_angle_delta(r, ec_ctx->angle_delta_cdf[intra_mode - V_PRED]) - : 0; -""" -assert old in s, "angle_delta_uv block moved" -s = s.replace(old, old + step("angle_uv", "mbmi->angle_delta[PLANE_TYPE_UV]"), 1) - -marker_old = "static int read_mv_component(aom_reader *r, nmv_component *mvcomp," -assert marker_old in s, "anchor for EC_INSTRUMENTED_INTRA_STEP marker moved" -s = s.replace(marker_old, "/* EC_INSTRUMENTED_INTRA_STEP */\n" + marker_old, 1) - -open(path, "w").write(s) -print("intra mode-info per-symbol ladder instrumented") -PYS - -# --- rung 11: per-symbol range ladder inside read_coeffs_txb (decodetxb.c) -- -# lane-sbpart r7: rung 3's EC_TRACE_COEFF only bracketed a whole coefficient -# block (entry/exit rng) -- too coarse to find WHICH symbol inside a Luma64 -# corner-scan block diverges. This adds EC_COEFF_STEP tag=eob/base_eob/ -# after_bases/sign/post_golomb lines, rng after each, under the same -# EC_TRACE_COEFF flag (no new env var). Localized r7's own bisect to the -# `base` symbol at scan position (row=1,col=0) inside block2's luma corner: -# entry rng and eob/base_eob both match ours byte-for-byte, then our `base` -# read at that position decodes value=3 (triggering an extra `br` read) -# where the oracle's equivalent position decodes level=1 -- see -# lanes/sbpart-r7.report.md. -G="$SRC/av1/decoder/decodetxb.c" -[ -f "$G" ] || { echo "no oracle source at $G" >&2; exit 1; } - -python3 - "$G" <<'PYC11' -import sys -path = sys.argv[1] -s = open(path).read() -if "EC_COEFF_STEP" in s: - print("decodetxb rung 11 already applied (no-op)") - sys.exit(0) - -old1 = " *eob = rec_eob_pos(eob_pt, eob_extra);\n" -new1 = old1 + """ { - const int ec_trace2 = getenv("EC_TRACE_COEFF") != NULL; - if (ec_trace2) { - fprintf(stderr, "EC_COEFF_STEP tag=eob eob=%d rng=%u\\n", *eob, (unsigned)r->ec.rng); - } - } -""" -assert old1 in s, "eob assign not found" -s = s.replace(old1, new1, 1) - -old2 = " levels[get_padded_idx(pos, bhl)] = level;\n }\n if (*eob > 1) {" -new2 = """ levels[get_padded_idx(pos, bhl)] = level; - if (getenv("EC_TRACE_COEFF") != NULL) { - fprintf(stderr, "EC_COEFF_STEP tag=base_eob level=%d rng=%u\\n", level, (unsigned)r->ec.rng); - } - } - if (*eob > 1) {""" -assert old2 in s, "base_eob block not found" -s = s.replace(old2, new2, 1) - -old3 = """ read_coeffs_reverse(r, tx_size, tx_class, 0, *eob - 1 - 1, scan, bhl, - levels, base_cdf, br_cdf); - } - } -""" -new3 = old3 + """ if (getenv("EC_TRACE_COEFF") != NULL) { - fprintf(stderr, "EC_COEFF_STEP tag=after_bases rng=%u\\n", (unsigned)r->ec.rng); - } -""" -assert old3 in s, "after_bases site not found" -s = s.replace(old3, new3, 1) - -old4 = """ if (level >= MAX_BASE_BR_RANGE) { - level += read_golomb(xd, r); - } - - if (c == 0) dc_val = sign ? -level : level;""" -new4 = """ if (getenv("EC_TRACE_COEFF") != NULL) { - fprintf(stderr, "EC_COEFF_STEP tag=sign c=%d sign=%d rng=%u\\n", c, sign, (unsigned)r->ec.rng); - } - if (level >= MAX_BASE_BR_RANGE) { - level += read_golomb(xd, r); - } - if (getenv("EC_TRACE_COEFF") != NULL) { - fprintf(stderr, "EC_COEFF_STEP tag=post_golomb c=%d level=%d rng=%u\\n", c, level, (unsigned)r->ec.rng); - } - - if (c == 0) dc_val = sign ? -level : level;""" -assert old4 in s, "sign/golomb site not found" -s = s.replace(old4, new4, 1) - -open(path, "w").write(s) -print("decodetxb rung 11 (per-symbol coeff ladder) instrumented") -PYC11 - -# --- rung 12: FINAL reconstruction dump (lane-hidden r1) ---------------- -# EC_AV1_FINAL_DUMP= -> .f per DECODED frame (decode order, -# hidden alt-ref frames included), written after CDEF + superres + loop -# restoration have all run, i.e. exactly the frame as it is stored into the -# reference buffer. Y then U then V, crop-sized rows (post-superres -# y_crop_width), 8-bit as u8 and high bitdepth as u16 LE -- bit-depth -# correct, unlike the u8-narrowing debug dumps. -# -# DEPTH TRAP (lane-av1oraclerungdepth) -- READ BEFORE USING ANY DUMP RUNG: -# rungs 1 (PREFILT :146), 6 (POSTDEBLOCK :352), 7 (PREFILT_WIDE :416) and -# 15 (POSTCDEF :934) write 1 byte per sample with NO YV12_FLAG_HIGHBITDEPTH -# check, because each is byte-paired with a decoder-side dump that narrows to -# u8 on purpose. On a 10/12-bit stream those four are unusable: measured on the -# HBD oracle build with `av112bit-key.obu` (160x128 4:2:0 12-bit, 30720 -# samples) their 1-byte fwrite SIGSEGVs (exit 139, 0-byte file), and where it -# survives it writes 30720 B where w*h*bps = 61440 B is expected -- EXACTLY -# HALF, which reads like a truncated decode. Check `stat -c%s` against -# w*h*bps before calling either a decoder defect. This rung (12) is the -# depth-correct one for HBD. Each of those four rungs carries a -# `DEPTH ASSUMPTION` block naming its decoder-side pair and line. -# -# Rungs 1/6 (pre-filter / post-deblock) stop before CDEF+LR+superres, and -# every ffmpeg/aomdec pixel gate in this repo compares SHOWN frames only -# (class gate-blind-to-hidden-frames), so before this rung no instrument in -# the repo could compare a hidden frame's final pixels at all. -python3 - "$F" <<'PYF' -import sys -path = sys.argv[1] -s = open(path).read() -if "EC_INSTRUMENTED_FINAL" in s: - print("final dump already instrumented (no-op)") - sys.exit(0) - -anchor = """ if (!pbi->dcb.corrupted) { - if (cm->features.refresh_frame_context == REFRESH_FRAME_CONTEXT_BACKWARD) {""" -dump = """ /* EC_INSTRUMENTED_FINAL */ - { - const char *ec_dump = getenv("EC_AV1_FINAL_DUMP"); - if (ec_dump) { - static int ec_final_idx = 0; - char ec_path[1024]; - snprintf(ec_path, sizeof(ec_path), "%s.f%d", ec_dump, ec_final_idx++); - FILE *ec_f = fopen(ec_path, "wb"); - if (ec_f) { - const YV12_BUFFER_CONFIG *ec_b = &cm->cur_frame->buf; - const int ec_hbd = (ec_b->flags & YV12_FLAG_HIGHBITDEPTH) != 0; - const uint8_t *const ec_p8[3] = { ec_b->y_buffer, ec_b->u_buffer, - ec_b->v_buffer }; - const int ec_st[3] = { ec_b->y_stride, ec_b->uv_stride, - ec_b->uv_stride }; - const int ec_w[3] = { ec_b->y_crop_width, ec_b->uv_crop_width, - ec_b->uv_crop_width }; - const int ec_h[3] = { ec_b->y_crop_height, ec_b->uv_crop_height, - ec_b->uv_crop_height }; - for (int ec_pl = 0; ec_pl < (num_planes > 1 ? 3 : 1); ++ec_pl) { - for (int ec_r = 0; ec_r < ec_h[ec_pl]; ++ec_r) { - if (ec_hbd) { - const uint16_t *ec_s = CONVERT_TO_SHORTPTR(ec_p8[ec_pl]); - fwrite(ec_s + (size_t)ec_r * ec_st[ec_pl], 2, ec_w[ec_pl], ec_f); - } else { - fwrite(ec_p8[ec_pl] + (size_t)ec_r * ec_st[ec_pl], 1, - ec_w[ec_pl], ec_f); - } - } - } - fclose(ec_f); - } - } - } - -""" -assert anchor in s, "final dump anchor moved" -s = s.replace(anchor, dump + anchor, 1) -open(path, "w").write(s) -print("final dump instrumented") -PYF - -# --- rung 13: MV ground truth inside the inter mode ladder (lane-inter8 r3) -- -# lane-inter8 r3 patched the live oracle tree BY HAND and rebuilt aomdec, so -# these two probes existed only in ~/.cache/aom-oracle/src and any rebuild -# from this script would have silently dropped them (class: instrument that -# lives only in a build tree). Both extend rung 4 and are gated by the same -# EC_TRACE_MODE: -# * EC_MODE_MV .. mode=.. mv0=(..,..) rng=.. -- printed immediately after -# assign_mv, i.e. the MV as decoded, BEFORE interintra/motion-mode/ -# interp-filter syntax moves the range further; lets a lane separate an -# MV defect from a later-symbol defect on the same block. -# * stack= added to rung 4's EC_MODE_VAL -- -# the reference's own mv-stack depth for the block's reference pair. -H="$SRC/av1/decoder/decodemv.c" -[ -f "$H" ] || { echo "no oracle source at $H" >&2; exit 1; } - -python3 - "$H" <<'PYMV' -import sys -path = sys.argv[1] -s = open(path).read() -if "EC_MODE_MV" in s: - print("decodemv rung 13 already applied (no-op)") - sys.exit(0) -assert "EC_INSTRUMENTED" in s, "rung 13 needs rung 4 (run this script top to bottom)" - -# (a) stack= on rung 4's EC_MODE_VAL -old_val = """ "mv0=(%d,%d) rng=%u\\n", - ec_xd->mi_row, ec_xd->mi_col, (int)mbmi->mode, - (int)mbmi->ref_frame[0], (int)mbmi->ref_frame[1], - mbmi->mv[0].as_mv.row, mbmi->mv[0].as_mv.col, - (unsigned)r->ec.rng);""" -new_val = """ "mv0=(%d,%d) stack=%d rng=%u\\n", - ec_xd->mi_row, ec_xd->mi_col, (int)mbmi->mode, - (int)mbmi->ref_frame[0], (int)mbmi->ref_frame[1], - mbmi->mv[0].as_mv.row, mbmi->mv[0].as_mv.col, - /* EC_STACK */ (int)dcb->ref_mv_count[av1_ref_frame_type(mbmi->ref_frame)], - (unsigned)r->ec.rng);""" -assert old_val in s, "rung 4's EC_MODE_VAL body moved" -s = s.replace(old_val, new_val, 1) - -# (b) EC_MODE_MV right after assign_mv's corrupted-flag merge -anchor = " aom_merge_corrupted_flag(&dcb->corrupted, mv_corrupted_flag);\n" -assert s.count(anchor) == 1, "assign_mv corrupted-flag merge is no longer unique" -probe = """ if (getenv("EC_TRACE_MODE") != NULL) { - fprintf(stderr, - "EC_MODE_MV mi_row=%d mi_col=%d mode=%d mv0=(%d,%d) rng=%u\\n", - xd->mi_row, xd->mi_col, (int)mbmi->mode, mbmi->mv[0].as_mv.row, - mbmi->mv[0].as_mv.col, (unsigned)r->ec.rng); - } -""" -s = s.replace(anchor, anchor + probe, 1) -open(path, "w").write(s) -print("decodemv rung 13 (EC_MODE_MV + EC_MODE_VAL stack=) instrumented") -PYMV - -# --- rung 14: temporal-MV (MFMV) ground truth (lane-interbis, scripted by ---- -# --- lane-refstamp r1) ----------------------------------------------------- -# lane-interbis patched the live oracle tree BY HAND for its motion-field hunt, -# so these two probes lived only in ~/.cache/aom-oracle/src and a rebuild from -# this script would have dropped them (class: instrument that lives only in a -# build tree -- same reason rung 13 exists). -# * EC_TRACE_TPL=1 -> "EC_TPL mi_row=.. mi_col=.. blk=(..,..) mfmv0=(..,..) -# rfo=.." (or ".. INVALID") for every temporal candidate `add_tpl_ref_mv` -# probes -- the reference's own projected motion field, cell by cell, to -# compare against ours (EC_TRACE_TPL on our side). -# * the resolved MV STACK itself, one "EC_STACK mi_row=.. mi_col=.. ref=.. -# i=.. this=(..,..) comp=(..,..) w=.." line per entry, printed under rung -# 4's EC_TRACE_MODE right after EC_MODE_VAL (rung 13 only prints the -# stack DEPTH). -python3 - "$SRC/av1/common/mvref_common.c" <<'PYT' -import sys -path = sys.argv[1] -s = open(path).read() -if "EC_TRACE_TPL" in s: - print("mvref_common rung 14 already applied (no-op)") - sys.exit(0) -old = " if (prev_frame_mvs->mfmv0.as_int == INVALID_MV) return 0;\n" -assert old in s, "add_tpl_ref_mv's INVALID_MV early return moved" -new = """ if (prev_frame_mvs->mfmv0.as_int == INVALID_MV) { - if (getenv("EC_TRACE_TPL")) - fprintf(stderr, "EC_TPL mi_row=%d mi_col=%d blk=(%d,%d) INVALID\\n", - mi_row, mi_col, blk_row, blk_col); - return 0; - } - if (getenv("EC_TRACE_TPL")) - fprintf(stderr, - "EC_TPL mi_row=%d mi_col=%d blk=(%d,%d) mfmv0=(%d,%d) rfo=%d\\n", - mi_row, mi_col, blk_row, blk_col, prev_frame_mvs->mfmv0.as_mv.row, - prev_frame_mvs->mfmv0.as_mv.col, prev_frame_mvs->ref_frame_offset); -""" -s = s.replace(old, new, 1) -open(path, "w").write(s) -print("mvref_common rung 14 (EC_TPL) instrumented") -PYT - -python3 - "$SRC/av1/decoder/decodemv.c" <<'PYST' -import sys -path = sys.argv[1] -s = open(path).read() -if "EC_STACK mi_row" in s: - print("decodemv rung 14 already applied (no-op)") - sys.exit(0) -assert "EC_MODE_MV" in s, "rung 14 needs rung 13 (run this script top to bottom)" -anchor = """ /* EC_STACK */ (int)dcb->ref_mv_count[av1_ref_frame_type(mbmi->ref_frame)], - (unsigned)r->ec.rng); -""" -assert s.count(anchor) == 1, "rung 13's EC_MODE_VAL body moved" -dump = """ /* EC_INSTRUMENTED lane-interbis: the resolved mv stack itself */ - const MV_REFERENCE_FRAME ec_rt = av1_ref_frame_type(mbmi->ref_frame); - for (int ec_i = 0; ec_i < dcb->ref_mv_count[ec_rt]; ec_i++) { - fprintf(stderr, - "EC_STACK mi_row=%d mi_col=%d ref=%d i=%d this=(%d,%d) " - "comp=(%d,%d) w=%d\\n", - ec_xd->mi_row, ec_xd->mi_col, (int)ec_rt, ec_i, - ec_xd->ref_mv_stack[ec_rt][ec_i].this_mv.as_mv.row, - ec_xd->ref_mv_stack[ec_rt][ec_i].this_mv.as_mv.col, - ec_xd->ref_mv_stack[ec_rt][ec_i].comp_mv.as_mv.row, - ec_xd->ref_mv_stack[ec_rt][ec_i].comp_mv.as_mv.col, - ec_xd->weight[ec_rt][ec_i]); - } -""" -s = s.replace(anchor, anchor + dump, 1) -open(path, "w").write(s) -print("decodemv rung 14 (per-entry EC_STACK) instrumented") -PYST - -# --- rung 15: post-CDEF, pre-superres 8-bit row dump (lane-av1422filter) --- -# The 8-bit mirror of rung 6 one stage later: written right after the CDEF -# pass (the `if (do_cdef) {...}` block) and before superres/LR, so a final -# chroma/luma mismatch splits into "already in CDEF" vs "introduced by -# loop restoration". The *_DUMP16 family covers this stage only in 16-bit -# builds (its 8-bit run SEGFAULTS); this rung is the 8-bit one. lane- -# av1422filter added it to the live oracle tree by hand first, then it was -# transcribed here (class: instrument that lives only in a build tree). -# DEPTH ASSUMPTION (lane-av1oraclerungdepth): 1 byte per sample, NO -# YV12_FLAG_HIGHBITDEPTH check. Deliberate -- byte-paired with our -# EC_AV1_POSTCDEF_DUMP, which narrows to u8 (decode.rs:20048-20054; same -# closure at :53489). TRAP: on an HBD stream the file is EXACTLY HALF w*h*2, -# which reads like a truncated/short decode, not a decoder bug. For HBD use rung 12 -# EC_AV1_FINAL_DUMP (:730) -- depth-correct (u8 / u16 LE). -# OBSERVED 2026-09-29 (HBD build, av112bit-key.obu): the 1-byte fwrite SIGSEGVs -# (exit 139); where it survives it writes 30720 B where 61440 B is expected -- -# exactly half. That is this rung, not a truncated decode. -python3 - "$F" <<'PYC' -import sys -path = sys.argv[1] -s = open(path).read() -if "EC_INSTRUMENTED_POSTCDEF" in s: - print("postcdef dump already instrumented (no-op)") - sys.exit(0) - -anchor = """ if (do_cdef) { - if (pbi->num_workers > 1) { - av1_cdef_frame_mt(cm, &pbi->dcb.xd, pbi->cdef_worker, - pbi->tile_workers, &pbi->cdef_sync, - pbi->num_workers, av1_cdef_init_fb_row_mt, - do_extend_border_mt); - } else { - av1_cdef_frame(&pbi->common.cur_frame->buf, cm, &pbi->dcb.xd, - av1_cdef_init_fb_row); - } - } -""" -dump = """ - /* EC_INSTRUMENTED_POSTCDEF (8-bit twin of the POSTDEBLOCK rung: - * full aligned buffer, post-CDEF pre-superres/LR) */ - { - const char *ec_dump = getenv("EC_AV1_POSTCDEF_DUMP"); - if (ec_dump) { - static int ec_postcdef_idx = 0; - char ec_path[1024]; - snprintf(ec_path, sizeof(ec_path), "%s.f%d", ec_dump, - ec_postcdef_idx++); - FILE *ec_f = fopen(ec_path, "wb"); - if (ec_f) { - const YV12_BUFFER_CONFIG *ec_b = &cm->cur_frame->buf; - for (int ec_r = 0; ec_r < ec_b->y_height; ++ec_r) - fwrite(ec_b->y_buffer + ec_r * ec_b->y_stride, 1, ec_b->y_width, - ec_f); - if (num_planes > 1) { - for (int ec_r = 0; ec_r < ec_b->uv_height; ++ec_r) - fwrite(ec_b->u_buffer + ec_r * ec_b->uv_stride, 1, - ec_b->uv_width, ec_f); - for (int ec_r = 0; ec_r < ec_b->uv_height; ++ec_r) - fwrite(ec_b->v_buffer + ec_r * ec_b->uv_stride, 1, - ec_b->uv_width, ec_f); - } - fclose(ec_f); - } - } - } -""" -assert anchor in s, "do_cdef block anchor moved" -s = s.replace(anchor, anchor + dump, 1) -open(path, "w").write(s) -print("postcdef dump instrumented") -PYC - -# --- depth contract for the four u8-narrowing dump rungs ------------------ -# PREFILT (rung 1), POSTDEBLOCK (rung 3), PREFILT_WIDE (rung 7) and POSTCDEF -# are paired with ec-av1 decoder rungs that narrow every sample with `as u8`, -# so the oracle side owes ONE BYTE PER SAMPLE at every depth. As instrumented -# above they wrote `fwrite(plane + r*stride, 1, w, f)`, which is wrong twice -# over on a high-bit-depth stream: -# 1. YV12_BUFFER_CONFIG stores plane pointers in HALVED form -- aom_ports/mem.h -# defines CONVERT_TO_BYTEPTR(x) = x >> 1 -- so the real address is -# CONVERT_TO_SHORTPTR(p) (p << 1). Pointer arithmetic on the raw uint8_t* -# therefore yields an unrelated half-address, and fwrite faults inside -# memmove: SIGSEGV (exit 139) with a 0-byte file, on EVERY HBD stream, for -# all four rungs, while rung 12 (which does convert) works. A lane hitting -# it sees a crashed aomdec and cannot tell it from a decoder defect. -# 2. y_stride/uv_stride count SAMPLES, so `+ r*stride` in bytes also picks the -# wrong row even where the address happens to be readable. -# At 8 bit neither applies: buf is the real pointer and flags is 0, so the -# bytes emitted are bit-for-bit what these rungs always wrote. This block owns -# the contract for all four, runs last, and is a REPAIR pass: it rewrites the -# loops an earlier (or pre-fix) instrumentation left behind, so re-running this -# script on an already-instrumented tree fixes it in place. -python3 - "$F" <<'PYN' -import re -import sys - -path = sys.argv[1] -s = open(path).read() - -helper = '''/* EC_INSTRUMENTED_NARROW_ROW: emit one plane row as ONE BYTE PER SAMPLE, the - * shape the ec-av1 decoder's own EC_AV1_*_DUMP rungs write (they narrow every - * sample with `as u8`). - * - * Two HBD traps this replaces, both fatal until fixed: - * 1. YV12_BUFFER_CONFIG stores plane pointers in HALVED form: the real - * address is `CONVERT_TO_SHORTPTR(p)` (aom_ports/mem.h defines - * `CONVERT_TO_BYTEPTR(x) = x >> 1`), so `p + r*stride` computed on the raw - * uint8_t* is an unrelated address. `fwrite(y_buffer + r*y_stride, 1, w, - * f)` on a 10/12-bit stream therefore hands fwrite a half-address that - * faults inside memmove -- SIGSEGV with a 0-byte file, which reads as a - * decoder crash rather than a broken rung. - * 2. y_stride/uv_stride count SAMPLES, so a byte-wise `+ r*stride` addresses - * the wrong row as well. - * At 8 bit neither applies: the pointer is the real one and the bytes written - * are exactly what the rung always emitted. */ -static void ec_dump_narrow_row(FILE *f, const YV12_BUFFER_CONFIG *b, - const uint8_t *plane8, int stride, int row, - int w) { - if (!(b->flags & YV12_FLAG_HIGHBITDEPTH)) { - fwrite(plane8 + (size_t)row * stride, 1, (size_t)w, f); - return; - } - const uint16_t *p = CONVERT_TO_SHORTPTR(plane8) + (size_t)row * stride; - uint8_t *narrow = (uint8_t *)aom_malloc((size_t)w); - if (!narrow) return; - for (int c = 0; c < w; ++c) narrow[c] = (uint8_t)(p[c] & 0xFF); - fwrite(narrow, 1, (size_t)w, f); - aom_free(narrow); -} - -/* EC_INSTRUMENTED_DUMP_CHECK: the harm the depth bug above caused is not a - * wrong number, it is a SILENT 0-byte dump -- downstream that reads as "the - * oracle has no data for this stage" and becomes a phantom stage diff. So - * every narrowing rung checks the byte count it just produced against the - * shape it claims to write and aborts IN THE ORACLE, naming itself, instead - * of handing the decoder an empty file. `expect` is Y + U + V at ONE BYTE PER - * SAMPLE: the crop extent when `aligned` is 0 (PREFILT), the mi-aligned - * extent when 1 (PREFILT_WIDE / POSTDEBLOCK / POSTCDEF). No configuration - * writes 0 bytes: a frame's crop extent is non-zero by construction, and a - * failed fopen skips the block entirely (so a bad path is not an abort). */ -static void ec_dump_finish(FILE *f, const char *rung, - const YV12_BUFFER_CONFIG *b, int num_planes, - int aligned) { - const size_t y = aligned ? (size_t)b->y_width * b->y_height - : (size_t)b->y_crop_width * b->y_crop_height; - const size_t uv = aligned ? (size_t)b->uv_width * b->uv_height - : (size_t)b->uv_crop_width * b->uv_crop_height; - const size_t expect = y + (num_planes > 1 ? 2 * uv : 0); - const long wrote = ftell(f); - if (wrote < 0 || (size_t)wrote != expect || fflush(f) != 0) { - fprintf(stderr, - "EC_DUMP_ABORT rung=%s bit_depth=%u hbd=%d expect=%zu wrote=%ld " - "(one byte per sample, Y+U+V)\\n", - rung, b->bit_depth, - (b->flags & YV12_FLAG_HIGHBITDEPTH) ? 1 : 0, expect, wrote); - abort(); - } - fclose(f); -} - -''' - -MARKER_ROW = "EC_INSTRUMENTED_NARROW_ROW" -MARKER_CHECK = "EC_INSTRUMENTED_DUMP_CHECK" -missing = "" -if MARKER_ROW not in s: - missing = helper -elif MARKER_CHECK not in s: - # The tree already carries the row helper from an earlier run of this - # script: add the byte-count checker on its own so a repaired tree - # converges instead of erroring. - missing = helper[helper.index("/* " + MARKER_CHECK):] -if missing: - # Both helpers must precede every user: the POSTCDEF rung was refactored - # into a static helper that sits ABOVE av1_decode_tg_tiles_and_wrapup, so - # anchor there when it exists and at the function itself otherwise. - for anchor in ("static void ec_dump_postcdef(const AV1_COMMON *cm, int num_planes) {", - "void av1_decode_tg_tiles_and_wrapup(AV1Decoder *pbi, const uint8_t *data,"): - if anchor in s: - s = s.replace(anchor, missing + anchor, 1) - break - else: - raise SystemExit("dump helpers: no anchor before the dump rungs") - print("dump helpers inserted: %s" - % ("narrow-row + byte-count check" if len(missing) == len(helper) - else "byte-count check only")) - -row_loop = re.compile( - r"for \(int ec_r = 0; ec_r < ec_b->(\w+); \+\+ec_r\)\n" - r"(\s*)fwrite\(ec_b->(\w+)_buffer \+ ec_r \* ec_b->(\w+), 1,\s*\n?\s*ec_b->(\w+),\s*\n?\s*ec_f\);") - - -def narrow(match): - rows, indent, plane, stride, width = match.groups() - return ("for (int ec_r = 0; ec_r < ec_b->%s; ++ec_r)\n%s" - "ec_dump_narrow_row(ec_f, ec_b, ec_b->%s_buffer, ec_b->%s, ec_r,\n" - "%s%s ec_b->%s);" % (rows, indent, plane, stride, indent, indent, width)) - - -s, rewritten = row_loop.subn(narrow, s) -if rewritten: - print("narrow-row depth fix: rewrote %d plane row loops" % rewritten) -else: - print("narrow-row depth fix: no legacy row loop left (already depth-correct)") - -# Close each narrowing rung through the checker. Keyed on the presence of a -# rewritten row loop, so rung 12 (EC_AV1_FINAL_DUMP, 2 bytes per sample and -# already depth-correct) is never reached: its block has no ec_dump_narrow_row. -# The terminator alternation keeps each block matched to ITS OWN close, so a -# re-run cannot run a block's body forward into a later rung's fclose. -dump_block = re.compile( - r'(FILE \*ec_f = fopen\(ec_path, "wb"\);)(.*?)' - r'((?:fclose\(ec_f\);)|(?:ec_dump_finish\([^;]*\);))', - re.S) - -WIRED = [] - -def finish(match): - opened, body, closed = match.groups() - if "ec_dump_narrow_row" not in body: - return match.group(0) - # The rung name can sit ABOVE the fopen (the POSTCDEF rung was refactored - # into a helper that does getenv -> fopen at the top), so take the nearest - # preceding EC_AV1_* env lookup rather than searching the block body. - preceding = re.findall(r'getenv\("(EC_AV1_[A-Z_]+)"\)', s[:match.start()]) - if not preceding: - raise SystemExit("dump check: no rung env var above a narrowing block") - aligned = 0 if "y_crop_height" in body else 1 - if closed.startswith("fclose"): - WIRED.append(preceding[-1]) - return "%s%s%s" % ( - opened, body, - 'ec_dump_finish(ec_f, "%s", ec_b, num_planes, %d);' % (preceding[-1], aligned)) - - -s, _ = dump_block.subn(finish, s) -if WIRED: - print("dump byte-count check: wired into %d narrowing rung(s): %s" - % (len(WIRED), ", ".join(WIRED))) -else: - print("dump byte-count check: every narrowing rung already checks its bytes") -open(path, "w").write(s) -PYN - -# --- rung 16: EC_PREDOUT8, the 8-bit predicted block (lane-av1cmpaudit) ---- -# This rung lived ONLY in the hand-patched oracle tree -- `instrument-aom- -# oracle.sh` never transcribed it -- so a rebuild from this script silently -# dropped it (class: instrument that lives only in a build tree, the same -# reason rung 13 exists). It is transcribed here at BOTH 8-bit prediction -# sites in reconintra.c: the non-directional early-return path (DC, SMOOTH*, -# PAETH) and the directional / filter-intra tail. lane-av1cmpaudit also grew -# `mode=` on both: without it, an agreeing-top / disagreeing-bottom pattern -# on a non-directional unit could not be attributed to a mode at all. -# `mode=` sits after `txh=`, matching EC_PREDND's own field order; every -# pre-existing field keeps its position. -# -# Idempotent, and an UPGRADE as well as an install: the oracle tree's git HEAD -# already carries the rung WITHOUT `mode=`, so the script has to rewrite that -# form too, not just insert the block into a pristine upstream file. -I="$SRC/av1/common/reconintra.c" -[ -f "$I" ] || { echo "no oracle source at $I" >&2; exit 1; } - -python3 - "$I" <<'PYRI' -import sys -path = sys.argv[1] -s = open(path).read() - -if 'EC_PREDOUT8' not in s: - # Pristine upstream: insert the rung at both 8-bit prediction sites. - nd_old = """ build_non_directional_intra_predictors(ref, ref_stride, dst, dst_stride, - mode, tx_size, n_top_px, n_left_px); - return; - }""" - nd_new = """ build_non_directional_intra_predictors(ref, ref_stride, dst, dst_stride, - mode, tx_size, n_top_px, n_left_px); - /* EC_INSTRUMENTED_PREDOUT8 (non-directional, 8-bit) */ - if (getenv("EC_PRED")) { - long ec_sum = 0; - for (int r = 0; r < txhpx; ++r) - for (int c = 0; c < txwpx; ++c) ec_sum += dst[r * dst_stride + c]; - fprintf(stderr, "EC_PREDOUT8 mi_row=%d mi_col=%d plane=%d row_off=%d col_off=%d txw=%d txh=%d mode=%d sum=%ld row0=", xd->mi_row, xd->mi_col, plane, row_off, col_off, txwpx, txhpx, mode, ec_sum); - for (int c = 0; c < txwpx && c < 8; ++c) fprintf(stderr, "%d,", dst[c]); - fprintf(stderr, " col0="); - for (int r = 0; r < txhpx && r < 8; ++r) fprintf(stderr, "%d,", dst[r * dst_stride]); - fprintf(stderr, "\\n"); - } - return; - }""" - assert nd_old in s, "non-directional intra predictor tail moved" - s = s.replace(nd_old, nd_new, 1) - - dir_old = """ build_directional_and_filter_intra_predictors( - ref, ref_stride, dst, dst_stride, mode, p_angle, filter_intra_mode, - tx_size, disable_edge_filter, n_top_px, n_topright_px, n_left_px, - n_bottomleft_px, intra_edge_filter_type); -}""" - dir_new = """ build_directional_and_filter_intra_predictors( - ref, ref_stride, dst, dst_stride, mode, p_angle, filter_intra_mode, - tx_size, disable_edge_filter, n_top_px, n_topright_px, n_left_px, - n_bottomleft_px, intra_edge_filter_type); - /* EC_INSTRUMENTED_PREDOUT8 (directional / filter-intra, 8-bit) */ - if (getenv("EC_PRED")) { - long ec_sum = 0; - for (int r = 0; r < txhpx; ++r) - for (int c = 0; c < txwpx; ++c) ec_sum += dst[r * dst_stride + c]; - fprintf(stderr, "EC_PREDOUT8 mi_row=%d mi_col=%d plane=%d row_off=%d col_off=%d txw=%d txh=%d mode=%d sum=%ld row0=", mi_row, mi_col, plane, row_off, col_off, txwpx, txhpx, mode, ec_sum); - for (int c = 0; c < txwpx && c < 8; ++c) fprintf(stderr, "%d,", dst[c]); - fprintf(stderr, " col0="); - for (int r = 0; r < txhpx && r < 8; ++r) fprintf(stderr, "%d,", dst[r * dst_stride]); - fprintf(stderr, "\\n"); - } -}""" - assert dir_old in s, "directional intra predictor tail moved" - s = s.replace(dir_old, dir_new, 1) - open(path, "w").write(s) - print("EC_PREDOUT8 installed (both 8-bit paths, with mode=)") - sys.exit(0) - -# Already present: upgrade the rung to carry `mode=` if it does not yet. -nd_fmt_old = 'txw=%d txh=%d sum=%ld row0=", xd->mi_row' -nd_fmt_new = 'txw=%d txh=%d mode=%d sum=%ld row0=", xd->mi_row' -dir_fmt_old = 'txw=%d txh=%d sum=%ld row0=", mi_row' -dir_fmt_new = 'txw=%d txh=%d mode=%d sum=%ld row0=", mi_row' -upgraded = 0 -arg_old = "col_off, txwpx, txhpx, ec_sum);" -arg_new = "col_off, txwpx, txhpx, mode, ec_sum);" -if nd_fmt_old in s: - s = s.replace(nd_fmt_old, nd_fmt_new, 1) - assert arg_old in s, "EC_PREDOUT8 non-directional argument list moved" - s = s.replace(arg_old, arg_new, 1) - upgraded += 1 -if dir_fmt_old in s: - s = s.replace(dir_fmt_old, dir_fmt_new, 1) - assert arg_old in s, "EC_PREDOUT8 directional argument list moved" - s = s.replace(arg_old, arg_new, 1) - upgraded += 1 -if upgraded: - open(path, "w").write(s) - print("EC_PREDOUT8 upgraded to mode= (%d site(s))" % upgraded) -else: - print("EC_PREDOUT8 already carries mode= (no-op)") -PYRI - -# --- rung 17: EC_PREDND, the hbd twin of EC_PREDOUT8 (lane-av1cmpaudit) ---- -# The 10/12-bit non-directional twin of rung 16, and like it this rung lived -# ONLY in the hand-patched oracle tree. Without it a rebuild drops the only -# prediction probe that fires on a high-bitdepth stream -- rung 16 and the -# pre-existing EC_PREDOUT both sit after the `is_hbd` early return and print -# nothing there. EC_PREDND already carried `mode=`, so unlike rung 16 this one -# is an INSTALL-ONLY rung: it is inserted into a pristine upstream file and is -# a no-op on the already-instrumented tree. -I="$SRC/av1/common/reconintra.c" -[ -f "$I" ] || { echo "no oracle source at $I" >&2; exit 1; } - -python3 - "$I" <<'PYND' -import sys -path = sys.argv[1] -s = open(path).read() -if "EC_PREDND" in s: - print("EC_PREDND already instrumented (no-op)") - sys.exit(0) - -old = """ highbd_build_non_directional_intra_predictors( - ref, ref_stride, dst, dst_stride, mode, tx_size, n_top_px, n_left_px, - xd->bd); - return; - }""" -new = """ highbd_build_non_directional_intra_predictors( - ref, ref_stride, dst, dst_stride, mode, tx_size, n_top_px, n_left_px, - xd->bd); - /* EC_INSTRUMENTED_PREDND (non-directional, high bitdepth) */ - if (getenv("EC_PRED")) { - const int ec_mi_row = -xd->mb_to_top_edge >> (3 + MI_SIZE_LOG2); - const int ec_mi_col = -xd->mb_to_left_edge >> (3 + MI_SIZE_LOG2); - const uint16_t *d16 = CONVERT_TO_SHORTPTR(dst); - long sum = 0; - for (int r = 0; r < txhpx; ++r) - for (int c = 0; c < txwpx; ++c) sum += d16[r * dst_stride + c]; - fprintf(stderr, - "EC_PREDND mi_row=%d mi_col=%d plane=%d row_off=%d col_off=%d " - "txw=%d txh=%d mode=%d n_top=%d n_left=%d sum=%ld row0=", - ec_mi_row, ec_mi_col, plane, row_off, col_off, txwpx, txhpx, - mode, n_top_px, n_left_px, sum); - for (int c = 0; c < txwpx && c < 8; ++c) fprintf(stderr, "%d,", d16[c]); - fprintf(stderr, " col0="); - for (int r = 0; r < txhpx && r < 8; ++r) - fprintf(stderr, "%d,", d16[r * dst_stride]); - fprintf(stderr, "\\n"); - } - return; - }""" -assert old in s, "highbd non-directional intra predictor tail moved" -s = s.replace(old, new, 1) -open(path, "w").write(s) -print("EC_PREDND instrumented (non-directional, high bitdepth)") -PYND - -# --- rung 18: var-tx partition CONTEXT OPERANDS (lane-av1oddheightfork3) ---- -# `EC_VARTX` itself was hand-added to the oracle tree and was NOT in this -# generator, so a rebuild from the script dropped it (the rung-loss class: -# every rung must be derived here or the next lane loses it). This block -# installs BOTH, from a pristine upstream file, idempotently, and is the only -# place either print may be edited. -# -# Why the operands: `txfm_partition_context` (av1_common_int.h:1747-1769) is -# `category * 3 + (*above_ctx < txw) + (*left_ctx < txh)`, so a ctx -# disagreement with our decoder names WHICH `TXFM_CONTEXT` neighbour band -# differs only if both operands are printed -- `EC_VARTX` alone gives the sum -# (ctx) and nothing under it. `above` is read at `+ blk_col` of the row band, -# `left` at `+ blk_row` of the column band; those indices are in the print so -# a reader can tell a band-offset bug from a value bug. Env-gated on -# EC_VARTXCTX (a separate flag from EC_VARTX so an existing EC_VARTX ladder -# log stays byte-identical to before this rung). -python3 - "$F" <<'PYVX' -import re, sys -path = sys.argv[1] -s = open(path).read() -if "EC_VARTXCTX" in s: - print("EC_VARTXCTX already instrumented (no-op)") - sys.exit(0) - -anchor = " is_split = aom_read_symbol(r, ec_ctx->txfm_partition_cdf[ctx], 2, ACCT_STR);\n" -assert anchor in s, "read_tx_size_vartx symbol read moved" - -# Drop a hand-added EC_VARTX print (the tree this block first ran against -# carried one that this script never derived), so the derived text is the -# only definition and a re-run is a no-op rather than a duplicate print. -legacy = re.search( - r' if \(getenv\("EC_VARTX"\) != NULL\)\n' - r' fprintf\(stderr,\n' - r' "EC_VARTX mi=\(%d,%d\).*?\(int\)aom_reader_tell\(r\)\);\n', - s, re.S) -if legacy: - s = s[:legacy.start()] + s[legacy.end():] - -new = anchor + """ if (getenv("EC_VARTX") != NULL) - fprintf(stderr, - "EC_VARTX mi=(%d,%d) row=%d col=%d ctx=%d n=2 s=%d bitpos=%d\\n", - xd->mi_row, xd->mi_col, blk_row, blk_col, ctx, is_split, - (int)aom_reader_tell(r)); - /* EC_INSTRUMENTED_VARTXCTX: the two TXFM_CONTEXT operands of `ctx`. */ - if (getenv("EC_VARTXCTX") != NULL) - fprintf(stderr, - "EC_VARTXCTX mi=(%d,%d) row=%d col=%d above=%d left=%d txw=%d " - "txh=%d ctx=%d\\n", - xd->mi_row, xd->mi_col, blk_row, blk_col, - (int)xd->above_txfm_context[blk_col], - (int)xd->left_txfm_context[blk_row], (int)tx_size_wide[tx_size], - (int)tx_size_high[tx_size], ctx); -""" -s = s.replace(anchor, new, 1) -open(path, "w").write(s) -print("EC_VARTX/EC_VARTXCTX instrumented (read_tx_size_vartx)") -PYVX - -# --- rung 19: EC_PIB, EVERY av1_predict_intra_block call (lane-av1422ctattr) --- -# WHY. Three lanes of 4:2:2 chroma archaeology stalled on ONE blind spot: -# `av1_predict_intra_block` has an early `if (use_palette) { ...; return; }` -# and TWO early `return`s after it (the 8-bit non-directional site and the -# hbd one), so EC_PREDOUT8 / EC_PREDND only print on SOME of the paths that -# write a block. A chroma region where no rung fires is therefore -# un-attributable: "libaom used dc_top" was an inference from the predicted -# VALUE, not a printed flag, and the whole ladder looked like it had no block -# there at all. EC_PIB prints the CALL IDENTITY -- before any early return -- -# so the question "which call wrote this pixel, and did it return early" is -# answerable from the trace instead of from arithmetic. -# -# Field order is deliberately identical to EC_PREDOUT8/EC_PRED for the fields -# they share, so a rung 16 line and a rung 19 line for the same block read as -# one line. `use_palette` is the early-return bit: use_palette=1 with no -# EC_PREDOUT8/EC_PRED twin line IS a palette write. -# -# Env: EC_PIB=1. Optional EC_PIBWIN="mi_row_lo:mi_row_hi:mi_col_lo:mi_col_hi" -# (any field < 0 means "any") so a seed's own block can be isolated without -# dumping a whole frame. -python3 - "$I" <<'PYPIB' -import sys -path = sys.argv[1] -s = open(path).read() -if "EC_PIB " in s: - print("EC_PIB already instrumented (no-op)") - sys.exit(0) - -anchor = """ const int is_hbd = is_cur_buf_hbd(xd); - - assert(mode < INTRA_MODES);""" -new = """ const int is_hbd = is_cur_buf_hbd(xd); - - /* EC_INSTRUMENTED_PIB: the call IDENTITY, printed BEFORE the palette - early return so every call is visible. */ - if (getenv("EC_PIB")) { - const char *ec_w = getenv("EC_PIBWIN"); - int ec_r0 = -1, ec_r1 = -1, ec_c0 = -1, ec_c1 = -1; - if (ec_w) sscanf(ec_w, "%d:%d:%d:%d", &ec_r0, &ec_r1, &ec_c0, &ec_c1); - if ((ec_r0 < 0 || (xd->mi_row >= ec_r0 && xd->mi_row <= ec_r1)) && - (ec_c0 < 0 || (xd->mi_col >= ec_c0 && xd->mi_col <= ec_c1))) { - fprintf(stderr, - "EC_PIB mi_row=%d mi_col=%d plane=%d row_off=%d col_off=%d " - "txw=%d txh=%d mode=%d use_palette=%d filter_intra=%d bsize=%d " - "px=%d py=%d hbd=%d\\n", - xd->mi_row, xd->mi_col, plane, row_off, col_off, txwpx, txhpx, - mode, use_palette, (int)filter_intra_mode, (int)mbmi->bsize, - col_off << MI_SIZE_LOG2, row_off << MI_SIZE_LOG2, (int)is_hbd); - } - } - - assert(mode < INTRA_MODES);""" -assert anchor in s, "av1_predict_intra_block prologue moved" -s = s.replace(anchor, new, 1) - -# --- rung 20: EC_DCIN, the DC path's availability INPUTS (lane-av1422ctattr) -- -# `dc_predictor`'s four variants are selected by (have_top, have_left) and -# scaled by (n_top_px, n_left_px); EC_PREDOUT8 prints none of them, only the -# RESULT and the mode. So a predicted value that "looks like dc_top" is an -# inference. EC_DCIN prints the four operands, the two edge SUMS they are -# taken from, the availability BITS themselves (including the per-plane -# chroma_* narrowing in set_mi_row_col), and the variant id the four-way -# select picked -- so the variant is a printed field, not an inference. -# -# Variant id: 0 = dc (both edges), 1 = dc_top, 2 = dc_left, 3 = dc_128. -# -# Installed at BOTH 8-bit and high-bitdepth non-directional sites, before the -# predictor call. Env: EC_DCIN=1 (EC_PIBWIN filters it too). -nd_anchor = """ build_non_directional_intra_predictors(ref, ref_stride, dst, dst_stride, - mode, tx_size, n_top_px, n_left_px);""" -nd_new = """ /* EC_INSTRUMENTED_DCIN (8-bit non-directional): the availability INPUTS - and the DC variant they select. */ - if (getenv("EC_DCIN")) { - long ec_atop = 0, ec_aleft = 0; - int ec_i; - for (ec_i = 0; ec_i < n_top_px; ++ec_i) ec_atop += ref[ec_i]; - for (ec_i = 0; ec_i < n_left_px; ++ec_i) ec_aleft += ref[ec_i * ref_stride]; - fprintf(stderr, - "EC_DCIN mi_row=%d mi_col=%d plane=%d row_off=%d col_off=%d " - "txw=%d txh=%d mode=%d have_top=%d have_left=%d n_top=%d " - "n_left=%d atop=%ld aleft=%ld dcv=%d up=%d left=%d cup=%d " - "cleft=%d ss_x=%d ss_y=%d bsize=%d\\n", - xd->mi_row, xd->mi_col, plane, row_off, col_off, txwpx, txhpx, - mode, have_top, have_left, n_top_px, n_left_px, ec_atop, - ec_aleft, - (n_top_px > 0 ? (n_left_px > 0 ? 0 : 1) - : (n_left_px > 0 ? 2 : 3)), - xd->up_available, xd->left_available, xd->chroma_up_available, - xd->chroma_left_available, ss_x, ss_y, (int)mbmi->bsize); - } - build_non_directional_intra_predictors(ref, ref_stride, dst, dst_stride, - mode, tx_size, n_top_px, n_left_px);""" -assert nd_anchor in s, "8-bit non-directional predictor call moved" -s = s.replace(nd_anchor, nd_new, 1) - -hbd_anchor = """ highbd_build_non_directional_intra_predictors( - ref, ref_stride, dst, dst_stride, mode, tx_size, n_top_px, n_left_px, - xd->bd);""" -hbd_new = """ /* EC_INSTRUMENTED_DCIN (high bitdepth non-directional): the hbd twin. */ - if (getenv("EC_DCIN")) { - const uint16_t *ec_r16 = CONVERT_TO_SHORTPTR(ref); - long ec_atop = 0, ec_aleft = 0; - int ec_i; - for (ec_i = 0; ec_i < n_top_px; ++ec_i) ec_atop += ec_r16[ec_i]; - for (ec_i = 0; ec_i < n_left_px; ++ec_i) - ec_aleft += ec_r16[ec_i * ref_stride]; - fprintf(stderr, - "EC_DCIN mi_row=%d mi_col=%d plane=%d row_off=%d col_off=%d " - "txw=%d txh=%d mode=%d have_top=%d have_left=%d n_top=%d " - "n_left=%d atop=%ld aleft=%ld dcv=%d up=%d left=%d cup=%d " - "cleft=%d ss_x=%d ss_y=%d bsize=%d\\n", - xd->mi_row, xd->mi_col, plane, row_off, col_off, txwpx, txhpx, - mode, have_top, have_left, n_top_px, n_left_px, ec_atop, - ec_aleft, - (n_top_px > 0 ? (n_left_px > 0 ? 0 : 1) - : (n_left_px > 0 ? 2 : 3)), - xd->up_available, xd->left_available, xd->chroma_up_available, - xd->chroma_left_available, ss_x, ss_y, (int)mbmi->bsize); - } - highbd_build_non_directional_intra_predictors( - ref, ref_stride, dst, dst_stride, mode, tx_size, n_top_px, n_left_px, - xd->bd);""" -if hbd_anchor in s: - s = s.replace(hbd_anchor, hbd_new, 1) -else: - print("WARN: hbd non-directional call anchor not found; EC_DCIN is 8-bit only") - -open(path, "w").write(s) -print("EC_PIB/EC_DCIN instrumented (av1_predict_intra_block)") -PYPIB - -# --- rung 21: EC_DP, the per-block branch taken in decode_token_recon_block --- -# WHY. `decode_token_recon_block` has two arms -- intra (the only one whose -# prediction prints a rung) and inter (`predict_inter_block_visit`, no -# intra rung at all) -- AND, inside the intra arm, `if (plane && !xd- -# >is_chroma_ref) break;`, so a chroma plane can be skipped entirely. A -# region where NO prediction rung fires is consistent with all three, and the -# rung ladder alone cannot tell them apart. EC_DP prints the branch decision -# for every block: which arm, whether chroma is reconstructed at all, and the -# max_unit geometry the loop walks. Env: EC_DP=1. -python3 - "$F" <<'PYDP' -import sys -path = sys.argv[1] -s = open(path).read() -if "EC_DP mi_row=" in s: - print("EC_DP already instrumented (no-op)") - sys.exit(0) - -anchor = """ MB_MODE_INFO *mbmi = xd->mi[0]; - - if (!is_inter_block(mbmi)) {""" -new = """ MB_MODE_INFO *mbmi = xd->mi[0]; - - /* EC_INSTRUMENTED_DP: the branch decode_token_recon_block takes for this - block -- intra vs inter, and whether the chroma planes are reconstructed - at all (`plane && !xd->is_chroma_ref`). Anchored on the `mbmi` + - `if (!is_inter_block)` pair, not on the function signature, because the - signature's parameter wrapping is not stable across libaom revisions - (v3.13.3 wraps `ThreadData *const td, aom_reader *r,` onto one line). */ - if (getenv("EC_DP")) { - fprintf(stderr, - "EC_DP mi_row=%d mi_col=%d bsize=%d inter=%d chroma_ref=%d " - "skip_txfm=%d bw=%d bh=%d planes=%d is_intrabc=%d\\n", - xd->mi_row, xd->mi_col, (int)bsize, (int)is_inter_block(mbmi), - (int)xd->is_chroma_ref, (int)mbmi->skip_txfm, - (int)max_block_wide(xd, bsize, 0), - (int)max_block_high(xd, bsize, 0), num_planes, - (int)is_intrabc_block(mbmi)); - } - - if (!is_inter_block(mbmi)) {""" -assert anchor in s, "decode_token_recon_block prologue moved" -s = s.replace(anchor, new, 1) -open(path, "w").write(s) -print("EC_DP instrumented (decode_token_recon_block)") -PYDP