diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index da6b5350..fae5ee61 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -2521,6 +2521,25 @@ thread_local! { const { std::cell::Cell::new([0; 3]) }; } +// lane-t900 r21: rect intra strips inside an inter frame that read the +// screen-content palette syntax (`allow_screen_content_tools` set and the +// strip's own shape admitted by `palette_bsize_ctx_wh`) -- the site a blanket +// refusal used to guard, so this counter is what keeps its witness gate +// non-vacuous. +thread_local! { + static INTRA_RECT_IN_INTER_SCREEN_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Current value of [`INTRA_RECT_IN_INTER_SCREEN_HITS`]. +pub(crate) fn intra_rect_in_inter_screen_hits() -> usize { + INTRA_RECT_IN_INTER_SCREEN_HITS.with(std::cell::Cell::get) +} + +/// Resets [`INTRA_RECT_IN_INTER_SCREEN_HITS`] before a decode. +pub(crate) fn reset_intra_rect_in_inter_screen_hits() { + INTRA_RECT_IN_INTER_SCREEN_HITS.with(|c| c.set(0)); +} + /// Current value of [`INTRA_RECT_IN_INTER_SPLIT_TX_HITS`], indexed by tx depth. pub(crate) fn intra_rect_in_inter_split_tx_hits() -> [usize; 3] { INTRA_RECT_IN_INTER_SPLIT_TX_HITS.with(std::cell::Cell::get) @@ -7852,15 +7871,14 @@ fn decode_intra_rect_in_inter( "an intra-coded {bw}x{bh} block on the inter block path (no size-group/tx-category row for that shape here)" ))); }; - // [`read_intra_mode_rect`]'s own refusal: palette/intrabc syntax is - // consumed for square blocks only, so a strip in a screen-content frame - // would skip symbols the encoder wrote. - if allow_screen_content_tools { - return Err(unsupported( - "a HORZ/VERT intra strip in a screen-content frame (palette syntax \ - is consumed for square blocks only)", - )); - } + // lane-t900 r21: this arm used to refuse EVERY rect strip of a + // screen-content frame ("palette syntax is consumed for square blocks + // only"). It is not: [`read_intra_mode_rect`] generalised the palette read + // to rect blocks on the key-frame path, and the 1:4 arm below goes through + // it, while the 2:1 reader inlined further down now codes the same syntax + // itself. A real `--tune-content=screen` inter stream reached this refusal + // on 8x16 / 16x8 strips (gate + // `a_real_aomenc_screen_inter_sequence_codes_palette_syntax_on_rect_intra_strips`). // lane-intra14 r1: a 1:4 strip decodes through the very readers the KEY // FRAME path already proves for this shape ([`decode_block_rect4`] at the // 32 level, [`decode_block_rect64`] at 64 -- both already handle the 1:4 @@ -7991,6 +8009,32 @@ fn decode_intra_rect_in_inter( UV_ANGLE_DELTA_HITS.with(|h| h.set(h.get() + 1)); INTRA_IN_INTER_ANGLE_DELTA_UV_HITS.with(|h| h.set(h.get() + 1)); } + // `read_palette_mode_info` (spec 5.11.13), in the position + // `read_intra_block_mode_info` writes it: after the chroma mode and + // before `filter_intra`. lane-t900 r21: a `--tune-content=screen` inter + // frame writes `palette_y_mode`/`palette_uv_mode` for every block whose + // shape [`palette_bsize_ctx_wh`] admits, intra strips included, so + // skipping the syntax here desynced the tile at the strip's own symbol. + // No block this decoder produces can USE a palette (the arms below refuse + // by name), so the neighbour mode context is 0 and there is no cache -- + // the same stand-in [`read_intra_mode_rect`] uses when its caller has none. + if allow_screen_content_tools + && let Some(bsize_ctx) = palette_bsize_ctx_wh(bw, bh) + { + INTRA_RECT_IN_INTER_SCREEN_HITS.with(|c| c.set(c.get() + 1)); + if mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][0]) != 0 { + return Err(unsupported( + "a block that actually uses a palette (Y) -- reconstruction is out of scope", + )); + } + // A 2:1 strip of at least 8x8 is always a chroma reference, so + // `read_palette_mode_info`'s `xd->is_chroma_ref` guard holds here. + if uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[0]) != 0 { + return Err(unsupported( + "a block that actually uses a palette (UV) -- reconstruction is out of scope", + )); + } + } // lane-fiinter (merged on main for the square intra-in-inter arm): // `read_filter_intra_mode_info` is the tail of // `read_intra_block_mode_info`, after the palette syntax (refused whole @@ -14351,6 +14395,81 @@ fn sub_tx_size_map_matches_libaom() { } } +/// The domain of var-tx leaf sizes, enumerated against the two refusals that +/// name a leaf "larger than 32x32" / "larger than 64x64". +/// +/// [`read_var_tx_size`] emits a leaf in exactly three places, and each one is +/// either the unit it was entered with or a `sub_tx_size_map` step below it: +/// the depth cap, the `!split` return, and libaom's `sub_txs == TX_4X4` early +/// return. So the leaf set reachable from an entry unit is that unit plus the +/// chain of `sub_tx_size_map` steps under it, capped at `MAX_VARTX_DEPTH` -- +/// which this test enumerates, and over which no leaf is ever larger than the +/// entry. +/// +/// That closes both refusals: +/// +/// * [`read_block_tx_size_rect`]'s `bw.max(bh) > 64` branch enters every unit +/// at TX_64X64 (`max_txsize_rect_lookup[BLOCK_128X64]`), so "larger than +/// 64x64" names a leaf the tree cannot produce; +/// * [`read_block_tx_size`] enters at `side.min(64)` with a ceiling of 32 +/// below the 128 root. The only entry that exceeds that ceiling is 64x64, +/// reached only when `side == 64`, and then the block is ONE unit whose only +/// above-ceiling leaf is the whole 64x64 unit itself -- which is the `single` +/// case the refusal is guarded by. +#[test] +fn a_var_tx_tree_never_presents_a_leaf_larger_than_the_unit_it_entered() { + // 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)); + if depth == MAX_VARTX_DEPTH { + return; + } + let sub = sub_tx_size_map(entry.0, entry.1); + if sub == (4, 4) { + out.push((depth + 1, 4, 4)); + return; + } + reachable(sub, depth + 1, out); + } + + for entry in [(4, 4), (8, 8), (16, 16), (32, 32), (64, 64)] { + let mut leaves = Vec::new(); + reachable(entry, 0, &mut leaves); + for (depth, w, h) in &leaves { + assert!( + w.max(h) <= &entry.0.max(entry.1), + "a {}x{} unit reaches a {w}x{h} leaf at depth {depth}", + entry.0, + entry.1 + ); + } + // Above-ceiling leaves of a 64x64 entry: the entry itself, at depth 0. + if entry == (64, 64) { + let above: Vec<&(usize, usize, usize)> = + leaves.iter().filter(|(_, w, h)| w.max(h) > &32).collect(); + assert_eq!(above, [&(0usize, 64usize, 64usize)], "64x64 entry, leaves above 32"); + } + } + + // The entry size and ceiling each caller uses, over the block sides that + // reach them (`read_block_tx_size`'s square path; the 128-root rect path + // enters at a fixed 64). + for side in [8usize, 16, 32, 64, 128] { + let max_tx = side.min(64); + let ceiling = if side > 64 { 64 } else { 32 }; + let units = (side / max_tx) * (side / max_tx); + if max_tx <= ceiling { + continue; + } + assert_eq!( + (side, units), + (64, 1), + "a {side}px block enters var-tx at {max_tx} over a ceiling of {ceiling} in \ + {units} units -- an above-ceiling leaf there would NOT be the `single` case" + ); + } +} + /// `read_var_tx_size` (spec 5.11.17, libaom `decodeframe.c` /// `read_tx_size_vartx`): the recursive `txfm_split` tree of one /// max-transform-sized unit of an inter block, collecting the resolved leaf diff --git a/crates/ec-av1/src/refusal_inventory.rs b/crates/ec-av1/src/refusal_inventory.rs index 8ca60f13..c066c43b 100644 --- a/crates/ec-av1/src/refusal_inventory.rs +++ b/crates/ec-av1/src/refusal_inventory.rs @@ -103,8 +103,17 @@ const REFUSALS: &[&str] = &[ // 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)", - // The same arm's screen-content gate: palette/intrabc syntax is consumed - // for square blocks only, so a strip in such a frame would skip symbols. + // 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 + // refuses is a 16x4/4x16 strip and a 128-root half, neither of which is + // palette-eligible (`palette_bsize_ctx_wh` wants `8 <= min`, `max <= 64`) + // and neither of which has a witness stream yet. "a HORZ/VERT intra strip in a screen-content frame (palette syntax is consumed for square blocks only)", "warp prediction with a scaled reference (superres, unimplemented)", "an 8x8 partition leaf under a scaled reference (superres, unimplemented)", @@ -166,6 +175,47 @@ const PROVEN: &[(&str, &str)] = &[ "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", ), + // 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", + ), + ( + "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", + ), + // 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", + ), + ( + "an INTER 32x32 partition type this decoder does not code (value={part32})", + "every_partition_value_of_an_enumerated_alphabet_has_an_arm", + ), + ( + "a 128x128 superblock partition value outside the 8-symbol alphabet", + "every_partition_value_of_an_enumerated_alphabet_has_an_arm", + ), + ( + "a bit depth of 12 (this decoder is gated at 8 and 10 only: warp/MC/wiener rounding shifts change at 12-bit and no 12-bit gate exists)", + "a_twelve_bit_sequence_header_is_refused_by_name", + ), + ( + "intra block copy on a HORZ/VERT/1:4 rect intra strip (reconstruction is not ported at this shape)", + "a_real_aomenc_screen_key_frame_reads_use_intrabc_on_rect_strips", + ), ]; /// Gates whose `Err` arm turns a decode failure into a printed SKIP rather than @@ -345,12 +395,127 @@ mod tests { ); } + /// 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() { + const 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 refusal in the fallback arm, the alphabet its CDF codes) + let blocks: [(&str, usize); 3] = [ + ("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), + ]; + // A pattern's own tokens, plus every value of an inclusive range + // (`p if (PARTITION_HORZ_A..=PARTITION_VERT_B).contains(&p)` is four + // arms in one). + let covered = |head: &str| -> BTreeSet { + let mut out = BTreeSet::new(); + let idx: Vec = head + .split(|c: char| !(c.is_ascii_alphanumeric() || c == '_')) + .filter_map(|tok| 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 + }; + + let src = include_str!("decode.rs"); + 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(covered(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| NAMES[*v]).collect::>() + ); + } + assert_eq!( + found, + blocks.len(), + "not every enumerated partition refusal was located in decode.rs" + ); + } + /// Every entry of [`PROVEN`] must still name a live refusal and a test /// that exists, and the count it prints is the inventory's numerator. #[test] fn every_proven_refusal_names_a_test_that_exists() { let found = decode_path_refusals(); - let sources = [include_str!("stream.rs"), include_str!("decode.rs")]; + let sources = [ + include_str!("stream.rs"), + include_str!("decode.rs"), + include_str!("refusal_inventory.rs"), + ]; for (reason, gate) in PROVEN { assert!( found.contains(*reason), diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index d23a281b..3553e151 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -30179,6 +30179,143 @@ mod tests { ); } + /// 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); + } + + 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 = 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()) + .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 mut child = 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", "-", "-"]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("aomenc failed to start"); + child + .stdin + .take() + .expect("aomenc stdin") + .write_all(&y4m.stdout) + .or_else(|e| match e.kind() { + std::io::ErrorKind::BrokenPipe => Ok(()), + _ => Err(e), + }) + .expect("writing y4m to aomenc"); + let out = child.wait_with_output().expect("aomenc failed to run"); + 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" + ); + } + /// 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