From 343ce49290fc5d734c064a92137992a767f1b3c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 2 Sep 2026 05:17:20 +0300 Subject: [PATCH] feat(av1): intra blocks in inter frames may split their luma transform An intra block inside an inter frame reads the same intra `tx_depth` symbol a key-frame block does; when it resolves below the block side the block codes one intra prediction plus one coefficient set PER transform unit (decode_block's multi-TU branch), with the inter frame's CDF state and the inter-frame intra mode syntax. read_block_tx_size now hands that leaf list back through the existing var-tx slot, so the caller's per-TU luma loop, record_split_luma write-back and per-TU deblock edges are the ones already proven for inter var-tx blocks. The 8x8 leaf's TX_4X4 2x2 grid has no per-TU intra loop and keeps a named refusal. Gate: a_real_aomenc_inter_sequence_with_a_split_transform_intra_block_ decodes_pixel_exact (+ 10bit arm) -- mandelbrot with a hard cut at frame 4 under --kf-min-dist=1000, 8 frames, all planes vs ffmpeg. --- crates/ec-av1/src/decode.rs | 213 ++++++++++++++++----- crates/ec-av1/src/refusal_inventory.rs | 6 +- crates/ec-av1/src/stream.rs | 254 +++++++++++++++++++++++++ 3 files changed, 421 insertions(+), 52 deletions(-) diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 45cd45b5..de90aaf8 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -1167,6 +1167,19 @@ pub(crate) fn palette_split_tx_hits() -> usize { PALETTE_SPLIT_TX_HITS.with(|c| c.get()) } +// lane-intrainter r1: intra blocks inside an INTER frame whose `tx_depth` +// symbol split their luma transform, bucketed by block side (8, 16, 32, 64) -- +// the gate's proof that the lifted path actually ran, per size. +thread_local! { + static INTRA_IN_INTER_SPLIT_TX_HITS: std::cell::Cell<[usize; 4]> = + const { std::cell::Cell::new([0; 4]) }; +} + +/// Current value of [`INTRA_IN_INTER_SPLIT_TX_HITS`], indexed 8/16/32/64. +pub(crate) fn intra_in_inter_split_tx_hits() -> [usize; 4] { + INTRA_IN_INTER_SPLIT_TX_HITS.with(std::cell::Cell::get) +} + thread_local! { /// A just-decoded palette-Y block's own predicted pixels /// (`side*side`, row-major, `colors[map[i]]`), consumed by @@ -9539,27 +9552,40 @@ fn read_block_tx_size( let tx = if is_inter { side.min(64) } else { - let resolved = read_tx_size( + read_tx_size( dec, cdfs, n, at_mi, side, Some(tx_size_context_txfm(n, at_mi, side)), - ); - if resolved != side { - // An intra block inside an inter frame whose `tx_depth` splits its - // luma transform needs the per-transform-unit intra prediction - // loop `decode_block` runs for a key frame; this path predicts the - // whole block at once, so refuse rather than mis-reconstruct. - return Err(unsupported( - "an intra block in an inter frame whose tx_depth splits its luma transform \ - (round 1)", - )); - } - resolved + ) }; set_txfm_ctxs(n, at_mi, tx, side_mi, side_mi, skip && is_inter); + if !is_inter && tx != side { + // lane-intrainter r1: an intra block inside an inter frame whose + // `tx_depth` split its luma transform codes exactly the key-frame + // split path's transform units (`decode_block`'s multi-TU loop), + // raster order over the block. Handed back in the same leaf shape the + // inter var-tx tree uses, so the caller's per-TU luma loop, the + // `record_split_luma` neighbour write-back and the per-TU deblock + // edges are the ones it already runs for a var-tx inter block. A + // caller that has no per-TU intra loop (the 8x8 leaf) refuses on + // seeing `Some` here. + let step = tx / MI; + let mut leaves = Vec::new(); + for row in (0..side_mi).step_by(step) { + for col in (0..side_mi).step_by(step) { + leaves.push((row, col, tx)); + } + } + INTRA_IN_INTER_SPLIT_TX_HITS.with(|c| { + let mut h = c.get(); + h[(side.trailing_zeros() as usize).saturating_sub(3).min(3)] += 1; + c.set(h); + }); + return Ok((tx, Some(leaves))); + } Ok((tx, None)) } @@ -15547,7 +15573,14 @@ fn decode_inter_block( } } - read_block_tx_size( + // lane-intrainter r1: an intra block in an inter frame reads the same + // `tx_depth` symbol a key-frame block does, and when it splits, the + // block codes one intra prediction + one coefficient set PER + // transform unit (`decode_block`'s multi-TU branch), not one for the + // whole block. The leaf list rides the existing `vartx_leaves` slot, + // whose tail already does the split-block neighbour write-back + // (`record_split_luma`) and the per-TU deblock edges. + vartx_leaves = read_block_tx_size( dec, cdfs, neighbours, @@ -15556,21 +15589,80 @@ fn decode_inter_block( (mi_cols as usize, mi_rows as usize), false, skip, - )?; + )? + .1; let reach = Reach::of(side, px, py, y.width, y.height); + let split_luma = vartx_leaves.is_some(); + if let Some(leaves) = vartx_leaves.clone() { + let reduced = REDUCED_TX_SET_INTER.with(std::cell::Cell::get); + for &(row, col, tx_px) in &leaves { + let tu_mi = (at_mi.0 + row, at_mi.1 + col); + let (tu_px, tu_py) = (px + col * MI, py + row * MI); + // A transform unit inside a block is not a block at that + // position (class from lane-palette2 r12): top-right / + // bottom-left availability is the block's, narrowed by the + // unit's own offset inside it. + let tu_reach = Reach::of_tu(side, side, col * MI, row * MI, tx_px, reach); + let tu_grid = if skip { + y.reconstruct( + tu_px, + tu_py, + tx_px, + mode, + 0, + tu_reach, + &vec![0i32; tx_px * tx_px], + None, + None, + false, + ); + vec![0i32; tx_px * tx_px] + } else { + // The unit's bsize is smaller than the block it sits in, + // so `txb_skip_ctx` is the neighbour-magnitude table, not + // the lone-TU 0 (`get_txb_ctx_general`). + let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_px / MI); + read_plane( + dec, + cdfs, + txbset_for(tx_px, reduced), + &default_scan(tx_px), + 0, + neighbours.around_mi(tu_mi, tx_px)[0], + mode, + mode, + 0, + tu_reach, + y, + tu_px, + tu_py, + tx_px, + tx_px, + base_q_idx, + None, + None, + Some(tu_skip_ctx), + false, + )? + }; + neighbours.record_mi_luma(tu_mi, tx_px, &tu_grid); + } + } if skip { - y.reconstruct( - px, - py, - side, - mode, - 0, - reach, - &vec![0i32; side * side], - None, - None, - false, - ); + if !split_luma { + y.reconstruct( + px, + py, + side, + mode, + 0, + reach, + &vec![0i32; side * side], + None, + None, + false, + ); + } let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side)); u.reconstruct( cpx, @@ -15601,28 +15693,35 @@ fn decode_inter_block( v_grid = vec![0i32; chroma_side * chroma_side]; } else { let around = neighbours.around(at, side); - luma_grid = read_plane( - dec, - cdfs, - luma_set_intra, - scan_luma, - 0, - around[0], - mode, - mode, - 0, - reach, - y, - px, - py, - side, - luma_tx, - base_q_idx, - None, - None, - None, - false, - )?; + luma_grid = if split_luma { + // Already coded and reconstructed unit by unit above; the + // block-level grid is only the neighbour write-back's input, + // which `record_split_luma` ignores for plane 0. + vec![0i32; side * side] + } else { + read_plane( + dec, + cdfs, + luma_set_intra, + scan_luma, + 0, + around[0], + mode, + mode, + 0, + reach, + y, + px, + py, + side, + luma_tx, + base_q_idx, + None, + None, + None, + false, + )? + }; let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side)); u_grid = read_plane( dec, @@ -17063,7 +17162,11 @@ fn decode_inter_block8( } } - read_block_tx_size( + // lane-intrainter r1: the 8x8 leaf's own intra `tx_depth` can only + // resolve to TX_4X4, whose 2x2 unit grid this leaf path has no + // prediction loop for (the >=16x16 square path above does). Refuse by + // name rather than mis-reconstruct. + if read_block_tx_size( dec, cdfs, neighbours, @@ -17072,7 +17175,15 @@ fn decode_inter_block8( (mi_cols as usize, mi_rows as usize), false, skip, - )?; + )? + .1 + .is_some() + { + return Err(unsupported( + "an 8x8 intra leaf in an inter frame whose tx_depth splits it into 4x4 \ + transform units", + )); + } let reach = Reach::of(SIDE, px, py, y.width, y.height); if skip { y.reconstruct( diff --git a/crates/ec-av1/src/refusal_inventory.rs b/crates/ec-av1/src/refusal_inventory.rs index 308975fa..e8578323 100644 --- a/crates/ec-av1/src/refusal_inventory.rs +++ b/crates/ec-av1/src/refusal_inventory.rs @@ -61,7 +61,11 @@ const REFUSALS: &[&str] = &[ "a reference picture whose height does not match this frame's own true size", "a show_existing_frame header naming an empty reference slot", "an inter var-tx tree with a leaf transform larger than 32x32", - "an intra block in an inter frame whose tx_depth splits its luma transform (round 1)", + // 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`); + // the 8x8 leaf's TX_4X4 2x2 grid is still refused here. + "an 8x8 intra leaf in an inter frame whose tx_depth splits it into 4x4 transform units", "an inter frame with no key frame before it", "an inter SB-level partition type other than NONE or SPLIT (this decoder's inter tile path recurses a superblock only as SPLIT)", "a masked compound 64x64 inter block (compound_type is inferred, not coded, at this size)", diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 73be302e..46642a8e 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -4180,6 +4180,260 @@ mod tests { ); } + /// 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); + } + + 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 = 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()) + .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 mut child = 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", + "-", + "-", + ]) + .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; + 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") + ); + } + /// 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-