diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 8ce7e8e3..1b09f752 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -1511,6 +1511,22 @@ pub(crate) fn rect_leaf_coeff_hits() -> usize { RECT_LEAF_COEFF_HITS.with(|c| c.get()) } +// lane-intrarect r1: how many intra-coded HORZ/VERT strips decoded on the +// INTER block path ([`decode_intra_rect_in_inter`]), per shape class -- +// [0] the superblock-level 64x32/32x64, [1] 32x16/16x32, [2] 16x8/8x16. +// Every one of them was the named refusal "an intra-coded HORZ/VERT strip +// needs rectangular intra prediction" before this round. +thread_local! { + static INTRA_RECT_IN_INTER_HITS: std::cell::Cell<[usize; 3]> = + const { std::cell::Cell::new([0; 3]) }; +} + +/// Current value of [`INTRA_RECT_IN_INTER_HITS`] for one shape class +/// (0 = 64x32/32x64, 1 = 32x16/16x32, 2 = 16x8/8x16). +pub(crate) fn intra_rect_strip_in_inter_hits(class: usize) -> usize { + INTRA_RECT_IN_INTER_HITS.with(|c| c.get()[class]) +} + // lane-rectx r5: how many times a NON-strip `kf_y_mode` reader // ([`decode_block`], [`decode_block_rect`], [`decode_block_rect64`]) took an // above/left mode from the mi-exact map that DIFFERS from its coarse 16x16 @@ -5150,6 +5166,175 @@ fn decode_rect_split( Ok(()) } +/// One intra-coded HORZ/VERT strip on the INTER block path (lane-intrarect +/// r1) -- the shape [`decode_inter_block`]'s intra arm refused by name +/// because it predicts squares only. Every pixel here goes through the rect +/// machinery the key-frame paths already prove: [`decode_rect_split`], which +/// at `depth == 0` is the unsplit strip as a single transform unit and +/// beyond it the per-unit walk of [`depth_to_tx_wh`]. +/// +/// What is genuinely different from [`decode_block_rect`] is the mode +/// syntax: on an inter frame an intra block reads `y_mode[size_group]` and +/// `uv_mode` (libaom `read_intra_block_mode_info`, decodemv.c:1065), never +/// the key frame's `kf_y_mode` above/left pair. This mirrors the square +/// intra-in-inter arm's own reads at the rect footprint, including its +/// inherited gaps -- no `use_filter_intra` symbol (every inter gate recipe +/// pins `--enable-filter-intra=0`; lane-fiinter owns that read for both the +/// square and this arm) and a nonzero luma angle delta refused by name. +/// +/// The strip's own neighbour records (luma per transform unit, chroma, skip +/// grid, deblock grid) are [`decode_rect_split`]'s; the caller adds the +/// inter-side bands and the mi map. +#[allow(clippy::too_many_arguments)] +fn decode_intra_rect_in_inter( + dec: &mut SymbolDecoder, + cdfs: &mut Cdfs, + neighbours: &mut Neighbours, + at: (usize, usize), + bw: usize, + bh: usize, + skip: bool, + allow_screen_content_tools: bool, + y: &mut PlaneBuf, + u: &mut PlaneBuf, + v: &mut PlaneBuf, + base_q_idx: u8, +) -> Result<()> { + let (r, c) = at; + let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI)); + // `size_group_lookup` (libaom common_data.h) and `bsize_to_tx_size_cat` + // (blockd.h) for the three 2:1 strip shapes: BLOCK_16X8 -> group 1 / + // cat 1, BLOCK_32X16 -> 2 / 2, BLOCK_64X32 -> 3 / 3 (the rectsplitx + // finding -- the category is NOT the same for every strip size). + // A 1:4 strip breaks that diagonal (BLOCK_32X8 is group 1 but cat 2), so + // it is refused by name rather than read from the wrong CDF row. + let (size_group, tx_cat) = match (bw.min(bh), bw.max(bh)) { + (8, 16) => (1usize, 1usize), + (16, 32) => (2, 2), + (32, 64) => (3, 3), + _ => { + return Err(unsupported( + "an intra-coded 1:4 (or other non-2:1) rect strip on the inter block path", + )) + } + }; + // [`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)", + )); + } + let mode = dec.symbol(&mut cdfs.y_mode[size_group]); + if mode >= 13 { + return Err(unsupported( + "an intra mode this decoder does not code (round 2)", + )); + } + if (V_PRED..=D67_PRED).contains(&mode) { + let angle = dec.symbol(&mut cdfs.angle_delta[mode - V_PRED]); + if angle != ANGLE_DELTA_ZERO { + return Err(unsupported( + "a nonzero angle delta (this encoder never writes one)", + )); + } + } + // `is_cfl_allowed` (spec 5.11.5) caps CFL at 32x32, so the + // superblock-level strip reads the no-CFL alphabet -- the same split + // [`read_intra_mode_rect`] makes for [`decode_block_rect64`]. + let cfl_allowed = bw.max(bh) <= 32; + let uv_mode = if cfl_allowed { + dec.symbol(&mut cdfs.uv_mode_cfl[mode]) + } else { + dec.symbol(&mut cdfs.uv_mode_no_cfl[mode]) + }; + if (9..=12).contains(&uv_mode) { + SMOOTH_UV_HITS.with(|h| h.set(h.get() + 1)); + } + let alpha = if cfl_allowed && uv_mode == UV_CFL_PRED { + Some(read_cfl_alphas(dec, cdfs)) + } else { + None + }; + let uv_predict_mode = if uv_mode == UV_CFL_PRED { + DC_PRED + } else { + uv_mode + }; + let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) { + DIRECTIONAL_UV_HITS.with(|h| h.set(h.get() + 1)); + read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED]) + } else { + 0 + }; + if angle_delta_uv != 0 { + UV_ANGLE_DELTA_HITS.with(|h| h.set(h.get() + 1)); + } + // The intra-edge filter type is the NEIGHBOUR's mode (libaom + // `get_filt_type`), luma's off the luma neighbours and chroma's off the + // chroma ones -- [`decode_block_rect`]'s own pair. + let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c); + let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode); + if smooth_neighbor { + SMOOTH_LUMA_HITS.with(|h| h.set(h.get() + 1)); + } + let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c); + let depth = if TX_SELECT_INTER.with(std::cell::Cell::get) { + let ctx = tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh); + match tx_cat { + 1 => dec.symbol(&mut cdfs.tx_size_cat1[ctx]), + 2 => dec.symbol(&mut cdfs.tx_size_cat2[ctx]), + _ => dec.symbol(&mut cdfs.tx_size_cat3[ctx]), + } + } else { + 0 + }; + if depth != 0 { + TX_DEPTH_HITS.with(|h| h.set(h.get() + 1)); + } + let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth); + let modes = RectStripModes { + skip, + mode, + angle_delta_y: 0, + uv_predict_mode, + angle_delta_uv, + alpha, + filter_intra: None, + smooth_neighbor, + smooth_neighbor_uv, + }; + decode_rect_split( + dec, + cdfs, + neighbours, + (mi_r, mi_c), + bw, + bh, + tx_w, + tx_h, + &modes, + y, + u, + v, + base_q_idx, + REDUCED_TX_SET_INTER.with(std::cell::Cell::get), + )?; + let class = match bw.max(bh) { + 64 => 0, + 32 => 1, + _ => 2, + }; + INTRA_RECT_IN_INTER_HITS.with(|h| { + let mut v = h.get(); + v[class] += 1; + h.set(v); + }); + Ok(()) +} + /// Decodes one true `bw`x`bh` `PARTITION_HORZ`/`PARTITION_VERT` intra strip /// (lane-intradisp r1, spec `decode_block` restricted to a 32x32 quadrant's /// two rect children). Only the `skip` case is supported: `skip`/`y_mode`/ @@ -13458,15 +13643,6 @@ fn decode_inter_block( maybe_read_cdef_idx(dec, r * SUB_MI as usize, c * SUB_MI as usize, skip); maybe_read_delta_q(dec, cdfs, r * SUB_MI as usize, c * SUB_MI as usize, side == 64, skip); maybe_read_delta_lf(dec, cdfs, r * SUB_MI as usize, c * SUB_MI as usize, side == 64, skip); - // lane-warp r5: see `reject_residual` -- a square-block decode of a - // HORZ_B strip is symbol-exact only for `skip` (no residual, no - // motion_mode/warp symbol), so gate here before any further read. - if reject_residual && !skip { - return Err(unsupported( - "a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual coding", - )); - } - let (has_above, has_left) = ( r > neighbours.tile_row0_mi / (SUB / MI), c > neighbours.tile_col0_mi / (SUB / MI), @@ -13482,6 +13658,21 @@ fn decode_inter_block( dec.debug_state().0 ); } + // lane-warp r5: see `reject_residual` -- a square-block decode of a + // HORZ_B strip is symbol-exact only for `skip` (no residual, no + // motion_mode/warp symbol). lane-intrarect r1 MOVED this gate from just + // after the `skip` read to here, past `is_inter` (class + // [[refusal-short-circuits-its-own-code]]: at the old place it refused + // 24/24 attempts of this lane's own gate before the intra arm below + // could run). An INTRA strip with its true `write_w`x`write_h` footprint + // now codes its residual rectangularly ([`decode_intra_rect_in_inter`]); + // an INTER one, and a strip decoded with square dimensions anyway, still + // cannot. + if reject_residual && !skip && (is_inter || (write_w == side && write_h == side)) { + return Err(unsupported( + "a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual coding", + )); + } if std::env::var_os("EC_AV1_TELL").is_some() { eprintln!( "TELL mi_row={} mi_col={} label=post_is_inter skip_mode={skip_mode} skip={skip} is_inter={is_inter} tell={} range={}", @@ -15255,10 +15446,51 @@ fn decode_inter_block( // already-square-predicted buffer). Named refusal instead of a // silently wrong square-shaped intra prediction. if write_w != side || write_h != side { - return Err(unsupported( - "an intra-coded HORZ/VERT strip needs rectangular intra prediction \ - this decoder does not code yet", - )); + // lane-intrarect r1: the strip decodes through its own rect + // machinery ([`decode_intra_rect_in_inter`] -> the key-frame + // paths' [`decode_rect_split`]) instead of refusing. That call + // already writes everything the shared tail below would for a + // square block EXCEPT the inter-side bands and the mi map, so + // this arm returns rather than falling through (a second + // `record_rect`/`fill_lf_grid_rect` at block granularity would + // overwrite the per-transform-unit records it just made). + decode_intra_rect_in_inter( + dec, + cdfs, + neighbours, + at, + write_w, + write_h, + skip, + allow_screen_content_tools, + y, + u, + v, + base_q_idx, + )?; + let (mi_r0, mi_c0) = (r * SUB_MI as usize, c * SUB_MI as usize); + for dr in 0..write_h / MI { + for dc in 0..write_w / MI { + grid.set( + mi_r0 + dr, + mi_c0 + dc, + MiInfo { + is_inter: false, + ref_frame: -1, + ref_frame1: None, + mv1: None, + mv: (0, 0), + is_new_mv: false, + size: write_w / MI, + size_h: write_h / MI, + is_global_mv0: false, + is_global_mv1: false, + }, + ); + } + } + neighbours.record_inter_rect(at, write_w, write_h, skip, false, 0, [3, 3], skip_mode); + return Ok(()); } let mode = dec.symbol(&mut cdfs.y_mode[size_group]); if mode >= 13 { diff --git a/crates/ec-av1/src/refusal_inventory.rs b/crates/ec-av1/src/refusal_inventory.rs index ce71ee0f..109769d7 100644 --- a/crates/ec-av1/src/refusal_inventory.rs +++ b/crates/ec-av1/src/refusal_inventory.rs @@ -65,7 +65,11 @@ const REFUSALS: &[&str] = &[ "a masked compound 64x64 inter block (compound_type is inferred, not coded, at this size)", "an inter partition below 16x16 other than SPLIT (16x8/8x16 rect inter leaves are not coded yet)", "an intra mode this decoder does not code (round 2)", - "an intra-coded HORZ/VERT strip needs rectangular intra prediction this decoder does not code yet", + // 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 1:4 (or other non-2:1) rect strip on the inter block path", // Lifted for the 16x8/8x16 leaf by lane-fistrip; still live one level // down, at the 4x8/8x4 sub-8 leaf (lane-tx4x8's `decode_leaf_rect8`). "filter intra on a HORZ/VERT strip (this decoder predicts square-only)", diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 56723c0d..3fc06781 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -3583,6 +3583,324 @@ mod tests { 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); + } + + 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 = 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()) + .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 mut child = 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", + "-", + "-", + ]) + .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_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") + ); + assert!( + shapes.iter().filter(|n| **n > 0).count() >= 2, + "{NAME} ({bit_depth}-bit): fewer than two intra-rect shape classes fired over \ + {compared} compared streams (64-level={} 32-level={} 16-level={})", + shapes[0], + shapes[1], + shapes[2] + ); + } + fn tx_select_inter_gate(bit_depth: u32) { if !have_ffmpeg() { eprintln!( diff --git a/lanes/intrarect-r1.report.md b/lanes/intrarect-r1.report.md index 50724575..945349ae 100644 --- a/lanes/intrarect-r1.report.md +++ b/lanes/intrarect-r1.report.md @@ -1,125 +1,86 @@ -# lane-intrarect r1 report +# lane-intrarect r1 — intra rect strips on the inter block path -VERDICT: DONE -- `intra::predict`/`Edges` are rect-capable (`bw != bh`), -C-verified for 8 rect shapes across DC/SMOOTH/PAETH + 17 directional angles -x {enable_edge_filter, smooth_neighbor}; full lib suite 224/224 (was -223/223, +1 the new C-verify test), square behaviour unchanged; tile -dispatch still refuses rect/AB partitions. +Branch `lane-intrarect` off `lane-rectsplitx` cbf8ffd. **Result: code landed, gate RED +(one real residual defect, evidence below). The lane does not merge in this state.** ## What changed -`crates/ec-av1/src/intra.rs`: -- `Edges::build`, `predict`, `directional`, `dc` all take `(bw, bh)` instead - of one `side`. `Edges::build`'s extension length is `bw + bh` (the reach - `av1_dr_prediction_z1_c`'s `max_base_x` and `z3_c`'s `max_base_y` both use, - libaom `reconintra.c`). -- `dc()`: exact `(sum + count/2) / count` stays for `bw == bh` (bit-identical - square path); a new `dc_rect_multiplier` ports `dc_predictor_rect`'s - multiply-shift approximate divide for `bw != bh` -- derived from `bw + bh`'s - odd factor (per libaom's own comment: shift until odd, `d == 3` for every - 1:2 ratio, `d == 5` for every 1:4 one), not tabulated. -- `SMOOTH_PRED`/`SMOOTH_V_PRED`/`SMOOTH_H_PRED`: width and height now index - separate `SM_WEIGHTS` rows (`smooth_weights + bw - 4` / `+ bh - 4` in the - source), matching `smooth_predictor`'s real per-axis split. -- `directional()`: `bw + bh` reach throughout (was `2 * side`); the edge - filter/upsample `n_px` extensions are CROSS-axis -- above's run-past - extension is `bh`, left's is `bw` (`reconintra.c`'s `txwpx`/`txhpx` argument - swap between the above and left calls). This is the same - scan-weights-cross-axis class the ledger already has two instances of. -- **Bug found and fixed in the same diff**: `intra_edge_filter_strength` was - missing the `blk_wh <= 12` branch present in libaom. No square block's - `bw + bh` ever lands in `9..=12` (sides are 4/8/16/32/64, sums are always - even and >= 8), so this was silently unreachable before this lane; a rect - block like 4x8 (`blk_wh == 12`) hits it. Ported verbatim. -- 21 call sites (`encode.rs` x4, `decode.rs` x2, `predict_filter_intra`'s own - internal `Edges::build` call) all pass `(side, side)` -- zero behaviour - change there, proven by the full suite staying green. -- `predict_filter_intra` (filter-intra) is untouched and stays square-only: - spec `av1_filter_intra_allowed_bsize` never offers it on a rect block, so - there is nothing to widen -- correctly out of scope, not a gap. -## C-verification (what's C-verified vs transcribed-only) -`lanes/intrarect_dump.c`: standalone C, **not linked against the built -oracle** (linking libaom's actual `.o`s pulled in RTCD/aom_config -dependencies past this lane's budget) -- an independent hand-transcription -of `aom_dsp/intrapred.c`'s `dc_predictor_rect`/`smooth_predictor`/ -`paeth_predictor` and `av1/common/reconintra.c`'s -`av1_dr_prediction_z1/z2/z3_c` + `intra_edge_filter_strength` + -`av1_use_intra_edge_upsample` + `av1_filter_intra_edge_c` + -`av1_upsample_intra_edge_c`, read fresh from `~/.cache/aom-oracle/src` this -round (same independent-transcription pattern `lanes/wedge_dump.c` used, -per the charter's shared-oracle-blindness note). +- `crates/ec-av1/src/decode.rs` (`decode_intra_rect_in_inter`, new, right before + `decode_block_rect`): an intra-coded HORZ/VERT strip on the inter block path reads its + mode info with the INTER frame's own intra syntax (`y_mode[size_group]` / + `uv_mode_cfl|uv_mode_no_cfl` / cfl alphas / uv angle delta — mirroring the square + intra-in-inter arm, including its inherited gaps: no `use_filter_intra` symbol, nonzero + luma angle delta refused), its tx depth from the shape's own `bsize_to_tx_size_cat` + (16x8 -> cat1, 32x16 -> cat2, 64x32 -> cat3, ctx from `tx_size_context_rect`), then hands + every pixel to `decode_rect_split` — the same machinery the key-frame rect paths use, which + at `depth == 0` is the unsplit single-transform strip. +- `crates/ec-av1/src/decode.rs` (`decode_inter_block`, the `write_w != side` arm): calls it + instead of refusing, then writes the mi map (`is_inter: false`, rect `size`/`size_h`) and + `record_inter_rect`, and returns — `decode_rect_split` already wrote the luma per-TU, + chroma, skip and deblock records the shared tail would otherwise stamp at block + granularity. +- `crates/ec-av1/src/decode.rs`: the `reject_residual && !skip` refusal MOVED from just after + the `skip` read to just after `is_inter` (class `refusal-short-circuits-its-own-code`) and + narrowed to `is_inter || (write_w == side && write_h == side)`. MEASURED: at its old place + it refused 24/24 attempts of this lane's own gate before the intra arm could run. +- `crates/ec-av1/src/refusal_inventory.rs`: lifted "an intra-coded HORZ/VERT strip needs + rectangular intra prediction this decoder does not code yet"; added the residue + "an intra-coded 1:4 (or other non-2:1) rect strip on the inter block path" (a 1:4 strip + breaks the size-group/tx-cat diagonal the 2:1 shapes share, so it is refused rather than + read from the wrong CDF row). +- `crates/ec-av1/src/stream.rs`: gate + `a_real_aomenc_inter_sequence_with_an_intra_rect_strip_decodes_pixel_exact` (+ `_10bit`), + 45 attempts sweeping seed x `--cpu-used` 0..4 x `--cq-level` {30,20,12}, per-shape counter + `decode::intra_rect_strip_in_inter_hits(0|1|2)`, every frame Y/U/V compared, no SKIP on a + decode error or mismatch. -**C-verified** (checksum-matched, 568 cases, `intra::tests::rect_predictors_match_c_dump`): -- `DC_PRED` (both the exact-divide and `dc_predictor_rect` approximate-divide - paths, since the test only exercises `bw != bh` shapes here) -- `SMOOTH_PRED`, `PAETH_PRED` -- All eight directional modes (`V_PRED`, `H_PRED`, `D45`/`D67`/`D113`/`D135`/ - `D157`/`D203_PRED`) across z1/z2/z3, both `enable_edge_filter` states, both - `smooth_neighbor` states, for shapes 8x4/4x8/16x8/8x16/4x16/16x4/32x16/16x32 - (both 1:2 and 1:4 ratios, both orientations) +## Recipe deviations from the charter (each measured, not chosen) -**Transcribed-only, not independently C-verified this round**: -- `SMOOTH_V_PRED`/`SMOOTH_H_PRED` -- same weight-split code path as - `SMOOTH_PRED` (which is verified), not separately dumped -- `filter_intra_edge_corner`'s rect gate (`reach >= 24`) -- exercised by the - dump's angle/shape sweep whenever it applies, but not isolated as its own - case -- The `n_top`/`n_left` < full-reach path (a block against the frame edge with - fewer real neighbour samples than `bw`/`bh`) -- the dump feeds full-length - synthetic neighbours throughout; this is unchanged pre-existing - `Edges::build` repeat-extension logic, not something this lane's widening - touches structurally, and it's exercised (for squares) by the full suite +- `--min-partition-size=8` -> `16`: at 8, 24/24 attempts stop at sub-16 AB refusals + ("a HORZ_A/HORZ_B/VERT_A partition below 16x16", "a coded (non-skip) HORZ_B/VERT_B rect + strip below 16x16") — other lanes' surfaces. +- `--enable-tx-size-search=1` -> `0`: with it 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`). Consequence: **the SPLIT rect arm on + the inter path is wired but UNGATED**; only the unsplit strip is exercised. +- Content: the charter's mandelbrot + overlay cut never produced an intra rect strip (every + rect strip in those streams was INTER, refused by lane-inter4's wall). The fixture that + works is a FAST-ZOOM mandelbrot (`end_scale=0.004:end_pts=8`), where consecutive frames + share almost no content so aomenc codes blocks intra inside inter frames. +- `--cpu-used` swept, not fixed: at 4 this content yields no rect partition at all + (class `gate-preset-gates-the-feature`); at 0 aomenc emits AB partitions the tile path + refuses (it ignores `--enable-ab-partitions=0`). Only cpu-used 1..3 both decode and produce + rect strips. -## Gate ladder run -(a) full lib suite: `EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --release ---lib -- --nocapture` -- 224 passed, 0 failed, 17 ignored (was 223/0/17 -before this lane's own test; no regression, no `--skip` needed -- the -charter's `--skip a_real_aomenc_stream_with_interintra_wedge` workaround is -stale per the task's own update, whole suite runs in ~70s). -(b)/(c) the 14-pin default list and the named intra gates -(`filter_intra`/`directional_chroma`/`tx_select`/`intra_with_deblocking`) are -all inside that same full-suite run (test names visible in the tail output: -`a_real_aomenc_stream_with_...` for all of them), all green. +## Gate result — RED -## Commits (this worktree, lane-intrarect branch, not pushed) -- `bade5c8` feat(av1): widen intra::predict/Edges to rect (bw != bh) -- `6813a8a` test(av1): C-verify rect intra predictors against an independent transcription +Command: +`CARGO_TARGET_DIR=$HOME/.cache/cargo-target-intrarect EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib -j3` -## Deviations from the charter -- Skipped the charter's stale `--skip a_real_aomenc_stream_with_interintra_wedge` - per the task's explicit override. -- Built the C harness as a standalone transcription rather than linking the - oracle's real `.o` files, matching `wedge_dump.c`'s existing pattern - (charter explicitly offers this as the "OR better" option) -- linking the - real oracle intrapred code would need RTCD/aom_config plumbing not worth - the budget for this lane. +EVIDENCE: $HOME/.cache/intrarect-suite.log | 45-attempt aomenc sweep, both depths, every frame Y/U/V vs ffmpeg | 8-bit seed 69 (`--cpu-used=2 --cq-level=12`) fired 1 intra rect strip at the 32x16/16x32 shape and frame 5 Y differs: first diff (88,58) got 97 want 98, 670 samples, max |diff|=3, rows 58..95. 10-bit seed 78 (`--cpu-used=1 --cq-level=20`) fired 1 strip at the same shape: frame 5 Y first diff (80,58) got 393 want 394, 533 samples, max |diff|=8, rows 58..95. -## Next lane -Flip the KEY-frame tile dispatch (`decode.rs` ~3624/~3841) to accept the -17/40 refused rect/AB partition attempts now that the predictor underneath -is rect-capable -- out of scope for r1 by charter, unchanged this round. +Suite: `335 passed; 2 failed (this lane's two new gates); 29 ignored` — nothing else regressed, +`refusal_inventory` and `gate_coverage` green with the moved refusal and the lifted string. -## Cross-provider verification (opus, 2026-08-30) — PASS, with two corrections +Shape coverage over the sweep: 32x16/16x32 fired (1 stream per depth); **16x8/8x16 never fired** +(sub-16 partitions on the inter path refuse earlier) and **64x32/32x64 is unreachable on this +branch at all** — the inter tile path refuses any SB-level partition other than NONE/SPLIT, so +a superblock-level intra strip cannot be produced. The charter's "at least two shapes" bar is +therefore not reachable here; the assert is left as-is (>= 2) and currently fails on the +pixel compare first. -All 6 claims CONFIRMED against pinned libaom v3.13.3: square paths provably -bit-identical (every `side` -> `(bw,bh)` substitution audited term by term); -`dc_predictor_rect`'s 0x5556/0x3334 multiply-shift and the `sum + ((bw+bh)>>1)` -dividend exact (intrapred.c:236-279); smooth weight rows not transposed -(intrapred.c:89-105); directional edge filter/upsample extension correctly -CROSS-axis (reconintra.c:1213-1240); the C harness genuinely independent (its -own `+bw-4` weight layout, structurally different from our `[bw..bw*2]` spec -layout, so a layout error cannot cancel out) covering 568 rect cases. +## Residue -CORRECTIONS to this report's earlier claims: -1. "Fixed a latent `intra_edge_filter_strength` bug (missing `blk_wh<=12` - branch)" is OVERSTATED. The branch does exist in reconintra.c:996-997, but - it is behaviourally IDENTICAL to its `<=16` successor (both `d >= 40 -> - strength 1`), so adding it changes no output for any input. It is a - fidelity-of-transcription improvement with zero behavioural effect, not a - bug fix. -2. The harness's uncovered modes are V_PRED and H_PRED **in addition to** the - SMOOTH_V/SMOOTH_H this report named. All four are transcribed-only; the - verifier hand-checked SMOOTH_V/H against intrapred.c:115-172 (correct), and - V/H are axis-free single-edge reads carrying no rect risk. -Also uncovered: `Edges::build`'s repeat-extension branch is never exercised at -rect reach (the harness always supplies a full bw+bh neighbour run). +- fix-now (r2): the pixel defect above. Frames 0..4 are exact and the magnitudes are small + (<= 3 at 8 bit), so this is NOT an entropy desync — the tile stays in sync. The diff band + starts at row 58 and runs to the frame bottom, i.e. the strip's own bottom deblock band + (edge at y=64 filters rows 57..70) plus everything predicted below it. Look at the deblock + records for a rect intra strip on the inter path first (`decode_rect_split`'s + `fill_lf_grid_rect` + the `record_inter_rect` the new call site adds), then at prediction; + entropy is cleared by construction. +- deferred(the square intra-in-inter tx-split refusal in `read_block_tx_size`) — the split + rect arm on the inter path is unproven. +- deferred(lane-inter4 merge) — 64x32/32x64 and the 16x8/8x16 shape need the inter-side rect + work; lane-inter4's `coded_rectangular_residual` gate is NOT on this branch and was not + un-ignored. +- accepted — 1:4 strips refuse by name on this path.