diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 58b0cd18..73f8fb07 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -442,6 +442,20 @@ pub(crate) fn rect_split_tx_hits() -> usize { RECT_SPLIT_TX_HITS.with(|c| c.get()) } +// How many HORZ/VERT intra strips actually predicted with filter intra +// (lane-rectsplit r1) -- the case `decode_block_rect` refused by name +// ("this decoder predicts square-only") until `predict_filter_intra` took +// `bw`x`bh`. +thread_local! { + static FILTER_INTRA_RECT_HITS: std::cell::Cell = + const { std::cell::Cell::new(0) }; +} + +/// Current value of [`FILTER_INTRA_RECT_HITS`]. +pub(crate) fn filter_intra_rect_hits() -> usize { + FILTER_INTRA_RECT_HITS.with(|c| c.get()) +} + // How many [`read_coeffs`] reads resolved a `tx_type` outside `TX_CLASS_2D` // (`V_DCT`/`H_DCT`, spec 5.11.39's `TxClass::Horiz`/`Vert`), across every // call on the current thread -- the same before/after counter pattern as @@ -3436,15 +3450,13 @@ fn decode_block_rect( // `uv_mode`, not the luma one. let smooth_neighbor_uv = is_smooth_mode(neighbours.above_uv_mode[c]) || is_smooth_mode(neighbours.left_uv_mode[r]); + // lane-rectsplit r1: `predict_filter_intra` now takes the block's own + // `bw`x`bh` (`av1_filter_intra_predictor_c` walks its 4x2 patches over a + // rectangle just as happily), so a `use_filter_intra` strip at this level + // predicts instead of refusing. The below-16x16 leaf arm + // (`decode_leaf_rect`) keeps the refusal: it has no gate of its own. if filter_intra.is_some() { - // `predict_filter_intra` (spec 7.11.2.3) is square-only in this - // decoder (`assert_eq!(dst.len(), side*side)`) -- a real symbol was - // already read above so the stream stays in sync, this only refuses - // the *pixel* decode of a rare case (`use_filter_intra` on a rect - // strip). - return Err(unsupported( - "filter intra on a HORZ/VERT strip (this decoder predicts square-only)", - )); + FILTER_INTRA_RECT_HITS.with(|c| c.set(c.get() + 1)); } let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED @@ -3830,7 +3842,7 @@ fn decode_leaf_rect( }; if depth != 0 { return Err(unsupported( - "a HORZ/VERT intra strip with a split transform (per-unit rect \ + "a HORZ/VERT intra strip below 16x16 with a split transform (per-unit rect \ prediction is not ported)", )); } @@ -4789,6 +4801,7 @@ impl PlaneBuf { left.as_deref(), corner, bw, + bh, &mut prediction, ); } else { @@ -4861,6 +4874,7 @@ impl PlaneBuf { left.as_deref(), corner, side, + side, &mut prediction, ); } else { diff --git a/crates/ec-av1/src/intra.rs b/crates/ec-av1/src/intra.rs index 818779d2..0d6f3ebe 100644 --- a/crates/ec-av1/src/intra.rs +++ b/crates/ec-av1/src/intra.rs @@ -726,37 +726,45 @@ const FILTER_INTRA_SCALE_BITS: u32 = 4; /// though this mode itself never reaches past its own `side` samples of /// either edge. /// +/// `bw`x`bh` is the block, not necessarily square (lane-rectsplit r1): +/// `av1_filter_intra_predictor_c` walks the same 4x2 patches over a +/// rectangular block, and `av1_filter_intra_allowed_bsize` genuinely offers +/// this mode on every HORZ/VERT strip whose sides are both <= 32 (16x8, +/// 8x16, 32x16, 16x32, ...), which the square-only assert refused before. +/// /// # Panics -/// Panics when `dst` is not `side * side` long, or `side` is not a multiple -/// of 4 (spec `av1_filter_intra_allowed_bsize` never offers this mode past -/// 32x32, and only on square blocks: 4, 8, 16 or 32). +/// Panics when `dst` is not `bw * bh` long, or `bw` is not a multiple of 4 +/// or `bh` not a multiple of 2 (spec `av1_filter_intra_allowed_bsize` never +/// offers this mode past 32x32). pub fn predict_filter_intra( mode: usize, above: Option<&[u16]>, left: Option<&[u16]>, corner: Option, - side: usize, + bw: usize, + bh: usize, dst: &mut [u16], ) { - assert_eq!(dst.len(), side * side, "the destination is the block"); - assert_eq!(side % 4, 0, "filter intra only offers 4/8/16/32"); - let edges = Edges::build(above, left, corner, side, side); + assert_eq!(dst.len(), bw * bh, "the destination is the block"); + assert_eq!(bw % 4, 0, "filter intra patches are 4 wide"); + assert_eq!(bh % 2, 0, "filter intra patches are 2 high"); + let edges = Edges::build(above, left, corner, bw, bh); let taps = &FILTER_INTRA_TAPS[mode]; // A (side+1)-square buffer: row 0 / column 0 hold the corner and the // above/left edges, `buffer[r+1][c+1]` the block's own sample at (r, c). - let mut buffer = vec![0i32; (side + 1) * (side + 1)]; - let at = |buffer: &[i32], r: usize, c: usize| buffer[r * (side + 1) + c]; + let mut buffer = vec![0i32; (bh + 1) * (bw + 1)]; + let at = |buffer: &[i32], r: usize, c: usize| buffer[r * (bw + 1) + c]; buffer[0] = edges.above(-1); - for c in 0..side { + for c in 0..bw { buffer[c + 1] = edges.above(c as i32); } - for r in 0..side { - buffer[(r + 1) * (side + 1)] = edges.left(r as i32); + for r in 0..bh { + buffer[(r + 1) * (bw + 1)] = edges.left(r as i32); } let mut r = 1; - while r < side + 1 { + while r < bh + 1 { let mut c = 1; - while c < side + 1 { + while c < bw + 1 { let p0 = at(&buffer, r - 1, c - 1); let p1 = at(&buffer, r - 1, c); let p2 = at(&buffer, r - 1, c + 1); @@ -769,16 +777,16 @@ pub fn predict_filter_intra( let (r_off, c_off) = (k >> 2, k & 3); let pr: i32 = taps[k].iter().zip(&p).map(|(t, s)| t * s).sum(); let value = round2(pr, FILTER_INTRA_SCALE_BITS).clamp(0, crate::decode::sample_max()); - let idx = (r + r_off) * (side + 1) + c + c_off; + let idx = (r + r_off) * (bw + 1) + c + c_off; buffer[idx] = value; } c += 4; } r += 2; } - for row in 0..side { - for col in 0..side { - dst[row * side + col] = at(&buffer, row + 1, col + 1) as u16; + for row in 0..bh { + for col in 0..bw { + dst[row * bw + col] = at(&buffer, row + 1, col + 1) as u16; } } } diff --git a/crates/ec-av1/src/refusal_inventory.rs b/crates/ec-av1/src/refusal_inventory.rs index 5c6a41a7..a1c24394 100644 --- a/crates/ec-av1/src/refusal_inventory.rs +++ b/crates/ec-av1/src/refusal_inventory.rs @@ -38,6 +38,7 @@ const REFUSALS: &[&str] = &[ "a coded (non-skip) HORZ_B/VERT_B rect strip below 16x16 (this decoder ports only the skip case at this size)", "a coded (non-skip) HORZ/VERT rect strip below 16x16 (this decoder ports only the skip case at this size)", "a coded HORZ/VERT strip whose chroma transform has no rect coefficient tables here", + "a HORZ/VERT intra strip below 16x16 with a split transform (per-unit rect prediction is not ported)", "a HORZ_A/HORZ_B/VERT_A partition below 16x16 (this decoder codes only the square arms, HORZ, VERT, VERT_B, and a clean split below 16x16)", "a 16x16 block whose true edge cuts through both axes needs a rectangular transform this decoder does not code yet", "a 16x16 inter block whose true edge cuts through both axes needs a rectangular transform this decoder does not code yet", diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 02d269af..2591a647 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -9504,6 +9504,204 @@ mod tests { ); } + /// 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 before = crate::decode::filter_intra_rect_hits(); + 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; + 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 = Command::new("ffmpeg") + .args([ + "-v", "error", "-f", "lavfi", "-i", &source, + // Same `hue=s=0` guard as gate (a): a real chroma gradient + // under the tx-size search hits a PRE-EXISTING square-path + // chroma defect that has nothing to do with this lane. + "-vf", "hue=s=0", + "-pix_fmt", "yuv420p", "-f", "yuv4mpegpipe", "-", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .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", + // The point of this gate. + "--enable-filter-intra=1", + // The square filter-intra gate's own way of making RD reach + // for filter intra at all: with the directional/smooth/paeth + // competitors off, DC_PRED + filter intra is what is left + // (recipe borrowed from + // `a_real_aomenc_filter_intra_stream_decodes_pixel_exact`; + // without them 20/20 streams picked filter intra zero times + // on a strip -- measured this round). + "--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 mut child = Command::new(aomenc_path()) + .args(&args) + .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) + .expect("writing y4m to aomenc"); + let out = child.wait_with_output().expect("aomenc failed to run"); + 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 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) + { + eprintln!( + "{NAME}: seed {seed} first luma mismatch at ({}, {}) ours={} ffmpeg={}", + i % width, + i / width, + frames[0].y[i], + ffmpeg_frames[0].y[i] + ); + } + 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})"); + matched += 1; + } + let fi_hits = crate::decode::filter_intra_rect_hits() - before; + 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-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