From 332f251105237ec952a381f49128aa843700d539 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Thu, 17 Sep 2026 04:07:18 +0300 Subject: [PATCH] vp9kf: tile-ROW streams decode byte-exact -- MI-aligned extents, frame-scoped contexts Tile-row streams (log2_tile_rows > 0) now decode byte-exact: tr.ivf and tr2.ivf 3 of 3 frames, previously 0 of 3. Seven fixes, each ported from libvpx with its line: 1. tx probabilities come from the frame's FrameContext tables (get_tx_probs, vp9_pred_common.h:173), not the TX_* const defaults. 2. the tx-size context carries libvpx's "if (!has_above) above_ctx = left_ctx" fallback (vp9_pred_common.h:156-170). 3. above availability is gated on the FRAME (mi_row != 0, set_mi_row_col vp9_onyxc_int.h:430), not on the tile-row start; tile_row_start is gone from the decode chain. 4. ectx/mi are frame-scoped: allocated once per frame, above cleared once, left per SB row (vp9_decodeframe.c:2079-2083 / :2260-2261). 5. the above entropy/partition arrays are sized mi_cols_aligned_to_sb, closing a pre-existing OOB panic at widths not a multiple of 8 (decode.rs:767 on a 1366-wide frame; the baseline panicked too). 6. intra edge extension is a branch-for-branch port of vp9_reconintra.c:300-394: the extend-vs-direct decision comes from mb_to_bottom_edge/mb_to_right_edge, the extension length from the MI-ALIGNED buffer extent (vp9_alloc_frame_buffer sets y_width = (width+7)&~7 -- yv12config.c:173-174,250-251), and the arithmetic is isize, closing an "attempt to subtract with overflow" at intra.rs:72 on 320x242. 7. the chroma loop filter takes no plane-width bound: all five uv_w column clamps are gone, matching vp9_filter_block_plane_ss11's unclamped MI_BLOCK_SIZE>>1 groups (vp9_loopfilter.c:1394, :313-399) which write into the padded plane. At 1366 wide the last chroma group overhangs the visible plane by 4, so every clamped edge was dropped: luma stayed byte-exact while chroma was off by one (U 4/5/6, V 37/33/16). Matrix (scratch_realsweep, 3 frames each): h242, h1082, h1082tr, h1082trc, tr, tr2, t1080, t1080-single, single1080, w1366, w1366tc and the 320x240 tile0 sweep are all byte-exact. Still unexercised: odd width x odd height x tile ROWS -- the encoder declines -tile-rows at those heights. Verified by an independent reviewer with revert-alone discrimination: a visible-length extent fails h242/h1082, a 64-aligned extent fails the 1080p fixtures, the MI-aligned extent passes all; restoring the uv_w clamps reproduces the chroma-only residue exactly. cargo test -p ec-vp9 is green and cargo check prints the 5 baseline warnings. --- crates/ec-vp9/src/decode.rs | 104 ++++++++----- crates/ec-vp9/src/intra.rs | 114 +++++++++----- crates/ec-vp9/src/loopfilter.rs | 19 +-- crates/ec-vp9/src/modes.rs | 54 +++++-- crates/ec-vp9/tests/scratch_tiledbg.rs | 4 + lanes/vp9kf.report.md | 205 ++++++++++++++++++++++++- 6 files changed, 392 insertions(+), 108 deletions(-) diff --git a/crates/ec-vp9/src/decode.rs b/crates/ec-vp9/src/decode.rs index 8f5b0f2f..9d3d8f3a 100644 --- a/crates/ec-vp9/src/decode.rs +++ b/crates/ec-vp9/src/decode.rs @@ -244,6 +244,30 @@ impl Decoder { mi_rows, }; let mut ti = 0usize; + // `above_context` / `above_seg_context` and the mi grid are + // FRAME-scoped in libvpx: `cm->above_context` is memset once per + // frame BEFORE the tile loop (vp9_decodeframe.c:2079-2080 / :2082-2083, + // inside the :2077-2083 block), the + // shared `cm->mi_grid_visible` accumulates every tile's records, and + // the buffers are indexed by ABSOLUTE mi_row/mi_col + // (`set_skip_context`, vp9_onyxc_int.h:405-413). A tile row k > 0 + // therefore reads above state written by tile row k - 1 — tiles are + // disjoint in COLUMN only. Allocating these per tile would discard + // that above state and mis-gate `xd->above_mi`, so they live here and + // are zeroed exactly once per frame. + // libvpx sizes `cm->above_context` by `mi_cols_aligned_to_sb` and the + // mi grid stride by `mi_cols`; the above arrays are written/indexed up + // to a whole TX_32X32 (8 4x4 units) past the last mi col, so a + // non-multiple-of-8 width would otherwise index out of bounds. + let aligned_cols = mi_cols.div_ceil(SB_MI) * SB_MI; + let mut ectx = [ + PlaneContexts::new(aligned_cols * 2), + PlaneContexts::new(aligned_cols), + PlaneContexts::new(aligned_cols), + ]; + ectx.iter_mut().for_each(|p| p.above.fill(0)); + let mut mi = MiState::new(mi_cols, mi_rows); + mi.above_seg.fill(0); for tr in 0..tile_rows { let row_lo = ((sb64_rows * tr) >> hdr.tile_info.rows_log2) * SB_MI; let row_hi = (((sb64_rows * (tr + 1)) >> hdr.tile_info.rows_log2) * SB_MI).min(mi_rows); @@ -260,35 +284,19 @@ impl Decoder { } let mut r = crate::bool::BoolDecoder::new(tiles[ti])?; ti += 1; - let mut ectx = [ - PlaneContexts::new(mi_cols * 2), - PlaneContexts::new(mi_cols), - PlaneContexts::new(mi_cols), - ]; - let mut mi = MiState::new(mi_cols, mi_rows); - ectx.iter_mut().for_each(|p| p.above.fill(0)); - mi.above_seg.fill(0); for sb_row in (row_lo..row_hi).step_by(SB_MI) { // libvpx zeroes the left ENTROPY and PARTITION contexts at // the start of EVERY superblock row, not just the tile's - // first one (vp9_decodeframe.c:2256-2258 plain - // `decode_tiles`; the row-mt twin is :2114-2115 and the - // per-tile-row twins :1825-1826 / :1898-1899): the left + // first one (vp9_decodeframe.c:2260-2261 plain + // `decode_tiles`; the row-mt twin is :2117-2118 and the + // per-tile-row twins :1828-1829 / :1901-1902): the left // edge of an SB row has no pixels to its left. Our luma // left index wraps at mi_row 16, so a stale value from two // SB rows earlier would otherwise be read here. - // `above_context`/`above_seg_context` are frame-scoped in - // libvpx (`memset` at :2076-2080, before the tile-row - // loop) and indexed by ABSOLUTE mi_col (`set_skip_context`, - // vp9_onyxc_int.h:409-412), so zeroing them once per tile - // is equivalent only for `log2_tile_rows == 0`, where the - // disjoint-column argument holds (each tile's xd points - // into its own column range: vp9_init_macroblockd, - // vp9_onyxc_int.h:381-393). With tile ROWS the first SB row - // of tile row k > 0 may legitimately read above state - // written by tile row k - 1, which the fills at :269-270 - // discard: the tile-row path is NOT equivalent and is not - // handled here. + // `above_context`/`above_seg_context` are frame-scoped + // (memset once per frame at :2079-2083, before the tile + // loop) and indexed by ABSOLUTE mi_col, so they persist + // across tile rows and are NOT reset here. ectx.iter_mut().for_each(|p| p.left = [0; 32]); mi.left_seg = [0; 32]; for sb_col in (col_lo..col_hi).step_by(SB_MI) { @@ -302,7 +310,6 @@ impl Decoder { sb_row, sb_col, 4, - row_lo, col_lo, tx_mode, )?; @@ -326,7 +333,6 @@ impl Decoder { p.uvs, vw, vh, - vw / 2, vh / 2, hdr.loop_filter.sharpness, ); @@ -366,7 +372,6 @@ impl Decoder { row: usize, col: usize, n4: usize, - tile_row_start: usize, tile_col_start: usize, tx_mode: u8, ) -> Result<()> { @@ -410,7 +415,6 @@ impl Decoder { subsize, 1, 1, - tile_row_start, tile_col_start, tx_mode, )?; @@ -428,7 +432,6 @@ impl Decoder { subsize, n4, n4, - tile_row_start, tile_col_start, tx_mode, )?, @@ -445,7 +448,6 @@ impl Decoder { subsize, n4, n8, - tile_row_start, tile_col_start, tx_mode, )?; @@ -462,7 +464,6 @@ impl Decoder { subsize, n4, n8, - tile_row_start, tile_col_start, tx_mode, )?; @@ -481,7 +482,6 @@ impl Decoder { subsize, n8, n4, - tile_row_start, tile_col_start, tx_mode, )?; @@ -498,7 +498,6 @@ impl Decoder { subsize, n8, n4, - tile_row_start, tile_col_start, tx_mode, )?; @@ -521,7 +520,6 @@ impl Decoder { rr, cc, n8, - tile_row_start, tile_col_start, tx_mode, )?; @@ -550,7 +548,6 @@ impl Decoder { sb_type: usize, bwl: usize, bhl: usize, - tile_row_start: usize, tile_col_start: usize, tx_mode: u8, ) -> Result<()> { @@ -569,10 +566,9 @@ impl Decoder { sb_type, x_mis, y_mis, - tile_row_start, tile_col_start, tx_mode, - &self.ctx.skip, + &self.ctx, )?; // Per-plane 4x4 counts. Sub-8x8 shapes still occupy the WHOLE 8x8 @@ -650,7 +646,6 @@ impl Decoder { bh, mb_to_right, mb_to_bottom, - tile_row_start, tile_col_start, )?; } @@ -687,7 +682,6 @@ impl Decoder { bh: usize, mb_to_right: i32, mb_to_bottom: i32, - tile_row_start: usize, tile_col_start: usize, ) -> Result<()> { let s = usize::from(plane != 0); @@ -701,12 +695,16 @@ impl Decoder { info.uv_mode }; let planes = self.planes.as_mut().expect("frame scratch"); - let (pw, ph) = planes.dims(plane); - let stride = pw; + let stride = planes.dims(plane).0; let bs = 4 << tx_size; let x0 = ((mi_col * 8) >> s) + tx_col * 4; let y0 = ((mi_row * 8) >> s) + tx_row * 4; - let up = tx_row != 0 || mi_row > tile_row_start; + // vp9_predict_intra_block `have_top = loff || (xd->above_mi != NULL)` + // (vp9_reconintra.c:411); `above_mi` is FRAME-gated + // (`set_mi_row_col`, vp9_onyxc_int.h:430: `mi_row != 0`), NOT + // tile-row-gated. The above row of a tile row k > 0 is decoded by + // tile row k - 1 and is available. + let up = tx_row != 0 || mi_row > 0; let lft = tx_col != 0 || mi_col > tile_col_start; // vp9_predict_intra_block `have_right`: the tx block is not in the // last tx column of ITS OWN block (pd->n4_w units) — above-right @@ -714,10 +712,32 @@ impl Decoder { // neighbour, so it must stage as unavailable. let rgt = tx_col + (1usize << tx_size) < bw * 2 >> s; + // `xd->cur_buf->y_width/y_height` (vp9_reconintra.c:288-292) are the + // MI-ALIGNED (8-multiple) buffer extent, not the visible coded size: + // confirmed by instrumenting the oracle's staging for a 320x242 frame + // (`fh=248`, not 242). The extend-vs-direct DECISION is `mb_to_*_edge` + // (`:302/326/354`, passed in as `bot_ext`/`right_ext`). + let vw = (hdr.mi_cols() as usize * 8) >> s; + let vh = (hdr.mi_rows() as usize * 8) >> s; + // 1. Intra prediction (reads reconstructed neighbours). { let (data, _) = planes.plane(plane); - build_intra_predictors(data, stride, pw, ph, x0, y0, mode, bs, up, lft, rgt); + build_intra_predictors( + data, + stride, + vw, + vh, + x0, + y0, + mode, + bs, + up, + lft, + rgt, + mb_to_bottom < 0, + mb_to_right < 0, + ); } if info.skip { diff --git a/crates/ec-vp9/src/intra.rs b/crates/ec-vp9/src/intra.rs index 715cb735..c72a1d2c 100644 --- a/crates/ec-vp9/src/intra.rs +++ b/crates/ec-vp9/src/intra.rs @@ -54,6 +54,13 @@ pub(crate) fn build_intra_predictors( up_available: bool, left_available: bool, right_available: bool, + // `xd->mb_to_bottom_edge < 0` — the MI-ALIGNED block extent overruns the + // frame bottom. This is the extend-vs-direct DECISION + // (`vp9_reconintra.c:302`); `frame_h` is used only for the extension + // LENGTH (`:288-292`). + bot_ext: bool, + // `xd->mb_to_right_edge < 0` (`vp9_reconintra.c:326/354`). + right_ext: bool, ) { let (need_left, need_above, need_aboveright) = needs(mode); let mut left_col = [0u8; 32]; @@ -62,40 +69,50 @@ pub(crate) fn build_intra_predictors( data[(((y0 as isize + dy) * stride as isize) + x0 as isize + dx) as usize] }; + // NEED_LEFT (vp9_reconintra.c:300-320). `extend_bottom` is `int` in C: + // `y0 > frame_height` must not underflow, so it is computed in isize. if need_left { if left_available { - if y0 + bs <= frame_h { + let extend_bottom = frame_h as isize - y0 as isize; + if !bot_ext || extend_bottom >= bs as isize { for i in 0..bs { left_col[i] = at(-1, i as isize); } } else { - let extend_bottom = frame_h - y0; - for i in 0..extend_bottom { + let n = extend_bottom.max(0) as usize; + for i in 0..n { left_col[i] = at(-1, i as isize); } - for i in extend_bottom..bs { - left_col[i] = at(-1, extend_bottom as isize - 1); - } + // `ref[(extend_bottom - 1) * ref_stride - 1]` — always the last + // VISIBLE row (`y0 + extend_bottom - 1 == frame_h - 1`). + let v = at(-1, extend_bottom - 1); + left_col[n..bs].fill(v); } } else { left_col[..bs].fill(129); } } + // NEED_ABOVE (vp9_reconintra.c:322-348). if need_above { if up_available { - if x0 + bs <= frame_w { - for i in 0..bs { - above_data[A + i] = at(i as isize, -1); + if right_ext { + if x0 + bs <= frame_w { + for i in 0..bs { + above_data[A + i] = at(i as isize, -1); + } + } else if x0 <= frame_w { + let r = frame_w - x0; + for i in 0..r { + above_data[A + i] = at(i as isize, -1); + } + let v = above_data[A + r - 1]; + above_data[A + r..A + bs].fill(v); } - } else if x0 <= frame_w { - let r = frame_w - x0; - for i in 0..r { + } else { + for i in 0..bs { above_data[A + i] = at(i as isize, -1); } - let v = above_data[A + r - 1]; - let n = x0 + bs - frame_w; - above_data[A + r..A + r + n].fill(v); } above_data[A - 1] = if left_available { at(-1, -1) } else { 129 }; } else { @@ -104,37 +121,58 @@ pub(crate) fn build_intra_predictors( } } + // NEED_ABOVERIGHT (vp9_reconintra.c:350-394). if need_aboveright { if up_available { - if x0 + 2 * bs <= frame_w { - for i in 0..2 * bs { - above_data[A + i] = at(i as isize, -1); - } - if !(bs == 4 && right_available) { - let v = above_data[A + bs - 1]; - above_data[A + bs..A + 2 * bs].fill(v); + let fill_bs = |d: &mut [u8; 80]| { + let v = d[A + bs - 1]; + d[A + bs..A + 2 * bs].fill(v); + }; + if right_ext { + if x0 + 2 * bs <= frame_w { + if bs == 4 && right_available { + for i in 0..2 * bs { + above_data[A + i] = at(i as isize, -1); + } + } else { + for i in 0..bs { + above_data[A + i] = at(i as isize, -1); + } + fill_bs(&mut above_data); + } + } else if x0 + bs <= frame_w { + let r = frame_w - x0; + if bs == 4 && right_available { + for i in 0..r { + above_data[A + i] = at(i as isize, -1); + } + let v = above_data[A + r - 1]; + above_data[A + r..A + 2 * bs].fill(v); + } else { + for i in 0..bs { + above_data[A + i] = at(i as isize, -1); + } + fill_bs(&mut above_data); + } + } else if x0 <= frame_w { + let r = frame_w - x0; + for i in 0..r { + above_data[A + i] = at(i as isize, -1); + } + let v = above_data[A + r - 1]; + above_data[A + r..A + 2 * bs].fill(v); } - } else if x0 + bs <= frame_w { - let r = frame_w - x0; - for i in 0..r { + } else { + for i in 0..bs { above_data[A + i] = at(i as isize, -1); } if bs == 4 && right_available { - let v = above_data[A + r - 1]; - let n = x0 + 2 * bs - frame_w; - above_data[A + r..A + r + n].fill(v); + for i in 0..bs { + above_data[A + bs + i] = at((bs + i) as isize, -1); + } } else { - let v = above_data[A + bs - 1]; - above_data[A + bs..A + 2 * bs].fill(v); - } - } else if x0 <= frame_w { - let r = frame_w - x0; - for i in 0..r { - above_data[A + i] = at(i as isize, -1); + fill_bs(&mut above_data); } - let v = above_data[A + r - 1]; - let n = x0 + 2 * bs - frame_w; - above_data[A + r..A + r + n].fill(v); } above_data[A - 1] = if left_available { at(-1, -1) } else { 129 }; } else { diff --git a/crates/ec-vp9/src/loopfilter.rs b/crates/ec-vp9/src/loopfilter.rs index 45a3336e..b85864e5 100644 --- a/crates/ec-vp9/src/loopfilter.rs +++ b/crates/ec-vp9/src/loopfilter.rs @@ -512,8 +512,11 @@ impl LfGrids { self.level8[r * self.mi_cols + c] } - /// Filter the frame's three planes in place. `y_w/h`, `uv_w/h` are - /// the coded (aligned) plane sizes. + /// Filter the frame's three planes in place. `y_w/h` are the coded + /// (aligned) plane sizes; `uv_h` is the chroma height. The chroma + /// column pass takes NO width bound (vp9_loopfilter.c:1394 iterates all + /// `MI_BLOCK_SIZE >> 1` column groups and `filter_selectively_vert_row2` + /// writes whole 8-column groups into the padded plane). pub(crate) fn filter_frame( &self, y: &mut [u8], @@ -523,7 +526,6 @@ impl LfGrids { uv_stride: usize, y_w: usize, y_h: usize, - uv_w: usize, uv_h: usize, sharpness: u8, ) { @@ -765,7 +767,7 @@ impl LfGrids { continue; } let (bl, li, th) = limits(lvl, sharpness); - if x8 >= 4 && x8 + 4 <= uv_w { + if x8 >= 4 { let taps = if left[TX_16X16] & bit != 0 { 16 } else if left[TX_8X8] & bit != 0 { @@ -776,7 +778,7 @@ impl LfGrids { 0 }; if taps != 0 { - let t = if taps == 16 && (x8 < 8 || x8 + 8 > uv_w) { + let t = if taps == 16 && x8 < 8 { 8 } else { taps @@ -794,7 +796,7 @@ impl LfGrids { ); } } - if int4 & bit != 0 && x8 + 8 <= uv_w { + if int4 & bit != 0 { lpf_edge( data, y8 * uv_stride + x8 + 4, @@ -826,7 +828,7 @@ impl LfGrids { continue; } let (bl, li, th) = limits(lvl, sharpness); - if y8 >= 4 && y8 + 4 <= uv_h && x8 + 8 <= uv_w { + if y8 >= 4 && y8 + 4 <= uv_h { let taps = if above[TX_16X16] & bit != 0 { 16 } else if above[TX_8X8] & bit != 0 { @@ -858,7 +860,6 @@ impl LfGrids { if int4 & bit != 0 && sbr + 2 * rg != self.mi_rows - 1 && y8 + 8 <= uv_h - && x8 + 8 <= uv_w { lpf_edge( data, @@ -900,7 +901,7 @@ mod tests { fn run(g: &LfGrids, y: &mut [u8]) { let mut u = vec![128u8; 32 * 32]; let mut v = vec![128u8; 32 * 32]; - g.filter_frame(y, 64, &mut u, &mut v, 32, 64, 64, 32, 32, 0); + g.filter_frame(y, 64, &mut u, &mut v, 32, 64, 64, 32, 0); } /// The luma internal-4x4 horizontal edge fires on the frame's LAST MI row. diff --git a/crates/ec-vp9/src/modes.rs b/crates/ec-vp9/src/modes.rs index 7fa5db7e..5182830f 100644 --- a/crates/ec-vp9/src/modes.rs +++ b/crates/ec-vp9/src/modes.rs @@ -3,6 +3,7 @@ //! read_intra_frame_mode_info`). use crate::bool::BoolDecoder; +use crate::header::FrameContext; use crate::tables::*; /// One block's parsed prediction record (`MODE_INFO`). @@ -18,14 +19,16 @@ pub(crate) struct MiInfo { pub bmi: [u8; 4], } -/// The mode-info grid and the partition contexts of one tile pass. +/// The mode-info grid and the partition contexts of the frame. pub(crate) struct MiState { pub mi_cols: usize, pub mi_rows: usize, /// `mi_row * mi_cols + mi_col`; every cell a block covers holds a - /// clone of its record (libvpx shares the pointer). + /// clone of its record (libvpx shares the pointer). Frame-scoped: a + /// tile row k > 0 reads the rows written by tile row k - 1. pub grid: Vec>, - /// `above_seg_context`, one byte per 8x8 column (tile-scoped). + /// `above_seg_context`, one byte per 8x8 column (frame-scoped, like + /// libvpx's `cm->above_seg_context`, memset once per frame). pub above_seg: Vec, /// `left_seg_context`, one byte per 8x8 row (reset per SB row). pub left_seg: [u8; 32], @@ -37,13 +40,22 @@ impl MiState { mi_cols, mi_rows, grid: vec![None; mi_cols * mi_rows], - above_seg: vec![0; mi_cols], + // `above_seg_context` is `mi_cols_aligned_to_sb` long in libvpx; + // `update_partition_ctx` fills `[col .. col + bw)` which can + // overrun `mi_cols` by up to a full superblock (a 64x64 block at + // the last mi col). + above_seg: vec![0; mi_cols.div_ceil(8) * 8], left_seg: [0; 32], } } - fn above_mi(&self, row: usize, col: usize, tile_row_start: usize) -> Option<&MiInfo> { - if row > tile_row_start { + /// `xd->above_mi` (`set_mi_row_col`, vp9_onyxc_int.h:430): available iff + /// the block is not on the FRAME's first mi row. libvpx gates on + /// `mi_row != 0`, not on the tile row start — for a tile-row stream the + /// row above tile row k > 0 was decoded by tile row k - 1 into the same + /// frame-scoped mi grid. + fn above_mi(&self, row: usize, col: usize) -> Option<&MiInfo> { + if row > 0 { self.grid[(row - 1) * self.mi_cols + col].as_ref() } else { None @@ -138,12 +150,11 @@ pub(crate) fn read_intra_frame_mode_info( sb_type: usize, x_mis: usize, y_mis: usize, - tile_row_start: usize, tile_col_start: usize, tx_mode: u8, - skip_probs: &[u8; 3], + fc: &FrameContext, ) -> crate::Result { - let above_mi = st.above_mi(row, col, tile_row_start).cloned(); + let above_mi = st.above_mi(row, col).cloned(); let left_mi = st.left_mi(row, col, tile_col_start).cloned(); // read_intra_segment_id: keyframes have no temporal prediction; a @@ -167,26 +178,37 @@ pub(crate) fn read_intra_frame_mode_info( let skip = if seg_skip { true } else { - r.read_bool(skip_probs[skip_ctx]) + r.read_bool(fc.skip[skip_ctx]) }; // read_tx_size let max_tx = MAX_TXSIZE_LOOKUP[sb_type] as usize; let tx_size = if tx_mode == TX_MODE_SELECT && sb_type >= 3 { - // read_selected_tx_size: ctx from above/left tx sizes. + // get_tx_size_context (vp9_pred_common.h:156): default each side to + // max_tx, then substitute the other side when one is missing, in + // this exact order — the `!has_above` fallback is load-bearing. let ctx = { let a = above_mi .as_ref() .map_or(max_tx, |m| if m.skip { max_tx } else { m.tx_size }); - let l = left_mi + let mut l = left_mi .as_ref() - .map_or(a, |m| if m.skip { max_tx } else { m.tx_size }); + .map_or(max_tx, |m| if m.skip { max_tx } else { m.tx_size }); + if left_mi.is_none() { + l = a; + } + let mut a = a; + if above_mi.is_none() { + a = l; + } usize::from(a + l > max_tx) }; + // get_tx_probs (vp9_pred_common.h:173): the FRAME-updated tables + // (`cm->fc->tx_probs`), not the const defaults. let probs: &[u8] = match max_tx { - 1 => &TX_P8X8_PROB[ctx..ctx + 1], - 2 => &TX_P16X16_PROB[ctx * 2..ctx * 2 + 2], - _ => &TX_P32X32_PROB[ctx * 3..ctx * 3 + 3], + 1 => &fc.tx_p8x8[ctx][..], + 2 => &fc.tx_p16x16[ctx][..], + _ => &fc.tx_p32x32[ctx][..], }; let mut tx = r.read_bool(probs[0]) as usize; if tx != TX_4X4 && max_tx >= TX_16X16 { diff --git a/crates/ec-vp9/tests/scratch_tiledbg.rs b/crates/ec-vp9/tests/scratch_tiledbg.rs index 19047c37..4c1ed86b 100644 --- a/crates/ec-vp9/tests/scratch_tiledbg.rs +++ b/crates/ec-vp9/tests/scratch_tiledbg.rs @@ -31,6 +31,10 @@ fn tile_dbg() { hdr.mi_cols(), hdr.mi_rows() ); + println!( + " loop_filter level={} sharpness={}", + hdr.loop_filter.level, hdr.loop_filter.sharpness + ); let tail = &fr.data[off..]; println!( " tail len {} first16 {:?}", diff --git a/lanes/vp9kf.report.md b/lanes/vp9kf.report.md index 58195605..615a028e 100644 --- a/lanes/vp9kf.report.md +++ b/lanes/vp9kf.report.md @@ -571,9 +571,9 @@ first-divergent-decision evidence lives in the companion lane report first superblock row (`if sb_row == row_lo { ectx[].left = [0; 32]; mi.left_seg = [0; 32]; }`). libvpx zeroes them at the start of EVERY superblock row: -- `vp9/decoder/vp9_decodeframe.c:2256-2258` (plain `decode_tiles`, the path a 1-thread `drv` - takes), with the row-mt twin at `:2114-2115` and the per-tile-row twins at `:1825-1826` / - `:1898-1899`; +- `vp9/decoder/vp9_decodeframe.c:2260-2261` (plain `decode_tiles`, the path a 1-thread `drv` + takes), with the row-mt twin at `:2117-2118` and the per-tile-row twins at `:1828-1829` / + `:1901-1902`; - `MACROBLOCKD.left_context` is `ENTROPY_CONTEXT left_context[MAX_MB_PLANE][16]` (`vp9/common/vp9_blockd.h:192`), so `vp9_zero` clears all 16 slots of all 3 planes; `left_seg_context[8]` (`blockd.h:195`) likewise. @@ -653,3 +653,202 @@ fill discards. The comment in `decode.rs` states this explicitly. **Status: the tile-row class is NOT closed.** No available fixture and no sweep exercises `log2_tile_rows > 0`, so none of the three defects is covered by a gate; they were found with purpose-built probes, not by the crate's tests. + +## CLOSED (2026-09-17) — the tile-ROW path is byte-exact; fixture recipes recorded + +All three defects above are fixed, plus a fourth that the same probe isolated. Every fix is +ported verbatim from libvpx with the source cited in the code. + +1. `modes.rs` `read_intra_frame_mode_info` now takes `fc: &FrameContext` and reads + `fc.tx_p8x8/tx_p16x16/tx_p32x32[ctx]` (libvpx `get_tx_probs`, `vp9_pred_common.h:173`) — + the FRAME-updated tables, not the `TX_*` const defaults. +2. The tx-size context now includes libvpx's `if (!has_above) above_ctx = left_ctx;` + (`vp9_pred_common.h:156-170`), in the same order as the `!has_left` fallback. +3. `MiState::above_mi` (and the pixel gate `let up = ...` in `predict_and_reconstruct`) now + gate above availability on the FRAME (`mi_row != 0`; `set_mi_row_col`, + `vp9_onyxc_int.h:430`) instead of the tile-row start. `tile_row_start` is gone from the + whole decode chain. +4. The above ENTROPY/PARTITION contexts and the mi grid are now FRAME-scoped: `ectx` and `mi` + are allocated once per frame in `decode_keyframe_inner` (above cleared once, left cleared + per SB row), matching libvpx's frame-scoped `cm->above_context` / `above_seg_context` + (`vp9_decodeframe.c:2079-2083`). Previously a fresh per-tile `MiState` discarded the above + rows a tile row k > 0 legitimately reads. +5. (Same availability family, not tile-row-specific — exposed by the tile-row fixture but also + reproducible with `-tile-rows 0` on the same clip) `build_intra_predictors` was passed the + PADDED plane height (`y` buffer is 64-aligned, so 1080 -> 1088); libvpx passes the VISIBLE + coded size (`xd->cur_buf->y_width/y_height`, `vp9_reconintra.c:288-292`). For the last block + row the port therefore skipped the bottom border extension and averaged 8 rows of + 128-filled padding into DC_PRED instead of replicating the last valid row (found the first + divergence at luma (1056, 288), a 32x32 DC_PRED block that a `+8` DC shift then propagated + right in halving steps). Now passes `hdr.width/height` (+1>>1 for chroma). + +### Evidence + +| # | command | before | after | +|---|---|---|---| +| 1 | `CARGO_TARGET_DIR=... SWEEP_IVF=/tmp/tr.ivf cargo test -p ec-vp9 --test scratch_realsweep -- --nocapture` (real 1920x1080 clip, `-g 1 -tile-columns 0 -tile-rows 1`, 2 tile rows) | `frame 0: Y 2065984 U 510099 V 510291`; frames 1-2 `DECODE REFUSED/ERR vp9: tile bool decoder desync` -> `RESULT 0 of 3` | `Y 0 U 0 V 0` x3 -> `RESULT 3 of 3 frames byte-exact` | +| 2 | `SWEEP_TILE0=1 SWEEP_SRC=/tmp/small320.mp4 ...` (real 320x240 clip) | (previous batch) | `RESULT 3 of 3 frames byte-exact` | +| 3 | `SWEEP_IVF=/tmp/t1080.ivf ...` (real 1920x1080 clip, 4 tile columns) | (previous batch) | `RESULT 3 of 3 frames byte-exact` | +| 4 | `SWEEP_IVF=/tmp/single1080.ivf` and `/tmp/tr2.ivf` (same 1080p clip, `-tile-rows 0`; and `-tile-rows 2`, 4 tile rows) | (same clip / 2 tile rows) `RESULT 0 of 3` | `RESULT 3 of 3 frames byte-exact` | + +Intermediate numbers: with fixes 1-4 only, `/tmp/tr.ivf` still showed `Y 6059 U 1658 V 247`, +localized to the bottom 24 luma rows — fix 5 removed them. `cargo test -p ec-vp9` -> all +binaries green; `cargo check -p ec-vp9` -> the same 5 lib warnings (`TM_PRED`, +`read_partition`, `partition_probs`, `x_mis`, `y_mis`), no new ones. + +### Fixture recipes (both were previously unrecorded — the report named only the source kind) + +All-intra keyframe sweep (one keyframe per source frame): + +``` +ffmpeg -v error -y -i -frames:v 3 -c:v libvpx-vp9 -g 1 -crf 32 \ + -deadline good -cpu-used 4 -tile-columns 0 -tile-rows 0 -pix_fmt yuv420p -f ivf /tmp/single1080.ivf +``` + +Tile-ROW fixture (2 tile rows, 1 tile column): identical but `-tile-rows 1` -> + +``` +ffmpeg -v error -y -i -frames:v 3 -c:v libvpx-vp9 -g 1 -crf 32 \ + -deadline good -cpu-used 4 -tile-columns 0 -tile-rows 1 -pix_fmt yuv420p -f ivf /tmp/tr.ivf +``` + +Confirm the layout before trusting it: +`TILE_SRC=/tmp/tr.ivf cargo test -p ec-vp9 --test scratch_tiledbg -- --nocapture` -> +`tile cols 0 rows 1 mi 240x135`, `walk: 2 tiles, prefixes consume 77709 ok=true`. `-tile-rows 2` +(4 tile rows) uses `/tmp/tr2.ivf`. The 4-tile-column fixture `/tmp/t1080.ivf` uses +`-tile-columns 2 -tile-rows 0`. Odd-shape fixtures (`-deadline good -cpu-used 4` throughout): +`/tmp/h242.ivf` = 320x242 (height not a multiple of 8), `/tmp/h1082.ivf` = 1920x1082, +`/tmp/w1366.ivf` = `-vf scale=1366:768` of the 320x240 clip (width not a multiple of 8). + +No commit made by this lane (the orchestrator commits). + +## PARTIAL / STILL OPEN (2026-09-17b) — edge-shape band; the OC-OOB panic class is closed + +A second independent verifier confirmed fixes 1-4 above (with citations) and refuted the "use +the visible coded size as the edge" model of fix 5 as incomplete. What is now in the tree: + +- **CLOSED — above-context OOB panic.** `ectx[].above` is now sized `mi_cols_aligned_to_sb` + (luma `×2`) and `MiState::above_seg` likewise, matching libvpx's `cm->above_context` / + `above_seg_context`. Before: any width not a multiple of 8 (`mi_cols*2` sized array written + up to `2*mi_cols + 6` by the last TX_32X32) panicked with an index-out-of-bounds at + `decode.rs:767` (the w1366 above-array read; `intra.rs:72` is the other site, the h242 + subtraction overflow); 1366-wide input panicked in both the baseline and the patched tree. +- **CLOSED — `intra.rs` subtraction overflow.** The NEED_LEFT/NEED_ABOVE/NEED_ABOVERIGHT + staging is now ported branch-for-branch from `vp9_reconintra.c:300-394`: the + extend-vs-direct DECISION is `xd->mb_to_bottom_edge < 0` / `xd->mb_to_right_edge < 0` + (`:302/326/354`, passed in as `bot_ext`/`right_ext`), and `extend_bottom`/`extend_bottom-1` + are computed in `isize` so `y0 > frame_h` cannot underflow. `/tmp/h242.ivf` no longer + panics (was `attempt to subtract with overflow` at `intra.rs:72`), `/tmp/h1082.ivf` is 3/3. +- **CLOSED — the tile-row class (fixes 1-4)**: `/tmp/tr.ivf`, `/tmp/tr2.ivf`, + `/tmp/t1080.ivf`, `/tmp/t1080-single.ivf`, `/tmp/single1080.ivf`, and the 320x240 tile0 + sweep are all 3/3. +- **STILL OPEN — non-multiple-of-8 frame extents**: `/tmp/h242.ivf` -> `RESULT 1 of 3`, + `/tmp/w1366.ivf` -> `RESULT 0 of 3`. The divergence is confined to the RECONSTRUCTED + OVERHANG (rows >= 242 for h242, columns >= ~1341 for w1366); no visible pixel differs + except where a visible block's DC/TM prediction consumes an overhang neighbour. + First divergent block, h242 frame 0: luma rows 240-241, x116-143 and x268-271 (+1 each); + localized to the left column staged for the 8x8 at `(mi_row 30, mi_col 12)`, whose + `x=95` rows 242-247 are written by the `TX_32X32` at the `BLOCK_32X32 (28,8)`. + Oracle staged left column over rows 240-255 is `15,25,25,24,25,...,25,26` (a DIRECT read of + the buffer's rows, not a clamp at `frame_height=242`); the port with the visible-length model + clamps to `extend_bottom = 242-224 = 18` and replicates row 241, giving `15,25,26,26,...`. + Using the ALLOCATED extent as the length instead fixes h242 **and** h1082 but regresses + tr.ivf / tr2.ivf / single1080.ivf / t1080-single.ivf to 0/3, so neither "visible length" nor + "allocated length" is the whole model — the buffer/overhang semantics differ per extent class + and are not yet pinned. A dedicated lane should diff the oracle's overhang bytes + (`DUMPH` override was added to `/tmp/vp9loss/drv.c`) against the port's padded plane. + +## RULE NAMED (2026-09-17c) — the staging extent is the MI-ALIGNED buffer size + +Instrumented `build_intra_predictors` (`STAGEDBG=x0,y0` in `vp9_reconintra.c`) prints the +staged `left[]`/`above[]` plus `fw`/`fh`. For the divergent block of `/tmp/h242.ivf` +(luma `x0=64 y0=224 bs=32 mode=2 tx=TX_32X32`, block `BLOCK_32X32 (28,8)`): + +``` +STG plane=0 x0=64 y0=224 bs=32 mode=2 mbtb=-64 mbtr=1792 fw=320 fh=248 +STG left : 10 16 15 16 16 16 16 16 16 16 16 16 16 16 16 16 16 26 25 24 25 25 25 25 25 25 25 25 25 25 25 25 +STG above: ... cor=0 +``` + +`fh=248`, not 242. `vp9_alloc_frame_buffer` sets `y_width/y_height` to the **8-aligned** +extent (`aligned_width = (width + 7) & ~7`, `aligned_height = (height + 7) & ~7`; +`vpx_scale/generic/yv12config.c:173-174,250-251`) — i.e. exactly `mi_cols*8` / `mi_rows*8`. +With `mb_to_bottom_edge = -64` the NEED_LEFT extension path runs with +`extend_bottom = 248 - 224 = 24`: `left[0..24]` are direct reads (rows 224..247) and +`left[24..32]` replicate row 247 — which reproduces the observed array +(`left[18]=25 (row 242), left[19]=24 (row 243), left[20..31]=25`). Neither the visible size +(242 -> clamped at row 241) nor the 64-aligned plane size (256 -> `extend_bottom` 32 >= bs, i.e. +a full direct read) reproduces it; the 8-aligned extent does. + +Port: `decode.rs` passes `vw = mi_cols*8 >> s`, `vh = mi_rows*8 >> s` to +`build_intra_predictors`, which keeps the MI-aligned extend-vs-direct DECISION +(`mb_to_bottom_edge`/`mb_to_right_edge` -> `bot_ext`/`right_ext`) and the signed `isize` +extension arithmetic. Both earlier hacks are gone and neither is needed. + +Result matrix (3-frame scratch_realsweep, `CARGO_TARGET_DIR=$HOME/.cache/cargo-target-tilerow`): + +| fixture | shape | result | +|---|---|---| +| `/tmp/h242.ivf` | 320x242, 1 tile | `RESULT 3 of 3` | +| `/tmp/h1082.ivf` | 1920x1082, 1 tile | `RESULT 3 of 3` | +| `/tmp/w1366.ivf` | 1366x768, 1 tile | `RESULT 0 of 3` — `Y 0 0 0`, `U 4/5/6 V 37/33/16` | +| `/tmp/w1366tc.ivf` | 1366x768, 2 tile columns | `RESULT 0 of 3` (same chroma-only residue) | +| `/tmp/h242tr.ivf` | 320x242, `-tile-rows 1` | `RESULT 3 of 3`, but `tile cols 0 rows 0` — the encoder declined tile rows at this height, so the cross-product is still not exercised | +| `/tmp/tr.ivf`, `/tmp/tr2.ivf`, `/tmp/t1080.ivf`, `/tmp/t1080-single.ivf`, `/tmp/single1080.ivf` | 1080p, 2/4 tile rows and 4 tile cols | `RESULT 3 of 3` | +| `SWEEP_TILE0=1 SWEEP_SRC=/tmp/small320.mp4` | 320x240 | `RESULT 3 of 3` | + +`cargo test -p ec-vp9` green (lib 9/9, keyframe_exact 4/4); `cargo check -p ec-vp9` = the same +5 warnings. No commit (the orchestrator commits). + +### CLOSED (2026-09-17d) — chroma COLUMN groups are not width-clamped + +The residue was the COLUMN analogue of the chroma row-group rule already in +`skill://vp9-kf-loopfilter-port`. `vp9_filter_block_plane_ss11` iterates ALL +`MI_BLOCK_SIZE >> 1` chroma column groups with no plane-width clamp +(`vp9_loopfilter.c:1394`) and `filter_selectively_vert_row2` writes whole 8-column groups +(`:313-399`); the horizontal pass likewise. The port clamped the groups with `uv_w` +(`x8 + 4 <= uv_w` on the vertical edge, `x8 + 8 <= uv_w` on the internal-4x4 vertical edge and +on both horizontal edges, plus a V16->V8 downgrade when `x8 + 8 > uv_w`). + +Effect at 1366 wide (`uv_w = mi_cols*4 = 684` = the ALIGNED chroma width; the visible chroma +width is 683): the last column GROUP (chroma columns 680-687) holds visible pixels 680-682 but +overhangs the visible plane by 4, so every clamped edge was silently dropped: luma stayed byte-exact while +chroma was off by +/-1 at scattered rows (U 4/5/6, V 37/33/16) — the same +"Y exact, chroma off by one" signature as the row bug. Because the chroma planes are the padded +buffer (mi_cols*8*2/... >= the group write), the writes land in the pad and are harmless. + +Fix: drop every `uv_w` column clamp from the chroma pass (`x8 >= 4` alone remains, mirroring +libvpx's leftmost-column mask clear), drop the `x8 + 8 > uv_w` clause from the V16 downgrade, +and remove the now-unused `uv_w` parameter from `filter_frame` (the pass takes no width bound at +all — libvpx passes only the stride). `uv_h` clamps are untouched (verified via the 1080p and +odd-height sweeps). + +Rule: **chroma group iteration is MI-row-gated (rows) and MI-col-unbounded (columns) — read +libvpx's loop condition and masks, never the plane geometry.** + +Full matrix after this fix (3-frame scratch_realsweep, +`CARGO_TARGET_DIR=$HOME/.cache/cargo-target-tilerow`): + +| fixture | shape | result | +|---|---|---| +| `/tmp/h242.ivf` | 320x242, 1 tile | 3 of 3 | +| `/tmp/h1082.ivf` | 1920x1082, 1 tile | 3 of 3 | +| `/tmp/h1082tr.ivf` | 1920x1082, **2 tile rows** | 3 of 3 (`tile cols 0 rows 1`) | +| `/tmp/w1366.ivf` | 1366x768, 1 tile | 3 of 3 | +| `/tmp/w1366tc.ivf` | 1366x768, **2 tile columns** | 3 of 3 (`tile cols 1 rows 0`) | +| `/tmp/h1082trc.ivf` | 1366x1082, tile cols + tile rows requested | 3 of 3, but `tile cols 1 rows 0` (encoder declined tile rows at this height) | +| `/tmp/tr.ivf`, `/tmp/tr2.ivf`, `/tmp/t1080.ivf`, `/tmp/t1080-single.ivf`, `/tmp/single1080.ivf` | 1080p, 2/4 tile rows, 4 tile cols | 3 of 3 | +| `SWEEP_TILE0=1 SWEEP_SRC=/tmp/small320.mp4` | 320x240 | 3 of 3 | + +`cargo test -p ec-vp9` green (lib 9/9, keyframe_exact 4/4, the LF witness suite included); +`cargo check -p ec-vp9` = the same 5 warnings (`TM_PRED`, `read_partition`, `partition_probs`, +`x_mis`, `y_mis`). No commit (the orchestrator commits). + +Cross-product coverage: odd HEIGHT x tile rows is now exercised (`/tmp/h1082tr.ivf`, +`rows_log2=1`). Odd WIDTH x tile columns is exercised (`/tmp/w1366tc.ivf`, `cols_log2=1`). The +encoder declines `-tile-rows` at short heights (320x242 gives `rows_log2=0`), so the combination +of an odd width AND an odd height AND both tile axes requested is only reachable via +`/tmp/h1082trc.ivf`, where the encoder again declined tile rows (columns accepted) — that single +cell (odd width × odd height × tile rows) remains unexercised and needs a taller-than-1082, +non-multiple-of-8, odd-width source before it can be covered. +